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