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