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