Merge pull request #22888 from civicrm/5.47
[civicrm-core.git] / CRM / Core / BAO / CustomGroup.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * Business object for managing custom data groups.
20 */
21 class CRM_Core_BAO_CustomGroup extends CRM_Core_DAO_CustomGroup {
22
23 /**
24 * Takes an associative array and creates a custom group object.
25 *
26 * This function is invoked from within the web form layer and also from the api layer
27 *
28 * @param array $params
29 * (reference) an assoc array of name/value pairs.
30 *
31 * @return CRM_Core_DAO_CustomGroup
32 * @throws \Exception
33 */
34 public static function create(&$params) {
35 // create custom group dao, populate fields and then save.
36 $group = new CRM_Core_DAO_CustomGroup();
37 if (isset($params['title'])) {
38 $group->title = $params['title'];
39 }
40
41 $extendsChildType = NULL;
42 // lets allow user to pass direct child type value, CRM-6893
43 if (!empty($params['extends_entity_column_value'])) {
44 $extendsChildType = $params['extends_entity_column_value'];
45 }
46 if (!CRM_Utils_System::isNull($extendsChildType)) {
47 $b = self::getMungedEntity($params['extends'], $params['extends_entity_column_id'] ?? NULL);
48 $registeredSubTypes = self::getSubTypes()[$b];
49 if (is_array($extendsChildType)) {
50 foreach ($extendsChildType as $childType) {
51 if (!array_key_exists($childType, $registeredSubTypes) && !in_array($childType, $registeredSubTypes, TRUE)) {
52 throw new CRM_Core_Exception('Supplied Sub type is not valid for the specified entitiy');
53 }
54 }
55 }
56 else {
57 if (!array_key_exists($extendsChildType, $registeredSubTypes) && !in_array($extendsChildType, $registeredSubTypes, TRUE)) {
58 throw new CRM_Core_Exception('Supplied Sub type is not valid for the specified entitiy');
59 }
60 $extendsChildType = [$extendsChildType];
61 }
62 $extendsChildType = implode(CRM_Core_DAO::VALUE_SEPARATOR, $extendsChildType);
63 if ($params['extends'] == 'Relationship') {
64 $extendsChildType = str_replace(['_a_b', '_b_a'], [
65 '',
66 '',
67 ], $extendsChildType);
68 }
69 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO::VALUE_SEPARATOR) {
70 $extendsChildType = CRM_Core_DAO::VALUE_SEPARATOR . $extendsChildType .
71 CRM_Core_DAO::VALUE_SEPARATOR;
72 }
73 }
74 else {
75 $extendsChildType = 'null';
76 }
77 $group->extends_entity_column_value = $extendsChildType;
78
79 if (isset($params['id'])) {
80 $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
81 }
82 else {
83 $oldWeight = 0;
84 }
85 $group->weight = CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array::value('weight', $params, FALSE));
86 $fields = [
87 'style',
88 'collapse_display',
89 'collapse_adv_display',
90 'help_pre',
91 'help_post',
92 'is_active',
93 'is_multiple',
94 'icon',
95 'extends_entity_column_id',
96 'extends',
97 ];
98 $current_db_version = CRM_Core_BAO_Domain::version();
99 $is_public_version = version_compare($current_db_version, '4.7.19', '>=');
100 if ($is_public_version) {
101 $fields[] = 'is_public';
102 }
103 foreach ($fields as $field) {
104 if (isset($params[$field])) {
105 $group->$field = $params[$field];
106 }
107 }
108 $group->max_multiple = isset($params['is_multiple']) ? (isset($params['max_multiple']) &&
109 $params['max_multiple'] >= '0'
110 ) ? $params['max_multiple'] : 'null' : 'null';
111
112 $tableName = $tableNameNeedingIndexUpdate = NULL;
113 if (isset($params['id'])) {
114 $group->id = $params['id'];
115
116 if (isset($params['is_multiple'])) {
117 // check whether custom group was changed from single-valued to multiple-valued
118 $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
119 $params['id'],
120 'is_multiple'
121 );
122
123 // dev/core#227 Fix issue where is_multiple in params maybe an empty string if checkbox is not rendered on the form.
124 $paramsIsMultiple = empty($params['is_multiple']) ? 0 : 1;
125 if ($paramsIsMultiple != $isMultiple) {
126 $tableNameNeedingIndexUpdate = CRM_Core_DAO::getFieldValue(
127 'CRM_Core_DAO_CustomGroup',
128 $params['id'],
129 'table_name'
130 );
131 }
132 }
133 }
134 else {
135 $group->created_id = $params['created_id'] ?? NULL;
136 $group->created_date = $params['created_date'] ?? NULL;
137
138 // Process name only during create, so it never changes
139 if (!empty($params['name'])) {
140 $group->name = CRM_Utils_String::munge($params['name']);
141 }
142 else {
143 $group->name = CRM_Utils_String::munge($group->title);
144 }
145
146 self::validateCustomGroupName($group);
147
148 if (isset($params['table_name'])) {
149 $tableName = $params['table_name'];
150
151 if (CRM_Core_DAO_AllCoreTables::isCoreTable($tableName)) {
152 // Bad idea. Prevent group creation because it might lead to a broken configuration.
153 throw new CRM_Core_Exception(ts('Cannot create custom table because %1 is already a core table.', ['1' => $tableName]));
154 }
155 }
156 }
157
158 if (array_key_exists('is_reserved', $params)) {
159 $group->is_reserved = $params['is_reserved'] ? 1 : 0;
160 }
161 $op = isset($params['id']) ? 'edit' : 'create';
162 CRM_Utils_Hook::pre($op, 'CustomGroup', CRM_Utils_Array::value('id', $params), $params);
163
164 // enclose the below in a transaction
165 $transaction = new CRM_Core_Transaction();
166
167 $group->save();
168 if (!isset($params['id'])) {
169 if (!isset($params['table_name'])) {
170 $munged_title = strtolower(CRM_Utils_String::munge($group->title, '_', 13));
171 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
172 }
173 $group->table_name = $tableName;
174 CRM_Core_DAO::setFieldValue('CRM_Core_DAO_CustomGroup',
175 $group->id,
176 'table_name',
177 $tableName
178 );
179
180 // now create the table associated with this group
181 self::createTable($group);
182 }
183 elseif ($tableNameNeedingIndexUpdate) {
184 CRM_Core_BAO_SchemaHandler::changeUniqueToIndex($tableNameNeedingIndexUpdate, CRM_Utils_Array::value('is_multiple', $params));
185 }
186
187 if (CRM_Utils_Array::value('overrideFKConstraint', $params) == 1) {
188 $table = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
189 $params['id'],
190 'table_name'
191 );
192 CRM_Core_BAO_SchemaHandler::changeFKConstraint($table, self::mapTableName($params['extends']));
193 }
194 $transaction->commit();
195
196 // reset the cache
197 CRM_Utils_System::flushCache();
198
199 if ($tableName) {
200 CRM_Utils_Hook::post('create', 'CustomGroup', $group->id, $group);
201 }
202 else {
203 CRM_Utils_Hook::post('edit', 'CustomGroup', $group->id, $group);
204 }
205
206 return $group;
207 }
208
209 /**
210 * Retrieve DB object and copy to defaults array.
211 *
212 * @param array $params
213 * Array of criteria values.
214 * @param array $defaults
215 * Array to be populated with found values.
216 *
217 * @return self|null
218 * The DAO object, if found.
219 *
220 * @deprecated
221 */
222 public static function retrieve($params, &$defaults) {
223 return self::commonRetrieve(self::class, $params, $defaults);
224 }
225
226 /**
227 * Ensure group name does not conflict with an existing field
228 *
229 * @param CRM_Core_DAO_CustomGroup $group
230 */
231 public static function validateCustomGroupName(CRM_Core_DAO_CustomGroup $group) {
232 $extends = in_array($group->extends, CRM_Contact_BAO_ContactType::basicTypes(TRUE)) ? 'Contact' : $group->extends;
233 $extendsDAO = CRM_Core_DAO_AllCoreTables::getFullName($extends);
234 if ($extendsDAO) {
235 $fields = array_column($extendsDAO::fields(), 'name');
236 if (in_array($group->name, $fields)) {
237 $group->name .= '0';
238 }
239 }
240 }
241
242 /**
243 * Update the is_active flag in the db.
244 *
245 * @param int $id
246 * Id of the database record.
247 * @param bool $is_active
248 * Value we want to set the is_active field.
249 *
250 * @return bool
251 * true if we found and updated the object, else false
252 */
253 public static function setIsActive($id, $is_active) {
254 // reset the cache
255 Civi::cache('fields')->flush();
256 // reset ACL and system caches.
257 CRM_Core_BAO_Cache::resetCaches();
258
259 if (!$is_active) {
260 CRM_Core_BAO_UFField::setUFFieldStatus($id, $is_active);
261 }
262
263 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
264 }
265
266 /**
267 * Determine if given entity (sub)type has any custom groups
268 *
269 * @param string $extends
270 * E.g. "Individual", "Activity".
271 * @param int $columnId
272 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
273 * @param string $columnValue
274 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
275 *
276 * @return bool
277 */
278 public static function hasCustomGroup($extends, $columnId, $columnValue) {
279 $dao = new CRM_Core_DAO_CustomGroup();
280 $dao->extends = $extends;
281 $dao->extends_entity_column_id = $columnId;
282 $escapedValue = CRM_Core_DAO::VALUE_SEPARATOR . CRM_Core_DAO::escapeString($columnValue) . CRM_Core_DAO::VALUE_SEPARATOR;
283 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
284 //$dao->extends_entity_column_value = $columnValue;
285 return (bool) $dao->find();
286 }
287
288 /**
289 * Determine if there are any CustomGroups for the given $activityTypeId.
290 * If none found, create one.
291 *
292 * @param int $activityTypeId
293 *
294 * @return bool
295 * TRUE if a group is found or created; FALSE on error
296 */
297 public static function autoCreateByActivityType($activityTypeId) {
298 if (self::hasCustomGroup('Activity', NULL, $activityTypeId)) {
299 return TRUE;
300 }
301 // everything
302 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE);
303 $params = [
304 'version' => 3,
305 'extends' => 'Activity',
306 'extends_entity_column_id' => NULL,
307 'extends_entity_column_value' => CRM_Utils_Array::implodePadded([$activityTypeId]),
308 'title' => ts('%1 Questions', [1 => $activityTypes[$activityTypeId]]),
309 'style' => 'Inline',
310 'is_active' => 1,
311 ];
312 $result = civicrm_api('CustomGroup', 'create', $params);
313 return !$result['is_error'];
314 }
315
316 /**
317 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
318 * This may also include entity specific data values.
319 *
320 * An array containing all custom groups and their custom fields is returned.
321 *
322 * @param string $entityType
323 * Of the contact whose contact type is needed.
324 * @param array $toReturn
325 * What data should be returned. ['custom_group' => ['id', 'name', etc.], 'custom_field' => ['id', 'label', etc.]]
326 * @param int $entityID
327 * @param int $groupID
328 * @param array $subTypes
329 * @param string $subName
330 * @param bool $fromCache
331 * @param bool $onlySubType
332 * Only return specified subtype or return specified subtype + unrestricted fields.
333 * @param bool $returnAll
334 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
335 * api - through which it is properly tested - so can be refactored with some comfort.)
336 * @param bool|int $checkPermission
337 * Either a CRM_Core_Permission constant or FALSE to disable checks
338 * @param string|int $singleRecord
339 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
340 * @param bool $showPublicOnly
341 *
342 * @return array
343 * Custom field 'tree'.
344 *
345 * The returned array is keyed by group id and has the custom group table fields
346 * and a subkey 'fields' holding the specific custom fields.
347 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
348 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
349 *
350 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
351 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
352 * With caching the performance impact would be small & the function would be cleaner
353 *
354 * @throws \CRM_Core_Exception
355 */
356 public static function getTree(
357 $entityType,
358 $toReturn = [],
359 $entityID = NULL,
360 $groupID = NULL,
361 $subTypes = [],
362 $subName = NULL,
363 $fromCache = TRUE,
364 $onlySubType = NULL,
365 $returnAll = FALSE,
366 $checkPermission = CRM_Core_Permission::EDIT,
367 $singleRecord = NULL,
368 $showPublicOnly = FALSE
369 ) {
370 if ($checkPermission === TRUE) {
371 CRM_Core_Error::deprecatedWarning('Unexpected TRUE passed to CustomGroup::getTree $checkPermission param.');
372 $checkPermission = CRM_Core_Permission::EDIT;
373 }
374 if ($entityID) {
375 $entityID = CRM_Utils_Type::escape($entityID, 'Integer');
376 }
377 if (!is_array($subTypes)) {
378 if (empty($subTypes)) {
379 $subTypes = [];
380 }
381 else {
382 if (stristr($subTypes, ',')) {
383 $subTypes = explode(',', $subTypes);
384 }
385 else {
386 $subTypes = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($subTypes, CRM_Core_DAO::VALUE_SEPARATOR));
387 }
388 }
389 }
390
391 // create a new tree
392
393 // legacy hardcoded list of data to return
394 $tableData = [
395 'custom_field' => [
396 'id',
397 'name',
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',
414 'in_selector',
415 ],
416 'custom_group' => [
417 'id',
418 'name',
419 'table_name',
420 'title',
421 'help_pre',
422 'help_post',
423 'collapse_display',
424 'style',
425 'is_multiple',
426 'extends',
427 'extends_entity_column_id',
428 'extends_entity_column_value',
429 'max_multiple',
430 ],
431 ];
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', '>=');
435 if ($is_public_version) {
436 $tableData['custom_group'][] = 'is_public';
437 }
438 if ($serialize_version) {
439 $tableData['custom_field'][] = 'serialize';
440 }
441 if (!$toReturn || !is_array($toReturn)) {
442 $toReturn = $tableData;
443 }
444 else {
445 // Supply defaults and remove unknown array keys
446 $toReturn = array_intersect_key(array_filter($toReturn) + $tableData, $tableData);
447 // Merge in required fields that we must have
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']));
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 }
454
455 // create select
456 $select = [];
457 foreach ($toReturn as $tableName => $tableColumn) {
458 foreach ($tableColumn as $columnName) {
459 $select[] = "civicrm_{$tableName}.{$columnName} as civicrm_{$tableName}_{$columnName}";
460 }
461 }
462 $strSelect = "SELECT " . implode(', ', $select);
463
464 // from, where, order by
465 $strFrom = "
466 FROM civicrm_custom_group
467 LEFT 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.
471 if ($entityType == "Individual" || $entityType == 'Organization' ||
472 $entityType == 'Household'
473 ) {
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
485 $params = [];
486 $sqlParamKey = 1;
487 $subType = '';
488 if (!empty($subTypes)) {
489 foreach ($subTypes as $key => $subType) {
490 $subTypeClauses[] = self::whereListHas("civicrm_custom_group.extends_entity_column_value", self::validateSubTypeByEntity($entityType, $subType));
491 }
492 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
493 if (!$onlySubType) {
494 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
495 }
496
497 $strWhere = "
498 WHERE 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) {
504 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = %{$sqlParamKey}";
505 $params[$sqlParamKey] = [$subName, 'String'];
506 $sqlParamKey = $sqlParamKey + 1;
507 }
508 }
509 else {
510 $strWhere = "
511 WHERE civicrm_custom_group.is_active = 1
512 AND civicrm_custom_field.is_active = 1
513 AND civicrm_custom_group.extends IN ($in)
514 ";
515 if (!$returnAll) {
516 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
517 }
518 }
519
520 if ($groupID > 0) {
521 // since we want a specific group id we add it to the where clause
522 $strWhere .= " AND civicrm_custom_group.id = %{$sqlParamKey}";
523 $params[$sqlParamKey] = [$groupID, 'Integer'];
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 }
529 if ($checkPermission) {
530 // ensure that the user has access to these custom groups
531 $strWhere .= " AND " .
532 CRM_Core_Permission::customGroupClause($checkPermission,
533 'civicrm_custom_group.'
534 );
535 }
536
537 if ($showPublicOnly && $is_public_version) {
538 $strWhere .= "AND civicrm_custom_group.is_public = 1";
539 }
540
541 $orderBy = "
542 ORDER 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;
553 if ($groupID > 0) {
554 $cacheString .= "_{$groupID}";
555 }
556 else {
557 $cacheString .= "_Inline";
558 }
559
560 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
561 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
562 $cache = CRM_Utils_Cache::singleton();
563 if ($fromCache) {
564 $groupTree = $cache->get($cacheKey);
565 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
566 }
567
568 if (empty($groupTree)) {
569 list($multipleFieldGroups, $groupTree) = self::buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType);
570
571 $cache->set($cacheKey, $groupTree);
572 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
573 }
574 // entitySelectClauses is an array of select clauses for custom value tables which are not multiple
575 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
576 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = [];
577 $singleFieldTables = [];
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
580 // add info to groupTree
581
582 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
583 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
584 ) {
585 $select = $from = $where = [];
586 $groupTree['info']['where'] = NULL;
587
588 foreach ($groupTree['info']['tables'] as $table => $fields) {
589 $groupTree['info']['from'][] = $table;
590 $select = [
591 "{$table}.id as {$table}_id",
592 "{$table}.entity_id as {$table}_entity_id",
593 ];
594 foreach ($fields as $column => $dontCare) {
595 $select[] = "{$table}.{$column} as {$table}_{$column}";
596 }
597 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
598 if ($entityID) {
599 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
600 if (in_array($table, $multipleFieldGroups) &&
601 self::customGroupDataExistsForEntity($entityID, $table)
602 ) {
603 $entityMultipleSelectClauses[$table] = $select;
604 }
605 else {
606 $singleFieldTables[] = $table;
607 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
608 }
609
610 }
611 }
612 if ($entityID && !empty($singleFieldTables)) {
613 self::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
614 }
615 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
616 if (!empty($multipleFieldTablesWithEntityData)) {
617 self::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
618 }
619
620 }
621 return $groupTree;
622 }
623
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
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 }
638
639 $contactTypes = CRM_Contact_BAO_ContactType::basicTypeInfo(TRUE);
640 $contactTypes = array_merge($contactTypes, ['Event' => 1]);
641
642 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
643 throw new CRM_Core_Exception('Invalid Entity Filter');
644 }
645 $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo($entityType, TRUE);
646 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant::eventType());
647 if (!array_key_exists($subType, $subTypes)) {
648 throw new CRM_Core_Exception('Invalid Filter');
649 }
650 return $subType;
651 }
652
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 */
663 private static function whereListHas($column, $value, $delimiter = CRM_Core_DAO::VALUE_SEPARATOR) {
664 // ?
665 $bareValue = trim($value, $delimiter);
666 $escapedValue = CRM_Utils_Type::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
667 return "($column LIKE \"$escapedValue\")";
668 }
669
670 /**
671 * Check whether the custom group has any data for the given entity.
672 *
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.
677 *
678 * @param bool $getCount
679 *
680 * @return bool
681 * does this entity have data in this custom table
682 */
683 public static function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
684 $query = "
685 SELECT count(id)
686 FROM $table
687 WHERE entity_id = $entityID
688 ";
689 $recordExists = CRM_Core_DAO::singleValueQuery($query);
690 if ($getCount) {
691 return $recordExists;
692 }
693 return (bool) $recordExists;
694 }
695
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 *
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.
711 */
712 public static function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
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 }
718
719 $query = "
720 SELECT $select
721 FROM $fromSQL
722 WHERE first.entity_id = $entityID
723 ";
724 self::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
725 }
726
727 /**
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 *
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.
740 * @param string|int $singleRecord
741 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
742 */
743 public static function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
744 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
745 $select = implode(',', $selectClauses);
746 $query = "
747 SELECT $select
748 FROM $table
749 WHERE entity_id = $entityID
750 ";
751 if ($singleRecord) {
752 $offset = $singleRecord - 1;
753 $query .= " LIMIT {$offset}, 1";
754 }
755 self::buildTreeEntityDataFromQuery($groupTree, $query, [$table], $singleRecord);
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 *
765 * @param array $groupTree
766 * (reference) group tree array which is being built.
767 * @param string $query
768 * @param array $includedTables
769 * Tables to include - required because the function (for historical reasons).
770 * iterates through the group tree
771 * @param string|int $singleRecord
772 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
773 */
774 public static function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
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
785 if (!in_array($table, $includedTables)) {
786 continue;
787 }
788 foreach ($group['fields'] as $fieldID => $dontCare) {
789 self::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
790 }
791 }
792 }
793 }
794
795 /**
796 * Build the entity-specific custom data into the group tree on a per-field basis
797 *
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.
804 * @param int $groupID
805 * Custom group ID.
806 * @param int $fieldID
807 * Custom field ID.
808 * @param string|int $singleRecord
809 * holds 'new' or id if loading view/edit/copy for a single record.
810 */
811 public static function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
812 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
813 $idName = "{$table}_id";
814 $fieldName = "{$table}_{$column}";
815 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
816 if ($dataType == 'File') {
817 if (isset($dao->$fieldName)) {
818 $config = CRM_Core_Config::singleton();
819 $fileDAO = new CRM_Core_DAO_File();
820 $fileDAO->id = $dao->$fieldName;
821
822 if ($fileDAO->find(TRUE)) {
823 $entityIDName = "{$table}_entity_id";
824 $fileHash = CRM_Core_BAO_File::generateFileHash($dao->$entityIDName, $fileDAO->id);
825 $customValue['id'] = $dao->$idName;
826 $customValue['data'] = $fileDAO->uri;
827 $customValue['fid'] = $fileDAO->id;
828 $customValue['fileURL'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}&fcs=$fileHash");
829 $customValue['displayURL'] = NULL;
830 $deleteExtra = ts('Are you sure you want to delete attached file.');
831 $deleteURL = [
832 CRM_Core_Action::DELETE => [
833 'name' => ts('Delete Attached File'),
834 'url' => 'civicrm/file',
835 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete&fcs=%%fcs%%',
836 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
837 . '\' ) ) this.href+=\'&amp;confirmed=1\'; else return false;"',
838 ],
839 ];
840 $customValue['deleteURL'] = CRM_Core_Action::formLink($deleteURL,
841 CRM_Core_Action::DELETE,
842 [
843 'id' => $fileDAO->id,
844 'eid' => $dao->$entityIDName,
845 'fid' => $fieldID,
846 'fcs' => $fileHash,
847 ],
848 ts('more'),
849 FALSE,
850 'file.manage.delete',
851 'File',
852 $fileDAO->id
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 );
868 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL) .
869 $fileDAO->uri;
870 list($path) = CRM_Core_BAO_File::path($fileDAO->id, $entityId);
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 }
877 }
878 }
879 }
880 else {
881 $customValue = [
882 'id' => $dao->$idName,
883 'data' => '',
884 ];
885 }
886 }
887 else {
888 $customValue = [
889 'id' => $dao->$idName,
890 'data' => $dao->$fieldName,
891 ];
892 }
893
894 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
895 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [];
896 }
897 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
898 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [$singleRecord => $customValue];
899 }
900 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
901 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [1 => $customValue];
902 }
903 else {
904 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
905 }
906 }
907
908 /**
909 * Get the group title.
910 *
911 * @param int $id
912 * Id of group.
913 *
914 * @return string
915 * title
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 *
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.
932 *
933 * @param bool $inSelector
934 *
935 * @return array
936 * array consisting of all group and field details
937 */
938 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
939 // create a new tree
940 $groupTree = [];
941
942 // using tableData to build the queryString
943 $tableData = [
944 'civicrm_custom_field' => [
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',
966 'in_selector',
967 ],
968 'civicrm_custom_group' => [
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',
979 'is_multiple',
980 ],
981 ];
982
983 // create select
984 $s = [];
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);
991 $params = [];
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) {
998 $params[1] = [$groupId, 'Integer'];
999 $where .= " AND civicrm_custom_group.id = %1";
1000 }
1001
1002 if ($searchable) {
1003 $where .= " AND civicrm_custom_field.is_searchable = 1";
1004 }
1005
1006 if ($inSelector) {
1007 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
1008 }
1009
1010 if ($extends) {
1011 $clause = [];
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) ) ";
1021 $params[2] = [CRM_Core_DAO::VALUE_SEPARATOR, 'String'];
1022 }
1023 }
1024
1025 // ensure that the user has access to these custom groups
1026 $where .= " AND " .
1027 CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
1028 'civicrm_custom_group.'
1029 );
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)) {
1046 $groupTree[$groupId] = [];
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
1059 $groupTree[$groupId]['fields'] = [];
1060 }
1061
1062 // add the fields now (note - the query row will always contain a field)
1063 $groupTree[$groupId]['fields'][$fieldId] = [];
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
1078 /**
1079 * @param $entityType
1080 * @param $path
1081 * @param string $cidToken
1082 *
1083 * @return array
1084 */
1085 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1086 // for Group's
1087 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1088
1089 // get 'Tab' and 'Tab with table' groups
1090 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1091 $customGroupDAO->whereAdd("is_active = 1");
1092
1093 // add whereAdd for entity type
1094 self::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1095
1096 $groups = [];
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()) {
1107 $group = [];
1108 $group['id'] = $customGroupDAO->id;
1109 $group['path'] = $path;
1110 $group['title'] = "$customGroupDAO->title";
1111 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1112 $group['extra'] = ['gid' => $customGroupDAO->id];
1113 $group['table_name'] = $customGroupDAO->table_name;
1114 $group['is_multiple'] = $customGroupDAO->is_multiple;
1115 $group['icon'] = $customGroupDAO->icon;
1116 $groups[] = $group;
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 *
1127 * @param string $entityType
1128 * What entity are we extending here ?.
1129 *
1130 * @return string
1131 *
1132 *
1133 * @see _apachesolr_civiAttachments_dereference_file_parent
1134 */
1135 public static function getTableNameByEntityName($entityType) {
1136 switch ($entityType) {
1137 case 'Contact':
1138 case 'Individual':
1139 case 'Household':
1140 case 'Organization':
1141 return 'civicrm_contact';
1142
1143 default:
1144 return CRM_Core_DAO_AllCoreTables::getTableForEntityName($entityType);
1145 }
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 *
1153 * @param string $entityType
1154 *
1155 * @return CRM_Core_DAO_CustomGroup
1156 */
1157 public static function getAllCustomGroupsByBaseEntity($entityType) {
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 *
1167 * @param object $customGroupDAO
1168 * @param string $entityType
1169 * What entity are we extending here ?.
1170 *
1171 * @param int $entityID
1172 * @param bool $allSubtypes
1173 */
1174 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1175 $addSubtypeClause = FALSE;
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);
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
1202 default:
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)) {
1211 $subtypeClause = [];
1212 foreach ($csType as $subtype) {
1213 $subtype = CRM_Core_DAO::VALUE_SEPARATOR . $subtype .
1214 CRM_Core_DAO::VALUE_SEPARATOR;
1215 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1216 }
1217 $subtypeClause[] = "extends_entity_column_value IS NULL";
1218 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1219 " )");
1220 }
1221 else {
1222 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1223 }
1224 }
1225 }
1226
1227 /**
1228 * Delete the Custom Group.
1229 *
1230 * @param CRM_Core_BAO_CustomGroup $group
1231 * Custom group object.
1232 * @param bool $force
1233 * whether to force the deletion, even if there are custom fields.
1234 *
1235 * @return bool
1236 * False if field exists for this group, true if group gets deleted.
1237 */
1238 public static function deleteGroup($group, $force = FALSE) {
1239
1240 //check whether this contain any custom fields
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
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
1282 /**
1283 * Set defaults.
1284 *
1285 * @param array $groupTree
1286 * @param array $defaults
1287 * @param bool $viewMode
1288 * @param bool $inactiveNeeded
1289 * @param int $action
1290 */
1291 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action::NONE) {
1292 foreach ($groupTree as $id => $group) {
1293 if (!isset($group['fields'])) {
1294 continue;
1295 }
1296 foreach ($group['fields'] as $field) {
1297 if (isset($field['element_value'])) {
1298 $value = $field['element_value'];
1299 }
1300 elseif (isset($field['default_value']) &&
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
1312 if (empty($field['element_name'])) {
1313 continue;
1314 }
1315
1316 $elementName = $field['element_name'];
1317 $serialize = CRM_Core_BAO_CustomField::isSerialized($field);
1318
1319 if ($serialize) {
1320 if ($field['data_type'] != 'Country' && $field['data_type'] != 'StateProvince' && $field['data_type'] != 'ContactReference') {
1321 $defaults[$elementName] = [];
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 {
1359 // Values may be "array strings" or actual arrays. Handle both.
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 }
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 }
1379 }
1380 else {
1381 if (isset($value)) {
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 }
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
1392 else {
1393 $checkedValue = explode(',', $value);
1394 }
1395 foreach ($checkedValue as $val) {
1396 if ($val) {
1397 $defaults[$elementName][$val] = $val;
1398 }
1399 }
1400 }
1401 }
1402 }
1403 else {
1404 if ($field['data_type'] == 'Country') {
1405 if ($value) {
1406 $defaults[$elementName] = $value;
1407 }
1408 else {
1409 $config = CRM_Core_Config::singleton();
1410 $defaults[$elementName] = $config->defaultContactCountry;
1411 }
1412 }
1413 else {
1414 if ($field['data_type'] == "Float") {
1415 $defaults[$elementName] = (float) $value;
1416 }
1417 elseif ($field['data_type'] == 'Money' &&
1418 $field['html_type'] == 'Text'
1419 ) {
1420 $defaults[$elementName] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($value);
1421 }
1422 else {
1423 $defaults[$elementName] = $value;
1424 }
1425 }
1426 }
1427 }
1428 }
1429 }
1430
1431 /**
1432 * Old function only called from one place...
1433 * @see CRM_Dedupe_Finder::formatParams
1434 *
1435 * @param array $groupTree
1436 * @param array $params
1437 * @param bool $skipFile
1438 */
1439 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1440 // Get the Custom form values and groupTree
1441 foreach ($groupTree as $groupID => $group) {
1442 if ($groupID === 'info') {
1443 continue;
1444 }
1445 foreach ($group['fields'] as $field) {
1446 $fieldId = $field['id'];
1447 $serialize = CRM_Core_BAO_CustomField::isSerialized($field);
1448
1449 // Reset all checkbox, radio and multiselect data
1450 if ($field['html_type'] == 'Radio' || $serialize) {
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
1463 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1464 // field exists in db so populate value from "form".
1465 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = [];
1466 }
1467
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 }
1473
1474 switch ($field['html_type']) {
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) {
1483 break;
1484 }
1485
1486 // store the file in d/b
1487 $entityId = explode('=', $groupTree['info']['where'][0]);
1488 $fileParams = ['upload_date' => date('YmdHis')];
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 }
1507 $defaults = [];
1508 $paramsFile = [
1509 'entity_table' => $groupTree[$groupID]['table_name'],
1510 'entity_id' => $entityId[1],
1511 ];
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 /**
1530 * Generic function to build all the form elements for a specific group tree.
1531 *
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.
1540 *
1541 * @throws \CiviCRM_API3_Exception
1542 */
1543 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1544 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1545
1546 foreach ($groupTree as $id => $group) {
1547 foreach ($group['fields'] as $field) {
1548 $required = $field['is_required'] ?? NULL;
1549 //fix for CRM-1620
1550 if ($field['data_type'] == 'File') {
1551 if (!empty($field['element_value']['data'])) {
1552 $required = 0;
1553 }
1554 }
1555
1556 $fieldId = $field['id'];
1557 $elementName = $field['element_name'];
1558 CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, $required);
1559 if ($form->getAction() == CRM_Core_Action::VIEW) {
1560 $form->getElement($elementName)->freeze();
1561 }
1562 }
1563 }
1564 }
1565
1566 /**
1567 * Extract the get params from the url, validate and store it in session.
1568 *
1569 * @param CRM_Core_Form $form
1570 * The form object.
1571 * @param string $type
1572 * The type of custom group we are using.
1573 *
1574 * @return array
1575 * @throws \CRM_Core_Exception
1576 * @throws \CiviCRM_API3_Exception
1577 */
1578 public static function extractGetParams(&$form, $type) {
1579 if (empty($_GET)) {
1580 return [];
1581 }
1582
1583 $groupTree = CRM_Core_BAO_CustomGroup::getTree($type);
1584 $customValue = [];
1585 $htmlType = [
1586 'CheckBox',
1587 'Multi-Select',
1588 'Select',
1589 'Radio',
1590 ];
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;
1598 $value = CRM_Utils_Request::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
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 }
1607 if (CRM_Core_BAO_CustomField::isSerialized($field)) {
1608 $value = str_replace("|", ",", $value);
1609 $mulValues = explode(',', $value);
1610 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, TRUE);
1611 $val = [];
1612 foreach ($mulValues as $v1) {
1613 foreach ($customOption as $coID => $coValue) {
1614 if (strtolower(trim($coValue['label'])) ==
1615 strtolower(trim($v1))
1616 ) {
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 }
1629 elseif ($field['html_type'] === 'Select' ||
1630 ($field['html_type'] === 'Radio' &&
1631 $field['data_type'] !== 'Boolean'
1632 )
1633 ) {
1634 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, TRUE);
1635 foreach ($customOption as $customID => $coValue) {
1636 if (strtolower(trim($coValue['label'])) ==
1637 strtolower(trim($value))
1638 ) {
1639 $value = $coValue['value'];
1640 $valid = TRUE;
1641 }
1642 }
1643 }
1644 elseif ($field['data_type'] === 'Date') {
1645 $valid = CRM_Utils_Rule::date($value);
1646 }
1647
1648 if ($valid) {
1649 $customValue[$fieldName] = $value;
1650 }
1651 }
1652 }
1653 }
1654
1655 return $customValue;
1656 }
1657
1658 /**
1659 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1660 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1661 *
1662 * @param int $customFieldId
1663 * Custom field id.
1664 * @param array $removeCustomFieldTypes
1665 * Remove custom fields of a type eg: array("Individual") ;.
1666 *
1667 * @return bool
1668 * false if it matches else true
1669 *
1670 * @throws \CRM_Core_Exception
1671 */
1672 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1673 $query = 'SELECT cg.extends as extends
1674 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1675 WHERE cg.id = cf.custom_group_id
1676 AND cf.id =' .
1677 CRM_Utils_Type::escape($customFieldId, 'Integer');
1678
1679 $extends = CRM_Core_DAO::singleValueQuery($query);
1680
1681 if (in_array($extends, $removeCustomFieldTypes)) {
1682 return FALSE;
1683 }
1684 return TRUE;
1685 }
1686
1687 /**
1688 * @param $table
1689 *
1690 * @return string
1691 * @throws Exception
1692 */
1693 public static function mapTableName($table) {
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
1710 case 'ContributionRecur':
1711 return 'civicrm_contribution_recur';
1712
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 = "
1742 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1743 $qParams = [1 => [$table, 'String']];
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 }
1754 throw new CRM_Core_Exception('Unknown error');
1755 }
1756 }
1757 }
1758
1759 /**
1760 * @param $group
1761 *
1762 * @throws \Exception
1763 */
1764 public static function createTable($group) {
1765 $params = [
1766 'name' => $group->table_name,
1767 'is_multiple' => $group->is_multiple ? 1 : 0,
1768 'extends_name' => self::mapTableName($group->extends),
1769 ];
1770
1771 $tableParams = CRM_Core_BAO_CustomField::defaultCustomTableSchema($params);
1772
1773 CRM_Core_BAO_SchemaHandler::createTable($tableParams);
1774 }
1775
1776 /**
1777 * Function returns formatted groupTree, so that form can be easily built in template
1778 *
1779 * @param array $groupTree
1780 * @param int $groupCount
1781 * Group count by default 1, but can vary for multiple value custom data.
1782 * @param \CRM_Core_Form $form
1783 *
1784 * @return array
1785 * @throws \CRM_Core_Exception
1786 */
1787 public static function formatGroupTree($groupTree, $groupCount = 1, &$form = NULL) {
1788 $formattedGroupTree = [];
1789 $uploadNames = $formValues = [];
1790
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) {
1796 $submittedValues = Civi::cache('customData')->get($qfKey);
1797 }
1798
1799 foreach ($groupTree as $key => $value) {
1800 if ($key === 'info') {
1801 continue;
1802 }
1803
1804 // add group information
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;
1812
1813 // this params needed of building multiple values
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;
1820
1821 // Properties that might have been filtered out but which
1822 // should be present to avoid smarty e-notices.
1823 $expectedProperties = ['options_per_line', 'help_pre', 'help_post'];
1824 // add field information
1825 foreach ($value['fields'] as $k => $properties) {
1826 $properties = array_merge(array_fill_keys($expectedProperties, NULL), $properties);
1827 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1828 if (isset($properties['customValue']) &&
1829 !CRM_Utils_System::isNull($properties['customValue']) &&
1830 !isset($properties['element_value'])
1831 ) {
1832 if (isset($properties['customValue'][$groupCount])) {
1833 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1834 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1835 if ($properties['data_type'] === 'File') {
1836 $properties['element_value'] = $properties['customValue'][$groupCount];
1837 $uploadNames[] = $properties['element_name'];
1838 }
1839 else {
1840 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1841 }
1842 }
1843 }
1844 if ($value = CRM_Utils_Request::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1845 $formValues[$properties['element_name']] = $value;
1846 }
1847 elseif (isset($submittedValues[$properties['element_name']])) {
1848 $properties['element_value'] = $submittedValues[$properties['element_name']];
1849 }
1850 unset($properties['customValue']);
1851 $formattedGroupTree[$key]['fields'][$k] = $properties;
1852 }
1853 }
1854
1855 if ($form) {
1856 if (count($formValues)) {
1857 $qf = $form->get('qfKey');
1858 $form->assign('qfKey', $qf);
1859 Civi::cache('customData')->set($qf, $formValues);
1860 }
1861
1862 // hack for field type File
1863 $formUploadNames = $form->get('uploadNames');
1864 if (is_array($formUploadNames)) {
1865 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1866 }
1867
1868 $form->set('uploadNames', $uploadNames);
1869 }
1870
1871 return $formattedGroupTree;
1872 }
1873
1874 /**
1875 * Build custom data view.
1876 *
1877 * @param CRM_Core_Form|CRM_Core_Page $form
1878 * Page object.
1879 * @param array $groupTree
1880 * @param bool $returnCount
1881 * True if customValue count needs to be returned.
1882 * @param int $gID
1883 * @param null $prefix
1884 * @param int $customValueId
1885 * @param int $entityId
1886 * @param bool $checkEditPermission
1887 *
1888 * @return array|int
1889 * @throws \CRM_Core_Exception
1890 */
1891 public static function buildCustomDataView(&$form, $groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL, $checkEditPermission = FALSE) {
1892 // Filter out pesky extra info
1893 unset($groupTree['info']);
1894
1895 $details = [];
1896
1897 $editableGroups = [];
1898 if ($checkEditPermission) {
1899 $editableGroups = \CRM_Core_Permission::customGroup(CRM_Core_Permission::EDIT);
1900 }
1901
1902 foreach ($groupTree as $key => $group) {
1903
1904 foreach ($group['fields'] as $k => $properties) {
1905 $groupID = $group['id'];
1906 if (!empty($properties['customValue'])) {
1907 foreach ($properties['customValue'] as $values) {
1908 if (!empty($customValueId) && $customValueId != $values['id']) {
1909 continue;
1910 }
1911 $details[$groupID][$values['id']]['title'] = $group['title'] ?? NULL;
1912 $details[$groupID][$values['id']]['name'] = $group['name'] ?? NULL;
1913 $details[$groupID][$values['id']]['help_pre'] = $group['help_pre'] ?? NULL;
1914 $details[$groupID][$values['id']]['help_post'] = $group['help_post'] ?? NULL;
1915 $details[$groupID][$values['id']]['collapse_display'] = $group['collapse_display'] ?? NULL;
1916 $details[$groupID][$values['id']]['collapse_adv_display'] = $group['collapse_adv_display'] ?? NULL;
1917 $details[$groupID][$values['id']]['style'] = $group['style'] ?? NULL;
1918 $details[$groupID][$values['id']]['fields'][$k] = [
1919 'field_title' => $properties['label'] ?? NULL,
1920 'field_type' => $properties['html_type'] ?? NULL,
1921 'field_data_type' => $properties['data_type'] ?? NULL,
1922 'field_value' => CRM_Core_BAO_CustomField::displayValue($values['data'], $properties['id'], $entityId),
1923 'options_per_line' => $properties['options_per_line'] ?? NULL,
1924 'data' => $values['data'],
1925 ];
1926 // editable = whether this set contains any non-read-only fields
1927 if (!isset($details[$groupID][$values['id']]['editable'])) {
1928 $details[$groupID][$values['id']]['editable'] = FALSE;
1929 }
1930 if (empty($properties['is_view']) && in_array($key, $editableGroups)) {
1931 $details[$groupID][$values['id']]['editable'] = TRUE;
1932 }
1933 // also return contact reference contact id if user has view all or edit all contacts perm
1934 if ($details[$groupID][$values['id']]['fields'][$k]['field_data_type'] === 'ContactReference'
1935 && CRM_Core_Permission::check([['view all contacts', 'edit all contacts']])
1936 ) {
1937 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_links'] = [];
1938 $path = CRM_Contact_DAO_Contact::getEntityPaths()['view'];
1939 foreach (CRM_Utils_Array::explodePadded($values['data'] ?? []) as $contactId) {
1940 $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'display_name');
1941 if ($displayName) {
1942 $url = CRM_Utils_System::url(str_replace('[id]', $contactId, $path));
1943 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_links'][] = '<a href="' . $url . '" title="' . htmlspecialchars(ts('View Contact')) . '">' .
1944 $displayName . '</a>';
1945 }
1946 }
1947 }
1948 }
1949 }
1950 else {
1951 $details[$groupID][0]['title'] = $group['title'] ?? NULL;
1952 $details[$groupID][0]['name'] = $group['name'] ?? NULL;
1953 $details[$groupID][0]['help_pre'] = $group['help_pre'] ?? NULL;
1954 $details[$groupID][0]['help_post'] = $group['help_post'] ?? NULL;
1955 $details[$groupID][0]['collapse_display'] = $group['collapse_display'] ?? NULL;
1956 $details[$groupID][0]['collapse_adv_display'] = $group['collapse_adv_display'] ?? NULL;
1957 $details[$groupID][0]['style'] = $group['style'] ?? NULL;
1958 $details[$groupID][0]['fields'][$k] = ['field_title' => $properties['label'] ?? NULL];
1959 }
1960 }
1961 }
1962
1963 if ($returnCount) {
1964 // return a single value count if group id is passed to function
1965 // else return a groupId and count mapped array
1966 if (!empty($gID)) {
1967 return count($details[$gID]);
1968 }
1969 else {
1970 $countValue = [];
1971 foreach ($details as $key => $value) {
1972 $countValue[$key] = count($details[$key]);
1973 }
1974 return $countValue;
1975 }
1976 }
1977 else {
1978 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1979 return $details;
1980 }
1981 }
1982
1983 /**
1984 * Get the custom group titles by custom field ids.
1985 *
1986 * @param array $fieldIds
1987 * Array of custom field ids.
1988 *
1989 * @return array|NULL
1990 * array consisting of groups and fields labels with ids.
1991 */
1992 public static function getGroupTitles($fieldIds) {
1993 if (!is_array($fieldIds) && empty($fieldIds)) {
1994 return NULL;
1995 }
1996
1997 $groupLabels = [];
1998 $fIds = "(" . implode(',', $fieldIds) . ")";
1999
2000 $query = "
2001 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2002 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2003 FROM civicrm_custom_group, civicrm_custom_field
2004 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2005 AND civicrm_custom_field.id IN {$fIds}";
2006
2007 $dao = CRM_Core_DAO::executeQuery($query);
2008 while ($dao->fetch()) {
2009 $groupLabels[$dao->fieldID] = [
2010 'fieldID' => $dao->fieldID,
2011 'fieldLabel' => $dao->fieldLabel,
2012 'groupID' => $dao->groupID,
2013 'groupTitle' => $dao->groupTitle,
2014 ];
2015 }
2016
2017 return $groupLabels;
2018 }
2019
2020 public static function dropAllTables() {
2021 $query = "SELECT table_name FROM civicrm_custom_group";
2022 $dao = CRM_Core_DAO::executeQuery($query);
2023
2024 while ($dao->fetch()) {
2025 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2026 CRM_Core_DAO::executeQuery($query);
2027 }
2028 }
2029
2030 /**
2031 * Check whether custom group is empty or not.
2032 *
2033 * @param int $gID
2034 * Custom group id.
2035 *
2036 * @return bool|NULL
2037 * true if empty otherwise false.
2038 */
2039 public static function isGroupEmpty($gID) {
2040 if (!$gID) {
2041 return NULL;
2042 }
2043
2044 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
2045 $gID,
2046 'table_name'
2047 );
2048
2049 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2050 $value = CRM_Core_DAO::singleValueQuery($query);
2051
2052 if (empty($value)) {
2053 return TRUE;
2054 }
2055
2056 return FALSE;
2057 }
2058
2059 /**
2060 * Get the list of types for objects that a custom group extends to.
2061 *
2062 * @param array $types
2063 * Var which should have the list appended.
2064 *
2065 * @return array
2066 * Array of types.
2067 * @throws \Exception
2068 */
2069 public static function getExtendedObjectTypes(&$types = []) {
2070 static $flag = FALSE, $objTypes = [];
2071
2072 if (!$flag) {
2073 $extendObjs = [];
2074 CRM_Core_OptionValue::getValues(['name' => 'cg_extend_objects'], $extendObjs, 'weight', TRUE);
2075
2076 foreach ($extendObjs as $ovId => $ovValues) {
2077 if ($ovValues['description']) {
2078 // description is expected to be a callback func to subtypes
2079 list($callback, $args) = explode(';', trim($ovValues['description']));
2080
2081 if (empty($args)) {
2082 $args = [];
2083 }
2084
2085 if (!is_array($args)) {
2086 throw new CRM_Core_Exception('Arg is not of type array');
2087 }
2088
2089 list($className) = explode('::', $callback);
2090 require_once str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
2091
2092 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2093 }
2094 }
2095 $flag = TRUE;
2096 }
2097
2098 $types = array_merge($types, $objTypes);
2099 return $objTypes;
2100 }
2101
2102 /**
2103 * @param int $customGroupId
2104 * @param int $entityId
2105 *
2106 * @return bool
2107 */
2108 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2109 // check whether the group is multiple
2110 $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2111 $isMultiple = (bool) $isMultiple;
2112 $hasReachedMax = FALSE;
2113 if ($isMultiple &&
2114 ($maxMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2115 ) {
2116 if (!$maxMultiple) {
2117 $hasReachedMax = FALSE;
2118 }
2119 else {
2120 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2121 // count the number of entries for a entity
2122 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2123 $params = [1 => [$entityId, 'Integer']];
2124 $count = CRM_Core_DAO::singleValueQuery($sql, $params);
2125
2126 if ($count >= $maxMultiple) {
2127 $hasReachedMax = TRUE;
2128 }
2129 }
2130 }
2131 return $hasReachedMax;
2132 }
2133
2134 /**
2135 * @return array
2136 */
2137 public static function getMultipleFieldGroup() {
2138 $multipleGroup = [];
2139 $dao = new CRM_Core_DAO_CustomGroup();
2140 $dao->is_multiple = 1;
2141 $dao->is_active = 1;
2142 $dao->find();
2143 while ($dao->fetch()) {
2144 $multipleGroup[$dao->id] = $dao->title;
2145 }
2146 return $multipleGroup;
2147 }
2148
2149 /**
2150 * Build the metadata tree for the custom group.
2151 *
2152 * @param string $entityType
2153 * @param array $toReturn
2154 * @param array $subTypes
2155 * @param string $queryString
2156 * @param array $params
2157 * @param string $subType
2158 *
2159 * @return array
2160 * @throws \CRM_Core_Exception
2161 */
2162 private static function buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType) {
2163 $groupTree = $multipleFieldGroups = [];
2164 $crmDAO = CRM_Core_DAO::executeQuery($queryString, $params);
2165 $customValueTables = [];
2166
2167 // process records
2168 while ($crmDAO->fetch()) {
2169 // get the id's
2170 $groupID = $crmDAO->civicrm_custom_group_id;
2171 $fieldId = $crmDAO->civicrm_custom_field_id;
2172 if ($crmDAO->civicrm_custom_group_is_multiple) {
2173 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name;
2174 }
2175 // create an array for groups if it does not exist
2176 if (!array_key_exists($groupID, $groupTree)) {
2177 $groupTree[$groupID] = [];
2178 $groupTree[$groupID]['id'] = $groupID;
2179
2180 // populate the group information
2181 foreach ($toReturn['custom_group'] as $fieldName) {
2182 $fullFieldName = "civicrm_custom_group_$fieldName";
2183 if ($fieldName == 'id' ||
2184 is_null($crmDAO->$fullFieldName)
2185 ) {
2186 continue;
2187 }
2188 // CRM-5507
2189 // This is an old bit of code - per the CRM number & probably does not work reliably if
2190 // that one contact sub-type exists.
2191 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
2192 $groupTree[$groupID]['subtype'] = self::validateSubTypeByEntity($entityType, $subType);
2193 }
2194 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
2195 }
2196 $groupTree[$groupID]['fields'] = [];
2197
2198 $customValueTables[$crmDAO->civicrm_custom_group_table_name] = [];
2199 }
2200
2201 // add the fields now (note - the query row will always contain a field)
2202 // we only reset this once, since multiple values come is as multiple rows
2203 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
2204 $groupTree[$groupID]['fields'][$fieldId] = [];
2205 }
2206
2207 $customValueTables[$crmDAO->civicrm_custom_group_table_name][$crmDAO->civicrm_custom_field_column_name] = 1;
2208 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
2209 // populate information for a custom field
2210 foreach ($toReturn['custom_field'] as $fieldName) {
2211 $fullFieldName = "civicrm_custom_field_$fieldName";
2212 if ($fieldName == 'id' ||
2213 is_null($crmDAO->$fullFieldName)
2214 ) {
2215 continue;
2216 }
2217 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
2218 }
2219 }
2220
2221 if (!empty($customValueTables)) {
2222 $groupTree['info'] = ['tables' => $customValueTables];
2223 }
2224 return [$multipleFieldGroups, $groupTree];
2225 }
2226
2227 public static function getSubTypes(): array {
2228 $sel2 = [];
2229 $activityType = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
2230
2231 $eventType = CRM_Core_OptionGroup::values('event_type');
2232 $grantType = CRM_Core_OptionGroup::values('grant_type');
2233 $campaignTypes = CRM_Campaign_PseudoConstant::campaignType();
2234 $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE);
2235 $participantRole = CRM_Core_OptionGroup::values('participant_role');
2236
2237 asort($activityType);
2238 asort($eventType);
2239 asort($grantType);
2240 asort($membershipType);
2241 asort($participantRole);
2242
2243 $sel2['Event'] = $eventType;
2244 $sel2['Grant'] = $grantType;
2245 $sel2['Activity'] = $activityType;
2246 $sel2['Campaign'] = $campaignTypes;
2247 $sel2['Membership'] = $membershipType;
2248 $sel2['ParticipantRole'] = $participantRole;
2249 $sel2['ParticipantEventName'] = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
2250 $sel2['ParticipantEventType'] = $eventType;
2251 $sel2['Contribution'] = CRM_Contribute_PseudoConstant::financialType();
2252 $sel2['Relationship'] = CRM_Custom_Form_Group::getRelationshipTypes();
2253
2254 $sel2['Individual'] = CRM_Contact_BAO_ContactType::subTypePairs('Individual', FALSE, NULL);
2255 $sel2['Household'] = CRM_Contact_BAO_ContactType::subTypePairs('Household', FALSE, NULL);
2256 $sel2['Organization'] = CRM_Contact_BAO_ContactType::subTypePairs('Organization', FALSE, NULL);
2257
2258 CRM_Core_BAO_CustomGroup::getExtendedObjectTypes($sel2);
2259 return $sel2;
2260 }
2261
2262 /**
2263 * Get the munged entity.
2264 *
2265 * This is the entity eg. Relationship or the name of the sub entity
2266 * e.g ParticipantRole.
2267 *
2268 * @param string $extends
2269 * @param int|null $extendsEntityColumn
2270 *
2271 * @return string
2272 */
2273 protected static function getMungedEntity($extends, $extendsEntityColumn = NULL) {
2274 if (!$extendsEntityColumn || $extendsEntityColumn === 'null') {
2275 return $extends;
2276 }
2277 return CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name')[$extendsEntityColumn];
2278 }
2279
2280 /**
2281 * @param int $groupId
2282 * @param int $operation
2283 * @param int|null $userId
2284 */
2285 public static function checkGroupAccess($groupId, $operation = CRM_Core_Permission::EDIT, $userId = NULL): bool {
2286 $allowedGroups = CRM_Core_Permission::customGroup($operation, FALSE, $userId);
2287 return in_array($groupId, $allowedGroups);
2288 }
2289
2290 }