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