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