Merge pull request #16629 from WeMoveEU/core-1620
[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 array
230 * array of objects(CRM_Core_BAO_Location)
231 */
232 public static function &getValues($entityBlock, $microformat = FALSE) {
233 if (empty($entityBlock)) {
234 return NULL;
235 }
236 $blocks = [];
237 $name_map = [
238 'im' => 'IM',
239 'openid' => 'OpenID',
240 ];
241 $blocks = [];
242 //get all the blocks for this contact
243 foreach (self::$blocks as $block) {
244 if (array_key_exists($block, $name_map)) {
245 $name = $name_map[$block];
246 }
247 else {
248 $name = ucfirst($block);
249 }
250 $baoString = 'CRM_Core_BAO_' . $name;
251 $blocks[$block] = $baoString::getValues($entityBlock, $microformat);
252 }
253 return $blocks;
254 }
255
256 /**
257 * Delete all the block associated with the location.
258 *
259 * @param int $contactId
260 * Contact id.
261 * @param int $locationTypeId
262 * Id of the location to delete.
263 * @throws CRM_Core_Exception
264 */
265 public static function deleteLocationBlocks($contactId, $locationTypeId) {
266 // ensure that contactId has a value
267 if (empty($contactId) ||
268 !CRM_Utils_Rule::positiveInteger($contactId)
269 ) {
270 throw new CRM_Core_Exception('Incorrect contact id parameter passed to deleteLocationBlocks');
271 }
272
273 if (empty($locationTypeId) ||
274 !CRM_Utils_Rule::positiveInteger($locationTypeId)
275 ) {
276 // so we only delete the blocks which DO NOT have a location type Id
277 // CRM-3581
278 $locationTypeId = 'null';
279 }
280
281 static $blocks = ['Address', 'Phone', 'IM', 'OpenID', 'Email'];
282
283 $params = ['contact_id' => $contactId, 'location_type_id' => $locationTypeId];
284 foreach ($blocks as $name) {
285 CRM_Core_BAO_Block::blockDelete($name, $params);
286 }
287 }
288
289 /**
290 * Make sure contact should have only one primary block, CRM-5051.
291 *
292 * @param int $contactId
293 * Contact id.
294 */
295 public static function checkPrimaryBlocks($contactId) {
296 if (!$contactId) {
297 return;
298 }
299
300 // get the loc block ids.
301 $primaryLocBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($contactId, ['is_primary' => 1]);
302 $nonPrimaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($contactId, ['is_primary' => 0]);
303
304 foreach ([
305 'Email',
306 'IM',
307 'Phone',
308 'Address',
309 'OpenID',
310 ] as $block) {
311 $name = strtolower($block);
312 if (array_key_exists($name, $primaryLocBlockIds) &&
313 !CRM_Utils_System::isNull($primaryLocBlockIds[$name])
314 ) {
315 if (count($primaryLocBlockIds[$name]) > 1) {
316 // keep only single block as primary.
317 $primaryId = array_pop($primaryLocBlockIds[$name]);
318 $resetIds = "(" . implode(',', $primaryLocBlockIds[$name]) . ")";
319 // reset all primary except one.
320 CRM_Core_DAO::executeQuery("UPDATE civicrm_$name SET is_primary = 0 WHERE id IN $resetIds");
321 }
322 }
323 elseif (array_key_exists($name, $nonPrimaryBlockIds) &&
324 !CRM_Utils_System::isNull($nonPrimaryBlockIds[$name])
325 ) {
326 // data exists and no primary block - make one primary.
327 CRM_Core_DAO::setFieldValue("CRM_Core_DAO_" . $block,
328 array_pop($nonPrimaryBlockIds[$name]), 'is_primary', 1
329 );
330 }
331 }
332 }
333
334 /**
335 * Get chain select values (whatever that means!).
336 *
337 * @param mixed $values
338 * @param string $valueType
339 * @param bool $flatten
340 *
341 * @return array
342 */
343 public static function getChainSelectValues($values, $valueType, $flatten = FALSE) {
344 if (!$values) {
345 return [];
346 }
347 $values = array_filter((array) $values);
348 $elements = [];
349 $list = &$elements;
350 $method = $valueType == 'country' ? 'stateProvinceForCountry' : 'countyForState';
351 foreach ($values as $val) {
352 $result = CRM_Core_PseudoConstant::$method($val);
353
354 // Format for quickform
355 if ($flatten) {
356 // Option-groups for multiple categories
357 if ($result && count($values) > 1) {
358 $elements["crm_optgroup_$val"] = CRM_Core_PseudoConstant::$valueType($val, FALSE);
359 }
360 $elements += $result;
361 }
362
363 // Format for js
364 else {
365 // Option-groups for multiple categories
366 if ($result && count($values) > 1) {
367 $elements[] = [
368 'value' => CRM_Core_PseudoConstant::$valueType($val, FALSE),
369 'children' => [],
370 ];
371 $list = &$elements[count($elements) - 1]['children'];
372 }
373 foreach ($result as $id => $name) {
374 $list[] = [
375 'value' => $name,
376 'key' => $id,
377 ];
378 }
379 }
380 }
381 return $elements;
382 }
383
384 }