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