Merge branch 4.5 into master
[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 object
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 object
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 The id (if exists)
688 * @static
689 */
690 public static function getKeyID($key, $all = FALSE) {
691 $match = array();
692 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
693 if (!$all) {
694 return $match[1];
695 }
696 else {
697 return array(
698 $match[1],
699 CRM_Utils_Array::value(2, $match),
700 );
701 }
702 }
703 return $all ? array(NULL, NULL) : NULL;
704 }
705
706 /**
707 * Use the cache to get all values of a specific custom field
708 *
709 * @param int $fieldID
710 * The custom field ID.
711 *
712 * @return CRM_Core_DAO_CustomField $field the field object
713 * @static
714 * public
715 */
716 public static function getFieldObject($fieldID) {
717 $field = new CRM_Core_DAO_CustomField();
718
719 // check if we can get the field values from the system cache
720 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
721 $cache = CRM_Utils_Cache::singleton();
722 $fieldValues = $cache->get($cacheKey);
723 if (empty($fieldValues)) {
724 $field->id = $fieldID;
725 if (!$field->find(TRUE)) {
726 CRM_Core_Error::fatal();
727 }
728
729 $fieldValues = array();
730 CRM_Core_DAO::storeValues($field, $fieldValues);
731
732 $cache->set($cacheKey, $fieldValues);
733 }
734 else {
735 $field->copyValues($fieldValues);
736 }
737
738 return $field;
739 }
740
741 /**
742 * This function for building custom fields
743 *
744 * @param CRM_Core_Form $qf
745 * Form object (reference).
746 * @param string $elementName
747 * Name of the custom field.
748 * @param int $fieldId
749 * @param bool $inactiveNeeded
750 * -deprecated.
751 * @param bool $useRequired
752 * True if required else false.
753 * @param bool $search
754 * True if used for search else false.
755 * @param string $label
756 * Label for custom field.
757 *
758 * @static
759 */
760 public static function addQuickFormElement(
761 &$qf,
762 $elementName,
763 $fieldId,
764 $inactiveNeeded = FALSE,
765 $useRequired = TRUE,
766 $search = FALSE,
767 $label = NULL
768 ) {
769 $field = self::getFieldObject($fieldId);
770 $widget = $field->html_type;
771
772 // Custom field HTML should indicate group+field name
773 $groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id);
774 $dataCrmCustomVal = $groupName . ':' . $field->name;
775 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
776 $field->attributes .= $dataCrmCustomAttr;
777
778 // Fixed for Issue CRM-2183
779 if ($widget == 'TextArea' && $search) {
780 $widget = 'Text';
781 }
782
783 $placeholder = $search ? ts('- any -') : ($useRequired ? ts('- select -') : ts('- none -'));
784
785 // FIXME: Why are select state/country separate widget types?
786 $isSelect = (in_array($widget, array(
787 'Select',
788 'Multi-Select',
789 'Select State/Province',
790 'Multi-Select State/Province',
791 'Select Country',
792 'Multi-Select Country',
793 'AdvMulti-Select',
794 'CheckBox',
795 'Radio',
796 )));
797
798 if ($isSelect) {
799 $options = CRM_Utils_Array::value('values', civicrm_api3('contact', 'getoptions', array(
800 'field' => "custom_$fieldId",
801 'context' => $search ? 'search' : 'create',
802 ), array()));
803
804 // Consolidate widget types to simplify the below switch statement
805 if ($search || ($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
806 $widget = 'Select';
807 }
808 $selectAttributes = array(
809 'data-crm-custom' => $dataCrmCustomVal,
810 'class' => 'crm-select2',
811 );
812 // Search field is always multi-select
813 if ($search || strpos($field->html_type, 'Multi') !== FALSE) {
814 $selectAttributes['class'] .= ' huge';
815 $selectAttributes['multiple'] = 'multiple';
816 $selectAttributes['placeholder'] = $placeholder;
817 }
818 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
819 if ($field->option_group_id && !$search && $widget == 'Select' && CRM_Core_Permission::check('administer CiviCRM')) {
820 $selectAttributes += array(
821 'data-api-entity' => 'contact',
822 // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
823 'data-api-field' => 'custom_' . $field->id,
824 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id),
825 );
826 }
827 }
828
829 if (!isset($label)) {
830 $label = $field->label;
831 }
832
833 /**
834 * at some point in time we might want to split the below into small functions
835 **/
836
837 switch ($widget) {
838 case 'Text':
839 case 'Link':
840 if ($field->is_search_range && $search) {
841 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes);
842 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes);
843 }
844 else {
845 $element = &$qf->add('text', $elementName, $label,
846 $field->attributes,
847 $useRequired && !$search
848 );
849 }
850 break;
851
852 case 'TextArea':
853 $attributes = $dataCrmCustomAttr;
854 if ($field->note_rows) {
855 $attributes .= 'rows=' . $field->note_rows;
856 }
857 else {
858 $attributes .= 'rows=4';
859 }
860 if ($field->note_columns) {
861 $attributes .= ' cols=' . $field->note_columns;
862 }
863 else {
864 $attributes .= ' cols=60';
865 }
866 if ($field->text_length) {
867 $attributes .= ' maxlength=' . $field->text_length;
868 }
869 $element = &$qf->add('textarea',
870 $elementName,
871 $label,
872 $attributes,
873 $useRequired && !$search
874 );
875 break;
876
877 case 'Select Date':
878 if ($field->is_search_range && $search) {
879 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
880 array(
881 'format' => $field->date_format,
882 'timeFormat' => $field->time_format,
883 'startOffset' => $field->start_date_years,
884 'endOffset' => $field->end_date_years,
885 'data-crm-custom' => $dataCrmCustomVal,
886 )
887 );
888
889 $qf->addDate($elementName . '_to', ts('To'), FALSE,
890 array(
891 'format' => $field->date_format,
892 'timeFormat' => $field->time_format,
893 'startOffset' => $field->start_date_years,
894 'endOffset' => $field->end_date_years,
895 'data-crm-custom' => $dataCrmCustomVal,
896 )
897 );
898 }
899 else {
900 $required = $useRequired && !$search;
901
902 $qf->addDate($elementName, $label, $required, array(
903 'format' => $field->date_format,
904 'timeFormat' => $field->time_format,
905 'startOffset' => $field->start_date_years,
906 'endOffset' => $field->end_date_years,
907 'data-crm-custom' => $dataCrmCustomVal,
908 ));
909 }
910 break;
911
912 case 'Radio':
913 $choice = array();
914 foreach ($options as $v => $l) {
915 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes);
916 }
917 $group = $qf->addGroup($choice, $elementName, $label);
918 if ($useRequired && !$search) {
919 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
920 }
921 else {
922 $group->setAttribute('allowClear', TRUE);
923 }
924 break;
925
926 // For all select elements
927 case 'Select':
928 if (empty($selectAttributes['multiple'])) {
929 $options = array('' => $placeholder) + $options;
930 }
931 $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
932
933 // Add and/or option for fields that store multiple values
934 if ($search && self::isSerialized($field)) {
935
936 $operators = array(
937 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
938 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
939 );
940 $qf->addGroup($operators, $elementName . '_operator');
941 $qf->setDefaults(array($elementName . '_operator' => 'or'));
942 }
943 break;
944
945 case 'AdvMulti-Select':
946 $include =& $qf->addElement(
947 'advmultiselect',
948 $elementName,
949 $label, $options,
950 array(
951 'size' => 5,
952 'style' => '',
953 'class' => 'advmultiselect',
954 'data-crm-custom' => $dataCrmCustomVal,
955 )
956 );
957
958 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
959 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
960
961 if ($useRequired && !$search) {
962 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
963 }
964 break;
965
966 case 'CheckBox':
967 $check = array();
968 foreach ($options as $v => $l) {
969 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
970 }
971 $qf->addGroup($check, $elementName, $label);
972 if ($useRequired && !$search) {
973 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
974 }
975 break;
976
977 case 'File':
978 // we should not build upload file in search mode
979 if ($search) {
980 return;
981 }
982 $qf->add(
983 strtolower($field->html_type),
984 $elementName,
985 $label,
986 $field->attributes,
987 $useRequired && !$search
988 );
989 $qf->addUploadElement($elementName);
990 break;
991
992 case 'RichTextEditor':
993 $attributes = array(
994 'rows' => $field->note_rows,
995 'cols' => $field->note_columns,
996 'data-crm-custom' => $dataCrmCustomVal,
997 );
998 if ($field->text_length) {
999 $attributes['maxlength'] = $field->text_length;
1000 }
1001 $qf->addWysiwyg($elementName, $label, $attributes, $search);
1002 break;
1003
1004 case 'Autocomplete-Select':
1005 static $customUrls = array();
1006 // Fixme: why is this a string in the first place??
1007 $attributes = array();
1008 if ($field->attributes) {
1009 foreach (explode(' ', $field->attributes) as $at) {
1010 if (strpos($at, '=')) {
1011 list($k, $v) = explode('=', $at);
1012 $attributes[$k] = trim($v, ' "');
1013 }
1014 }
1015 }
1016 if ($field->data_type == 'ContactReference') {
1017 $attributes['class'] = (isset($attributes['class']) ? $attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1018 $attributes['data-api-entity'] = 'contact';
1019 $qf->add('text', $elementName, $label, $attributes,
1020 $useRequired && !$search
1021 );
1022
1023 $urlParams = "context=customfield&id={$field->id}";
1024
1025 $customUrls[$elementName] = CRM_Utils_System::url('civicrm/ajax/contactref',
1026 $urlParams,
1027 FALSE, NULL, FALSE
1028 );
1029
1030 }
1031 else {
1032 // FIXME: This won't work with customFieldOptions hook
1033 $attributes += array(
1034 'entity' => 'option_value',
1035 'placeholder' => $placeholder,
1036 'multiple' => $search,
1037 'api' => array(
1038 'params' => array('option_group_id' => $field->option_group_id),
1039 ),
1040 );
1041 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1042 }
1043
1044 $qf->assign('customUrls', $customUrls);
1045 break;
1046 }
1047
1048 switch ($field->data_type) {
1049 case 'Int':
1050 // integers will have numeric rule applied to them.
1051 if ($field->is_search_range && $search) {
1052 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1053 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1054 }
1055 elseif ($widget == 'Text') {
1056 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1057 }
1058 break;
1059
1060 case 'Float':
1061 if ($field->is_search_range && $search) {
1062 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1063 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1064 }
1065 elseif ($widget == 'Text') {
1066 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1067 }
1068 break;
1069
1070 case 'Money':
1071 if ($field->is_search_range && $search) {
1072 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1073 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1074 }
1075 elseif ($widget == 'Text') {
1076 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1077 }
1078 break;
1079
1080 case 'Link':
1081 $element->setAttribute('onfocus', "if (!this.value) {this.value='http://';}");
1082 $element->setAttribute('onblur', "if (this.value == 'http://') {this.value='';}");
1083 $element->setAttribute('class', "url");
1084 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1085 break;
1086 }
1087 if ($field->is_view && !$search) {
1088 $qf->freeze($elementName);
1089 }
1090 }
1091
1092 /**
1093 * Delete the Custom Field.
1094 *
1095 * @param object $field
1096 * The field object.
1097 *
1098 * @return boolean
1099 *
1100 * @static
1101 */
1102 public static function deleteField($field) {
1103 CRM_Utils_System::flushCache();
1104
1105 // first delete the custom option group and values associated with this field
1106 if ($field->option_group_id) {
1107 //check if option group is related to any other field, if
1108 //not delete the option group and related option values
1109 self::checkOptionGroup($field->option_group_id);
1110 }
1111
1112 // next drop the column from the custom value table
1113 self::createField($field, 'delete');
1114
1115 $field->delete();
1116 CRM_Core_BAO_UFField::delUFField($field->id);
1117 CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1118
1119 return;
1120 }
1121
1122 /**
1123 * Given a custom field value, its id and the set of options
1124 * find the display value for this field
1125 *
1126 * @param mixed $value
1127 * The custom field value.
1128 * @param int $id
1129 * The custom field id.
1130 * @param int $options
1131 * The assoc array of option name/value pairs.
1132 *
1133 * @param int $contactID
1134 * @param int $fieldID
1135 *
1136 * @return string
1137 * the display value
1138 *
1139 * @static
1140 */
1141 public static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1142 $option = &$options[$id];
1143 $attributes = &$option['attributes'];
1144 $html_type = $attributes['html_type'];
1145 $data_type = $attributes['data_type'];
1146 $format = CRM_Utils_Array::value('format', $attributes);
1147
1148 return self::getDisplayValueCommon($value,
1149 $option,
1150 $html_type,
1151 $data_type,
1152 $format,
1153 $contactID,
1154 $fieldID
1155 );
1156 }
1157
1158 /**
1159 * @param $value
1160 * @param $option
1161 * @param $html_type
1162 * @param $data_type
1163 * @param null $format
1164 * @param int $contactID
1165 * @param int $fieldID
1166 *
1167 * @return array|mixed|null|string
1168 */
1169 static function getDisplayValueCommon(
1170 $value,
1171 &$option,
1172 $html_type,
1173 $data_type,
1174 $format = NULL,
1175 $contactID = NULL,
1176 $fieldID = NULL
1177 ) {
1178 $display = $value;
1179
1180 if ($fieldID &&
1181 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1182 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1183 $html_type == 'Select' ||
1184 $html_type == 'CheckBox' ||
1185 $html_type == 'AdvMulti-Select' ||
1186 $html_type == 'Multi-Select'
1187 )
1188 ) {
1189 CRM_Utils_Hook::customFieldOptions($fieldID, $option);
1190 }
1191
1192 switch ($html_type) {
1193 case 'Radio':
1194 if ($data_type == 'Boolean') {
1195 // Do not assume that if not yes means no.
1196 $display = '';
1197 if ($value) {
1198 $display = ts('Yes');
1199 }
1200 elseif ((string) $value === '0') {
1201 $display = ts('No');
1202 }
1203 }
1204 else {
1205 $display = CRM_Utils_Array::value($value, $option);
1206 }
1207 break;
1208
1209 case 'Autocomplete-Select':
1210 if ($data_type == 'ContactReference' &&
1211 $value
1212 ) {
1213 $display = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1214 }
1215 else {
1216 $display = CRM_Utils_Array::value($value, $option);
1217 }
1218 break;
1219
1220 case 'Select':
1221 $display = CRM_Utils_Array::value($value, $option);
1222 break;
1223
1224 case 'CheckBox':
1225 case 'AdvMulti-Select':
1226 case 'Multi-Select':
1227 if (is_array($value)) {
1228 $checkedData = $value;
1229 }
1230 else {
1231 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1232 substr($value, 1, -1)
1233 );
1234 if ($html_type == 'CheckBox') {
1235 $newData = array();
1236 foreach ($checkedData as $v) {
1237 $newData[$v] = 1;
1238 }
1239 $checkedData = $newData;
1240 }
1241 }
1242
1243 $v = array();
1244 $p = array();
1245 foreach ($checkedData as $key => $val) {
1246 if ($html_type == 'CheckBox') {
1247 if ($val) {
1248 $p[] = $key;
1249 $v[] = CRM_Utils_Array::value($key, $option);
1250 }
1251 }
1252 else {
1253 $p[] = $val;
1254 $v[] = CRM_Utils_Array::value($val, $option);
1255 }
1256 }
1257 if (!empty($v)) {
1258 $display = implode(', ', $v);
1259 }
1260 break;
1261
1262 case 'Select Date':
1263 if (is_array($value)) {
1264 foreach ($value as $key => $val) {
1265 $display[$key] = CRM_Utils_Date::customFormat($val);
1266 }
1267 }
1268 else {
1269 // remove time element display if time is not set
1270 if (empty($option['attributes']['time_format'])) {
1271 $value = substr($value, 0, 10);
1272 }
1273 $display = CRM_Utils_Date::customFormat($value);
1274 }
1275 break;
1276
1277 case 'Select State/Province':
1278 if (empty($value)) {
1279 $display = '';
1280 }
1281 else {
1282 $display = CRM_Core_PseudoConstant::stateProvince($value);
1283 }
1284 break;
1285
1286 case 'Multi-Select State/Province':
1287 if (is_array($value)) {
1288 $checkedData = $value;
1289 }
1290 else {
1291 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1292 substr($value, 1, -1)
1293 );
1294 }
1295
1296 $states = CRM_Core_PseudoConstant::stateProvince();
1297 $display = NULL;
1298 foreach ($checkedData as $stateID) {
1299 if ($display) {
1300 $display .= ', ';
1301 }
1302 $display .= $states[$stateID];
1303 }
1304 break;
1305
1306 case 'Select Country':
1307 if (empty($value)) {
1308 $display = '';
1309 }
1310 else {
1311 $display = CRM_Core_PseudoConstant::country($value);
1312 }
1313 break;
1314
1315 case 'Multi-Select Country':
1316 if (is_array($value)) {
1317 $checkedData = $value;
1318 }
1319 else {
1320 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1321 substr($value, 1, -1)
1322 );
1323 }
1324
1325 $countries = CRM_Core_PseudoConstant::country();
1326 $display = NULL;
1327 foreach ($checkedData as $countryID) {
1328 if ($display) {
1329 $display .= ', ';
1330 }
1331 $display .= $countries[$countryID];
1332 }
1333 break;
1334
1335 case 'File':
1336 if ($contactID) {
1337 $url = self::getFileURL($contactID, $fieldID, $value);
1338 if ($url) {
1339 $display = $url['file_url'];
1340 }
1341 }
1342 break;
1343
1344 case 'TextArea':
1345 if (empty($value)) {
1346 $display = '';
1347 }
1348 else {
1349 $display = nl2br($value);
1350 }
1351 break;
1352
1353 case 'Link':
1354 if (empty($value)) {
1355 $display = '';
1356 }
1357 else {
1358 $display = $value;
1359 }
1360 }
1361 return $display ? $display : $value;
1362 }
1363
1364 /**
1365 * Set default values for custom data used in profile
1366 *
1367 * @param int $customFieldId
1368 * Custom field id.
1369 * @param string $elementName
1370 * Custom field name.
1371 * @param array $defaults
1372 * Associated array of fields.
1373 * @param int $contactId
1374 * Contact id.
1375 * @param int $mode
1376 * Profile mode.
1377 * @param mixed $value
1378 * If passed - dont fetch value from db,.
1379 * just format the given value
1380 *
1381 * @static
1382 */
1383 static function setProfileDefaults(
1384 $customFieldId,
1385 $elementName,
1386 &$defaults,
1387 $contactId = NULL,
1388 $mode = NULL,
1389 $value = NULL
1390 ) {
1391 //get the type of custom field
1392 $customField = new CRM_Core_BAO_CustomField();
1393 $customField->id = $customFieldId;
1394 $customField->find(TRUE);
1395
1396 if (!$contactId) {
1397 if ($mode == CRM_Profile_Form::MODE_CREATE) {
1398 $value = $customField->default_value;
1399 }
1400 }
1401 else {
1402 if (!isset($value)) {
1403 $info = self::getTableColumnGroup($customFieldId);
1404 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1405 $result = CRM_Core_DAO::executeQuery($query);
1406 if ($result->fetch()) {
1407 $value = $result->value;
1408 }
1409 }
1410
1411 if ($customField->data_type == 'Country') {
1412 if (!$value) {
1413 $config = CRM_Core_Config::singleton();
1414 if ($config->defaultContactCountry) {
1415 $value = $config->defaultContactCountry();
1416 }
1417 }
1418 }
1419 }
1420
1421 //set defaults if mode is registration
1422 if (!trim($value) &&
1423 ($value !== 0) &&
1424 (!in_array($mode, array(CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH)))
1425 ) {
1426 $value = $customField->default_value;
1427 }
1428
1429 if ($customField->data_type == 'Money' && isset($value)) {
1430 $value = number_format($value, 2);
1431 }
1432 switch ($customField->html_type) {
1433 case 'CheckBox':
1434 case 'AdvMulti-Select':
1435 case 'Multi-Select':
1436 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldId, FALSE);
1437 $defaults[$elementName] = array();
1438 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1439 substr($value, 1, -1)
1440 );
1441 foreach ($customOption as $val) {
1442 if (in_array($val['value'], $checkedValue)) {
1443 if ($customField->html_type == 'CheckBox') {
1444 $defaults[$elementName][$val['value']] = 1;
1445 }
1446 elseif ($customField->html_type == 'Multi-Select' ||
1447 $customField->html_type == 'AdvMulti-Select'
1448 ) {
1449 $defaults[$elementName][$val['value']] = $val['value'];
1450 }
1451 }
1452 }
1453 break;
1454
1455 case 'Select Date':
1456 if ($value) {
1457 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date::setDateDefaults(
1458 $value,
1459 NULL,
1460 $customField->date_format,
1461 $customField->time_format
1462 );
1463 }
1464 break;
1465
1466 case 'Autocomplete-Select':
1467 if ($customField->data_type == 'ContactReference') {
1468 if (is_numeric($value)) {
1469 $defaults[$elementName . '_id'] = $value;
1470 $defaults[$elementName] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1471 }
1472 }
1473 else {
1474 $defaults[$elementName] = $value;
1475 }
1476 break;
1477
1478 default:
1479 $defaults[$elementName] = $value;
1480 }
1481 }
1482
1483 /**
1484 * @param int $contactID
1485 * @param int $cfID
1486 * @param int $fileID
1487 * @param bool $absolute
1488 *
1489 * @return array
1490 */
1491 /**
1492 * @param int $contactID
1493 * @param int $cfID
1494 * @param int $fileID
1495 * @param bool $absolute
1496 *
1497 * @return array
1498 */
1499 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1500 if ($contactID) {
1501 if (!$fileID) {
1502 $params = array('id' => $cfID);
1503 $defaults = array();
1504 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1505 $columnName = $defaults['column_name'];
1506
1507 //table name of custom data
1508 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
1509 $defaults['custom_group_id'],
1510 'table_name', 'id'
1511 );
1512
1513 //query to fetch id from civicrm_file
1514 if ($multiRecordWhereClause) {
1515 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1516 }
1517 else {
1518 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1519 }
1520 $fileID = CRM_Core_DAO::singleValueQuery($query);
1521 }
1522
1523 $result = array();
1524 if ($fileID) {
1525 $fileType = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1526 $fileID,
1527 'mime_type',
1528 'id'
1529 );
1530 $result['file_id'] = $fileID;
1531
1532 if ($fileType == 'image/jpeg' ||
1533 $fileType == 'image/pjpeg' ||
1534 $fileType == 'image/gif' ||
1535 $fileType == 'image/x-png' ||
1536 $fileType == 'image/png'
1537 ) {
1538 $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile',
1539 $fileID,
1540 'entity_id',
1541 'id'
1542 );
1543 list($path) = CRM_Core_BAO_File::path($fileID, $entityId, NULL, NULL);
1544 list($imageWidth, $imageHeight) = getimagesize($path);
1545 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
1546 $url = CRM_Utils_System::url('civicrm/file',
1547 "reset=1&id=$fileID&eid=$contactID",
1548 $absolute, NULL, TRUE, TRUE
1549 );
1550 $result['file_url'] = "
1551 <a href=\"$url\" class='crm-image-popup'>
1552 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1553 </a>";
1554 // for non image files
1555 }
1556 else {
1557 $uri = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1558 $fileID,
1559 'uri'
1560 );
1561 $url = CRM_Utils_System::url('civicrm/file',
1562 "reset=1&id=$fileID&eid=$contactID",
1563 $absolute, NULL, TRUE, TRUE
1564 );
1565 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1566 }
1567 }
1568 return $result;
1569 }
1570 }
1571
1572 /**
1573 * Format custom fields before inserting
1574 *
1575 * @param int $customFieldId
1576 * Custom field id.
1577 * @param array $customFormatted
1578 * Formatted array.
1579 * @param mix $value
1580 * Value of custom field.
1581 * @param string $customFieldExtend
1582 * Custom field extends.
1583 * @param int $customValueId
1584 * Custom option value id.
1585 * @param int $entityId
1586 * Entity id (contribution, membership...).
1587 * @param bool $inline
1588 * Consider inline custom groups only.
1589 * @param bool $checkPermission
1590 * If false, do not include permissioning clause.
1591 * @param bool $includeViewOnly
1592 * If true, fields marked 'View Only' are included. Required for APIv3.
1593 *
1594 * @return array
1595 * formatted custom field array
1596 * @static
1597 */
1598 static function formatCustomField(
1599 $customFieldId, &$customFormatted, $value,
1600 $customFieldExtend, $customValueId = NULL,
1601 $entityId = NULL,
1602 $inline = FALSE,
1603 $checkPermission = TRUE,
1604 $includeViewOnly = FALSE
1605 ) {
1606 //get the custom fields for the entity
1607 //subtype and basic type
1608 $customDataSubType = NULL;
1609 if (is_array($customFieldExtend)) {
1610 $customFieldExtend = $customFieldExtend[0];
1611 }
1612
1613 if (in_array($customFieldExtend,
1614 CRM_Contact_BAO_ContactType::subTypes()
1615 )) {
1616 // This is the case when getFieldsForImport() requires fields
1617 // of subtype and its parent.CRM-5143
1618 $customDataSubType = $customFieldExtend;
1619 $customFieldExtend = CRM_Contact_BAO_ContactType::getBasicType($customDataSubType);
1620 }
1621
1622 $customFields = CRM_Core_BAO_CustomField::getFields($customFieldExtend,
1623 FALSE,
1624 $inline,
1625 $customDataSubType,
1626 NULL,
1627 FALSE,
1628 FALSE,
1629 $checkPermission
1630 );
1631
1632 if (!array_key_exists($customFieldId, $customFields)) {
1633 return;
1634 }
1635
1636 // return if field is a 'code' field
1637 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1638 return;
1639 }
1640
1641 list($tableName, $columnName, $groupID) = self::getTableColumnGroup($customFieldId);
1642
1643 if (!$customValueId &&
1644 // we always create new entites for is_multiple unless specified
1645 !$customFields[$customFieldId]['is_multiple'] &&
1646 $entityId
1647 ) {
1648 $query = "
1649 SELECT id
1650 FROM $tableName
1651 WHERE entity_id={$entityId}";
1652
1653 $customValueId = CRM_Core_DAO::singleValueQuery($query);
1654 }
1655
1656 //fix checkbox, now check box always submits values
1657 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1658 if ($value) {
1659 // Note that only during merge this is not an array, and you can directly use value
1660 if (is_array($value)) {
1661 $selectedValues = array();
1662 foreach ($value as $selId => $val) {
1663 if ($val) {
1664 $selectedValues[] = $selId;
1665 }
1666 }
1667 if (!empty($selectedValues)) {
1668 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1669 $selectedValues
1670 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1671 }
1672 else {
1673 $value = '';
1674 }
1675 }
1676 }
1677 }
1678
1679 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1680 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1681 ) {
1682 if ($value) {
1683 // Note that only during merge this is not an array,
1684 // and you can directly use value, CRM-4385
1685 if (is_array($value)) {
1686 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1687 array_values($value)
1688 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1689 }
1690 }
1691 else {
1692 $value = '';
1693 }
1694 }
1695
1696 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1697 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1698 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1699 ) &&
1700 $customFields[$customFieldId]['data_type'] == 'String' &&
1701 !empty($customFields[$customFieldId]['text_length']) &&
1702 !empty($value)
1703 ) {
1704 // lets make sure that value is less than the length, else we'll
1705 // be losing some data, CRM-7481
1706 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1707 // need to do a few things here
1708
1709 // 1. lets find a new length
1710 $newLength = $customFields[$customFieldId]['text_length'];
1711 $minLength = strlen($value);
1712 while ($newLength < $minLength) {
1713 $newLength = $newLength * 2;
1714 }
1715
1716 // set the custom field meta data to have a length larger than value
1717 // alter the custom value table column to match this length
1718 CRM_Core_BAO_SchemaHandler::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1719 }
1720 }
1721
1722 $date = NULL;
1723 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1724 if (!CRM_Utils_System::isNull($value)) {
1725 $format = $customFields[$customFieldId]['date_format'];
1726 $date = CRM_Utils_Date::processDate($value, NULL, FALSE, 'YmdHis', $format);
1727 }
1728 $value = $date;
1729 }
1730
1731 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1732 $customFields[$customFieldId]['data_type'] == 'Money'
1733 ) {
1734 if (!$value) {
1735 $value = 0;
1736 }
1737
1738 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1739 $value = CRM_Utils_Rule::cleanMoney($value);
1740 }
1741 }
1742
1743 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1744 $customFields[$customFieldId]['data_type'] == 'Country'
1745 ) &&
1746 empty($value)
1747 ) {
1748 // CRM-3415
1749 $value = 0;
1750 }
1751
1752 $fileId = NULL;
1753
1754 if ($customFields[$customFieldId]['data_type'] == 'File') {
1755 if (empty($value)) {
1756 return;
1757 }
1758
1759 $config = CRM_Core_Config::singleton();
1760
1761 $fName = $value['name'];
1762 $mimeType = $value['type'];
1763
1764 $filename = pathinfo($fName, PATHINFO_BASENAME);
1765
1766 // rename this file to go into the secure directory
1767 if (!rename($fName, $config->customFileUploadDir . $filename)) {
1768 CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
1769 }
1770
1771 if ($customValueId) {
1772 $query = "
1773 SELECT $columnName
1774 FROM $tableName
1775 WHERE id = %1";
1776 $params = array(1 => array($customValueId, 'Integer'));
1777 $fileId = CRM_Core_DAO::singleValueQuery($query, $params);
1778 }
1779
1780 $fileDAO = new CRM_Core_DAO_File();
1781
1782 if ($fileId) {
1783 $fileDAO->id = $fileId;
1784 }
1785
1786 $fileDAO->uri = $filename;
1787 $fileDAO->mime_type = $mimeType;
1788 $fileDAO->upload_date = date('Ymdhis');
1789 $fileDAO->save();
1790 $fileId = $fileDAO->id;
1791 $value = $filename;
1792 }
1793
1794 if (!is_array($customFormatted)) {
1795 $customFormatted = array();
1796 }
1797
1798 if (!array_key_exists($customFieldId, $customFormatted)) {
1799 $customFormatted[$customFieldId] = array();
1800 }
1801
1802 $index = -1;
1803 if ($customValueId) {
1804 $index = $customValueId;
1805 }
1806
1807 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1808 $customFormatted[$customFieldId][$index] = array();
1809 }
1810 $customFormatted[$customFieldId][$index] = array(
1811 'id' => $customValueId > 0 ? $customValueId : NULL,
1812 'value' => $value,
1813 'type' => $customFields[$customFieldId]['data_type'],
1814 'custom_field_id' => $customFieldId,
1815 'custom_group_id' => $groupID,
1816 'table_name' => $tableName,
1817 'column_name' => $columnName,
1818 'file_id' => $fileId,
1819 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1820 );
1821
1822 //we need to sort so that custom fields are created in the order of entry
1823 krsort($customFormatted[$customFieldId]);
1824 return $customFormatted;
1825 }
1826
1827 /**
1828 * @param array $params
1829 *
1830 * @return array
1831 */
1832 public static function &defaultCustomTableSchema(&$params) {
1833 // add the id and extends_id
1834 $table = array(
1835 'name' => $params['name'],
1836 'is_multiple' => $params['is_multiple'],
1837 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1838 'fields' => array(
1839 array(
1840 'name' => 'id',
1841 'type' => 'int unsigned',
1842 'primary' => TRUE,
1843 'required' => TRUE,
1844 'attributes' => 'AUTO_INCREMENT',
1845 'comment' => 'Default MySQL primary key',
1846 ),
1847 array(
1848 'name' => 'entity_id',
1849 'type' => 'int unsigned',
1850 'required' => TRUE,
1851 'comment' => 'Table that this extends',
1852 'fk_table_name' => $params['extends_name'],
1853 'fk_field_name' => 'id',
1854 'fk_attributes' => 'ON DELETE CASCADE',
1855 ),
1856 ),
1857 );
1858
1859 if (!$params['is_multiple']) {
1860 $table['indexes'] = array(
1861 array(
1862 'unique' => TRUE,
1863 'field_name_1' => 'entity_id',
1864 ),
1865 );
1866 }
1867 return $table;
1868 }
1869
1870 /**
1871 * @param $field
1872 * @param $operation
1873 * @param bool $indexExist
1874 * @param bool $triggerRebuild
1875 */
1876 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1877 $tableName = CRM_Core_DAO::getFieldValue(
1878 'CRM_Core_DAO_CustomGroup',
1879 $field->custom_group_id,
1880 'table_name'
1881 );
1882
1883 $params = array(
1884 'table_name' => $tableName,
1885 'operation' => $operation,
1886 'name' => $field->column_name,
1887 'type' => CRM_Core_BAO_CustomValueTable::fieldToSQLType(
1888 $field->data_type,
1889 $field->text_length
1890 ),
1891 'required' => $field->is_required,
1892 'searchable' => $field->is_searchable,
1893 );
1894
1895 if ($operation == 'delete') {
1896 $fkName = "{$tableName}_{$field->column_name}";
1897 if (strlen($fkName) >= 48) {
1898 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1899 }
1900 $params['fkName'] = $fkName;
1901 }
1902 if ($field->data_type == 'Country' && $field->html_type == 'Select Country') {
1903 $params['fk_table_name'] = 'civicrm_country';
1904 $params['fk_field_name'] = 'id';
1905 $params['fk_attributes'] = 'ON DELETE SET NULL';
1906 }
1907 elseif ($field->data_type == 'Country' && $field->html_type == 'Multi-Select Country') {
1908 $params['type'] = 'varchar(255)';
1909 }
1910 elseif ($field->data_type == 'StateProvince' && $field->html_type == 'Select State/Province') {
1911 $params['fk_table_name'] = 'civicrm_state_province';
1912 $params['fk_field_name'] = 'id';
1913 $params['fk_attributes'] = 'ON DELETE SET NULL';
1914 }
1915 elseif ($field->data_type == 'StateProvince' && $field->html_type == 'Multi-Select State/Province') {
1916 $params['type'] = 'varchar(255)';
1917 }
1918 elseif ($field->data_type == 'File') {
1919 $params['fk_table_name'] = 'civicrm_file';
1920 $params['fk_field_name'] = 'id';
1921 $params['fk_attributes'] = 'ON DELETE SET NULL';
1922 }
1923 elseif ($field->data_type == 'ContactReference') {
1924 $params['fk_table_name'] = 'civicrm_contact';
1925 $params['fk_field_name'] = 'id';
1926 $params['fk_attributes'] = 'ON DELETE SET NULL';
1927 }
1928 if (isset($field->default_value)) {
1929 $params['default'] = "'{$field->default_value}'";
1930 }
1931
1932 CRM_Core_BAO_SchemaHandler::alterFieldSQL($params, $indexExist, $triggerRebuild);
1933 }
1934
1935 /**
1936 * Determine whether it would be safe to move a field
1937 *
1938 * @param int $fieldID
1939 * FK to civicrm_custom_field.
1940 * @param int $newGroupID
1941 * FK to civicrm_custom_group.
1942 *
1943 * @return array(
1944 * string) or TRUE
1945 */
1946 public static function _moveFieldValidate($fieldID, $newGroupID) {
1947 $errors = array();
1948
1949 $field = new CRM_Core_DAO_CustomField();
1950 $field->id = $fieldID;
1951 if (!$field->find(TRUE)) {
1952 $errors['fieldID'] = 'Invalid ID for custom field';
1953 return $errors;
1954 }
1955
1956 $oldGroup = new CRM_Core_DAO_CustomGroup();
1957 $oldGroup->id = $field->custom_group_id;
1958 if (!$oldGroup->find(TRUE)) {
1959 $errors['fieldID'] = 'Invalid ID for old custom group';
1960 return $errors;
1961 }
1962
1963 $newGroup = new CRM_Core_DAO_CustomGroup();
1964 $newGroup->id = $newGroupID;
1965 if (!$newGroup->find(TRUE)) {
1966 $errors['newGroupID'] = 'Invalid ID for new custom group';
1967 return $errors;
1968 }
1969
1970 $query = "
1971 SELECT b.id
1972 FROM civicrm_custom_field a
1973 INNER JOIN civicrm_custom_field b
1974 WHERE a.id = %1
1975 AND a.label = b.label
1976 AND b.custom_group_id = %2
1977 ";
1978 $params = array(
1979 1 => array($field->id, 'Integer'),
1980 2 => array($newGroup->id, 'Integer'),
1981 );
1982 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1983 if ($count > 0) {
1984 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1985 }
1986
1987 $tableName = $oldGroup->table_name;
1988 $columnName = $field->column_name;
1989
1990 $query = "
1991 SELECT count(*)
1992 FROM $tableName
1993 WHERE $columnName is not null
1994 ";
1995 $count = CRM_Core_DAO::singleValueQuery($query,
1996 CRM_Core_DAO::$_nullArray
1997 );
1998 if ($count > 0) {
1999 $query = "
2000 SELECT extends
2001 FROM civicrm_custom_group
2002 WHERE id IN ( %1, %2 )
2003 ";
2004 $params = array(
2005 1 => array($oldGroup->id, 'Integer'),
2006 2 => array($newGroup->id, 'Integer'),
2007 );
2008
2009 $dao = CRM_Core_DAO::executeQuery($query, $params);
2010 $extends = array();
2011 while ($dao->fetch()) {
2012 $extends[] = $dao->extends;
2013 }
2014 if ($extends[0] != $extends[1]) {
2015 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
2016 }
2017 }
2018
2019 return empty($errors) ? TRUE : $errors;
2020 }
2021
2022 /**
2023 * Move a custom data field from one group (table) to another
2024 *
2025 * @param int $fieldID
2026 * FK to civicrm_custom_field.
2027 * @param int $newGroupID
2028 * FK to civicrm_custom_group.
2029 *
2030 * @return void
2031 */
2032 public static function moveField($fieldID, $newGroupID) {
2033 $validation = self::_moveFieldValidate($fieldID, $newGroupID);
2034 if (TRUE !== $validation) {
2035 CRM_Core_Error::fatal(implode(' ', $validation));
2036 }
2037 $field = new CRM_Core_DAO_CustomField();
2038 $field->id = $fieldID;
2039 $field->find(TRUE);
2040
2041 $newGroup = new CRM_Core_DAO_CustomGroup();
2042 $newGroup->id = $newGroupID;
2043 $newGroup->find(TRUE);
2044
2045 $oldGroup = new CRM_Core_DAO_CustomGroup();
2046 $oldGroup->id = $field->custom_group_id;
2047 $oldGroup->find(TRUE);
2048
2049 $add = clone$field;
2050 $add->custom_group_id = $newGroup->id;
2051 self::createField($add, 'add');
2052
2053 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
2054 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
2055 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
2056 ";
2057 CRM_Core_DAO::executeQuery($sql);
2058
2059 $del = clone$field;
2060 $del->custom_group_id = $oldGroup->id;
2061 self::createField($del, 'delete');
2062
2063 $add->save();
2064
2065 CRM_Utils_System::flushCache();
2066 }
2067
2068 /**
2069 * Get the database table name and column name for a custom field
2070 *
2071 * @param int $fieldID
2072 * The fieldID of the custom field.
2073 * @param bool $force
2074 * Force the sql to be run again (primarily used for tests).
2075 *
2076 * @return array
2077 * fatal is fieldID does not exists, else array of tableName, columnName
2078 * @static
2079 */
2080 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2081 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2082 $cache = CRM_Utils_Cache::singleton();
2083 $fieldValues = $cache->get($cacheKey);
2084 if (empty($fieldValues) || $force) {
2085 $query = "
2086 SELECT cg.table_name, cf.column_name, cg.id
2087 FROM civicrm_custom_group cg,
2088 civicrm_custom_field cf
2089 WHERE cf.custom_group_id = cg.id
2090 AND cf.id = %1";
2091 $params = array(1 => array($fieldID, 'Integer'));
2092 $dao = CRM_Core_DAO::executeQuery($query, $params);
2093
2094 if (!$dao->fetch()) {
2095 CRM_Core_Error::fatal();
2096 }
2097 $dao->free();
2098 $fieldValues = array($dao->table_name, $dao->column_name, $dao->id);
2099 $cache->set($cacheKey, $fieldValues);
2100 }
2101 return $fieldValues;
2102 }
2103
2104 /**
2105 * Get custom option groups
2106 *
2107 * @param array $includeFieldIds
2108 * Ids of custom fields for which.
2109 * option groups must be included.
2110 *
2111 * Currently this is required in the cases where option groups are to be included
2112 * for inactive fields : CRM-5369
2113 *
2114 *
2115 * @return mixed $customOptionGroup
2116 * @static
2117 */
2118 public static function &customOptionGroup($includeFieldIds = NULL) {
2119 static $customOptionGroup = NULL;
2120
2121 $cacheKey = (empty($includeFieldIds)) ? 'onlyActive' : 'force';
2122 if ($cacheKey == 'force') {
2123 $customOptionGroup[$cacheKey] = NULL;
2124 }
2125
2126 if (empty($customOptionGroup[$cacheKey])) {
2127 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2128
2129 //support for single as well as array format.
2130 if (!empty($includeFieldIds)) {
2131 if (is_array($includeFieldIds)) {
2132 $includeFieldIds = implode(',', $includeFieldIds);
2133 }
2134 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2135 }
2136
2137 $query = "
2138 SELECT g.id, g.title
2139 FROM civicrm_option_group g
2140 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2141 WHERE {$whereClause}";
2142
2143 $dao = CRM_Core_DAO::executeQuery($query);
2144 while ($dao->fetch()) {
2145 $customOptionGroup[$cacheKey][$dao->id] = $dao->title;
2146 }
2147 }
2148
2149 return $customOptionGroup[$cacheKey];
2150 }
2151
2152 /**
2153 * Fix orphan groups
2154 *
2155 * @param int $customFieldId
2156 * Custom field id.
2157 * @param int $optionGroupId
2158 * Option group id.
2159 *
2160 * @return void
2161 * @static
2162 */
2163 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2164 // check if option group belongs to any custom Field else delete
2165 // get the current option group
2166 $currentOptionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
2167 $customFieldId,
2168 'option_group_id'
2169 );
2170 // get the updated option group
2171 // if both are same return
2172 if ($currentOptionGroupId == $optionGroupId) {
2173 return;
2174 }
2175
2176 // check if option group is related to any other field
2177 self::checkOptionGroup($currentOptionGroupId);
2178 }
2179
2180 /**
2181 * Check if option group is related to more than one
2182 * custom field
2183 *
2184 * @param int $optionGroupId
2185 * Option group id.
2186 *
2187 * @return void
2188 * @static
2189 */
2190 public static function checkOptionGroup($optionGroupId) {
2191 $query = "
2192 SELECT count(*)
2193 FROM civicrm_custom_field
2194 WHERE option_group_id = {$optionGroupId}";
2195
2196 $count = CRM_Core_DAO::singleValueQuery($query);
2197
2198 if ($count < 2) {
2199 //delete the option group
2200 CRM_Core_BAO_OptionGroup::del($optionGroupId);
2201 }
2202 }
2203
2204 /**
2205 * @param int $optionGroupId
2206 * @param $htmlType
2207 *
2208 * @return null|string
2209 */
2210 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2211 $query = "
2212 SELECT default_value, html_type
2213 FROM civicrm_custom_field
2214 WHERE option_group_id = {$optionGroupId}
2215 AND default_value IS NOT NULL
2216 ORDER BY html_type";
2217
2218 $dao = CRM_Core_DAO::executeQuery($query);
2219 $defaultValue = NULL;
2220 $defaultHTMLType = NULL;
2221 while ($dao->fetch()) {
2222 if ($dao->html_type == $htmlType) {
2223 return $dao->default_value;
2224 }
2225 if ($defaultValue == NULL) {
2226 $defaultValue = $dao->default_value;
2227 $defaultHTMLType = $dao->html_type;
2228 }
2229 }
2230
2231 // some conversions are needed if either the old or new has a html type which has potential
2232 // multiple default values.
2233 if (($htmlType == 'CheckBox' || $htmlType == 'Multi-Select') &&
2234 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2235 ) {
2236 $defaultValue = CRM_Core_DAO::VALUE_SEPARATOR . $defaultValue . CRM_Core_DAO::VALUE_SEPARATOR;
2237 }
2238 elseif (($defaultHTMLType == 'CheckBox' || $defaultHTMLType == 'Multi-Select') &&
2239 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2240 ) {
2241 $defaultValue = substr($defaultValue, 1, -1);
2242 $values = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2243 substr($defaultValue, 1, -1)
2244 );
2245 $defaultValue = $values[0];
2246 }
2247
2248 return $defaultValue;
2249 }
2250
2251 /**
2252 * @param array $params
2253 * @param $customFields
2254 * @param int $entityID
2255 * @param $customFieldExtends
2256 * @param bool $inline
2257 *
2258 * @return array
2259 */
2260 static function postProcess(
2261 &$params,
2262 &$customFields,
2263 $entityID,
2264 $customFieldExtends,
2265 $inline = FALSE
2266 ) {
2267 $customData = array();
2268
2269 foreach ($params as $key => $value) {
2270 if ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($key, TRUE)) {
2271
2272 // for autocomplete transfer hidden value instead of label
2273 if ($params[$key] && isset($params[$key . '_id'])) {
2274 $value = $params[$key . '_id'];
2275 }
2276
2277 // we need to append time with date
2278 if ($params[$key] && isset($params[$key . '_time'])) {
2279 $value .= ' ' . $params[$key . '_time'];
2280 }
2281
2282 CRM_Core_BAO_CustomField::formatCustomField($customFieldInfo[0],
2283 $customData,
2284 $value,
2285 $customFieldExtends,
2286 $customFieldInfo[1],
2287 $entityID,
2288 $inline
2289 );
2290 }
2291 }
2292 return $customData;
2293 }
2294
2295 /**
2296 * @param $field
2297 * @param $options
2298 *
2299 * @throws Exception
2300 */
2301 public static function buildOption($field, &$options) {
2302 // Fixme - adding anything but options to the $options array is a bad idea
2303 // What if an option had the key 'attributes'?
2304 $options['attributes'] = array(
2305 'label' => $field['label'],
2306 'data_type' => $field['data_type'],
2307 'html_type' => $field['html_type'],
2308 );
2309
2310 $optionGroupID = NULL;
2311 if (($field['html_type'] == 'CheckBox' ||
2312 $field['html_type'] == 'Radio' ||
2313 $field['html_type'] == 'Select' ||
2314 $field['html_type'] == 'AdvMulti-Select' ||
2315 $field['html_type'] == 'Multi-Select' ||
2316 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2317 )
2318 ) {
2319 if ($field['option_group_id']) {
2320 $optionGroupID = $field['option_group_id'];
2321 }
2322 elseif ($field['data_type'] != 'Boolean') {
2323 CRM_Core_Error::fatal();
2324 }
2325 }
2326
2327 // build the cache for custom values with options (label => value)
2328 if ($optionGroupID != NULL) {
2329 $query = "
2330 SELECT label, value
2331 FROM civicrm_option_value
2332 WHERE option_group_id = $optionGroupID
2333 ";
2334
2335 $dao = CRM_Core_DAO::executeQuery($query);
2336 while ($dao->fetch()) {
2337 if ($field['data_type'] == 'Int' || $field['data_type'] == 'Float') {
2338 $num = round($dao->value, 2);
2339 $options["$num"] = $dao->label;
2340 }
2341 else {
2342 $options[$dao->value] = $dao->label;
2343 }
2344 }
2345
2346 CRM_Utils_Hook::customFieldOptions($field['id'], $options);
2347 }
2348 }
2349
2350 /**
2351 * @param $fieldLabel
2352 * @param null $groupTitle
2353 *
2354 * @return null
2355 */
2356 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2357 $params = array(1 => array($fieldLabel, 'String'));
2358 if ($groupTitle) {
2359 $params[2] = array($groupTitle, 'String');
2360 $sql = "
2361 SELECT f.id
2362 FROM civicrm_custom_field f
2363 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2364 WHERE ( f.label = %1 OR f.name = %1 )
2365 AND ( g.title = %2 OR g.name = %2 )
2366 ";
2367 }
2368 else {
2369 $sql = "
2370 SELECT f.id
2371 FROM civicrm_custom_field f
2372 WHERE ( f.label = %1 OR f.name = %1 )
2373 ";
2374 }
2375
2376 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2377 if ($dao->fetch() &&
2378 $dao->N == 1
2379 ) {
2380 return $dao->id;
2381 }
2382 else {
2383 return NULL;
2384 }
2385 }
2386
2387 /**
2388 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2389 */
2390 public static function getNameFromID($ids) {
2391 if (is_array($ids)) {
2392 $ids = implode(',', $ids);
2393 }
2394 $sql = "
2395 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2396 FROM civicrm_custom_field f
2397 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2398 WHERE f.id IN ($ids)";
2399
2400 $dao = CRM_Core_DAO::executeQuery($sql);
2401 $result = array();
2402 while ($dao->fetch()) {
2403 $result[$dao->id] = array(
2404 'field_name' => $dao->field_name,
2405 'field_label' => $dao->field_label,
2406 'group_name' => $dao->group_name,
2407 'group_title' => $dao->group_title,
2408 );
2409 }
2410 return $result;
2411 }
2412
2413 /**
2414 * Validate custom data.
2415 *
2416 * @param array $params
2417 * Custom data submitted.
2418 * ie array( 'custom_1' => 'validate me' );
2419 *
2420 * @return array
2421 * validation errors.
2422 * @static
2423 */
2424 public static function validateCustomData($params) {
2425 $errors = array();
2426 if (!is_array($params) || empty($params)) {
2427 return $errors;
2428 }
2429
2430 //pick up profile fields.
2431 $profileFields = array();
2432 $ufGroupId = CRM_Utils_Array::value('ufGroupId', $params);
2433 if ($ufGroupId) {
2434 $profileFields = CRM_Core_BAO_UFGroup::getFields($ufGroupId,
2435 FALSE,
2436 CRM_Core_Action::VIEW
2437 );
2438 }
2439
2440 //lets start w/ params.
2441 foreach ($params as $key => $value) {
2442 $customFieldID = self::getKeyID($key);
2443 if (!$customFieldID) {
2444 continue;
2445 }
2446
2447 //load the structural info for given field.
2448 $field = new CRM_Core_DAO_CustomField();
2449 $field->id = $customFieldID;
2450 if (!$field->find(TRUE)) {
2451 continue;
2452 }
2453 $dataType = $field->data_type;
2454
2455 $profileField = CRM_Utils_Array::value($key, $profileFields, array());
2456 $fieldTitle = CRM_Utils_Array::value('title', $profileField);
2457 $isRequired = CRM_Utils_Array::value('is_required', $profileField);
2458 if (!$fieldTitle) {
2459 $fieldTitle = $field->label;
2460 }
2461
2462 //no need to validate.
2463 if (CRM_Utils_System::isNull($value) && !$isRequired) {
2464 continue;
2465 }
2466
2467 //lets validate first for required field.
2468 if ($isRequired && CRM_Utils_System::isNull($value)) {
2469 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2470 continue;
2471 }
2472
2473 //now time to take care of custom field form rules.
2474 $ruleName = $errorMsg = NULL;
2475 switch ($dataType) {
2476 case 'Int':
2477 $ruleName = 'integer';
2478 $errorMsg = ts('%1 must be an integer (whole number).',
2479 array(1 => $fieldTitle)
2480 );
2481 break;
2482
2483 case 'Money':
2484 $ruleName = 'money';
2485 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2486 array(1 => $fieldTitle)
2487 );
2488 break;
2489
2490 case 'Float':
2491 $ruleName = 'numeric';
2492 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2493 array(1 => $fieldTitle)
2494 );
2495 break;
2496
2497 case 'Link':
2498 $ruleName = 'wikiURL';
2499 $errorMsg = ts('%1 must be valid Website.',
2500 array(1 => $fieldTitle)
2501 );
2502 break;
2503 }
2504
2505 if ($ruleName && !CRM_Utils_System::isNull($value)) {
2506 $valid = FALSE;
2507 $funName = "CRM_Utils_Rule::{$ruleName}";
2508 if (is_callable($funName)) {
2509 $valid = call_user_func($funName, $value);
2510 }
2511 if (!$valid) {
2512 $errors[$key] = $errorMsg;
2513 }
2514 }
2515 }
2516
2517 return $errors;
2518 }
2519
2520 /**
2521 * @param int $customId
2522 *
2523 * @return bool
2524 */
2525 public static function isMultiRecordField($customId) {
2526 $isMultipleWithGid = FALSE;
2527 if (!is_numeric($customId)) {
2528 $customId = self::getKeyID($customId);
2529 }
2530 if (is_numeric($customId)) {
2531 $sql = "SELECT cg.id cgId
2532 FROM civicrm_custom_group cg
2533 INNER JOIN civicrm_custom_field cf
2534 ON cg.id = cf.custom_group_id
2535 WHERE cf.id = %1 AND cg.is_multiple = 1";
2536 $params[1] = array($customId, 'Integer');
2537 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2538 if ($dao->fetch()) {
2539 if ($dao->cgId) {
2540 $isMultipleWithGid = $dao->cgId;
2541 }
2542 }
2543 }
2544
2545 return $isMultipleWithGid;
2546 }
2547
2548 /**
2549 * Does this field store a serialized string?
2550 * @param CRM_Core_DAO_CustomField|array $field
2551 * @return bool
2552 */
2553 public static function isSerialized($field) {
2554 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2555 $field = (array) $field;
2556 // 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.
2557 return ($field['html_type'] == 'CheckBox' || strpos($field['html_type'], 'Multi') !== FALSE);
2558 }
2559 }