Merge pull request #20396 from eileenmcnaughton/entry3
[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 * Class constructor.
25 */
26 public function __construct() {
27 parent::__construct();
28 }
29
30 /**
31 * Takes an associative array and creates a custom group object.
32 *
33 * This function is invoked from within the web form layer and also from the api layer
34 *
35 * @param array $params
36 * (reference) an assoc array of name/value pairs.
37 *
38 * @return CRM_Core_DAO_CustomGroup
39 * @throws \Exception
40 */
41 public static function create(&$params) {
42 // create custom group dao, populate fields and then save.
43 $group = new CRM_Core_DAO_CustomGroup();
44 if (isset($params['title'])) {
45 $group->title = $params['title'];
46 }
47
48 $extendsChildType = NULL;
49 // lets allow user to pass direct child type value, CRM-6893
50 if (!empty($params['extends_entity_column_value'])) {
51 $extendsChildType = $params['extends_entity_column_value'];
52 }
53 if (!CRM_Utils_System::isNull($extendsChildType)) {
54 $b = self::getMungedEntity($params['extends'], $params['extends_entity_column_id'] ?? NULL);
55 $registeredSubTypes = self::getSubTypes()[$b];
56 if (is_array($extendsChildType)) {
57 foreach ($extendsChildType as $childType) {
58 if (!array_key_exists($childType, $registeredSubTypes) && !in_array($childType, $registeredSubTypes, TRUE)) {
59 throw new CRM_Core_Exception('Supplied Sub type is not valid for the specified entitiy');
60 }
61 }
62 }
63 else {
64 if (!array_key_exists($extendsChildType, $registeredSubTypes) && !in_array($extendsChildType, $registeredSubTypes, TRUE)) {
65 throw new CRM_Core_Exception('Supplied Sub type is not valid for the specified entitiy');
66 }
67 $extendsChildType = [$extendsChildType];
68 }
69 $extendsChildType = implode(CRM_Core_DAO::VALUE_SEPARATOR, $extendsChildType);
70 if ($params['extends'] == 'Relationship') {
71 $extendsChildType = str_replace(['_a_b', '_b_a'], [
72 '',
73 '',
74 ], $extendsChildType);
75 }
76 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO::VALUE_SEPARATOR) {
77 $extendsChildType = CRM_Core_DAO::VALUE_SEPARATOR . $extendsChildType .
78 CRM_Core_DAO::VALUE_SEPARATOR;
79 }
80 }
81 else {
82 $extendsChildType = 'null';
83 }
84 $group->extends_entity_column_value = $extendsChildType;
85
86 if (isset($params['id'])) {
87 $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
88 }
89 else {
90 $oldWeight = 0;
91 }
92 $group->weight = CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array::value('weight', $params, FALSE));
93 $fields = [
94 'style',
95 'collapse_display',
96 'collapse_adv_display',
97 'help_pre',
98 'help_post',
99 'is_active',
100 'is_multiple',
101 'icon',
102 'extends_entity_column_id',
103 'extends',
104 ];
105 $current_db_version = CRM_Core_BAO_Domain::version();
106 $is_public_version = version_compare($current_db_version, '4.7.19', '>=');
107 if ($is_public_version) {
108 $fields[] = 'is_public';
109 }
110 foreach ($fields as $field) {
111 if (isset($params[$field])) {
112 $group->$field = $params[$field];
113 }
114 }
115 $group->max_multiple = isset($params['is_multiple']) ? (isset($params['max_multiple']) &&
116 $params['max_multiple'] >= '0'
117 ) ? $params['max_multiple'] : 'null' : 'null';
118
119 $tableName = $tableNameNeedingIndexUpdate = NULL;
120 if (isset($params['id'])) {
121 $group->id = $params['id'];
122
123 if (isset($params['is_multiple'])) {
124 // check whether custom group was changed from single-valued to multiple-valued
125 $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
126 $params['id'],
127 'is_multiple'
128 );
129
130 // dev/core#227 Fix issue where is_multiple in params maybe an empty string if checkbox is not rendered on the form.
131 $paramsIsMultiple = empty($params['is_multiple']) ? 0 : 1;
132 if ($paramsIsMultiple != $isMultiple) {
133 $tableNameNeedingIndexUpdate = CRM_Core_DAO::getFieldValue(
134 'CRM_Core_DAO_CustomGroup',
135 $params['id'],
136 'table_name'
137 );
138 }
139 }
140 }
141 else {
142 $group->created_id = $params['created_id'] ?? NULL;
143 $group->created_date = $params['created_date'] ?? NULL;
144
145 // Process name only during create, so it never changes
146 if (!empty($params['name'])) {
147 $group->name = CRM_Utils_String::munge($params['name']);
148 }
149 else {
150 $group->name = CRM_Utils_String::munge($group->title);
151 }
152
153 self::validateCustomGroupName($group);
154
155 if (isset($params['table_name'])) {
156 $tableName = $params['table_name'];
157
158 if (CRM_Core_DAO_AllCoreTables::isCoreTable($tableName)) {
159 // Bad idea. Prevent group creation because it might lead to a broken configuration.
160 throw new CRM_Core_Exception(ts('Cannot create custom table because %1 is already a core table.', ['1' => $tableName]));
161 }
162 }
163 }
164
165 if (array_key_exists('is_reserved', $params)) {
166 $group->is_reserved = $params['is_reserved'] ? 1 : 0;
167 }
168 $op = isset($params['id']) ? 'edit' : 'create';
169 CRM_Utils_Hook::pre($op, 'CustomGroup', CRM_Utils_Array::value('id', $params), $params);
170
171 // enclose the below in a transaction
172 $transaction = new CRM_Core_Transaction();
173
174 $group->save();
175 if (!isset($params['id'])) {
176 if (!isset($params['table_name'])) {
177 $munged_title = strtolower(CRM_Utils_String::munge($group->title, '_', 13));
178 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
179 }
180 $group->table_name = $tableName;
181 CRM_Core_DAO::setFieldValue('CRM_Core_DAO_CustomGroup',
182 $group->id,
183 'table_name',
184 $tableName
185 );
186
187 // now create the table associated with this group
188 self::createTable($group);
189 }
190 elseif ($tableNameNeedingIndexUpdate) {
191 CRM_Core_BAO_SchemaHandler::changeUniqueToIndex($tableNameNeedingIndexUpdate, CRM_Utils_Array::value('is_multiple', $params));
192 }
193
194 if (CRM_Utils_Array::value('overrideFKConstraint', $params) == 1) {
195 $table = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
196 $params['id'],
197 'table_name'
198 );
199 CRM_Core_BAO_SchemaHandler::changeFKConstraint($table, self::mapTableName($params['extends']));
200 }
201 $transaction->commit();
202
203 // reset the cache
204 CRM_Utils_System::flushCache();
205
206 if ($tableName) {
207 CRM_Utils_Hook::post('create', 'CustomGroup', $group->id, $group);
208 }
209 else {
210 CRM_Utils_Hook::post('edit', 'CustomGroup', $group->id, $group);
211 }
212
213 return $group;
214 }
215
216 /**
217 * Fetch object based on array of properties.
218 *
219 * @param array $params
220 * (reference ) an assoc array of name/value pairs.
221 * @param array $defaults
222 * (reference ) an assoc array to hold the flattened values.
223 *
224 * @return CRM_Core_DAO_CustomGroup
225 */
226 public static function retrieve(&$params, &$defaults) {
227 return CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
228 }
229
230 /**
231 * Ensure group name does not conflict with an existing field
232 *
233 * @param CRM_Core_DAO_CustomGroup $group
234 */
235 public static function validateCustomGroupName(CRM_Core_DAO_CustomGroup $group) {
236 $extends = in_array($group->extends, CRM_Contact_BAO_ContactType::basicTypes(TRUE)) ? 'Contact' : $group->extends;
237 $extendsDAO = CRM_Core_DAO_AllCoreTables::getFullName($extends);
238 if ($extendsDAO) {
239 $fields = array_column($extendsDAO::fields(), 'name');
240 if (in_array($group->name, $fields)) {
241 $group->name .= '0';
242 }
243 }
244 }
245
246 /**
247 * Update the is_active flag in the db.
248 *
249 * @param int $id
250 * Id of the database record.
251 * @param bool $is_active
252 * Value we want to set the is_active field.
253 *
254 * @return bool
255 * true if we found and updated the object, else false
256 */
257 public static function setIsActive($id, $is_active) {
258 // reset the cache
259 Civi::cache('fields')->flush();
260 // reset ACL and system caches.
261 CRM_Core_BAO_Cache::resetCaches();
262
263 if (!$is_active) {
264 CRM_Core_BAO_UFField::setUFFieldStatus($id, $is_active);
265 }
266
267 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
268 }
269
270 /**
271 * Determine if given entity (sub)type has any custom groups
272 *
273 * @param string $extends
274 * E.g. "Individual", "Activity".
275 * @param int $columnId
276 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
277 * @param string $columnValue
278 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
279 *
280 * @return bool
281 */
282 public static function hasCustomGroup($extends, $columnId, $columnValue) {
283 $dao = new CRM_Core_DAO_CustomGroup();
284 $dao->extends = $extends;
285 $dao->extends_entity_column_id = $columnId;
286 $escapedValue = CRM_Core_DAO::VALUE_SEPARATOR . CRM_Core_DAO::escapeString($columnValue) . CRM_Core_DAO::VALUE_SEPARATOR;
287 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
288 //$dao->extends_entity_column_value = $columnValue;
289 return (bool) $dao->find();
290 }
291
292 /**
293 * Determine if there are any CustomGroups for the given $activityTypeId.
294 * If none found, create one.
295 *
296 * @param int $activityTypeId
297 *
298 * @return bool
299 * TRUE if a group is found or created; FALSE on error
300 */
301 public static function autoCreateByActivityType($activityTypeId) {
302 if (self::hasCustomGroup('Activity', NULL, $activityTypeId)) {
303 return TRUE;
304 }
305 // everything
306 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE);
307 $params = [
308 'version' => 3,
309 'extends' => 'Activity',
310 'extends_entity_column_id' => NULL,
311 'extends_entity_column_value' => CRM_Utils_Array::implodePadded([$activityTypeId]),
312 'title' => ts('%1 Questions', [1 => $activityTypes[$activityTypeId]]),
313 'style' => 'Inline',
314 'is_active' => 1,
315 ];
316 $result = civicrm_api('CustomGroup', 'create', $params);
317 return !$result['is_error'];
318 }
319
320 /**
321 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
322 * This may also include entity specific data values.
323 *
324 * An array containing all custom groups and their custom fields is returned.
325 *
326 * @param string $entityType
327 * Of the contact whose contact type is needed.
328 * @param array $toReturn
329 * What data should be returned. ['custom_group' => ['id', 'name', etc.], 'custom_field' => ['id', 'label', etc.]]
330 * @param int $entityID
331 * @param int $groupID
332 * @param array $subTypes
333 * @param string $subName
334 * @param bool $fromCache
335 * @param bool $onlySubType
336 * Only return specified subtype or return specified subtype + unrestricted fields.
337 * @param bool $returnAll
338 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
339 * api - through which it is properly tested - so can be refactored with some comfort.)
340 *
341 * @param bool $checkPermission
342 * @param string|int $singleRecord
343 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
344 * @param bool $showPublicOnly
345 *
346 * @return array
347 * Custom field 'tree'.
348 *
349 * The returned array is keyed by group id and has the custom group table fields
350 * and a subkey 'fields' holding the specific custom fields.
351 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
352 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
353 *
354 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
355 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
356 * With caching the performance impact would be small & the function would be cleaner
357 *
358 * @throws \CRM_Core_Exception
359 */
360 public static function getTree(
361 $entityType,
362 $toReturn = [],
363 $entityID = NULL,
364 $groupID = NULL,
365 $subTypes = [],
366 $subName = NULL,
367 $fromCache = TRUE,
368 $onlySubType = NULL,
369 $returnAll = FALSE,
370 $checkPermission = TRUE,
371 $singleRecord = NULL,
372 $showPublicOnly = FALSE
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(CRM_Core_Permission::VIEW,
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 bulding 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 // add field information
1822 foreach ($value['fields'] as $k => $properties) {
1823 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1824 if (isset($properties['customValue']) &&
1825 !CRM_Utils_System::isNull($properties['customValue']) &&
1826 !isset($properties['element_value'])
1827 ) {
1828 if (isset($properties['customValue'][$groupCount])) {
1829 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1830 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1831 if ($properties['data_type'] === 'File') {
1832 $properties['element_value'] = $properties['customValue'][$groupCount];
1833 $uploadNames[] = $properties['element_name'];
1834 }
1835 else {
1836 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1837 }
1838 }
1839 }
1840 if ($value = CRM_Utils_Request::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1841 $formValues[$properties['element_name']] = $value;
1842 }
1843 elseif (isset($submittedValues[$properties['element_name']])) {
1844 $properties['element_value'] = $submittedValues[$properties['element_name']];
1845 }
1846 unset($properties['customValue']);
1847 $formattedGroupTree[$key]['fields'][$k] = $properties;
1848 }
1849 }
1850
1851 if ($form) {
1852 if (count($formValues)) {
1853 $qf = $form->get('qfKey');
1854 $form->assign('qfKey', $qf);
1855 Civi::cache('customData')->set($qf, $formValues);
1856 }
1857
1858 // hack for field type File
1859 $formUploadNames = $form->get('uploadNames');
1860 if (is_array($formUploadNames)) {
1861 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1862 }
1863
1864 $form->set('uploadNames', $uploadNames);
1865 }
1866
1867 return $formattedGroupTree;
1868 }
1869
1870 /**
1871 * Build custom data view.
1872 *
1873 * @param CRM_Core_Form|CRM_Core_Page $form
1874 * Page object.
1875 * @param array $groupTree
1876 * @param bool $returnCount
1877 * True if customValue count needs to be returned.
1878 * @param int $gID
1879 * @param null $prefix
1880 * @param int $customValueId
1881 * @param int $entityId
1882 *
1883 * @return array|int
1884 * @throws \CRM_Core_Exception
1885 */
1886 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
1887 $details = [];
1888 foreach ($groupTree as $key => $group) {
1889 if ($key === 'info') {
1890 continue;
1891 }
1892
1893 foreach ($group['fields'] as $k => $properties) {
1894 $groupID = $group['id'];
1895 if (!empty($properties['customValue'])) {
1896 foreach ($properties['customValue'] as $values) {
1897 if (!empty($customValueId) && $customValueId != $values['id']) {
1898 continue;
1899 }
1900 $details[$groupID][$values['id']]['title'] = $group['title'] ?? NULL;
1901 $details[$groupID][$values['id']]['name'] = $group['name'] ?? NULL;
1902 $details[$groupID][$values['id']]['help_pre'] = $group['help_pre'] ?? NULL;
1903 $details[$groupID][$values['id']]['help_post'] = $group['help_post'] ?? NULL;
1904 $details[$groupID][$values['id']]['collapse_display'] = $group['collapse_display'] ?? NULL;
1905 $details[$groupID][$values['id']]['collapse_adv_display'] = $group['collapse_adv_display'] ?? NULL;
1906 $details[$groupID][$values['id']]['style'] = $group['style'] ?? NULL;
1907 $details[$groupID][$values['id']]['fields'][$k] = [
1908 'field_title' => $properties['label'] ?? NULL,
1909 'field_type' => $properties['html_type'] ?? NULL,
1910 'field_data_type' => $properties['data_type'] ?? NULL,
1911 'field_value' => CRM_Core_BAO_CustomField::displayValue($values['data'], $properties['id'], $entityId),
1912 'options_per_line' => $properties['options_per_line'] ?? NULL,
1913 ];
1914 // editable = whether this set contains any non-read-only fields
1915 if (!isset($details[$groupID][$values['id']]['editable'])) {
1916 $details[$groupID][$values['id']]['editable'] = FALSE;
1917 }
1918 if (empty($properties['is_view'])) {
1919 $details[$groupID][$values['id']]['editable'] = TRUE;
1920 }
1921 // also return contact reference contact id if user has view all or edit all contacts perm
1922 if ($details[$groupID][$values['id']]['fields'][$k]['field_data_type'] === 'ContactReference'
1923 && CRM_Core_Permission::check([['view all contacts', 'edit all contacts']])
1924 ) {
1925 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_links'] = [];
1926 $path = CRM_Contact_DAO_Contact::getEntityPaths()['view'];
1927 foreach (CRM_Utils_Array::explodePadded($values['data'] ?? []) as $contactId) {
1928 $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'display_name');
1929 if ($displayName) {
1930 $url = CRM_Utils_System::url(str_replace('[id]', $contactId, $path));
1931 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_links'][] = '<a href="' . $url . '" title="' . htmlspecialchars(ts('View Contact')) . '">' .
1932 $displayName . '</a>';
1933 }
1934 }
1935 }
1936 }
1937 }
1938 else {
1939 $details[$groupID][0]['title'] = $group['title'] ?? NULL;
1940 $details[$groupID][0]['name'] = $group['name'] ?? NULL;
1941 $details[$groupID][0]['help_pre'] = $group['help_pre'] ?? NULL;
1942 $details[$groupID][0]['help_post'] = $group['help_post'] ?? NULL;
1943 $details[$groupID][0]['collapse_display'] = $group['collapse_display'] ?? NULL;
1944 $details[$groupID][0]['collapse_adv_display'] = $group['collapse_adv_display'] ?? NULL;
1945 $details[$groupID][0]['style'] = $group['style'] ?? NULL;
1946 $details[$groupID][0]['fields'][$k] = ['field_title' => $properties['label'] ?? NULL];
1947 }
1948 }
1949 }
1950
1951 if ($returnCount) {
1952 // return a single value count if group id is passed to function
1953 // else return a groupId and count mapped array
1954 if (!empty($gID)) {
1955 return count($details[$gID]);
1956 }
1957 else {
1958 $countValue = [];
1959 foreach ($details as $key => $value) {
1960 $countValue[$key] = count($details[$key]);
1961 }
1962 return $countValue;
1963 }
1964 }
1965 else {
1966 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1967 return $details;
1968 }
1969 }
1970
1971 /**
1972 * Get the custom group titles by custom field ids.
1973 *
1974 * @param array $fieldIds
1975 * Array of custom field ids.
1976 *
1977 * @return array|NULL
1978 * array consisting of groups and fields labels with ids.
1979 */
1980 public static function getGroupTitles($fieldIds) {
1981 if (!is_array($fieldIds) && empty($fieldIds)) {
1982 return NULL;
1983 }
1984
1985 $groupLabels = [];
1986 $fIds = "(" . implode(',', $fieldIds) . ")";
1987
1988 $query = "
1989 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
1990 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
1991 FROM civicrm_custom_group, civicrm_custom_field
1992 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
1993 AND civicrm_custom_field.id IN {$fIds}";
1994
1995 $dao = CRM_Core_DAO::executeQuery($query);
1996 while ($dao->fetch()) {
1997 $groupLabels[$dao->fieldID] = [
1998 'fieldID' => $dao->fieldID,
1999 'fieldLabel' => $dao->fieldLabel,
2000 'groupID' => $dao->groupID,
2001 'groupTitle' => $dao->groupTitle,
2002 ];
2003 }
2004
2005 return $groupLabels;
2006 }
2007
2008 public static function dropAllTables() {
2009 $query = "SELECT table_name FROM civicrm_custom_group";
2010 $dao = CRM_Core_DAO::executeQuery($query);
2011
2012 while ($dao->fetch()) {
2013 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2014 CRM_Core_DAO::executeQuery($query);
2015 }
2016 }
2017
2018 /**
2019 * Check whether custom group is empty or not.
2020 *
2021 * @param int $gID
2022 * Custom group id.
2023 *
2024 * @return bool|NULL
2025 * true if empty otherwise false.
2026 */
2027 public static function isGroupEmpty($gID) {
2028 if (!$gID) {
2029 return NULL;
2030 }
2031
2032 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
2033 $gID,
2034 'table_name'
2035 );
2036
2037 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2038 $value = CRM_Core_DAO::singleValueQuery($query);
2039
2040 if (empty($value)) {
2041 return TRUE;
2042 }
2043
2044 return FALSE;
2045 }
2046
2047 /**
2048 * Get the list of types for objects that a custom group extends to.
2049 *
2050 * @param array $types
2051 * Var which should have the list appended.
2052 *
2053 * @return array
2054 * Array of types.
2055 * @throws \Exception
2056 */
2057 public static function getExtendedObjectTypes(&$types = []) {
2058 static $flag = FALSE, $objTypes = [];
2059
2060 if (!$flag) {
2061 $extendObjs = [];
2062 CRM_Core_OptionValue::getValues(['name' => 'cg_extend_objects'], $extendObjs, 'weight', TRUE);
2063
2064 foreach ($extendObjs as $ovId => $ovValues) {
2065 if ($ovValues['description']) {
2066 // description is expected to be a callback func to subtypes
2067 list($callback, $args) = explode(';', trim($ovValues['description']));
2068
2069 if (empty($args)) {
2070 $args = [];
2071 }
2072
2073 if (!is_array($args)) {
2074 throw new CRM_Core_Exception('Arg is not of type array');
2075 }
2076
2077 list($className) = explode('::', $callback);
2078 require_once str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
2079
2080 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2081 }
2082 }
2083 $flag = TRUE;
2084 }
2085
2086 $types = array_merge($types, $objTypes);
2087 return $objTypes;
2088 }
2089
2090 /**
2091 * @param int $customGroupId
2092 * @param int $entityId
2093 *
2094 * @return bool
2095 */
2096 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2097 // check whether the group is multiple
2098 $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2099 $isMultiple = (bool) $isMultiple;
2100 $hasReachedMax = FALSE;
2101 if ($isMultiple &&
2102 ($maxMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2103 ) {
2104 if (!$maxMultiple) {
2105 $hasReachedMax = FALSE;
2106 }
2107 else {
2108 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2109 // count the number of entries for a entity
2110 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2111 $params = [1 => [$entityId, 'Integer']];
2112 $count = CRM_Core_DAO::singleValueQuery($sql, $params);
2113
2114 if ($count >= $maxMultiple) {
2115 $hasReachedMax = TRUE;
2116 }
2117 }
2118 }
2119 return $hasReachedMax;
2120 }
2121
2122 /**
2123 * @return array
2124 */
2125 public static function getMultipleFieldGroup() {
2126 $multipleGroup = [];
2127 $dao = new CRM_Core_DAO_CustomGroup();
2128 $dao->is_multiple = 1;
2129 $dao->is_active = 1;
2130 $dao->find();
2131 while ($dao->fetch()) {
2132 $multipleGroup[$dao->id] = $dao->title;
2133 }
2134 return $multipleGroup;
2135 }
2136
2137 /**
2138 * Build the metadata tree for the custom group.
2139 *
2140 * @param string $entityType
2141 * @param array $toReturn
2142 * @param array $subTypes
2143 * @param string $queryString
2144 * @param array $params
2145 * @param string $subType
2146 *
2147 * @return array
2148 * @throws \CRM_Core_Exception
2149 */
2150 private static function buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType) {
2151 $groupTree = $multipleFieldGroups = [];
2152 $crmDAO = CRM_Core_DAO::executeQuery($queryString, $params);
2153 $customValueTables = [];
2154
2155 // process records
2156 while ($crmDAO->fetch()) {
2157 // get the id's
2158 $groupID = $crmDAO->civicrm_custom_group_id;
2159 $fieldId = $crmDAO->civicrm_custom_field_id;
2160 if ($crmDAO->civicrm_custom_group_is_multiple) {
2161 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name;
2162 }
2163 // create an array for groups if it does not exist
2164 if (!array_key_exists($groupID, $groupTree)) {
2165 $groupTree[$groupID] = [];
2166 $groupTree[$groupID]['id'] = $groupID;
2167
2168 // populate the group information
2169 foreach ($toReturn['custom_group'] as $fieldName) {
2170 $fullFieldName = "civicrm_custom_group_$fieldName";
2171 if ($fieldName == 'id' ||
2172 is_null($crmDAO->$fullFieldName)
2173 ) {
2174 continue;
2175 }
2176 // CRM-5507
2177 // This is an old bit of code - per the CRM number & probably does not work reliably if
2178 // that one contact sub-type exists.
2179 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
2180 $groupTree[$groupID]['subtype'] = self::validateSubTypeByEntity($entityType, $subType);
2181 }
2182 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
2183 }
2184 $groupTree[$groupID]['fields'] = [];
2185
2186 $customValueTables[$crmDAO->civicrm_custom_group_table_name] = [];
2187 }
2188
2189 // add the fields now (note - the query row will always contain a field)
2190 // we only reset this once, since multiple values come is as multiple rows
2191 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
2192 $groupTree[$groupID]['fields'][$fieldId] = [];
2193 }
2194
2195 $customValueTables[$crmDAO->civicrm_custom_group_table_name][$crmDAO->civicrm_custom_field_column_name] = 1;
2196 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
2197 // populate information for a custom field
2198 foreach ($toReturn['custom_field'] as $fieldName) {
2199 $fullFieldName = "civicrm_custom_field_$fieldName";
2200 if ($fieldName == 'id' ||
2201 is_null($crmDAO->$fullFieldName)
2202 ) {
2203 continue;
2204 }
2205 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
2206 }
2207 }
2208
2209 if (!empty($customValueTables)) {
2210 $groupTree['info'] = ['tables' => $customValueTables];
2211 }
2212 return [$multipleFieldGroups, $groupTree];
2213 }
2214
2215 public static function getSubTypes(): array {
2216 $sel2 = [];
2217 $activityType = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
2218
2219 $eventType = CRM_Core_OptionGroup::values('event_type');
2220 $grantType = CRM_Core_OptionGroup::values('grant_type');
2221 $campaignTypes = CRM_Campaign_PseudoConstant::campaignType();
2222 $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE);
2223 $participantRole = CRM_Core_OptionGroup::values('participant_role');
2224
2225 asort($activityType);
2226 asort($eventType);
2227 asort($grantType);
2228 asort($membershipType);
2229 asort($participantRole);
2230
2231 $sel2['Event'] = $eventType;
2232 $sel2['Grant'] = $grantType;
2233 $sel2['Activity'] = $activityType;
2234 $sel2['Campaign'] = $campaignTypes;
2235 $sel2['Membership'] = $membershipType;
2236 $sel2['ParticipantRole'] = $participantRole;
2237 $sel2['ParticipantEventName'] = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )");
2238 $sel2['ParticipantEventType'] = $eventType;
2239 $sel2['Contribution'] = CRM_Contribute_PseudoConstant::financialType();
2240 $sel2['Relationship'] = CRM_Custom_Form_Group::getRelationshipTypes();
2241
2242 $sel2['Individual'] = CRM_Contact_BAO_ContactType::subTypePairs('Individual', FALSE, NULL);
2243 $sel2['Household'] = CRM_Contact_BAO_ContactType::subTypePairs('Household', FALSE, NULL);
2244 $sel2['Organization'] = CRM_Contact_BAO_ContactType::subTypePairs('Organization', FALSE, NULL);
2245
2246 CRM_Core_BAO_CustomGroup::getExtendedObjectTypes($sel2);
2247 return $sel2;
2248 }
2249
2250 /**
2251 * Get the munged entity.
2252 *
2253 * This is the entity eg. Relationship or the name of the sub entity
2254 * e.g ParticipantRole.
2255 *
2256 * @param string $extends
2257 * @param int|null $extendsEntityColumn
2258 *
2259 * @return string
2260 */
2261 protected static function getMungedEntity($extends, $extendsEntityColumn = NULL) {
2262 if (!$extendsEntityColumn || $extendsEntityColumn === 'null') {
2263 return $extends;
2264 }
2265 return CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name')[$extendsEntityColumn];
2266 }
2267
2268 }