Merge pull request #4898 from monishdeb/CRM-15619-fix
[civicrm-core.git] / CRM / Core / BAO / OptionValue.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 */
35 class CRM_Core_BAO_OptionValue extends CRM_Core_DAO_OptionValue {
36
37 /**
38 * Class constructor
39 */
40 public function __construct() {
41 parent::__construct();
42 }
43
44 /**
45 * Create option value - note that the create function calls 'add' but
46 * has more business logic
47 *
48 * @param array $params
49 * Input parameters.
50 *
51 * @return object
52 */
53 public static function create($params) {
54 if (empty($params['id'])) {
55 self::setDefaults($params);
56 }
57 $ids = array();
58 if (!empty($params['id'])) {
59 $ids = array('optionValue' => $params['id']);
60 }
61 return CRM_Core_BAO_OptionValue::add($params, $ids);
62 }
63
64 /**
65 * Set default Parameters
66 * This functions sets default parameters if not set:
67 * - name & label are set to each other as required (it might make more sense for one
68 * to be required but this would mean a change to the api level)
69 * - weight & value will be set to their respective option groups next values
70 * if nothing is passed in.
71 *
72 * Note this function does not check for presence of $params['id'] so should only be called
73 * if 'id' is not present
74 *
75 * @param array $params
76 */
77 public static function setDefaults(&$params) {
78 if (CRM_Utils_Array::value('label', $params, NULL) === NULL) {
79 $params['label'] = $params['name'];
80 }
81 if (CRM_Utils_Array::value('name', $params, NULL) === NULL) {
82 $params['name'] = $params['label'];
83 }
84 if (CRM_Utils_Array::value('weight', $params, NULL) === NULL) {
85 $params['weight'] = self::getDefaultWeight($params);
86 }
87 if (CRM_Utils_Array::value('value', $params, NULL) === NULL) {
88 $params['value'] = self::getDefaultValue($params);
89 }
90 }
91
92 /**
93 * Get next available value
94 * We will take the highest numeric value (or 0 if no numeric values exist)
95 * and add one. The calling function is responsible for any
96 * more complex decision making
97 *
98 * @param array $params
99 *
100 * @return int
101 */
102 public static function getDefaultWeight($params) {
103 return (int) CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue',
104 array('option_group_id' => $params['option_group_id']));
105 }
106
107 /**
108 * Get next available value
109 * We will take the highest numeric value (or 0 if no numeric values exist)
110 * and add one. The calling function is responsible for any
111 * more complex decision making
112 * @param array $params
113 */
114 public static function getDefaultValue($params) {
115 $bao = new CRM_Core_BAO_OptionValue();
116 $bao->option_group_id = $params['option_group_id'];
117 if (isset($params['domain_id'])) {
118 $bao->domain_id = $params['domain_id'];
119 }
120 $bao->selectAdd();
121 $bao->whereAdd("value REGEXP '^[0-9]+$'");
122 $bao->selectAdd('(ROUND(COALESCE(MAX(CONVERT(value, UNSIGNED)),0)) +1) as nextvalue');
123 $bao->find(TRUE);
124 return $bao->nextvalue;
125 }
126
127 /**
128 * Fetch object based on array of properties
129 *
130 * @param array $params
131 * (reference ) an assoc array of name/value pairs.
132 * @param array $defaults
133 * (reference ) an assoc array to hold the flattened values.
134 *
135 * @return CRM_Core_BAO_OptionValue
136 * @static
137 */
138 public static function retrieve(&$params, &$defaults) {
139 $optionValue = new CRM_Core_DAO_OptionValue();
140 $optionValue->copyValues($params);
141 if ($optionValue->find(TRUE)) {
142 CRM_Core_DAO::storeValues($optionValue, $defaults);
143 return $optionValue;
144 }
145 return NULL;
146 }
147
148 /**
149 * Update the is_active flag in the db
150 *
151 * @param int $id
152 * Id of the database record.
153 * @param bool $is_active
154 * Value we want to set the is_active field.
155 *
156 * @return Object
157 * DAO object on sucess, null otherwise
158 * @static
159 */
160 public static function setIsActive($id, $is_active) {
161 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_OptionValue', $id, 'is_active', $is_active);
162 }
163
164 /**
165 * Add an Option Value
166 *
167 * @param array $params
168 * Reference array contains the values submitted by the form.
169 * @param array $ids
170 * Reference array contains the id.
171 *
172 * @static
173 *
174 * @return CRM_Core_DAO_OptionValue
175 */
176 public static function add(&$params, &$ids) {
177 // CRM-10921: do not reset attributes to default if this is an update
178 //@todo consider if defaults are being set in the right place. 'dumb' defaults like
179 // these would be usefully set @ the api layer so they are visible to api users
180 // complex defaults like the domain id below would make sense in the setDefauls function
181 // but unclear what other ways this function is being used
182 if (empty($ids['optionValue'])) {
183 $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
184 $params['is_default'] = CRM_Utils_Array::value('is_default', $params, FALSE);
185 $params['is_optgroup'] = CRM_Utils_Array::value('is_optgroup', $params, FALSE);
186 $params['filter'] = CRM_Utils_Array::value('filter', $params, FALSE);
187 }
188
189 // action is taken depending upon the mode
190 $optionValue = new CRM_Core_DAO_OptionValue();
191 $optionValue->copyValues($params);
192
193 if (!empty($params['is_default'])) {
194 $query = 'UPDATE civicrm_option_value SET is_default = 0 WHERE option_group_id = %1';
195
196 // tweak default reset, and allow multiple default within group.
197 if ($resetDefaultFor = CRM_Utils_Array::value('reset_default_for', $params)) {
198 if (is_array($resetDefaultFor)) {
199 $colName = key($resetDefaultFor);
200 $colVal = $resetDefaultFor[$colName];
201 $query .= " AND ( $colName IN ( $colVal ) )";
202 }
203 }
204
205 $p = array(1 => array($params['option_group_id'], 'Integer'));
206 CRM_Core_DAO::executeQuery($query, $p);
207 }
208
209 // CRM-13814 : evalute option group id
210 if (!array_key_exists('option_group_id', $params) && !empty($ids['optionValue'])) {
211 $groupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue',
212 $ids['optionValue'], 'option_group_id', 'id'
213 );
214 }
215 else {
216 $groupId = $params['option_group_id'];
217 }
218
219 $groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
220 $groupId, 'name', 'id'
221 );
222 if (in_array($groupName, CRM_Core_OptionGroup::$_domainIDGroups)) {
223 $optionValue->domain_id = CRM_Utils_Array::value('domain_id', $params, CRM_Core_Config::domainID());
224 }
225
226 $optionValue->id = CRM_Utils_Array::value('optionValue', $ids);
227 $optionValue->save();
228 CRM_Core_PseudoConstant::flush();
229 return $optionValue;
230 }
231
232 /**
233 * Delete Option Value
234 *
235 * @param int $optionValueId
236 *
237 * @return boolean
238 *
239 * @static
240 */
241 public static function del($optionValueId) {
242 $optionValue = new CRM_Core_DAO_OptionValue();
243 $optionValue->id = $optionValueId;
244 if (self::updateRecords($optionValueId, CRM_Core_Action::DELETE)) {
245 CRM_Core_PseudoConstant::flush();
246 return $optionValue->delete();
247 }
248 return FALSE;
249 }
250
251 /**
252 * Retrieve activity type label and description
253 *
254 * @param int $activityTypeId
255 * Activity type id.
256 *
257 * @return array
258 * label and description
259 * @static
260 */
261 public static function getActivityTypeDetails($activityTypeId) {
262 $query = "SELECT civicrm_option_value.label, civicrm_option_value.description
263 FROM civicrm_option_value
264 LEFT JOIN civicrm_option_group ON ( civicrm_option_value.option_group_id = civicrm_option_group.id )
265 WHERE civicrm_option_group.name = 'activity_type'
266 AND civicrm_option_value.value = {$activityTypeId} ";
267
268 $dao = CRM_Core_DAO::executeQuery($query);
269
270 $dao->fetch();
271
272 return array($dao->label, $dao->description);
273 }
274
275 /**
276 * Get the Option Value title.
277 *
278 * @param int $id
279 * Id of Option Value.
280 *
281 * @return string
282 * title
283 *
284 * @static
285 */
286 public static function getTitle($id) {
287 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $id, 'label');
288 }
289
290 /**
291 * Updates contacts affected by the option value passed.
292 *
293 * @param int $optionValueId
294 * The option value id.
295 * @param int $action
296 * The action describing whether prefix/suffix was UPDATED or DELETED.
297 *
298 * @return bool
299 */
300 public static function updateRecords(&$optionValueId, $action) {
301 //finding group name
302 $optionValue = new CRM_Core_DAO_OptionValue();
303 $optionValue->id = $optionValueId;
304 $optionValue->find(TRUE);
305
306 $optionGroup = new CRM_Core_DAO_OptionGroup();
307 $optionGroup->id = $optionValue->option_group_id;
308 $optionGroup->find(TRUE);
309
310 // group name
311 $gName = $optionGroup->name;
312 // value
313 $value = $optionValue->value;
314
315 // get the proper group name & affected field name
316 // todo: this may no longer be needed for individuals - check inputs
317 $individuals = array(
318 'gender' => 'gender_id',
319 'individual_prefix' => 'prefix_id',
320 'individual_suffix' => 'suffix_id',
321 'communication_style' => 'communication_style_id',
322 // Not only Individuals -- but the code seems to be generic for all contact types, despite the naming...
323 );
324 $contributions = array('payment_instrument' => 'payment_instrument_id');
325 $activities = array('activity_type' => 'activity_type_id');
326 $participant = array('participant_role' => 'role_id');
327 $eventType = array('event_type' => 'event_type_id');
328 $aclRole = array('acl_role' => 'acl_role_id');
329
330 $all = array_merge($individuals, $contributions, $activities, $participant, $eventType, $aclRole);
331 $fieldName = '';
332
333 foreach ($all as $name => $id) {
334 if ($gName == $name) {
335 $fieldName = $id;
336 }
337 }
338 if ($fieldName == '') {
339 return TRUE;
340 }
341
342 if (array_key_exists($gName, $individuals)) {
343 $contactDAO = new CRM_Contact_DAO_Contact();
344
345 $contactDAO->$fieldName = $value;
346 $contactDAO->find();
347
348 while ($contactDAO->fetch()) {
349 if ($action == CRM_Core_Action::DELETE) {
350 $contact = new CRM_Contact_DAO_Contact();
351 $contact->id = $contactDAO->id;
352 $contact->find(TRUE);
353
354 // make sure dates doesn't get reset
355 $contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date);
356 $contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date);
357 $contact->$fieldName = 'NULL';
358 $contact->save();
359 }
360 }
361
362 return TRUE;
363 }
364
365 if (array_key_exists($gName, $contributions)) {
366 $contribution = new CRM_Contribute_DAO_Contribution();
367 $contribution->$fieldName = $value;
368 $contribution->find();
369 while ($contribution->fetch()) {
370 if ($action == CRM_Core_Action::DELETE) {
371 $contribution->$fieldName = 'NULL';
372 $contribution->save();
373 }
374 }
375 return TRUE;
376 }
377
378 if (array_key_exists($gName, $activities)) {
379 $activity = new CRM_Activity_DAO_Activity();
380 $activity->$fieldName = $value;
381 $activity->find();
382 while ($activity->fetch()) {
383 $activity->delete();
384 }
385 return TRUE;
386 }
387
388 //delete participant role, type and event type option value
389 if (array_key_exists($gName, $participant)) {
390 $participantValue = new CRM_Event_DAO_Participant();
391 $participantValue->$fieldName = $value;
392 if ($participantValue->find(TRUE)) {
393 return FALSE;
394 }
395 return TRUE;
396 }
397
398 //delete event type option value
399 if (array_key_exists($gName, $eventType)) {
400 $event = new CRM_Event_DAO_Event();
401 $event->$fieldName = $value;
402 if ($event->find(TRUE)) {
403 return FALSE;
404 }
405 return TRUE;
406 }
407
408 //delete acl_role option value
409 if (array_key_exists($gName, $aclRole)) {
410 $entityRole = new CRM_ACL_DAO_EntityRole();
411 $entityRole->$fieldName = $value;
412
413 $aclDAO = new CRM_ACL_DAO_ACL();
414 $aclDAO->entity_id = $value;
415 if ($entityRole->find(TRUE) || $aclDAO->find(TRUE)) {
416 return FALSE;
417 }
418 return TRUE;
419 }
420 }
421
422 /**
423 * Updates options values weights.
424 *
425 * @param int $opGroupId
426 * @param array $opWeights
427 * Options value , weight pair.
428 *
429 * @return void
430 * @static
431 */
432 public static function updateOptionWeights($opGroupId, $opWeights) {
433 if (!is_array($opWeights) || empty($opWeights)) {
434 return;
435 }
436
437 foreach ($opWeights as $opValue => $opWeight) {
438 $optionValue = new CRM_Core_DAO_OptionValue();
439 $optionValue->option_group_id = $opGroupId;
440 $optionValue->value = $opValue;
441 if ($optionValue->find(TRUE)) {
442 $optionValue->weight = $opWeight;
443 $optionValue->save();
444 }
445 $optionValue->free();
446 }
447 }
448
449 /**
450 * Get the values of all option values given an option group ID. Store in system cache
451 * Does not take any filtering arguments. The object is to avoid hitting the DB and retrieve
452 * from memory
453 *
454 * @param int $optionGroupID
455 * The option group for which we want the values from.
456 *
457 * @return array
458 * an array of array of values for this option group
459 * @static
460 */
461 public static function getOptionValuesArray($optionGroupID) {
462 // check if we can get the field values from the system cache
463 $cacheKey = "CRM_Core_BAO_OptionValue_OptionGroupID_{$optionGroupID}";
464 $cache = CRM_Utils_Cache::singleton();
465 $optionValues = $cache->get($cacheKey);
466 if (empty($optionValues)) {
467 $dao = new CRM_Core_DAO_OptionValue();
468 $dao->option_group_id = $optionGroupID;
469 $dao->orderBy('weight ASC, label ASC');
470 $dao->find();
471
472 $optionValues = array();
473 while ($dao->fetch()) {
474 $optionValues[$dao->id] = array();
475 CRM_Core_DAO::storeValues($dao, $optionValues[$dao->id]);
476 }
477
478 $cache->set($cacheKey, $optionValues);
479 }
480
481 return $optionValues;
482 }
483
484 /**
485 * Get the values of all option values given an option group ID as a key => value pair
486 * Use above cached function to make it super efficient
487 *
488 * @param int $optionGroupID
489 * The option group for which we want the values from.
490 *
491 * @return array
492 * an associative array of label, value pairs
493 * @static
494 */
495 public static function getOptionValuesAssocArray($optionGroupID) {
496 $optionValues = self::getOptionValuesArray($optionGroupID);
497
498 $options = array();
499 foreach ($optionValues as $id => $value) {
500 $options[$value['value']] = $value['label'];
501 }
502 return $options;
503 }
504
505 /**
506 * Get the values of all option values given an option group Name as a key => value pair
507 * Use above cached function to make it super efficient
508 *
509 * @param string $optionGroupName
510 * The option group name for which we want the values from.
511 *
512 * @return array
513 * an associative array of label, value pairs
514 * @static
515 */
516 public static function getOptionValuesAssocArrayFromName($optionGroupName) {
517 $dao = new CRM_Core_DAO_OptionGroup();
518 $dao->name = $optionGroupName;
519 $dao->selectAdd();
520 $dao->selectAdd('id');
521 $dao->find(TRUE);
522 $optionValues = self::getOptionValuesArray($dao->id);
523
524 $options = array();
525 foreach ($optionValues as $id => $value) {
526 $options[$value['value']] = $value['label'];
527 }
528 return $options;
529 }
530
531 }