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