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