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