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