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