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