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