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