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