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