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