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