bulk comment fixes
[civicrm-core.git] / CRM / Core / BAO / Block.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 * add static functions to include some common functionality
35 * used across location sub object BAO classes
36 *
37 */
38class 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 *
77b97be7
EM
54 * @param string $blockName name of the above object
55 * @param array $params input parameters to find object
56 *
57 * @internal param Object $block typically a Phone|Email|IM|OpenID object
58 * @internal param array $values output values of the object
6a488035
TO
59 *
60 * @return array of $block objects.
61 * @access public
62 * @static
63 */
64 static function &getValues($blockName, $params) {
65 if (empty($params)) {
66 return NULL;
67 }
e52506b0 68 $BAOString = 'CRM_Core_BAO_' . $blockName;
69 $block = new $BAOString( );
6a488035
TO
70
71 $blocks = array();
72 if (!isset($params['entity_table'])) {
73 $block->contact_id = $params['contact_id'];
74 if (!$block->contact_id) {
75 CRM_Core_Error::fatal();
76 }
77 $blocks = self::retrieveBlock($block, $blockName);
78 }
79 else {
80 $blockIds = self::getBlockIds($blockName, NULL, $params);
81
82 if (empty($blockIds)) {
83 return $blocks;
84 }
85
86 $count = 1;
87 foreach ($blockIds as $blockId) {
e52506b0 88 $block = new $BAOString( );
6a488035
TO
89 $block->id = $blockId['id'];
90 $getBlocks = self::retrieveBlock($block, $blockName);
91 $blocks[$count++] = array_pop($getBlocks);
92 }
93 }
94
95 return $blocks;
96 }
97
98 /**
99 * Given the list of params in the params array, fetch the object
100 * and store the values in the values array
101 *
77b97be7
EM
102 * @param Object $block typically a Phone|Email|IM|OpenID object
103 * @param string $blockName name of the above object
104 *
105 * @internal param array $values output values of the object
6a488035
TO
106 *
107 * @return array of $block objects.
108 * @access public
109 * @static
110 */
111 static function retrieveBlock(&$block, $blockName) {
112 // we first get the primary location due to the order by clause
113 $block->orderBy('is_primary desc, id');
114 $block->find();
115
116 $count = 1;
117 $blocks = array();
118 while ($block->fetch()) {
119 CRM_Core_DAO::storeValues($block, $blocks[$count]);
120 //unset is_primary after first block. Due to some bug in earlier version
121 //there might be more than one primary blocks, hence unset is_primary other than first
122 if ($count > 1) {
123 unset($blocks[$count]['is_primary']);
124 }
125 $count++;
126 }
127
128 return $blocks;
129 }
130
131 /**
132 * check if the current block object has any valid data
133 *
134 * @param array $blockFields array of fields that are of interest for this object
135 * @param array $params associated array of submitted fields
136 *
137 * @return boolean true if the block has data, otherwise false
138 * @access public
139 * @static
140 */
141 static function dataExists($blockFields, &$params) {
142 foreach ($blockFields as $field) {
143 if (CRM_Utils_System::isNull(CRM_Utils_Array::value($field, $params))) {
144 return FALSE;
145 }
146 }
147 return TRUE;
148 }
149
150 /**
151 * check if the current block exits
152 *
153 * @param string $blockName bloack name
154 * @param array $params associated array of submitted fields
155 *
156 * @return boolean true if the block exits, otherwise false
157 * @access public
158 * @static
159 */
160 static function blockExists($blockName, &$params) {
161 // return if no data present
a7488080 162 if (empty($params[$blockName]) || !is_array($params[$blockName])) {
6a488035
TO
163 return FALSE;
164 }
165
166 return TRUE;
167 }
168
169 /**
170 * Function to get all block ids for a contact
171 *
172 * @param string $blockName block name
173 * @param int $contactId contact id
174 *
175 * @return array $contactBlockIds formatted array of block ids
176 *
177 * @access public
178 * @static
179 */
180 static function getBlockIds($blockName, $contactId = NULL, $entityElements = NULL, $updateBlankLocInfo = FALSE) {
181 $allBlocks = array();
e4f5a5f9 182
6a488035
TO
183 $name = ucfirst($blockName);
184 if ($blockName == 'im') {
185 $name = 'IM';
186 }
187 elseif ($blockName == 'openid') {
188 $name = 'OpenID';
189 }
190
e4f5a5f9 191 $baoString = 'CRM_Core_BAO_' . $name;
6a488035 192 if ($contactId) {
e4f5a5f9 193 //@todo a cleverer way to do this would be to use the same fn name on each
194 // BAO rather than constructing the fn
195 // it would also be easier to grep for
196 // e.g $bao = new $baoString;
197 // $bao->getAllBlocks()
198 $baoFunction = 'all' . $name . 's';
199 $allBlocks = $baoString::$baoFunction( $contactId, $updateBlankLocInfo );
6a488035
TO
200 }
201 elseif (!empty($entityElements) && $blockName != 'openid') {
e4f5a5f9 202 $baoFunction = 'allEntity' . $name . 's';
203 $allBlocks = $baoString::$baoFunction( $entityElements );
6a488035
TO
204 }
205
206 return $allBlocks;
207 }
208
209 /**
210 * takes an associative array and creates a block
211 *
212 * @param string $blockName block name
213 * @param array $params (reference ) an assoc array of name/value pairs
214 * @param array $requiredFields fields that's are required in a block
215 *
216 * @return object CRM_Core_BAO_Block object on success, null otherwise
217 * @access public
218 * @static
219 */
220 static function create($blockName, &$params, $entity = NULL, $contactId = NULL) {
221 if (!self::blockExists($blockName, $params)) {
222 return NULL;
223 }
224
225 $name = ucfirst($blockName);
226 $contactId = NULL;
227 $isPrimary = $isBilling = TRUE;
228 $entityElements = $blocks = array();
229
230 if ($entity) {
231 $entityElements = array(
232 'entity_table' => $params['entity_table'],
233 'entity_id' => $params['entity_id'],
234 );
235 }
236 else {
237 $contactId = $params['contact_id'];
238 }
239
240 $updateBlankLocInfo = CRM_Utils_Array::value('updateBlankLocInfo', $params, FALSE);
241
242 //get existsing block ids.
243 $blockIds = self::getBlockIds($blockName, $contactId, $entityElements, $updateBlankLocInfo);
244
245 if (!$updateBlankLocInfo) {
246 $resetPrimaryId = NULL;
247 $primaryId = FALSE;
248 foreach ($params[$blockName] as $count => $value) {
249 $blockId = CRM_Utils_Array::value('id', $value);
250 if ($blockId) {
251 if (is_array($blockIds)
252 && array_key_exists($blockId, $blockIds)
253 ) {
254 unset($blockIds[$blockId]);
255 }
256 else {
257 unset($value['id']);
258 }
259 }
260 //lets allow to update primary w/ more cleanly.
8cc574cf 261 if (!$resetPrimaryId && !empty($value['is_primary'])) {
6a488035
TO
262 $primaryId = TRUE;
263 if (is_array($blockIds)) {
264 foreach ($blockIds as $blockId => $blockValue) {
a7488080 265 if (!empty($blockValue['is_primary'])) {
6a488035
TO
266 $resetPrimaryId = $blockId;
267 break;
268 }
269 }
270 }
271 if ($resetPrimaryId) {
e4f5a5f9 272 $baoString = 'CRM_Core_BAO_' . $blockName;
273 $block = new $baoString( );
6a488035
TO
274 $block->selectAdd();
275 $block->selectAdd("id, is_primary");
276 $block->id = $resetPrimaryId;
277 if ($block->find(TRUE)) {
278 $block->is_primary = FALSE;
279 $block->save();
280 }
281 $block->free();
282 }
283 }
284 }
285 }
286
287 foreach ($params[$blockName] as $count => $value) {
288 if (!is_array($value)) {
289 continue;
290 }
291 $contactFields = array(
292 'contact_id' => $contactId,
293 'location_type_id' => CRM_Utils_Array::value('location_type_id', $value),
294 );
295
296 //check for update
a7488080 297 if (empty($value['id']) &&
6a488035
TO
298 is_array($blockIds) && !empty($blockIds)
299 ) {
300 foreach ($blockIds as $blockId => $blockValue) {
301 if ($updateBlankLocInfo) {
a7488080 302 if (!empty($blockIds[$count])) {
6a488035
TO
303 $value['id'] = $blockIds[$count]['id'];
304 unset($blockIds[$count]);
305 }
306 }
307 else {
308 if ($blockValue['locationTypeId'] == CRM_Utils_Array::value('location_type_id', $value)) {
309 $valueId = FALSE;
310
311 if ($blockName == 'phone') {
312 $phoneTypeBlockValue = CRM_Utils_Array::value('phoneTypeId', $blockValue);
d5f1ee75 313 if ($phoneTypeBlockValue == CRM_Utils_Array::value('phone_type_id', $value)) {
6a488035
TO
314 $valueId = TRUE;
315 }
316 }
317 elseif ($blockName == 'im') {
318 $providerBlockValue = CRM_Utils_Array::value('providerId', $blockValue);
319 if ($providerBlockValue == $value['provider_id']) {
320 $valueId = TRUE;
321 }
322 }
323 else {
324 $valueId = TRUE;
325 }
326
327 if ($valueId) {
328 //assigned id as first come first serve basis
329 $value['id'] = $blockValue['id'];
8cc574cf 330 if (!$primaryId && !empty($blockValue['is_primary'])) {
6a488035
TO
331 $value['is_primary'] = $blockValue['is_primary'];
332 }
333 unset($blockIds[$blockId]);
334 break;
335 }
336 }
337 }
338 }
339 }
340
341 $dataExits = self::dataExists(self::$requiredBlockFields[$blockName], $value);
342
343 // Note there could be cases when block info already exist ($value[id] is set) for a contact/entity
344 // BUT info is not present at this time, and therefore we should be really careful when deleting the block.
345 // $updateBlankLocInfo will help take appropriate decision. CRM-5969
a7488080 346 if (!empty($value['id']) && !$dataExits && $updateBlankLocInfo) {
6a488035
TO
347 //delete the existing record
348 self::blockDelete($blockName, array('id' => $value['id']));
349 continue;
350 }
351 elseif (!$dataExits) {
352 continue;
353 }
354
8cc574cf 355 if ($isPrimary && !empty($value['is_primary'])) {
6a488035
TO
356 $contactFields['is_primary'] = $value['is_primary'];
357 $isPrimary = FALSE;
358 }
359 else {
360 $contactFields['is_primary'] = 0;
361 }
362
8cc574cf 363 if ($isBilling && !empty($value['is_billing'])) {
6a488035
TO
364 $contactFields['is_billing'] = $value['is_billing'];
365 $isBilling = FALSE;
366 }
367 else {
368 $contactFields['is_billing'] = 0;
369 }
370
371 $blockFields = array_merge($value, $contactFields);
293daac2 372 $baoString = 'CRM_Core_BAO_' . $name;
373 $blocks[] = $baoString::add( $blockFields );
6a488035
TO
374 }
375
376 // we need to delete blocks that were deleted during update
377 if ($updateBlankLocInfo && !empty($blockIds)) {
378 foreach ($blockIds as $deleteBlock) {
a7488080 379 if (empty($deleteBlock['id'])) {
6a488035
TO
380 continue;
381 }
382 self::blockDelete($blockName, array('id' => $deleteBlock['id']));
383 }
384 }
385
386 return $blocks;
387 }
388
389 /**
390 * Function to delete block
391 *
392 * @param string $blockName block name
393 * @param int $params associates array
394 *
395 * @return void
396 * @static
397 */
398 static function blockDelete($blockName, $params) {
399 $name = ucfirst($blockName);
400 if ($blockName == 'im') {
401 $name = 'IM';
402 }
403 elseif ($blockName == 'openid') {
404 $name = 'OpenID';
405 }
406
e4f5a5f9 407 $baoString = 'CRM_Core_DAO_' . $name;
408 $block = new $baoString( );
6a488035
TO
409
410 $block->copyValues($params);
411 /*
412 * CRM-11006 add call to pre and post hook for delete action
413 */
414 CRM_Utils_Hook::pre('delete', $name, $block->id, CRM_Core_DAO::$_nullArray);
415 $block->delete();
416 CRM_Utils_Hook::post('delete', $name, $block->id, $block);
417 }
418
419 /**
420 * Handling for is_primary.
421 * $params is_primary could be
422 * # 1 - find other entries with is_primary = 1 & reset them to 0
423 * # 0 - make sure at least one entry is set to 1
424 * - if no other entry is 1 change to 1
425 * - if one other entry exists change that to 1
426 * - if more than one other entry exists change first one to 1
77b97be7 427 * @fixme - perhaps should choose by location_type
6a488035
TO
428 * # empty - same as 0 as once we have checked first step
429 * we know if it should be 1 or 0
430 *
431 * if $params['id'] is set $params['contact_id'] may need to be retrieved
432 *
77b97be7
EM
433 * @param array $params
434 * @param $class
435 *
436 * @throws API_Exception
6a488035
TO
437 * @static
438 */
439 public static function handlePrimary(&$params, $class) {
37a77d9c
TO
440 $table = CRM_Core_DAO_AllCoreTables::getTableForClass($class);
441 if (!$table) {
442 throw new API_Exception("Failed to locate table for class [$class]");
443 }
d195b60c 444
50fa40e8
CW
445 // contact_id in params might be empty or the string 'null' so cast to integer
446 $contactId = (int) CRM_Utils_Array::value('contact_id', $params);
447 // If id is set & we haven't been passed a contact_id, retrieve it
448 if (!empty($params['id']) && !isset($params['contact_id'])) {
6a488035
TO
449 $entity = new $class();
450 $entity->id = $params['id'];
451 $entity->find(TRUE);
452 $contactId = $entity->contact_id;
453 }
50fa40e8
CW
454 // If entity is not associated with contact, concept of is_primary not relevant
455 if (!$contactId) {
6a488035
TO
456 return;
457 }
458
459 // if params is_primary then set all others to not be primary & exit out
a7488080 460 if (!empty($params['is_primary'])) {
6a488035
TO
461 $sql = "UPDATE $table SET is_primary = 0 WHERE contact_id = %1";
462 $sqlParams = array(1 => array($contactId, 'Integer'));
463 // we don't want to create unecessary entries in the log_ tables so exclude the one we are working on
464 if(!empty($params['id'])){
465 $sql .= " AND id <> %2";
466 $sqlParams[2] = array($params['id'], 'Integer');
467 }
468 CRM_Core_DAO::executeQuery($sql, $sqlParams);
469 return;
470 }
471
472 //Check what other emails exist for the contact
473 $existingEntities = new $class();
474 $existingEntities->contact_id = $contactId;
475 $existingEntities->orderBy('is_primary DESC');
476 if (!$existingEntities->find(TRUE) || (!empty($params['id']) && $existingEntities->id == $params['id'])) {
477 // ie. if no others is set to be primary then this has to be primary set to 1 so change
478 $params['is_primary'] = 1;
479 return;
480 }
481 else {
482 /*
483 * If the only existing email is the one we are editing then we must set
484 * is_primary to 1
485 * CRM-10451
486 */
487 if ( $existingEntities->N == 1 && $existingEntities->id == CRM_Utils_Array::value( 'id', $params ) ) {
488 $params['is_primary'] = 1;
489 return;
490 }
491
492 if ($existingEntities->is_primary == 1) {
493 return;
494 }
495 // so at this point we are only dealing with ones explicity setting is_primary to 0
496 // since we have reverse sorted by email we can either set the first one to
497 // primary or return if is already is
498 $existingEntities->is_primary = 1;
499 $existingEntities->save();
500 }
501 }
502
503 /**
504 * Sort location array so primary element is first
505 * @param Array $location
506 */
507 static function sortPrimaryFirst(&$locations){
508 uasort($locations, 'self::primaryComparison');
509 }
510
511/**
512 * compare 2 locations to see which should go first based on is_primary
513 * (sort function for sortPrimaryFirst)
514 * @param array $location1
515 * @param array_type $location2
516 * @return number
517 */
518 static function primaryComparison($location1, $location2){
519 $l1 = CRM_Utils_Array::value('is_primary', $location1);
520 $l2 = CRM_Utils_Array::value('is_primary', $location2);
521 if ($l1 == $l2) {
522 return 0;
523 }
524 return ($l1 < $l2) ? -1 : 1;
525 }
526}
527