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