3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 name of the above object
55 * @param array $params input parameters to find object
57 * @return array of $block objects.
61 static function &getValues($blockName, $params) {
65 $BAOString = 'CRM_Core_BAO_' . $blockName;
66 $block = new $BAOString( );
69 if (!isset($params['entity_table'])) {
70 $block->contact_id
= $params['contact_id'];
71 if (!$block->contact_id
) {
72 CRM_Core_Error
::fatal();
74 $blocks = self
::retrieveBlock($block, $blockName);
77 $blockIds = self
::getBlockIds($blockName, NULL, $params);
79 if (empty($blockIds)) {
84 foreach ($blockIds as $blockId) {
85 $block = new $BAOString( );
86 $block->id
= $blockId['id'];
87 $getBlocks = self
::retrieveBlock($block, $blockName);
88 $blocks[$count++
] = array_pop($getBlocks);
96 * Given the list of params in the params array, fetch the object
97 * and store the values in the values array
99 * @param Object $block typically a Phone|Email|IM|OpenID object
100 * @param string $blockName name of the above object
102 * @return array of $block objects.
106 static function retrieveBlock(&$block, $blockName) {
107 // we first get the primary location due to the order by clause
108 $block->orderBy('is_primary desc, id');
113 while ($block->fetch()) {
114 CRM_Core_DAO
::storeValues($block, $blocks[$count]);
115 //unset is_primary after first block. Due to some bug in earlier version
116 //there might be more than one primary blocks, hence unset is_primary other than first
118 unset($blocks[$count]['is_primary']);
127 * check if the current block object has any valid data
129 * @param array $blockFields array of fields that are of interest for this object
130 * @param array $params associated array of submitted fields
132 * @return boolean true if the block has data, otherwise false
136 static function dataExists($blockFields, &$params) {
137 foreach ($blockFields as $field) {
138 if (CRM_Utils_System
::isNull(CRM_Utils_Array
::value($field, $params))) {
146 * check if the current block exits
148 * @param string $blockName bloack name
149 * @param array $params associated array of submitted fields
151 * @return boolean true if the block exits, otherwise false
155 static function blockExists($blockName, &$params) {
156 // return if no data present
157 if (empty($params[$blockName]) ||
!is_array($params[$blockName])) {
165 * get all block ids for a contact
167 * @param string $blockName block name
168 * @param int $contactId contact id
170 * @param null $entityElements
171 * @param bool $updateBlankLocInfo
173 * @return array $contactBlockIds formatted array of block ids
178 static function getBlockIds($blockName, $contactId = NULL, $entityElements = NULL, $updateBlankLocInfo = FALSE) {
179 $allBlocks = array();
181 $name = ucfirst($blockName);
182 if ($blockName == 'im') {
185 elseif ($blockName == 'openid') {
189 $baoString = 'CRM_Core_BAO_' . $name;
191 //@todo a cleverer way to do this would be to use the same fn name on each
192 // BAO rather than constructing the fn
193 // it would also be easier to grep for
194 // e.g $bao = new $baoString;
195 // $bao->getAllBlocks()
196 $baoFunction = 'all' . $name . 's';
197 $allBlocks = $baoString::$baoFunction( $contactId, $updateBlankLocInfo );
199 elseif (!empty($entityElements) && $blockName != 'openid') {
200 $baoFunction = 'allEntity' . $name . 's';
201 $allBlocks = $baoString::$baoFunction( $entityElements );
208 * takes an associative array and creates a block
210 * @param string $blockName block name
211 * @param array $params (reference ) an assoc array of name/value pairs
212 * @param null $entity
213 * @param null $contactId
215 * @return object CRM_Core_BAO_Block object on success, null otherwise
219 static function create($blockName, &$params, $entity = NULL, $contactId = NULL) {
220 if (!self
::blockExists($blockName, $params)) {
224 $name = ucfirst($blockName);
226 $isPrimary = $isBilling = TRUE;
227 $entityElements = $blocks = array();
230 $entityElements = array(
231 'entity_table' => $params['entity_table'],
232 'entity_id' => $params['entity_id'],
236 $contactId = $params['contact_id'];
239 $updateBlankLocInfo = CRM_Utils_Array
::value('updateBlankLocInfo', $params, FALSE);
241 //get existsing block ids.
242 $blockIds = self
::getBlockIds($blockName, $contactId, $entityElements, $updateBlankLocInfo);
244 if (!$updateBlankLocInfo) {
245 $resetPrimaryId = NULL;
247 foreach ($params[$blockName] as $count => $value) {
248 $blockId = CRM_Utils_Array
::value('id', $value);
250 if (is_array($blockIds)
251 && array_key_exists($blockId, $blockIds)
253 unset($blockIds[$blockId]);
259 //lets allow to update primary w/ more cleanly.
260 if (!$resetPrimaryId && !empty($value['is_primary'])) {
262 if (is_array($blockIds)) {
263 foreach ($blockIds as $blockId => $blockValue) {
264 if (!empty($blockValue['is_primary'])) {
265 $resetPrimaryId = $blockId;
270 if ($resetPrimaryId) {
271 $baoString = 'CRM_Core_BAO_' . $blockName;
272 $block = new $baoString( );
274 $block->selectAdd("id, is_primary");
275 $block->id
= $resetPrimaryId;
276 if ($block->find(TRUE)) {
277 $block->is_primary
= FALSE;
286 foreach ($params[$blockName] as $count => $value) {
287 if (!is_array($value)) {
290 $contactFields = array(
291 'contact_id' => $contactId,
292 'location_type_id' => CRM_Utils_Array
::value('location_type_id', $value),
296 if (empty($value['id']) &&
297 is_array($blockIds) && !empty($blockIds)
299 foreach ($blockIds as $blockId => $blockValue) {
300 if ($updateBlankLocInfo) {
301 if (!empty($blockIds[$count])) {
302 $value['id'] = $blockIds[$count]['id'];
303 unset($blockIds[$count]);
307 if ($blockValue['locationTypeId'] == CRM_Utils_Array
::value('location_type_id', $value)) {
310 if ($blockName == 'phone') {
311 $phoneTypeBlockValue = CRM_Utils_Array
::value('phoneTypeId', $blockValue);
312 if ($phoneTypeBlockValue == CRM_Utils_Array
::value('phone_type_id', $value)) {
316 elseif ($blockName == 'im') {
317 $providerBlockValue = CRM_Utils_Array
::value('providerId', $blockValue);
318 if ($providerBlockValue == $value['provider_id']) {
327 //assigned id as first come first serve basis
328 $value['id'] = $blockValue['id'];
329 if (!$primaryId && !empty($blockValue['is_primary'])) {
330 $value['is_primary'] = $blockValue['is_primary'];
332 unset($blockIds[$blockId]);
340 $dataExits = self
::dataExists(self
::$requiredBlockFields[$blockName], $value);
342 // Note there could be cases when block info already exist ($value[id] is set) for a contact/entity
343 // BUT info is not present at this time, and therefore we should be really careful when deleting the block.
344 // $updateBlankLocInfo will help take appropriate decision. CRM-5969
345 if (!empty($value['id']) && !$dataExits && $updateBlankLocInfo) {
346 //delete the existing record
347 self
::blockDelete($blockName, array('id' => $value['id']));
350 elseif (!$dataExits) {
354 if ($isPrimary && !empty($value['is_primary'])) {
355 $contactFields['is_primary'] = $value['is_primary'];
359 $contactFields['is_primary'] = 0;
362 if ($isBilling && !empty($value['is_billing'])) {
363 $contactFields['is_billing'] = $value['is_billing'];
367 $contactFields['is_billing'] = 0;
370 $blockFields = array_merge($value, $contactFields);
371 $baoString = 'CRM_Core_BAO_' . $name;
372 $blocks[] = $baoString::add( $blockFields );
375 // we need to delete blocks that were deleted during update
376 if ($updateBlankLocInfo && !empty($blockIds)) {
377 foreach ($blockIds as $deleteBlock) {
378 if (empty($deleteBlock['id'])) {
381 self
::blockDelete($blockName, array('id' => $deleteBlock['id']));
391 * @param string $blockName block name
392 * @param int $params associates array
397 static function blockDelete($blockName, $params) {
398 $name = ucfirst($blockName);
399 if ($blockName == 'im') {
402 elseif ($blockName == 'openid') {
406 $baoString = 'CRM_Core_DAO_' . $name;
407 $block = new $baoString( );
409 $block->copyValues($params);
411 * CRM-11006 add call to pre and post hook for delete action
413 CRM_Utils_Hook
::pre('delete', $name, $block->id
, CRM_Core_DAO
::$_nullArray);
415 CRM_Utils_Hook
::post('delete', $name, $block->id
, $block);
419 * Handling for is_primary.
420 * $params is_primary could be
421 * # 1 - find other entries with is_primary = 1 & reset them to 0
422 * # 0 - make sure at least one entry is set to 1
423 * - if no other entry is 1 change to 1
424 * - if one other entry exists change that to 1
425 * - if more than one other entry exists change first one to 1
426 * @fixme - perhaps should choose by location_type
427 * # empty - same as 0 as once we have checked first step
428 * we know if it should be 1 or 0
430 * if $params['id'] is set $params['contact_id'] may need to be retrieved
432 * @param array $params
435 * @throws API_Exception
438 public static function handlePrimary(&$params, $class) {
439 $table = CRM_Core_DAO_AllCoreTables
::getTableForClass($class);
441 throw new API_Exception("Failed to locate table for class [$class]");
444 // contact_id in params might be empty or the string 'null' so cast to integer
445 $contactId = (int) CRM_Utils_Array
::value('contact_id', $params);
446 // If id is set & we haven't been passed a contact_id, retrieve it
447 if (!empty($params['id']) && !isset($params['contact_id'])) {
448 $entity = new $class();
449 $entity->id
= $params['id'];
451 $contactId = $entity->contact_id
;
453 // If entity is not associated with contact, concept of is_primary not relevant
458 // if params is_primary then set all others to not be primary & exit out
459 if (!empty($params['is_primary'])) {
460 $sql = "UPDATE $table SET is_primary = 0 WHERE contact_id = %1";
461 $sqlParams = array(1 => array($contactId, 'Integer'));
462 // we don't want to create unecessary entries in the log_ tables so exclude the one we are working on
463 if(!empty($params['id'])){
464 $sql .= " AND id <> %2";
465 $sqlParams[2] = array($params['id'], 'Integer');
467 CRM_Core_DAO
::executeQuery($sql, $sqlParams);
471 //Check what other emails exist for the contact
472 $existingEntities = new $class();
473 $existingEntities->contact_id
= $contactId;
474 $existingEntities->orderBy('is_primary DESC');
475 if (!$existingEntities->find(TRUE) ||
(!empty($params['id']) && $existingEntities->id
== $params['id'])) {
476 // ie. if no others is set to be primary then this has to be primary set to 1 so change
477 $params['is_primary'] = 1;
482 * If the only existing email is the one we are editing then we must set
486 if ( $existingEntities->N
== 1 && $existingEntities->id
== CRM_Utils_Array
::value( 'id', $params ) ) {
487 $params['is_primary'] = 1;
491 if ($existingEntities->is_primary
== 1) {
494 // so at this point we are only dealing with ones explicity setting is_primary to 0
495 // since we have reverse sorted by email we can either set the first one to
496 // primary or return if is already is
497 $existingEntities->is_primary
= 1;
498 $existingEntities->save();
503 * Sort location array so primary element is first
505 * @param array $locations
508 static function sortPrimaryFirst(&$locations){
509 uasort($locations, 'self::primaryComparison');
513 * compare 2 locations to see which should go first based on is_primary
514 * (sort function for sortPrimaryFirst)
515 * @param array $location1
516 * @param array $location2
519 static function primaryComparison($location1, $location2){
520 $l1 = CRM_Utils_Array
::value('is_primary', $location1);
521 $l2 = CRM_Utils_Array
::value('is_primary', $location2);
525 return ($l1 < $l2) ?
-1 : 1;