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