Merge pull request #20556 from ixiam/dev#2642
[civicrm-core.git] / CRM / Core / BAO / CustomGroup.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
3a8f58ec 19 * Business object for managing custom data groups.
6a488035
TO
20 */
21class CRM_Core_BAO_CustomGroup extends CRM_Core_DAO_CustomGroup {
22
23 /**
fe482240 24 * Class constructor.
6a488035 25 */
00be9182 26 public function __construct() {
6a488035
TO
27 parent::__construct();
28 }
29
30 /**
fe482240 31 * Takes an associative array and creates a custom group object.
6a488035
TO
32 *
33 * This function is invoked from within the web form layer and also from the api layer
34 *
6a0b768e
TO
35 * @param array $params
36 * (reference) an assoc array of name/value pairs.
6a488035 37 *
16b10e64 38 * @return CRM_Core_DAO_CustomGroup
aa965915 39 * @throws \Exception
6a488035 40 */
00be9182 41 public static function create(&$params) {
6a488035
TO
42 // create custom group dao, populate fields and then save.
43 $group = new CRM_Core_DAO_CustomGroup();
117cc973
EM
44 if (isset($params['title'])) {
45 $group->title = $params['title'];
46 }
6a488035 47
9857487f 48 $extendsChildType = NULL;
aa965915 49 // lets allow user to pass direct child type value, CRM-6893
a7488080 50 if (!empty($params['extends_entity_column_value'])) {
6a488035
TO
51 $extendsChildType = $params['extends_entity_column_value'];
52 }
53 if (!CRM_Utils_System::isNull($extendsChildType)) {
92ef7828
SL
54 $b = self::getMungedEntity($params['extends'], $params['extends_entity_column_id'] ?? NULL);
55 $registeredSubTypes = self::getSubTypes()[$b];
13d328b3
SL
56 if (is_array($extendsChildType)) {
57 foreach ($extendsChildType as $childType) {
58 if (!array_key_exists($childType, $registeredSubTypes) && !in_array($childType, $registeredSubTypes, TRUE)) {
59 throw new CRM_Core_Exception('Supplied Sub type is not valid for the specified entitiy');
60 }
61 }
62 }
63 else {
64 if (!array_key_exists($extendsChildType, $registeredSubTypes) && !in_array($extendsChildType, $registeredSubTypes, TRUE)) {
65 throw new CRM_Core_Exception('Supplied Sub type is not valid for the specified entitiy');
66 }
67 $extendsChildType = [$extendsChildType];
68 }
9857487f
SL
69 $extendsChildType = implode(CRM_Core_DAO::VALUE_SEPARATOR, $extendsChildType);
70 if ($params['extends'] == 'Relationship') {
be2fb01f 71 $extendsChildType = str_replace(['_a_b', '_b_a'], [
353ffa53
TO
72 '',
73 '',
be2fb01f 74 ], $extendsChildType);
6a488035
TO
75 }
76 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO::VALUE_SEPARATOR) {
9d72cede
EM
77 $extendsChildType = CRM_Core_DAO::VALUE_SEPARATOR . $extendsChildType .
78 CRM_Core_DAO::VALUE_SEPARATOR;
6a488035
TO
79 }
80 }
81 else {
82 $extendsChildType = 'null';
83 }
84 $group->extends_entity_column_value = $extendsChildType;
85
86 if (isset($params['id'])) {
87 $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
88 }
89 else {
90 $oldWeight = 0;
91 }
92 $group->weight = CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array::value('weight', $params, FALSE));
be2fb01f 93 $fields = [
9d72cede
EM
94 'style',
95 'collapse_display',
96 'collapse_adv_display',
97 'help_pre',
98 'help_post',
99 'is_active',
21dfd5f5 100 'is_multiple',
2af06525 101 'icon',
9857487f
SL
102 'extends_entity_column_id',
103 'extends',
be2fb01f 104 ];
da0577d8
CW
105 $current_db_version = CRM_Core_BAO_Domain::version();
106 $is_public_version = version_compare($current_db_version, '4.7.19', '>=');
f7ed3a24
SL
107 if ($is_public_version) {
108 $fields[] = 'is_public';
109 }
6a488035 110 foreach ($fields as $field) {
e2cb881c
MD
111 if (isset($params[$field])) {
112 $group->$field = $params[$field];
117cc973 113 }
6a488035
TO
114 }
115 $group->max_multiple = isset($params['is_multiple']) ? (isset($params['max_multiple']) &&
116 $params['max_multiple'] >= '0'
117 ) ? $params['max_multiple'] : 'null' : 'null';
118
c746070e 119 $tableName = $tableNameNeedingIndexUpdate = NULL;
6a488035
TO
120 if (isset($params['id'])) {
121 $group->id = $params['id'];
6a488035 122
c746070e 123 if (isset($params['is_multiple'])) {
aa965915 124 // check whether custom group was changed from single-valued to multiple-valued
c746070e 125 $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
6a488035 126 $params['id'],
c746070e 127 'is_multiple'
6a488035 128 );
c746070e 129
1f85becb
SL
130 // dev/core#227 Fix issue where is_multiple in params maybe an empty string if checkbox is not rendered on the form.
131 $paramsIsMultiple = empty($params['is_multiple']) ? 0 : 1;
132 if ($paramsIsMultiple != $isMultiple) {
c746070e 133 $tableNameNeedingIndexUpdate = CRM_Core_DAO::getFieldValue(
134 'CRM_Core_DAO_CustomGroup',
135 $params['id'],
136 'table_name'
137 );
138 }
6a488035
TO
139 }
140 }
141 else {
9c1bc317
CW
142 $group->created_id = $params['created_id'] ?? NULL;
143 $group->created_date = $params['created_date'] ?? NULL;
6a488035 144
e6766df9
CW
145 // Process name only during create, so it never changes
146 if (!empty($params['name'])) {
147 $group->name = CRM_Utils_String::munge($params['name']);
6a488035
TO
148 }
149 else {
e6766df9 150 $group->name = CRM_Utils_String::munge($group->title);
6a488035
TO
151 }
152
e6766df9
CW
153 self::validateCustomGroupName($group);
154
8b3b9a2e
ARW
155 if (isset($params['table_name'])) {
156 $tableName = $params['table_name'];
157
158 if (CRM_Core_DAO_AllCoreTables::isCoreTable($tableName)) {
159 // Bad idea. Prevent group creation because it might lead to a broken configuration.
36769590 160 throw new CRM_Core_Exception(ts('Cannot create custom table because %1 is already a core table.', ['1' => $tableName]));
8b3b9a2e
ARW
161 }
162 }
6a488035
TO
163 }
164
4e8506a4 165 if (array_key_exists('is_reserved', $params)) {
1155dd58 166 $group->is_reserved = $params['is_reserved'] ? 1 : 0;
f329e1de 167 }
202f05c9
FG
168 $op = isset($params['id']) ? 'edit' : 'create';
169 CRM_Utils_Hook::pre($op, 'CustomGroup', CRM_Utils_Array::value('id', $params), $params);
170
6a488035
TO
171 // enclose the below in a transaction
172 $transaction = new CRM_Core_Transaction();
173
174 $group->save();
8b3b9a2e
ARW
175 if (!isset($params['id'])) {
176 if (!isset($params['table_name'])) {
2caf0feb 177 $munged_title = strtolower(CRM_Utils_String::munge($group->title, '_', 13));
8b3b9a2e
ARW
178 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
179 }
6a488035
TO
180 $group->table_name = $tableName;
181 CRM_Core_DAO::setFieldValue('CRM_Core_DAO_CustomGroup',
182 $group->id,
183 'table_name',
184 $tableName
185 );
186
187 // now create the table associated with this group
188 self::createTable($group);
189 }
c746070e 190 elseif ($tableNameNeedingIndexUpdate) {
191 CRM_Core_BAO_SchemaHandler::changeUniqueToIndex($tableNameNeedingIndexUpdate, CRM_Utils_Array::value('is_multiple', $params));
6a488035
TO
192 }
193
194 if (CRM_Utils_Array::value('overrideFKConstraint', $params) == 1) {
195 $table = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
196 $params['id'],
197 'table_name'
198 );
9857487f 199 CRM_Core_BAO_SchemaHandler::changeFKConstraint($table, self::mapTableName($params['extends']));
6a488035
TO
200 }
201 $transaction->commit();
202
203 // reset the cache
204 CRM_Utils_System::flushCache();
205
206 if ($tableName) {
207 CRM_Utils_Hook::post('create', 'CustomGroup', $group->id, $group);
208 }
209 else {
210 CRM_Utils_Hook::post('edit', 'CustomGroup', $group->id, $group);
211 }
212
213 return $group;
214 }
215
216 /**
fe482240 217 * Fetch object based on array of properties.
6a488035 218 *
6a0b768e
TO
219 * @param array $params
220 * (reference ) an assoc array of name/value pairs.
221 * @param array $defaults
222 * (reference ) an assoc array to hold the flattened values.
6a488035 223 *
16b10e64 224 * @return CRM_Core_DAO_CustomGroup
6a488035 225 */
00be9182 226 public static function retrieve(&$params, &$defaults) {
6a488035
TO
227 return CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
228 }
229
e6766df9
CW
230 /**
231 * Ensure group name does not conflict with an existing field
232 *
233 * @param CRM_Core_DAO_CustomGroup $group
234 */
235 public static function validateCustomGroupName(CRM_Core_DAO_CustomGroup $group) {
236 $extends = in_array($group->extends, CRM_Contact_BAO_ContactType::basicTypes(TRUE)) ? 'Contact' : $group->extends;
237 $extendsDAO = CRM_Core_DAO_AllCoreTables::getFullName($extends);
238 if ($extendsDAO) {
239 $fields = array_column($extendsDAO::fields(), 'name');
240 if (in_array($group->name, $fields)) {
241 $group->name .= '0';
242 }
243 }
244 }
245
6a488035 246 /**
fe482240 247 * Update the is_active flag in the db.
6a488035 248 *
6a0b768e
TO
249 * @param int $id
250 * Id of the database record.
a1a2a83d 251 * @param bool $is_active
6a0b768e 252 * Value we want to set the is_active field.
6a488035 253 *
8a4fede3 254 * @return bool
255 * true if we found and updated the object, else false
6a488035 256 */
00be9182 257 public static function setIsActive($id, $is_active) {
6a488035 258 // reset the cache
9cdf85c1 259 Civi::cache('fields')->flush();
5e601882
SL
260 // reset ACL and system caches.
261 CRM_Core_BAO_Cache::resetCaches();
6a488035
TO
262
263 if (!$is_active) {
264 CRM_Core_BAO_UFField::setUFFieldStatus($id, $is_active);
265 }
266
267 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
268 }
269
270 /**
271 * Determine if given entity (sub)type has any custom groups
272 *
6a0b768e
TO
273 * @param string $extends
274 * E.g. "Individual", "Activity".
275 * @param int $columnId
276 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
277 * @param string $columnValue
278 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
77b97be7
EM
279 *
280 * @return bool
6a488035
TO
281 */
282 public static function hasCustomGroup($extends, $columnId, $columnValue) {
283 $dao = new CRM_Core_DAO_CustomGroup();
9d72cede 284 $dao->extends = $extends;
6a488035 285 $dao->extends_entity_column_id = $columnId;
6c552737 286 $escapedValue = CRM_Core_DAO::VALUE_SEPARATOR . CRM_Core_DAO::escapeString($columnValue) . CRM_Core_DAO::VALUE_SEPARATOR;
6a488035
TO
287 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
288 //$dao->extends_entity_column_value = $columnValue;
63d76404 289 return (bool) $dao->find();
6a488035
TO
290 }
291
292 /**
293 * Determine if there are any CustomGroups for the given $activityTypeId.
294 * If none found, create one.
295 *
296 * @param int $activityTypeId
9d72cede 297 *
a6c01b45
CW
298 * @return bool
299 * TRUE if a group is found or created; FALSE on error
6a488035
TO
300 */
301 public static function autoCreateByActivityType($activityTypeId) {
302 if (self::hasCustomGroup('Activity', NULL, $activityTypeId)) {
303 return TRUE;
304 }
cf9ccf98
TO
305 // everything
306 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE);
be2fb01f 307 $params = [
6a488035
TO
308 'version' => 3,
309 'extends' => 'Activity',
310 'extends_entity_column_id' => NULL,
be2fb01f
CW
311 'extends_entity_column_value' => CRM_Utils_Array::implodePadded([$activityTypeId]),
312 'title' => ts('%1 Questions', [1 => $activityTypes[$activityTypeId]]),
6a488035
TO
313 'style' => 'Inline',
314 'is_active' => 1,
be2fb01f 315 ];
6a488035 316 $result = civicrm_api('CustomGroup', 'create', $params);
9d72cede 317 return !$result['is_error'];
6a488035
TO
318 }
319
320 /**
c43cedc8 321 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
322 * This may also include entity specific data values.
6a488035
TO
323 *
324 * An array containing all custom groups and their custom fields is returned.
325 *
6a0b768e
TO
326 * @param string $entityType
327 * Of the contact whose contact type is needed.
0b330e6d
CW
328 * @param array $toReturn
329 * What data should be returned. ['custom_group' => ['id', 'name', etc.], 'custom_field' => ['id', 'label', etc.]]
c490a46a
CW
330 * @param int $entityID
331 * @param int $groupID
79363422 332 * @param array $subTypes
c43cedc8 333 * @param string $subName
c490a46a
CW
334 * @param bool $fromCache
335 * @param bool $onlySubType
b62bc939
EM
336 * Only return specified subtype or return specified subtype + unrestricted fields.
337 * @param bool $returnAll
338 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
339 * api - through which it is properly tested - so can be refactored with some comfort.)
6a488035 340 *
e9ff5391 341 * @param bool $checkPermission
0b330e6d 342 * @param string|int $singleRecord
e1d48b72 343 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
460931ca 344 * @param bool $showPublicOnly
e9ff5391 345 *
a6c01b45 346 * @return array
e9ff5391 347 * Custom field 'tree'.
348 *
16b10e64
CW
349 * The returned array is keyed by group id and has the custom group table fields
350 * and a subkey 'fields' holding the specific custom fields.
351 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
352 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
c43cedc8 353 *
354 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
16b10e64
CW
355 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
356 * With caching the performance impact would be small & the function would be cleaner
aa965915
MWMC
357 *
358 * @throws \CRM_Core_Exception
6a488035 359 */
27dd6252 360 public static function getTree(
0e6e8724 361 $entityType,
be2fb01f 362 $toReturn = [],
6a488035 363 $entityID = NULL,
9d72cede 364 $groupID = NULL,
be2fb01f 365 $subTypes = [],
9d72cede 366 $subName = NULL,
63dbed83 367 $fromCache = TRUE,
b62bc939 368 $onlySubType = NULL,
e9ff5391 369 $returnAll = FALSE,
e1d48b72 370 $checkPermission = TRUE,
460931ca
JP
371 $singleRecord = NULL,
372 $showPublicOnly = FALSE
6a488035
TO
373 ) {
374 if ($entityID) {
375 $entityID = CRM_Utils_Type::escape($entityID, 'Integer');
376 }
79363422
E
377 if (!is_array($subTypes)) {
378 if (empty($subTypes)) {
be2fb01f 379 $subTypes = [];
79363422
E
380 }
381 else {
45e5c872 382 if (stristr($subTypes, ',')) {
35e83f39 383 $subTypes = explode(',', $subTypes);
384 }
385 else {
386 $subTypes = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($subTypes, CRM_Core_DAO::VALUE_SEPARATOR));
387 }
79363422
E
388 }
389 }
6a488035
TO
390
391 // create a new tree
6a488035 392
0b330e6d 393 // legacy hardcoded list of data to return
be2fb01f
CW
394 $tableData = [
395 'custom_field' => [
6a488035 396 'id',
24871985 397 'name',
6a488035
TO
398 'label',
399 'column_name',
400 'data_type',
401 'html_type',
402 'default_value',
403 'attributes',
404 'is_required',
405 'is_view',
406 'help_pre',
407 'help_post',
408 'options_per_line',
409 'start_date_years',
410 'end_date_years',
411 'date_format',
412 'time_format',
413 'option_group_id',
21dfd5f5 414 'in_selector',
be2fb01f
CW
415 ],
416 'custom_group' => [
6a488035
TO
417 'id',
418 'name',
419 'table_name',
420 'title',
421 'help_pre',
422 'help_post',
423 'collapse_display',
f6ad11c1 424 'style',
6a488035
TO
425 'is_multiple',
426 'extends',
427 'extends_entity_column_id',
428 'extends_entity_column_value',
429 'max_multiple',
be2fb01f
CW
430 ],
431 ];
da0577d8
CW
432 $current_db_version = CRM_Core_BAO_Domain::version();
433 $is_public_version = version_compare($current_db_version, '4.7.19', '>=');
434 $serialize_version = version_compare($current_db_version, '5.27.alpha1', '>=');
f7ed3a24
SL
435 if ($is_public_version) {
436 $tableData['custom_group'][] = 'is_public';
437 }
da0577d8
CW
438 if ($serialize_version) {
439 $tableData['custom_field'][] = 'serialize';
440 }
0b330e6d
CW
441 if (!$toReturn || !is_array($toReturn)) {
442 $toReturn = $tableData;
443 }
444 else {
ee21211c
CW
445 // Supply defaults and remove unknown array keys
446 $toReturn = array_intersect_key(array_filter($toReturn) + $tableData, $tableData);
0b330e6d 447 // Merge in required fields that we must have
be2fb01f
CW
448 $toReturn['custom_field'] = array_unique(array_merge($toReturn['custom_field'], ['id', 'column_name', 'data_type']));
449 $toReturn['custom_group'] = array_unique(array_merge($toReturn['custom_group'], ['id', 'is_multiple', 'table_name', 'name']));
0b330e6d
CW
450 // Validate return fields
451 $toReturn['custom_field'] = array_intersect($toReturn['custom_field'], array_keys(CRM_Core_DAO_CustomField::fieldKeys()));
452 $toReturn['custom_group'] = array_intersect($toReturn['custom_group'], array_keys(CRM_Core_DAO_CustomGroup::fieldKeys()));
453 }
6a488035
TO
454
455 // create select
be2fb01f 456 $select = [];
0b330e6d 457 foreach ($toReturn as $tableName => $tableColumn) {
6a488035 458 foreach ($tableColumn as $columnName) {
0b330e6d 459 $select[] = "civicrm_{$tableName}.{$columnName} as civicrm_{$tableName}_{$columnName}";
6a488035
TO
460 }
461 }
462 $strSelect = "SELECT " . implode(', ', $select);
463
464 // from, where, order by
465 $strFrom = "
466FROM civicrm_custom_group
467LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
468";
469
470 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
9d72cede
EM
471 if ($entityType == "Individual" || $entityType == 'Organization' ||
472 $entityType == 'Household'
473 ) {
6a488035
TO
474 $in = "'$entityType', 'Contact'";
475 }
476 elseif (strpos($entityType, "'") !== FALSE) {
477 // this allows the calling function to send in multiple entity types
478 $in = $entityType;
479 }
480 else {
481 // quote it
482 $in = "'$entityType'";
483 }
484
be2fb01f 485 $params = [];
babf3eef 486 $sqlParamKey = 1;
b2ccd9fe 487 $subType = '';
79363422
E
488 if (!empty($subTypes)) {
489 foreach ($subTypes as $key => $subType) {
8cefa956 490 $subTypeClauses[] = self::whereListHas("civicrm_custom_group.extends_entity_column_value", self::validateSubTypeByEntity($entityType, $subType));
6a488035 491 }
cf9ccf98 492 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
79363422
E
493 if (!$onlySubType) {
494 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
993c3848
CB
495 }
496
6a488035
TO
497 $strWhere = "
498WHERE civicrm_custom_group.is_active = 1
499 AND civicrm_custom_field.is_active = 1
500 AND civicrm_custom_group.extends IN ($in)
501 AND $subTypeClause
502";
503 if ($subName) {
babf3eef 504 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = %{$sqlParamKey}";
be2fb01f 505 $params[$sqlParamKey] = [$subName, 'String'];
babf3eef 506 $sqlParamKey = $sqlParamKey + 1;
6a488035
TO
507 }
508 }
509 else {
510 $strWhere = "
511WHERE civicrm_custom_group.is_active = 1
512 AND civicrm_custom_field.is_active = 1
513 AND civicrm_custom_group.extends IN ($in)
6a488035 514";
b62bc939
EM
515 if (!$returnAll) {
516 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
517 }
6a488035
TO
518 }
519
6a488035
TO
520 if ($groupID > 0) {
521 // since we want a specific group id we add it to the where clause
babf3eef 522 $strWhere .= " AND civicrm_custom_group.id = %{$sqlParamKey}";
be2fb01f 523 $params[$sqlParamKey] = [$groupID, 'Integer'];
6a488035
TO
524 }
525 elseif (!$groupID) {
526 // since groupID is false we need to show all Inline groups
527 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
528 }
e9ff5391 529 if ($checkPermission) {
530 // ensure that the user has access to these custom groups
531 $strWhere .= " AND " .
532 CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
533 'civicrm_custom_group.'
534 );
535 }
6a488035 536
f7ed3a24 537 if ($showPublicOnly && $is_public_version) {
460931ca
JP
538 $strWhere .= "AND civicrm_custom_group.is_public = 1";
539 }
540
6a488035
TO
541 $orderBy = "
542ORDER BY civicrm_custom_group.weight,
543 civicrm_custom_group.title,
544 civicrm_custom_field.weight,
545 civicrm_custom_field.label
546";
547
548 // final query string
549 $queryString = "$strSelect $strFrom $strWhere $orderBy";
550
551 // lets see if we can retrieve the groupTree from cache
552 $cacheString = $queryString;
9d72cede 553 if ($groupID > 0) {
6a488035 554 $cacheString .= "_{$groupID}";
9d72cede
EM
555 }
556 else {
6a488035
TO
557 $cacheString .= "_Inline";
558 }
559
560 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
6c552737 561 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
6a488035 562 $cache = CRM_Utils_Cache::singleton();
6a488035
TO
563 if ($fromCache) {
564 $groupTree = $cache->get($cacheKey);
c43cedc8 565 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
6a488035
TO
566 }
567
568 if (empty($groupTree)) {
b2ccd9fe 569 list($multipleFieldGroups, $groupTree) = self::buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType);
6a488035
TO
570
571 $cache->set($cacheKey, $groupTree);
c43cedc8 572 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
6a488035 573 }
aa965915 574 // entitySelectClauses is an array of select clauses for custom value tables which are not multiple
c43cedc8 575 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
be2fb01f
CW
576 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = [];
577 $singleFieldTables = [];
6a488035
TO
578 // now that we have all the groups and fields, lets get the values
579 // since we need to know the table and field names
6a488035 580 // add info to groupTree
c43cedc8 581
9d72cede 582 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
e1d48b72 583 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
9d72cede 584 ) {
be2fb01f 585 $select = $from = $where = [];
c43cedc8 586 $groupTree['info']['where'] = NULL;
6a488035 587
c43cedc8 588 foreach ($groupTree['info']['tables'] as $table => $fields) {
9d72cede 589 $groupTree['info']['from'][] = $table;
be2fb01f 590 $select = [
9d72cede 591 "{$table}.id as {$table}_id",
21dfd5f5 592 "{$table}.entity_id as {$table}_entity_id",
be2fb01f 593 ];
6a488035
TO
594 foreach ($fields as $column => $dontCare) {
595 $select[] = "{$table}.{$column} as {$table}_{$column}";
596 }
c43cedc8 597 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
6a488035 598 if ($entityID) {
c43cedc8 599 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
9d72cede
EM
600 if (in_array($table, $multipleFieldGroups) &&
601 self::customGroupDataExistsForEntity($entityID, $table)
602 ) {
c43cedc8 603 $entityMultipleSelectClauses[$table] = $select;
604 }
9d72cede 605 else {
c43cedc8 606 $singleFieldTables[] = $table;
607 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
608 }
609
6a488035
TO
610 }
611 }
c43cedc8 612 if ($entityID && !empty($singleFieldTables)) {
e8cb3963 613 self::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
c43cedc8 614 }
615 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
9d72cede 616 if (!empty($multipleFieldTablesWithEntityData)) {
e1d48b72 617 self::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
c43cedc8 618 }
6a488035 619
9d72cede 620 }
c43cedc8 621 return $groupTree;
622 }
6a488035 623
79363422
E
624 /**
625 * Clean and validate the filter before it is used in a db query.
626 *
627 * @param string $entityType
628 * @param string $subType
629 *
630 * @return string
631 * @throws \CRM_Core_Exception
79363422
E
632 */
633 protected static function validateSubTypeByEntity($entityType, $subType) {
634 $subType = trim($subType, CRM_Core_DAO::VALUE_SEPARATOR);
635 if (is_numeric($subType)) {
636 return $subType;
637 }
93ecb8e8 638
639 $contactTypes = CRM_Contact_BAO_ContactType::basicTypeInfo(TRUE);
be2fb01f 640 $contactTypes = array_merge($contactTypes, ['Event' => 1]);
2072f97d 641
93ecb8e8 642 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
79363422
E
643 throw new CRM_Core_Exception('Invalid Entity Filter');
644 }
93ecb8e8 645 $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo($entityType, TRUE);
2072f97d 646 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant::eventType());
93ecb8e8 647 if (!array_key_exists($subType, $subTypes)) {
79363422
E
648 throw new CRM_Core_Exception('Invalid Filter');
649 }
650 return $subType;
651 }
652
8cefa956
TO
653 /**
654 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
655 * a WHERE condition for rows that include $value. Use whereListHas().
656 *
657 * @param string $column
658 * @param string $value
659 * @param string $delimiter
660 * @return string
661 * SQL condition.
662 */
518fa0ee 663 private static function whereListHas($column, $value, $delimiter = CRM_Core_DAO::VALUE_SEPARATOR) {
cf9ccf98
TO
664 // ?
665 $bareValue = trim($value, $delimiter);
8cefa956
TO
666 $escapedValue = CRM_Utils_Type::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
667 return "($column LIKE \"$escapedValue\")";
668 }
669
c43cedc8 670 /**
671 * Check whether the custom group has any data for the given entity.
672 *
6a0b768e
TO
673 * @param int $entityID
674 * Id of entity for whom we are checking data for.
675 * @param string $table
676 * Table that we are checking.
c43cedc8 677 *
2a6da8d7
EM
678 * @param bool $getCount
679 *
5c766a0b 680 * @return bool
a6c01b45 681 * does this entity have data in this custom table
c43cedc8 682 */
518fa0ee 683 public static function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
c43cedc8 684 $query = "
685 SELECT count(id)
686 FROM $table
687 WHERE entity_id = $entityID
688 ";
689 $recordExists = CRM_Core_DAO::singleValueQuery($query);
bf076628
PJ
690 if ($getCount) {
691 return $recordExists;
692 }
63d76404 693 return (bool) $recordExists;
c43cedc8 694 }
6a488035 695
9d72cede
EM
696 /**
697 * Build the group tree for Custom fields which are not 'is_multiple'
698 *
699 * The combination of all these fields in one query with a 'using' join was not working for
700 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
701 * mechanism as it seemed to be acceptable in this context
702 *
6a0b768e
TO
703 * @param array $groupTree
704 * (reference) group tree array which is being built.
705 * @param int $entityID
706 * Id of entity for whom the tree is being build up.
707 * @param array $entitySingleSelectClauses
708 * Array of select clauses relevant to the entity.
709 * @param array $singleFieldTablesWithEntityData
710 * Array of tables in which this entity has data.
9d72cede 711 */
518fa0ee 712 public static function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
c43cedc8 713 $select = implode(', ', $entitySingleSelectClauses);
714 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
715 foreach ($singleFieldTablesWithEntityData as $table) {
716 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
717 }
6a488035 718
c43cedc8 719 $query = "
720 SELECT $select
721 FROM $fromSQL
722 WHERE first.entity_id = $entityID
723 ";
e8cb3963 724 self::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
c43cedc8 725 }
6a488035 726
c43cedc8 727 /**
9d72cede
EM
728 * Build the group tree for Custom fields which are 'is_multiple'
729 *
730 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
731 *
6a0b768e
TO
732 * @param array $groupTree
733 * (reference) group tree array which is being built.
734 * @param int $entityID
735 * Id of entity for whom the tree is being build up.
736 * @param array $entityMultipleSelectClauses
737 * Array of select clauses relevant to the entity.
738 * @param array $multipleFieldTablesWithEntityData
739 * Array of tables in which this entity has data.
aa965915 740 * @param string|int $singleRecord
e1d48b72 741 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
9d72cede 742 */
518fa0ee 743 public static function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
c43cedc8 744 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
745 $select = implode(',', $selectClauses);
746 $query = "
747 SELECT $select
748 FROM $table
749 WHERE entity_id = $entityID
750 ";
e1d48b72 751 if ($singleRecord) {
752 $offset = $singleRecord - 1;
753 $query .= " LIMIT {$offset}, 1";
754 }
be2fb01f 755 self::buildTreeEntityDataFromQuery($groupTree, $query, [$table], $singleRecord);
c43cedc8 756 }
757 }
758
759 /**
760 * Build the tree entity data - starting from a query retrieving the custom fields build the group
761 * tree data for the relevant entity (entity is included in the query).
762 *
763 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
764 *
6a0b768e
TO
765 * @param array $groupTree
766 * (reference) group tree array which is being built.
c43cedc8 767 * @param string $query
6a0b768e
TO
768 * @param array $includedTables
769 * Tables to include - required because the function (for historical reasons).
16b10e64 770 * iterates through the group tree
aa965915 771 * @param string|int $singleRecord
e1d48b72 772 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
c43cedc8 773 */
518fa0ee 774 public static function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
c43cedc8 775 $dao = CRM_Core_DAO::executeQuery($query);
776 while ($dao->fetch()) {
777 foreach ($groupTree as $groupID => $group) {
778 if ($groupID === 'info') {
779 continue;
780 }
781 $table = $groupTree[$groupID]['table_name'];
782 //working from the groupTree instead of the table list means we have to iterate & exclude.
783 // this could possibly be re-written as other parts of the function have been refactored
784 // for now we just check if the given table is to be included in this function
9d72cede 785 if (!in_array($table, $includedTables)) {
c43cedc8 786 continue;
787 }
788 foreach ($group['fields'] as $fieldID => $dontCare) {
e1d48b72 789 self::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
c43cedc8 790 }
791 }
792 }
793 }
794
795 /**
796 * Build the entity-specific custom data into the group tree on a per-field basis
797 *
6a0b768e
TO
798 * @param object $dao
799 * Object representing the custom field to be populated into the groupTree.
800 * @param array $groupTree
801 * (reference) the group tree being build.
802 * @param string $table
803 * Table name.
3a8f58ec 804 * @param int $groupID
6a0b768e 805 * Custom group ID.
3a8f58ec 806 * @param int $fieldID
6a0b768e 807 * Custom field ID.
aa965915 808 * @param string|int $singleRecord
e1d48b72 809 * holds 'new' or id if loading view/edit/copy for a single record.
c43cedc8 810 */
518fa0ee 811 public static function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
9d72cede
EM
812 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
813 $idName = "{$table}_id";
c43cedc8 814 $fieldName = "{$table}_{$column}";
815 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
816 if ($dataType == 'File') {
817 if (isset($dao->$fieldName)) {
9d72cede
EM
818 $config = CRM_Core_Config::singleton();
819 $fileDAO = new CRM_Core_DAO_File();
c43cedc8 820 $fileDAO->id = $dao->$fieldName;
821
822 if ($fileDAO->find(TRUE)) {
823 $entityIDName = "{$table}_entity_id";
efddd94f 824 $fileHash = CRM_Core_BAO_File::generateFileHash($dao->$entityIDName, $fileDAO->id);
c43cedc8 825 $customValue['id'] = $dao->$idName;
826 $customValue['data'] = $fileDAO->uri;
827 $customValue['fid'] = $fileDAO->id;
ff9aeadb 828 $customValue['fileURL'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}&fcs=$fileHash");
c43cedc8 829 $customValue['displayURL'] = NULL;
830 $deleteExtra = ts('Are you sure you want to delete attached file.');
be2fb01f
CW
831 $deleteURL = [
832 CRM_Core_Action::DELETE => [
c43cedc8 833 'name' => ts('Delete Attached File'),
834 'url' => 'civicrm/file',
ff9aeadb 835 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete&fcs=%%fcs%%',
a1a2a83d
TO
836 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
837 . '\' ) ) this.href+=\'&amp;confirmed=1\'; else return false;"',
be2fb01f
CW
838 ],
839 ];
c43cedc8 840 $customValue['deleteURL'] = CRM_Core_Action::formLink($deleteURL,
841 CRM_Core_Action::DELETE,
be2fb01f 842 [
c43cedc8 843 'id' => $fileDAO->id,
844 'eid' => $dao->$entityIDName,
845 'fid' => $fieldID,
ff9aeadb 846 'fcs' => $fileHash,
be2fb01f 847 ],
87dab4a4
AH
848 ts('more'),
849 FALSE,
850 'file.manage.delete',
851 'File',
852 $fileDAO->id
c43cedc8 853 );
854 $customValue['deleteURLArgs'] = CRM_Core_BAO_File::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id);
855 $customValue['fileName'] = CRM_Utils_File::cleanFileName(basename($fileDAO->uri));
856 if ($fileDAO->mime_type == "image/jpeg" ||
857 $fileDAO->mime_type == "image/pjpeg" ||
858 $fileDAO->mime_type == "image/gif" ||
859 $fileDAO->mime_type == "image/x-png" ||
860 $fileDAO->mime_type == "image/png"
861 ) {
862 $customValue['displayURL'] = $customValue['fileURL'];
863 $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile',
864 $fileDAO->id,
865 'entity_id',
866 'file_id'
867 );
6c552737 868 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL) .
9d72cede 869 $fileDAO->uri;
9bbc34f1 870 list($path) = CRM_Core_BAO_File::path($fileDAO->id, $entityId);
a52de115
CB
871 if ($path && file_exists($path)) {
872 list($imageWidth, $imageHeight) = getimagesize($path);
873 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
874 $customValue['imageThumbWidth'] = $imageThumbWidth;
875 $customValue['imageThumbHeight'] = $imageThumbHeight;
876 }
6a488035
TO
877 }
878 }
879 }
c43cedc8 880 else {
be2fb01f 881 $customValue = [
c43cedc8 882 'id' => $dao->$idName,
883 'data' => '',
be2fb01f 884 ];
c43cedc8 885 }
886 }
887 else {
be2fb01f 888 $customValue = [
c43cedc8 889 'id' => $dao->$idName,
890 'data' => $dao->$fieldName,
be2fb01f 891 ];
6a488035
TO
892 }
893
c43cedc8 894 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
be2fb01f 895 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [];
c43cedc8 896 }
e1d48b72 897 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
be2fb01f 898 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [$singleRecord => $customValue];
e1d48b72 899 }
900 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
be2fb01f 901 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [1 => $customValue];
c43cedc8 902 }
903 else {
904 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
905 }
6a488035
TO
906 }
907
908 /**
909 * Get the group title.
910 *
6a0b768e
TO
911 * @param int $id
912 * Id of group.
6a488035 913 *
a6c01b45
CW
914 * @return string
915 * title
6a488035
TO
916 */
917 public static function getTitle($id) {
918 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
919 }
920
921 /**
922 * Get custom group details for a group.
923 *
924 * An array containing custom group details (including their custom field) is returned.
925 *
6a0b768e
TO
926 * @param int $groupId
927 * Group id whose details are needed.
928 * @param bool $searchable
929 * Is this field searchable.
930 * @param array $extends
931 * Which table does it extend if any.
dd244018 932 *
aa965915 933 * @param bool $inSelector
6a488035 934 *
a6c01b45
CW
935 * @return array
936 * array consisting of all group and field details
6a488035 937 */
e41f4660 938 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
6a488035 939 // create a new tree
be2fb01f 940 $groupTree = [];
6a488035
TO
941
942 // using tableData to build the queryString
be2fb01f
CW
943 $tableData = [
944 'civicrm_custom_field' => [
6a488035
TO
945 'id',
946 'label',
947 'data_type',
948 'html_type',
949 'default_value',
950 'attributes',
951 'is_required',
952 'help_pre',
953 'help_post',
954 'options_per_line',
955 'is_searchable',
956 'start_date_years',
957 'end_date_years',
958 'is_search_range',
959 'date_format',
960 'time_format',
961 'note_columns',
962 'note_rows',
963 'column_name',
964 'is_view',
965 'option_group_id',
e41f4660 966 'in_selector',
be2fb01f
CW
967 ],
968 'civicrm_custom_group' => [
6a488035
TO
969 'id',
970 'name',
971 'title',
972 'help_pre',
973 'help_post',
974 'collapse_display',
975 'collapse_adv_display',
976 'extends',
977 'extends_entity_column_value',
978 'table_name',
e41f4660 979 'is_multiple',
be2fb01f
CW
980 ],
981 ];
6a488035
TO
982
983 // create select
be2fb01f 984 $s = [];
6a488035
TO
985 foreach ($tableData as $tableName => $tableColumn) {
986 foreach ($tableColumn as $columnName) {
987 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
988 }
989 }
990 $select = 'SELECT ' . implode(', ', $s);
be2fb01f 991 $params = [];
6a488035
TO
992 // from, where, order by
993 $from = " FROM civicrm_custom_field, civicrm_custom_group";
994 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
995 AND civicrm_custom_group.is_active = 1
996 AND civicrm_custom_field.is_active = 1 ";
997 if ($groupId) {
be2fb01f 998 $params[1] = [$groupId, 'Integer'];
6a488035
TO
999 $where .= " AND civicrm_custom_group.id = %1";
1000 }
1001
1002 if ($searchable) {
1003 $where .= " AND civicrm_custom_field.is_searchable = 1";
1004 }
1005
e41f4660
PJ
1006 if ($inSelector) {
1007 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
1008 }
1009
6a488035 1010 if ($extends) {
be2fb01f 1011 $clause = [];
6a488035
TO
1012 foreach ($extends as $e) {
1013 $clause[] = "civicrm_custom_group.extends = '$e'";
1014 }
1015 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1016
1017 //include case activities customdata if case is enabled
1018 if (in_array('Activity', $extends)) {
1019 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1020 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
be2fb01f 1021 $params[2] = [CRM_Core_DAO::VALUE_SEPARATOR, 'String'];
6a488035
TO
1022 }
1023 }
1024
1025 // ensure that the user has access to these custom groups
9d72cede
EM
1026 $where .= " AND " .
1027 CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
1028 'civicrm_custom_group.'
1029 );
6a488035
TO
1030
1031 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1032
1033 // final query string
1034 $queryString = $select . $from . $where . $orderBy;
1035
1036 // dummy dao needed
1037 $crmDAO = CRM_Core_DAO::executeQuery($queryString, $params);
1038
1039 // process records
1040 while ($crmDAO->fetch()) {
1041 $groupId = $crmDAO->civicrm_custom_group_id;
1042 $fieldId = $crmDAO->civicrm_custom_field_id;
1043
1044 // create an array for groups if it does not exist
1045 if (!array_key_exists($groupId, $groupTree)) {
be2fb01f 1046 $groupTree[$groupId] = [];
6a488035
TO
1047 $groupTree[$groupId]['id'] = $groupId;
1048
1049 foreach ($tableData['civicrm_custom_group'] as $v) {
1050 $fullField = "civicrm_custom_group_" . $v;
1051
1052 if ($v == 'id' || is_null($crmDAO->$fullField)) {
1053 continue;
1054 }
1055
1056 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1057 }
1058
be2fb01f 1059 $groupTree[$groupId]['fields'] = [];
6a488035
TO
1060 }
1061
1062 // add the fields now (note - the query row will always contain a field)
be2fb01f 1063 $groupTree[$groupId]['fields'][$fieldId] = [];
6a488035
TO
1064 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1065
1066 foreach ($tableData['civicrm_custom_field'] as $v) {
1067 $fullField = "civicrm_custom_field_" . $v;
1068 if ($v == 'id' || is_null($crmDAO->$fullField)) {
1069 continue;
1070 }
1071 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1072 }
1073 }
1074
1075 return $groupTree;
1076 }
1077
b5c2afd0
EM
1078 /**
1079 * @param $entityType
1080 * @param $path
1081 * @param string $cidToken
1082 *
1083 * @return array
1084 */
6a488035
TO
1085 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1086 // for Group's
1087 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1088
e41f4660
PJ
1089 // get 'Tab' and 'Tab with table' groups
1090 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
6a488035
TO
1091 $customGroupDAO->whereAdd("is_active = 1");
1092
1093 // add whereAdd for entity type
1094 self::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1095
be2fb01f 1096 $groups = [];
6a488035
TO
1097
1098 $permissionClause = CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW, NULL, TRUE);
1099 $customGroupDAO->whereAdd($permissionClause);
1100
1101 // order by weight
1102 $customGroupDAO->orderBy('weight');
1103 $customGroupDAO->find();
1104
1105 // process each group with menu tab
1106 while ($customGroupDAO->fetch()) {
be2fb01f 1107 $group = [];
9d72cede
EM
1108 $group['id'] = $customGroupDAO->id;
1109 $group['path'] = $path;
1110 $group['title'] = "$customGroupDAO->title";
1111 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
be2fb01f 1112 $group['extra'] = ['gid' => $customGroupDAO->id];
6a488035 1113 $group['table_name'] = $customGroupDAO->table_name;
a97040f5 1114 $group['is_multiple'] = $customGroupDAO->is_multiple;
2af06525 1115 $group['icon'] = $customGroupDAO->icon;
9d72cede 1116 $groups[] = $group;
6a488035
TO
1117 }
1118
1119 return $groups;
1120 }
1121
1122 /**
1123 * Get the table name for the entity type
1124 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1125 * tableName is 'civicrm_contact'
1126 *
6a0b768e
TO
1127 * @param string $entityType
1128 * What entity are we extending here ?.
6a488035 1129 *
a6c01b45 1130 * @return string
6a488035 1131 *
6a488035 1132 *
6de76520 1133 * @see _apachesolr_civiAttachments_dereference_file_parent
6a488035 1134 */
6de76520 1135 public static function getTableNameByEntityName($entityType) {
6a488035
TO
1136 switch ($entityType) {
1137 case 'Contact':
1138 case 'Individual':
1139 case 'Household':
1140 case 'Organization':
c9eaf5de 1141 return 'civicrm_contact';
6a488035 1142
c9eaf5de
CW
1143 default:
1144 return CRM_Core_DAO_AllCoreTables::getTableForEntityName($entityType);
6a488035 1145 }
6a488035
TO
1146 }
1147
1148 /**
1149 * Get a list of custom groups which extend a given entity type.
1150 * If there are custom-groups which only apply to certain subtypes,
1151 * those WILL be included.
1152 *
5a4f6742 1153 * @param string $entityType
9d72cede 1154 *
6a488035
TO
1155 * @return CRM_Core_DAO_CustomGroup
1156 */
00be9182 1157 public static function getAllCustomGroupsByBaseEntity($entityType) {
6a488035
TO
1158 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1159 self::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1160 return $customGroupDAO;
1161 }
1162
1163 /**
1164 * Add the whereAdd clause for the DAO depending on the type of entity
1165 * the custom group is extending.
1166 *
6c552737 1167 * @param object $customGroupDAO
6a0b768e
TO
1168 * @param string $entityType
1169 * What entity are we extending here ?.
fd31fa4c 1170 *
6c552737 1171 * @param int $entityID
fd31fa4c 1172 * @param bool $allSubtypes
6a488035
TO
1173 */
1174 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1175 $addSubtypeClause = FALSE;
6bbc383d 1176 // This function isn't really accessible with user data but since the string
1177 // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless
1178 // precaution.
1179 $entityType = CRM_Core_DAO::escapeString($entityType);
6a488035
TO
1180
1181 switch ($entityType) {
1182 case 'Contact':
1183 // if contact, get all related to contact
1184 $extendList = "'Contact','Individual','Household','Organization'";
1185 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1186 if (!$allSubtypes) {
1187 $addSubtypeClause = TRUE;
1188 }
1189 break;
1190
1191 case 'Individual':
1192 case 'Household':
1193 case 'Organization':
1194 // is I/H/O then get I/H/O and contact
1195 $extendList = "'Contact','$entityType'";
1196 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1197 if (!$allSubtypes) {
1198 $addSubtypeClause = TRUE;
1199 }
1200 break;
1201
6bbc383d 1202 default:
6a488035
TO
1203 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1204 break;
1205 }
1206
1207 if ($addSubtypeClause) {
1208 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact::getContactSubType($entityID) : FALSE;
1209
1210 if (!empty($csType)) {
be2fb01f 1211 $subtypeClause = [];
6a488035 1212 foreach ($csType as $subtype) {
9d72cede
EM
1213 $subtype = CRM_Core_DAO::VALUE_SEPARATOR . $subtype .
1214 CRM_Core_DAO::VALUE_SEPARATOR;
6a488035
TO
1215 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1216 }
1217 $subtypeClause[] = "extends_entity_column_value IS NULL";
9d72cede
EM
1218 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1219 " )");
6a488035
TO
1220 }
1221 else {
1222 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1223 }
1224 }
1225 }
1226
1227 /**
1228 * Delete the Custom Group.
1229 *
3a8f58ec
EM
1230 * @param CRM_Core_BAO_CustomGroup $group
1231 * Custom group object.
5a4f6742
CW
1232 * @param bool $force
1233 * whether to force the deletion, even if there are custom fields.
6a488035 1234 *
5c766a0b 1235 * @return bool
3a8f58ec 1236 * False if field exists for this group, true if group gets deleted.
6a488035
TO
1237 */
1238 public static function deleteGroup($group, $force = FALSE) {
1239
3a8f58ec 1240 //check whether this contain any custom fields
6a488035
TO
1241 $customField = new CRM_Core_DAO_CustomField();
1242 $customField->custom_group_id = $group->id;
1243 $customField->find();
1244
1245 // return early if there are custom fields and we're not
1246 // forcing the delete, otherwise delete the fields one by one
1247 while ($customField->fetch()) {
1248 if (!$force) {
1249 return FALSE;
1250 }
1251 CRM_Core_BAO_CustomField::deleteField($customField);
1252 }
1253
1254 // drop the table associated with this custom group
1255 CRM_Core_BAO_SchemaHandler::dropTable($group->table_name);
1256
1257 //delete custom group
1258 $group->delete();
1259
1260 CRM_Utils_Hook::post('delete', 'CustomGroup', $group->id, $group);
1261
1262 return TRUE;
1263 }
1264
a4fc91e0
MW
1265 /**
1266 * Delete a record from supplied params.
1267 * API3 calls deleteGroup() which removes the related civicrm_value_X table.
1268 * This function does the same for API4.
1269 *
1270 * @param array $record
1271 * 'id' is required.
1272 * @return CRM_Core_DAO
1273 * @throws CRM_Core_Exception
1274 */
1275 public static function deleteRecord(array $record) {
1276 $table = CRM_Core_DAO::getFieldValue(__CLASS__, $record['id'], 'table_name');
1277 $result = parent::deleteRecord($record);
1278 CRM_Core_BAO_SchemaHandler::dropTable($table);
1279 return $result;
1280 }
1281
b5c2afd0 1282 /**
3a8f58ec
EM
1283 * Set defaults.
1284 *
1285 * @param array $groupTree
1286 * @param array $defaults
b5c2afd0
EM
1287 * @param bool $viewMode
1288 * @param bool $inactiveNeeded
1289 * @param int $action
1290 */
00be9182 1291 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action::NONE) {
6a488035
TO
1292 foreach ($groupTree as $id => $group) {
1293 if (!isset($group['fields'])) {
1294 continue;
1295 }
6a488035 1296 foreach ($group['fields'] as $field) {
015ba54e 1297 if (isset($field['element_value'])) {
6a488035
TO
1298 $value = $field['element_value'];
1299 }
015ba54e 1300 elseif (isset($field['default_value']) &&
6a488035
TO
1301 ($action != CRM_Core_Action::UPDATE ||
1302 // CRM-7548
1303 !array_key_exists('element_value', $field)
1304 )
1305 ) {
1306 $value = $viewMode ? NULL : $field['default_value'];
1307 }
1308 else {
1309 continue;
1310 }
1311
3dd2f681
BZ
1312 if (empty($field['element_name'])) {
1313 continue;
6df71703 1314 }
58593e74 1315
3dd2f681 1316 $elementName = $field['element_name'];
e30142ba 1317 $serialize = CRM_Core_BAO_CustomField::isSerialized($field);
58593e74 1318
e30142ba 1319 if ($serialize) {
a61d2ab7 1320 if ($field['data_type'] != 'Country' && $field['data_type'] != 'StateProvince' && $field['data_type'] != 'ContactReference') {
be2fb01f 1321 $defaults[$elementName] = [];
6a488035
TO
1322 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($field['id'], $inactiveNeeded);
1323 if ($viewMode) {
1324 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1));
1325 if (isset($value)) {
1326 foreach ($customOption as $customValue => $customLabel) {
1327 if (in_array($customValue, $checkedData)) {
1328 if ($field['html_type'] == 'CheckBox') {
1329 $defaults[$elementName][$customValue] = 1;
1330 }
1331 else {
1332 $defaults[$elementName][$customValue] = $customValue;
1333 }
1334 }
1335 else {
1336 $defaults[$elementName][$customValue] = 0;
1337 }
1338 }
1339 }
1340 }
1341 else {
1342 if (isset($field['customValue']['data'])) {
1343 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($field['customValue']['data'], 1, -1));
1344 foreach ($customOption as $val) {
1345 if (in_array($val['value'], $checkedData)) {
1346 if ($field['html_type'] == 'CheckBox') {
1347 $defaults[$elementName][$val['value']] = 1;
1348 }
1349 else {
1350 $defaults[$elementName][$val['value']] = $val['value'];
1351 }
1352 }
1353 else {
1354 $defaults[$elementName][$val['value']] = 0;
1355 }
1356 }
1357 }
1358 else {
b4afac65 1359 // Values may be "array strings" or actual arrays. Handle both.
fb56e964 1360 if (is_array($value) && count($value)) {
1361 CRM_Utils_Array::formatArrayKeys($value);
1362 $checkedValue = $value;
1363 }
1364 else {
1365 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1));
1366 }
6a488035
TO
1367 foreach ($customOption as $val) {
1368 if (in_array($val['value'], $checkedValue)) {
1369 if ($field['html_type'] == 'CheckBox') {
1370 $defaults[$elementName][$val['value']] = 1;
1371 }
1372 else {
1373 $defaults[$elementName][$val['value']] = $val['value'];
1374 }
1375 }
1376 }
1377 }
1378 }
e30142ba
CW
1379 }
1380 else {
6a488035 1381 if (isset($value)) {
b4afac65
CW
1382 // Values may be "array strings" or actual arrays. Handle both.
1383 if (is_array($value) && count($value)) {
1384 CRM_Utils_Array::formatArrayKeys($value);
1385 $checkedValue = $value;
1386 }
01f1409c
CW
1387 // Serialized values from db
1388 elseif ($value === '' || strpos($value, CRM_Core_DAO::VALUE_SEPARATOR) !== FALSE) {
1389 $checkedValue = CRM_Utils_Array::explodePadded($value);
1390 }
1391 // Comma-separated values e.g. from a select2 widget during reload on form error
b4afac65 1392 else {
01f1409c 1393 $checkedValue = explode(',', $value);
b4afac65 1394 }
6a488035
TO
1395 foreach ($checkedValue as $val) {
1396 if ($val) {
1397 $defaults[$elementName][$val] = $val;
1398 }
1399 }
1400 }
e30142ba
CW
1401 }
1402 }
1403 else {
1404 if ($field['data_type'] == 'Country') {
6a488035
TO
1405 if ($value) {
1406 $defaults[$elementName] = $value;
1407 }
1408 else {
1409 $config = CRM_Core_Config::singleton();
1410 $defaults[$elementName] = $config->defaultContactCountry;
1411 }
e30142ba
CW
1412 }
1413 else {
6a488035 1414 if ($field['data_type'] == "Float") {
9d72cede 1415 $defaults[$elementName] = (float) $value;
6a488035
TO
1416 }
1417 elseif ($field['data_type'] == 'Money' &&
1418 $field['html_type'] == 'Text'
1419 ) {
476a47e9 1420 $defaults[$elementName] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($value);
6a488035
TO
1421 }
1422 else {
1423 $defaults[$elementName] = $value;
1424 }
e30142ba 1425 }
6a488035
TO
1426 }
1427 }
1428 }
1429 }
1430
b5c2afd0 1431 /**
54844703
CW
1432 * Old function only called from one place...
1433 * @see CRM_Dedupe_Finder::formatParams
3a8f58ec
EM
1434 *
1435 * @param array $groupTree
c490a46a 1436 * @param array $params
b5c2afd0
EM
1437 * @param bool $skipFile
1438 */
00be9182 1439 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
6a488035 1440 // Get the Custom form values and groupTree
6a488035
TO
1441 foreach ($groupTree as $groupID => $group) {
1442 if ($groupID === 'info') {
1443 continue;
1444 }
1445 foreach ($group['fields'] as $field) {
1446 $fieldId = $field['id'];
54844703 1447 $serialize = CRM_Core_BAO_CustomField::isSerialized($field);
6a488035 1448
54844703
CW
1449 // Reset all checkbox, radio and multiselect data
1450 if ($field['html_type'] == 'Radio' || $serialize) {
6a488035
TO
1451 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1452 }
1453
1454 $v = NULL;
1455 foreach ($params as $key => $val) {
1456 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1457 $match[1] == $field['id']
1458 ) {
1459 $v = $val;
1460 }
1461 }
1462
6a488035
TO
1463 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1464 // field exists in db so populate value from "form".
be2fb01f 1465 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = [];
6a488035
TO
1466 }
1467
54844703
CW
1468 // Serialize checkbox and multi-select data (using array keys for checkbox)
1469 if ($serialize) {
1470 $v = ($v && $field['html_type'] === 'Checkbox') ? array_keys($v) : $v;
1471 $v = $v ? CRM_Utils_Array::implodePadded($v) : NULL;
1472 }
6a488035 1473
54844703 1474 switch ($field['html_type']) {
6a488035
TO
1475
1476 case 'Select Date':
1477 $date = CRM_Utils_Date::processDate($v);
1478 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1479 break;
1480
1481 case 'File':
1482 if ($skipFile) {
94b444d0 1483 break;
6a488035
TO
1484 }
1485
aa965915 1486 // store the file in d/b
6a488035 1487 $entityId = explode('=', $groupTree['info']['where'][0]);
be2fb01f 1488 $fileParams = ['upload_date' => date('YmdHis')];
6a488035
TO
1489
1490 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1491 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1492 }
1493 if (!empty($v)) {
1494 $fileParams['uri'] = $v['name'];
1495 $fileParams['mime_type'] = $v['type'];
1496 CRM_Core_BAO_File::filePostProcess($v['name'],
1497 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1498 $groupTree[$groupID]['table_name'],
1499 trim($entityId[1]),
1500 FALSE,
1501 TRUE,
1502 $fileParams,
1503 'custom_' . $fieldId,
1504 $v['type']
1505 );
1506 }
be2fb01f
CW
1507 $defaults = [];
1508 $paramsFile = [
6a488035
TO
1509 'entity_table' => $groupTree[$groupID]['table_name'],
1510 'entity_id' => $entityId[1],
be2fb01f 1511 ];
6a488035
TO
1512
1513 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_EntityFile',
1514 $paramsFile,
1515 $defaults
1516 );
1517
1518 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1519 break;
1520
1521 default:
1522 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1523 break;
1524 }
1525 }
1526 }
1527 }
1528
1529 /**
fe482240 1530 * Generic function to build all the form elements for a specific group tree.
6a488035 1531 *
6a0b768e
TO
1532 * @param CRM_Core_Form $form
1533 * The form object.
1534 * @param array $groupTree
1535 * The group tree object.
1536 * @param bool $inactiveNeeded
1537 * Return inactive custom groups.
1538 * @param string $prefix
1539 * Prefix for custom grouptree assigned to template.
aa965915
MWMC
1540 *
1541 * @throws \CiviCRM_API3_Exception
6a488035 1542 */
00be9182 1543 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
6a488035 1544 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
6a488035 1545
6a488035 1546 foreach ($groupTree as $id => $group) {
6a488035 1547 foreach ($group['fields'] as $field) {
9c1bc317 1548 $required = $field['is_required'] ?? NULL;
6a488035
TO
1549 //fix for CRM-1620
1550 if ($field['data_type'] == 'File') {
bdadc7ac 1551 if (!empty($field['element_value']['data'])) {
6a488035
TO
1552 $required = 0;
1553 }
1554 }
1555
1556 $fieldId = $field['id'];
1557 $elementName = $field['element_name'];
3a7773be 1558 CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, $required);
25cdc89e
MWMC
1559 if ($form->getAction() == CRM_Core_Action::VIEW) {
1560 $form->getElement($elementName)->freeze();
1561 }
6a488035
TO
1562 }
1563 }
1564 }
1565
1566 /**
3a8f58ec 1567 * Extract the get params from the url, validate and store it in session.
6a488035 1568 *
6a0b768e
TO
1569 * @param CRM_Core_Form $form
1570 * The form object.
1571 * @param string $type
1572 * The type of custom group we are using.
6a488035 1573 *
03110609 1574 * @return array
aa965915
MWMC
1575 * @throws \CRM_Core_Exception
1576 * @throws \CiviCRM_API3_Exception
6a488035 1577 */
00be9182 1578 public static function extractGetParams(&$form, $type) {
6a488035 1579 if (empty($_GET)) {
be2fb01f 1580 return [];
6a488035
TO
1581 }
1582
79363422 1583 $groupTree = CRM_Core_BAO_CustomGroup::getTree($type);
be2fb01f
CW
1584 $customValue = [];
1585 $htmlType = [
9d72cede
EM
1586 'CheckBox',
1587 'Multi-Select',
9d72cede 1588 'Select',
21dfd5f5 1589 'Radio',
be2fb01f 1590 ];
6a488035
TO
1591
1592 foreach ($groupTree as $group) {
1593 if (!isset($group['fields'])) {
1594 continue;
1595 }
1596 foreach ($group['fields'] as $key => $field) {
1597 $fieldName = 'custom_' . $key;
6fc7508a 1598 $value = CRM_Utils_Request::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
6a488035
TO
1599
1600 if ($value) {
1601 $valid = FALSE;
1602 if (!in_array($field['html_type'], $htmlType) ||
1603 $field['data_type'] == 'Boolean'
1604 ) {
1605 $valid = CRM_Core_BAO_CustomValue::typecheck($field['data_type'], $value);
1606 }
3d86eb05 1607 if (CRM_Core_BAO_CustomField::isSerialized($field)) {
9d72cede
EM
1608 $value = str_replace("|", ",", $value);
1609 $mulValues = explode(',', $value);
6a488035 1610 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, TRUE);
be2fb01f 1611 $val = [];
6a488035
TO
1612 foreach ($mulValues as $v1) {
1613 foreach ($customOption as $coID => $coValue) {
9d72cede
EM
1614 if (strtolower(trim($coValue['label'])) ==
1615 strtolower(trim($v1))
1616 ) {
6a488035
TO
1617 $val[$coValue['value']] = 1;
1618 }
1619 }
1620 }
1621 if (!empty($val)) {
1622 $value = $val;
1623 $valid = TRUE;
1624 }
1625 else {
1626 $value = NULL;
1627 }
1628 }
36769590 1629 elseif ($field['html_type'] === 'Select' ||
1630 ($field['html_type'] === 'Radio' &&
1631 $field['data_type'] !== 'Boolean'
6a488035
TO
1632 )
1633 ) {
1634 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, TRUE);
1635 foreach ($customOption as $customID => $coValue) {
9d72cede
EM
1636 if (strtolower(trim($coValue['label'])) ==
1637 strtolower(trim($value))
1638 ) {
6a488035
TO
1639 $value = $coValue['value'];
1640 $valid = TRUE;
1641 }
1642 }
1643 }
36769590 1644 elseif ($field['data_type'] === 'Date') {
31349d27 1645 $valid = CRM_Utils_Rule::date($value);
6a488035
TO
1646 }
1647
1648 if ($valid) {
1649 $customValue[$fieldName] = $value;
1650 }
1651 }
1652 }
1653 }
1654
1655 return $customValue;
1656 }
1657
1658 /**
100fef9d 1659 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
6a488035
TO
1660 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1661 *
6a0b768e
TO
1662 * @param int $customFieldId
1663 * Custom field id.
1664 * @param array $removeCustomFieldTypes
1665 * Remove custom fields of a type eg: array("Individual") ;.
6a488035 1666 *
5c766a0b 1667 * @return bool
a6c01b45 1668 * false if it matches else true
36769590 1669 *
1670 * @throws \CRM_Core_Exception
6a488035 1671 */
00be9182 1672 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
36769590 1673 $query = 'SELECT cg.extends as extends
6a488035
TO
1674 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1675 WHERE cg.id = cf.custom_group_id
36769590 1676 AND cf.id =' .
9d72cede 1677 CRM_Utils_Type::escape($customFieldId, 'Integer');
6a488035
TO
1678
1679 $extends = CRM_Core_DAO::singleValueQuery($query);
1680
1681 if (in_array($extends, $removeCustomFieldTypes)) {
1682 return FALSE;
1683 }
1684 return TRUE;
1685 }
1686
b5c2afd0
EM
1687 /**
1688 * @param $table
1689 *
1690 * @return string
1691 * @throws Exception
1692 */
00be9182 1693 public static function mapTableName($table) {
6a488035
TO
1694 switch ($table) {
1695 case 'Contact':
1696 case 'Individual':
1697 case 'Household':
1698 case 'Organization':
1699 return 'civicrm_contact';
1700
1701 case 'Activity':
1702 return 'civicrm_activity';
1703
1704 case 'Group':
1705 return 'civicrm_group';
1706
1707 case 'Contribution':
1708 return 'civicrm_contribution';
1709
95974e8e
DG
1710 case 'ContributionRecur':
1711 return 'civicrm_contribution_recur';
1712
6a488035
TO
1713 case 'Relationship':
1714 return 'civicrm_relationship';
1715
1716 case 'Event':
1717 return 'civicrm_event';
1718
1719 case 'Membership':
1720 return 'civicrm_membership';
1721
1722 case 'Participant':
1723 case 'ParticipantRole':
1724 case 'ParticipantEventName':
1725 case 'ParticipantEventType':
1726 return 'civicrm_participant';
1727
1728 case 'Grant':
1729 return 'civicrm_grant';
1730
1731 case 'Pledge':
1732 return 'civicrm_pledge';
1733
1734 case 'Address':
1735 return 'civicrm_address';
1736
1737 case 'Campaign':
1738 return 'civicrm_campaign';
1739
1740 default:
1741 $query = "
1742SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
be2fb01f 1743 $qParams = [1 => [$table, 'String']];
6a488035
TO
1744 $result = CRM_Core_DAO::singleValueQuery($query, $qParams);
1745
1746 if ($result) {
1747 return 'civicrm_contact';
1748 }
1749 else {
1750 $extendObjs = CRM_Core_OptionGroup::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1751 if (array_key_exists($table, $extendObjs)) {
1752 return $extendObjs[$table];
1753 }
36769590 1754 throw new CRM_Core_Exception('Unknown error');
6a488035
TO
1755 }
1756 }
1757 }
1758
b5c2afd0
EM
1759 /**
1760 * @param $group
aa965915
MWMC
1761 *
1762 * @throws \Exception
b5c2afd0 1763 */
00be9182 1764 public static function createTable($group) {
be2fb01f 1765 $params = [
6a488035
TO
1766 'name' => $group->table_name,
1767 'is_multiple' => $group->is_multiple ? 1 : 0,
1768 'extends_name' => self::mapTableName($group->extends),
be2fb01f 1769 ];
6a488035
TO
1770
1771 $tableParams = CRM_Core_BAO_CustomField::defaultCustomTableSchema($params);
1772
1773 CRM_Core_BAO_SchemaHandler::createTable($tableParams);
1774 }
1775
1776 /**
aa965915 1777 * Function returns formatted groupTree, so that form can be easily built in template
6a488035 1778 *
6a0b768e 1779 * @param array $groupTree
6a0b768e 1780 * @param int $groupCount
aa965915
MWMC
1781 * Group count by default 1, but can vary for multiple value custom data.
1782 * @param \CRM_Core_Form $form
6a488035 1783 *
a6c01b45 1784 * @return array
aa965915 1785 * @throws \CRM_Core_Exception
6a488035 1786 */
18b623d0 1787 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NULL) {
be2fb01f
CW
1788 $formattedGroupTree = [];
1789 $uploadNames = $formValues = [];
fb56e964 1790
29a1df58 1791 // retrieve qf key from url
1792 $qfKey = CRM_Utils_Request::retrieve('qf', 'String');
1793
1794 // fetch submitted custom field values later use to set as a default values
1795 if ($qfKey) {
792fce0b 1796 $submittedValues = Civi::cache('customData')->get($qfKey);
fb56e964 1797 }
6a488035
TO
1798
1799 foreach ($groupTree as $key => $value) {
1800 if ($key === 'info') {
1801 continue;
1802 }
1803
1804 // add group information
9c1bc317
CW
1805 $formattedGroupTree[$key]['name'] = $value['name'] ?? NULL;
1806 $formattedGroupTree[$key]['title'] = $value['title'] ?? NULL;
1807 $formattedGroupTree[$key]['help_pre'] = $value['help_pre'] ?? NULL;
1808 $formattedGroupTree[$key]['help_post'] = $value['help_post'] ?? NULL;
1809 $formattedGroupTree[$key]['collapse_display'] = $value['collapse_display'] ?? NULL;
1810 $formattedGroupTree[$key]['collapse_adv_display'] = $value['collapse_adv_display'] ?? NULL;
1811 $formattedGroupTree[$key]['style'] = $value['style'] ?? NULL;
6a488035
TO
1812
1813 // this params needed of bulding multiple values
9c1bc317
CW
1814 $formattedGroupTree[$key]['is_multiple'] = $value['is_multiple'] ?? NULL;
1815 $formattedGroupTree[$key]['extends'] = $value['extends'] ?? NULL;
1816 $formattedGroupTree[$key]['extends_entity_column_id'] = $value['extends_entity_column_id'] ?? NULL;
1817 $formattedGroupTree[$key]['extends_entity_column_value'] = $value['extends_entity_column_value'] ?? NULL;
1818 $formattedGroupTree[$key]['subtype'] = $value['subtype'] ?? NULL;
1819 $formattedGroupTree[$key]['max_multiple'] = $value['max_multiple'] ?? NULL;
6a488035
TO
1820
1821 // add field information
1822 foreach ($value['fields'] as $k => $properties) {
1823 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
9d72cede 1824 if (isset($properties['customValue']) &&
fb56e964 1825 !CRM_Utils_System::isNull($properties['customValue']) &&
1826 !isset($properties['element_value'])
9d72cede 1827 ) {
6a488035
TO
1828 if (isset($properties['customValue'][$groupCount])) {
1829 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1830 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
36769590 1831 if ($properties['data_type'] === 'File') {
6a488035
TO
1832 $properties['element_value'] = $properties['customValue'][$groupCount];
1833 $uploadNames[] = $properties['element_name'];
1834 }
1835 else {
1836 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1837 }
1838 }
1839 }
16806c95 1840 if ($value = CRM_Utils_Request::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1841 $formValues[$properties['element_name']] = $value;
1842 }
1843 elseif (isset($submittedValues[$properties['element_name']])) {
1844 $properties['element_value'] = $submittedValues[$properties['element_name']];
1845 }
6a488035
TO
1846 unset($properties['customValue']);
1847 $formattedGroupTree[$key]['fields'][$k] = $properties;
1848 }
1849 }
1850
1851 if ($form) {
fb56e964 1852 if (count($formValues)) {
29a1df58 1853 $qf = $form->get('qfKey');
1854 $form->assign('qfKey', $qf);
792fce0b 1855 Civi::cache('customData')->set($qf, $formValues);
fb56e964 1856 }
1857
6a488035
TO
1858 // hack for field type File
1859 $formUploadNames = $form->get('uploadNames');
1860 if (is_array($formUploadNames)) {
1861 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1862 }
1863
1864 $form->set('uploadNames', $uploadNames);
1865 }
1866
1867 return $formattedGroupTree;
1868 }
1869
1870 /**
fe482240 1871 * Build custom data view.
77b97be7 1872 *
24eba103 1873 * @param CRM_Core_Form|CRM_Core_Page $form
6a0b768e
TO
1874 * Page object.
1875 * @param array $groupTree
6a0b768e
TO
1876 * @param bool $returnCount
1877 * True if customValue count needs to be returned.
100fef9d 1878 * @param int $gID
77b97be7 1879 * @param null $prefix
100fef9d 1880 * @param int $customValueId
080d719e 1881 * @param int $entityId
77b97be7
EM
1882 *
1883 * @return array|int
5d7c2bd2 1884 * @throws \CRM_Core_Exception
6a488035 1885 */
080d719e 1886 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
be2fb01f 1887 $details = [];
6a488035
TO
1888 foreach ($groupTree as $key => $group) {
1889 if ($key === 'info') {
1890 continue;
1891 }
1892
1893 foreach ($group['fields'] as $k => $properties) {
1894 $groupID = $group['id'];
1895 if (!empty($properties['customValue'])) {
1896 foreach ($properties['customValue'] as $values) {
e41f4660
PJ
1897 if (!empty($customValueId) && $customValueId != $values['id']) {
1898 continue;
1899 }
9c1bc317
CW
1900 $details[$groupID][$values['id']]['title'] = $group['title'] ?? NULL;
1901 $details[$groupID][$values['id']]['name'] = $group['name'] ?? NULL;
1902 $details[$groupID][$values['id']]['help_pre'] = $group['help_pre'] ?? NULL;
1903 $details[$groupID][$values['id']]['help_post'] = $group['help_post'] ?? NULL;
1904 $details[$groupID][$values['id']]['collapse_display'] = $group['collapse_display'] ?? NULL;
1905 $details[$groupID][$values['id']]['collapse_adv_display'] = $group['collapse_adv_display'] ?? NULL;
1906 $details[$groupID][$values['id']]['style'] = $group['style'] ?? NULL;
be2fb01f 1907 $details[$groupID][$values['id']]['fields'][$k] = [
6b409353
CW
1908 'field_title' => $properties['label'] ?? NULL,
1909 'field_type' => $properties['html_type'] ?? NULL,
1910 'field_data_type' => $properties['data_type'] ?? NULL,
080d719e 1911 'field_value' => CRM_Core_BAO_CustomField::displayValue($values['data'], $properties['id'], $entityId),
6b409353 1912 'options_per_line' => $properties['options_per_line'] ?? NULL,
be2fb01f 1913 ];
7dcdb6fa
CW
1914 // editable = whether this set contains any non-read-only fields
1915 if (!isset($details[$groupID][$values['id']]['editable'])) {
1916 $details[$groupID][$values['id']]['editable'] = FALSE;
1917 }
1918 if (empty($properties['is_view'])) {
1919 $details[$groupID][$values['id']]['editable'] = TRUE;
1920 }
6a488035 1921 // also return contact reference contact id if user has view all or edit all contacts perm
a61d2ab7
CW
1922 if ($details[$groupID][$values['id']]['fields'][$k]['field_data_type'] === 'ContactReference'
1923 && CRM_Core_Permission::check([['view all contacts', 'edit all contacts']])
6a488035 1924 ) {
a61d2ab7
CW
1925 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_links'] = [];
1926 $path = CRM_Contact_DAO_Contact::getEntityPaths()['view'];
1927 foreach (CRM_Utils_Array::explodePadded($values['data'] ?? []) as $contactId) {
1928 $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'display_name');
1929 if ($displayName) {
1930 $url = CRM_Utils_System::url(str_replace('[id]', $contactId, $path));
1931 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_links'][] = '<a href="' . $url . '" title="' . htmlspecialchars(ts('View Contact')) . '">' .
1932 $displayName . '</a>';
1933 }
1934 }
6a488035
TO
1935 }
1936 }
1937 }
1938 else {
9c1bc317
CW
1939 $details[$groupID][0]['title'] = $group['title'] ?? NULL;
1940 $details[$groupID][0]['name'] = $group['name'] ?? NULL;
1941 $details[$groupID][0]['help_pre'] = $group['help_pre'] ?? NULL;
1942 $details[$groupID][0]['help_post'] = $group['help_post'] ?? NULL;
1943 $details[$groupID][0]['collapse_display'] = $group['collapse_display'] ?? NULL;
1944 $details[$groupID][0]['collapse_adv_display'] = $group['collapse_adv_display'] ?? NULL;
1945 $details[$groupID][0]['style'] = $group['style'] ?? NULL;
a61d2ab7 1946 $details[$groupID][0]['fields'][$k] = ['field_title' => $properties['label'] ?? NULL];
6a488035
TO
1947 }
1948 }
1949 }
1950
1951 if ($returnCount) {
aa965915
MWMC
1952 // return a single value count if group id is passed to function
1953 // else return a groupId and count mapped array
9d72cede 1954 if (!empty($gID)) {
6a488035
TO
1955 return count($details[$gID]);
1956 }
1957 else {
be2fb01f 1958 $countValue = [];
9d72cede 1959 foreach ($details as $key => $value) {
6a488035
TO
1960 $countValue[$key] = count($details[$key]);
1961 }
1962 return $countValue;
1963 }
1964 }
1965 else {
1966 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1967 return $details;
1968 }
1969 }
1970
6a488035
TO
1971 /**
1972 * Get the custom group titles by custom field ids.
1973 *
6a0b768e
TO
1974 * @param array $fieldIds
1975 * Array of custom field ids.
6a488035 1976 *
a1a2a83d 1977 * @return array|NULL
a6c01b45 1978 * array consisting of groups and fields labels with ids.
6a488035
TO
1979 */
1980 public static function getGroupTitles($fieldIds) {
1981 if (!is_array($fieldIds) && empty($fieldIds)) {
a1a2a83d 1982 return NULL;
6a488035
TO
1983 }
1984
be2fb01f 1985 $groupLabels = [];
6a488035
TO
1986 $fIds = "(" . implode(',', $fieldIds) . ")";
1987
1988 $query = "
1989SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
1990 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
1991 FROM civicrm_custom_group, civicrm_custom_field
1992 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
1993 AND civicrm_custom_field.id IN {$fIds}";
1994
1995 $dao = CRM_Core_DAO::executeQuery($query);
1996 while ($dao->fetch()) {
be2fb01f 1997 $groupLabels[$dao->fieldID] = [
6a488035
TO
1998 'fieldID' => $dao->fieldID,
1999 'fieldLabel' => $dao->fieldLabel,
2000 'groupID' => $dao->groupID,
2001 'groupTitle' => $dao->groupTitle,
be2fb01f 2002 ];
6a488035
TO
2003 }
2004
2005 return $groupLabels;
2006 }
2007
00be9182 2008 public static function dropAllTables() {
6a488035
TO
2009 $query = "SELECT table_name FROM civicrm_custom_group";
2010 $dao = CRM_Core_DAO::executeQuery($query);
2011
2012 while ($dao->fetch()) {
2013 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2014 CRM_Core_DAO::executeQuery($query);
2015 }
2016 }
2017
2018 /**
2019 * Check whether custom group is empty or not.
2020 *
6a0b768e
TO
2021 * @param int $gID
2022 * Custom group id.
6a488035 2023 *
a1a2a83d 2024 * @return bool|NULL
a6c01b45 2025 * true if empty otherwise false.
6a488035 2026 */
00be9182 2027 public static function isGroupEmpty($gID) {
6a488035 2028 if (!$gID) {
a1a2a83d 2029 return NULL;
6a488035
TO
2030 }
2031
2032 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
9d72cede
EM
2033 $gID,
2034 'table_name'
2035 );
6a488035
TO
2036
2037 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2038 $value = CRM_Core_DAO::singleValueQuery($query);
2039
2040 if (empty($value)) {
2041 return TRUE;
2042 }
2043
2044 return FALSE;
2045 }
2046
2047 /**
2048 * Get the list of types for objects that a custom group extends to.
2049 *
6a0b768e
TO
2050 * @param array $types
2051 * Var which should have the list appended.
6a488035 2052 *
a6c01b45 2053 * @return array
16b10e64 2054 * Array of types.
aa965915 2055 * @throws \Exception
6a488035 2056 */
be2fb01f
CW
2057 public static function getExtendedObjectTypes(&$types = []) {
2058 static $flag = FALSE, $objTypes = [];
6a488035
TO
2059
2060 if (!$flag) {
be2fb01f 2061 $extendObjs = [];
fffc190b 2062 CRM_Core_OptionValue::getValues(['name' => 'cg_extend_objects'], $extendObjs, 'weight', TRUE);
6a488035
TO
2063
2064 foreach ($extendObjs as $ovId => $ovValues) {
2065 if ($ovValues['description']) {
2066 // description is expected to be a callback func to subtypes
2067 list($callback, $args) = explode(';', trim($ovValues['description']));
2068
0e6e8724 2069 if (empty($args)) {
be2fb01f 2070 $args = [];
6a488035
TO
2071 }
2072
2073 if (!is_array($args)) {
36769590 2074 throw new CRM_Core_Exception('Arg is not of type array');
6a488035
TO
2075 }
2076
2077 list($className) = explode('::', $callback);
aa965915 2078 require_once str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
6a488035
TO
2079
2080 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2081 }
2082 }
2083 $flag = TRUE;
2084 }
2085
2086 $types = array_merge($types, $objTypes);
2087 return $objTypes;
2088 }
2089
b5c2afd0 2090 /**
100fef9d
CW
2091 * @param int $customGroupId
2092 * @param int $entityId
b5c2afd0
EM
2093 *
2094 * @return bool
2095 */
00be9182 2096 public static function hasReachedMaxLimit($customGroupId, $entityId) {
aa965915 2097 // check whether the group is multiple
6a488035 2098 $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
63d76404 2099 $isMultiple = (bool) $isMultiple;
6a488035
TO
2100 $hasReachedMax = FALSE;
2101 if ($isMultiple &&
9d72cede
EM
2102 ($maxMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2103 ) {
6a488035
TO
2104 if (!$maxMultiple) {
2105 $hasReachedMax = FALSE;
9d72cede
EM
2106 }
2107 else {
6a488035 2108 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
aa965915 2109 // count the number of entries for a entity
6a488035 2110 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
be2fb01f 2111 $params = [1 => [$entityId, 'Integer']];
6a488035
TO
2112 $count = CRM_Core_DAO::singleValueQuery($sql, $params);
2113
2114 if ($count >= $maxMultiple) {
2115 $hasReachedMax = TRUE;
2116 }
2117 }
2118 }
2119 return $hasReachedMax;
2120 }
2121
b5c2afd0
EM
2122 /**
2123 * @return array
2124 */
00be9182 2125 public static function getMultipleFieldGroup() {
be2fb01f 2126 $multipleGroup = [];
9ff5f6c0 2127 $dao = new CRM_Core_DAO_CustomGroup();
9d72cede 2128 $dao->is_multiple = 1;
209a3cc3 2129 $dao->is_active = 1;
9ff5f6c0 2130 $dao->find();
9d72cede 2131 while ($dao->fetch()) {
9ff5f6c0
N
2132 $multipleGroup[$dao->id] = $dao->title;
2133 }
2134 return $multipleGroup;
2135 }
96025800 2136
b2ccd9fe 2137 /**
2138 * Build the metadata tree for the custom group.
2139 *
2140 * @param string $entityType
2141 * @param array $toReturn
2142 * @param array $subTypes
2143 * @param string $queryString
2144 * @param array $params
2145 * @param string $subType
2146 *
2147 * @return array
2148 * @throws \CRM_Core_Exception
2149 */
2150 private static function buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType) {
2151 $groupTree = $multipleFieldGroups = [];
2152 $crmDAO = CRM_Core_DAO::executeQuery($queryString, $params);
2153 $customValueTables = [];
2154
2155 // process records
2156 while ($crmDAO->fetch()) {
2157 // get the id's
2158 $groupID = $crmDAO->civicrm_custom_group_id;
2159 $fieldId = $crmDAO->civicrm_custom_field_id;
2160 if ($crmDAO->civicrm_custom_group_is_multiple) {
2161 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name;
2162 }
2163 // create an array for groups if it does not exist
2164 if (!array_key_exists($groupID, $groupTree)) {
2165 $groupTree[$groupID] = [];
2166 $groupTree[$groupID]['id'] = $groupID;
2167
2168 // populate the group information
2169 foreach ($toReturn['custom_group'] as $fieldName) {
2170 $fullFieldName = "civicrm_custom_group_$fieldName";
2171 if ($fieldName == 'id' ||
2172 is_null($crmDAO->$fullFieldName)
2173 ) {
2174 continue;
2175 }
2176 // CRM-5507
2177 // This is an old bit of code - per the CRM number & probably does not work reliably if
2178 // that one contact sub-type exists.
2179 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
2180 $groupTree[$groupID]['subtype'] = self::validateSubTypeByEntity($entityType, $subType);
2181 }
2182 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
2183 }
2184 $groupTree[$groupID]['fields'] = [];
2185
2186 $customValueTables[$crmDAO->civicrm_custom_group_table_name] = [];
2187 }
2188
2189 // add the fields now (note - the query row will always contain a field)
2190 // we only reset this once, since multiple values come is as multiple rows
2191 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
2192 $groupTree[$groupID]['fields'][$fieldId] = [];
2193 }
2194
2195 $customValueTables[$crmDAO->civicrm_custom_group_table_name][$crmDAO->civicrm_custom_field_column_name] = 1;
2196 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
2197 // populate information for a custom field
2198 foreach ($toReturn['custom_field'] as $fieldName) {
2199 $fullFieldName = "civicrm_custom_field_$fieldName";
2200 if ($fieldName == 'id' ||
2201 is_null($crmDAO->$fullFieldName)
2202 ) {
2203 continue;
2204 }
2205 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
2206 }
2207 }
2208
2209 if (!empty($customValueTables)) {
2210 $groupTree['info'] = ['tables' => $customValueTables];
2211 }
2212 return [$multipleFieldGroups, $groupTree];
2213 }
2214
13d328b3
SL
2215 public static function getSubTypes(): array {
2216 $sel2 = [];
2217 $activityType = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
2218
2219 $eventType = CRM_Core_OptionGroup::values('event_type');
2220 $grantType = CRM_Core_OptionGroup::values('grant_type');
2221 $campaignTypes = CRM_Campaign_PseudoConstant::campaignType();
2222 $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE);
2223 $participantRole = CRM_Core_OptionGroup::values('participant_role');
2224
2225 asort($activityType);
2226 asort($eventType);
2227 asort($grantType);
2228 asort($membershipType);
2229 asort($participantRole);
2230
2231 $sel2['Event'] = $eventType;
2232 $sel2['Grant'] = $grantType;
2233 $sel2['Activity'] = $activityType;
2234 $sel2['Campaign'] = $campaignTypes;
2235 $sel2['Membership'] = $membershipType;
2236 $sel2['ParticipantRole'] = $participantRole;
2237 $sel2['ParticipantEventName'] = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
2238 $sel2['ParticipantEventType'] = $eventType;
2239 $sel2['Contribution'] = CRM_Contribute_PseudoConstant::financialType();
2240 $sel2['Relationship'] = CRM_Custom_Form_Group::getRelationshipTypes();
2241
2242 $sel2['Individual'] = CRM_Contact_BAO_ContactType::subTypePairs('Individual', FALSE, NULL);
2243 $sel2['Household'] = CRM_Contact_BAO_ContactType::subTypePairs('Household', FALSE, NULL);
2244 $sel2['Organization'] = CRM_Contact_BAO_ContactType::subTypePairs('Organization', FALSE, NULL);
2245
2246 CRM_Core_BAO_CustomGroup::getExtendedObjectTypes($sel2);
2247 return $sel2;
2248 }
2249
92ef7828
SL
2250 /**
2251 * Get the munged entity.
2252 *
2253 * This is the entity eg. Relationship or the name of the sub entity
2254 * e.g ParticipantRole.
2255 *
2256 * @param string $extends
2257 * @param int|null $extendsEntityColumn
2258 *
2259 * @return string
2260 */
2261 protected static function getMungedEntity($extends, $extendsEntityColumn = NULL) {
2262 if (!$extendsEntityColumn || $extendsEntityColumn === 'null') {
2263 return $extends;
2264 }
2265 return CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name')[$extendsEntityColumn];
2266 }
2267
9d72cede 2268}