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