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