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