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