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