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