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