Merge pull request #3619 from totten/master-14871
[civicrm-core.git] / CRM / Core / BAO / CustomGroup.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * Business object for managing custom data groups
38 *
39 */
40 class CRM_Core_BAO_CustomGroup extends CRM_Core_DAO_CustomGroup {
41
42 /**
43 * class constructor
44 */
45 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 (!empty($params['extends_entity_column_value'])) {
92 $extendsChildType = $params['extends_entity_column_value'];
93 }
94 if (!CRM_Utils_System::isNull($extendsChildType)) {
95 $extendsChildType = implode(CRM_Core_DAO::VALUE_SEPARATOR, $extendsChildType);
96 if (CRM_Utils_Array::value(0, $params['extends']) == 'Relationship') {
97 $extendsChildType = str_replace(array('_a_b', '_b_a'), array('', ''), $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 ((!empty($params['is_multiple']) || $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
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 }
161 }
162
163 // enclose the below in a transaction
164 $transaction = new CRM_Core_Transaction();
165
166 $group->save();
167 if (!isset($params['id'])) {
168 if (!isset($params['table_name'])) {
169 $munged_title = strtolower(CRM_Utils_String::munge($group->title, '_', 42));
170 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
171 }
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 * @return bool
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 /**
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.
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
298 * @param object $form - not used but required
299 * @param null $entityID
300 * @param null $groupID
301 * @param string $subType
302 * @param string $subName
303 * @param boolean $fromCache
304 *
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
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
319 *
320 * @access public
321 *
322 * @static
323 */
324 public static function &getTree(
325 $entityType,
326 &$form,
327 $entityID = NULL,
328 $groupID = NULL,
329 $subType = NULL,
330 $subName = NULL,
331 $fromCache = TRUE,
332 $onlySubType = NULL
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',
363 'in_selector'
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 = "
394 FROM civicrm_custom_group
395 LEFT 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 }
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 }
430 }
431 else {
432 $subType = CRM_Core_DAO::VALUE_SEPARATOR . trim($subType, CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
433
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 }
441 }
442
443 $strWhere = "
444 WHERE 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 = "
455 WHERE 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 = "
479 ORDER 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);
497 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
498 $cache = CRM_Utils_Cache::singleton();
499 $tablesWithEntityData = array();
500 if ($fromCache) {
501 $groupTree = $cache->get($cacheKey);
502 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
503 }
504
505 if (empty($groupTree)) {
506 $groupTree = $multipleFieldGroups =array();
507 $crmDAO = CRM_Core_DAO::executeQuery($queryString, $params);
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;
515 if($crmDAO->civicrm_custom_group_is_multiple){
516 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name;
517 }
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);
567 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
568 }
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();
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
575 // add info to groupTree
576
577 if (isset($groupTree['info']) && !empty($groupTree['info']) && !empty($groupTree['info']['tables'])) {
578 $select = $from = $where = array();
579 $groupTree['info']['where'] = NULL;
580
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");
585 foreach ($fields as $column => $dontCare) {
586 $select[] = "{$table}.{$column} as {$table}_{$column}";
587 }
588 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
589 if ($entityID) {
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
599 }
600 }
601 if ($entityID && !empty($singleFieldTables)) {
602 self::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
603 }
604 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
605 if(!empty($multipleFieldTablesWithEntityData)){
606 self::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
607 }
608
609 }
610 return $groupTree;
611 }
612
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 *
620 * @param bool $getCount
621 *
622 * @return boolean does this entity have data in this custom table
623 */
624 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE){
625 $query = "
626 SELECT count(id)
627 FROM $table
628 WHERE entity_id = $entityID
629 ";
630 $recordExists = CRM_Core_DAO::singleValueQuery($query);
631 if ($getCount) {
632 return $recordExists;
633 }
634 return $recordExists ? TRUE : FALSE;
635 }
636
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 }
655
656 $query = "
657 SELECT $select
658 FROM $fromSQL
659 WHERE first.entity_id = $entityID
660 ";
661 self::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
662 }
663
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 ";
682 self::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
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,
762 ),
763 ts('more'),
764 FALSE,
765 'file.manage.delete',
766 'File',
767 $fileDAO->id
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 );
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 }
793 }
794 }
795 }
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 );
808 }
809
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 }
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 *
841 * @param int $groupId - group id whose details are needed
842 * @param boolean $searchable - is this field searchable
843 * @param array $extends - which table does it extend if any
844 *
845 * @param null $inSelector
846 *
847 * @return array $groupTree - array consisting of all group and field details
848 *
849 * @access public
850 *
851 * @static
852 */
853 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
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',
885 'in_selector',
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',
899 'is_multiple',
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
927 if ($inSelector) {
928 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
929 }
930
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
998 /**
999 * @param $entityType
1000 * @param $path
1001 * @param string $cidToken
1002 *
1003 * @return array
1004 */
1005 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1006 // for Group's
1007 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1008
1009 // get 'Tab' and 'Tab with table' groups
1010 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
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 public
1050 * @static
1051 *
1052 * @see _apachesolr_civiAttachments_dereference_file_parent
1053 */
1054 public static function getTableNameByEntityName($entityType) {
1055 $tableName = '';
1056 switch ($entityType) {
1057 case 'Contact':
1058 case 'Individual':
1059 case 'Household':
1060 case 'Organization':
1061 $tableName = 'civicrm_contact';
1062 break;
1063
1064 case 'Contribution':
1065 $tableName = 'civicrm_contribution';
1066 break;
1067
1068 case 'Group':
1069 $tableName = 'civicrm_group';
1070 break;
1071 // DRAFTING: Verify if we cannot make it pluggable
1072
1073 case 'Activity':
1074 $tableName = 'civicrm_activity';
1075 break;
1076
1077 case 'Relationship':
1078 $tableName = 'civicrm_relationship';
1079 break;
1080
1081 case 'Membership':
1082 $tableName = 'civicrm_membership';
1083 break;
1084
1085 case 'Participant':
1086 $tableName = 'civicrm_participant';
1087 break;
1088
1089 case 'Event':
1090 $tableName = 'civicrm_event';
1091 break;
1092
1093 case 'Grant':
1094 $tableName = 'civicrm_grant';
1095 break;
1096 // need to add cases for Location, Address
1097 }
1098
1099 return $tableName;
1100 }
1101
1102 /**
1103 * Get a list of custom groups which extend a given entity type.
1104 * If there are custom-groups which only apply to certain subtypes,
1105 * those WILL be included.
1106 *
1107 * @param $entityType string
1108 * @return CRM_Core_DAO_CustomGroup
1109 */
1110 static function getAllCustomGroupsByBaseEntity($entityType) {
1111 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1112 self::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1113 return $customGroupDAO;
1114 }
1115
1116 /**
1117 * Add the whereAdd clause for the DAO depending on the type of entity
1118 * the custom group is extending.
1119 *
1120 * @param $customGroupDAO
1121 * @param string $entityType - what entity are we extending here ?
1122 *
1123 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
1124 * @param bool $allSubtypes
1125 *
1126 * @return void
1127 *
1128 * @access private
1129 * @static
1130 */
1131 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1132 $addSubtypeClause = FALSE;
1133
1134 switch ($entityType) {
1135 case 'Contact':
1136 // if contact, get all related to contact
1137 $extendList = "'Contact','Individual','Household','Organization'";
1138 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1139 if (!$allSubtypes) {
1140 $addSubtypeClause = TRUE;
1141 }
1142 break;
1143
1144 case 'Individual':
1145 case 'Household':
1146 case 'Organization':
1147 // is I/H/O then get I/H/O and contact
1148 $extendList = "'Contact','$entityType'";
1149 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1150 if (!$allSubtypes) {
1151 $addSubtypeClause = TRUE;
1152 }
1153 break;
1154
1155 case 'Case':
1156 case 'Location':
1157 case 'Address':
1158 case 'Activity':
1159 case 'Contribution':
1160 case 'Membership':
1161 case 'Participant':
1162 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1163 break;
1164 }
1165
1166 if ($addSubtypeClause) {
1167 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact::getContactSubType($entityID) : FALSE;
1168
1169 if (!empty($csType)) {
1170 $subtypeClause = array();
1171 foreach ($csType as $subtype) {
1172 $subtype = CRM_Core_DAO::VALUE_SEPARATOR . $subtype . CRM_Core_DAO::VALUE_SEPARATOR;
1173 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1174 }
1175 $subtypeClause[] = "extends_entity_column_value IS NULL";
1176 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) . " )");
1177 }
1178 else {
1179 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1180 }
1181 }
1182 }
1183
1184 /**
1185 * Delete the Custom Group.
1186 *
1187 * @param $group object the DAO custom group object
1188 * @param $force boolean whether to force the deletion, even if there are custom fields
1189 *
1190 * @return boolean false if field exists for this group, true if group gets deleted.
1191 *
1192 * @access public
1193 * @static
1194 *
1195 */
1196 public static function deleteGroup($group, $force = FALSE) {
1197
1198 //check wheter this contain any custom fields
1199 $customField = new CRM_Core_DAO_CustomField();
1200 $customField->custom_group_id = $group->id;
1201 $customField->find();
1202
1203 // return early if there are custom fields and we're not
1204 // forcing the delete, otherwise delete the fields one by one
1205 while ($customField->fetch()) {
1206 if (!$force) {
1207 return FALSE;
1208 }
1209 CRM_Core_BAO_CustomField::deleteField($customField);
1210 }
1211
1212 // drop the table associated with this custom group
1213 CRM_Core_BAO_SchemaHandler::dropTable($group->table_name);
1214
1215 //delete custom group
1216 $group->delete();
1217
1218 CRM_Utils_Hook::post('delete', 'CustomGroup', $group->id, $group);
1219
1220 return TRUE;
1221 }
1222
1223 /**
1224 * @param $groupTree
1225 * @param $defaults
1226 * @param bool $viewMode
1227 * @param bool $inactiveNeeded
1228 * @param int $action
1229 */
1230 static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action::NONE) {
1231 foreach ($groupTree as $id => $group) {
1232 if (!isset($group['fields'])) {
1233 continue;
1234 }
1235 $groupId = CRM_Utils_Array::value('id', $group);
1236 foreach ($group['fields'] as $field) {
1237 if (CRM_Utils_Array::value('element_value', $field) !== NULL) {
1238 $value = $field['element_value'];
1239 }
1240 elseif (CRM_Utils_Array::value('default_value', $field) !== NULL &&
1241 ($action != CRM_Core_Action::UPDATE ||
1242 // CRM-7548
1243 !array_key_exists('element_value', $field)
1244 )
1245 ) {
1246 $value = $viewMode ? NULL : $field['default_value'];
1247 }
1248 else {
1249 continue;
1250 }
1251
1252 $fieldId = $field['id'];
1253 if (!empty($field['element_name'])) {
1254 $elementName = $field['element_name'];
1255 }
1256 switch ($field['html_type']) {
1257 case 'Multi-Select':
1258 case 'AdvMulti-Select':
1259 case 'CheckBox':
1260 $defaults[$elementName] = array();
1261 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($field['id'], $inactiveNeeded);
1262 if ($viewMode) {
1263 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1));
1264 if (isset($value)) {
1265 foreach ($customOption as $customValue => $customLabel) {
1266 if (in_array($customValue, $checkedData)) {
1267 if ($field['html_type'] == 'CheckBox') {
1268 $defaults[$elementName][$customValue] = 1;
1269 }
1270 else {
1271 $defaults[$elementName][$customValue] = $customValue;
1272 }
1273 }
1274 else {
1275 $defaults[$elementName][$customValue] = 0;
1276 }
1277 }
1278 }
1279 }
1280 else {
1281 if (isset($field['customValue']['data'])) {
1282 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($field['customValue']['data'], 1, -1));
1283 foreach ($customOption as $val) {
1284 if (in_array($val['value'], $checkedData)) {
1285 if ($field['html_type'] == 'CheckBox') {
1286 $defaults[$elementName][$val['value']] = 1;
1287 }
1288 else {
1289 $defaults[$elementName][$val['value']] = $val['value'];
1290 }
1291 }
1292 else {
1293 $defaults[$elementName][$val['value']] = 0;
1294 }
1295 }
1296 }
1297 else {
1298 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1));
1299 foreach ($customOption as $val) {
1300 if (in_array($val['value'], $checkedValue)) {
1301 if ($field['html_type'] == 'CheckBox') {
1302 $defaults[$elementName][$val['value']] = 1;
1303 }
1304 else {
1305 $defaults[$elementName][$val['value']] = $val['value'];
1306 }
1307 }
1308 }
1309 }
1310 }
1311 break;
1312
1313 case 'Select Date':
1314 if (isset($value)) {
1315 if (empty($field['time_format'])) {
1316 list($defaults[$elementName]) = CRM_Utils_Date::setDateDefaults($value, NULL,
1317 $field['date_format']
1318 );
1319 }
1320 else {
1321 $timeElement = $elementName . '_time';
1322 if (substr($elementName, -1) == ']') {
1323 $timeElement = substr($elementName, 0, -1) . '_time]';
1324 }
1325 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1326 }
1327 }
1328 break;
1329
1330 case 'Multi-Select Country':
1331 case 'Multi-Select State/Province':
1332 if (isset($value)) {
1333 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1334 foreach ($checkedValue as $val) {
1335 if ($val) {
1336 $defaults[$elementName][$val] = $val;
1337 }
1338 }
1339 }
1340 break;
1341
1342 case 'Select Country':
1343 if ($value) {
1344 $defaults[$elementName] = $value;
1345 }
1346 else {
1347 $config = CRM_Core_Config::singleton();
1348 $defaults[$elementName] = $config->defaultContactCountry;
1349 }
1350 break;
1351
1352 default:
1353 if ($field['data_type'] == "Float") {
1354 $defaults[$elementName] = (float)$value;
1355 }
1356 elseif ($field['data_type'] == 'Money' &&
1357 $field['html_type'] == 'Text'
1358 ) {
1359 $defaults[$elementName] = CRM_Utils_Money::format($value, NULL, '%a');
1360 }
1361 else {
1362 $defaults[$elementName] = $value;
1363 }
1364 }
1365 }
1366 }
1367 }
1368
1369 /**
1370 * @param $groupTree
1371 * @param $params
1372 * @param bool $skipFile
1373 */
1374 static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1375 // Get the Custom form values and groupTree
1376 // first reset all checkbox and radio data
1377 foreach ($groupTree as $groupID => $group) {
1378 if ($groupID === 'info') {
1379 continue;
1380 }
1381 foreach ($group['fields'] as $field) {
1382 $fieldId = $field['id'];
1383
1384 //added Multi-Select option in the below if-statement
1385 if ($field['html_type'] == 'CheckBox' || $field['html_type'] == 'Radio' ||
1386 $field['html_type'] == 'AdvMulti-Select' || $field['html_type'] == 'Multi-Select'
1387 ) {
1388 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1389 }
1390
1391 $v = NULL;
1392 foreach ($params as $key => $val) {
1393 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1394 $match[1] == $field['id']
1395 ) {
1396 $v = $val;
1397 }
1398 }
1399
1400
1401 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1402 // field exists in db so populate value from "form".
1403 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1404 }
1405
1406 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1407
1408 //added for CheckBox
1409
1410 case 'CheckBox':
1411 if (!empty($v)) {
1412 $customValue = array_keys($v);
1413 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $customValue) . CRM_Core_DAO::VALUE_SEPARATOR;
1414 }
1415 else {
1416 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1417 }
1418 break;
1419
1420 //added for Advanced Multi-Select
1421
1422 case 'AdvMulti-Select':
1423 //added for Multi-Select
1424 case 'Multi-Select':
1425 if (!empty($v)) {
1426 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $v) . CRM_Core_DAO::VALUE_SEPARATOR;
1427 }
1428 else {
1429 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1430 }
1431 break;
1432
1433 case 'Select Date':
1434 $date = CRM_Utils_Date::processDate($v);
1435 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1436 break;
1437
1438 case 'File':
1439 if ($skipFile) {
1440 continue;
1441 }
1442
1443 //store the file in d/b
1444 $entityId = explode('=', $groupTree['info']['where'][0]);
1445 $fileParams = array('upload_date' => date('Ymdhis'));
1446
1447 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1448 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1449 }
1450 if (!empty($v)) {
1451 $fileParams['uri'] = $v['name'];
1452 $fileParams['mime_type'] = $v['type'];
1453 CRM_Core_BAO_File::filePostProcess($v['name'],
1454 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1455 $groupTree[$groupID]['table_name'],
1456 trim($entityId[1]),
1457 FALSE,
1458 TRUE,
1459 $fileParams,
1460 'custom_' . $fieldId,
1461 $v['type']
1462 );
1463 }
1464 $defaults = array();
1465 $paramsFile = array(
1466 'entity_table' => $groupTree[$groupID]['table_name'],
1467 'entity_id' => $entityId[1],
1468 );
1469
1470 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_EntityFile',
1471 $paramsFile,
1472 $defaults
1473 );
1474
1475 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1476 break;
1477
1478 default:
1479 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1480 break;
1481 }
1482 }
1483 }
1484 }
1485
1486 /**
1487 * generic function to build all the form elements for a specific group tree
1488 *
1489 * @param object $form the form object
1490 * @param array $groupTree the group tree object
1491 * @param boolean $inactiveNeeded return inactive custom groups
1492 * @param string $prefix prefix for custom grouptree assigned to template
1493 *
1494 * @return void
1495 * @access public
1496 * @static
1497 */
1498 static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '' ) {
1499 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1500
1501 // this is fix for date field
1502 $form->assign('currentYear', date('Y'));
1503
1504 foreach ($groupTree as $id => $group) {
1505 CRM_Core_ShowHideBlocks::links($form, $group['title'], '', '');
1506 foreach ($group['fields'] as $field) {
1507 $required = CRM_Utils_Array::value('is_required', $field);
1508 //fix for CRM-1620
1509 if ($field['data_type'] == 'File') {
1510 if (!empty($field['element_value']['data'])) {
1511 $required = 0;
1512 }
1513 }
1514
1515 $fieldId = $field['id'];
1516 $elementName = $field['element_name'];
1517 CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1518 }
1519 }
1520 if (!empty($form->_stateCountryMap['state_province']) && !empty($form->_stateCountryMap['country'])) {
1521 foreach ($form->_stateCountryMap['state_province'] as $key => $value) {
1522 $stateCountryMap[$key]['state_province'] = $value;
1523 $stateCountryMap[$key]['country'] = $form->_stateCountryMap['country'][$key];
1524 }
1525 CRM_Core_BAO_Address::addStateCountryMap($stateCountryMap);
1526 }
1527 }
1528
1529 /**
1530 * Function to extract the get params from the url, validate
1531 * and store it in session
1532 *
1533 * @param CRM_Core_Form $form the form object
1534 * @param string $type the type of custom group we are using
1535 *
1536 * @return void
1537 * @access public
1538 * @static
1539 */
1540 static function extractGetParams(&$form, $type) {
1541 // if not GET params return
1542 if (empty($_GET)) {
1543 return;
1544 }
1545
1546 $groupTree = CRM_Core_BAO_CustomGroup::getTree($type, $form);
1547 $customValue = array();
1548 $htmlType = array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Select', 'Radio');
1549
1550 foreach ($groupTree as $group) {
1551 if (!isset($group['fields'])) {
1552 continue;
1553 }
1554 foreach ($group['fields'] as $key => $field) {
1555 $fieldName = 'custom_' . $key;
1556 $value = CRM_Utils_Request::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1557
1558 if ($value) {
1559 $valid = FALSE;
1560 if (!in_array($field['html_type'], $htmlType) ||
1561 $field['data_type'] == 'Boolean'
1562 ) {
1563 $valid = CRM_Core_BAO_CustomValue::typecheck($field['data_type'], $value);
1564 }
1565 if ($field['html_type'] == 'CheckBox' ||
1566 $field['html_type'] == 'AdvMulti-Select' ||
1567 $field['html_type'] == 'Multi-Select'
1568 ) {
1569 $value = str_replace("|", ",", $value);
1570 $mulValues = explode(',', $value);
1571 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, TRUE);
1572 $val = array();
1573 foreach ($mulValues as $v1) {
1574 foreach ($customOption as $coID => $coValue) {
1575 if (strtolower(trim($coValue['label'])) == strtolower(trim($v1))) {
1576 $val[$coValue['value']] = 1;
1577 }
1578 }
1579 }
1580 if (!empty($val)) {
1581 $value = $val;
1582 $valid = TRUE;
1583 }
1584 else {
1585 $value = NULL;
1586 }
1587 }
1588 elseif ($field['html_type'] == 'Select' ||
1589 ($field['html_type'] == 'Radio' &&
1590 $field['data_type'] != 'Boolean'
1591 )
1592 ) {
1593 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, TRUE);
1594 foreach ($customOption as $customID => $coValue) {
1595 if (strtolower(trim($coValue['label'])) == strtolower(trim($value))) {
1596 $value = $coValue['value'];
1597 $valid = TRUE;
1598 }
1599 }
1600 }
1601 elseif ($field['data_type'] == 'Date') {
1602 if (!empty($value)) {
1603 $time = NULL;
1604 if (!empty($field['time_format'])) {
1605 $time = CRM_Utils_Request::retrieve($fieldName . '_time', 'String', $form, FALSE, NULL, 'GET');
1606 }
1607 list($value, $time) = CRM_Utils_Date::setDateDefaults($value . ' ' . $time);
1608 if (!empty($field['time_format'])) {
1609 $customValue[$fieldName . '_time'] = $time;
1610 }
1611 }
1612 $valid = TRUE;
1613 }
1614
1615 if ($valid) {
1616 $customValue[$fieldName] = $value;
1617 }
1618 }
1619 }
1620 }
1621
1622 return $customValue;
1623 }
1624
1625 /**
1626 * Function to check the type of custom field type (eg: Used for Individual, Contribution, etc)
1627 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1628 *
1629 * @param int $customFieldId custom field id
1630 * @param array $removeCustomFieldTypes remove custom fields of a type eg: array("Individual") ;
1631 *
1632 *
1633 * @return boolean false if it matches else true
1634 * @static
1635 * @access public
1636 */
1637 static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1638 $query = "SELECT cg.extends as extends
1639 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1640 WHERE cg.id = cf.custom_group_id
1641 AND cf.id =" . CRM_Utils_Type::escape($customFieldId, 'Integer');
1642
1643 $extends = CRM_Core_DAO::singleValueQuery($query);
1644
1645 if (in_array($extends, $removeCustomFieldTypes)) {
1646 return FALSE;
1647 }
1648 return TRUE;
1649 }
1650
1651 /**
1652 * @param $table
1653 *
1654 * @return string
1655 * @throws Exception
1656 */
1657 static function mapTableName($table) {
1658 switch ($table) {
1659 case 'Contact':
1660 case 'Individual':
1661 case 'Household':
1662 case 'Organization':
1663 return 'civicrm_contact';
1664
1665 case 'Activity':
1666 return 'civicrm_activity';
1667
1668 case 'Group':
1669 return 'civicrm_group';
1670
1671 case 'Contribution':
1672 return 'civicrm_contribution';
1673
1674 case 'Relationship':
1675 return 'civicrm_relationship';
1676
1677 case 'Event':
1678 return 'civicrm_event';
1679
1680 case 'Membership':
1681 return 'civicrm_membership';
1682
1683 case 'Participant':
1684 case 'ParticipantRole':
1685 case 'ParticipantEventName':
1686 case 'ParticipantEventType':
1687 return 'civicrm_participant';
1688
1689 case 'Grant':
1690 return 'civicrm_grant';
1691
1692 case 'Pledge':
1693 return 'civicrm_pledge';
1694
1695 case 'Address':
1696 return 'civicrm_address';
1697
1698 case 'Campaign':
1699 return 'civicrm_campaign';
1700
1701 default:
1702 $query = "
1703 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1704 $qParams = array(1 => array($table, 'String'));
1705 $result = CRM_Core_DAO::singleValueQuery($query, $qParams);
1706
1707 if ($result) {
1708 return 'civicrm_contact';
1709 }
1710 else {
1711 $extendObjs = CRM_Core_OptionGroup::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1712 if (array_key_exists($table, $extendObjs)) {
1713 return $extendObjs[$table];
1714 }
1715 CRM_Core_Error::fatal();
1716 }
1717 }
1718 }
1719
1720 /**
1721 * @param $group
1722 */
1723 static function createTable($group) {
1724 $params = array(
1725 'name' => $group->table_name,
1726 'is_multiple' => $group->is_multiple ? 1 : 0,
1727 'extends_name' => self::mapTableName($group->extends),
1728 );
1729
1730 $tableParams = CRM_Core_BAO_CustomField::defaultCustomTableSchema($params);
1731
1732 CRM_Core_BAO_SchemaHandler::createTable($tableParams);
1733 }
1734
1735 /**
1736 * Function returns formatted groupTree, sothat form can be easily build in template
1737 *
1738 * @param array $groupTree associated array
1739 * @param int $groupCount group count by default 1, but can varry for multiple value custom data
1740 * @param object form object
1741 *
1742 * @return array $formattedGroupTree
1743 */
1744 static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1745 $formattedGroupTree = array();
1746 $uploadNames = array();
1747
1748 foreach ($groupTree as $key => $value) {
1749 if ($key === 'info') {
1750 continue;
1751 }
1752
1753 // add group information
1754 $formattedGroupTree[$key]['name'] = CRM_Utils_Array::value('name', $value);
1755 $formattedGroupTree[$key]['title'] = CRM_Utils_Array::value('title', $value);
1756 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array::value('help_pre', $value);
1757 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array::value('help_post', $value);
1758 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array::value('collapse_display', $value);
1759 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array::value('collapse_adv_display', $value);
1760
1761 // this params needed of bulding multiple values
1762 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array::value('is_multiple', $value);
1763 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array::value('extends', $value);
1764 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array::value('extends_entity_column_id', $value);
1765 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array::value('extends_entity_column_value', $value);
1766 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array::value('subtype', $value);
1767 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array::value('max_multiple', $value);
1768
1769 // add field information
1770 foreach ($value['fields'] as $k => $properties) {
1771 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1772 if (isset($properties['customValue']) && !CRM_Utils_System::isNull($properties['customValue'])) {
1773 if (isset($properties['customValue'][$groupCount])) {
1774 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1775 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1776 if ($properties['data_type'] == 'File') {
1777 $properties['element_value'] = $properties['customValue'][$groupCount];
1778 $uploadNames[] = $properties['element_name'];
1779 }
1780 else {
1781 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1782 }
1783 }
1784 }
1785 unset($properties['customValue']);
1786 $formattedGroupTree[$key]['fields'][$k] = $properties;
1787 }
1788 }
1789
1790 if ($form) {
1791 // hack for field type File
1792 $formUploadNames = $form->get('uploadNames');
1793 if (is_array($formUploadNames)) {
1794 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1795 }
1796
1797 $form->set('uploadNames', $uploadNames);
1798 }
1799
1800 return $formattedGroupTree;
1801 }
1802
1803 /**
1804 * Build custom data view
1805 *
1806 * @param object $form page object
1807 * @param array $groupTree associated array
1808 * @param boolean $returnCount true if customValue count needs to be returned
1809 * @param null $gID
1810 * @param null $prefix
1811 * @param null $customValueId
1812 *
1813 * @return array|int
1814 */
1815 static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1816 $details = array();
1817 foreach ($groupTree as $key => $group) {
1818 if ($key === 'info') {
1819 continue;
1820 }
1821
1822 foreach ($group['fields'] as $k => $properties) {
1823 $groupID = $group['id'];
1824 if (!empty($properties['customValue'])) {
1825 foreach ($properties['customValue'] as $values) {
1826 if (!empty($customValueId) && $customValueId != $values['id']) {
1827 continue;
1828 }
1829 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array::value('title', $group);
1830 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array::value('name', $group);
1831 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array::value('help_pre', $group);
1832 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array::value('help_post', $group);
1833 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array::value('collapse_display', $group);
1834 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array::value('collapse_adv_display', $group);
1835 $details[$groupID][$values['id']]['fields'][$k] = array('field_title' => CRM_Utils_Array::value('label', $properties),
1836 'field_type' => CRM_Utils_Array::value('html_type',
1837 $properties
1838 ),
1839 'field_data_type' => CRM_Utils_Array::value('data_type',
1840 $properties
1841 ),
1842 'field_value' => self::formatCustomValues($values,
1843 $properties
1844 ),
1845 'options_per_line' => CRM_Utils_Array::value('options_per_line',
1846 $properties
1847 ),
1848 );
1849 // also return contact reference contact id if user has view all or edit all contacts perm
1850 if ((CRM_Core_Permission::check('view all contacts') || CRM_Core_Permission::check('edit all contacts'))
1851 && $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] == 'ContactReference'
1852 ) {
1853 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array::value('data', $values);
1854 }
1855 }
1856 }
1857 else {
1858 $details[$groupID][0]['title'] = CRM_Utils_Array::value('title', $group);
1859 $details[$groupID][0]['name'] = CRM_Utils_Array::value('name', $group);
1860 $details[$groupID][0]['help_pre'] = CRM_Utils_Array::value('help_pre', $group);
1861 $details[$groupID][0]['help_post'] = CRM_Utils_Array::value('help_post', $group);
1862 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array::value('collapse_display', $group);
1863 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array::value('collapse_adv_display', $group);
1864 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array::value('label', $properties));
1865 }
1866 }
1867 }
1868
1869 if ($returnCount) {
1870 //return a single value count if group id is passed to function
1871 //else return a groupId and count mapped array
1872 if (!empty($gID)){
1873 return count($details[$gID]);
1874 }
1875 else {
1876 $countValue = array();
1877 foreach( $details as $key => $value ) {
1878 $countValue[$key] = count($details[$key]);
1879 }
1880 return $countValue;
1881 }
1882 }
1883 else {
1884 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1885 return $details;
1886 }
1887 }
1888
1889 /**
1890 * Format custom value according to data, view mode
1891 *
1892 * @param array $values associated array of custom values
1893 * @param array $field associated array
1894 * @param boolean $dncOptionPerLine true if optionPerLine should not be consider
1895 *
1896 * @return array|null|string
1897 */
1898 static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1899 $value = $values['data'];
1900
1901 //changed isset CRM-4601
1902 if (CRM_Utils_System::isNull($value)) {
1903 return;
1904 }
1905
1906 $htmlType = CRM_Utils_Array::value('html_type', $field);
1907 $dataType = CRM_Utils_Array::value('data_type', $field);
1908 $option_group_id = CRM_Utils_Array::value('option_group_id', $field);
1909 $timeFormat = CRM_Utils_Array::value('time_format', $field);
1910 $optionPerLine = CRM_Utils_Array::value('options_per_line', $field);
1911
1912 $freezeString = "";
1913 $freezeStringChecked = "";
1914
1915 switch ($dataType) {
1916 case 'Date':
1917 $customTimeFormat = '';
1918 $customFormat = NULL;
1919
1920 switch ($timeFormat) {
1921 case 1:
1922 $customTimeFormat = '%l:%M %P';
1923 break;
1924
1925 case 2:
1926 $customTimeFormat = '%H:%M';
1927 break;
1928
1929 default:
1930 // if time is not selected remove time from value
1931 $value = substr($value, 0, 10);
1932 }
1933
1934 $supportableFormats = array(
1935 'mm/dd' => "%B %E%f $customTimeFormat",
1936 'dd-mm' => "%E%f %B $customTimeFormat",
1937 'yy' => "%Y $customTimeFormat",
1938 'M yy' => "%b %Y $customTimeFormat",
1939 'yy-mm' => "%Y-%m $customTimeFormat"
1940 );
1941
1942 if ($format = CRM_Utils_Array::value('date_format', $field)) {
1943 if (array_key_exists($format, $supportableFormats)) {
1944 $customFormat = $supportableFormats["$format"];
1945 }
1946 }
1947
1948 $retValue = CRM_Utils_Date::customFormat($value, $customFormat);
1949 break;
1950
1951 case 'Boolean':
1952 if ($value == '1') {
1953 $retValue = $freezeStringChecked . ts('Yes') . "\n";
1954 }
1955 else {
1956 $retValue = $freezeStringChecked . ts('No') . "\n";
1957 }
1958 break;
1959
1960 case 'Link':
1961 if ($value) {
1962 $retValue = CRM_Utils_System::formatWikiURL($value);
1963 }
1964 break;
1965
1966 case 'File':
1967 $retValue = $values;
1968 break;
1969
1970 case 'ContactReference':
1971 if (!empty($values['data'])) {
1972 $retValue = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
1973 }
1974 break;
1975
1976 case 'Memo':
1977 $retValue = $value;
1978 break;
1979
1980 case 'Float':
1981 if ($htmlType == 'Text') {
1982 $retValue = (float)$value;
1983 break;
1984 }
1985 case 'Money':
1986 if ($htmlType == 'Text') {
1987 $retValue = CRM_Utils_Money::format($value, NULL, '%a');
1988 break;
1989 }
1990 case 'String':
1991 case 'Int':
1992 if (in_array($htmlType, array('Text', 'TextArea'))) {
1993 $retValue = $value;
1994 break;
1995 }
1996 // note that if its not text / textarea, the code falls thru and executes
1997 // the below case also
1998 case 'StateProvince':
1999 case 'Country':
2000 $options = array();
2001 $coDAO = NULL;
2002
2003 //added check for Multi-Select in the below if-statement
2004 $customData[] = $value;
2005
2006 //form custom data for multiple-valued custom data
2007 switch ($htmlType) {
2008 case 'Multi-Select Country':
2009 case 'Select Country':
2010 $customData = $value;
2011 if (!is_array($value)) {
2012 $customData = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2013 }
2014 $query = "
2015 SELECT id as value, name as label
2016 FROM civicrm_country";
2017 $coDAO = CRM_Core_DAO::executeQuery($query);
2018 break;
2019
2020 case 'Select State/Province':
2021 case 'Multi-Select State/Province':
2022 $customData = $value;
2023 if (!is_array($value)) {
2024 $customData = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2025 }
2026
2027 $query = "
2028 SELECT id as value, name as label
2029 FROM civicrm_state_province";
2030 $coDAO = CRM_Core_DAO::executeQuery($query);
2031 break;
2032
2033 case 'Select':
2034 $customData = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2035 if ($option_group_id) {
2036 $options = CRM_Core_BAO_OptionValue::getOptionValuesAssocArray($option_group_id);
2037 }
2038 break;
2039
2040 case 'CheckBox':
2041 case 'AdvMulti-Select':
2042 case 'Multi-Select':
2043 $customData = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2044 default:
2045 if ($option_group_id) {
2046 $options = CRM_Core_BAO_OptionValue::getOptionValuesAssocArray($option_group_id);
2047 }
2048 }
2049
2050 if (is_object($coDAO)) {
2051 while ($coDAO->fetch()) {
2052 if ($dataType == 'Country') {
2053 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2054 // and already extracted to .pot files.
2055 $options[$coDAO->value] = ts($coDAO->label, array('context' => 'country'));
2056 }
2057 elseif ($dataType == 'StateProvince') {
2058 $options[$coDAO->value] = ts($coDAO->label, array('context' => 'province'));
2059 }
2060 else {
2061 $options[$coDAO->value] = $coDAO->label;
2062 }
2063 }
2064 }
2065
2066 CRM_Utils_Hook::customFieldOptions($field['id'], $options, FALSE);
2067
2068 $retValue = NULL;
2069 foreach ($options as $optionValue => $optionLabel) {
2070 if ($dataType == 'Money') {
2071 foreach ($customData as $k => $v) {
2072 $customData[] = CRM_Utils_Money::format($v, NULL, '%a');
2073 }
2074 }
2075
2076 //to show only values that are checked
2077 if (in_array((string) $optionValue, $customData)) {
2078 $checked = in_array($optionValue, $customData) ? $freezeStringChecked : $freezeString;
2079 if (!$optionPerLine || $dncOptionPerLine) {
2080 if ($retValue) {
2081 $retValue .= ", ";
2082 }
2083 $retValue .= $checked . $optionLabel;
2084 }
2085 else {
2086 $retValue[] = $checked . $optionLabel;
2087 }
2088 }
2089 }
2090 break;
2091 }
2092
2093 //special case for option per line formatting
2094 if ($optionPerLine > 1 && is_array($retValue)) {
2095 $rowCounter = 0;
2096 $fieldCounter = 0;
2097 $displayValues = array();
2098 $displayString = '';
2099 foreach ($retValue as $val) {
2100 if ($displayString) {
2101 $displayString .= ", ";
2102 }
2103
2104 $displayString .= $val;
2105 $rowCounter++;
2106 $fieldCounter++;
2107
2108 if (($rowCounter == $optionPerLine) || ($fieldCounter == count($retValue))) {
2109 $displayValues[] = $displayString;
2110 $displayString = '';
2111 $rowCounter = 0;
2112 }
2113 }
2114 $retValue = $displayValues;
2115 }
2116
2117 $retValue = isset($retValue) ? $retValue : NULL;
2118 return $retValue;
2119 }
2120
2121 /**
2122 * Get the custom group titles by custom field ids.
2123 *
2124 * @param array $fieldIds - array of custom field ids.
2125 *
2126 * @return array $groupLabels - array consisting of groups and fields labels with ids.
2127 * @access public
2128 */
2129 public static function getGroupTitles($fieldIds) {
2130 if (!is_array($fieldIds) && empty($fieldIds)) {
2131 return;
2132 }
2133
2134 $groupLabels = array();
2135 $fIds = "(" . implode(',', $fieldIds) . ")";
2136
2137 $query = "
2138 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2139 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2140 FROM civicrm_custom_group, civicrm_custom_field
2141 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2142 AND civicrm_custom_field.id IN {$fIds}";
2143
2144 $dao = CRM_Core_DAO::executeQuery($query);
2145 while ($dao->fetch()) {
2146 $groupLabels[$dao->fieldID] = array(
2147 'fieldID' => $dao->fieldID,
2148 'fieldLabel' => $dao->fieldLabel,
2149 'groupID' => $dao->groupID,
2150 'groupTitle' => $dao->groupTitle,
2151 );
2152 }
2153
2154 return $groupLabels;
2155 }
2156
2157 static function dropAllTables() {
2158 $query = "SELECT table_name FROM civicrm_custom_group";
2159 $dao = CRM_Core_DAO::executeQuery($query);
2160
2161 while ($dao->fetch()) {
2162 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2163 CRM_Core_DAO::executeQuery($query);
2164 }
2165 }
2166
2167 /**
2168 * Check whether custom group is empty or not.
2169 *
2170 * @param int $gID - custom group id.
2171 *
2172 * @return boolean true if empty otherwise false.
2173 * @access public
2174 */
2175 static function isGroupEmpty($gID) {
2176 if (!$gID) {
2177 return;
2178 }
2179
2180 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
2181 $gID,
2182 'table_name'
2183 );
2184
2185 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2186 $value = CRM_Core_DAO::singleValueQuery($query);
2187
2188 if (empty($value)) {
2189 return TRUE;
2190 }
2191
2192 return FALSE;
2193 }
2194
2195 /**
2196 * Get the list of types for objects that a custom group extends to.
2197 *
2198 * @param array $types - var which should have the list appended.
2199 *
2200 * @return array of types.
2201 * @access public
2202 */
2203 static function getExtendedObjectTypes(&$types = array( )) {
2204 static $flag = FALSE, $objTypes = array();
2205
2206 if (!$flag) {
2207 $extendObjs = array();
2208 CRM_Core_OptionValue::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2209
2210 foreach ($extendObjs as $ovId => $ovValues) {
2211 if ($ovValues['description']) {
2212 // description is expected to be a callback func to subtypes
2213 list($callback, $args) = explode(';', trim($ovValues['description']));
2214
2215 if (empty($args)) {
2216 $args = array();
2217 }
2218
2219 if (!is_array($args)) {
2220 CRM_Core_Error::fatal('Arg is not of type array');
2221 }
2222
2223 list($className) = explode('::', $callback);
2224 require_once (str_replace('_',DIRECTORY_SEPARATOR, $className) . '.php');
2225
2226 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2227 }
2228 }
2229 $flag = TRUE;
2230 }
2231
2232 $types = array_merge($types, $objTypes);
2233 return $objTypes;
2234 }
2235
2236 /**
2237 * @param $customGroupId
2238 * @param $entityId
2239 *
2240 * @return bool
2241 */
2242 static function hasReachedMaxLimit($customGroupId, $entityId) {
2243 //check whether the group is multiple
2244 $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2245 $isMultiple = ($isMultiple) ? TRUE : FALSE;
2246 $hasReachedMax = FALSE;
2247 if ($isMultiple &&
2248 ($maxMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))) {
2249 if (!$maxMultiple) {
2250 $hasReachedMax = FALSE;
2251 } else {
2252 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2253 //count the number of entries for a entity
2254 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2255 $params = array(1 => array($entityId, 'Integer'));
2256 $count = CRM_Core_DAO::singleValueQuery($sql, $params);
2257
2258 if ($count >= $maxMultiple) {
2259 $hasReachedMax = TRUE;
2260 }
2261 }
2262 }
2263 return $hasReachedMax;
2264 }
2265
2266 /**
2267 * @return array
2268 */
2269 static function getMultipleFieldGroup() {
2270 $multipleGroup = array();
2271 $dao = new CRM_Core_DAO_CustomGroup();
2272 $dao->is_multiple = 1 ;
2273 $dao->find();
2274 while($dao->fetch()) {
2275 $multipleGroup[$dao->id] = $dao->title;
2276 }
2277 return $multipleGroup;
2278 }
2279 }
2280