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