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