Merge pull request #18069 from civicrm/5.28
[civicrm-core.git] / CRM / Core / BAO / Location.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class handle creation of location block elements.
20 */
21 class CRM_Core_BAO_Location extends CRM_Core_DAO {
22
23 /**
24 * Location block element array.
25 * @var array
26 */
27 public static $blocks = ['phone', 'email', 'im', 'openid', 'address'];
28
29 /**
30 * Create various elements of location block.
31 *
32 * @param array $params
33 * (reference ) an assoc array of name/value pairs.
34 * @param bool $fixAddress
35 * True if you need to fix (format) address values.
36 * before inserting in db
37 *
38 * @param null $entity
39 *
40 * @return array
41 */
42 public static function create(&$params, $fixAddress = TRUE, $entity = NULL) {
43 $location = [];
44 if (!self::dataExists($params)) {
45 return $location;
46 }
47
48 // create location blocks.
49 foreach (self::$blocks as $block) {
50 if ($block != 'address') {
51 $location[$block] = CRM_Core_BAO_Block::create($block, $params, $entity);
52 }
53 else {
54 $location[$block] = CRM_Core_BAO_Address::create($params, $fixAddress, $entity);
55 }
56 }
57
58 if ($entity) {
59 // this is a special case for adding values in location block table
60 $entityElements = [
61 'entity_table' => $params['entity_table'],
62 'entity_id' => $params['entity_id'],
63 ];
64
65 $location['id'] = self::createLocBlock($location, $entityElements);
66 }
67 else {
68 // when we come from a form which displays all the location elements (like the edit form or the inline block
69 // elements, we can skip the below check. The below check adds quite a feq queries to an already overloaded
70 // form
71 if (empty($params['updateBlankLocInfo'])) {
72 // make sure contact should have only one primary block, CRM-5051
73 self::checkPrimaryBlocks(CRM_Utils_Array::value('contact_id', $params));
74 }
75 }
76
77 return $location;
78 }
79
80 /**
81 * Creates the entry in the civicrm_loc_block.
82 *
83 * @param string $location
84 * @param array $entityElements
85 *
86 * @return int
87 */
88 public static function createLocBlock(&$location, &$entityElements) {
89 $locId = self::findExisting($entityElements);
90 $locBlock = [];
91
92 if ($locId) {
93 $locBlock['id'] = $locId;
94 }
95
96 foreach ([
97 'phone',
98 'email',
99 'im',
100 'address',
101 ] as $loc) {
102 $locBlock["{$loc}_id"] = !empty($location["$loc"][0]) ? $location["$loc"][0]->id : NULL;
103 $locBlock["{$loc}_2_id"] = !empty($location["$loc"][1]) ? $location["$loc"][1]->id : NULL;
104 }
105
106 $countNull = 0;
107 foreach ($locBlock as $key => $block) {
108 if (empty($locBlock[$key])) {
109 $locBlock[$key] = 'null';
110 $countNull++;
111 }
112 }
113
114 if (count($locBlock) == $countNull) {
115 // implies nothing is set.
116 return NULL;
117 }
118
119 $locBlockInfo = self::addLocBlock($locBlock);
120 return $locBlockInfo->id;
121 }
122
123 /**
124 * Takes an entity array and finds the existing location block.
125 *
126 * @param array $entityElements
127 *
128 * @return int
129 */
130 public static function findExisting($entityElements) {
131 $eid = $entityElements['entity_id'];
132 $etable = $entityElements['entity_table'];
133 $query = "
134 SELECT e.loc_block_id as locId
135 FROM {$etable} e
136 WHERE e.id = %1";
137
138 $params = [1 => [$eid, 'Integer']];
139 $dao = CRM_Core_DAO::executeQuery($query, $params);
140 while ($dao->fetch()) {
141 $locBlockId = $dao->locId;
142 }
143 return $locBlockId;
144 }
145
146 /**
147 * Takes an associative array and adds location block.
148 *
149 * @param array $params
150 * (reference ) an assoc array of name/value pairs.
151 *
152 * @return CRM_Core_BAO_locBlock
153 * Object on success, null otherwise
154 */
155 public static function addLocBlock(&$params) {
156 $locBlock = new CRM_Core_DAO_LocBlock();
157
158 $locBlock->copyValues($params);
159
160 return $locBlock->save();
161 }
162
163 /**
164 * Delete the Location Block.
165 *
166 * @param int $locBlockId
167 * Id of the Location Block.
168 */
169 public static function deleteLocBlock($locBlockId) {
170 if (!$locBlockId) {
171 return;
172 }
173
174 $locBlock = new CRM_Core_DAO_LocBlock();
175 $locBlock->id = $locBlockId;
176
177 $locBlock->find(TRUE);
178
179 //resolve conflict of having same ids for multiple blocks
180 $store = [
181 'IM_1' => $locBlock->im_id,
182 'IM_2' => $locBlock->im_2_id,
183 'Email_1' => $locBlock->email_id,
184 'Email_2' => $locBlock->email_2_id,
185 'Phone_1' => $locBlock->phone_id,
186 'Phone_2' => $locBlock->phone_2_id,
187 'Address_1' => $locBlock->address_id,
188 'Address_2' => $locBlock->address_2_id,
189 ];
190 $locBlock->delete();
191 foreach ($store as $daoName => $id) {
192 if ($id) {
193 $daoName = 'CRM_Core_DAO_' . substr($daoName, 0, -2);
194 $dao = new $daoName();
195 $dao->id = $id;
196 $dao->find(TRUE);
197 $dao->delete();
198 }
199 }
200 }
201
202 /**
203 * Check if there is data to create the object.
204 *
205 * @param array $params
206 * (reference ) an assoc array of name/value pairs.
207 *
208 * @return bool
209 */
210 public static function dataExists(&$params) {
211 // return if no data present
212 $dataExists = FALSE;
213 foreach (self::$blocks as $block) {
214 if (array_key_exists($block, $params)) {
215 $dataExists = TRUE;
216 break;
217 }
218 }
219
220 return $dataExists;
221 }
222
223 /**
224 * Get values.
225 *
226 * @param array $entityBlock
227 * @param bool $microformat
228 *
229 * @return CRM_Core_BAO_Location[]|NULL
230 */
231 public static function getValues($entityBlock, $microformat = FALSE) {
232 if (empty($entityBlock)) {
233 return NULL;
234 }
235 $blocks = [];
236 $name_map = [
237 'im' => 'IM',
238 'openid' => 'OpenID',
239 ];
240 $blocks = [];
241 //get all the blocks for this contact
242 foreach (self::$blocks as $block) {
243 if (array_key_exists($block, $name_map)) {
244 $name = $name_map[$block];
245 }
246 else {
247 $name = ucfirst($block);
248 }
249 $baoString = 'CRM_Core_BAO_' . $name;
250 $blocks[$block] = $baoString::getValues($entityBlock, $microformat);
251 }
252 return $blocks;
253 }
254
255 /**
256 * Delete all the block associated with the location.
257 *
258 * @param int $contactId
259 * Contact id.
260 * @param int $locationTypeId
261 * Id of the location to delete.
262 * @throws CRM_Core_Exception
263 */
264 public static function deleteLocationBlocks($contactId, $locationTypeId) {
265 // ensure that contactId has a value
266 if (empty($contactId) ||
267 !CRM_Utils_Rule::positiveInteger($contactId)
268 ) {
269 throw new CRM_Core_Exception('Incorrect contact id parameter passed to deleteLocationBlocks');
270 }
271
272 if (empty($locationTypeId) ||
273 !CRM_Utils_Rule::positiveInteger($locationTypeId)
274 ) {
275 // so we only delete the blocks which DO NOT have a location type Id
276 // CRM-3581
277 $locationTypeId = 'null';
278 }
279
280 static $blocks = ['Address', 'Phone', 'IM', 'OpenID', 'Email'];
281
282 $params = ['contact_id' => $contactId, 'location_type_id' => $locationTypeId];
283 foreach ($blocks as $name) {
284 CRM_Core_BAO_Block::blockDelete($name, $params);
285 }
286 }
287
288 /**
289 * Make sure contact should have only one primary block, CRM-5051.
290 *
291 * @param int $contactId
292 * Contact id.
293 */
294 public static function checkPrimaryBlocks($contactId) {
295 if (!$contactId) {
296 return;
297 }
298
299 // get the loc block ids.
300 $primaryLocBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($contactId, ['is_primary' => 1]);
301 $nonPrimaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($contactId, ['is_primary' => 0]);
302
303 foreach ([
304 'Email',
305 'IM',
306 'Phone',
307 'Address',
308 'OpenID',
309 ] as $block) {
310 $name = strtolower($block);
311 if (array_key_exists($name, $primaryLocBlockIds) &&
312 !CRM_Utils_System::isNull($primaryLocBlockIds[$name])
313 ) {
314 if (count($primaryLocBlockIds[$name]) > 1) {
315 // keep only single block as primary.
316 $primaryId = array_pop($primaryLocBlockIds[$name]);
317 $resetIds = "(" . implode(',', $primaryLocBlockIds[$name]) . ")";
318 // reset all primary except one.
319 CRM_Core_DAO::executeQuery("UPDATE civicrm_$name SET is_primary = 0 WHERE id IN $resetIds");
320 }
321 }
322 elseif (array_key_exists($name, $nonPrimaryBlockIds) &&
323 !CRM_Utils_System::isNull($nonPrimaryBlockIds[$name])
324 ) {
325 // data exists and no primary block - make one primary.
326 CRM_Core_DAO::setFieldValue("CRM_Core_DAO_" . $block,
327 array_pop($nonPrimaryBlockIds[$name]), 'is_primary', 1
328 );
329 }
330 }
331 }
332
333 /**
334 * Get chain select values (whatever that means!).
335 *
336 * @param mixed $values
337 * @param string $valueType
338 * @param bool $flatten
339 *
340 * @return array
341 */
342 public static function getChainSelectValues($values, $valueType, $flatten = FALSE) {
343 if (!$values) {
344 return [];
345 }
346 $values = array_filter((array) $values);
347 $elements = [];
348 $list = &$elements;
349 $method = $valueType == 'country' ? 'stateProvinceForCountry' : 'countyForState';
350 foreach ($values as $val) {
351 $result = CRM_Core_PseudoConstant::$method($val);
352
353 // Format for quickform
354 if ($flatten) {
355 // Option-groups for multiple categories
356 if ($result && count($values) > 1) {
357 $elements["crm_optgroup_$val"] = CRM_Core_PseudoConstant::$valueType($val, FALSE);
358 }
359 $elements += $result;
360 }
361
362 // Format for js
363 else {
364 // Option-groups for multiple categories
365 if ($result && count($values) > 1) {
366 $elements[] = [
367 'value' => CRM_Core_PseudoConstant::$valueType($val, FALSE),
368 'children' => [],
369 ];
370 $list = &$elements[count($elements) - 1]['children'];
371 }
372 foreach ($result as $id => $name) {
373 $list[] = [
374 'value' => $name,
375 'key' => $id,
376 ];
377 }
378 }
379 }
380 return $elements;
381 }
382
383 }