Merge pull request #3813 from NileemaJadhav/CRM-master
[civicrm-core.git] / CRM / Core / BAO / CustomField.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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
36 /**
37 * Business objects for managing custom data fields.
38 *
39 */
40 class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
41
42 /**
43 * Array for valid combinations of data_type & descriptions
44 *
45 * @var array
46 * @static
47 */
48 public static $_dataType = NULL;
49
50 /**
51 * Array for valid combinations of data_type & html_type
52 *
53 * @var array
54 * @static
55 */
56 public static $_dataToHtml = NULL;
57
58 /**
59 * Array to hold (formatted) fields for import
60 *
61 * @var array
62 * @static
63 */
64 public static $_importFields = NULL;
65
66 /**
67 * Build and retrieve the list of data types and descriptions
68 *
69 * @param NULL
70 *
71 * @return array Data type => Description
72 * @access public
73 * @static
74 */
75 static function &dataType() {
76 if (!(self::$_dataType)) {
77 self::$_dataType = array(
78 'String' => ts('Alphanumeric'),
79 'Int' => ts('Integer'),
80 'Float' => ts('Number'),
81 'Money' => ts('Money'),
82 'Memo' => ts('Note'),
83 'Date' => ts('Date'),
84 'Boolean' => ts('Yes or No'),
85 'StateProvince' => ts('State/Province'),
86 'Country' => ts('Country'),
87 'File' => ts('File'),
88 'Link' => ts('Link'),
89 'ContactReference' => ts('Contact Reference'),
90 );
91 }
92 return self::$_dataType;
93 }
94
95 /**
96 * @return array
97 */
98 static function dataToHtml() {
99 if (!self::$_dataToHtml) {
100 self::$_dataToHtml = array(
101 array(
102 'Text' => 'Text', 'Select' => 'Select',
103 'Radio' => 'Radio', 'CheckBox' => 'CheckBox',
104 'Multi-Select' => 'Multi-Select',
105 'AdvMulti-Select' => 'AdvMulti-Select',
106 'Autocomplete-Select' => 'Autocomplete-Select',
107 ),
108 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
109 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
110 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
111 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
112 array('Date' => 'Select Date'),
113 array('Radio' => 'Radio'),
114 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
115 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
116 array('File' => 'File'),
117 array('Link' => 'Link'),
118 array('ContactReference' => 'Autocomplete-Select'),
119 );
120 }
121 return self::$_dataToHtml;
122 }
123
124 /**
125 * takes an associative array and creates a custom field object
126 *
127 * This function is invoked from within the web form layer and also from the api layer
128 *
129 * @param array $params (reference) an assoc array of name/value pairs
130 *
131 * @return CRM_Core_DAO_CustomField object
132 * @access public
133 * @static
134 */
135 static function create(&$params) {
136 $origParams = array_merge(array(), $params);
137
138 if (!isset($params['id'])) {
139 if (!isset($params['column_name'])) {
140 // if add mode & column_name not present, calculate it.
141 $params['column_name'] = strtolower(CRM_Utils_String::munge($params['label'], '_', 32));
142 }
143 if (!isset($params['name'])) {
144 $params['name'] = CRM_Utils_String::munge($params['label'], '_', 64);
145 }
146 }
147 else {
148 $params['column_name'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
149 $params['id'],
150 'column_name'
151 );
152 }
153 $columnName = $params['column_name'];
154
155 $indexExist = FALSE;
156 //as during create if field is_searchable we had created index.
157 if (!empty($params['id'])) {
158 $indexExist = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
159 }
160
161 switch (CRM_Utils_Array::value('html_type', $params)){
162 case 'Select Date':
163 if(empty($params['date_format'])){
164 $config = CRM_Core_Config::singleton();
165 $params['date_format'] = $config->dateInputFormat;
166 }
167 break;
168 case 'CheckBox':
169 case 'AdvMulti-Select':
170 case 'Multi-Select':
171 if (isset($params['default_checkbox_option'])) {
172 $tempArray = array_keys($params['default_checkbox_option']);
173 $defaultArray = array();
174 foreach ($tempArray as $k => $v) {
175 if ($params['option_value'][$v]) {
176 $defaultArray[] = $params['option_value'][$v];
177 }
178 }
179
180 if (!empty($defaultArray)) {
181 // also add the seperator before and after the value per new conventio (CRM-1604)
182 $params['default_value'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $defaultArray) . CRM_Core_DAO::VALUE_SEPARATOR;
183 }
184 }
185 else {
186 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
187 ) {
188 $params['default_value'] = $params['option_value'][$params['default_option']];
189 }
190 }
191 break;
192 }
193
194 $transaction = new CRM_Core_Transaction();
195 // create any option group & values if required
196 if ($params['html_type'] != 'Text' &&
197 in_array($params['data_type'], array(
198 'String', 'Int', 'Float', 'Money'))
199 ) {
200
201 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
202 $params['custom_group_id'],
203 'table_name'
204 );
205
206
207 if ($params['option_type'] == 1) {
208 // first create an option group for this custom group
209 $optionGroup = new CRM_Core_DAO_OptionGroup();
210 $optionGroup->name = "{$columnName}_" . date('YmdHis');
211 $optionGroup->title = $params['label'];
212 $optionGroup->is_active = 1;
213 $optionGroup->save();
214 $params['option_group_id'] = $optionGroup->id;
215 if(!empty($params['option_value']) && is_array($params['option_value'])){
216 foreach ($params['option_value'] as $k => $v) {
217 if (strlen(trim($v))) {
218 $optionValue = new CRM_Core_DAO_OptionValue();
219 $optionValue->option_group_id = $optionGroup->id;
220 $optionValue->label = $params['option_label'][$k];
221 $optionValue->name = CRM_Utils_String::titleToVar($params['option_label'][$k]);
222 switch ($params['data_type']) {
223 case 'Money':
224 $optionValue->value = CRM_Utils_Rule::cleanMoney($v);
225 break;
226
227 case 'Int':
228 $optionValue->value = intval($v);
229 break;
230
231 case 'Float':
232 $optionValue->value = floatval($v);
233 break;
234
235 default:
236 $optionValue->value = trim($v);
237 }
238
239 $optionValue->weight = $params['option_weight'][$k];
240 $optionValue->is_active = CRM_Utils_Array::value($k, $params['option_status'], FALSE);
241 $optionValue->save();
242 }
243 }
244 }
245 }
246 }
247
248 // check for orphan option groups
249 if (!empty($params['option_group_id'])) {
250 if (!empty($params['id'])) {
251 self::fixOptionGroups($params['id'], $params['option_group_id']);
252 }
253
254 // if we dont have a default value
255 // retrive it from one of the other custom fields which use this option group
256 if (empty($params['default_value'])) {
257 //don't insert only value separator as default value, CRM-4579
258 $defaultValue = self::getOptionGroupDefault($params['option_group_id'],
259 $params['html_type']
260 );
261
262 if (!CRM_Utils_System::isNull(explode(CRM_Core_DAO::VALUE_SEPARATOR,
263 $defaultValue
264 ))) {
265 $params['default_value'] = $defaultValue;
266 }
267 }
268 }
269
270 // since we need to save option group id :)
271 if (!isset($params['attributes']) && strtolower($params['html_type']) == 'textarea') {
272 $params['attributes'] = 'rows=4, cols=60';
273 }
274
275 $customField = new CRM_Core_DAO_CustomField();
276 $customField->copyValues($params);
277 $customField->is_required = CRM_Utils_Array::value('is_required', $params, FALSE);
278 $customField->is_searchable = CRM_Utils_Array::value('is_searchable', $params, FALSE);
279 $customField->in_selector = CRM_Utils_Array::value('in_selector', $params, FALSE);
280 $customField->is_search_range = CRM_Utils_Array::value('is_search_range', $params, FALSE);
281 $customField->is_active = CRM_Utils_Array::value('is_active', $params, FALSE);
282 $customField->is_view = CRM_Utils_Array::value('is_view', $params, FALSE);
283 $customField->save();
284
285 // make sure all values are present in the object for further processing
286 $customField->find(TRUE);
287
288 $triggerRebuild = CRM_Utils_Array::value('triggerRebuild', $params, TRUE);
289 //create/drop the index when we toggle the is_searchable flag
290 if (!empty($params['id'])) {
291 self::createField($customField, 'modify', $indexExist, $triggerRebuild);
292 }
293 else {
294 if (!isset($origParams['column_name'])) {
295 $columnName .= "_{$customField->id}";
296 $params['column_name'] = $columnName;
297 }
298 $customField->column_name = $columnName;
299 $customField->save();
300 // make sure all values are present in the object
301 $customField->find(TRUE);
302
303 $indexExist = FALSE;
304 self::createField($customField, 'add', $indexExist, $triggerRebuild);
305 }
306
307 // complete transaction
308 $transaction->commit();
309
310 CRM_Utils_System::flushCache();
311
312 return $customField;
313 }
314
315 /**
316 * Takes a bunch of params that are needed to match certain criteria and
317 * retrieves the relevant objects. Typically the valid params are only
318 * contact_id. We'll tweak this function to be more full featured over a period
319 * of time. This is the inverse function of create. It also stores all the retrieved
320 * values in the default array
321 *
322 * @param array $params (reference ) an assoc array of name/value pairs
323 * @param array $defaults (reference ) an assoc array to hold the flattened values
324 *
325 * @return object CRM_Core_DAO_CustomField object
326 * @access public
327 * @static
328 */
329 static function retrieve(&$params, &$defaults) {
330 return CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
331 }
332
333 /**
334 * update the is_active flag in the db
335 *
336 * @param int $id Id of the database record
337 * @param boolean $is_active Value we want to set the is_active field
338 *
339 * @return Object DAO object on sucess, null otherwise
340 *
341 * @access public
342 * @static
343 */
344 static function setIsActive($id, $is_active) {
345
346 CRM_Utils_System::flushCache();
347
348 //enable-disable CustomField
349 CRM_Core_BAO_UFField::setUFField($id, $is_active);
350 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
351 }
352
353 /**
354 * Get the field title.
355 *
356 * @param int $id id of field.
357 *
358 * @return string name
359 *
360 * @access public
361 * @static
362 *
363 */
364 public static function getTitle($id) {
365 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
366 }
367
368 /**
369 * Store and return an array of all active custom fields.
370 *
371 * @param string $customDataType type of Custom Data; empty is a synonym for "all contact data types"
372 * @param boolean $showAll If true returns all fields (includes disabled fields)
373 * @param boolean $inline If true returns all inline fields (includes disabled fields)
374 * @param int $customDataSubType Custom Data sub type value
375 * @param int $customDataSubName Custom Data sub name value
376 * @param boolean $onlyParent return only top level custom data, for eg, only Participant and ignore subname and subtype
377 * @param boolean $onlySubType return only custom data for subtype
378 * @param boolean $checkPermission if false, do not include permissioning clause
379 *
380 * @return array $fields - an array of active custom fields.
381 *
382 * @access public
383 * @static
384 */
385 public static function &getFields($customDataType = 'Individual',
386 $showAll = FALSE,
387 $inline = FALSE,
388 $customDataSubType = NULL,
389 $customDataSubName = NULL,
390 $onlyParent = FALSE,
391 $onlySubType = FALSE,
392 $checkPermission = TRUE
393 ) {
394 if (empty($customDataType)) {
395 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
396 }
397 if ($customDataType && !is_array($customDataType)) {
398
399 if (in_array($customDataType, CRM_Contact_BAO_ContactType::subTypes())) {
400 // This is the case when getFieldsForImport() requires fields
401 // limited strictly to a subtype.
402 $customDataSubType = $customDataType;
403 $customDataType = CRM_Contact_BAO_ContactType::getBasicType($customDataType);
404 $onlySubType = TRUE;
405 }
406
407 if (in_array($customDataType, array_keys(CRM_Core_SelectValues::customGroupExtends()))) {
408 // this makes the method flexible to support retrieving fields
409 // for multiple extends value.
410 $customDataType = array($customDataType);
411 }
412 }
413
414 if ($customDataSubType && !is_array($customDataSubType)) {
415 $customDataSubType = explode(CRM_Core_DAO::VALUE_SEPARATOR,
416 trim($customDataSubType, CRM_Core_DAO::VALUE_SEPARATOR)
417 );
418 }
419
420 if (is_array($customDataType)) {
421 $cacheKey = implode('_', $customDataType);
422 }
423 else {
424 $cacheKey = $customDataType;
425 }
426
427 $cacheKey .= !empty($customDataSubType) ? ('_' . implode('_', $customDataSubType)) : '_0';
428 $cacheKey .= $customDataSubName ? "{$customDataSubName}_" : '_0';
429 $cacheKey .= $showAll ? '_1' : '_0';
430 $cacheKey .= $inline ? '_1_' : '_0_';
431 $cacheKey .= $onlyParent ? '_1_' : '_0_';
432 $cacheKey .= $onlySubType ? '_1_' : '_0_';
433 $cacheKey .= $checkPermission ? '_1_' : '_0_';
434
435 $cgTable = CRM_Core_DAO_CustomGroup::getTableName();
436
437 // also get the permission stuff here
438 if ($checkPermission) {
439 $permissionClause = CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
440 "{$cgTable}."
441 );
442 }
443 else {
444 $permissionClause = '(1)';
445 }
446
447 // lets md5 permission clause and take first 8 characters
448 $cacheKey .= substr(md5($permissionClause), 0, 8);
449
450 if (strlen($cacheKey) > 40) {
451 $cacheKey = md5($cacheKey);
452 }
453
454 if (!self::$_importFields ||
455 CRM_Utils_Array::value($cacheKey, self::$_importFields) === NULL
456 ) {
457 if (!self::$_importFields) {
458 self::$_importFields = array();
459 }
460
461 // check if we can retrieve from database cache
462 $fields = CRM_Core_BAO_Cache::getItem('contact fields', "custom importableFields $cacheKey");
463
464 if ($fields === NULL) {
465 $cfTable = self::getTableName();
466
467 $extends = '';
468 if (is_array($customDataType)) {
469 $value = NULL;
470 foreach ($customDataType as $dataType) {
471 if (in_array($dataType, array_keys(CRM_Core_SelectValues::customGroupExtends()))) {
472 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
473 $val = "'" . CRM_Utils_Type::escape($dataType, 'String') . "', 'Contact' ";
474 }
475 else {
476 $val = "'" . CRM_Utils_Type::escape($dataType, 'String') . "'";
477 }
478 $value = $value ? $value . ", {$val}" : $val;
479 }
480 }
481 if ($value) {
482 $extends = "AND $cgTable.extends IN ( $value ) ";
483 }
484 }
485
486 if (!empty($customDataType) && empty($extends)) {
487 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
488 self::$_importFields[$cacheKey] = array();
489 return self::$_importFields[$cacheKey];
490 }
491
492 if ($onlyParent) {
493 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
494 }
495
496 $query = "SELECT $cfTable.id, $cfTable.label,
497 $cgTable.title,
498 $cfTable.data_type,
499 $cfTable.html_type,
500 $cfTable.default_value,
501 $cfTable.options_per_line, $cfTable.text_length,
502 $cfTable.custom_group_id,
503 $cfTable.is_required,
504 $cgTable.extends, $cfTable.is_search_range,
505 $cgTable.extends_entity_column_value,
506 $cgTable.extends_entity_column_id,
507 $cfTable.is_view,
508 $cfTable.option_group_id,
509 $cfTable.date_format,
510 $cfTable.time_format,
511 $cgTable.is_multiple
512 FROM $cfTable
513 INNER JOIN $cgTable
514 ON $cfTable.custom_group_id = $cgTable.id
515 WHERE ( 1 ) ";
516
517 if (!$showAll) {
518 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
519 }
520
521 if ($inline) {
522 $query .= " AND $cgTable.style = 'Inline' ";
523 }
524
525 //get the custom fields for specific type in
526 //combination with fields those support any type.
527 if (!empty($customDataSubType)) {
528 $subtypeClause = array();
529 foreach ($customDataSubType as $subtype) {
530 $subtype = CRM_Core_DAO::VALUE_SEPARATOR . $subtype . CRM_Core_DAO::VALUE_SEPARATOR;
531 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
532 }
533 if (!$onlySubType) {
534 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
535 }
536 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
537 }
538
539 if ($customDataSubName) {
540 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
541 }
542
543 // also get the permission stuff here
544 if ($checkPermission) {
545 $permissionClause = CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
546 "{$cgTable}.", TRUE
547 );
548 }
549 else {
550 $permissionClause = '(1)';
551 }
552
553 $query .= " $extends AND $permissionClause
554 ORDER BY $cgTable.weight, $cgTable.title,
555 $cfTable.weight, $cfTable.label";
556
557 $dao = CRM_Core_DAO::executeQuery($query);
558
559 $fields = array();
560 while (($dao->fetch()) != NULL) {
561 $fields[$dao->id]['label'] = $dao->label;
562 $fields[$dao->id]['groupTitle'] = $dao->title;
563 $fields[$dao->id]['data_type'] = $dao->data_type;
564 $fields[$dao->id]['html_type'] = $dao->html_type;
565 $fields[$dao->id]['default_value'] = $dao->default_value;
566 $fields[$dao->id]['text_length'] = $dao->text_length;
567 $fields[$dao->id]['options_per_line'] = $dao->options_per_line;
568 $fields[$dao->id]['custom_group_id'] = $dao->custom_group_id;
569 $fields[$dao->id]['extends'] = $dao->extends;
570 $fields[$dao->id]['is_search_range'] = $dao->is_search_range;
571 $fields[$dao->id]['extends_entity_column_value'] = $dao->extends_entity_column_value;
572 $fields[$dao->id]['extends_entity_column_id'] = $dao->extends_entity_column_id;
573 $fields[$dao->id]['is_view'] = $dao->is_view;
574 $fields[$dao->id]['is_multiple'] = $dao->is_multiple;
575 $fields[$dao->id]['option_group_id'] = $dao->option_group_id;
576 $fields[$dao->id]['date_format'] = $dao->date_format;
577 $fields[$dao->id]['time_format'] = $dao->time_format;
578 $fields[$dao->id]['is_required'] = $dao->is_required;
579 }
580
581 CRM_Core_BAO_Cache::setItem($fields,
582 'contact fields',
583 "custom importableFields $cacheKey"
584 );
585 }
586 self::$_importFields[$cacheKey] = $fields;
587 }
588
589 return self::$_importFields[$cacheKey];
590 }
591
592 /**
593 * Return the field ids and names (with groups) for import purpose.
594 *
595 * @param int|string $contactType Contact type
596 * @param boolean $showAll If true returns all fields (includes disabled fields)
597 * @param boolean $onlyParent return fields ONLY related to basic types
598 * @param boolean $search when called from search and multiple records need to be returned
599 * @param boolean $checkPermission if false, do not include permissioning clause
600 *
601 * @param bool $withMultiple
602 *
603 * @return array $fields -
604 *
605 * @access public
606 * @static
607 */
608 public static function &getFieldsForImport($contactType = 'Individual',
609 $showAll = FALSE,
610 $onlyParent = FALSE,
611 $search = FALSE,
612 $checkPermission = TRUE,
613 $withMultiple = FALSE
614 ) {
615 // Note: there are situations when we want getFieldsForImport() return fields related
616 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
617 $fields = &self::getFields($contactType,
618 $showAll,
619 FALSE,
620 NULL,
621 NULL,
622 $onlyParent,
623 FALSE,
624 $checkPermission
625 );
626
627 $importableFields = array();
628 foreach ($fields as $id => $values) {
629 // for now we should not allow multiple fields in profile / export etc, hence unsetting
630 if (!$search &&
631 (!empty($values['is_multiple']) && !$withMultiple)
632 ) {
633 continue;
634 }
635
636 /* generate the key for the fields array */
637
638 $key = "custom_$id";
639
640 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array::value(0, $values));
641 $importableFields[$key] = array(
642 'name' => $key,
643 'title' => CRM_Utils_Array::value('label', $values),
644 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
645 'import' => 1,
646 'custom_field_id' => $id,
647 'options_per_line' => CRM_Utils_Array::value('options_per_line', $values),
648 'text_length' => CRM_Utils_Array::value('text_length', $values, 255),
649 'data_type' => CRM_Utils_Array::value('data_type', $values),
650 'html_type' => CRM_Utils_Array::value('html_type', $values),
651 'is_search_range' => CRM_Utils_Array::value('is_search_range', $values),
652 );
653
654 // CRM-6681, pass date and time format when html_type = Select Date
655 if (CRM_Utils_Array::value('html_type', $values) == 'Select Date') {
656 $importableFields[$key]['date_format'] = CRM_Utils_Array::value('date_format', $values);
657 $importableFields[$key]['time_format'] = CRM_Utils_Array::value('time_format', $values);
658 }
659 }
660
661 return $importableFields;
662 }
663
664 /**
665 * Get the field id from an import key
666 *
667 * @param string $key The key to parse
668 *
669 * @param bool $all
670 * @return int|null The id (if exists)
671 * @access public
672 * @static
673 */
674 public static function getKeyID($key, $all = FALSE) {
675 $match = array();
676 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
677 if (!$all) {
678 return $match[1];
679 }
680 else {
681 return array(
682 $match[1],
683 CRM_Utils_Array::value(2, $match),
684 );
685 }
686 }
687 return $all ? array(
688 NULL, NULL) : NULL;
689 }
690
691 /**
692 * Use the cache to get all values of a specific custom field
693 *
694 * @param int $fieldID the custom field ID
695 *
696 * @return CRM_Core_DAO_CustomField $field the field object
697 * @static
698 * public
699 */
700 static function getFieldObject($fieldID) {
701 $field = new CRM_Core_DAO_CustomField();
702
703 // check if we can get the field values from the system cache
704 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
705 $cache = CRM_Utils_Cache::singleton();
706 $fieldValues = $cache->get($cacheKey);
707 if (empty($fieldValues)) {
708 $field->id = $fieldID;
709 if (!$field->find(TRUE)) {
710 CRM_Core_Error::fatal();
711 }
712
713 $fieldValues = array();
714 CRM_Core_DAO::storeValues($field, $fieldValues);
715
716 $cache->set($cacheKey, $fieldValues);
717 }
718 else {
719 $field->copyValues($fieldValues);
720 }
721
722 return $field;
723 }
724
725 /**
726 * This function for building custom fields
727 *
728 * @param CRM_Core_Form $qf form object (reference)
729 * @param string $elementName name of the custom field
730 * @param $fieldId
731 * @param boolean $inactiveNeeded -deprecated
732 * @param bool $useRequired
733 * @param boolean $search true if used for search else false
734 * @param string $label label for custom field
735 *
736 * @internal param bool $userRequired true if required else false
737 * @access public
738 * @static
739 */
740 public static function addQuickFormElement(&$qf,
741 $elementName,
742 $fieldId,
743 $inactiveNeeded = FALSE,
744 $useRequired = TRUE,
745 $search = FALSE,
746 $label = NULL
747 ) {
748 $field = self::getFieldObject($fieldId);
749 $widget = $field->html_type;
750
751 // Custom field HTML should indicate group+field name
752 $groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id);
753 $dataCrmCustomVal = $groupName.':'.$field->name;
754 $dataCrmCustomAttr = 'data-crm-custom="'.$dataCrmCustomVal.'"';
755 $field->attributes .= $dataCrmCustomAttr;
756
757 // Fixed for Issue CRM-2183
758 if ($widget == 'TextArea' && $search) {
759 $widget = 'Text';
760 }
761
762 if ($widget == 'Select State/Province' || $widget == 'Select Country') {
763 $qf->_stateCountryMap[$widget == 'Select Country' ? 'country' : 'state_province'][] = $elementName;
764 }
765
766 $placeholder = $search ? ts('- any -') : ($useRequired ? ts('- select -') : ts('- none -'));
767
768 // FIXME: Why are select state/country separate widget types?
769 $isSelect = (in_array($widget, array('Select', 'Multi-Select', 'Select State/Province', 'Multi-Select State/Province', 'Select Country', 'Multi-Select Country', 'AdvMulti-Select', 'CheckBox', 'Radio')));
770
771 if ($isSelect) {
772 $options = CRM_Utils_Array::value('values', civicrm_api3('contact', 'getoptions', array('field' => "custom_$fieldId", 'context' => $search ? 'search' : 'create'), array()));
773
774 // Consolidate widget types to simplify the below switch statement
775 if ($search || ($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
776 $widget = 'Select';
777 }
778 $selectAttributes = array(
779 'data-crm-custom' => $dataCrmCustomVal,
780 'class' => 'crm-select2',
781 );
782 // Search field is always multi-select
783 if ($search || strpos($field->html_type, 'Multi') !== FALSE) {
784 $selectAttributes['class'] .= ' huge';
785 $selectAttributes['multiple'] = 'multiple';
786 $selectAttributes['placeholder'] = $placeholder;
787 }
788 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
789 if ($field->option_group_id && !$search && $widget == 'Select' && CRM_Core_Permission::check('administer CiviCRM')) {
790 $selectAttributes += array(
791 'data-api-entity' => 'contact', // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
792 'data-api-field' => 'custom_' . $field->id,
793 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id),
794 );
795 }
796 }
797
798 if (!isset($label)) {
799 $label = $field->label;
800 }
801
802 /**
803 * at some point in time we might want to split the below into small functions
804 **/
805
806 switch ($widget) {
807 case 'Text':
808 case 'Link':
809 if ($field->is_search_range && $search) {
810 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes);
811 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes);
812 }
813 else {
814 $element = &$qf->add('text', $elementName, $label,
815 $field->attributes,
816 $useRequired && !$search
817 );
818 }
819 break;
820
821 case 'TextArea':
822 $attributes = $dataCrmCustomAttr;
823 if ($field->note_rows) {
824 $attributes .= 'rows=' . $field->note_rows;
825 }
826 else {
827 $attributes .= 'rows=4';
828 }
829 if ($field->note_columns) {
830 $attributes .= ' cols=' . $field->note_columns;
831 }
832 else {
833 $attributes .= ' cols=60';
834 }
835 if ($field->text_length) {
836 $attributes .= ' maxlength=' . $field->text_length;
837 }
838 $element = &$qf->add('textarea',
839 $elementName,
840 $label,
841 $attributes,
842 $useRequired && !$search
843 );
844 break;
845
846 case 'Select Date':
847 if ($field->is_search_range && $search) {
848 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
849 array(
850 'format' => $field->date_format,
851 'timeFormat' => $field->time_format,
852 'startOffset' => $field->start_date_years,
853 'endOffset' => $field->end_date_years,
854 'data-crm-custom' => $dataCrmCustomVal,
855 )
856 );
857
858 $qf->addDate($elementName . '_to', ts('To'), FALSE,
859 array(
860 'format' => $field->date_format,
861 'timeFormat' => $field->time_format,
862 'startOffset' => $field->start_date_years,
863 'endOffset' => $field->end_date_years,
864 'data-crm-custom' => $dataCrmCustomVal,
865 )
866 );
867 }
868 else {
869 $required = $useRequired && !$search;
870
871 $qf->addDate($elementName, $label, $required, array(
872 'format' => $field->date_format,
873 'timeFormat' => $field->time_format,
874 'startOffset' => $field->start_date_years,
875 'endOffset' => $field->end_date_years,
876 'data-crm-custom' => $dataCrmCustomVal,
877 ));
878 }
879 break;
880
881 case 'Radio':
882 $choice = array();
883 foreach ($options as $v => $l) {
884 $choice[] = $qf->createElement('radio', NULL, '', $l, (string)$v, $field->attributes);
885 }
886 $group = $qf->addGroup($choice, $elementName, $label);
887 if ($useRequired && !$search) {
888 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
889 }
890 else {
891 $group->setAttribute('allowClear', TRUE);
892 }
893 break;
894
895 // For all select elements
896 case 'Select':
897 if (empty($selectAttributes['multiple'])) {
898 $options = array('' => $placeholder) + $options;
899 }
900 $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
901
902 // Add and/or option for fields that store multiple values
903 if ($search && self::isSerialized($field)) {
904
905 $operators = array(
906 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
907 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
908 );
909 $qf->addGroup($operators, $elementName . '_operator');
910 $qf->setDefaults(array($elementName . '_operator' => 'or'));
911 }
912 break;
913
914 case 'AdvMulti-Select':
915 $include =& $qf->addElement(
916 'advmultiselect',
917 $elementName,
918 $label, $options,
919 array(
920 'size' => 5,
921 'style' => '',
922 'class' => 'advmultiselect',
923 'data-crm-custom' => $dataCrmCustomVal,
924 )
925 );
926
927 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
928 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
929
930 if ($useRequired && !$search) {
931 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
932 }
933 break;
934
935 case 'CheckBox':
936 $check = array();
937 foreach ($options as $v => $l) {
938 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
939 }
940 $qf->addGroup($check, $elementName, $label);
941 if ($useRequired && !$search) {
942 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
943 }
944 break;
945
946 case 'File':
947 // we should not build upload file in search mode
948 if ($search) {
949 return;
950 }
951 $qf->add(
952 strtolower($field->html_type),
953 $elementName,
954 $label,
955 $field->attributes,
956 $useRequired && !$search
957 );
958 $qf->addUploadElement($elementName);
959 break;
960
961 case 'RichTextEditor':
962 $attributes = array('rows' => $field->note_rows, 'cols' => $field->note_columns, 'data-crm-custom' => $dataCrmCustomVal);
963 if ($field->text_length) {
964 $attributes['maxlength'] = $field->text_length;
965 }
966 $qf->addWysiwyg($elementName, $label, $attributes, $search);
967 break;
968
969 case 'Autocomplete-Select':
970 static $customUrls = array();
971 // Fixme: why is this a string in the first place??
972 $attributes = array();
973 if ($field->attributes) {
974 foreach(explode(' ', $field->attributes) as $at) {
975 if (strpos($at, '=')) {
976 list($k, $v) = explode('=', $at);
977 $attributes[$k] = trim($v, ' "');
978 }
979 }
980 }
981 if ($field->data_type == 'ContactReference') {
982 $attributes['class'] = (isset($attributes['class']) ? $attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
983 $attributes['data-api-entity'] = 'contact';
984 $qf->add('text', $elementName, $label, $attributes,
985 $useRequired && !$search
986 );
987
988 $urlParams = "context=customfield&id={$field->id}";
989
990 $customUrls[$elementName] = CRM_Utils_System::url('civicrm/ajax/contactref',
991 $urlParams,
992 FALSE, NULL, FALSE
993 );
994
995 }
996 else {
997 // FIXME: This won't work with customFieldOptions hook
998 $attributes += array(
999 'entity' => 'option_value',
1000 'placeholder' => $placeholder,
1001 'multiple' => $search,
1002 'api' => array(
1003 'params' => array('option_group_id' => $field->option_group_id),
1004 ),
1005 );
1006 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1007 }
1008
1009 $qf->assign('customUrls', $customUrls);
1010 break;
1011 }
1012
1013 switch ($field->data_type) {
1014 case 'Int':
1015 // integers will have numeric rule applied to them.
1016 if ($field->is_search_range && $search) {
1017 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1018 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1019 }
1020 elseif ($widget == 'Text') {
1021 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1022 }
1023 break;
1024
1025 case 'Float':
1026 if ($field->is_search_range && $search) {
1027 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1028 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1029 }
1030 elseif ($widget == 'Text') {
1031 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1032 }
1033 break;
1034
1035 case 'Money':
1036 if ($field->is_search_range && $search) {
1037 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1038 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1039 }
1040 elseif ($widget == 'Text') {
1041 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1042 }
1043 break;
1044
1045 case 'Link':
1046 $element->setAttribute('onfocus', "if (!this.value) {this.value='http://';}");
1047 $element->setAttribute('onblur', "if (this.value == 'http://') {this.value='';}");
1048 $element->setAttribute('class', "url");
1049 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1050 break;
1051 }
1052 if ($field->is_view && !$search) {
1053 $qf->freeze($elementName);
1054 }
1055 }
1056
1057 /**
1058 * Delete the Custom Field.
1059 *
1060 * @param object $field - the field object
1061 *
1062 * @return boolean
1063 *
1064 * @access public
1065 * @static
1066 *
1067 */
1068 public static function deleteField($field) {
1069 CRM_Utils_System::flushCache();
1070
1071 // first delete the custom option group and values associated with this field
1072 if ($field->option_group_id) {
1073 //check if option group is related to any other field, if
1074 //not delete the option group and related option values
1075 self::checkOptionGroup($field->option_group_id);
1076 }
1077
1078 // next drop the column from the custom value table
1079 self::createField($field, 'delete');
1080
1081 $field->delete();
1082 CRM_Core_BAO_UFField::delUFField($field->id);
1083 CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1084
1085 return;
1086 }
1087
1088 /**
1089 * Given a custom field value, its id and the set of options
1090 * find the display value for this field
1091 *
1092 * @param mixed $value the custom field value
1093 * @param int $id the custom field id
1094 * @param int $options the assoc array of option name/value pairs
1095 *
1096 * @param null $contactID
1097 * @param null $fieldID
1098 *
1099 * @return string the display value
1100 *
1101 * @static
1102 * @access public
1103 */
1104 static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1105 $option = &$options[$id];
1106 $attributes = &$option['attributes'];
1107 $html_type = $attributes['html_type'];
1108 $data_type = $attributes['data_type'];
1109 $format = CRM_Utils_Array::value('format', $attributes);
1110
1111 return self::getDisplayValueCommon($value,
1112 $option,
1113 $html_type,
1114 $data_type,
1115 $format,
1116 $contactID,
1117 $fieldID
1118 );
1119 }
1120
1121 /**
1122 * @param $value
1123 * @param $option
1124 * @param $html_type
1125 * @param $data_type
1126 * @param null $format
1127 * @param null $contactID
1128 * @param null $fieldID
1129 *
1130 * @return array|mixed|null|string
1131 */
1132 static function getDisplayValueCommon($value,
1133 &$option,
1134 $html_type,
1135 $data_type,
1136 $format = NULL,
1137 $contactID = NULL,
1138 $fieldID = NULL
1139 ) {
1140 $display = $value;
1141
1142 if ($fieldID &&
1143 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1144 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1145 $html_type == 'Select' ||
1146 $html_type == 'CheckBox' ||
1147 $html_type == 'AdvMulti-Select' ||
1148 $html_type == 'Multi-Select'
1149 )
1150 ) {
1151 CRM_Utils_Hook::customFieldOptions($fieldID, $option);
1152 }
1153
1154 switch ($html_type) {
1155 case 'Radio':
1156 if ($data_type == 'Boolean') {
1157 // Do not assume that if not yes means no.
1158 $display = '';
1159 if ($value) {
1160 $display = ts('Yes');
1161 }
1162 elseif ((string)$value === '0') {
1163 $display = ts('No');
1164 }
1165 }
1166 else {
1167 $display = CRM_Utils_Array::value($value, $option);
1168 }
1169 break;
1170
1171 case 'Autocomplete-Select':
1172 if ($data_type == 'ContactReference' &&
1173 $value
1174 ) {
1175 $display = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1176 }
1177 else {
1178 $display = CRM_Utils_Array::value($value, $option);
1179 }
1180 break;
1181
1182 case 'Select':
1183 $display = CRM_Utils_Array::value($value, $option);
1184 break;
1185
1186 case 'CheckBox':
1187 case 'AdvMulti-Select':
1188 case 'Multi-Select':
1189 if (is_array($value)) {
1190 $checkedData = $value;
1191 }
1192 else {
1193 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1194 substr($value, 1, -1)
1195 );
1196 if ($html_type == 'CheckBox') {
1197 $newData = array();
1198 foreach ($checkedData as $v) {
1199 $newData[$v] = 1;
1200 }
1201 $checkedData = $newData;
1202 }
1203 }
1204
1205 $v = array();
1206 $p = array();
1207 foreach ($checkedData as $key => $val) {
1208 if ($html_type == 'CheckBox') {
1209 if ($val) {
1210 $p[] = $key;
1211 $v[] = CRM_Utils_Array::value($key, $option);
1212 }
1213 }
1214 else {
1215 $p[] = $val;
1216 $v[] = CRM_Utils_Array::value($val, $option);
1217 }
1218 }
1219 if (!empty($v)) {
1220 $display = implode(', ', $v);
1221 }
1222 break;
1223
1224 case 'Select Date':
1225 if (is_array($value)) {
1226 foreach ($value as $key => $val) {
1227 $display[$key] = CRM_Utils_Date::customFormat($val);
1228 }
1229 }
1230 else {
1231 // remove time element display if time is not set
1232 if (empty($option['attributes']['time_format'])) {
1233 $value = substr($value, 0, 10);
1234 }
1235 $display = CRM_Utils_Date::customFormat($value);
1236 }
1237 break;
1238
1239 case 'Select State/Province':
1240 if (empty($value)) {
1241 $display = '';
1242 }
1243 else {
1244 $display = CRM_Core_PseudoConstant::stateProvince($value);
1245 }
1246 break;
1247
1248 case 'Multi-Select State/Province':
1249 if (is_array($value)) {
1250 $checkedData = $value;
1251 }
1252 else {
1253 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1254 substr($value, 1, -1)
1255 );
1256 }
1257
1258 $states = CRM_Core_PseudoConstant::stateProvince();
1259 $display = NULL;
1260 foreach ($checkedData as $stateID) {
1261 if ($display) {
1262 $display .= ', ';
1263 }
1264 $display .= $states[$stateID];
1265 }
1266 break;
1267
1268 case 'Select Country':
1269 if (empty($value)) {
1270 $display = '';
1271 }
1272 else {
1273 $display = CRM_Core_PseudoConstant::country($value);
1274 }
1275 break;
1276
1277 case 'Multi-Select Country':
1278 if (is_array($value)) {
1279 $checkedData = $value;
1280 }
1281 else {
1282 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1283 substr($value, 1, -1)
1284 );
1285 }
1286
1287 $countries = CRM_Core_PseudoConstant::country();
1288 $display = NULL;
1289 foreach ($checkedData as $countryID) {
1290 if ($display) {
1291 $display .= ', ';
1292 }
1293 $display .= $countries[$countryID];
1294 }
1295 break;
1296
1297 case 'File':
1298 if ($contactID) {
1299 $url = self::getFileURL($contactID, $fieldID, $value);
1300 if ($url) {
1301 $display = $url['file_url'];
1302 }
1303 }
1304 break;
1305
1306 case 'TextArea':
1307 if (empty($value)) {
1308 $display = '';
1309 }
1310 else {
1311 $display = nl2br($value);
1312 }
1313 break;
1314
1315 case 'Link':
1316 if (empty($value)) {
1317 $display = '';
1318 }
1319 else {
1320 $display = $value;
1321 }
1322 }
1323 return $display ? $display : $value;
1324 }
1325
1326 /**
1327 * Function to set default values for custom data used in profile
1328 *
1329 * @params int $customFieldId custom field id
1330 * @params string $elementName custom field name
1331 * @params array $defaults associated array of fields
1332 * @params int $contactId contact id
1333 * @param $customFieldId
1334 * @param $elementName
1335 * @param $defaults
1336 * @param null $contactId
1337 * @param int $mode profile mode
1338 * @param mixed $value if passed - dont fetch value from db,
1339 * just format the given value
1340 *
1341 * @static
1342 * @access public
1343 */
1344 static function setProfileDefaults($customFieldId,
1345 $elementName,
1346 &$defaults,
1347 $contactId = NULL,
1348 $mode = NULL,
1349 $value = NULL
1350 ) {
1351 //get the type of custom field
1352 $customField = new CRM_Core_BAO_CustomField();
1353 $customField->id = $customFieldId;
1354 $customField->find(TRUE);
1355
1356 if (!$contactId) {
1357 if ($mode == CRM_Profile_Form::MODE_CREATE) {
1358 $value = $customField->default_value;
1359 }
1360 }
1361 else {
1362 if (!isset($value)) {
1363 $info = self::getTableColumnGroup($customFieldId);
1364 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1365 $result = CRM_Core_DAO::executeQuery($query);
1366 if ($result->fetch()) {
1367 $value = $result->value;
1368 }
1369 }
1370
1371 if ($customField->data_type == 'Country') {
1372 if (!$value) {
1373 $config = CRM_Core_Config::singleton();
1374 if ($config->defaultContactCountry) {
1375 $value = $config->defaultContactCountry();
1376 }
1377 }
1378 }
1379 }
1380
1381 //set defaults if mode is registration
1382 if (!trim($value) &&
1383 ($value !== 0) &&
1384 (!in_array($mode, array(CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH)))
1385 ) {
1386 $value = $customField->default_value;
1387 }
1388
1389 if ($customField->data_type == 'Money' && isset($value)) {
1390 $value = number_format($value, 2);
1391 }
1392 switch ($customField->html_type) {
1393 case 'CheckBox':
1394 case 'AdvMulti-Select':
1395 case 'Multi-Select':
1396 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldId, FALSE);
1397 $defaults[$elementName] = array();
1398 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1399 substr($value, 1, -1)
1400 );
1401 foreach ($customOption as $val) {
1402 if (in_array($val['value'], $checkedValue)) {
1403 if ($customField->html_type == 'CheckBox') {
1404 $defaults[$elementName][$val['value']] = 1;
1405 }
1406 elseif ($customField->html_type == 'Multi-Select' ||
1407 $customField->html_type == 'AdvMulti-Select'
1408 ) {
1409 $defaults[$elementName][$val['value']] = $val['value'];
1410 }
1411 }
1412 }
1413 break;
1414
1415 case 'Select Date':
1416 if ($value) {
1417 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date::setDateDefaults(
1418 $value,
1419 NULL,
1420 $customField->date_format,
1421 $customField->time_format
1422 );
1423 }
1424 break;
1425
1426 case 'Autocomplete-Select':
1427 if ($customField->data_type == 'ContactReference') {
1428 if (is_numeric($value)) {
1429 $defaults[$elementName . '_id'] = $value;
1430 $defaults[$elementName] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1431 }
1432 }
1433 else {
1434 $defaults[$elementName] = $value;
1435 }
1436 break;
1437
1438 default:
1439 $defaults[$elementName] = $value;
1440 }
1441 }
1442
1443 /**
1444 * @param $contactID
1445 * @param $cfID
1446 * @param null $fileID
1447 * @param bool $absolute
1448 *
1449 * @return array
1450 */
1451 /**
1452 * @param $contactID
1453 * @param $cfID
1454 * @param null $fileID
1455 * @param bool $absolute
1456 *
1457 * @return array
1458 */
1459 static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE) {
1460 if ($contactID) {
1461 if (!$fileID) {
1462 $params = array('id' => $cfID);
1463 $defaults = array();
1464 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1465 $columnName = $defaults['column_name'];
1466
1467 //table name of custom data
1468 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
1469 $defaults['custom_group_id'],
1470 'table_name', 'id'
1471 );
1472
1473 //query to fetch id from civicrm_file
1474 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1475 $fileID = CRM_Core_DAO::singleValueQuery($query);
1476 }
1477
1478 $result = array();
1479 if ($fileID) {
1480 $fileType = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1481 $fileID,
1482 'mime_type',
1483 'id'
1484 );
1485 $result['file_id'] = $fileID;
1486
1487 if ($fileType == 'image/jpeg' ||
1488 $fileType == 'image/pjpeg' ||
1489 $fileType == 'image/gif' ||
1490 $fileType == 'image/x-png' ||
1491 $fileType == 'image/png'
1492 ) {
1493 $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile',
1494 $fileID,
1495 'entity_id',
1496 'id'
1497 );
1498 list($path) = CRM_Core_BAO_File::path($fileID, $entityId, NULL, NULL);
1499 list($imageWidth, $imageHeight) = getimagesize($path);
1500 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
1501 $url = CRM_Utils_System::url('civicrm/file',
1502 "reset=1&id=$fileID&eid=$contactID",
1503 $absolute, NULL, TRUE, TRUE
1504 );
1505 $result['file_url'] = "
1506 <a href=\"$url\" class='crm-image-popup'>
1507 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1508 </a>";
1509 // for non image files
1510 }
1511 else {
1512 $uri = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1513 $fileID,
1514 'uri'
1515 );
1516 $url = CRM_Utils_System::url('civicrm/file',
1517 "reset=1&id=$fileID&eid=$contactID",
1518 $absolute, NULL, TRUE, TRUE
1519 );
1520 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1521 }
1522 }
1523 return $result;
1524 }
1525 }
1526
1527 /**
1528 * Format custom fields before inserting
1529 *
1530 * @param int $customFieldId custom field id
1531 * @param array $customFormatted formatted array
1532 * @param mix $value value of custom field
1533 * @param string $customFieldExtend custom field extends
1534 * @param int $customValueId custom option value id
1535 * @param int $entityId entity id (contribution, membership...)
1536 * @param boolean $inline consider inline custom groups only
1537 * @param boolean $checkPermission if false, do not include permissioning clause
1538 *
1539 * @return array $customFormatted formatted custom field array
1540 * @static
1541 */
1542 static function formatCustomField($customFieldId, &$customFormatted, $value,
1543 $customFieldExtend, $customValueId = NULL,
1544 $entityId = NULL,
1545 $inline = FALSE,
1546 $checkPermission = TRUE
1547 ) {
1548 //get the custom fields for the entity
1549 //subtype and basic type
1550 $customDataSubType = NULL;
1551 if (is_array($customFieldExtend)) {
1552 $customFieldExtend = $customFieldExtend[0];
1553 }
1554
1555 if (in_array($customFieldExtend,
1556 CRM_Contact_BAO_ContactType::subTypes()
1557 )) {
1558 // This is the case when getFieldsForImport() requires fields
1559 // of subtype and its parent.CRM-5143
1560 $customDataSubType = $customFieldExtend;
1561 $customFieldExtend = CRM_Contact_BAO_ContactType::getBasicType($customDataSubType);
1562 }
1563
1564 $customFields = CRM_Core_BAO_CustomField::getFields($customFieldExtend,
1565 FALSE,
1566 $inline,
1567 $customDataSubType,
1568 NULL,
1569 FALSE,
1570 FALSE,
1571 $checkPermission
1572 );
1573
1574 if (!array_key_exists($customFieldId, $customFields)) {
1575 return;
1576 }
1577
1578 // return if field is a 'code' field
1579 if (!empty($customFields[$customFieldId]['is_view'])) {
1580 return;
1581 }
1582
1583 list($tableName, $columnName, $groupID) = self::getTableColumnGroup($customFieldId);
1584
1585 if (!$customValueId &&
1586 // we always create new entites for is_multiple unless specified
1587 !$customFields[$customFieldId]['is_multiple'] &&
1588 $entityId
1589 ) {
1590 $query = "
1591 SELECT id
1592 FROM $tableName
1593 WHERE entity_id={$entityId}";
1594
1595 $customValueId = CRM_Core_DAO::singleValueQuery($query);
1596 }
1597
1598 //fix checkbox, now check box always submits values
1599 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1600 if ($value) {
1601 // Note that only during merge this is not an array, and you can directly use value
1602 if (is_array($value)) {
1603 $selectedValues = array();
1604 foreach ($value as $selId => $val) {
1605 if ($val) {
1606 $selectedValues[] = $selId;
1607 }
1608 }
1609 if (!empty($selectedValues)) {
1610 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1611 $selectedValues
1612 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1613 }
1614 else {
1615 $value = '';
1616 }
1617 }
1618 }
1619 }
1620
1621 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1622 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1623 ) {
1624 if ($value) {
1625 // Note that only during merge this is not an array,
1626 // and you can directly use value, CRM-4385
1627 if (is_array($value)) {
1628 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1629 array_values($value)
1630 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1631 }
1632 }
1633 else {
1634 $value = '';
1635 }
1636 }
1637
1638 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1639 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1640 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1641 ) &&
1642 $customFields[$customFieldId]['data_type'] == 'String' &&
1643 !empty($customFields[$customFieldId]['text_length']) &&
1644 !empty($value)
1645 ) {
1646 // lets make sure that value is less than the length, else we'll
1647 // be losing some data, CRM-7481
1648 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1649 // need to do a few things here
1650
1651 // 1. lets find a new length
1652 $newLength = $customFields[$customFieldId]['text_length'];
1653 $minLength = strlen($value);
1654 while ($newLength < $minLength) {
1655 $newLength = $newLength * 2;
1656 }
1657
1658 // set the custom field meta data to have a length larger than value
1659 // alter the custom value table column to match this length
1660 CRM_Core_BAO_SchemaHandler::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1661 }
1662 }
1663
1664 $date = NULL;
1665 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1666 if (!CRM_Utils_System::isNull($value)) {
1667 $format = $customFields[$customFieldId]['date_format'];
1668 $date = CRM_Utils_Date::processDate($value, NULL, FALSE, 'YmdHis', $format);
1669 }
1670 $value = $date;
1671 }
1672
1673 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1674 $customFields[$customFieldId]['data_type'] == 'Money'
1675 ) {
1676 if (!$value) {
1677 $value = 0;
1678 }
1679
1680 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1681 $value = CRM_Utils_Rule::cleanMoney($value);
1682 }
1683 }
1684
1685 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1686 $customFields[$customFieldId]['data_type'] == 'Country'
1687 ) &&
1688 empty($value)
1689 ) {
1690 // CRM-3415
1691 $value = 0;
1692 }
1693
1694 $fileId = NULL;
1695
1696 if ($customFields[$customFieldId]['data_type'] == 'File') {
1697 if (empty($value)) {
1698 return;
1699 }
1700
1701 $config = CRM_Core_Config::singleton();
1702
1703 $fName = $value['name'];
1704 $mimeType = $value['type'];
1705
1706 $filename = pathinfo($fName, PATHINFO_BASENAME);
1707
1708 // rename this file to go into the secure directory
1709 if (!rename($fName, $config->customFileUploadDir . $filename)) {
1710 CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
1711 }
1712
1713 if ($customValueId) {
1714 $query = "
1715 SELECT $columnName
1716 FROM $tableName
1717 WHERE id = %1";
1718 $params = array(1 => array($customValueId, 'Integer'));
1719 $fileId = CRM_Core_DAO::singleValueQuery($query, $params);
1720 }
1721
1722 $fileDAO = new CRM_Core_DAO_File();
1723
1724 if ($fileId) {
1725 $fileDAO->id = $fileId;
1726 }
1727
1728 $fileDAO->uri = $filename;
1729 $fileDAO->mime_type = $mimeType;
1730 $fileDAO->upload_date = date('Ymdhis');
1731 $fileDAO->save();
1732 $fileId = $fileDAO->id;
1733 $value = $filename;
1734 }
1735
1736 if (!is_array($customFormatted)) {
1737 $customFormatted = array();
1738 }
1739
1740 if (!array_key_exists($customFieldId, $customFormatted)) {
1741 $customFormatted[$customFieldId] = array();
1742 }
1743
1744 $index = -1;
1745 if ($customValueId) {
1746 $index = $customValueId;
1747 }
1748
1749 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1750 $customFormatted[$customFieldId][$index] = array();
1751 }
1752 $customFormatted[$customFieldId][$index] = array(
1753 'id' => $customValueId > 0 ? $customValueId : NULL,
1754 'value' => $value,
1755 'type' => $customFields[$customFieldId]['data_type'],
1756 'custom_field_id' => $customFieldId,
1757 'custom_group_id' => $groupID,
1758 'table_name' => $tableName,
1759 'column_name' => $columnName,
1760 'file_id' => $fileId,
1761 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1762 );
1763
1764 //we need to sort so that custom fields are created in the order of entry
1765 krsort($customFormatted[$customFieldId]);
1766 return $customFormatted;
1767 }
1768
1769 /**
1770 * @param $params
1771 *
1772 * @return array
1773 */
1774 static function &defaultCustomTableSchema(&$params) {
1775 // add the id and extends_id
1776 $table = array(
1777 'name' => $params['name'],
1778 'is_multiple' => $params['is_multiple'],
1779 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1780 'fields' => array(
1781 array(
1782 'name' => 'id',
1783 'type' => 'int unsigned',
1784 'primary' => TRUE,
1785 'required' => TRUE,
1786 'attributes' => 'AUTO_INCREMENT',
1787 'comment' => 'Default MySQL primary key',
1788 ),
1789 array(
1790 'name' => 'entity_id',
1791 'type' => 'int unsigned',
1792 'required' => TRUE,
1793 'comment' => 'Table that this extends',
1794 'fk_table_name' => $params['extends_name'],
1795 'fk_field_name' => 'id',
1796 'fk_attributes' => 'ON DELETE CASCADE',
1797 ),
1798 ),
1799 );
1800
1801 if (!$params['is_multiple']) {
1802 $table['indexes'] = array(
1803 array(
1804 'unique' => TRUE,
1805 'field_name_1' => 'entity_id',
1806 ),
1807 );
1808 }
1809 return $table;
1810 }
1811
1812 /**
1813 * @param $field
1814 * @param $operation
1815 * @param bool $indexExist
1816 * @param bool $triggerRebuild
1817 */
1818 static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1819 $tableName = CRM_Core_DAO::getFieldValue(
1820 'CRM_Core_DAO_CustomGroup',
1821 $field->custom_group_id,
1822 'table_name'
1823 );
1824
1825 $params = array(
1826 'table_name' => $tableName,
1827 'operation' => $operation,
1828 'name' => $field->column_name,
1829 'type' => CRM_Core_BAO_CustomValueTable::fieldToSQLType(
1830 $field->data_type,
1831 $field->text_length
1832 ),
1833 'required' => $field->is_required,
1834 'searchable' => $field->is_searchable,
1835 );
1836
1837 if ($operation == 'delete') {
1838 $fkName = "{$tableName}_{$field->column_name}";
1839 if (strlen($fkName) >= 48) {
1840 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1841 }
1842 $params['fkName'] = $fkName;
1843 }
1844 if ($field->data_type == 'Country' && $field->html_type == 'Select Country') {
1845 $params['fk_table_name'] = 'civicrm_country';
1846 $params['fk_field_name'] = 'id';
1847 $params['fk_attributes'] = 'ON DELETE SET NULL';
1848 }
1849 elseif ($field->data_type == 'Country' && $field->html_type == 'Multi-Select Country') {
1850 $params['type'] = 'varchar(255)';
1851 }
1852 elseif ($field->data_type == 'StateProvince' && $field->html_type == 'Select State/Province') {
1853 $params['fk_table_name'] = 'civicrm_state_province';
1854 $params['fk_field_name'] = 'id';
1855 $params['fk_attributes'] = 'ON DELETE SET NULL';
1856 }
1857 elseif ($field->data_type == 'StateProvince' && $field->html_type == 'Multi-Select State/Province') {
1858 $params['type'] = 'varchar(255)';
1859 }
1860 elseif ($field->data_type == 'File') {
1861 $params['fk_table_name'] = 'civicrm_file';
1862 $params['fk_field_name'] = 'id';
1863 $params['fk_attributes'] = 'ON DELETE SET NULL';
1864 }
1865 elseif ($field->data_type == 'ContactReference') {
1866 $params['fk_table_name'] = 'civicrm_contact';
1867 $params['fk_field_name'] = 'id';
1868 $params['fk_attributes'] = 'ON DELETE SET NULL';
1869 }
1870 if ($field->default_value) {
1871 $params['default'] = "'{$field->default_value}'";
1872 }
1873
1874 CRM_Core_BAO_SchemaHandler::alterFieldSQL($params, $indexExist, $triggerRebuild);
1875 }
1876
1877 /**
1878 * Determine whether it would be safe to move a field
1879 *
1880 * @param int $fieldID FK to civicrm_custom_field
1881 * @param int $newGroupID FK to civicrm_custom_group
1882 *
1883 * @return array(
1884 string) or TRUE
1885 */
1886 static function _moveFieldValidate($fieldID, $newGroupID) {
1887 $errors = array();
1888
1889 $field = new CRM_Core_DAO_CustomField();
1890 $field->id = $fieldID;
1891 if (!$field->find(TRUE)) {
1892 $errors['fieldID'] = 'Invalid ID for custom field';
1893 return $errors;
1894 }
1895
1896 $oldGroup = new CRM_Core_DAO_CustomGroup();
1897 $oldGroup->id = $field->custom_group_id;
1898 if (!$oldGroup->find(TRUE)) {
1899 $errors['fieldID'] = 'Invalid ID for old custom group';
1900 return $errors;
1901 }
1902
1903 $newGroup = new CRM_Core_DAO_CustomGroup();
1904 $newGroup->id = $newGroupID;
1905 if (!$newGroup->find(TRUE)) {
1906 $errors['newGroupID'] = 'Invalid ID for new custom group';
1907 return $errors;
1908 }
1909
1910 $query = "
1911 SELECT b.id
1912 FROM civicrm_custom_field a
1913 INNER JOIN civicrm_custom_field b
1914 WHERE a.id = %1
1915 AND a.label = b.label
1916 AND b.custom_group_id = %2
1917 ";
1918 $params = array(
1919 1 => array($field->id, 'Integer'),
1920 2 => array($newGroup->id, 'Integer'),
1921 );
1922 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1923 if ($count > 0) {
1924 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1925 }
1926
1927 $tableName = $oldGroup->table_name;
1928 $columnName = $field->column_name;
1929
1930 $query = "
1931 SELECT count(*)
1932 FROM $tableName
1933 WHERE $columnName is not null
1934 ";
1935 $count = CRM_Core_DAO::singleValueQuery($query,
1936 CRM_Core_DAO::$_nullArray
1937 );
1938 if ($count > 0) {
1939 $query = "
1940 SELECT extends
1941 FROM civicrm_custom_group
1942 WHERE id IN ( %1, %2 )
1943 ";
1944 $params = array(1 => array($oldGroup->id, 'Integer'),
1945 2 => array($newGroup->id, 'Integer'),
1946 );
1947
1948 $dao = CRM_Core_DAO::executeQuery($query, $params);
1949 $extends = array();
1950 while ($dao->fetch()) {
1951 $extends[] = $dao->extends;
1952 }
1953 if ($extends[0] != $extends[1]) {
1954 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1955 }
1956 }
1957
1958 return empty($errors) ? TRUE : $errors;
1959 }
1960
1961 /**
1962 * Move a custom data field from one group (table) to another
1963 *
1964 * @param int $fieldID FK to civicrm_custom_field
1965 * @param int $newGroupID FK to civicrm_custom_group
1966 *
1967 * @return void
1968 */
1969 static function moveField($fieldID, $newGroupID) {
1970 $validation = self::_moveFieldValidate($fieldID, $newGroupID);
1971 if (TRUE !== $validation) {
1972 CRM_Core_Error::fatal(implode(' ', $validation));
1973 }
1974 $field = new CRM_Core_DAO_CustomField();
1975 $field->id = $fieldID;
1976 $field->find(TRUE);
1977
1978 $newGroup = new CRM_Core_DAO_CustomGroup();
1979 $newGroup->id = $newGroupID;
1980 $newGroup->find(TRUE);
1981
1982 $oldGroup = new CRM_Core_DAO_CustomGroup();
1983 $oldGroup->id = $field->custom_group_id;
1984 $oldGroup->find(TRUE);
1985
1986 $add = clone$field;
1987 $add->custom_group_id = $newGroup->id;
1988 self::createField($add, 'add');
1989
1990 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1991 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1992 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1993 ";
1994 CRM_Core_DAO::executeQuery($sql);
1995
1996 $del = clone$field;
1997 $del->custom_group_id = $oldGroup->id;
1998 self::createField($del, 'delete');
1999
2000 $add->save();
2001
2002 CRM_Utils_System::flushCache();
2003 }
2004
2005 /**
2006 * Get the database table name and column name for a custom field
2007 *
2008 * @param int $fieldID - the fieldID of the custom field
2009 * @param boolean $force - force the sql to be run again (primarily used for tests)
2010 *
2011 * @return array - fatal is fieldID does not exists, else array of tableName, columnName
2012 * @static
2013 * @public
2014 */
2015 static function getTableColumnGroup($fieldID, $force = FALSE) {
2016 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2017 $cache = CRM_Utils_Cache::singleton();
2018 $fieldValues = $cache->get($cacheKey);
2019 if (empty($fieldValues) || $force) {
2020 $query = "
2021 SELECT cg.table_name, cf.column_name, cg.id
2022 FROM civicrm_custom_group cg,
2023 civicrm_custom_field cf
2024 WHERE cf.custom_group_id = cg.id
2025 AND cf.id = %1";
2026 $params = array(1 => array($fieldID, 'Integer'));
2027 $dao = CRM_Core_DAO::executeQuery($query, $params);
2028
2029 if (!$dao->fetch()) {
2030 CRM_Core_Error::fatal();
2031 }
2032 $dao->free();
2033 $fieldValues = array($dao->table_name, $dao->column_name, $dao->id);
2034 $cache->set($cacheKey, $fieldValues);
2035 }
2036 return $fieldValues;
2037 }
2038
2039 /**
2040 * Function to get custom option groups
2041 *
2042 * @params array $includeFieldIds ids of custom fields for which
2043 * option groups must be included.
2044 *
2045 * Currently this is required in the cases where option groups are to be included
2046 * for inactive fields : CRM-5369
2047 *
2048 * @access public
2049 *
2050 * @param null $includeFieldIds
2051 *
2052 * @return mixed $customOptionGroup@static
2053 */
2054 public static function &customOptionGroup($includeFieldIds = NULL) {
2055 static $customOptionGroup = NULL;
2056
2057 $cacheKey = (empty($includeFieldIds)) ? 'onlyActive' : 'force';
2058 if ($cacheKey == 'force') {
2059 $customOptionGroup[$cacheKey] = NULL;
2060 }
2061
2062 if (empty($customOptionGroup[$cacheKey])) {
2063 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2064
2065 //support for single as well as array format.
2066 if (!empty($includeFieldIds)) {
2067 if (is_array($includeFieldIds)) {
2068 $includeFieldIds = implode(',', $includeFieldIds);
2069 }
2070 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2071 }
2072
2073 $query = "
2074 SELECT g.id, g.title
2075 FROM civicrm_option_group g
2076 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2077 WHERE {$whereClause}";
2078
2079 $dao = CRM_Core_DAO::executeQuery($query);
2080 while ($dao->fetch()) {
2081 $customOptionGroup[$cacheKey][$dao->id] = $dao->title;
2082 }
2083 }
2084
2085 return $customOptionGroup[$cacheKey];
2086 }
2087
2088 /**
2089 * Function to fix orphan groups
2090 *
2091 * @params int $customFieldId custom field id
2092 * @params int $optionGroupId option group id
2093 *
2094 * @access public
2095 *
2096 * @param $customFieldId
2097 * @param $optionGroupId
2098 *
2099 * @return void
2100 * @static
2101 */
2102 static function fixOptionGroups($customFieldId, $optionGroupId) {
2103 // check if option group belongs to any custom Field else delete
2104 // get the current option group
2105 $currentOptionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
2106 $customFieldId,
2107 'option_group_id'
2108 );
2109 // get the updated option group
2110 // if both are same return
2111 if ($currentOptionGroupId == $optionGroupId) {
2112 return;
2113 }
2114
2115 // check if option group is related to any other field
2116 self::checkOptionGroup($currentOptionGroupId);
2117 }
2118
2119 /**
2120 * Function to check if option group is related to more than one
2121 * custom field
2122 *
2123 * @params int $optionGroupId option group id
2124 *
2125 * @param $optionGroupId
2126 *
2127 * @return void
2128 @static
2129 */
2130 static function checkOptionGroup($optionGroupId) {
2131 $query = "
2132 SELECT count(*)
2133 FROM civicrm_custom_field
2134 WHERE option_group_id = {$optionGroupId}";
2135
2136 $count = CRM_Core_DAO::singleValueQuery($query);
2137
2138 if ($count < 2) {
2139 //delete the option group
2140 CRM_Core_BAO_OptionGroup::del($optionGroupId);
2141 }
2142 }
2143
2144 /**
2145 * @param $optionGroupId
2146 * @param $htmlType
2147 *
2148 * @return null|string
2149 */
2150 static function getOptionGroupDefault($optionGroupId, $htmlType) {
2151 $query = "
2152 SELECT default_value, html_type
2153 FROM civicrm_custom_field
2154 WHERE option_group_id = {$optionGroupId}
2155 AND default_value IS NOT NULL
2156 ORDER BY html_type";
2157
2158 $dao = CRM_Core_DAO::executeQuery($query);
2159 $defaultValue = NULL;
2160 $defaultHTMLType = NULL;
2161 while ($dao->fetch()) {
2162 if ($dao->html_type == $htmlType) {
2163 return $dao->default_value;
2164 }
2165 if ($defaultValue == NULL) {
2166 $defaultValue = $dao->default_value;
2167 $defaultHTMLType = $dao->html_type;
2168 }
2169 }
2170
2171 // some conversions are needed if either the old or new has a html type which has potential
2172 // multiple default values.
2173 if (($htmlType == 'CheckBox' || $htmlType == 'Multi-Select') &&
2174 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2175 ) {
2176 $defaultValue = CRM_Core_DAO::VALUE_SEPARATOR . $defaultValue . CRM_Core_DAO::VALUE_SEPARATOR;
2177 }
2178 elseif (($defaultHTMLType == 'CheckBox' || $defaultHTMLType == 'Multi-Select') &&
2179 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2180 ) {
2181 $defaultValue = substr($defaultValue, 1, -1);
2182 $values = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2183 substr($defaultValue, 1, -1)
2184 );
2185 $defaultValue = $values[0];
2186 }
2187
2188 return $defaultValue;
2189 }
2190
2191 /**
2192 * @param $params
2193 * @param $customFields
2194 * @param $entityID
2195 * @param $customFieldExtends
2196 * @param bool $inline
2197 *
2198 * @return array
2199 */
2200 static function postProcess(&$params,
2201 &$customFields,
2202 $entityID,
2203 $customFieldExtends,
2204 $inline = FALSE
2205 ) {
2206 $customData = array();
2207
2208 foreach ($params as $key => $value) {
2209 if ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($key, TRUE)) {
2210
2211 // for autocomplete transfer hidden value instead of label
2212 if ($params[$key] && isset($params[$key . '_id'])) {
2213 $value = $params[$key . '_id'];
2214 }
2215
2216 // we need to append time with date
2217 if ($params[$key] && isset($params[$key . '_time'])) {
2218 $value .= ' ' . $params[$key . '_time'];
2219 }
2220
2221 CRM_Core_BAO_CustomField::formatCustomField($customFieldInfo[0],
2222 $customData,
2223 $value,
2224 $customFieldExtends,
2225 $customFieldInfo[1],
2226 $entityID,
2227 $inline
2228 );
2229 }
2230 }
2231 return $customData;
2232 }
2233
2234 /**
2235 * @param $field
2236 * @param $options
2237 *
2238 * @throws Exception
2239 */
2240 static function buildOption($field, &$options) {
2241 // Fixme - adding anything but options to the $options array is a bad idea
2242 // What if an option had the key 'attributes'?
2243 $options['attributes'] = array(
2244 'label' => $field['label'],
2245 'data_type' => $field['data_type'],
2246 'html_type' => $field['html_type'],
2247 );
2248
2249 $optionGroupID = NULL;
2250 if (($field['html_type'] == 'CheckBox' ||
2251 $field['html_type'] == 'Radio' ||
2252 $field['html_type'] == 'Select' ||
2253 $field['html_type'] == 'AdvMulti-Select' ||
2254 $field['html_type'] == 'Multi-Select' ||
2255 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2256 )) {
2257 if ($field['option_group_id']) {
2258 $optionGroupID = $field['option_group_id'];
2259 }
2260 elseif ($field['data_type'] != 'Boolean') {
2261 CRM_Core_Error::fatal();
2262 }
2263 }
2264
2265 // build the cache for custom values with options (label => value)
2266 if ($optionGroupID != NULL) {
2267 $query = "
2268 SELECT label, value
2269 FROM civicrm_option_value
2270 WHERE option_group_id = $optionGroupID
2271 ";
2272
2273 $dao = CRM_Core_DAO::executeQuery($query);
2274 while ($dao->fetch()) {
2275 if ($field['data_type'] == 'Int' || $field['data_type'] == 'Float') {
2276 $num = round($dao->value, 2);
2277 $options["$num"] = $dao->label;
2278 }
2279 else {
2280 $options[$dao->value] = $dao->label;
2281 }
2282 }
2283
2284 CRM_Utils_Hook::customFieldOptions($field['id'], $options);
2285 }
2286 }
2287
2288 /**
2289 * @param $fieldLabel
2290 * @param null $groupTitle
2291 *
2292 * @return null
2293 */
2294 static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2295 $params = array(1 => array($fieldLabel, 'String'));
2296 if ($groupTitle) {
2297 $params[2] = array($groupTitle, 'String');
2298 $sql = "
2299 SELECT f.id
2300 FROM civicrm_custom_field f
2301 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2302 WHERE ( f.label = %1 OR f.name = %1 )
2303 AND ( g.title = %2 OR g.name = %2 )
2304 ";
2305 }
2306 else {
2307 $sql = "
2308 SELECT f.id
2309 FROM civicrm_custom_field f
2310 WHERE ( f.label = %1 OR f.name = %1 )
2311 ";
2312 }
2313
2314 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2315 if ($dao->fetch() &&
2316 $dao->N == 1
2317 ) {
2318 return $dao->id;
2319 }
2320 else {
2321 return NULL;
2322 }
2323 }
2324
2325 /**
2326 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2327 *
2328 */
2329 static function getNameFromID($ids) {
2330 if (is_array($ids)) {
2331 $ids = implode(',', $ids);
2332 }
2333 $sql = "
2334 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2335 FROM civicrm_custom_field f
2336 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2337 WHERE f.id IN ($ids)";
2338
2339
2340 $dao = CRM_Core_DAO::executeQuery($sql);
2341 $result = array();
2342 while ($dao->fetch()) {
2343 $result[$dao->id] = array(
2344 'field_name' => $dao->field_name,
2345 'field_label' => $dao->field_label,
2346 'group_name' => $dao->group_name,
2347 'group_title' => $dao->group_title,
2348 );
2349 }
2350 return $result;
2351 }
2352
2353 /**
2354 * Validate custom data.
2355 *
2356 * @param array $params custom data submitted.
2357 * ie array( 'custom_1' => 'validate me' );
2358 *
2359 * @return array $errors validation errors.
2360 * @static
2361 */
2362 static function validateCustomData($params) {
2363 $errors = array();
2364 if (!is_array($params) || empty($params)) {
2365 return $errors;
2366 }
2367
2368
2369 //pick up profile fields.
2370 $profileFields = array();
2371 $ufGroupId = CRM_Utils_Array::value('ufGroupId', $params);
2372 if ($ufGroupId) {
2373 $profileFields = CRM_Core_BAO_UFGroup::getFields($ufGroupId,
2374 FALSE,
2375 CRM_Core_Action::VIEW
2376 );
2377 }
2378
2379 //lets start w/ params.
2380 foreach ($params as $key => $value) {
2381 $customFieldID = self::getKeyID($key);
2382 if (!$customFieldID) {
2383 continue;
2384 }
2385
2386 //load the structural info for given field.
2387 $field = new CRM_Core_DAO_CustomField();
2388 $field->id = $customFieldID;
2389 if (!$field->find(TRUE)) {
2390 continue;
2391 }
2392 $dataType = $field->data_type;
2393
2394 $profileField = CRM_Utils_Array::value($key, $profileFields, array());
2395 $fieldTitle = CRM_Utils_Array::value('title', $profileField);
2396 $isRequired = CRM_Utils_Array::value('is_required', $profileField);
2397 if (!$fieldTitle) {
2398 $fieldTitle = $field->label;
2399 }
2400
2401 //no need to validate.
2402 if (CRM_Utils_System::isNull($value) && !$isRequired) {
2403 continue;
2404 }
2405
2406 //lets validate first for required field.
2407 if ($isRequired && CRM_Utils_System::isNull($value)) {
2408 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2409 continue;
2410 }
2411
2412 //now time to take care of custom field form rules.
2413 $ruleName = $errorMsg = NULL;
2414 switch ($dataType) {
2415 case 'Int':
2416 $ruleName = 'integer';
2417 $errorMsg = ts('%1 must be an integer (whole number).',
2418 array(1 => $fieldTitle)
2419 );
2420 break;
2421
2422 case 'Money':
2423 $ruleName = 'money';
2424 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2425 array(1 => $fieldTitle)
2426 );
2427 break;
2428
2429 case 'Float':
2430 $ruleName = 'numeric';
2431 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2432 array(1 => $fieldTitle)
2433 );
2434 break;
2435
2436 case 'Link':
2437 $ruleName = 'wikiURL';
2438 $errorMsg = ts('%1 must be valid Website.',
2439 array(1 => $fieldTitle)
2440 );
2441 break;
2442 }
2443
2444 if ($ruleName && !CRM_Utils_System::isNull($value)) {
2445 $valid = FALSE;
2446 $funName = "CRM_Utils_Rule::{$ruleName}";
2447 if (is_callable($funName)) {
2448 $valid = call_user_func($funName, $value);
2449 }
2450 if (!$valid) {
2451 $errors[$key] = $errorMsg;
2452 }
2453 }
2454 }
2455
2456 return $errors;
2457 }
2458
2459 /**
2460 * @param $customId
2461 *
2462 * @return bool
2463 */
2464 static function isMultiRecordField($customId) {
2465 $isMultipleWithGid = FALSE;
2466 if (!is_numeric($customId)) {
2467 $customId = self::getKeyID($customId);
2468 }
2469 if (is_numeric($customId)) {
2470 $sql = "SELECT cg.id cgId
2471 FROM civicrm_custom_group cg
2472 INNER JOIN civicrm_custom_field cf
2473 ON cg.id = cf.custom_group_id
2474 WHERE cf.id = %1 AND cg.is_multiple = 1";
2475 $params[1] = array($customId, 'Integer');
2476 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2477 if ($dao->fetch()) {
2478 if ($dao->cgId) {
2479 $isMultipleWithGid = $dao->cgId;
2480 }
2481 }
2482 }
2483
2484 return $isMultipleWithGid;
2485 }
2486
2487 /**
2488 * Does this field store a serialized string?
2489 * @param CRM_Core_DAO_CustomField|array $field
2490 * @return bool
2491 */
2492 static function isSerialized($field) {
2493 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2494 $field = (array) $field;
2495 // FIXME: Currently the only way to know if data is serialized is by looking at the html_type. It would be cleaner to decouple this.
2496 return ($field['html_type'] == 'CheckBox' || strpos($field['html_type'], 'Multi') !== FALSE);
2497 }
2498 }
2499