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