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