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