Cleanup phpdoc comments
[civicrm-core.git] / CRM / Core / BAO / Block.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 * add static functions to include some common functionality
35 * used across location sub object BAO classes
36 *
37 */
38 class CRM_Core_BAO_Block {
39
40 /**
41 * Fields that are required for a valid block
42 */
43 static $requiredBlockFields = array(
44 'email' => array('email'),
45 'phone' => array('phone'),
46 'im' => array('name'),
47 'openid' => array('openid')
48 );
49
50 /**
51 * Given the list of params in the params array, fetch the object
52 * and store the values in the values array
53 *
54 * @param string $blockName name of the above object
55 * @param array $params input parameters to find object
56 *
57 * @return array of $block objects.
58 * @access public
59 * @static
60 */
61 static function &getValues($blockName, $params) {
62 if (empty($params)) {
63 return NULL;
64 }
65 $BAOString = 'CRM_Core_BAO_' . $blockName;
66 $block = new $BAOString( );
67
68 $blocks = array();
69 if (!isset($params['entity_table'])) {
70 $block->contact_id = $params['contact_id'];
71 if (!$block->contact_id) {
72 CRM_Core_Error::fatal();
73 }
74 $blocks = self::retrieveBlock($block, $blockName);
75 }
76 else {
77 $blockIds = self::getBlockIds($blockName, NULL, $params);
78
79 if (empty($blockIds)) {
80 return $blocks;
81 }
82
83 $count = 1;
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);
89 }
90 }
91
92 return $blocks;
93 }
94
95 /**
96 * Given the list of params in the params array, fetch the object
97 * and store the values in the values array
98 *
99 * @param Object $block typically a Phone|Email|IM|OpenID object
100 * @param string $blockName name of the above object
101 *
102 * @return array of $block objects.
103 * @access public
104 * @static
105 */
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');
109 $block->find();
110
111 $count = 1;
112 $blocks = array();
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
117 if ($count > 1) {
118 unset($blocks[$count]['is_primary']);
119 }
120 $count++;
121 }
122
123 return $blocks;
124 }
125
126 /**
127 * Check if the current block object has any valid data
128 *
129 * @param array $blockFields array of fields that are of interest for this object
130 * @param array $params associated array of submitted fields
131 *
132 * @return boolean true if the block has data, otherwise false
133 * @access public
134 * @static
135 */
136 static function dataExists($blockFields, &$params) {
137 foreach ($blockFields as $field) {
138 if (CRM_Utils_System::isNull(CRM_Utils_Array::value($field, $params))) {
139 return FALSE;
140 }
141 }
142 return TRUE;
143 }
144
145 /**
146 * Check if the current block exits
147 *
148 * @param string $blockName bloack name
149 * @param array $params associated array of submitted fields
150 *
151 * @return boolean true if the block exits, otherwise false
152 * @access public
153 * @static
154 */
155 static function blockExists($blockName, &$params) {
156 // return if no data present
157 if (empty($params[$blockName]) || !is_array($params[$blockName])) {
158 return FALSE;
159 }
160
161 return TRUE;
162 }
163
164 /**
165 * Get all block ids for a contact
166 *
167 * @param string $blockName block name
168 * @param int $contactId contact id
169 *
170 * @param null $entityElements
171 * @param bool $updateBlankLocInfo
172 *
173 * @return array $contactBlockIds formatted array of block ids
174 *
175 * @access public
176 * @static
177 */
178 static function getBlockIds($blockName, $contactId = NULL, $entityElements = NULL, $updateBlankLocInfo = FALSE) {
179 $allBlocks = array();
180
181 $name = ucfirst($blockName);
182 if ($blockName == 'im') {
183 $name = 'IM';
184 }
185 elseif ($blockName == 'openid') {
186 $name = 'OpenID';
187 }
188
189 $baoString = 'CRM_Core_BAO_' . $name;
190 if ($contactId) {
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 );
198 }
199 elseif (!empty($entityElements) && $blockName != 'openid') {
200 $baoFunction = 'allEntity' . $name . 's';
201 $allBlocks = $baoString::$baoFunction( $entityElements );
202 }
203
204 return $allBlocks;
205 }
206
207 /**
208 * Takes an associative array and creates a block
209 *
210 * @param string $blockName block name
211 * @param array $params (reference ) an assoc array of name/value pairs
212 * @param null $entity
213 * @param int $contactId
214 *
215 * @return object CRM_Core_BAO_Block object on success, null otherwise
216 * @access public
217 * @static
218 */
219 static function create($blockName, &$params, $entity = NULL, $contactId = NULL) {
220 if (!self::blockExists($blockName, $params)) {
221 return NULL;
222 }
223
224 $name = ucfirst($blockName);
225 $contactId = NULL;
226 $isPrimary = $isBilling = TRUE;
227 $entityElements = $blocks = array();
228
229 if ($entity) {
230 $entityElements = array(
231 'entity_table' => $params['entity_table'],
232 'entity_id' => $params['entity_id'],
233 );
234 }
235 else {
236 $contactId = $params['contact_id'];
237 }
238
239 $updateBlankLocInfo = CRM_Utils_Array::value('updateBlankLocInfo', $params, FALSE);
240
241 //get existsing block ids.
242 $blockIds = self::getBlockIds($blockName, $contactId, $entityElements, $updateBlankLocInfo);
243
244 if (!$updateBlankLocInfo) {
245 $resetPrimaryId = NULL;
246 $primaryId = FALSE;
247 foreach ($params[$blockName] as $count => $value) {
248 $blockId = CRM_Utils_Array::value('id', $value);
249 if ($blockId) {
250 if (is_array($blockIds)
251 && array_key_exists($blockId, $blockIds)
252 ) {
253 unset($blockIds[$blockId]);
254 }
255 else {
256 unset($value['id']);
257 }
258 }
259 //lets allow to update primary w/ more cleanly.
260 if (!$resetPrimaryId && !empty($value['is_primary'])) {
261 $primaryId = TRUE;
262 if (is_array($blockIds)) {
263 foreach ($blockIds as $blockId => $blockValue) {
264 if (!empty($blockValue['is_primary'])) {
265 $resetPrimaryId = $blockId;
266 break;
267 }
268 }
269 }
270 if ($resetPrimaryId) {
271 $baoString = 'CRM_Core_BAO_' . $blockName;
272 $block = new $baoString( );
273 $block->selectAdd();
274 $block->selectAdd("id, is_primary");
275 $block->id = $resetPrimaryId;
276 if ($block->find(TRUE)) {
277 $block->is_primary = FALSE;
278 $block->save();
279 }
280 $block->free();
281 }
282 }
283 }
284 }
285
286 foreach ($params[$blockName] as $count => $value) {
287 if (!is_array($value)) {
288 continue;
289 }
290 $contactFields = array(
291 'contact_id' => $contactId,
292 'location_type_id' => CRM_Utils_Array::value('location_type_id', $value),
293 );
294
295 //check for update
296 if (empty($value['id']) &&
297 is_array($blockIds) && !empty($blockIds)
298 ) {
299 foreach ($blockIds as $blockId => $blockValue) {
300 if ($updateBlankLocInfo) {
301 if (!empty($blockIds[$count])) {
302 $value['id'] = $blockIds[$count]['id'];
303 unset($blockIds[$count]);
304 }
305 }
306 else {
307 if ($blockValue['locationTypeId'] == CRM_Utils_Array::value('location_type_id', $value)) {
308 $valueId = FALSE;
309
310 if ($blockName == 'phone') {
311 $phoneTypeBlockValue = CRM_Utils_Array::value('phoneTypeId', $blockValue);
312 if ($phoneTypeBlockValue == CRM_Utils_Array::value('phone_type_id', $value)) {
313 $valueId = TRUE;
314 }
315 }
316 elseif ($blockName == 'im') {
317 $providerBlockValue = CRM_Utils_Array::value('providerId', $blockValue);
318 if ($providerBlockValue == $value['provider_id']) {
319 $valueId = TRUE;
320 }
321 }
322 else {
323 $valueId = TRUE;
324 }
325
326 if ($valueId) {
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'];
331 }
332 unset($blockIds[$blockId]);
333 break;
334 }
335 }
336 }
337 }
338 }
339
340 $dataExits = self::dataExists(self::$requiredBlockFields[$blockName], $value);
341
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']));
348 continue;
349 }
350 elseif (!$dataExits) {
351 continue;
352 }
353
354 if ($isPrimary && !empty($value['is_primary'])) {
355 $contactFields['is_primary'] = $value['is_primary'];
356 $isPrimary = FALSE;
357 }
358 else {
359 $contactFields['is_primary'] = 0;
360 }
361
362 if ($isBilling && !empty($value['is_billing'])) {
363 $contactFields['is_billing'] = $value['is_billing'];
364 $isBilling = FALSE;
365 }
366 else {
367 $contactFields['is_billing'] = 0;
368 }
369
370 $blockFields = array_merge($value, $contactFields);
371 $baoString = 'CRM_Core_BAO_' . $name;
372 $blocks[] = $baoString::add( $blockFields );
373 }
374
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'])) {
379 continue;
380 }
381 self::blockDelete($blockName, array('id' => $deleteBlock['id']));
382 }
383 }
384
385 return $blocks;
386 }
387
388 /**
389 * Delete block
390 *
391 * @param string $blockName block name
392 * @param int $params associates array
393 *
394 * @return void
395 * @static
396 */
397 static function blockDelete($blockName, $params) {
398 $name = ucfirst($blockName);
399 if ($blockName == 'im') {
400 $name = 'IM';
401 }
402 elseif ($blockName == 'openid') {
403 $name = 'OpenID';
404 }
405
406 $baoString = 'CRM_Core_DAO_' . $name;
407 $block = new $baoString( );
408
409 $block->copyValues($params);
410 /*
411 * CRM-11006 add call to pre and post hook for delete action
412 */
413 CRM_Utils_Hook::pre('delete', $name, $block->id, CRM_Core_DAO::$_nullArray);
414 $block->delete();
415 CRM_Utils_Hook::post('delete', $name, $block->id, $block);
416 }
417
418 /**
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
429 *
430 * if $params['id'] is set $params['contact_id'] may need to be retrieved
431 *
432 * @param array $params
433 * @param $class
434 *
435 * @throws API_Exception
436 * @static
437 */
438 public static function handlePrimary(&$params, $class) {
439 $table = CRM_Core_DAO_AllCoreTables::getTableForClass($class);
440 if (!$table) {
441 throw new API_Exception("Failed to locate table for class [$class]");
442 }
443
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'];
450 $entity->find(TRUE);
451 $contactId = $entity->contact_id;
452 }
453 // If entity is not associated with contact, concept of is_primary not relevant
454 if (!$contactId) {
455 return;
456 }
457
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');
466 }
467 CRM_Core_DAO::executeQuery($sql, $sqlParams);
468 return;
469 }
470
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;
478 return;
479 }
480 else {
481 /*
482 * If the only existing email is the one we are editing then we must set
483 * is_primary to 1
484 * CRM-10451
485 */
486 if ( $existingEntities->N == 1 && $existingEntities->id == CRM_Utils_Array::value( 'id', $params ) ) {
487 $params['is_primary'] = 1;
488 return;
489 }
490
491 if ($existingEntities->is_primary == 1) {
492 return;
493 }
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();
499 }
500 }
501
502 /**
503 * Sort location array so primary element is first
504 *
505 * @param array $locations
506 *
507 */
508 static function sortPrimaryFirst(&$locations){
509 uasort($locations, 'self::primaryComparison');
510 }
511
512 /**
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
517 * @return number
518 */
519 static function primaryComparison($location1, $location2){
520 $l1 = CRM_Utils_Array::value('is_primary', $location1);
521 $l2 = CRM_Utils_Array::value('is_primary', $location2);
522 if ($l1 == $l2) {
523 return 0;
524 }
525 return ($l1 < $l2) ? -1 : 1;
526 }
527 }
528