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