Merge pull request #16626 from pradpnayak/lineItemFixes
[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_DAO::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config::domainID());
112 $is_public_version = $current_db_version >= '4.7.19' ? 1 : 0;
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 'serialize',
404 ],
405 'custom_group' => [
406 'id',
407 'name',
408 'table_name',
409 'title',
410 'help_pre',
411 'help_post',
412 'collapse_display',
413 'style',
414 'is_multiple',
415 'extends',
416 'extends_entity_column_id',
417 'extends_entity_column_value',
418 'max_multiple',
419 ],
420 ];
421 $current_db_version = CRM_Core_DAO::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config::domainID());
422 $is_public_version = $current_db_version >= '4.7.19' ? 1 : 0;
423 if ($is_public_version) {
424 $tableData['custom_group'][] = 'is_public';
425 }
426 if (!$toReturn || !is_array($toReturn)) {
427 $toReturn = $tableData;
428 }
429 else {
430 // Supply defaults and remove unknown array keys
431 $toReturn = array_intersect_key(array_filter($toReturn) + $tableData, $tableData);
432 // Merge in required fields that we must have
433 $toReturn['custom_field'] = array_unique(array_merge($toReturn['custom_field'], ['id', 'column_name', 'data_type']));
434 $toReturn['custom_group'] = array_unique(array_merge($toReturn['custom_group'], ['id', 'is_multiple', 'table_name', 'name']));
435 // Validate return fields
436 $toReturn['custom_field'] = array_intersect($toReturn['custom_field'], array_keys(CRM_Core_DAO_CustomField::fieldKeys()));
437 $toReturn['custom_group'] = array_intersect($toReturn['custom_group'], array_keys(CRM_Core_DAO_CustomGroup::fieldKeys()));
438 }
439
440 // create select
441 $select = [];
442 foreach ($toReturn as $tableName => $tableColumn) {
443 foreach ($tableColumn as $columnName) {
444 $select[] = "civicrm_{$tableName}.{$columnName} as civicrm_{$tableName}_{$columnName}";
445 }
446 }
447 $strSelect = "SELECT " . implode(', ', $select);
448
449 // from, where, order by
450 $strFrom = "
451 FROM civicrm_custom_group
452 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
453 ";
454
455 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
456 if ($entityType == "Individual" || $entityType == 'Organization' ||
457 $entityType == 'Household'
458 ) {
459 $in = "'$entityType', 'Contact'";
460 }
461 elseif (strpos($entityType, "'") !== FALSE) {
462 // this allows the calling function to send in multiple entity types
463 $in = $entityType;
464 }
465 else {
466 // quote it
467 $in = "'$entityType'";
468 }
469
470 $params = [];
471 $sqlParamKey = 1;
472 $subType = '';
473 if (!empty($subTypes)) {
474 foreach ($subTypes as $key => $subType) {
475 $subTypeClauses[] = self::whereListHas("civicrm_custom_group.extends_entity_column_value", self::validateSubTypeByEntity($entityType, $subType));
476 }
477 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
478 if (!$onlySubType) {
479 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
480 }
481
482 $strWhere = "
483 WHERE civicrm_custom_group.is_active = 1
484 AND civicrm_custom_field.is_active = 1
485 AND civicrm_custom_group.extends IN ($in)
486 AND $subTypeClause
487 ";
488 if ($subName) {
489 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = %{$sqlParamKey}";
490 $params[$sqlParamKey] = [$subName, 'String'];
491 $sqlParamKey = $sqlParamKey + 1;
492 }
493 }
494 else {
495 $strWhere = "
496 WHERE civicrm_custom_group.is_active = 1
497 AND civicrm_custom_field.is_active = 1
498 AND civicrm_custom_group.extends IN ($in)
499 ";
500 if (!$returnAll) {
501 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
502 }
503 }
504
505 if ($groupID > 0) {
506 // since we want a specific group id we add it to the where clause
507 $strWhere .= " AND civicrm_custom_group.id = %{$sqlParamKey}";
508 $params[$sqlParamKey] = [$groupID, 'Integer'];
509 }
510 elseif (!$groupID) {
511 // since groupID is false we need to show all Inline groups
512 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
513 }
514 if ($checkPermission) {
515 // ensure that the user has access to these custom groups
516 $strWhere .= " AND " .
517 CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
518 'civicrm_custom_group.'
519 );
520 }
521
522 if ($showPublicOnly && $is_public_version) {
523 $strWhere .= "AND civicrm_custom_group.is_public = 1";
524 }
525
526 $orderBy = "
527 ORDER BY civicrm_custom_group.weight,
528 civicrm_custom_group.title,
529 civicrm_custom_field.weight,
530 civicrm_custom_field.label
531 ";
532
533 // final query string
534 $queryString = "$strSelect $strFrom $strWhere $orderBy";
535
536 // lets see if we can retrieve the groupTree from cache
537 $cacheString = $queryString;
538 if ($groupID > 0) {
539 $cacheString .= "_{$groupID}";
540 }
541 else {
542 $cacheString .= "_Inline";
543 }
544
545 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
546 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
547 $cache = CRM_Utils_Cache::singleton();
548 if ($fromCache) {
549 $groupTree = $cache->get($cacheKey);
550 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
551 }
552
553 if (empty($groupTree)) {
554 list($multipleFieldGroups, $groupTree) = self::buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType);
555
556 $cache->set($cacheKey, $groupTree);
557 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
558 }
559 // entitySelectClauses is an array of select clauses for custom value tables which are not multiple
560 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
561 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = [];
562 $singleFieldTables = [];
563 // now that we have all the groups and fields, lets get the values
564 // since we need to know the table and field names
565 // add info to groupTree
566
567 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
568 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
569 ) {
570 $select = $from = $where = [];
571 $groupTree['info']['where'] = NULL;
572
573 foreach ($groupTree['info']['tables'] as $table => $fields) {
574 $groupTree['info']['from'][] = $table;
575 $select = [
576 "{$table}.id as {$table}_id",
577 "{$table}.entity_id as {$table}_entity_id",
578 ];
579 foreach ($fields as $column => $dontCare) {
580 $select[] = "{$table}.{$column} as {$table}_{$column}";
581 }
582 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
583 if ($entityID) {
584 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
585 if (in_array($table, $multipleFieldGroups) &&
586 self::customGroupDataExistsForEntity($entityID, $table)
587 ) {
588 $entityMultipleSelectClauses[$table] = $select;
589 }
590 else {
591 $singleFieldTables[] = $table;
592 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
593 }
594
595 }
596 }
597 if ($entityID && !empty($singleFieldTables)) {
598 self::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
599 }
600 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
601 if (!empty($multipleFieldTablesWithEntityData)) {
602 self::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
603 }
604
605 }
606 return $groupTree;
607 }
608
609 /**
610 * Clean and validate the filter before it is used in a db query.
611 *
612 * @param string $entityType
613 * @param string $subType
614 *
615 * @return string
616 * @throws \CRM_Core_Exception
617 */
618 protected static function validateSubTypeByEntity($entityType, $subType) {
619 $subType = trim($subType, CRM_Core_DAO::VALUE_SEPARATOR);
620 if (is_numeric($subType)) {
621 return $subType;
622 }
623
624 $contactTypes = CRM_Contact_BAO_ContactType::basicTypeInfo(TRUE);
625 $contactTypes = array_merge($contactTypes, ['Event' => 1]);
626
627 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
628 throw new CRM_Core_Exception('Invalid Entity Filter');
629 }
630 $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo($entityType, TRUE);
631 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant::eventType());
632 if (!array_key_exists($subType, $subTypes)) {
633 throw new CRM_Core_Exception('Invalid Filter');
634 }
635 return $subType;
636 }
637
638 /**
639 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
640 * a WHERE condition for rows that include $value. Use whereListHas().
641 *
642 * @param string $column
643 * @param string $value
644 * @param string $delimiter
645 * @return string
646 * SQL condition.
647 */
648 private static function whereListHas($column, $value, $delimiter = CRM_Core_DAO::VALUE_SEPARATOR) {
649 // ?
650 $bareValue = trim($value, $delimiter);
651 $escapedValue = CRM_Utils_Type::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
652 return "($column LIKE \"$escapedValue\")";
653 }
654
655 /**
656 * Check whether the custom group has any data for the given entity.
657 *
658 * @param int $entityID
659 * Id of entity for whom we are checking data for.
660 * @param string $table
661 * Table that we are checking.
662 *
663 * @param bool $getCount
664 *
665 * @return bool
666 * does this entity have data in this custom table
667 */
668 public static function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
669 $query = "
670 SELECT count(id)
671 FROM $table
672 WHERE entity_id = $entityID
673 ";
674 $recordExists = CRM_Core_DAO::singleValueQuery($query);
675 if ($getCount) {
676 return $recordExists;
677 }
678 return (bool) $recordExists;
679 }
680
681 /**
682 * Build the group tree for Custom fields which are not 'is_multiple'
683 *
684 * The combination of all these fields in one query with a 'using' join was not working for
685 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
686 * mechanism as it seemed to be acceptable in this context
687 *
688 * @param array $groupTree
689 * (reference) group tree array which is being built.
690 * @param int $entityID
691 * Id of entity for whom the tree is being build up.
692 * @param array $entitySingleSelectClauses
693 * Array of select clauses relevant to the entity.
694 * @param array $singleFieldTablesWithEntityData
695 * Array of tables in which this entity has data.
696 */
697 public static function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
698 $select = implode(', ', $entitySingleSelectClauses);
699 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
700 foreach ($singleFieldTablesWithEntityData as $table) {
701 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
702 }
703
704 $query = "
705 SELECT $select
706 FROM $fromSQL
707 WHERE first.entity_id = $entityID
708 ";
709 self::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
710 }
711
712 /**
713 * Build the group tree for Custom fields which are 'is_multiple'
714 *
715 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
716 *
717 * @param array $groupTree
718 * (reference) group tree array which is being built.
719 * @param int $entityID
720 * Id of entity for whom the tree is being build up.
721 * @param array $entityMultipleSelectClauses
722 * Array of select clauses relevant to the entity.
723 * @param array $multipleFieldTablesWithEntityData
724 * Array of tables in which this entity has data.
725 * @param string|int $singleRecord
726 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
727 */
728 public static function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
729 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
730 $select = implode(',', $selectClauses);
731 $query = "
732 SELECT $select
733 FROM $table
734 WHERE entity_id = $entityID
735 ";
736 if ($singleRecord) {
737 $offset = $singleRecord - 1;
738 $query .= " LIMIT {$offset}, 1";
739 }
740 self::buildTreeEntityDataFromQuery($groupTree, $query, [$table], $singleRecord);
741 }
742 }
743
744 /**
745 * Build the tree entity data - starting from a query retrieving the custom fields build the group
746 * tree data for the relevant entity (entity is included in the query).
747 *
748 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
749 *
750 * @param array $groupTree
751 * (reference) group tree array which is being built.
752 * @param string $query
753 * @param array $includedTables
754 * Tables to include - required because the function (for historical reasons).
755 * iterates through the group tree
756 * @param string|int $singleRecord
757 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
758 */
759 public static function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
760 $dao = CRM_Core_DAO::executeQuery($query);
761 while ($dao->fetch()) {
762 foreach ($groupTree as $groupID => $group) {
763 if ($groupID === 'info') {
764 continue;
765 }
766 $table = $groupTree[$groupID]['table_name'];
767 //working from the groupTree instead of the table list means we have to iterate & exclude.
768 // this could possibly be re-written as other parts of the function have been refactored
769 // for now we just check if the given table is to be included in this function
770 if (!in_array($table, $includedTables)) {
771 continue;
772 }
773 foreach ($group['fields'] as $fieldID => $dontCare) {
774 self::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
775 }
776 }
777 }
778 }
779
780 /**
781 * Build the entity-specific custom data into the group tree on a per-field basis
782 *
783 * @param object $dao
784 * Object representing the custom field to be populated into the groupTree.
785 * @param array $groupTree
786 * (reference) the group tree being build.
787 * @param string $table
788 * Table name.
789 * @param int $groupID
790 * Custom group ID.
791 * @param int $fieldID
792 * Custom field ID.
793 * @param string|int $singleRecord
794 * holds 'new' or id if loading view/edit/copy for a single record.
795 */
796 public static function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
797 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
798 $idName = "{$table}_id";
799 $fieldName = "{$table}_{$column}";
800 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
801 if ($dataType == 'File') {
802 if (isset($dao->$fieldName)) {
803 $config = CRM_Core_Config::singleton();
804 $fileDAO = new CRM_Core_DAO_File();
805 $fileDAO->id = $dao->$fieldName;
806
807 if ($fileDAO->find(TRUE)) {
808 $entityIDName = "{$table}_entity_id";
809 $fileHash = CRM_Core_BAO_File::generateFileHash($dao->$entityIDName, $fileDAO->id);
810 $customValue['id'] = $dao->$idName;
811 $customValue['data'] = $fileDAO->uri;
812 $customValue['fid'] = $fileDAO->id;
813 $customValue['fileURL'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}&fcs=$fileHash");
814 $customValue['displayURL'] = NULL;
815 $deleteExtra = ts('Are you sure you want to delete attached file.');
816 $deleteURL = [
817 CRM_Core_Action::DELETE => [
818 'name' => ts('Delete Attached File'),
819 'url' => 'civicrm/file',
820 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete&fcs=%%fcs%%',
821 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
822 . '\' ) ) this.href+=\'&amp;confirmed=1\'; else return false;"',
823 ],
824 ];
825 $customValue['deleteURL'] = CRM_Core_Action::formLink($deleteURL,
826 CRM_Core_Action::DELETE,
827 [
828 'id' => $fileDAO->id,
829 'eid' => $dao->$entityIDName,
830 'fid' => $fieldID,
831 'fcs' => $fileHash,
832 ],
833 ts('more'),
834 FALSE,
835 'file.manage.delete',
836 'File',
837 $fileDAO->id
838 );
839 $customValue['deleteURLArgs'] = CRM_Core_BAO_File::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id);
840 $customValue['fileName'] = CRM_Utils_File::cleanFileName(basename($fileDAO->uri));
841 if ($fileDAO->mime_type == "image/jpeg" ||
842 $fileDAO->mime_type == "image/pjpeg" ||
843 $fileDAO->mime_type == "image/gif" ||
844 $fileDAO->mime_type == "image/x-png" ||
845 $fileDAO->mime_type == "image/png"
846 ) {
847 $customValue['displayURL'] = $customValue['fileURL'];
848 $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile',
849 $fileDAO->id,
850 'entity_id',
851 'file_id'
852 );
853 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL) .
854 $fileDAO->uri;
855 list($path) = CRM_Core_BAO_File::path($fileDAO->id, $entityId);
856 if ($path && file_exists($path)) {
857 list($imageWidth, $imageHeight) = getimagesize($path);
858 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
859 $customValue['imageThumbWidth'] = $imageThumbWidth;
860 $customValue['imageThumbHeight'] = $imageThumbHeight;
861 }
862 }
863 }
864 }
865 else {
866 $customValue = [
867 'id' => $dao->$idName,
868 'data' => '',
869 ];
870 }
871 }
872 else {
873 $customValue = [
874 'id' => $dao->$idName,
875 'data' => $dao->$fieldName,
876 ];
877 }
878
879 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
880 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [];
881 }
882 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
883 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [$singleRecord => $customValue];
884 }
885 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
886 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = [1 => $customValue];
887 }
888 else {
889 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
890 }
891 }
892
893 /**
894 * Get the group title.
895 *
896 * @param int $id
897 * Id of group.
898 *
899 * @return string
900 * title
901 */
902 public static function getTitle($id) {
903 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
904 }
905
906 /**
907 * Get custom group details for a group.
908 *
909 * An array containing custom group details (including their custom field) is returned.
910 *
911 * @param int $groupId
912 * Group id whose details are needed.
913 * @param bool $searchable
914 * Is this field searchable.
915 * @param array $extends
916 * Which table does it extend if any.
917 *
918 * @param bool $inSelector
919 *
920 * @return array
921 * array consisting of all group and field details
922 */
923 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
924 // create a new tree
925 $groupTree = [];
926
927 // using tableData to build the queryString
928 $tableData = [
929 'civicrm_custom_field' => [
930 'id',
931 'label',
932 'data_type',
933 'html_type',
934 'default_value',
935 'attributes',
936 'is_required',
937 'help_pre',
938 'help_post',
939 'options_per_line',
940 'is_searchable',
941 'start_date_years',
942 'end_date_years',
943 'is_search_range',
944 'date_format',
945 'time_format',
946 'note_columns',
947 'note_rows',
948 'column_name',
949 'is_view',
950 'option_group_id',
951 'in_selector',
952 ],
953 'civicrm_custom_group' => [
954 'id',
955 'name',
956 'title',
957 'help_pre',
958 'help_post',
959 'collapse_display',
960 'collapse_adv_display',
961 'extends',
962 'extends_entity_column_value',
963 'table_name',
964 'is_multiple',
965 ],
966 ];
967
968 // create select
969 $s = [];
970 foreach ($tableData as $tableName => $tableColumn) {
971 foreach ($tableColumn as $columnName) {
972 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
973 }
974 }
975 $select = 'SELECT ' . implode(', ', $s);
976 $params = [];
977 // from, where, order by
978 $from = " FROM civicrm_custom_field, civicrm_custom_group";
979 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
980 AND civicrm_custom_group.is_active = 1
981 AND civicrm_custom_field.is_active = 1 ";
982 if ($groupId) {
983 $params[1] = [$groupId, 'Integer'];
984 $where .= " AND civicrm_custom_group.id = %1";
985 }
986
987 if ($searchable) {
988 $where .= " AND civicrm_custom_field.is_searchable = 1";
989 }
990
991 if ($inSelector) {
992 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
993 }
994
995 if ($extends) {
996 $clause = [];
997 foreach ($extends as $e) {
998 $clause[] = "civicrm_custom_group.extends = '$e'";
999 }
1000 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1001
1002 //include case activities customdata if case is enabled
1003 if (in_array('Activity', $extends)) {
1004 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1005 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1006 $params[2] = [CRM_Core_DAO::VALUE_SEPARATOR, 'String'];
1007 }
1008 }
1009
1010 // ensure that the user has access to these custom groups
1011 $where .= " AND " .
1012 CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
1013 'civicrm_custom_group.'
1014 );
1015
1016 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1017
1018 // final query string
1019 $queryString = $select . $from . $where . $orderBy;
1020
1021 // dummy dao needed
1022 $crmDAO = CRM_Core_DAO::executeQuery($queryString, $params);
1023
1024 // process records
1025 while ($crmDAO->fetch()) {
1026 $groupId = $crmDAO->civicrm_custom_group_id;
1027 $fieldId = $crmDAO->civicrm_custom_field_id;
1028
1029 // create an array for groups if it does not exist
1030 if (!array_key_exists($groupId, $groupTree)) {
1031 $groupTree[$groupId] = [];
1032 $groupTree[$groupId]['id'] = $groupId;
1033
1034 foreach ($tableData['civicrm_custom_group'] as $v) {
1035 $fullField = "civicrm_custom_group_" . $v;
1036
1037 if ($v == 'id' || is_null($crmDAO->$fullField)) {
1038 continue;
1039 }
1040
1041 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1042 }
1043
1044 $groupTree[$groupId]['fields'] = [];
1045 }
1046
1047 // add the fields now (note - the query row will always contain a field)
1048 $groupTree[$groupId]['fields'][$fieldId] = [];
1049 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1050
1051 foreach ($tableData['civicrm_custom_field'] as $v) {
1052 $fullField = "civicrm_custom_field_" . $v;
1053 if ($v == 'id' || is_null($crmDAO->$fullField)) {
1054 continue;
1055 }
1056 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1057 }
1058 }
1059
1060 return $groupTree;
1061 }
1062
1063 /**
1064 * @param $entityType
1065 * @param $path
1066 * @param string $cidToken
1067 *
1068 * @return array
1069 */
1070 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1071 // for Group's
1072 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1073
1074 // get 'Tab' and 'Tab with table' groups
1075 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1076 $customGroupDAO->whereAdd("is_active = 1");
1077
1078 // add whereAdd for entity type
1079 self::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1080
1081 $groups = [];
1082
1083 $permissionClause = CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW, NULL, TRUE);
1084 $customGroupDAO->whereAdd($permissionClause);
1085
1086 // order by weight
1087 $customGroupDAO->orderBy('weight');
1088 $customGroupDAO->find();
1089
1090 // process each group with menu tab
1091 while ($customGroupDAO->fetch()) {
1092 $group = [];
1093 $group['id'] = $customGroupDAO->id;
1094 $group['path'] = $path;
1095 $group['title'] = "$customGroupDAO->title";
1096 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1097 $group['extra'] = ['gid' => $customGroupDAO->id];
1098 $group['table_name'] = $customGroupDAO->table_name;
1099 $group['is_multiple'] = $customGroupDAO->is_multiple;
1100 $group['icon'] = $customGroupDAO->icon;
1101 $groups[] = $group;
1102 }
1103
1104 return $groups;
1105 }
1106
1107 /**
1108 * Get the table name for the entity type
1109 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1110 * tableName is 'civicrm_contact'
1111 *
1112 * @param string $entityType
1113 * What entity are we extending here ?.
1114 *
1115 * @return string
1116 *
1117 *
1118 * @see _apachesolr_civiAttachments_dereference_file_parent
1119 */
1120 public static function getTableNameByEntityName($entityType) {
1121 $tableName = '';
1122 switch ($entityType) {
1123 case 'Contact':
1124 case 'Individual':
1125 case 'Household':
1126 case 'Organization':
1127 $tableName = 'civicrm_contact';
1128 break;
1129
1130 case 'Contribution':
1131 $tableName = 'civicrm_contribution';
1132 break;
1133
1134 case 'Group':
1135 $tableName = 'civicrm_group';
1136 break;
1137
1138 // DRAFTING: Verify if we cannot make it pluggable
1139
1140 case 'Activity':
1141 $tableName = 'civicrm_activity';
1142 break;
1143
1144 case 'Relationship':
1145 $tableName = 'civicrm_relationship';
1146 break;
1147
1148 case 'Membership':
1149 $tableName = 'civicrm_membership';
1150 break;
1151
1152 case 'Participant':
1153 $tableName = 'civicrm_participant';
1154 break;
1155
1156 case 'Event':
1157 $tableName = 'civicrm_event';
1158 break;
1159
1160 case 'Grant':
1161 $tableName = 'civicrm_grant';
1162 break;
1163
1164 // need to add cases for Location, Address
1165 }
1166
1167 return $tableName;
1168 }
1169
1170 /**
1171 * Get a list of custom groups which extend a given entity type.
1172 * If there are custom-groups which only apply to certain subtypes,
1173 * those WILL be included.
1174 *
1175 * @param string $entityType
1176 *
1177 * @return CRM_Core_DAO_CustomGroup
1178 */
1179 public static function getAllCustomGroupsByBaseEntity($entityType) {
1180 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1181 self::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1182 return $customGroupDAO;
1183 }
1184
1185 /**
1186 * Add the whereAdd clause for the DAO depending on the type of entity
1187 * the custom group is extending.
1188 *
1189 * @param object $customGroupDAO
1190 * @param string $entityType
1191 * What entity are we extending here ?.
1192 *
1193 * @param int $entityID
1194 * @param bool $allSubtypes
1195 */
1196 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1197 $addSubtypeClause = FALSE;
1198 // This function isn't really accessible with user data but since the string
1199 // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless
1200 // precaution.
1201 $entityType = CRM_Core_DAO::escapeString($entityType);
1202
1203 switch ($entityType) {
1204 case 'Contact':
1205 // if contact, get all related to contact
1206 $extendList = "'Contact','Individual','Household','Organization'";
1207 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1208 if (!$allSubtypes) {
1209 $addSubtypeClause = TRUE;
1210 }
1211 break;
1212
1213 case 'Individual':
1214 case 'Household':
1215 case 'Organization':
1216 // is I/H/O then get I/H/O and contact
1217 $extendList = "'Contact','$entityType'";
1218 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1219 if (!$allSubtypes) {
1220 $addSubtypeClause = TRUE;
1221 }
1222 break;
1223
1224 default:
1225 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1226 break;
1227 }
1228
1229 if ($addSubtypeClause) {
1230 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact::getContactSubType($entityID) : FALSE;
1231
1232 if (!empty($csType)) {
1233 $subtypeClause = [];
1234 foreach ($csType as $subtype) {
1235 $subtype = CRM_Core_DAO::VALUE_SEPARATOR . $subtype .
1236 CRM_Core_DAO::VALUE_SEPARATOR;
1237 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1238 }
1239 $subtypeClause[] = "extends_entity_column_value IS NULL";
1240 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1241 " )");
1242 }
1243 else {
1244 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1245 }
1246 }
1247 }
1248
1249 /**
1250 * Delete the Custom Group.
1251 *
1252 * @param CRM_Core_BAO_CustomGroup $group
1253 * Custom group object.
1254 * @param bool $force
1255 * whether to force the deletion, even if there are custom fields.
1256 *
1257 * @return bool
1258 * False if field exists for this group, true if group gets deleted.
1259 */
1260 public static function deleteGroup($group, $force = FALSE) {
1261
1262 //check whether this contain any custom fields
1263 $customField = new CRM_Core_DAO_CustomField();
1264 $customField->custom_group_id = $group->id;
1265 $customField->find();
1266
1267 // return early if there are custom fields and we're not
1268 // forcing the delete, otherwise delete the fields one by one
1269 while ($customField->fetch()) {
1270 if (!$force) {
1271 return FALSE;
1272 }
1273 CRM_Core_BAO_CustomField::deleteField($customField);
1274 }
1275
1276 // drop the table associated with this custom group
1277 CRM_Core_BAO_SchemaHandler::dropTable($group->table_name);
1278
1279 //delete custom group
1280 $group->delete();
1281
1282 CRM_Utils_Hook::post('delete', 'CustomGroup', $group->id, $group);
1283
1284 return TRUE;
1285 }
1286
1287 /**
1288 * Set defaults.
1289 *
1290 * @param array $groupTree
1291 * @param array $defaults
1292 * @param bool $viewMode
1293 * @param bool $inactiveNeeded
1294 * @param int $action
1295 */
1296 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action::NONE) {
1297 foreach ($groupTree as $id => $group) {
1298 if (!isset($group['fields'])) {
1299 continue;
1300 }
1301 foreach ($group['fields'] as $field) {
1302 if (isset($field['element_value'])) {
1303 $value = $field['element_value'];
1304 }
1305 elseif (isset($field['default_value']) &&
1306 ($action != CRM_Core_Action::UPDATE ||
1307 // CRM-7548
1308 !array_key_exists('element_value', $field)
1309 )
1310 ) {
1311 $value = $viewMode ? NULL : $field['default_value'];
1312 }
1313 else {
1314 continue;
1315 }
1316
1317 if (empty($field['element_name'])) {
1318 continue;
1319 }
1320
1321 $elementName = $field['element_name'];
1322 $serialize = CRM_Core_BAO_CustomField::isSerialized($field);
1323
1324 if ($serialize) {
1325 if ($field['data_type'] != 'Country' && $field['data_type'] != 'StateProvince') {
1326 $defaults[$elementName] = [];
1327 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($field['id'], $inactiveNeeded);
1328 if ($viewMode) {
1329 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1));
1330 if (isset($value)) {
1331 foreach ($customOption as $customValue => $customLabel) {
1332 if (in_array($customValue, $checkedData)) {
1333 if ($field['html_type'] == 'CheckBox') {
1334 $defaults[$elementName][$customValue] = 1;
1335 }
1336 else {
1337 $defaults[$elementName][$customValue] = $customValue;
1338 }
1339 }
1340 else {
1341 $defaults[$elementName][$customValue] = 0;
1342 }
1343 }
1344 }
1345 }
1346 else {
1347 if (isset($field['customValue']['data'])) {
1348 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($field['customValue']['data'], 1, -1));
1349 foreach ($customOption as $val) {
1350 if (in_array($val['value'], $checkedData)) {
1351 if ($field['html_type'] == 'CheckBox') {
1352 $defaults[$elementName][$val['value']] = 1;
1353 }
1354 else {
1355 $defaults[$elementName][$val['value']] = $val['value'];
1356 }
1357 }
1358 else {
1359 $defaults[$elementName][$val['value']] = 0;
1360 }
1361 }
1362 }
1363 else {
1364 // Values may be "array strings" or actual arrays. Handle both.
1365 if (is_array($value) && count($value)) {
1366 CRM_Utils_Array::formatArrayKeys($value);
1367 $checkedValue = $value;
1368 }
1369 else {
1370 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1));
1371 }
1372 foreach ($customOption as $val) {
1373 if (in_array($val['value'], $checkedValue)) {
1374 if ($field['html_type'] == 'CheckBox') {
1375 $defaults[$elementName][$val['value']] = 1;
1376 }
1377 else {
1378 $defaults[$elementName][$val['value']] = $val['value'];
1379 }
1380 }
1381 }
1382 }
1383 }
1384 }
1385 else {
1386 if (isset($value)) {
1387 // Values may be "array strings" or actual arrays. Handle both.
1388 if (is_array($value) && count($value)) {
1389 CRM_Utils_Array::formatArrayKeys($value);
1390 $checkedValue = $value;
1391 }
1392 else {
1393 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1));
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::format($value, NULL, '%a');
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 ((CRM_Core_Permission::check('view all contacts') ||
1923 CRM_Core_Permission::check('edit all contacts'))
1924 &&
1925 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1926 'ContactReference'
1927 ) {
1928 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = $values['data'] ?? NULL;
1929 }
1930 }
1931 }
1932 else {
1933 $details[$groupID][0]['title'] = $group['title'] ?? NULL;
1934 $details[$groupID][0]['name'] = $group['name'] ?? NULL;
1935 $details[$groupID][0]['help_pre'] = $group['help_pre'] ?? NULL;
1936 $details[$groupID][0]['help_post'] = $group['help_post'] ?? NULL;
1937 $details[$groupID][0]['collapse_display'] = $group['collapse_display'] ?? NULL;
1938 $details[$groupID][0]['collapse_adv_display'] = $group['collapse_adv_display'] ?? NULL;
1939 $details[$groupID][0]['style'] = $group['style'] ?? NULL;
1940 $details[$groupID][0]['fields'][$k] = ['field_title' => CRM_Utils_Array::value('label', $properties)];
1941 }
1942 }
1943 }
1944
1945 if ($returnCount) {
1946 // return a single value count if group id is passed to function
1947 // else return a groupId and count mapped array
1948 if (!empty($gID)) {
1949 return count($details[$gID]);
1950 }
1951 else {
1952 $countValue = [];
1953 foreach ($details as $key => $value) {
1954 $countValue[$key] = count($details[$key]);
1955 }
1956 return $countValue;
1957 }
1958 }
1959 else {
1960 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1961 return $details;
1962 }
1963 }
1964
1965 /**
1966 * Get the custom group titles by custom field ids.
1967 *
1968 * @param array $fieldIds
1969 * Array of custom field ids.
1970 *
1971 * @return array|NULL
1972 * array consisting of groups and fields labels with ids.
1973 */
1974 public static function getGroupTitles($fieldIds) {
1975 if (!is_array($fieldIds) && empty($fieldIds)) {
1976 return NULL;
1977 }
1978
1979 $groupLabels = [];
1980 $fIds = "(" . implode(',', $fieldIds) . ")";
1981
1982 $query = "
1983 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
1984 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
1985 FROM civicrm_custom_group, civicrm_custom_field
1986 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
1987 AND civicrm_custom_field.id IN {$fIds}";
1988
1989 $dao = CRM_Core_DAO::executeQuery($query);
1990 while ($dao->fetch()) {
1991 $groupLabels[$dao->fieldID] = [
1992 'fieldID' => $dao->fieldID,
1993 'fieldLabel' => $dao->fieldLabel,
1994 'groupID' => $dao->groupID,
1995 'groupTitle' => $dao->groupTitle,
1996 ];
1997 }
1998
1999 return $groupLabels;
2000 }
2001
2002 public static function dropAllTables() {
2003 $query = "SELECT table_name FROM civicrm_custom_group";
2004 $dao = CRM_Core_DAO::executeQuery($query);
2005
2006 while ($dao->fetch()) {
2007 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2008 CRM_Core_DAO::executeQuery($query);
2009 }
2010 }
2011
2012 /**
2013 * Check whether custom group is empty or not.
2014 *
2015 * @param int $gID
2016 * Custom group id.
2017 *
2018 * @return bool|NULL
2019 * true if empty otherwise false.
2020 */
2021 public static function isGroupEmpty($gID) {
2022 if (!$gID) {
2023 return NULL;
2024 }
2025
2026 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
2027 $gID,
2028 'table_name'
2029 );
2030
2031 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2032 $value = CRM_Core_DAO::singleValueQuery($query);
2033
2034 if (empty($value)) {
2035 return TRUE;
2036 }
2037
2038 return FALSE;
2039 }
2040
2041 /**
2042 * Get the list of types for objects that a custom group extends to.
2043 *
2044 * @param array $types
2045 * Var which should have the list appended.
2046 *
2047 * @return array
2048 * Array of types.
2049 * @throws \Exception
2050 */
2051 public static function getExtendedObjectTypes(&$types = []) {
2052 static $flag = FALSE, $objTypes = [];
2053
2054 if (!$flag) {
2055 $extendObjs = [];
2056 CRM_Core_OptionValue::getValues(['name' => 'cg_extend_objects'], $extendObjs, 'weight', TRUE);
2057
2058 foreach ($extendObjs as $ovId => $ovValues) {
2059 if ($ovValues['description']) {
2060 // description is expected to be a callback func to subtypes
2061 list($callback, $args) = explode(';', trim($ovValues['description']));
2062
2063 if (empty($args)) {
2064 $args = [];
2065 }
2066
2067 if (!is_array($args)) {
2068 throw new CRM_Core_Exception('Arg is not of type array');
2069 }
2070
2071 list($className) = explode('::', $callback);
2072 require_once str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
2073
2074 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2075 }
2076 }
2077 $flag = TRUE;
2078 }
2079
2080 $types = array_merge($types, $objTypes);
2081 return $objTypes;
2082 }
2083
2084 /**
2085 * @param int $customGroupId
2086 * @param int $entityId
2087 *
2088 * @return bool
2089 */
2090 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2091 // check whether the group is multiple
2092 $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2093 $isMultiple = (bool) $isMultiple;
2094 $hasReachedMax = FALSE;
2095 if ($isMultiple &&
2096 ($maxMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2097 ) {
2098 if (!$maxMultiple) {
2099 $hasReachedMax = FALSE;
2100 }
2101 else {
2102 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2103 // count the number of entries for a entity
2104 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2105 $params = [1 => [$entityId, 'Integer']];
2106 $count = CRM_Core_DAO::singleValueQuery($sql, $params);
2107
2108 if ($count >= $maxMultiple) {
2109 $hasReachedMax = TRUE;
2110 }
2111 }
2112 }
2113 return $hasReachedMax;
2114 }
2115
2116 /**
2117 * @return array
2118 */
2119 public static function getMultipleFieldGroup() {
2120 $multipleGroup = [];
2121 $dao = new CRM_Core_DAO_CustomGroup();
2122 $dao->is_multiple = 1;
2123 $dao->is_active = 1;
2124 $dao->find();
2125 while ($dao->fetch()) {
2126 $multipleGroup[$dao->id] = $dao->title;
2127 }
2128 return $multipleGroup;
2129 }
2130
2131 /**
2132 * Build the metadata tree for the custom group.
2133 *
2134 * @param string $entityType
2135 * @param array $toReturn
2136 * @param array $subTypes
2137 * @param string $queryString
2138 * @param array $params
2139 * @param string $subType
2140 *
2141 * @return array
2142 * @throws \CRM_Core_Exception
2143 */
2144 private static function buildGroupTree($entityType, $toReturn, $subTypes, $queryString, $params, $subType) {
2145 $groupTree = $multipleFieldGroups = [];
2146 $crmDAO = CRM_Core_DAO::executeQuery($queryString, $params);
2147 $customValueTables = [];
2148
2149 // process records
2150 while ($crmDAO->fetch()) {
2151 // get the id's
2152 $groupID = $crmDAO->civicrm_custom_group_id;
2153 $fieldId = $crmDAO->civicrm_custom_field_id;
2154 if ($crmDAO->civicrm_custom_group_is_multiple) {
2155 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name;
2156 }
2157 // create an array for groups if it does not exist
2158 if (!array_key_exists($groupID, $groupTree)) {
2159 $groupTree[$groupID] = [];
2160 $groupTree[$groupID]['id'] = $groupID;
2161
2162 // populate the group information
2163 foreach ($toReturn['custom_group'] as $fieldName) {
2164 $fullFieldName = "civicrm_custom_group_$fieldName";
2165 if ($fieldName == 'id' ||
2166 is_null($crmDAO->$fullFieldName)
2167 ) {
2168 continue;
2169 }
2170 // CRM-5507
2171 // This is an old bit of code - per the CRM number & probably does not work reliably if
2172 // that one contact sub-type exists.
2173 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
2174 $groupTree[$groupID]['subtype'] = self::validateSubTypeByEntity($entityType, $subType);
2175 }
2176 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
2177 }
2178 $groupTree[$groupID]['fields'] = [];
2179
2180 $customValueTables[$crmDAO->civicrm_custom_group_table_name] = [];
2181 }
2182
2183 // add the fields now (note - the query row will always contain a field)
2184 // we only reset this once, since multiple values come is as multiple rows
2185 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
2186 $groupTree[$groupID]['fields'][$fieldId] = [];
2187 }
2188
2189 $customValueTables[$crmDAO->civicrm_custom_group_table_name][$crmDAO->civicrm_custom_field_column_name] = 1;
2190 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
2191 // populate information for a custom field
2192 foreach ($toReturn['custom_field'] as $fieldName) {
2193 $fullFieldName = "civicrm_custom_field_$fieldName";
2194 if ($fieldName == 'id' ||
2195 is_null($crmDAO->$fullFieldName)
2196 ) {
2197 continue;
2198 }
2199 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
2200 }
2201 }
2202
2203 if (!empty($customValueTables)) {
2204 $groupTree['info'] = ['tables' => $customValueTables];
2205 }
2206 return [$multipleFieldGroups, $groupTree];
2207 }
2208
2209 }