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