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