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