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