Merge pull request #11757 from eileenmcnaughton/manual
[civicrm-core.git] / CRM / Core / BAO / CustomGroup.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
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
1263 switch ($entityType) {
1264 case 'Contact':
1265 // if contact, get all related to contact
1266 $extendList = "'Contact','Individual','Household','Organization'";
1267 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1268 if (!$allSubtypes) {
1269 $addSubtypeClause = TRUE;
1270 }
1271 break;
1272
1273 case 'Individual':
1274 case 'Household':
1275 case 'Organization':
1276 // is I/H/O then get I/H/O and contact
1277 $extendList = "'Contact','$entityType'";
1278 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1279 if (!$allSubtypes) {
1280 $addSubtypeClause = TRUE;
1281 }
1282 break;
1283
1284 case 'Case':
1285 case 'Location':
1286 case 'Address':
1287 case 'Activity':
1288 case 'Contribution':
1289 case 'Membership':
1290 case 'Participant':
1291 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1292 break;
1293 }
1294
1295 if ($addSubtypeClause) {
1296 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact::getContactSubType($entityID) : FALSE;
1297
1298 if (!empty($csType)) {
1299 $subtypeClause = array();
1300 foreach ($csType as $subtype) {
1301 $subtype = CRM_Core_DAO::VALUE_SEPARATOR . $subtype .
1302 CRM_Core_DAO::VALUE_SEPARATOR;
1303 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1304 }
1305 $subtypeClause[] = "extends_entity_column_value IS NULL";
1306 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1307 " )");
1308 }
1309 else {
1310 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1311 }
1312 }
1313 }
1314
1315 /**
1316 * Delete the Custom Group.
1317 *
1318 * @param CRM_Core_BAO_CustomGroup $group
1319 * Custom group object.
1320 * @param bool $force
1321 * whether to force the deletion, even if there are custom fields.
1322 *
1323 * @return bool
1324 * False if field exists for this group, true if group gets deleted.
1325 */
1326 public static function deleteGroup($group, $force = FALSE) {
1327
1328 //check whether this contain any custom fields
1329 $customField = new CRM_Core_DAO_CustomField();
1330 $customField->custom_group_id = $group->id;
1331 $customField->find();
1332
1333 // return early if there are custom fields and we're not
1334 // forcing the delete, otherwise delete the fields one by one
1335 while ($customField->fetch()) {
1336 if (!$force) {
1337 return FALSE;
1338 }
1339 CRM_Core_BAO_CustomField::deleteField($customField);
1340 }
1341
1342 // drop the table associated with this custom group
1343 CRM_Core_BAO_SchemaHandler::dropTable($group->table_name);
1344
1345 //delete custom group
1346 $group->delete();
1347
1348 CRM_Utils_Hook::post('delete', 'CustomGroup', $group->id, $group);
1349
1350 return TRUE;
1351 }
1352
1353 /**
1354 * Set defaults.
1355 *
1356 * @param array $groupTree
1357 * @param array $defaults
1358 * @param bool $viewMode
1359 * @param bool $inactiveNeeded
1360 * @param int $action
1361 */
1362 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action::NONE) {
1363 foreach ($groupTree as $id => $group) {
1364 if (!isset($group['fields'])) {
1365 continue;
1366 }
1367 foreach ($group['fields'] as $field) {
1368 if (CRM_Utils_Array::value('element_value', $field) !== NULL) {
1369 $value = $field['element_value'];
1370 }
1371 elseif (CRM_Utils_Array::value('default_value', $field) !== NULL &&
1372 ($action != CRM_Core_Action::UPDATE ||
1373 // CRM-7548
1374 !array_key_exists('element_value', $field)
1375 )
1376 ) {
1377 $value = $viewMode ? NULL : $field['default_value'];
1378 }
1379 else {
1380 continue;
1381 }
1382
1383 if (empty($field['element_name'])) {
1384 continue;
1385 }
1386
1387 $elementName = $field['element_name'];
1388
1389 switch ($field['html_type']) {
1390 case 'Multi-Select':
1391 case 'AdvMulti-Select':
1392 case 'CheckBox':
1393 $defaults[$elementName] = array();
1394 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($field['id'], $inactiveNeeded);
1395 if ($viewMode) {
1396 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1));
1397 if (isset($value)) {
1398 foreach ($customOption as $customValue => $customLabel) {
1399 if (in_array($customValue, $checkedData)) {
1400 if ($field['html_type'] == 'CheckBox') {
1401 $defaults[$elementName][$customValue] = 1;
1402 }
1403 else {
1404 $defaults[$elementName][$customValue] = $customValue;
1405 }
1406 }
1407 else {
1408 $defaults[$elementName][$customValue] = 0;
1409 }
1410 }
1411 }
1412 }
1413 else {
1414 if (isset($field['customValue']['data'])) {
1415 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($field['customValue']['data'], 1, -1));
1416 foreach ($customOption as $val) {
1417 if (in_array($val['value'], $checkedData)) {
1418 if ($field['html_type'] == 'CheckBox') {
1419 $defaults[$elementName][$val['value']] = 1;
1420 }
1421 else {
1422 $defaults[$elementName][$val['value']] = $val['value'];
1423 }
1424 }
1425 else {
1426 $defaults[$elementName][$val['value']] = 0;
1427 }
1428 }
1429 }
1430 else {
1431 if (is_array($value) && count($value)) {
1432 CRM_Utils_Array::formatArrayKeys($value);
1433 $checkedValue = $value;
1434 }
1435 else {
1436 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1));
1437 }
1438 foreach ($customOption as $val) {
1439 if (in_array($val['value'], $checkedValue)) {
1440 if ($field['html_type'] == 'CheckBox') {
1441 $defaults[$elementName][$val['value']] = 1;
1442 }
1443 else {
1444 $defaults[$elementName][$val['value']] = $val['value'];
1445 }
1446 }
1447 }
1448 }
1449 }
1450 break;
1451
1452 case 'Multi-Select Country':
1453 case 'Multi-Select State/Province':
1454 if (isset($value)) {
1455 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1456 foreach ($checkedValue as $val) {
1457 if ($val) {
1458 $defaults[$elementName][$val] = $val;
1459 }
1460 }
1461 }
1462 break;
1463
1464 case 'Select Country':
1465 if ($value) {
1466 $defaults[$elementName] = $value;
1467 }
1468 else {
1469 $config = CRM_Core_Config::singleton();
1470 $defaults[$elementName] = $config->defaultContactCountry;
1471 }
1472 break;
1473
1474 default:
1475 if ($field['data_type'] == "Float") {
1476 $defaults[$elementName] = (float) $value;
1477 }
1478 elseif ($field['data_type'] == 'Money' &&
1479 $field['html_type'] == 'Text'
1480 ) {
1481 $defaults[$elementName] = CRM_Utils_Money::format($value, NULL, '%a');
1482 }
1483 else {
1484 $defaults[$elementName] = $value;
1485 }
1486 }
1487 }
1488 }
1489 }
1490
1491 /**
1492 * PostProcess function.
1493 *
1494 * @param array $groupTree
1495 * @param array $params
1496 * @param bool $skipFile
1497 */
1498 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1499 // Get the Custom form values and groupTree
1500 // first reset all checkbox and radio data
1501 foreach ($groupTree as $groupID => $group) {
1502 if ($groupID === 'info') {
1503 continue;
1504 }
1505 foreach ($group['fields'] as $field) {
1506 $fieldId = $field['id'];
1507
1508 //added Multi-Select option in the below if-statement
1509 if ($field['html_type'] == 'CheckBox' ||
1510 $field['html_type'] == 'Radio' ||
1511 $field['html_type'] == 'AdvMulti-Select' ||
1512 $field['html_type'] == 'Multi-Select'
1513 ) {
1514 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1515 }
1516
1517 $v = NULL;
1518 foreach ($params as $key => $val) {
1519 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1520 $match[1] == $field['id']
1521 ) {
1522 $v = $val;
1523 }
1524 }
1525
1526 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1527 // field exists in db so populate value from "form".
1528 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1529 }
1530
1531 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1532
1533 //added for CheckBox
1534
1535 case 'CheckBox':
1536 if (!empty($v)) {
1537 $customValue = array_keys($v);
1538 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO::VALUE_SEPARATOR
1539 . implode(CRM_Core_DAO::VALUE_SEPARATOR, $customValue)
1540 . CRM_Core_DAO::VALUE_SEPARATOR;
1541 }
1542 else {
1543 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1544 }
1545 break;
1546
1547 //added for Advanced Multi-Select
1548
1549 case 'AdvMulti-Select':
1550 //added for Multi-Select
1551 case 'Multi-Select':
1552 if (!empty($v)) {
1553 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO::VALUE_SEPARATOR
1554 . implode(CRM_Core_DAO::VALUE_SEPARATOR, $v)
1555 . CRM_Core_DAO::VALUE_SEPARATOR;
1556 }
1557 else {
1558 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1559 }
1560 break;
1561
1562 case 'Select Date':
1563 $date = CRM_Utils_Date::processDate($v);
1564 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1565 break;
1566
1567 case 'File':
1568 if ($skipFile) {
1569 continue;
1570 }
1571
1572 //store the file in d/b
1573 $entityId = explode('=', $groupTree['info']['where'][0]);
1574 $fileParams = array('upload_date' => date('YmdHis'));
1575
1576 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1577 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1578 }
1579 if (!empty($v)) {
1580 $fileParams['uri'] = $v['name'];
1581 $fileParams['mime_type'] = $v['type'];
1582 CRM_Core_BAO_File::filePostProcess($v['name'],
1583 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1584 $groupTree[$groupID]['table_name'],
1585 trim($entityId[1]),
1586 FALSE,
1587 TRUE,
1588 $fileParams,
1589 'custom_' . $fieldId,
1590 $v['type']
1591 );
1592 }
1593 $defaults = array();
1594 $paramsFile = array(
1595 'entity_table' => $groupTree[$groupID]['table_name'],
1596 'entity_id' => $entityId[1],
1597 );
1598
1599 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_EntityFile',
1600 $paramsFile,
1601 $defaults
1602 );
1603
1604 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1605 break;
1606
1607 default:
1608 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1609 break;
1610 }
1611 }
1612 }
1613 }
1614
1615 /**
1616 * Generic function to build all the form elements for a specific group tree.
1617 *
1618 * @param CRM_Core_Form $form
1619 * The form object.
1620 * @param array $groupTree
1621 * The group tree object.
1622 * @param bool $inactiveNeeded
1623 * Return inactive custom groups.
1624 * @param string $prefix
1625 * Prefix for custom grouptree assigned to template.
1626 */
1627 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1628 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1629
1630 foreach ($groupTree as $id => $group) {
1631 CRM_Core_ShowHideBlocks::links($form, $group['title'], '', '');
1632 foreach ($group['fields'] as $field) {
1633 $required = CRM_Utils_Array::value('is_required', $field);
1634 //fix for CRM-1620
1635 if ($field['data_type'] == 'File') {
1636 if (!empty($field['element_value']['data'])) {
1637 $required = 0;
1638 }
1639 }
1640
1641 $fieldId = $field['id'];
1642 $elementName = $field['element_name'];
1643 CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, $required);
1644 }
1645 }
1646 }
1647
1648 /**
1649 * Extract the get params from the url, validate and store it in session.
1650 *
1651 * @param CRM_Core_Form $form
1652 * The form object.
1653 * @param string $type
1654 * The type of custom group we are using.
1655 *
1656 * @return array
1657 */
1658 public static function extractGetParams(&$form, $type) {
1659 if (empty($_GET)) {
1660 return array();
1661 }
1662
1663 $groupTree = CRM_Core_BAO_CustomGroup::getTree($type);
1664 $customValue = array();
1665 $htmlType = array(
1666 'CheckBox',
1667 'Multi-Select',
1668 'AdvMulti-Select',
1669 'Select',
1670 'Radio',
1671 );
1672
1673 foreach ($groupTree as $group) {
1674 if (!isset($group['fields'])) {
1675 continue;
1676 }
1677 foreach ($group['fields'] as $key => $field) {
1678 $fieldName = 'custom_' . $key;
1679 $value = CRM_Utils_Request::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1680
1681 if ($value) {
1682 $valid = FALSE;
1683 if (!in_array($field['html_type'], $htmlType) ||
1684 $field['data_type'] == 'Boolean'
1685 ) {
1686 $valid = CRM_Core_BAO_CustomValue::typecheck($field['data_type'], $value);
1687 }
1688 if ($field['html_type'] == 'CheckBox' ||
1689 $field['html_type'] == 'AdvMulti-Select' ||
1690 $field['html_type'] == 'Multi-Select'
1691 ) {
1692 $value = str_replace("|", ",", $value);
1693 $mulValues = explode(',', $value);
1694 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, TRUE);
1695 $val = array();
1696 foreach ($mulValues as $v1) {
1697 foreach ($customOption as $coID => $coValue) {
1698 if (strtolower(trim($coValue['label'])) ==
1699 strtolower(trim($v1))
1700 ) {
1701 $val[$coValue['value']] = 1;
1702 }
1703 }
1704 }
1705 if (!empty($val)) {
1706 $value = $val;
1707 $valid = TRUE;
1708 }
1709 else {
1710 $value = NULL;
1711 }
1712 }
1713 elseif ($field['html_type'] == 'Select' ||
1714 ($field['html_type'] == 'Radio' &&
1715 $field['data_type'] != 'Boolean'
1716 )
1717 ) {
1718 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, TRUE);
1719 foreach ($customOption as $customID => $coValue) {
1720 if (strtolower(trim($coValue['label'])) ==
1721 strtolower(trim($value))
1722 ) {
1723 $value = $coValue['value'];
1724 $valid = TRUE;
1725 }
1726 }
1727 }
1728 elseif ($field['data_type'] == 'Date') {
1729 if (!empty($value)) {
1730 $time = NULL;
1731 if (!empty($field['time_format'])) {
1732 $time = CRM_Utils_Request::retrieve($fieldName .
1733 '_time', 'String', $form, FALSE, NULL, 'GET');
1734 }
1735 list($value, $time) = CRM_Utils_Date::setDateDefaults($value .
1736 ' ' . $time);
1737 if (!empty($field['time_format'])) {
1738 $customValue[$fieldName . '_time'] = $time;
1739 }
1740 }
1741 $valid = TRUE;
1742 }
1743
1744 if ($valid) {
1745 $customValue[$fieldName] = $value;
1746 }
1747 }
1748 }
1749 }
1750
1751 return $customValue;
1752 }
1753
1754 /**
1755 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1756 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1757 *
1758 * @param int $customFieldId
1759 * Custom field id.
1760 * @param array $removeCustomFieldTypes
1761 * Remove custom fields of a type eg: array("Individual") ;.
1762 *
1763 * @return bool
1764 * false if it matches else true
1765 */
1766 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1767 $query = "SELECT cg.extends as extends
1768 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1769 WHERE cg.id = cf.custom_group_id
1770 AND cf.id =" .
1771 CRM_Utils_Type::escape($customFieldId, 'Integer');
1772
1773 $extends = CRM_Core_DAO::singleValueQuery($query);
1774
1775 if (in_array($extends, $removeCustomFieldTypes)) {
1776 return FALSE;
1777 }
1778 return TRUE;
1779 }
1780
1781 /**
1782 * @param $table
1783 *
1784 * @return string
1785 * @throws Exception
1786 */
1787 public static function mapTableName($table) {
1788 switch ($table) {
1789 case 'Contact':
1790 case 'Individual':
1791 case 'Household':
1792 case 'Organization':
1793 return 'civicrm_contact';
1794
1795 case 'Activity':
1796 return 'civicrm_activity';
1797
1798 case 'Group':
1799 return 'civicrm_group';
1800
1801 case 'Contribution':
1802 return 'civicrm_contribution';
1803
1804 case 'ContributionRecur':
1805 return 'civicrm_contribution_recur';
1806
1807 case 'Relationship':
1808 return 'civicrm_relationship';
1809
1810 case 'Event':
1811 return 'civicrm_event';
1812
1813 case 'Membership':
1814 return 'civicrm_membership';
1815
1816 case 'Participant':
1817 case 'ParticipantRole':
1818 case 'ParticipantEventName':
1819 case 'ParticipantEventType':
1820 return 'civicrm_participant';
1821
1822 case 'Grant':
1823 return 'civicrm_grant';
1824
1825 case 'Pledge':
1826 return 'civicrm_pledge';
1827
1828 case 'Address':
1829 return 'civicrm_address';
1830
1831 case 'Campaign':
1832 return 'civicrm_campaign';
1833
1834 default:
1835 $query = "
1836 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1837 $qParams = array(1 => array($table, 'String'));
1838 $result = CRM_Core_DAO::singleValueQuery($query, $qParams);
1839
1840 if ($result) {
1841 return 'civicrm_contact';
1842 }
1843 else {
1844 $extendObjs = CRM_Core_OptionGroup::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1845 if (array_key_exists($table, $extendObjs)) {
1846 return $extendObjs[$table];
1847 }
1848 CRM_Core_Error::fatal();
1849 }
1850 }
1851 }
1852
1853 /**
1854 * @param $group
1855 */
1856 public static function createTable($group) {
1857 $params = array(
1858 'name' => $group->table_name,
1859 'is_multiple' => $group->is_multiple ? 1 : 0,
1860 'extends_name' => self::mapTableName($group->extends),
1861 );
1862
1863 $tableParams = CRM_Core_BAO_CustomField::defaultCustomTableSchema($params);
1864
1865 CRM_Core_BAO_SchemaHandler::createTable($tableParams);
1866 }
1867
1868 /**
1869 * Function returns formatted groupTree, sothat form can be easily build in template
1870 *
1871 * @param array $groupTree
1872 * @param int $groupCount
1873 * Group count by default 1, but can varry for multiple value custom data.
1874 * @param object $form
1875 *
1876 * @return array
1877 */
1878 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NULL) {
1879 $formattedGroupTree = array();
1880 $uploadNames = $formValues = array();
1881
1882 // retrieve qf key from url
1883 $qfKey = CRM_Utils_Request::retrieve('qf', 'String');
1884
1885 // fetch submitted custom field values later use to set as a default values
1886 if ($qfKey) {
1887 $submittedValues = CRM_Core_BAO_Cache::getItem('custom data', $qfKey);
1888 }
1889
1890 foreach ($groupTree as $key => $value) {
1891 if ($key === 'info') {
1892 continue;
1893 }
1894
1895 // add group information
1896 $formattedGroupTree[$key]['name'] = CRM_Utils_Array::value('name', $value);
1897 $formattedGroupTree[$key]['title'] = CRM_Utils_Array::value('title', $value);
1898 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array::value('help_pre', $value);
1899 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array::value('help_post', $value);
1900 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array::value('collapse_display', $value);
1901 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array::value('collapse_adv_display', $value);
1902 $formattedGroupTree[$key]['style'] = CRM_Utils_Array::value('style', $value);
1903
1904 // this params needed of bulding multiple values
1905 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array::value('is_multiple', $value);
1906 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array::value('extends', $value);
1907 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array::value('extends_entity_column_id', $value);
1908 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array::value('extends_entity_column_value', $value);
1909 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array::value('subtype', $value);
1910 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array::value('max_multiple', $value);
1911
1912 // add field information
1913 foreach ($value['fields'] as $k => $properties) {
1914 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1915 if (isset($properties['customValue']) &&
1916 !CRM_Utils_System::isNull($properties['customValue']) &&
1917 !isset($properties['element_value'])
1918 ) {
1919 if (isset($properties['customValue'][$groupCount])) {
1920 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1921 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1922 if ($properties['data_type'] == 'File') {
1923 $properties['element_value'] = $properties['customValue'][$groupCount];
1924 $uploadNames[] = $properties['element_name'];
1925 }
1926 else {
1927 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1928 }
1929 }
1930 }
1931 if ($value = CRM_Utils_Request::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1932 $formValues[$properties['element_name']] = $value;
1933 }
1934 elseif (isset($submittedValues[$properties['element_name']])) {
1935 $properties['element_value'] = $submittedValues[$properties['element_name']];
1936 }
1937 unset($properties['customValue']);
1938 $formattedGroupTree[$key]['fields'][$k] = $properties;
1939 }
1940 }
1941
1942 if ($form) {
1943 if (count($formValues)) {
1944 $qf = $form->get('qfKey');
1945 $form->assign('qfKey', $qf);
1946 CRM_Core_BAO_Cache::setItem($formValues, 'custom data', $qf);
1947 }
1948
1949 // hack for field type File
1950 $formUploadNames = $form->get('uploadNames');
1951 if (is_array($formUploadNames)) {
1952 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1953 }
1954
1955 $form->set('uploadNames', $uploadNames);
1956 }
1957
1958 return $formattedGroupTree;
1959 }
1960
1961 /**
1962 * Build custom data view.
1963 *
1964 * @param CRM_Core_Form $form
1965 * Page object.
1966 * @param array $groupTree
1967 * @param bool $returnCount
1968 * True if customValue count needs to be returned.
1969 * @param int $gID
1970 * @param null $prefix
1971 * @param int $customValueId
1972 * @param int $entityId
1973 *
1974 * @return array|int
1975 */
1976 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
1977 $details = array();
1978 foreach ($groupTree as $key => $group) {
1979 if ($key === 'info') {
1980 continue;
1981 }
1982
1983 foreach ($group['fields'] as $k => $properties) {
1984 $groupID = $group['id'];
1985 if (!empty($properties['customValue'])) {
1986 foreach ($properties['customValue'] as $values) {
1987 if (!empty($customValueId) && $customValueId != $values['id']) {
1988 continue;
1989 }
1990 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array::value('title', $group);
1991 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array::value('name', $group);
1992 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array::value('help_pre', $group);
1993 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array::value('help_post', $group);
1994 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array::value('collapse_display', $group);
1995 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array::value('collapse_adv_display', $group);
1996 $details[$groupID][$values['id']]['style'] = CRM_Utils_Array::value('style', $group);
1997 $details[$groupID][$values['id']]['fields'][$k] = array(
1998 'field_title' => CRM_Utils_Array::value('label', $properties),
1999 'field_type' => CRM_Utils_Array::value('html_type', $properties),
2000 'field_data_type' => CRM_Utils_Array::value('data_type', $properties),
2001 'field_value' => CRM_Core_BAO_CustomField::displayValue($values['data'], $properties['id'], $entityId),
2002 'options_per_line' => CRM_Utils_Array::value('options_per_line', $properties),
2003 );
2004 // editable = whether this set contains any non-read-only fields
2005 if (!isset($details[$groupID][$values['id']]['editable'])) {
2006 $details[$groupID][$values['id']]['editable'] = FALSE;
2007 }
2008 if (empty($properties['is_view'])) {
2009 $details[$groupID][$values['id']]['editable'] = TRUE;
2010 }
2011 // also return contact reference contact id if user has view all or edit all contacts perm
2012 if ((CRM_Core_Permission::check('view all contacts') ||
2013 CRM_Core_Permission::check('edit all contacts'))
2014 &&
2015 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
2016 'ContactReference'
2017 ) {
2018 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array::value('data', $values);
2019 }
2020 }
2021 }
2022 else {
2023 $details[$groupID][0]['title'] = CRM_Utils_Array::value('title', $group);
2024 $details[$groupID][0]['name'] = CRM_Utils_Array::value('name', $group);
2025 $details[$groupID][0]['help_pre'] = CRM_Utils_Array::value('help_pre', $group);
2026 $details[$groupID][0]['help_post'] = CRM_Utils_Array::value('help_post', $group);
2027 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array::value('collapse_display', $group);
2028 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array::value('collapse_adv_display', $group);
2029 $details[$groupID][0]['style'] = CRM_Utils_Array::value('style', $group);
2030 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array::value('label', $properties));
2031 }
2032 }
2033 }
2034
2035 if ($returnCount) {
2036 //return a single value count if group id is passed to function
2037 //else return a groupId and count mapped array
2038 if (!empty($gID)) {
2039 return count($details[$gID]);
2040 }
2041 else {
2042 $countValue = array();
2043 foreach ($details as $key => $value) {
2044 $countValue[$key] = count($details[$key]);
2045 }
2046 return $countValue;
2047 }
2048 }
2049 else {
2050 $form->assign_by_ref("{$prefix}viewCustomData", $details);
2051 return $details;
2052 }
2053 }
2054
2055 /**
2056 * Get the custom group titles by custom field ids.
2057 *
2058 * @param array $fieldIds
2059 * Array of custom field ids.
2060 *
2061 * @return array|NULL
2062 * array consisting of groups and fields labels with ids.
2063 */
2064 public static function getGroupTitles($fieldIds) {
2065 if (!is_array($fieldIds) && empty($fieldIds)) {
2066 return NULL;
2067 }
2068
2069 $groupLabels = array();
2070 $fIds = "(" . implode(',', $fieldIds) . ")";
2071
2072 $query = "
2073 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2074 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2075 FROM civicrm_custom_group, civicrm_custom_field
2076 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2077 AND civicrm_custom_field.id IN {$fIds}";
2078
2079 $dao = CRM_Core_DAO::executeQuery($query);
2080 while ($dao->fetch()) {
2081 $groupLabels[$dao->fieldID] = array(
2082 'fieldID' => $dao->fieldID,
2083 'fieldLabel' => $dao->fieldLabel,
2084 'groupID' => $dao->groupID,
2085 'groupTitle' => $dao->groupTitle,
2086 );
2087 }
2088
2089 return $groupLabels;
2090 }
2091
2092 public static function dropAllTables() {
2093 $query = "SELECT table_name FROM civicrm_custom_group";
2094 $dao = CRM_Core_DAO::executeQuery($query);
2095
2096 while ($dao->fetch()) {
2097 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2098 CRM_Core_DAO::executeQuery($query);
2099 }
2100 }
2101
2102 /**
2103 * Check whether custom group is empty or not.
2104 *
2105 * @param int $gID
2106 * Custom group id.
2107 *
2108 * @return bool|NULL
2109 * true if empty otherwise false.
2110 */
2111 public static function isGroupEmpty($gID) {
2112 if (!$gID) {
2113 return NULL;
2114 }
2115
2116 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
2117 $gID,
2118 'table_name'
2119 );
2120
2121 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2122 $value = CRM_Core_DAO::singleValueQuery($query);
2123
2124 if (empty($value)) {
2125 return TRUE;
2126 }
2127
2128 return FALSE;
2129 }
2130
2131 /**
2132 * Get the list of types for objects that a custom group extends to.
2133 *
2134 * @param array $types
2135 * Var which should have the list appended.
2136 *
2137 * @return array
2138 * Array of types.
2139 */
2140 public static function getExtendedObjectTypes(&$types = array()) {
2141 static $flag = FALSE, $objTypes = array();
2142
2143 if (!$flag) {
2144 $extendObjs = array();
2145 CRM_Core_OptionValue::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2146
2147 foreach ($extendObjs as $ovId => $ovValues) {
2148 if ($ovValues['description']) {
2149 // description is expected to be a callback func to subtypes
2150 list($callback, $args) = explode(';', trim($ovValues['description']));
2151
2152 if (empty($args)) {
2153 $args = array();
2154 }
2155
2156 if (!is_array($args)) {
2157 CRM_Core_Error::fatal('Arg is not of type array');
2158 }
2159
2160 list($className) = explode('::', $callback);
2161 require_once str_replace('_', DIRECTORY_SEPARATOR, $className) .
2162 '.php';
2163
2164 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2165 }
2166 }
2167 $flag = TRUE;
2168 }
2169
2170 $types = array_merge($types, $objTypes);
2171 return $objTypes;
2172 }
2173
2174 /**
2175 * @param int $customGroupId
2176 * @param int $entityId
2177 *
2178 * @return bool
2179 */
2180 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2181 //check whether the group is multiple
2182 $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2183 $isMultiple = ($isMultiple) ? TRUE : FALSE;
2184 $hasReachedMax = FALSE;
2185 if ($isMultiple &&
2186 ($maxMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2187 ) {
2188 if (!$maxMultiple) {
2189 $hasReachedMax = FALSE;
2190 }
2191 else {
2192 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2193 //count the number of entries for a entity
2194 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2195 $params = array(1 => array($entityId, 'Integer'));
2196 $count = CRM_Core_DAO::singleValueQuery($sql, $params);
2197
2198 if ($count >= $maxMultiple) {
2199 $hasReachedMax = TRUE;
2200 }
2201 }
2202 }
2203 return $hasReachedMax;
2204 }
2205
2206 /**
2207 * @return array
2208 */
2209 public static function getMultipleFieldGroup() {
2210 $multipleGroup = array();
2211 $dao = new CRM_Core_DAO_CustomGroup();
2212 $dao->is_multiple = 1;
2213 $dao->is_active = 1;
2214 $dao->find();
2215 while ($dao->fetch()) {
2216 $multipleGroup[$dao->id] = $dao->title;
2217 }
2218 return $multipleGroup;
2219 }
2220
2221 }