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