3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
34 * add static functions to include some common functionality
35 * used across location sub object BAO classes
38 class CRM_Core_BAO_Block
{
41 * Fields that are required for a valid block
43 static $requiredBlockFields = array(
44 'email' => array('email'),
45 'phone' => array('phone'),
46 'im' => array('name'),
47 'openid' => array('openid'),
51 * Given the list of params in the params array, fetch the object
52 * and store the values in the values array
54 * @param string $blockName
55 * Name of the above object.
56 * @param array $params
57 * Input parameters to find object.
60 * Array of $block objects.
63 public static function &getValues($blockName, $params) {
67 $BAOString = 'CRM_Core_BAO_' . $blockName;
68 $block = new $BAOString();
71 if (!isset($params['entity_table'])) {
72 $block->contact_id
= $params['contact_id'];
73 if (!$block->contact_id
) {
74 CRM_Core_Error
::fatal();
76 $blocks = self
::retrieveBlock($block, $blockName);
79 $blockIds = self
::getBlockIds($blockName, NULL, $params);
81 if (empty($blockIds)) {
86 foreach ($blockIds as $blockId) {
87 $block = new $BAOString();
88 $block->id
= $blockId['id'];
89 $getBlocks = self
::retrieveBlock($block, $blockName);
90 $blocks[$count++
] = array_pop($getBlocks);
98 * Given the list of params in the params array, fetch the object
99 * and store the values in the values array
101 * @param Object $block
102 * Typically a Phone|Email|IM|OpenID object.
103 * @param string $blockName
104 * Name of the above object.
107 * Array of $block objects.
110 public static function retrieveBlock(&$block, $blockName) {
111 // we first get the primary location due to the order by clause
112 $block->orderBy('is_primary desc, id');
117 while ($block->fetch()) {
118 CRM_Core_DAO
::storeValues($block, $blocks[$count]);
119 //unset is_primary after first block. Due to some bug in earlier version
120 //there might be more than one primary blocks, hence unset is_primary other than first
122 unset($blocks[$count]['is_primary']);
131 * Check if the current block object has any valid data
133 * @param array $blockFields
134 * Array of fields that are of interest for this object.
135 * @param array $params
136 * Associated array of submitted fields.
139 * true if the block has data, otherwise false
142 public static function dataExists($blockFields, &$params) {
143 foreach ($blockFields as $field) {
144 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value($field, $params))) {
152 * Check if the current block exits
154 * @param string $blockName
156 * @param array $params
157 * Associated array of submitted fields.
160 * true if the block exits, otherwise false
163 public static function blockExists($blockName, &$params) {
164 // return if no data present
165 if (empty($params[$blockName]) ||
!is_array($params[$blockName])) {
173 * Get all block ids for a contact
175 * @param string $blockName
177 * @param int $contactId
180 * @param null $entityElements
181 * @param bool $updateBlankLocInfo
184 * formatted array of block ids
188 public static function getBlockIds($blockName, $contactId = NULL, $entityElements = NULL, $updateBlankLocInfo = FALSE) {
189 $allBlocks = array();
191 $name = ucfirst($blockName);
192 if ($blockName == 'im') {
195 elseif ($blockName == 'openid') {
199 $baoString = 'CRM_Core_BAO_' . $name;
201 //@todo a cleverer way to do this would be to use the same fn name on each
202 // BAO rather than constructing the fn
203 // it would also be easier to grep for
204 // e.g $bao = new $baoString;
205 // $bao->getAllBlocks()
206 $baoFunction = 'all' . $name . 's';
207 $allBlocks = $baoString::$baoFunction($contactId, $updateBlankLocInfo);
209 elseif (!empty($entityElements) && $blockName != 'openid') {
210 $baoFunction = 'allEntity' . $name . 's';
211 $allBlocks = $baoString::$baoFunction($entityElements);
218 * Takes an associative array and creates a block
220 * @param string $blockName
222 * @param array $params
223 * (reference ) an assoc array of name/value pairs.
224 * @param null $entity
225 * @param int $contactId
228 * CRM_Core_BAO_Block object on success, null otherwise
231 public static function create($blockName, &$params, $entity = NULL, $contactId = NULL) {
232 if (!self
::blockExists($blockName, $params)) {
236 $name = ucfirst($blockName);
238 $isPrimary = $isBilling = TRUE;
239 $entityElements = $blocks = array();
242 $entityElements = array(
243 'entity_table' => $params['entity_table'],
244 'entity_id' => $params['entity_id'],
248 $contactId = $params['contact_id'];
251 $updateBlankLocInfo = CRM_Utils_Array
::value('updateBlankLocInfo', $params, FALSE);
253 //get existsing block ids.
254 $blockIds = self
::getBlockIds($blockName, $contactId, $entityElements, $updateBlankLocInfo);
256 if (!$updateBlankLocInfo) {
257 $resetPrimaryId = NULL;
259 foreach ($params[$blockName] as $count => $value) {
260 $blockId = CRM_Utils_Array
::value('id', $value);
262 if (is_array($blockIds)
263 && array_key_exists($blockId, $blockIds)
265 unset($blockIds[$blockId]);
271 //lets allow to update primary w/ more cleanly.
272 if (!$resetPrimaryId && !empty($value['is_primary'])) {
274 if (is_array($blockIds)) {
275 foreach ($blockIds as $blockId => $blockValue) {
276 if (!empty($blockValue['is_primary'])) {
277 $resetPrimaryId = $blockId;
282 if ($resetPrimaryId) {
283 $baoString = 'CRM_Core_BAO_' . $blockName;
284 $block = new $baoString();
286 $block->selectAdd("id, is_primary");
287 $block->id
= $resetPrimaryId;
288 if ($block->find(TRUE)) {
289 $block->is_primary
= FALSE;
298 foreach ($params[$blockName] as $count => $value) {
299 if (!is_array($value)) {
302 $contactFields = array(
303 'contact_id' => $contactId,
304 'location_type_id' => CRM_Utils_Array
::value('location_type_id', $value),
308 if (empty($value['id']) &&
309 is_array($blockIds) && !empty($blockIds)
311 foreach ($blockIds as $blockId => $blockValue) {
312 if ($updateBlankLocInfo) {
313 if (!empty($blockIds[$count])) {
314 $value['id'] = $blockIds[$count]['id'];
315 unset($blockIds[$count]);
319 if ($blockValue['locationTypeId'] == CRM_Utils_Array
::value('location_type_id', $value)) {
322 if ($blockName == 'phone') {
323 $phoneTypeBlockValue = CRM_Utils_Array
::value('phoneTypeId', $blockValue);
324 if ($phoneTypeBlockValue == CRM_Utils_Array
::value('phone_type_id', $value)) {
328 elseif ($blockName == 'im') {
329 $providerBlockValue = CRM_Utils_Array
::value('providerId', $blockValue);
330 if ($providerBlockValue == $value['provider_id']) {
339 //assigned id as first come first serve basis
340 $value['id'] = $blockValue['id'];
341 if (!$primaryId && !empty($blockValue['is_primary'])) {
342 $value['is_primary'] = $blockValue['is_primary'];
344 unset($blockIds[$blockId]);
352 $dataExits = self
::dataExists(self
::$requiredBlockFields[$blockName], $value);
354 // Note there could be cases when block info already exist ($value[id] is set) for a contact/entity
355 // BUT info is not present at this time, and therefore we should be really careful when deleting the block.
356 // $updateBlankLocInfo will help take appropriate decision. CRM-5969
357 if (!empty($value['id']) && !$dataExits && $updateBlankLocInfo) {
358 //delete the existing record
359 self
::blockDelete($blockName, array('id' => $value['id']));
362 elseif (!$dataExits) {
366 if ($isPrimary && !empty($value['is_primary'])) {
367 $contactFields['is_primary'] = $value['is_primary'];
371 $contactFields['is_primary'] = 0;
374 if ($isBilling && !empty($value['is_billing'])) {
375 $contactFields['is_billing'] = $value['is_billing'];
379 $contactFields['is_billing'] = 0;
382 $blockFields = array_merge($value, $contactFields);
383 $baoString = 'CRM_Core_BAO_' . $name;
384 $blocks[] = $baoString::add($blockFields);
387 // we need to delete blocks that were deleted during update
388 if ($updateBlankLocInfo && !empty($blockIds)) {
389 foreach ($blockIds as $deleteBlock) {
390 if (empty($deleteBlock['id'])) {
393 self
::blockDelete($blockName, array('id' => $deleteBlock['id']));
403 * @param string $blockName
411 public static function blockDelete($blockName, $params) {
412 $name = ucfirst($blockName);
413 if ($blockName == 'im') {
416 elseif ($blockName == 'openid') {
420 $baoString = 'CRM_Core_DAO_' . $name;
421 $block = new $baoString();
423 $block->copyValues($params);
425 // CRM-11006 add call to pre and post hook for delete action
426 CRM_Utils_Hook
::pre('delete', $name, $block->id
, CRM_Core_DAO
::$_nullArray);
428 CRM_Utils_Hook
::post('delete', $name, $block->id
, $block);
432 * Handling for is_primary.
433 * $params is_primary could be
434 * # 1 - find other entries with is_primary = 1 & reset them to 0
435 * # 0 - make sure at least one entry is set to 1
436 * - if no other entry is 1 change to 1
437 * - if one other entry exists change that to 1
438 * - if more than one other entry exists change first one to 1
439 * @fixme - perhaps should choose by location_type
440 * # empty - same as 0 as once we have checked first step
441 * we know if it should be 1 or 0
443 * if $params['id'] is set $params['contact_id'] may need to be retrieved
445 * @param array $params
448 * @throws API_Exception
451 public static function handlePrimary(&$params, $class) {
452 $table = CRM_Core_DAO_AllCoreTables
::getTableForClass($class);
454 throw new API_Exception("Failed to locate table for class [$class]");
457 // contact_id in params might be empty or the string 'null' so cast to integer
458 $contactId = (int) CRM_Utils_Array
::value('contact_id', $params);
459 // If id is set & we haven't been passed a contact_id, retrieve it
460 if (!empty($params['id']) && !isset($params['contact_id'])) {
461 $entity = new $class();
462 $entity->id
= $params['id'];
464 $contactId = $entity->contact_id
;
466 // If entity is not associated with contact, concept of is_primary not relevant
471 // if params is_primary then set all others to not be primary & exit out
472 if (!empty($params['is_primary'])) {
473 $sql = "UPDATE $table SET is_primary = 0 WHERE contact_id = %1";
474 $sqlParams = array(1 => array($contactId, 'Integer'));
475 // we don't want to create unecessary entries in the log_ tables so exclude the one we are working on
476 if (!empty($params['id'])) {
477 $sql .= " AND id <> %2";
478 $sqlParams[2] = array($params['id'], 'Integer');
480 CRM_Core_DAO
::executeQuery($sql, $sqlParams);
484 //Check what other emails exist for the contact
485 $existingEntities = new $class();
486 $existingEntities->contact_id
= $contactId;
487 $existingEntities->orderBy('is_primary DESC');
488 if (!$existingEntities->find(TRUE) ||
(!empty($params['id']) && $existingEntities->id
== $params['id'])) {
489 // ie. if no others is set to be primary then this has to be primary set to 1 so change
490 $params['is_primary'] = 1;
495 * If the only existing email is the one we are editing then we must set
499 if ($existingEntities->N
== 1 && $existingEntities->id
== CRM_Utils_Array
::value('id', $params)) {
500 $params['is_primary'] = 1;
504 if ($existingEntities->is_primary
== 1) {
507 // so at this point we are only dealing with ones explicity setting is_primary to 0
508 // since we have reverse sorted by email we can either set the first one to
509 // primary or return if is already is
510 $existingEntities->is_primary
= 1;
511 $existingEntities->save();
516 * Sort location array so primary element is first
518 * @param array $locations
520 public static function sortPrimaryFirst(&$locations) {
521 uasort($locations, 'self::primaryComparison');
525 * compare 2 locations to see which should go first based on is_primary
526 * (sort function for sortPrimaryFirst)
527 * @param array $location1
528 * @param array $location2
531 public static function primaryComparison($location1, $location2) {
532 $l1 = CRM_Utils_Array
::value('is_primary', $location1);
533 $l2 = CRM_Utils_Array
::value('is_primary', $location2);
537 return ($l1 < $l2) ?
-1 : 1;