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