3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * Business objects for managing custom data fields.
40 class CRM_Core_BAO_CustomField
extends CRM_Core_DAO_CustomField
{
43 * Array for valid combinations of data_type & descriptions
48 public static $_dataType = NULL;
51 * Array for valid combinations of data_type & html_type
56 public static $_dataToHtml = NULL;
59 * Array to hold (formatted) fields for import
64 public static $_importFields = NULL;
67 * Build and retrieve the list of data types and descriptions
71 * @return array Data type => Description
75 static function &dataType() {
76 if (!(self
::$_dataType)) {
77 self
::$_dataType = array(
78 'String' => ts('Alphanumeric'),
79 'Int' => ts('Integer'),
80 'Float' => ts('Number'),
81 'Money' => ts('Money'),
84 'Boolean' => ts('Yes or No'),
85 'StateProvince' => ts('State/Province'),
86 'Country' => ts('Country'),
89 'ContactReference' => ts('Contact Reference'),
92 return self
::$_dataType;
98 static function dataToHtml() {
99 if (!self
::$_dataToHtml) {
100 self
::$_dataToHtml = array(
102 'Text' => 'Text', 'Select' => 'Select',
103 'Radio' => 'Radio', 'CheckBox' => 'CheckBox',
104 'Multi-Select' => 'Multi-Select',
105 'AdvMulti-Select' => 'AdvMulti-Select',
106 'Autocomplete-Select' => 'Autocomplete-Select',
108 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
109 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
110 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
111 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
112 array('Date' => 'Select Date'),
113 array('Radio' => 'Radio'),
114 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
115 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
116 array('File' => 'File'),
117 array('Link' => 'Link'),
118 array('ContactReference' => 'Autocomplete-Select'),
121 return self
::$_dataToHtml;
125 * takes an associative array and creates a custom field object
127 * This function is invoked from within the web form layer and also from the api layer
129 * @param array $params (reference) an assoc array of name/value pairs
131 * @return CRM_Core_DAO_CustomField object
135 static function create(&$params) {
136 $origParams = array_merge(array(), $params);
138 if (!isset($params['id'])) {
139 if (!isset($params['column_name'])) {
140 // if add mode & column_name not present, calculate it.
141 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
143 if (!isset($params['name'])) {
144 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
148 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
153 $columnName = $params['column_name'];
156 //as during create if field is_searchable we had created index.
157 if (!empty($params['id'])) {
158 $indexExist = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
161 switch (CRM_Utils_Array
::value('html_type', $params)){
163 if(empty($params['date_format'])){
164 $config = CRM_Core_Config
::singleton();
165 $params['date_format'] = $config->dateInputFormat
;
169 case 'AdvMulti-Select':
171 if (isset($params['default_checkbox_option'])) {
172 $tempArray = array_keys($params['default_checkbox_option']);
173 $defaultArray = array();
174 foreach ($tempArray as $k => $v) {
175 if ($params['option_value'][$v]) {
176 $defaultArray[] = $params['option_value'][$v];
180 if (!empty($defaultArray)) {
181 // also add the seperator before and after the value per new conventio (CRM-1604)
182 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
186 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
188 $params['default_value'] = $params['option_value'][$params['default_option']];
194 $transaction = new CRM_Core_Transaction();
195 // create any option group & values if required
196 if ($params['html_type'] != 'Text' &&
197 in_array($params['data_type'], array(
198 'String', 'Int', 'Float', 'Money'))
201 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
202 $params['custom_group_id'],
207 if ($params['option_type'] == 1) {
208 // first create an option group for this custom group
209 $optionGroup = new CRM_Core_DAO_OptionGroup();
210 $optionGroup->name
= "{$columnName}_" . date('YmdHis');
211 $optionGroup->title
= $params['label'];
212 $optionGroup->is_active
= 1;
213 $optionGroup->save();
214 $params['option_group_id'] = $optionGroup->id
;
215 if(!empty($params['option_value']) && is_array($params['option_value'])){
216 foreach ($params['option_value'] as $k => $v) {
217 if (strlen(trim($v))) {
218 $optionValue = new CRM_Core_DAO_OptionValue();
219 $optionValue->option_group_id
= $optionGroup->id
;
220 $optionValue->label
= $params['option_label'][$k];
221 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$k]);
222 switch ($params['data_type']) {
224 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($v);
228 $optionValue->value
= intval($v);
232 $optionValue->value
= floatval($v);
236 $optionValue->value
= trim($v);
239 $optionValue->weight
= $params['option_weight'][$k];
240 $optionValue->is_active
= CRM_Utils_Array
::value($k, $params['option_status'], FALSE);
241 $optionValue->save();
248 // check for orphan option groups
249 if (!empty($params['option_group_id'])) {
250 if (!empty($params['id'])) {
251 self
::fixOptionGroups($params['id'], $params['option_group_id']);
254 // if we dont have a default value
255 // retrive it from one of the other custom fields which use this option group
256 if (empty($params['default_value'])) {
257 //don't insert only value separator as default value, CRM-4579
258 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
262 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
265 $params['default_value'] = $defaultValue;
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';
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 $customField->is_active
= CRM_Utils_Array
::value('is_active', $params, FALSE);
282 $customField->is_view
= CRM_Utils_Array
::value('is_view', $params, FALSE);
283 $customField->save();
285 // make sure all values are present in the object for further processing
286 $customField->find(TRUE);
288 //create/drop the index when we toggle the is_searchable flag
289 if (!empty($params['id'])) {
290 self
::createField($customField, 'modify', $indexExist);
293 if (!isset($origParams['column_name'])) {
294 $columnName .= "_{$customField->id}";
295 $params['column_name'] = $columnName;
297 $customField->column_name
= $columnName;
298 $customField->save();
299 // make sure all values are present in the object
300 $customField->find(TRUE);
302 self
::createField($customField, 'add');
305 // complete transaction
306 $transaction->commit();
308 CRM_Utils_System
::flushCache();
314 * Takes a bunch of params that are needed to match certain criteria and
315 * retrieves the relevant objects. Typically the valid params are only
316 * contact_id. We'll tweak this function to be more full featured over a period
317 * of time. This is the inverse function of create. It also stores all the retrieved
318 * values in the default array
320 * @param array $params (reference ) an assoc array of name/value pairs
321 * @param array $defaults (reference ) an assoc array to hold the flattened values
323 * @return object CRM_Core_DAO_CustomField object
327 static function retrieve(&$params, &$defaults) {
328 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
332 * update the is_active flag in the db
334 * @param int $id Id of the database record
335 * @param boolean $is_active Value we want to set the is_active field
337 * @return Object DAO object on sucess, null otherwise
342 static function setIsActive($id, $is_active) {
344 CRM_Utils_System
::flushCache();
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);
352 * Get the field title.
354 * @param int $id id of field.
356 * @return string name
362 public static function getTitle($id) {
363 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
367 * Store and return an array of all active custom fields.
369 * @param string $customDataType type of Custom Data; empty is a synonym for "all contact data types"
370 * @param boolean $showAll If true returns all fields (includes disabled fields)
371 * @param boolean $inline If true returns all inline fields (includes disabled fields)
372 * @param int $customDataSubType Custom Data sub type value
373 * @param int $customDataSubName Custom Data sub name value
374 * @param boolean $onlyParent return only top level custom data, for eg, only Participant and ignore subname and subtype
375 * @param boolean $onlySubType return only custom data for subtype
376 * @param boolean $checkPermission if false, do not include permissioning clause
378 * @return array $fields - an array of active custom fields.
383 public static function &getFields($customDataType = 'Individual',
386 $customDataSubType = NULL,
387 $customDataSubName = NULL,
389 $onlySubType = FALSE,
390 $checkPermission = TRUE
392 if (empty($customDataType)) {
393 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
395 if ($customDataType && !is_array($customDataType)) {
397 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
398 // This is the case when getFieldsForImport() requires fields
399 // limited strictly to a subtype.
400 $customDataSubType = $customDataType;
401 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
405 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
406 // this makes the method flexible to support retrieving fields
407 // for multiple extends value.
408 $customDataType = array($customDataType);
412 if ($customDataSubType && !is_array($customDataSubType)) {
413 $customDataSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
414 trim($customDataSubType, CRM_Core_DAO
::VALUE_SEPARATOR
)
418 if (is_array($customDataType)) {
419 $cacheKey = implode('_', $customDataType);
422 $cacheKey = $customDataType;
425 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
426 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
427 $cacheKey .= $showAll ?
'_1' : '_0';
428 $cacheKey .= $inline ?
'_1_' : '_0_';
429 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
430 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
431 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
433 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
435 // also get the permission stuff here
436 if ($checkPermission) {
437 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
442 $permissionClause = '(1)';
445 // lets md5 permission clause and take first 8 characters
446 $cacheKey .= substr(md5($permissionClause), 0, 8);
448 if (strlen($cacheKey) > 40) {
449 $cacheKey = md5($cacheKey);
452 if (!self
::$_importFields ||
453 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
455 if (!self
::$_importFields) {
456 self
::$_importFields = array();
459 // check if we can retrieve from database cache
460 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
462 if ($fields === NULL) {
463 $cfTable = self
::getTableName();
466 if (is_array($customDataType)) {
468 foreach ($customDataType as $dataType) {
469 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
470 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
471 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
474 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
476 $value = $value ?
$value . ", {$val}" : $val;
480 $extends = "AND $cgTable.extends IN ( $value ) ";
484 if (!empty($customDataType) && empty($extends)) {
485 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
486 self
::$_importFields[$cacheKey] = array();
487 return self
::$_importFields[$cacheKey];
491 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
494 $query = "SELECT $cfTable.id, $cfTable.label,
498 $cfTable.default_value,
499 $cfTable.options_per_line, $cfTable.text_length,
500 $cfTable.custom_group_id,
501 $cfTable.is_required,
502 $cgTable.extends, $cfTable.is_search_range,
503 $cgTable.extends_entity_column_value,
504 $cgTable.extends_entity_column_id,
506 $cfTable.option_group_id,
507 $cfTable.date_format,
508 $cfTable.time_format,
512 ON $cfTable.custom_group_id = $cgTable.id
516 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
520 $query .= " AND $cgTable.style = 'Inline' ";
523 //get the custom fields for specific type in
524 //combination with fields those support any type.
525 if (!empty($customDataSubType)) {
526 $subtypeClause = array();
527 foreach ($customDataSubType as $subtype) {
528 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
529 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
532 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
534 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
537 if ($customDataSubName) {
538 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
541 // also get the permission stuff here
542 if ($checkPermission) {
543 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
548 $permissionClause = '(1)';
551 $query .= " $extends AND $permissionClause
552 ORDER BY $cgTable.weight, $cgTable.title,
553 $cfTable.weight, $cfTable.label";
555 $dao = CRM_Core_DAO
::executeQuery($query);
558 while (($dao->fetch()) != NULL) {
559 $fields[$dao->id
]['label'] = $dao->label
;
560 $fields[$dao->id
]['groupTitle'] = $dao->title
;
561 $fields[$dao->id
]['data_type'] = $dao->data_type
;
562 $fields[$dao->id
]['html_type'] = $dao->html_type
;
563 $fields[$dao->id
]['default_value'] = $dao->default_value
;
564 $fields[$dao->id
]['text_length'] = $dao->text_length
;
565 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
566 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
567 $fields[$dao->id
]['extends'] = $dao->extends;
568 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
569 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
570 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
571 $fields[$dao->id
]['is_view'] = $dao->is_view
;
572 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
573 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
574 $fields[$dao->id
]['date_format'] = $dao->date_format
;
575 $fields[$dao->id
]['time_format'] = $dao->time_format
;
576 $fields[$dao->id
]['is_required'] = $dao->is_required
;
579 CRM_Core_BAO_Cache
::setItem($fields,
581 "custom importableFields $cacheKey"
584 self
::$_importFields[$cacheKey] = $fields;
587 return self
::$_importFields[$cacheKey];
591 * Return the field ids and names (with groups) for import purpose.
593 * @param int|string $contactType Contact type
594 * @param boolean $showAll If true returns all fields (includes disabled fields)
595 * @param boolean $onlyParent return fields ONLY related to basic types
596 * @param boolean $search when called from search and multiple records need to be returned
597 * @param boolean $checkPermission if false, do not include permissioning clause
599 * @param bool $withMultiple
601 * @return array $fields -
606 public static function &getFieldsForImport($contactType = 'Individual',
610 $checkPermission = TRUE,
611 $withMultiple = FALSE
613 // Note: there are situations when we want getFieldsForImport() return fields related
614 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
615 $fields = &self
::getFields($contactType,
625 $importableFields = array();
626 foreach ($fields as $id => $values) {
627 // for now we should not allow multiple fields in profile / export etc, hence unsetting
629 (!empty($values['is_multiple']) && !$withMultiple)
634 /* generate the key for the fields array */
638 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
639 $importableFields[$key] = array(
641 'title' => CRM_Utils_Array
::value('label', $values),
642 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
644 'custom_field_id' => $id,
645 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
646 'data_type' => CRM_Utils_Array
::value('data_type', $values),
647 'html_type' => CRM_Utils_Array
::value('html_type', $values),
648 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
651 // CRM-6681, pass date and time format when html_type = Select Date
652 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
653 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
654 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
658 return $importableFields;
662 * Get the field id from an import key
664 * @param string $key The key to parse
667 * @return int|null The id (if exists)
671 public static function getKeyID($key, $all = FALSE) {
673 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
680 CRM_Utils_Array
::value(2, $match),
689 * Use the cache to get all values of a specific custom field
691 * @param int $fieldID the custom field ID
693 * @return CRM_Core_DAO_CustomField $field the field object
697 static function getFieldObject($fieldID) {
698 $field = new CRM_Core_DAO_CustomField();
700 // check if we can get the field values from the system cache
701 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
702 $cache = CRM_Utils_Cache
::singleton();
703 $fieldValues = $cache->get($cacheKey);
704 if (empty($fieldValues)) {
705 $field->id
= $fieldID;
706 if (!$field->find(TRUE)) {
707 CRM_Core_Error
::fatal();
710 $fieldValues = array();
711 CRM_Core_DAO
::storeValues($field, $fieldValues);
713 $cache->set($cacheKey, $fieldValues);
716 $field->copyValues($fieldValues);
723 * This function for building custom fields
725 * @param CRM_Core_Form $qf form object (reference)
726 * @param string $elementName name of the custom field
728 * @param boolean $inactiveNeeded
729 * @param bool $useRequired
730 * @param boolean $search true if used for search else false
731 * @param string $label label for custom field
733 * @internal param bool $userRequired true if required else false
737 public static function addQuickFormElement(&$qf,
740 $inactiveNeeded = FALSE,
745 $field = self
::getFieldObject($fieldId);
747 // Custom field HTML should indicate group+field name
748 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
749 $dataCrmCustomVal = $groupName.':'.$field->name
;
750 $dataCrmCustomAttr = 'data-crm-custom="'.$dataCrmCustomVal.'"';
751 $field->attributes
.= $dataCrmCustomAttr;
753 // Fixed for Issue CRM-2183
754 if ($field->html_type
== 'TextArea' && $search) {
755 $field->html_type
= 'Text';
758 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
760 // FIXME: Why are select state/country separate widget types?
761 if (in_array($field->html_type
, array('Select', 'Multi-Select', 'Select State/Province', 'Multi-Select State/Province', 'Select Country', 'Multi-Select Country'))) {
762 $selectAttributes = array(
763 'data-crm-custom' => $dataCrmCustomVal,
764 'class' => 'crm-select2',
766 if (strpos($field->html_type
, 'Multi') === 0) {
767 $selectAttributes['multiple'] = 'multiple';
770 // Add data so popup link. Normally this is handled by CRM_Core_Form->addSelect
771 if ($field->option_group_id
&& !$search && in_array($field->html_type
, array('Select', 'Multi-Select')) && CRM_Core_Permission
::check('administer CiviCRM')) {
772 $selectAttributes +
= array(
773 'data-api-entity' => 'contact', // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
774 'data-api-field' => 'custom_' . $field->id
,
775 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
779 if (!isset($label)) {
780 $label = $field->label
;
784 * at some point in time we might want to split the below into small functions
787 switch ($field->html_type
) {
789 if ($field->is_search_range
&& $search) {
790 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
791 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
794 $element = &$qf->add(strtolower($field->html_type
), $elementName, $label,
796 $useRequired && !$search
802 $attributes = $dataCrmCustomAttr;
803 if ($field->note_rows
) {
804 $attributes .= 'rows=' . $field->note_rows
;
807 $attributes .= 'rows=4';
809 if ($field->note_columns
) {
810 $attributes .= ' cols=' . $field->note_columns
;
813 $attributes .= ' cols=60';
815 if ($field->text_length
) {
816 $attributes .= ' maxlength=' . $field->text_length
;
818 $element = &$qf->add(strtolower($field->html_type
),
822 $useRequired && !$search
827 if ($field->is_search_range
&& $search) {
828 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
830 'format' => $field->date_format
,
831 'timeFormat' => $field->time_format
,
832 'startOffset' => $field->start_date_years
,
833 'endOffset' => $field->end_date_years
,
834 'data-crm-custom' => $dataCrmCustomVal,
838 $qf->addDate($elementName . '_to', ts('To'), FALSE,
840 'format' => $field->date_format
,
841 'timeFormat' => $field->time_format
,
842 'startOffset' => $field->start_date_years
,
843 'endOffset' => $field->end_date_years
,
844 'data-crm-custom' => $dataCrmCustomVal,
849 $required = $useRequired && !$search;
851 $qf->addDate($elementName, $label, $required, array(
852 'format' => $field->date_format
,
853 'timeFormat' => $field->time_format
,
854 'startOffset' => $field->start_date_years
,
855 'endOffset' => $field->end_date_years
,
856 'data-crm-custom' => $dataCrmCustomVal,
863 if ($field->data_type
!= 'Boolean') {
864 $customOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
865 $field->option_group_id
867 foreach ($customOption as $v => $l) {
868 $choice[] = $qf->createElement('radio', NULL, '', $l, (string)$v, $field->attributes
);
870 $group = $qf->addGroup($choice, $elementName, $label);
873 $choice[] = $qf->createElement('radio', NULL, '', ts('Yes'), '1', $field->attributes
);
874 $choice[] = $qf->createElement('radio', NULL, '', ts('No'), '0', $field->attributes
);
875 $group = $qf->addGroup($choice, $elementName, $label);
877 if ($useRequired && !$search) {
878 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
881 $group->setAttribute('allowClear', TRUE);
886 $selectOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
887 $field->option_group_id
890 $qf->add('select', $elementName, $label,
891 array('' => $placeholder) +
$selectOption,
892 $useRequired && !$search,
897 //added for select multiple
899 case 'AdvMulti-Select':
900 $selectOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
901 $field->option_group_id
904 count($selectOption) > 1
906 $selectOption['CiviCRM_OP_OR'] = ts('Select to match ANY; unselect to match ALL');
909 $include =& $qf->addElement(
912 $label, $selectOption,
916 'class' => 'advmultiselect',
917 'data-crm-custom' => $dataCrmCustomVal,
921 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
922 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
924 if ($useRequired && !$search) {
925 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
930 $selectOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
931 $field->option_group_id
934 count($selectOption) > 1
936 $selectOption['CiviCRM_OP_OR'] = ts('Select to match ANY; unselect to match ALL');
938 $qf->addElement('select', $elementName, $label, $selectOption, $selectAttributes);
940 if ($useRequired && !$search) {
941 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
946 $customOption = CRM_Core_BAO_CustomOption
::valuesByID($field->id
,
947 $field->option_group_id
950 foreach ($customOption as $v => $l) {
951 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
956 $check[] = &$qf->addElement('advcheckbox', 'CiviCRM_OP_OR', NULL, ts('Check to match ANY; uncheck to match ALL'), array('data-crm-custom' => $dataCrmCustomVal));
958 $qf->addGroup($check, $elementName, $label);
959 if ($useRequired && !$search) {
960 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
965 // we should not build upload file in search mode
970 strtolower($field->html_type
),
974 $useRequired && !$search
976 $qf->addUploadElement($elementName);
979 case 'Select State/Province':
981 $stateOption = array('' => $placeholder) + CRM_Core_PseudoConstant
::stateProvince();
982 $qf->add('select', $elementName, $label, $stateOption,
983 $useRequired && !$search,
986 $qf->_stateCountryMap
['state_province'][] = $elementName;
989 case 'Multi-Select State/Province':
990 //Add Multi-select State/Province
991 $stateOption = CRM_Core_PseudoConstant
::stateProvince();
993 $qf->addElement('select', $elementName, $label, $stateOption, $selectAttributes);
994 if ($useRequired && !$search) {
995 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
999 case 'Select Country':
1001 $countryOption = array('' => $placeholder) + CRM_Core_PseudoConstant
::country();
1002 $qf->add('select', $elementName, $label, $countryOption,
1003 $useRequired && !$search,
1006 $qf->_stateCountryMap
['country'][] = $elementName;
1009 case 'Multi-Select Country':
1011 $countryOption = CRM_Core_PseudoConstant
::country();
1012 $qf->addElement('select', $elementName, $label, $countryOption, $selectAttributes);
1013 if ($useRequired && !$search) {
1014 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
1018 case 'RichTextEditor':
1019 $attributes = array('rows' => $field->note_rows
, 'cols' => $field->note_columns
, 'data-crm-custom' => $dataCrmCustomVal);
1020 if ($field->text_length
) {
1021 $attributes['maxlength'] = $field->text_length
;
1023 $qf->addWysiwyg($elementName, $label, $attributes, $search);
1026 case 'Autocomplete-Select':
1027 static $customUrls = array();
1028 // Fixme: why is this a string in the first place??
1029 $attributes = array();
1030 if ($field->attributes
) {
1031 foreach(explode(' ', $field->attributes
) as $at) {
1032 if (strpos($at, '=')) {
1033 list($k, $v) = explode('=', $at);
1034 $attributes[$k] = trim($v, ' "');
1038 if ($field->data_type
== 'ContactReference') {
1039 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1040 $attributes['data-api-entity'] = 'contact';
1041 $qf->add('text', $elementName, $label, $attributes,
1042 $useRequired && !$search
1045 $urlParams = "context=customfield&id={$field->id}";
1047 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1054 // FIXME: This won't work with customFieldOptions hook
1055 $attributes +
= array(
1056 'entity' => 'option_value',
1057 'placeholder' => $placeholder,
1059 'params' => array('option_group_id' => $field->option_group_id
),
1062 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1065 $qf->assign('customUrls', $customUrls);
1069 switch ($field->data_type
) {
1071 // integers will have numeric rule applied to them.
1072 if ($field->is_search_range
&& $search) {
1073 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1074 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1077 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1082 if ($field->is_search_range
&& $search) {
1083 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1084 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1087 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1092 if ($field->is_search_range
&& $search) {
1093 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1094 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1097 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1107 'onfocus' => "if (!this.value) { this.value='http://';} else return false",
1108 'onblur' => "if ( this.value == 'http://') { this.value='';} else return false",
1109 'data-crm-custom' => $dataCrmCustomVal,
1111 $useRequired && !$search
1113 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1116 if ($field->is_view
&& !$search) {
1117 $qf->freeze($elementName);
1122 * Delete the Custom Field.
1124 * @param object $field - the field object
1132 public static function deleteField($field) {
1133 CRM_Utils_System
::flushCache();
1135 // first delete the custom option group and values associated with this field
1136 if ($field->option_group_id
) {
1137 //check if option group is related to any other field, if
1138 //not delete the option group and related option values
1139 self
::checkOptionGroup($field->option_group_id
);
1142 // next drop the column from the custom value table
1143 self
::createField($field, 'delete');
1146 CRM_Core_BAO_UFField
::delUFField($field->id
);
1147 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1153 * Given a custom field value, its id and the set of options
1154 * find the display value for this field
1156 * @param mixed $value the custom field value
1157 * @param int $id the custom field id
1158 * @param int $options the assoc array of option name/value pairs
1160 * @param null $contactID
1161 * @param null $fieldID
1163 * @return string the display value
1168 static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1169 $option = &$options[$id];
1170 $attributes = &$option['attributes'];
1171 $html_type = $attributes['html_type'];
1172 $data_type = $attributes['data_type'];
1173 $format = CRM_Utils_Array
::value('format', $attributes);
1175 return self
::getDisplayValueCommon($value,
1190 * @param null $format
1191 * @param null $contactID
1192 * @param null $fieldID
1194 * @return array|mixed|null|string
1196 static function getDisplayValueCommon($value,
1207 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1208 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1209 $html_type == 'Select' ||
1210 $html_type == 'CheckBox' ||
1211 $html_type == 'AdvMulti-Select' ||
1212 $html_type == 'Multi-Select'
1215 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1218 switch ($html_type) {
1220 if ($data_type == 'Boolean') {
1221 // Do not assume that if not yes means no.
1224 $display = ts('Yes');
1226 elseif ((string)$value === '0') {
1227 $display = ts('No');
1231 $display = CRM_Utils_Array
::value($value, $option);
1235 case 'Autocomplete-Select':
1236 if ($data_type == 'ContactReference' &&
1239 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1242 $display = CRM_Utils_Array
::value($value, $option);
1247 $display = CRM_Utils_Array
::value($value, $option);
1251 case 'AdvMulti-Select':
1252 case 'Multi-Select':
1253 if (is_array($value)) {
1254 $checkedData = $value;
1257 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1258 substr($value, 1, -1)
1260 if ($html_type == 'CheckBox') {
1262 foreach ($checkedData as $v) {
1265 $checkedData = $newData;
1271 foreach ($checkedData as $key => $val) {
1272 if ($key === 'CiviCRM_OP_OR') {
1276 if ($html_type == 'CheckBox') {
1279 $v[] = CRM_Utils_Array
::value($key, $option);
1284 $v[] = CRM_Utils_Array
::value($val, $option);
1288 $display = implode(', ', $v);
1293 if (is_array($value)) {
1294 foreach ($value as $key => $val) {
1295 $display[$key] = CRM_Utils_Date
::customFormat($val);
1299 // remove time element display if time is not set
1300 if (empty($option['attributes']['time_format'])) {
1301 $value = substr($value, 0, 10);
1303 $display = CRM_Utils_Date
::customFormat($value);
1307 case 'Select State/Province':
1308 if (empty($value)) {
1312 $display = CRM_Core_PseudoConstant
::stateProvince($value);
1316 case 'Multi-Select State/Province':
1317 if (is_array($value)) {
1318 $checkedData = $value;
1321 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1322 substr($value, 1, -1)
1326 $states = CRM_Core_PseudoConstant
::stateProvince();
1328 foreach ($checkedData as $stateID) {
1332 $display .= $states[$stateID];
1336 case 'Select Country':
1337 if (empty($value)) {
1341 $display = CRM_Core_PseudoConstant
::country($value);
1345 case 'Multi-Select Country':
1346 if (is_array($value)) {
1347 $checkedData = $value;
1350 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1351 substr($value, 1, -1)
1355 $countries = CRM_Core_PseudoConstant
::country();
1357 foreach ($checkedData as $countryID) {
1361 $display .= $countries[$countryID];
1367 $url = self
::getFileURL($contactID, $fieldID, $value);
1369 $display = $url['file_url'];
1375 if (empty($value)) {
1379 $display = nl2br($value);
1384 if (empty($value)) {
1391 return $display ?
$display : $value;
1395 * Function to set default values for custom data used in profile
1397 * @params int $customFieldId custom field id
1398 * @params string $elementName custom field name
1399 * @params array $defaults associated array of fields
1400 * @params int $contactId contact id
1401 * @param $customFieldId
1402 * @param $elementName
1404 * @param null $contactId
1405 * @param int $mode profile mode
1406 * @param mixed $value if passed - dont fetch value from db,
1407 * just format the given value
1412 static function setProfileDefaults($customFieldId,
1419 //get the type of custom field
1420 $customField = new CRM_Core_BAO_CustomField();
1421 $customField->id
= $customFieldId;
1422 $customField->find(TRUE);
1425 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1426 $value = $customField->default_value
;
1430 if (!isset($value)) {
1431 $info = self
::getTableColumnGroup($customFieldId);
1432 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1433 $result = CRM_Core_DAO
::executeQuery($query);
1434 if ($result->fetch()) {
1435 $value = $result->value
;
1439 if ($customField->data_type
== 'Country') {
1441 $config = CRM_Core_Config
::singleton();
1442 if ($config->defaultContactCountry
) {
1443 $value = $config->defaultContactCountry();
1449 //set defaults if mode is registration
1450 if (!trim($value) &&
1452 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1454 $value = $customField->default_value
;
1457 if ($customField->data_type
== 'Money' && isset($value)) {
1458 $value = number_format($value, 2);
1460 switch ($customField->html_type
) {
1462 case 'AdvMulti-Select':
1463 case 'Multi-Select':
1464 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1465 $defaults[$elementName] = array();
1466 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1467 substr($value, 1, -1)
1469 foreach ($customOption as $val) {
1470 if (in_array($val['value'], $checkedValue)) {
1471 if ($customField->html_type
== 'CheckBox') {
1472 $defaults[$elementName][$val['value']] = 1;
1474 elseif ($customField->html_type
== 'Multi-Select' ||
1475 $customField->html_type
== 'AdvMulti-Select'
1477 $defaults[$elementName][$val['value']] = $val['value'];
1485 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1488 $customField->date_format
,
1489 $customField->time_format
1494 case 'Autocomplete-Select':
1495 if ($customField->data_type
== 'ContactReference') {
1496 if (is_numeric($value)) {
1497 $defaults[$elementName . '_id'] = $value;
1498 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1502 $defaults[$elementName] = $value;
1507 $defaults[$elementName] = $value;
1514 * @param null $fileID
1515 * @param bool $absolute
1522 * @param null $fileID
1523 * @param bool $absolute
1527 static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE) {
1530 $params = array('id' => $cfID);
1531 $defaults = array();
1532 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1533 $columnName = $defaults['column_name'];
1535 //table name of custom data
1536 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1537 $defaults['custom_group_id'],
1541 //query to fetch id from civicrm_file
1542 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1543 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1548 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1553 $result['file_id'] = $fileID;
1555 if ($fileType == 'image/jpeg' ||
1556 $fileType == 'image/pjpeg' ||
1557 $fileType == 'image/gif' ||
1558 $fileType == 'image/x-png' ||
1559 $fileType == 'image/png'
1561 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1566 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1567 list($imageWidth, $imageHeight) = getimagesize($path);
1568 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1569 $url = CRM_Utils_System
::url('civicrm/file',
1570 "reset=1&id=$fileID&eid=$contactID",
1571 $absolute, NULL, TRUE, TRUE
1573 $result['file_url'] = "
1574 <a href=\"$url\" class='crm-image-popup'>
1575 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1577 // for non image files
1580 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1584 $url = CRM_Utils_System
::url('civicrm/file',
1585 "reset=1&id=$fileID&eid=$contactID",
1586 $absolute, NULL, TRUE, TRUE
1588 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1596 * Format custom fields before inserting
1598 * @param int $customFieldId custom field id
1599 * @param array $customFormatted formatted array
1600 * @param mix $value value of custom field
1601 * @param string $customFieldExtend custom field extends
1602 * @param int $customValueId custom option value id
1603 * @param int $entityId entity id (contribution, membership...)
1604 * @param boolean $inline consider inline custom groups only
1605 * @param boolean $checkPermission if false, do not include permissioning clause
1607 * @return array $customFormatted formatted custom field array
1610 static function formatCustomField($customFieldId, &$customFormatted, $value,
1611 $customFieldExtend, $customValueId = NULL,
1614 $checkPermission = TRUE
1616 //get the custom fields for the entity
1617 //subtype and basic type
1618 $customDataSubType = NULL;
1619 if (is_array($customFieldExtend)) {
1620 $customFieldExtend = $customFieldExtend[0];
1623 if (in_array($customFieldExtend,
1624 CRM_Contact_BAO_ContactType
::subTypes()
1626 // This is the case when getFieldsForImport() requires fields
1627 // of subtype and its parent.CRM-5143
1628 $customDataSubType = $customFieldExtend;
1629 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1632 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1642 if (!array_key_exists($customFieldId, $customFields)) {
1646 // return if field is a 'code' field
1647 if (!empty($customFields[$customFieldId]['is_view'])) {
1651 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1653 if (!$customValueId &&
1654 // we always create new entites for is_multiple unless specified
1655 !$customFields[$customFieldId]['is_multiple'] &&
1661 WHERE entity_id={$entityId}";
1663 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1666 //fix checkbox, now check box always submits values
1667 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1669 // Note that only during merge this is not an array, and you can directly use value
1670 if (is_array($value)) {
1671 $selectedValues = array();
1672 foreach ($value as $selId => $val) {
1674 $selectedValues[] = $selId;
1677 if (!empty($selectedValues)) {
1678 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1680 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1689 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1690 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1693 // Note that only during merge this is not an array,
1694 // and you can directly use value, CRM-4385
1695 if (is_array($value)) {
1696 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1697 array_values($value)
1698 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1706 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1707 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1708 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1710 $customFields[$customFieldId]['data_type'] == 'String' &&
1711 !empty($customFields[$customFieldId]['text_length']) &&
1714 // lets make sure that value is less than the length, else we'll
1715 // be losing some data, CRM-7481
1716 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1717 // need to do a few things here
1719 // 1. lets find a new length
1720 $newLength = $customFields[$customFieldId]['text_length'];
1721 $minLength = strlen($value);
1722 while ($newLength < $minLength) {
1723 $newLength = $newLength * 2;
1726 // set the custom field meta data to have a length larger than value
1727 // alter the custom value table column to match this length
1728 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1733 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1734 if (!CRM_Utils_System
::isNull($value)) {
1735 $format = $customFields[$customFieldId]['date_format'];
1736 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1741 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1742 $customFields[$customFieldId]['data_type'] == 'Money'
1748 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1749 $value = CRM_Utils_Rule
::cleanMoney($value);
1753 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1754 $customFields[$customFieldId]['data_type'] == 'Country'
1764 if ($customFields[$customFieldId]['data_type'] == 'File') {
1765 if (empty($value)) {
1769 $config = CRM_Core_Config
::singleton();
1771 $fName = $value['name'];
1772 $mimeType = $value['type'];
1774 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1776 // rename this file to go into the secure directory
1777 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1778 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1781 if ($customValueId) {
1786 $params = array(1 => array($customValueId, 'Integer'));
1787 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1790 $fileDAO = new CRM_Core_DAO_File();
1793 $fileDAO->id
= $fileId;
1796 $fileDAO->uri
= $filename;
1797 $fileDAO->mime_type
= $mimeType;
1798 $fileDAO->upload_date
= date('Ymdhis');
1800 $fileId = $fileDAO->id
;
1804 if (!is_array($customFormatted)) {
1805 $customFormatted = array();
1808 if (!array_key_exists($customFieldId, $customFormatted)) {
1809 $customFormatted[$customFieldId] = array();
1813 if ($customValueId) {
1814 $index = $customValueId;
1817 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1818 $customFormatted[$customFieldId][$index] = array();
1820 $customFormatted[$customFieldId][$index] = array(
1821 'id' => $customValueId > 0 ?
$customValueId : NULL,
1823 'type' => $customFields[$customFieldId]['data_type'],
1824 'custom_field_id' => $customFieldId,
1825 'custom_group_id' => $groupID,
1826 'table_name' => $tableName,
1827 'column_name' => $columnName,
1828 'file_id' => $fileId,
1829 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1832 //we need to sort so that custom fields are created in the order of entry
1833 krsort($customFormatted[$customFieldId]);
1834 return $customFormatted;
1842 static function &defaultCustomTableSchema(&$params) {
1843 // add the id and extends_id
1845 'name' => $params['name'],
1846 'is_multiple' => $params['is_multiple'],
1847 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1851 'type' => 'int unsigned',
1854 'attributes' => 'AUTO_INCREMENT',
1855 'comment' => 'Default MySQL primary key',
1858 'name' => 'entity_id',
1859 'type' => 'int unsigned',
1861 'comment' => 'Table that this extends',
1862 'fk_table_name' => $params['extends_name'],
1863 'fk_field_name' => 'id',
1864 'fk_attributes' => 'ON DELETE CASCADE',
1869 if (!$params['is_multiple']) {
1870 $table['indexes'] = array(
1873 'field_name_1' => 'entity_id',
1883 * @param bool $indexExist
1884 * @param bool $triggerRebuild
1886 static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1887 $tableName = CRM_Core_DAO
::getFieldValue(
1888 'CRM_Core_DAO_CustomGroup',
1889 $field->custom_group_id
,
1894 'table_name' => $tableName,
1895 'operation' => $operation,
1896 'name' => $field->column_name
,
1897 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1901 'required' => $field->is_required
,
1902 'searchable' => $field->is_searchable
,
1905 if ($operation == 'delete') {
1906 $fkName = "{$tableName}_{$field->column_name}";
1907 if (strlen($fkName) >= 48) {
1908 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1910 $params['fkName'] = $fkName;
1912 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1913 $params['fk_table_name'] = 'civicrm_country';
1914 $params['fk_field_name'] = 'id';
1915 $params['fk_attributes'] = 'ON DELETE SET NULL';
1917 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1918 $params['type'] = 'varchar(255)';
1920 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1921 $params['fk_table_name'] = 'civicrm_state_province';
1922 $params['fk_field_name'] = 'id';
1923 $params['fk_attributes'] = 'ON DELETE SET NULL';
1925 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1926 $params['type'] = 'varchar(255)';
1928 elseif ($field->data_type
== 'File') {
1929 $params['fk_table_name'] = 'civicrm_file';
1930 $params['fk_field_name'] = 'id';
1931 $params['fk_attributes'] = 'ON DELETE SET NULL';
1933 elseif ($field->data_type
== 'ContactReference') {
1934 $params['fk_table_name'] = 'civicrm_contact';
1935 $params['fk_field_name'] = 'id';
1936 $params['fk_attributes'] = 'ON DELETE SET NULL';
1938 if ($field->default_value
) {
1939 $params['default'] = "'{$field->default_value}'";
1942 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1946 * Determine whether it would be safe to move a field
1948 * @param int $fieldID FK to civicrm_custom_field
1949 * @param int $newGroupID FK to civicrm_custom_group
1954 static function _moveFieldValidate($fieldID, $newGroupID) {
1957 $field = new CRM_Core_DAO_CustomField();
1958 $field->id
= $fieldID;
1959 if (!$field->find(TRUE)) {
1960 $errors['fieldID'] = 'Invalid ID for custom field';
1964 $oldGroup = new CRM_Core_DAO_CustomGroup();
1965 $oldGroup->id
= $field->custom_group_id
;
1966 if (!$oldGroup->find(TRUE)) {
1967 $errors['fieldID'] = 'Invalid ID for old custom group';
1971 $newGroup = new CRM_Core_DAO_CustomGroup();
1972 $newGroup->id
= $newGroupID;
1973 if (!$newGroup->find(TRUE)) {
1974 $errors['newGroupID'] = 'Invalid ID for new custom group';
1980 FROM civicrm_custom_field a
1981 INNER JOIN civicrm_custom_field b
1983 AND a.label = b.label
1984 AND b.custom_group_id = %2
1987 1 => array($field->id
, 'Integer'),
1988 2 => array($newGroup->id
, 'Integer'),
1990 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1992 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1995 $tableName = $oldGroup->table_name
;
1996 $columnName = $field->column_name
;
2001 WHERE $columnName is not null
2003 $count = CRM_Core_DAO
::singleValueQuery($query,
2004 CRM_Core_DAO
::$_nullArray
2009 FROM civicrm_custom_group
2010 WHERE id IN ( %1, %2 )
2012 $params = array(1 => array($oldGroup->id
, 'Integer'),
2013 2 => array($newGroup->id
, 'Integer'),
2016 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2018 while ($dao->fetch()) {
2019 $extends[] = $dao->extends;
2021 if ($extends[0] != $extends[1]) {
2022 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
2026 return empty($errors) ?
TRUE : $errors;
2030 * Move a custom data field from one group (table) to another
2032 * @param int $fieldID FK to civicrm_custom_field
2033 * @param int $newGroupID FK to civicrm_custom_group
2037 static function moveField($fieldID, $newGroupID) {
2038 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
2039 if (TRUE !== $validation) {
2040 CRM_Core_Error
::fatal(implode(' ', $validation));
2042 $field = new CRM_Core_DAO_CustomField();
2043 $field->id
= $fieldID;
2046 $newGroup = new CRM_Core_DAO_CustomGroup();
2047 $newGroup->id
= $newGroupID;
2048 $newGroup->find(TRUE);
2050 $oldGroup = new CRM_Core_DAO_CustomGroup();
2051 $oldGroup->id
= $field->custom_group_id
;
2052 $oldGroup->find(TRUE);
2055 $add->custom_group_id
= $newGroup->id
;
2056 self
::createField($add, 'add');
2058 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
2059 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
2060 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
2062 CRM_Core_DAO
::executeQuery($sql);
2065 $del->custom_group_id
= $oldGroup->id
;
2066 self
::createField($del, 'delete');
2070 CRM_Utils_System
::flushCache();
2074 * Get the database table name and column name for a custom field
2076 * @param int $fieldID - the fieldID of the custom field
2077 * @param boolean $force - force the sql to be run again (primarily used for tests)
2079 * @return array - fatal is fieldID does not exists, else array of tableName, columnName
2083 static function getTableColumnGroup($fieldID, $force = FALSE) {
2084 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2085 $cache = CRM_Utils_Cache
::singleton();
2086 $fieldValues = $cache->get($cacheKey);
2087 if (empty($fieldValues) ||
$force) {
2089 SELECT cg.table_name, cf.column_name, cg.id
2090 FROM civicrm_custom_group cg,
2091 civicrm_custom_field cf
2092 WHERE cf.custom_group_id = cg.id
2094 $params = array(1 => array($fieldID, 'Integer'));
2095 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2097 if (!$dao->fetch()) {
2098 CRM_Core_Error
::fatal();
2101 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2102 $cache->set($cacheKey, $fieldValues);
2104 return $fieldValues;
2108 * Function to get custom option groups
2110 * @params array $includeFieldIds ids of custom fields for which
2111 * option groups must be included.
2113 * Currently this is required in the cases where option groups are to be included
2114 * for inactive fields : CRM-5369
2118 * @param null $includeFieldIds
2120 * @return mixed $customOptionGroup@static
2122 public static function &customOptionGroup($includeFieldIds = NULL) {
2123 static $customOptionGroup = NULL;
2125 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2126 if ($cacheKey == 'force') {
2127 $customOptionGroup[$cacheKey] = NULL;
2130 if (empty($customOptionGroup[$cacheKey])) {
2131 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2133 //support for single as well as array format.
2134 if (!empty($includeFieldIds)) {
2135 if (is_array($includeFieldIds)) {
2136 $includeFieldIds = implode(',', $includeFieldIds);
2138 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2142 SELECT g.id, g.title
2143 FROM civicrm_option_group g
2144 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2145 WHERE {$whereClause}";
2147 $dao = CRM_Core_DAO
::executeQuery($query);
2148 while ($dao->fetch()) {
2149 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2153 return $customOptionGroup[$cacheKey];
2157 * Function to fix orphan groups
2159 * @params int $customFieldId custom field id
2160 * @params int $optionGroupId option group id
2164 * @param $customFieldId
2165 * @param $optionGroupId
2170 static function fixOptionGroups($customFieldId, $optionGroupId) {
2171 // check if option group belongs to any custom Field else delete
2172 // get the current option group
2173 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2177 // get the updated option group
2178 // if both are same return
2179 if ($currentOptionGroupId == $optionGroupId) {
2183 // check if option group is related to any other field
2184 self
::checkOptionGroup($currentOptionGroupId);
2188 * Function to check if option group is related to more than one
2191 * @params int $optionGroupId option group id
2193 * @param $optionGroupId
2198 static function checkOptionGroup($optionGroupId) {
2201 FROM civicrm_custom_field
2202 WHERE option_group_id = {$optionGroupId}";
2204 $count = CRM_Core_DAO
::singleValueQuery($query);
2207 //delete the option group
2208 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2213 * @param $optionGroupId
2216 * @return null|string
2218 static function getOptionGroupDefault($optionGroupId, $htmlType) {
2220 SELECT default_value, html_type
2221 FROM civicrm_custom_field
2222 WHERE option_group_id = {$optionGroupId}
2223 AND default_value IS NOT NULL
2224 ORDER BY html_type";
2226 $dao = CRM_Core_DAO
::executeQuery($query);
2227 $defaultValue = NULL;
2228 $defaultHTMLType = NULL;
2229 while ($dao->fetch()) {
2230 if ($dao->html_type
== $htmlType) {
2231 return $dao->default_value
;
2233 if ($defaultValue == NULL) {
2234 $defaultValue = $dao->default_value
;
2235 $defaultHTMLType = $dao->html_type
;
2239 // some conversions are needed if either the old or new has a html type which has potential
2240 // multiple default values.
2241 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2242 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2244 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2246 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2247 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2249 $defaultValue = substr($defaultValue, 1, -1);
2250 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2251 substr($defaultValue, 1, -1)
2253 $defaultValue = $values[0];
2256 return $defaultValue;
2261 * @param $customFields
2263 * @param $customFieldExtends
2264 * @param bool $inline
2268 static function postProcess(&$params,
2271 $customFieldExtends,
2274 $customData = array();
2276 foreach ($params as $key => $value) {
2277 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2279 // for autocomplete transfer hidden value instead of label
2280 if ($params[$key] && isset($params[$key . '_id'])) {
2281 $value = $params[$key . '_id'];
2284 // we need to append time with date
2285 if ($params[$key] && isset($params[$key . '_time'])) {
2286 $value .= ' ' . $params[$key . '_time'];
2289 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2292 $customFieldExtends,
2293 $customFieldInfo[1],
2308 static function buildOption($field, &$options) {
2309 // Fixme - adding anything but options to the $options array is a bad idea
2310 // What if an option had the key 'attributes'?
2311 $options['attributes'] = array(
2312 'label' => $field['label'],
2313 'data_type' => $field['data_type'],
2314 'html_type' => $field['html_type'],
2317 $optionGroupID = NULL;
2318 if (($field['html_type'] == 'CheckBox' ||
2319 $field['html_type'] == 'Radio' ||
2320 $field['html_type'] == 'Select' ||
2321 $field['html_type'] == 'AdvMulti-Select' ||
2322 $field['html_type'] == 'Multi-Select' ||
2323 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2325 if ($field['option_group_id']) {
2326 $optionGroupID = $field['option_group_id'];
2328 elseif ($field['data_type'] != 'Boolean') {
2329 CRM_Core_Error
::fatal();
2333 // build the cache for custom values with options (label => value)
2334 if ($optionGroupID != NULL) {
2337 FROM civicrm_option_value
2338 WHERE option_group_id = $optionGroupID
2341 $dao = CRM_Core_DAO
::executeQuery($query);
2342 while ($dao->fetch()) {
2343 if ($field['data_type'] == 'Int' ||
$field['data_type'] == 'Float') {
2344 $num = round($dao->value
, 2);
2345 $options["$num"] = $dao->label
;
2348 $options[$dao->value
] = $dao->label
;
2352 CRM_Utils_Hook
::customFieldOptions($field['id'], $options);
2357 * @param $fieldLabel
2358 * @param null $groupTitle
2362 static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2363 $params = array(1 => array($fieldLabel, 'String'));
2365 $params[2] = array($groupTitle, 'String');
2368 FROM civicrm_custom_field f
2369 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2370 WHERE ( f.label = %1 OR f.name = %1 )
2371 AND ( g.title = %2 OR g.name = %2 )
2377 FROM civicrm_custom_field f
2378 WHERE ( f.label = %1 OR f.name = %1 )
2382 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2383 if ($dao->fetch() &&
2394 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2397 static function getNameFromID($ids) {
2398 if (is_array($ids)) {
2399 $ids = implode(',', $ids);
2402 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2403 FROM civicrm_custom_field f
2404 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2405 WHERE f.id IN ($ids)";
2408 $dao = CRM_Core_DAO
::executeQuery($sql);
2410 while ($dao->fetch()) {
2411 $result[$dao->id
] = array(
2412 'field_name' => $dao->field_name
,
2413 'field_label' => $dao->field_label
,
2414 'group_name' => $dao->group_name
,
2415 'group_title' => $dao->group_title
,
2422 * Validate custom data.
2424 * @param array $params custom data submitted.
2425 * ie array( 'custom_1' => 'validate me' );
2427 * @return array $errors validation errors.
2430 static function validateCustomData($params) {
2432 if (!is_array($params) ||
empty($params)) {
2437 //pick up profile fields.
2438 $profileFields = array();
2439 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2441 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2443 CRM_Core_Action
::VIEW
2447 //lets start w/ params.
2448 foreach ($params as $key => $value) {
2449 $customFieldID = self
::getKeyID($key);
2450 if (!$customFieldID) {
2454 //load the structural info for given field.
2455 $field = new CRM_Core_DAO_CustomField();
2456 $field->id
= $customFieldID;
2457 if (!$field->find(TRUE)) {
2460 $dataType = $field->data_type
;
2462 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2463 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2464 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2466 $fieldTitle = $field->label
;
2469 //no need to validate.
2470 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2474 //lets validate first for required field.
2475 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2476 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2480 //now time to take care of custom field form rules.
2481 $ruleName = $errorMsg = NULL;
2482 switch ($dataType) {
2484 $ruleName = 'integer';
2485 $errorMsg = ts('%1 must be an integer (whole number).',
2486 array(1 => $fieldTitle)
2491 $ruleName = 'money';
2492 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2493 array(1 => $fieldTitle)
2498 $ruleName = 'numeric';
2499 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2500 array(1 => $fieldTitle)
2505 $ruleName = 'wikiURL';
2506 $errorMsg = ts('%1 must be valid Website.',
2507 array(1 => $fieldTitle)
2512 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2514 $funName = "CRM_Utils_Rule::{$ruleName}";
2515 if (is_callable($funName)) {
2516 $valid = call_user_func($funName, $value);
2519 $errors[$key] = $errorMsg;
2532 static function isMultiRecordField($customId) {
2533 $isMultipleWithGid = FALSE;
2534 if (!is_numeric($customId)) {
2535 $customId = self
::getKeyID($customId);
2537 if (is_numeric($customId)) {
2538 $sql = "SELECT cg.id cgId
2539 FROM civicrm_custom_group cg
2540 INNER JOIN civicrm_custom_field cf
2541 ON cg.id = cf.custom_group_id
2542 WHERE cf.id = %1 AND cg.is_multiple = 1";
2543 $params[1] = array($customId, 'Integer');
2544 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2545 if ($dao->fetch()) {
2547 $isMultipleWithGid = $dao->cgId
;
2552 return $isMultipleWithGid;