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