ae9c4023a18b806875c4058d6ceb543267825567
[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 $entityId
1144 *
1145 * @return string
1146 */
1147 private static function formatDisplayValue($value, $field, $entityId = 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 ($value) {
1221 if ($entityId) {
1222 $url = self::getFileURL($entityId, $field['id']);
1223 if ($url) {
1224 $display = $url['file_url'];
1225 }
1226 }
1227 else {
1228 // In other contexts show a paperclip icon
1229 $icons = CRM_Core_BAO_File::paperIconAttachment('*', $value);
1230 $display = $icons[$value];
1231 }
1232 }
1233 break;
1234
1235 case 'TextArea':
1236 $display = nl2br($display);
1237 break;
1238 }
1239 return $display;
1240 }
1241
1242 /**
1243 * Set default values for custom data used in profile.
1244 *
1245 * @param int $customFieldId
1246 * Custom field id.
1247 * @param string $elementName
1248 * Custom field name.
1249 * @param array $defaults
1250 * Associated array of fields.
1251 * @param int $contactId
1252 * Contact id.
1253 * @param int $mode
1254 * Profile mode.
1255 * @param mixed $value
1256 * If passed - dont fetch value from db,.
1257 * just format the given value
1258 */
1259 public static function setProfileDefaults(
1260 $customFieldId,
1261 $elementName,
1262 &$defaults,
1263 $contactId = NULL,
1264 $mode = NULL,
1265 $value = NULL
1266 ) {
1267 //get the type of custom field
1268 $customField = new CRM_Core_BAO_CustomField();
1269 $customField->id = $customFieldId;
1270 $customField->find(TRUE);
1271
1272 if (!$contactId) {
1273 if ($mode == CRM_Profile_Form::MODE_CREATE) {
1274 $value = $customField->default_value;
1275 }
1276 }
1277 else {
1278 if (!isset($value)) {
1279 $info = self::getTableColumnGroup($customFieldId);
1280 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1281 $result = CRM_Core_DAO::executeQuery($query);
1282 if ($result->fetch()) {
1283 $value = $result->value;
1284 }
1285 }
1286
1287 if ($customField->data_type == 'Country') {
1288 if (!$value) {
1289 $config = CRM_Core_Config::singleton();
1290 if ($config->defaultContactCountry) {
1291 $value = $config->defaultContactCountry();
1292 }
1293 }
1294 }
1295 }
1296
1297 //set defaults if mode is registration
1298 if (!trim($value) &&
1299 ($value !== 0) &&
1300 (!in_array($mode, array(CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH)))
1301 ) {
1302 $value = $customField->default_value;
1303 }
1304
1305 if ($customField->data_type == 'Money' && isset($value)) {
1306 $value = number_format($value, 2);
1307 }
1308 switch ($customField->html_type) {
1309 case 'CheckBox':
1310 case 'AdvMulti-Select':
1311 case 'Multi-Select':
1312 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldId, FALSE);
1313 $defaults[$elementName] = array();
1314 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1315 substr($value, 1, -1)
1316 );
1317 foreach ($customOption as $val) {
1318 if (in_array($val['value'], $checkedValue)) {
1319 if ($customField->html_type == 'CheckBox') {
1320 $defaults[$elementName][$val['value']] = 1;
1321 }
1322 elseif ($customField->html_type == 'Multi-Select' ||
1323 $customField->html_type == 'AdvMulti-Select'
1324 ) {
1325 $defaults[$elementName][$val['value']] = $val['value'];
1326 }
1327 }
1328 }
1329 break;
1330
1331 case 'Autocomplete-Select':
1332 if ($customField->data_type == 'ContactReference') {
1333 if (is_numeric($value)) {
1334 $defaults[$elementName . '_id'] = $value;
1335 $defaults[$elementName] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1336 }
1337 }
1338 else {
1339 $defaults[$elementName] = $value;
1340 }
1341 break;
1342
1343 default:
1344 $defaults[$elementName] = $value;
1345 }
1346 }
1347
1348 /**
1349 * Get file url.
1350 *
1351 * @param int $contactID
1352 * @param int $cfID
1353 * @param int $fileID
1354 * @param bool $absolute
1355 *
1356 * @param string $multiRecordWhereClause
1357 *
1358 * @return array
1359 */
1360 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1361 if ($contactID) {
1362 if (!$fileID) {
1363 $params = array('id' => $cfID);
1364 $defaults = array();
1365 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1366 $columnName = $defaults['column_name'];
1367
1368 //table name of custom data
1369 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
1370 $defaults['custom_group_id'],
1371 'table_name', 'id'
1372 );
1373
1374 //query to fetch id from civicrm_file
1375 if ($multiRecordWhereClause) {
1376 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1377 }
1378 else {
1379 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1380 }
1381 $fileID = CRM_Core_DAO::singleValueQuery($query);
1382 }
1383
1384 $result = array();
1385 if ($fileID) {
1386 $fileType = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1387 $fileID,
1388 'mime_type',
1389 'id'
1390 );
1391 $result['file_id'] = $fileID;
1392
1393 if ($fileType == 'image/jpeg' ||
1394 $fileType == 'image/pjpeg' ||
1395 $fileType == 'image/gif' ||
1396 $fileType == 'image/x-png' ||
1397 $fileType == 'image/png'
1398 ) {
1399 $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile',
1400 $fileID,
1401 'entity_id',
1402 'id'
1403 );
1404 list($path) = CRM_Core_BAO_File::path($fileID, $entityId, NULL, NULL);
1405 list($imageWidth, $imageHeight) = getimagesize($path);
1406 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
1407 $url = CRM_Utils_System::url('civicrm/file',
1408 "reset=1&id=$fileID&eid=$contactID",
1409 $absolute, NULL, TRUE, TRUE
1410 );
1411 $result['file_url'] = "
1412 <a href=\"$url\" class='crm-image-popup'>
1413 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1414 </a>";
1415 // for non image files
1416 }
1417 else {
1418 $uri = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1419 $fileID,
1420 'uri'
1421 );
1422 $url = CRM_Utils_System::url('civicrm/file',
1423 "reset=1&id=$fileID&eid=$contactID",
1424 $absolute, NULL, TRUE, TRUE
1425 );
1426 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1427 }
1428 }
1429 return $result;
1430 }
1431 }
1432
1433 /**
1434 * Format custom fields before inserting.
1435 *
1436 * @param int $customFieldId
1437 * Custom field id.
1438 * @param array $customFormatted
1439 * Formatted array.
1440 * @param mixed $value
1441 * Value of custom field.
1442 * @param string $customFieldExtend
1443 * Custom field extends.
1444 * @param int $customValueId
1445 * Custom option value id.
1446 * @param int $entityId
1447 * Entity id (contribution, membership...).
1448 * @param bool $inline
1449 * Consider inline custom groups only.
1450 * @param bool $checkPermission
1451 * If false, do not include permissioning clause.
1452 * @param bool $includeViewOnly
1453 * If true, fields marked 'View Only' are included. Required for APIv3.
1454 *
1455 * @return array|NULL
1456 * formatted custom field array
1457 */
1458 public static function formatCustomField(
1459 $customFieldId, &$customFormatted, $value,
1460 $customFieldExtend, $customValueId = NULL,
1461 $entityId = NULL,
1462 $inline = FALSE,
1463 $checkPermission = TRUE,
1464 $includeViewOnly = FALSE
1465 ) {
1466 //get the custom fields for the entity
1467 //subtype and basic type
1468 $customDataSubType = NULL;
1469 if ($customFieldExtend) {
1470 // This is the case when getFieldsForImport() requires fields
1471 // of subtype and its parent.CRM-5143
1472 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1473 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType::subTypes(), (array) $customFieldExtend);
1474 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1475 $customFieldExtend = CRM_Contact_BAO_ContactType::getBasicType($customDataSubType);
1476 if (is_array($customFieldExtend)) {
1477 $customFieldExtend = array_unique(array_values($customFieldExtend));
1478 }
1479 }
1480 }
1481
1482 $customFields = CRM_Core_BAO_CustomField::getFields($customFieldExtend,
1483 FALSE,
1484 $inline,
1485 $customDataSubType,
1486 NULL,
1487 FALSE,
1488 FALSE,
1489 $checkPermission
1490 );
1491
1492 if (!array_key_exists($customFieldId, $customFields)) {
1493 return NULL;
1494 }
1495
1496 // return if field is a 'code' field
1497 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1498 return NULL;
1499 }
1500
1501 list($tableName, $columnName, $groupID) = self::getTableColumnGroup($customFieldId);
1502
1503 if (!$customValueId &&
1504 // we always create new entites for is_multiple unless specified
1505 !$customFields[$customFieldId]['is_multiple'] &&
1506 $entityId
1507 ) {
1508 $query = "
1509 SELECT id
1510 FROM $tableName
1511 WHERE entity_id={$entityId}";
1512
1513 $customValueId = CRM_Core_DAO::singleValueQuery($query);
1514 }
1515
1516 //fix checkbox, now check box always submits values
1517 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1518 if ($value) {
1519 // Note that only during merge this is not an array, and you can directly use value
1520 if (is_array($value)) {
1521 $selectedValues = array();
1522 foreach ($value as $selId => $val) {
1523 if ($val) {
1524 $selectedValues[] = $selId;
1525 }
1526 }
1527 if (!empty($selectedValues)) {
1528 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1529 $selectedValues
1530 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1531 }
1532 else {
1533 $value = '';
1534 }
1535 }
1536 }
1537 }
1538
1539 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1540 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1541 ) {
1542 if ($value) {
1543 $value = CRM_Utils_Array::implodePadded($value);
1544 }
1545 else {
1546 $value = '';
1547 }
1548 }
1549
1550 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1551 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1552 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1553 ) &&
1554 $customFields[$customFieldId]['data_type'] == 'String' &&
1555 !empty($customFields[$customFieldId]['text_length']) &&
1556 !empty($value)
1557 ) {
1558 // lets make sure that value is less than the length, else we'll
1559 // be losing some data, CRM-7481
1560 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1561 // need to do a few things here
1562
1563 // 1. lets find a new length
1564 $newLength = $customFields[$customFieldId]['text_length'];
1565 $minLength = strlen($value);
1566 while ($newLength < $minLength) {
1567 $newLength = $newLength * 2;
1568 }
1569
1570 // set the custom field meta data to have a length larger than value
1571 // alter the custom value table column to match this length
1572 CRM_Core_BAO_SchemaHandler::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1573 }
1574 }
1575
1576 $date = NULL;
1577 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1578 if (!CRM_Utils_System::isNull($value)) {
1579 $format = $customFields[$customFieldId]['date_format'];
1580 $date = CRM_Utils_Date::processDate($value, NULL, FALSE, 'YmdHis', $format);
1581 }
1582 $value = $date;
1583 }
1584
1585 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1586 $customFields[$customFieldId]['data_type'] == 'Money'
1587 ) {
1588 if (!$value) {
1589 $value = 0;
1590 }
1591
1592 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1593 $value = CRM_Utils_Rule::cleanMoney($value);
1594 }
1595 }
1596
1597 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1598 $customFields[$customFieldId]['data_type'] == 'Country'
1599 ) &&
1600 empty($value)
1601 ) {
1602 // CRM-3415
1603 $value = 0;
1604 }
1605
1606 $fileId = NULL;
1607
1608 if ($customFields[$customFieldId]['data_type'] == 'File') {
1609 if (empty($value)) {
1610 return;
1611 }
1612
1613 $config = CRM_Core_Config::singleton();
1614
1615 $fName = $value['name'];
1616 $mimeType = $value['type'];
1617
1618 $filename = pathinfo($fName, PATHINFO_BASENAME);
1619
1620 // rename this file to go into the secure directory
1621 if (!rename($fName, $config->customFileUploadDir . $filename)) {
1622 CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
1623 }
1624
1625 if ($customValueId) {
1626 $query = "
1627 SELECT $columnName
1628 FROM $tableName
1629 WHERE id = %1";
1630 $params = array(1 => array($customValueId, 'Integer'));
1631 $fileId = CRM_Core_DAO::singleValueQuery($query, $params);
1632 }
1633
1634 $fileDAO = new CRM_Core_DAO_File();
1635
1636 if ($fileId) {
1637 $fileDAO->id = $fileId;
1638 }
1639
1640 $fileDAO->uri = $filename;
1641 $fileDAO->mime_type = $mimeType;
1642 $fileDAO->upload_date = date('Ymdhis');
1643 $fileDAO->save();
1644 $fileId = $fileDAO->id;
1645 $value = $filename;
1646 }
1647
1648 if (!is_array($customFormatted)) {
1649 $customFormatted = array();
1650 }
1651
1652 if (!array_key_exists($customFieldId, $customFormatted)) {
1653 $customFormatted[$customFieldId] = array();
1654 }
1655
1656 $index = -1;
1657 if ($customValueId) {
1658 $index = $customValueId;
1659 }
1660
1661 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1662 $customFormatted[$customFieldId][$index] = array();
1663 }
1664 $customFormatted[$customFieldId][$index] = array(
1665 'id' => $customValueId > 0 ? $customValueId : NULL,
1666 'value' => $value,
1667 'type' => $customFields[$customFieldId]['data_type'],
1668 'custom_field_id' => $customFieldId,
1669 'custom_group_id' => $groupID,
1670 'table_name' => $tableName,
1671 'column_name' => $columnName,
1672 'file_id' => $fileId,
1673 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1674 );
1675
1676 //we need to sort so that custom fields are created in the order of entry
1677 krsort($customFormatted[$customFieldId]);
1678 return $customFormatted;
1679 }
1680
1681 /**
1682 * Get default custom table schema.
1683 *
1684 * @param array $params
1685 *
1686 * @return array
1687 */
1688 public static function defaultCustomTableSchema($params) {
1689 // add the id and extends_id
1690 $table = array(
1691 'name' => $params['name'],
1692 'is_multiple' => $params['is_multiple'],
1693 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1694 'fields' => array(
1695 array(
1696 'name' => 'id',
1697 'type' => 'int unsigned',
1698 'primary' => TRUE,
1699 'required' => TRUE,
1700 'attributes' => 'AUTO_INCREMENT',
1701 'comment' => 'Default MySQL primary key',
1702 ),
1703 array(
1704 'name' => 'entity_id',
1705 'type' => 'int unsigned',
1706 'required' => TRUE,
1707 'comment' => 'Table that this extends',
1708 'fk_table_name' => $params['extends_name'],
1709 'fk_field_name' => 'id',
1710 'fk_attributes' => 'ON DELETE CASCADE',
1711 ),
1712 ),
1713 );
1714
1715 if (!$params['is_multiple']) {
1716 $table['indexes'] = array(
1717 array(
1718 'unique' => TRUE,
1719 'field_name_1' => 'entity_id',
1720 ),
1721 );
1722 }
1723 return $table;
1724 }
1725
1726 /**
1727 * Create custom field.
1728 *
1729 * @param CRM_Core_DAO_CustomField $field
1730 * @param string $operation
1731 * @param bool $indexExist
1732 * @param bool $triggerRebuild
1733 */
1734 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1735 $tableName = CRM_Core_DAO::getFieldValue(
1736 'CRM_Core_DAO_CustomGroup',
1737 $field->custom_group_id,
1738 'table_name'
1739 );
1740
1741 $params = array(
1742 'table_name' => $tableName,
1743 'operation' => $operation,
1744 'name' => $field->column_name,
1745 'type' => CRM_Core_BAO_CustomValueTable::fieldToSQLType(
1746 $field->data_type,
1747 $field->text_length
1748 ),
1749 'required' => $field->is_required,
1750 'searchable' => $field->is_searchable,
1751 );
1752
1753 if ($operation == 'delete') {
1754 $fkName = "{$tableName}_{$field->column_name}";
1755 if (strlen($fkName) >= 48) {
1756 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1757 }
1758 $params['fkName'] = $fkName;
1759 }
1760 if ($field->data_type == 'Country' && $field->html_type == 'Select Country') {
1761 $params['fk_table_name'] = 'civicrm_country';
1762 $params['fk_field_name'] = 'id';
1763 $params['fk_attributes'] = 'ON DELETE SET NULL';
1764 }
1765 elseif ($field->data_type == 'Country' && $field->html_type == 'Multi-Select Country') {
1766 $params['type'] = 'varchar(255)';
1767 }
1768 elseif ($field->data_type == 'StateProvince' && $field->html_type == 'Select State/Province') {
1769 $params['fk_table_name'] = 'civicrm_state_province';
1770 $params['fk_field_name'] = 'id';
1771 $params['fk_attributes'] = 'ON DELETE SET NULL';
1772 }
1773 elseif ($field->data_type == 'StateProvince' && $field->html_type == 'Multi-Select State/Province') {
1774 $params['type'] = 'varchar(255)';
1775 }
1776 elseif ($field->data_type == 'File') {
1777 $params['fk_table_name'] = 'civicrm_file';
1778 $params['fk_field_name'] = 'id';
1779 $params['fk_attributes'] = 'ON DELETE SET NULL';
1780 }
1781 elseif ($field->data_type == 'ContactReference') {
1782 $params['fk_table_name'] = 'civicrm_contact';
1783 $params['fk_field_name'] = 'id';
1784 $params['fk_attributes'] = 'ON DELETE SET NULL';
1785 }
1786 if (isset($field->default_value)) {
1787 $params['default'] = "'{$field->default_value}'";
1788 }
1789
1790 CRM_Core_BAO_SchemaHandler::alterFieldSQL($params, $indexExist, $triggerRebuild);
1791 }
1792
1793 /**
1794 * Determine whether it would be safe to move a field.
1795 *
1796 * @param int $fieldID
1797 * FK to civicrm_custom_field.
1798 * @param int $newGroupID
1799 * FK to civicrm_custom_group.
1800 *
1801 * @return array
1802 * array(string) or TRUE
1803 */
1804 public static function _moveFieldValidate($fieldID, $newGroupID) {
1805 $errors = array();
1806
1807 $field = new CRM_Core_DAO_CustomField();
1808 $field->id = $fieldID;
1809 if (!$field->find(TRUE)) {
1810 $errors['fieldID'] = 'Invalid ID for custom field';
1811 return $errors;
1812 }
1813
1814 $oldGroup = new CRM_Core_DAO_CustomGroup();
1815 $oldGroup->id = $field->custom_group_id;
1816 if (!$oldGroup->find(TRUE)) {
1817 $errors['fieldID'] = 'Invalid ID for old custom group';
1818 return $errors;
1819 }
1820
1821 $newGroup = new CRM_Core_DAO_CustomGroup();
1822 $newGroup->id = $newGroupID;
1823 if (!$newGroup->find(TRUE)) {
1824 $errors['newGroupID'] = 'Invalid ID for new custom group';
1825 return $errors;
1826 }
1827
1828 $query = "
1829 SELECT b.id
1830 FROM civicrm_custom_field a
1831 INNER JOIN civicrm_custom_field b
1832 WHERE a.id = %1
1833 AND a.label = b.label
1834 AND b.custom_group_id = %2
1835 ";
1836 $params = array(
1837 1 => array($field->id, 'Integer'),
1838 2 => array($newGroup->id, 'Integer'),
1839 );
1840 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1841 if ($count > 0) {
1842 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1843 }
1844
1845 $tableName = $oldGroup->table_name;
1846 $columnName = $field->column_name;
1847
1848 $query = "
1849 SELECT count(*)
1850 FROM $tableName
1851 WHERE $columnName is not null
1852 ";
1853 $count = CRM_Core_DAO::singleValueQuery($query,
1854 CRM_Core_DAO::$_nullArray
1855 );
1856 if ($count > 0) {
1857 $query = "
1858 SELECT extends
1859 FROM civicrm_custom_group
1860 WHERE id IN ( %1, %2 )
1861 ";
1862 $params = array(
1863 1 => array($oldGroup->id, 'Integer'),
1864 2 => array($newGroup->id, 'Integer'),
1865 );
1866
1867 $dao = CRM_Core_DAO::executeQuery($query, $params);
1868 $extends = array();
1869 while ($dao->fetch()) {
1870 $extends[] = $dao->extends;
1871 }
1872 if ($extends[0] != $extends[1]) {
1873 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1874 }
1875 }
1876
1877 return empty($errors) ? TRUE : $errors;
1878 }
1879
1880 /**
1881 * Move a custom data field from one group (table) to another.
1882 *
1883 * @param int $fieldID
1884 * FK to civicrm_custom_field.
1885 * @param int $newGroupID
1886 * FK to civicrm_custom_group.
1887 */
1888 public static function moveField($fieldID, $newGroupID) {
1889 $validation = self::_moveFieldValidate($fieldID, $newGroupID);
1890 if (TRUE !== $validation) {
1891 CRM_Core_Error::fatal(implode(' ', $validation));
1892 }
1893 $field = new CRM_Core_DAO_CustomField();
1894 $field->id = $fieldID;
1895 $field->find(TRUE);
1896
1897 $newGroup = new CRM_Core_DAO_CustomGroup();
1898 $newGroup->id = $newGroupID;
1899 $newGroup->find(TRUE);
1900
1901 $oldGroup = new CRM_Core_DAO_CustomGroup();
1902 $oldGroup->id = $field->custom_group_id;
1903 $oldGroup->find(TRUE);
1904
1905 $add = clone$field;
1906 $add->custom_group_id = $newGroup->id;
1907 self::createField($add, 'add');
1908
1909 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1910 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1911 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1912 ";
1913 CRM_Core_DAO::executeQuery($sql);
1914
1915 $del = clone$field;
1916 $del->custom_group_id = $oldGroup->id;
1917 self::createField($del, 'delete');
1918
1919 $add->save();
1920
1921 CRM_Utils_System::flushCache();
1922 }
1923
1924 /**
1925 * Get the database table name and column name for a custom field.
1926 *
1927 * @param int $fieldID
1928 * The fieldID of the custom field.
1929 * @param bool $force
1930 * Force the sql to be run again (primarily used for tests).
1931 *
1932 * @return array
1933 * fatal is fieldID does not exists, else array of tableName, columnName
1934 */
1935 public static function getTableColumnGroup($fieldID, $force = FALSE) {
1936 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
1937 $cache = CRM_Utils_Cache::singleton();
1938 $fieldValues = $cache->get($cacheKey);
1939 if (empty($fieldValues) || $force) {
1940 $query = "
1941 SELECT cg.table_name, cf.column_name, cg.id
1942 FROM civicrm_custom_group cg,
1943 civicrm_custom_field cf
1944 WHERE cf.custom_group_id = cg.id
1945 AND cf.id = %1";
1946 $params = array(1 => array($fieldID, 'Integer'));
1947 $dao = CRM_Core_DAO::executeQuery($query, $params);
1948
1949 if (!$dao->fetch()) {
1950 CRM_Core_Error::fatal();
1951 }
1952 $dao->free();
1953 $fieldValues = array($dao->table_name, $dao->column_name, $dao->id);
1954 $cache->set($cacheKey, $fieldValues);
1955 }
1956 return $fieldValues;
1957 }
1958
1959 /**
1960 * Get custom option groups.
1961 *
1962 * @param array $includeFieldIds
1963 * Ids of custom fields for which option groups must be included.
1964 *
1965 * Currently this is required in the cases where option groups are to be included
1966 * for inactive fields : CRM-5369
1967 *
1968 * @return mixed
1969 */
1970 public static function customOptionGroup($includeFieldIds = NULL) {
1971 static $customOptionGroup = NULL;
1972
1973 $cacheKey = (empty($includeFieldIds)) ? 'onlyActive' : 'force';
1974 if ($cacheKey == 'force') {
1975 $customOptionGroup[$cacheKey] = NULL;
1976 }
1977
1978 if (empty($customOptionGroup[$cacheKey])) {
1979 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
1980
1981 //support for single as well as array format.
1982 if (!empty($includeFieldIds)) {
1983 if (is_array($includeFieldIds)) {
1984 $includeFieldIds = implode(',', $includeFieldIds);
1985 }
1986 $whereClause .= "OR f.id IN ( $includeFieldIds )";
1987 }
1988
1989 $query = "
1990 SELECT g.id, g.title
1991 FROM civicrm_option_group g
1992 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
1993 WHERE {$whereClause}";
1994
1995 $dao = CRM_Core_DAO::executeQuery($query);
1996 while ($dao->fetch()) {
1997 $customOptionGroup[$cacheKey][$dao->id] = $dao->title;
1998 }
1999 }
2000
2001 return $customOptionGroup[$cacheKey];
2002 }
2003
2004 /**
2005 * Fix orphan groups.
2006 *
2007 * @param int $customFieldId
2008 * Custom field id.
2009 * @param int $optionGroupId
2010 * Option group id.
2011 */
2012 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2013 // check if option group belongs to any custom Field else delete
2014 // get the current option group
2015 $currentOptionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
2016 $customFieldId,
2017 'option_group_id'
2018 );
2019 // get the updated option group
2020 // if both are same return
2021 if ($currentOptionGroupId == $optionGroupId) {
2022 return;
2023 }
2024
2025 // check if option group is related to any other field
2026 self::checkOptionGroup($currentOptionGroupId);
2027 }
2028
2029 /**
2030 * Check if option group is related to more than one custom field.
2031 *
2032 * @param int $optionGroupId
2033 * Option group id.
2034 */
2035 public static function checkOptionGroup($optionGroupId) {
2036 $query = "
2037 SELECT count(*)
2038 FROM civicrm_custom_field
2039 WHERE option_group_id = {$optionGroupId}";
2040
2041 $count = CRM_Core_DAO::singleValueQuery($query);
2042
2043 if ($count < 2) {
2044 //delete the option group
2045 CRM_Core_BAO_OptionGroup::del($optionGroupId);
2046 }
2047 }
2048
2049 /**
2050 * Get option group default.
2051 *
2052 * @param int $optionGroupId
2053 * @param string $htmlType
2054 *
2055 * @return null|string
2056 */
2057 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2058 $query = "
2059 SELECT default_value, html_type
2060 FROM civicrm_custom_field
2061 WHERE option_group_id = {$optionGroupId}
2062 AND default_value IS NOT NULL
2063 ORDER BY html_type";
2064
2065 $dao = CRM_Core_DAO::executeQuery($query);
2066 $defaultValue = NULL;
2067 $defaultHTMLType = NULL;
2068 while ($dao->fetch()) {
2069 if ($dao->html_type == $htmlType) {
2070 return $dao->default_value;
2071 }
2072 if ($defaultValue == NULL) {
2073 $defaultValue = $dao->default_value;
2074 $defaultHTMLType = $dao->html_type;
2075 }
2076 }
2077
2078 // some conversions are needed if either the old or new has a html type which has potential
2079 // multiple default values.
2080 if (($htmlType == 'CheckBox' || $htmlType == 'Multi-Select') &&
2081 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2082 ) {
2083 $defaultValue = CRM_Core_DAO::VALUE_SEPARATOR . $defaultValue . CRM_Core_DAO::VALUE_SEPARATOR;
2084 }
2085 elseif (($defaultHTMLType == 'CheckBox' || $defaultHTMLType == 'Multi-Select') &&
2086 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2087 ) {
2088 $defaultValue = substr($defaultValue, 1, -1);
2089 $values = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2090 substr($defaultValue, 1, -1)
2091 );
2092 $defaultValue = $values[0];
2093 }
2094
2095 return $defaultValue;
2096 }
2097
2098 /**
2099 * Post process function.
2100 *
2101 * @param array $params
2102 * @param int $entityID
2103 * @param string $customFieldExtends
2104 * @param bool $inline
2105 * @param bool $checkPermissions
2106 *
2107 * @return array
2108 */
2109 public static function postProcess(
2110 &$params,
2111 $entityID,
2112 $customFieldExtends,
2113 $inline = FALSE,
2114 $checkPermissions = TRUE
2115 ) {
2116 $customData = array();
2117
2118 foreach ($params as $key => $value) {
2119 if ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($key, TRUE)) {
2120
2121 // for autocomplete transfer hidden value instead of label
2122 if ($params[$key] && isset($params[$key . '_id'])) {
2123 $value = $params[$key . '_id'];
2124 }
2125
2126 // we need to append time with date
2127 if ($params[$key] && isset($params[$key . '_time'])) {
2128 $value .= ' ' . $params[$key . '_time'];
2129 }
2130
2131 CRM_Core_BAO_CustomField::formatCustomField($customFieldInfo[0],
2132 $customData,
2133 $value,
2134 $customFieldExtends,
2135 $customFieldInfo[1],
2136 $entityID,
2137 $inline,
2138 $checkPermissions
2139 );
2140 }
2141 }
2142 return $customData;
2143 }
2144
2145 /**
2146 *
2147 */
2148
2149 /**
2150 * Get custom field ID.
2151 *
2152 * @param string $fieldLabel
2153 * @param null $groupTitle
2154 *
2155 * @return int|null
2156 */
2157 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2158 $params = array(1 => array($fieldLabel, 'String'));
2159 if ($groupTitle) {
2160 $params[2] = array($groupTitle, 'String');
2161 $sql = "
2162 SELECT f.id
2163 FROM civicrm_custom_field f
2164 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2165 WHERE ( f.label = %1 OR f.name = %1 )
2166 AND ( g.title = %2 OR g.name = %2 )
2167 ";
2168 }
2169 else {
2170 $sql = "
2171 SELECT f.id
2172 FROM civicrm_custom_field f
2173 WHERE ( f.label = %1 OR f.name = %1 )
2174 ";
2175 }
2176
2177 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2178 if ($dao->fetch() &&
2179 $dao->N == 1
2180 ) {
2181 return $dao->id;
2182 }
2183 else {
2184 return NULL;
2185 }
2186 }
2187
2188 /**
2189 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2190 *
2191 * @param array $ids
2192 *
2193 * @return array
2194 */
2195 public static function getNameFromID($ids) {
2196 if (is_array($ids)) {
2197 $ids = implode(',', $ids);
2198 }
2199 $sql = "
2200 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2201 FROM civicrm_custom_field f
2202 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2203 WHERE f.id IN ($ids)";
2204
2205 $dao = CRM_Core_DAO::executeQuery($sql);
2206 $result = array();
2207 while ($dao->fetch()) {
2208 $result[$dao->id] = array(
2209 'field_name' => $dao->field_name,
2210 'field_label' => $dao->field_label,
2211 'group_name' => $dao->group_name,
2212 'group_title' => $dao->group_title,
2213 );
2214 }
2215 return $result;
2216 }
2217
2218 /**
2219 * Validate custom data.
2220 *
2221 * @param array $params
2222 * Custom data submitted.
2223 * ie array( 'custom_1' => 'validate me' );
2224 *
2225 * @return array
2226 * validation errors.
2227 */
2228 public static function validateCustomData($params) {
2229 $errors = array();
2230 if (!is_array($params) || empty($params)) {
2231 return $errors;
2232 }
2233
2234 //pick up profile fields.
2235 $profileFields = array();
2236 $ufGroupId = CRM_Utils_Array::value('ufGroupId', $params);
2237 if ($ufGroupId) {
2238 $profileFields = CRM_Core_BAO_UFGroup::getFields($ufGroupId,
2239 FALSE,
2240 CRM_Core_Action::VIEW
2241 );
2242 }
2243
2244 //lets start w/ params.
2245 foreach ($params as $key => $value) {
2246 $customFieldID = self::getKeyID($key);
2247 if (!$customFieldID) {
2248 continue;
2249 }
2250
2251 //load the structural info for given field.
2252 $field = new CRM_Core_DAO_CustomField();
2253 $field->id = $customFieldID;
2254 if (!$field->find(TRUE)) {
2255 continue;
2256 }
2257 $dataType = $field->data_type;
2258
2259 $profileField = CRM_Utils_Array::value($key, $profileFields, array());
2260 $fieldTitle = CRM_Utils_Array::value('title', $profileField);
2261 $isRequired = CRM_Utils_Array::value('is_required', $profileField);
2262 if (!$fieldTitle) {
2263 $fieldTitle = $field->label;
2264 }
2265
2266 //no need to validate.
2267 if (CRM_Utils_System::isNull($value) && !$isRequired) {
2268 continue;
2269 }
2270
2271 //lets validate first for required field.
2272 if ($isRequired && CRM_Utils_System::isNull($value)) {
2273 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2274 continue;
2275 }
2276
2277 //now time to take care of custom field form rules.
2278 $ruleName = $errorMsg = NULL;
2279 switch ($dataType) {
2280 case 'Int':
2281 $ruleName = 'integer';
2282 $errorMsg = ts('%1 must be an integer (whole number).',
2283 array(1 => $fieldTitle)
2284 );
2285 break;
2286
2287 case 'Money':
2288 $ruleName = 'money';
2289 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2290 array(1 => $fieldTitle)
2291 );
2292 break;
2293
2294 case 'Float':
2295 $ruleName = 'numeric';
2296 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2297 array(1 => $fieldTitle)
2298 );
2299 break;
2300
2301 case 'Link':
2302 $ruleName = 'wikiURL';
2303 $errorMsg = ts('%1 must be valid Website.',
2304 array(1 => $fieldTitle)
2305 );
2306 break;
2307 }
2308
2309 if ($ruleName && !CRM_Utils_System::isNull($value)) {
2310 $valid = FALSE;
2311 $funName = "CRM_Utils_Rule::{$ruleName}";
2312 if (is_callable($funName)) {
2313 $valid = call_user_func($funName, $value);
2314 }
2315 if (!$valid) {
2316 $errors[$key] = $errorMsg;
2317 }
2318 }
2319 }
2320
2321 return $errors;
2322 }
2323
2324 /**
2325 * Is this field a multi record field.
2326 *
2327 * @param int $customId
2328 *
2329 * @return bool
2330 */
2331 public static function isMultiRecordField($customId) {
2332 $isMultipleWithGid = FALSE;
2333 if (!is_numeric($customId)) {
2334 $customId = self::getKeyID($customId);
2335 }
2336 if (is_numeric($customId)) {
2337 $sql = "SELECT cg.id cgId
2338 FROM civicrm_custom_group cg
2339 INNER JOIN civicrm_custom_field cf
2340 ON cg.id = cf.custom_group_id
2341 WHERE cf.id = %1 AND cg.is_multiple = 1";
2342 $params[1] = array($customId, 'Integer');
2343 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2344 if ($dao->fetch()) {
2345 if ($dao->cgId) {
2346 $isMultipleWithGid = $dao->cgId;
2347 }
2348 }
2349 }
2350
2351 return $isMultipleWithGid;
2352 }
2353
2354 /**
2355 * Does this field store a serialized string?
2356 *
2357 * @param array $field
2358 *
2359 * @return bool
2360 */
2361 public static function isSerialized($field) {
2362 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2363 $field = (array) $field;
2364 // 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.
2365 return ($field['html_type'] == 'CheckBox' || strpos($field['html_type'], 'Multi') !== FALSE);
2366 }
2367
2368 /**
2369 * Get api entity for this field
2370 *
2371 * @return string
2372 */
2373 public function getEntity() {
2374 $entity = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id, 'extends');
2375 return in_array($entity, array('Individual', 'Household', 'Organization')) ? 'Contact' : $entity;
2376 }
2377
2378 /**
2379 * Set pseudoconstant properties for field metadata.
2380 *
2381 * @param array $field
2382 * @param string|null $optionGroupName
2383 */
2384 private static function getOptionsForField(&$field, $optionGroupName) {
2385 if ($optionGroupName) {
2386 $field['pseudoconstant'] = array(
2387 'optionGroupName' => $optionGroupName,
2388 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2389 );
2390 }
2391 elseif ($field['data_type'] == 'Boolean') {
2392 $field['pseudoconstant'] = array(
2393 'callback' => 'CRM_Core_SelectValues::boolean',
2394 );
2395 }
2396 elseif ($field['data_type'] == 'Country') {
2397 $field['pseudoconstant'] = array(
2398 'table' => 'civicrm_country',
2399 'keyColumn' => 'id',
2400 'labelColumn' => 'name',
2401 'nameColumn' => 'iso_code',
2402 );
2403 }
2404 elseif ($field['data_type'] == 'StateProvince') {
2405 $field['pseudoconstant'] = array(
2406 'table' => 'civicrm_state_province',
2407 'keyColumn' => 'id',
2408 'labelColumn' => 'name',
2409 );
2410 }
2411 }
2412
2413 }