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