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