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