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