Merge pull request #2568 from seamuslee001/master
[civicrm-core.git] / CRM / Core / BAO / CustomGroup.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id$
33 *
34 */
35
36 /**
37 * Business object for managing custom data groups
38 *
39 */
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 public static function hasCustomGroup($extends, $columnId, $columnValue) {
255 $dao = new CRM_Core_DAO_CustomGroup();
256 $dao->extends = $extends;
257 $dao->extends_entity_column_id = $columnId;
258 $escapedValue = CRM_Core_DAO::VALUE_SEPARATOR . CRM_Core_DAO::escapeString($columnValue) . CRM_Core_DAO::VALUE_SEPARATOR;
259 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
260 //$dao->extends_entity_column_value = $columnValue;
261 return $dao->find() ? TRUE : FALSE;
262 }
263
264 /**
265 * Determine if there are any CustomGroups for the given $activityTypeId.
266 * If none found, create one.
267 *
268 * @param int $activityTypeId
269 * @return bool TRUE if a group is found or created; FALSE on error
270 */
271 public static function autoCreateByActivityType($activityTypeId) {
272 if (self::hasCustomGroup('Activity', NULL, $activityTypeId)) {
273 return TRUE;
274 }
275 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
276 $params = array(
277 'version' => 3,
278 'extends' => 'Activity',
279 'extends_entity_column_id' => NULL,
280 'extends_entity_column_value' => CRM_Utils_Array::implodePadded(array($activityTypeId)),
281 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
282 'style' => 'Inline',
283 'is_active' => 1,
284 );
285 $result = civicrm_api('CustomGroup', 'create', $params);
286 return ! $result['is_error'];
287 }
288
289 /**
290 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
291 * This may also include entity specific data values.
292 *
293 * An array containing all custom groups and their custom fields is returned.
294 *
295 * @param string $entityType - of the contact whose contact type is needed
296 * @param object $form - not used but required
297 * @param int $entityId - optional - id of entity if we need to populate the tree with custom values.
298 * @param int $groupId - optional group id (if we need it for a single group only)
299 * - if groupId is 0 it gets for inline groups only
300 * - if groupId is -1 we get for all groups
301 * @param string $subType
302 * @param string $subName
303 * @param boolean $fromCache
304 *
305 * @return array $groupTree - array The returned array is keyed by group id and has the custom group table fields
306 * and a subkey 'fields' holding the specific custom fields.
307 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
308 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
309 *
310 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
311 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
312 * With caching the performance impact would be small & the function would be cleaner
313 *
314 * @access public
315 *
316 * @static
317 *
318 */
319 public static function &getTree(
320 $entityType,
321 &$form,
322 $entityID = NULL,
323 $groupID = NULL,
324 $subType = NULL,
325 $subName = NULL,
326 $fromCache = TRUE,
327 $onlySubType = NULL
328 ) {
329 if ($entityID) {
330 $entityID = CRM_Utils_Type::escape($entityID, 'Integer');
331 }
332
333 // create a new tree
334 $strSelect = $strFrom = $strWhere = $orderBy = '';
335 $tableData = array();
336
337 // using tableData to build the queryString
338 $tableData = array(
339 'civicrm_custom_field' =>
340 array(
341 'id',
342 'label',
343 'column_name',
344 'data_type',
345 'html_type',
346 'default_value',
347 'attributes',
348 'is_required',
349 'is_view',
350 'help_pre',
351 'help_post',
352 'options_per_line',
353 'start_date_years',
354 'end_date_years',
355 'date_format',
356 'time_format',
357 'option_group_id',
358 'in_selector'
359 ),
360 'civicrm_custom_group' =>
361 array(
362 'id',
363 'name',
364 'table_name',
365 'title',
366 'help_pre',
367 'help_post',
368 'collapse_display',
369 'is_multiple',
370 'extends',
371 'extends_entity_column_id',
372 'extends_entity_column_value',
373 'max_multiple',
374 ),
375 );
376
377 // create select
378 $select = array();
379 foreach ($tableData as $tableName => $tableColumn) {
380 foreach ($tableColumn as $columnName) {
381 $alias = $tableName . "_" . $columnName;
382 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
383 }
384 }
385 $strSelect = "SELECT " . implode(', ', $select);
386
387 // from, where, order by
388 $strFrom = "
389 FROM civicrm_custom_group
390 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
391 ";
392
393 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
394 if ($entityType == "Individual" || $entityType == 'Organization' || $entityType == 'Household') {
395 $in = "'$entityType', 'Contact'";
396 }
397 elseif (strpos($entityType, "'") !== FALSE) {
398 // this allows the calling function to send in multiple entity types
399 $in = $entityType;
400 }
401 else {
402 // quote it
403 $in = "'$entityType'";
404 }
405
406 if ($subType) {
407 $subTypeClause = '';
408 if (is_array($subType)) {
409 $subType = implode(',', $subType);
410 }
411 if (strpos($subType, ',')) {
412 $subTypeParts = explode(',', $subType);
413 $subTypeClauses = array();
414 foreach ($subTypeParts as $subTypePart) {
415 $subTypePart = CRM_Core_DAO::VALUE_SEPARATOR . trim($subTypePart, CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
416 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
417 }
418
419 if ($onlySubType) {
420 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
421 }
422 else {
423 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
424 }
425 }
426 else {
427 $subType = CRM_Core_DAO::VALUE_SEPARATOR . trim($subType, CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
428
429 if ($onlySubType) {
430 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
431 }
432 else {
433 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
434 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
435 }
436 }
437
438 $strWhere = "
439 WHERE civicrm_custom_group.is_active = 1
440 AND civicrm_custom_field.is_active = 1
441 AND civicrm_custom_group.extends IN ($in)
442 AND $subTypeClause
443 ";
444 if ($subName) {
445 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
446 }
447 }
448 else {
449 $strWhere = "
450 WHERE civicrm_custom_group.is_active = 1
451 AND civicrm_custom_field.is_active = 1
452 AND civicrm_custom_group.extends IN ($in)
453 AND civicrm_custom_group.extends_entity_column_value IS NULL
454 ";
455 }
456
457 $params = array();
458 if ($groupID > 0) {
459 // since we want a specific group id we add it to the where clause
460 $strWhere .= " AND civicrm_custom_group.id = %1";
461 $params[1] = array($groupID, 'Integer');
462 }
463 elseif (!$groupID) {
464 // since groupID is false we need to show all Inline groups
465 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
466 }
467
468 // ensure that the user has access to these custom groups
469 $strWhere .= " AND " . CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
470 'civicrm_custom_group.'
471 );
472
473 $orderBy = "
474 ORDER BY civicrm_custom_group.weight,
475 civicrm_custom_group.title,
476 civicrm_custom_field.weight,
477 civicrm_custom_field.label
478 ";
479
480 // final query string
481 $queryString = "$strSelect $strFrom $strWhere $orderBy";
482
483 // lets see if we can retrieve the groupTree from cache
484 $cacheString = $queryString;
485 if ( $groupID > 0 ) {
486 $cacheString .= "_{$groupID}";
487 } else {
488 $cacheString .= "_Inline";
489 }
490
491 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
492 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
493 $cache = CRM_Utils_Cache::singleton();
494 $tablesWithEntityData = array();
495 if ($fromCache) {
496 $groupTree = $cache->get($cacheKey);
497 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
498 }
499
500 if (empty($groupTree)) {
501 $groupTree = $multipleFieldGroups =array();
502 $crmDAO = CRM_Core_DAO::executeQuery($queryString, $params);
503 $customValueTables = array();
504
505 // process records
506 while ($crmDAO->fetch()) {
507 // get the id's
508 $groupID = $crmDAO->civicrm_custom_group_id;
509 $fieldId = $crmDAO->civicrm_custom_field_id;
510 if($crmDAO->civicrm_custom_group_is_multiple){
511 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name;
512 }
513 // create an array for groups if it does not exist
514 if (!array_key_exists($groupID, $groupTree)) {
515 $groupTree[$groupID] = array();
516 $groupTree[$groupID]['id'] = $groupID;
517
518 // populate the group information
519 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
520 $fullFieldName = "civicrm_custom_group_$fieldName";
521 if ($fieldName == 'id' ||
522 is_null($crmDAO->$fullFieldName)
523 ) {
524 continue;
525 }
526 // CRM-5507
527 if ($fieldName == 'extends_entity_column_value' && $subType) {
528 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO::VALUE_SEPARATOR);
529 }
530 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
531 }
532 $groupTree[$groupID]['fields'] = array();
533
534 $customValueTables[$crmDAO->civicrm_custom_group_table_name] = array();
535 }
536
537 // add the fields now (note - the query row will always contain a field)
538 // we only reset this once, since multiple values come is as multiple rows
539 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
540 $groupTree[$groupID]['fields'][$fieldId] = array();
541 }
542
543 $customValueTables[$crmDAO->civicrm_custom_group_table_name][$crmDAO->civicrm_custom_field_column_name] = 1;
544 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
545 // populate information for a custom field
546 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
547 $fullFieldName = "civicrm_custom_field_$fieldName";
548 if ($fieldName == 'id' ||
549 is_null($crmDAO->$fullFieldName)
550 ) {
551 continue;
552 }
553 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
554 }
555 }
556
557 if (!empty($customValueTables)) {
558 $groupTree['info'] = array('tables' => $customValueTables);
559 }
560
561 $cache->set($cacheKey, $groupTree);
562 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
563 }
564 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
565 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
566 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
567 $singleFieldTables = array();
568 // now that we have all the groups and fields, lets get the values
569 // since we need to know the table and field names
570 // add info to groupTree
571
572 if (isset($groupTree['info']) && !empty($groupTree['info']) && !empty($groupTree['info']['tables'])) {
573 $select = $from = $where = array();
574 $groupTree['info']['where'] = NULL;
575
576 foreach ($groupTree['info']['tables'] as $table => $fields) {
577 $groupTree['info']['from'][] = $table;
578 $select = array("{$table}.id as {$table}_id",
579 "{$table}.entity_id as {$table}_entity_id");
580 foreach ($fields as $column => $dontCare) {
581 $select[] = "{$table}.{$column} as {$table}_{$column}";
582 }
583 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
584 if ($entityID) {
585 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
586 if(in_array($table, $multipleFieldGroups) && self::customGroupDataExistsForEntity($entityID, $table)){
587 $entityMultipleSelectClauses[$table] = $select;
588 }
589 else{
590 $singleFieldTables[] = $table;
591 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
592 }
593
594 }
595 }
596 if ($entityID && !empty($singleFieldTables)) {
597 self::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
598 }
599 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
600 if(!empty($multipleFieldTablesWithEntityData)){
601 self::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
602 }
603
604 }
605 return $groupTree;
606 }
607
608 /**
609 * Check whether the custom group has any data for the given entity.
610 *
611 *
612 * @param integer $entityID id of entity for whom we are checking data for
613 * @param string $table table that we are checking
614 *
615 * @return boolean does this entity have data in this custom table
616 */
617 static public function customGroupDataExistsForEntity($entityID, $table){
618 $query = "
619 SELECT count(id)
620 FROM $table
621 WHERE entity_id = $entityID
622 ";
623 $recordExists = CRM_Core_DAO::singleValueQuery($query);
624 return $recordExists ? TRUE : FALSE;
625 }
626
627 /**
628 * Build the group tree for Custom fields which are not 'is_multiple'
629 *
630 * The combination of all these fields in one query with a 'using' join was not working for
631 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
632 * mechanism as it seemed to be acceptable in this context
633 *
634 * @param array $groupTree (reference) group tree array which is being built
635 * @param integer $entityID id of entity for whom the tree is being build up.
636 * @param array $entitySingleSelectClauses array of select clauses relevant to the entity
637 * @param array $singleFieldTablesWithEntityData array of tables in which this entity has data
638 */
639 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData){
640 $select = implode(', ', $entitySingleSelectClauses);
641 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
642 foreach ($singleFieldTablesWithEntityData as $table) {
643 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
644 }
645
646 $query = "
647 SELECT $select
648 FROM $fromSQL
649 WHERE first.entity_id = $entityID
650 ";
651 self::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
652 }
653
654 /**
655 * Build the group tree for Custom fields which are 'is_multiple'
656 *
657 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
658 *
659 * @param array $groupTree (reference) group tree array which is being built
660 * @param integer $entityID id of entity for whom the tree is being build up.
661 * @param array $entityMultipleSelectClauses array of select clauses relevant to the entity
662 * @param array $multipleFieldTablesWithEntityData array of tables in which this entity has data
663 */
664 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData){
665 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
666 $select = implode(',', $selectClauses);
667 $query = "
668 SELECT $select
669 FROM $table
670 WHERE entity_id = $entityID
671 ";
672 self::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
673 }
674 }
675
676 /**
677 * Build the tree entity data - starting from a query retrieving the custom fields build the group
678 * tree data for the relevant entity (entity is included in the query).
679 *
680 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
681 *
682 * @param array $groupTree (reference) group tree array which is being built
683 * @param string $query
684 * @param array $includedTables tables to include - required because the function (for historical reasons)
685 * iterates through the group tree
686 */
687 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables){
688 $dao = CRM_Core_DAO::executeQuery($query);
689 while ($dao->fetch()) {
690 foreach ($groupTree as $groupID => $group) {
691 if ($groupID === 'info') {
692 continue;
693 }
694 $table = $groupTree[$groupID]['table_name'];
695 //working from the groupTree instead of the table list means we have to iterate & exclude.
696 // this could possibly be re-written as other parts of the function have been refactored
697 // for now we just check if the given table is to be included in this function
698 if( !in_array($table, $includedTables)){
699 continue;
700 }
701 foreach ($group['fields'] as $fieldID => $dontCare) {
702 self::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
703 }
704 }
705 }
706 }
707
708 /**
709 * Build the entity-specific custom data into the group tree on a per-field basis
710 *
711 * @param object $dao object representing the custom field to be populated into the groupTree
712 * @param array $groupTree (reference) the group tree being build
713 * @param string $table table name
714 * @param unknown_type $groupID custom group ID
715 * @param unknown_type $fieldID custom field ID
716 */
717 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID){
718 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
719 $idName = "{$table}_id";
720 $fieldName = "{$table}_{$column}";
721 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
722 if ($dataType == 'File') {
723 if (isset($dao->$fieldName)) {
724 $config = CRM_Core_Config::singleton();
725 $fileDAO = new CRM_Core_DAO_File();
726 $fileDAO->id = $dao->$fieldName;
727
728 if ($fileDAO->find(TRUE)) {
729 $entityIDName = "{$table}_entity_id";
730 $customValue['id'] = $dao->$idName;
731 $customValue['data'] = $fileDAO->uri;
732 $customValue['fid'] = $fileDAO->id;
733 $customValue['fileURL'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
734 $customValue['displayURL'] = NULL;
735 $deleteExtra = ts('Are you sure you want to delete attached file.');
736 $deleteURL = array(
737 CRM_Core_Action::DELETE =>
738 array(
739 'name' => ts('Delete Attached File'),
740 'url' => 'civicrm/file',
741 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
742 'extra' =>
743 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&amp;confirmed=1\'; else return false;"',
744 ),
745 );
746 $customValue['deleteURL'] = CRM_Core_Action::formLink($deleteURL,
747 CRM_Core_Action::DELETE,
748 array(
749 'id' => $fileDAO->id,
750 'eid' => $dao->$entityIDName,
751 'fid' => $fieldID,
752 ),
753 ts('more'),
754 FALSE,
755 'file.manage.delete',
756 'File',
757 $fileDAO->id
758 );
759 $customValue['deleteURLArgs'] = CRM_Core_BAO_File::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id);
760 $customValue['fileName'] = CRM_Utils_File::cleanFileName(basename($fileDAO->uri));
761 if ($fileDAO->mime_type == "image/jpeg" ||
762 $fileDAO->mime_type == "image/pjpeg" ||
763 $fileDAO->mime_type == "image/gif" ||
764 $fileDAO->mime_type == "image/x-png" ||
765 $fileDAO->mime_type == "image/png"
766 ) {
767 $customValue['displayURL'] = $customValue['fileURL'];
768 $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile',
769 $fileDAO->id,
770 'entity_id',
771 'file_id'
772 );
773 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL) . $fileDAO->uri;
774 list($path) = CRM_Core_BAO_File::path($fileDAO->id, $entityId,
775 NULL, NULL
776 );
777 list($imageWidth, $imageHeight) = getimagesize($path);
778 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
779 $customValue['imageThumbWidth'] = $imageThumbWidth;
780 $customValue['imageThumbHeight'] = $imageThumbHeight;
781 }
782 }
783 }
784 else {
785 $customValue = array(
786 'id' => $dao->$idName,
787 'data' => '',
788 );
789 }
790 }
791 else {
792 $customValue = array(
793 'id' => $dao->$idName,
794 'data' => $dao->$fieldName,
795 );
796 }
797
798 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
799 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
800 }
801 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
802 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
803 }
804 else {
805 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
806 }
807 }
808
809 /**
810 * Get the group title.
811 *
812 * @param int $id id of group.
813 *
814 * @return string title
815 *
816 * @access public
817 * @static
818 *
819 */
820 public static function getTitle($id) {
821 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
822 }
823
824 /**
825 * Get custom group details for a group.
826 *
827 * An array containing custom group details (including their custom field) is returned.
828 *
829 * @param int $groupId - group id whose details are needed
830 * @param boolean $searchable - is this field searchable
831 * @param array $extends - which table does it extend if any
832 *
833 * @return array $groupTree - array consisting of all group and field details
834 *
835 * @access public
836 *
837 * @static
838 *
839 */
840 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
841 // create a new tree
842 $groupTree = array();
843 $select = $from = $where = $orderBy = '';
844
845 $tableData = array();
846
847 // using tableData to build the queryString
848 $tableData = array(
849 'civicrm_custom_field' =>
850 array(
851 'id',
852 'label',
853 'data_type',
854 'html_type',
855 'default_value',
856 'attributes',
857 'is_required',
858 'help_pre',
859 'help_post',
860 'options_per_line',
861 'is_searchable',
862 'start_date_years',
863 'end_date_years',
864 'is_search_range',
865 'date_format',
866 'time_format',
867 'note_columns',
868 'note_rows',
869 'column_name',
870 'is_view',
871 'option_group_id',
872 'in_selector',
873 ),
874 'civicrm_custom_group' =>
875 array(
876 'id',
877 'name',
878 'title',
879 'help_pre',
880 'help_post',
881 'collapse_display',
882 'collapse_adv_display',
883 'extends',
884 'extends_entity_column_value',
885 'table_name',
886 'is_multiple',
887 ),
888 );
889
890 // create select
891 $select = "SELECT";
892 $s = array();
893 foreach ($tableData as $tableName => $tableColumn) {
894 foreach ($tableColumn as $columnName) {
895 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
896 }
897 }
898 $select = 'SELECT ' . implode(', ', $s);
899 $params = array();
900 // from, where, order by
901 $from = " FROM civicrm_custom_field, civicrm_custom_group";
902 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
903 AND civicrm_custom_group.is_active = 1
904 AND civicrm_custom_field.is_active = 1 ";
905 if ($groupId) {
906 $params[1] = array($groupId, 'Integer');
907 $where .= " AND civicrm_custom_group.id = %1";
908 }
909
910 if ($searchable) {
911 $where .= " AND civicrm_custom_field.is_searchable = 1";
912 }
913
914 if ($inSelector) {
915 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
916 }
917
918 if ($extends) {
919 $clause = array();
920 foreach ($extends as $e) {
921 $clause[] = "civicrm_custom_group.extends = '$e'";
922 }
923 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
924
925 //include case activities customdata if case is enabled
926 if (in_array('Activity', $extends)) {
927 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
928 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
929 $params[2] = array(CRM_Core_DAO::VALUE_SEPARATOR, 'String');
930 }
931 }
932
933 // ensure that the user has access to these custom groups
934 $where .= " AND " . CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
935 'civicrm_custom_group.'
936 );
937
938 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
939
940 // final query string
941 $queryString = $select . $from . $where . $orderBy;
942
943 // dummy dao needed
944 $crmDAO = CRM_Core_DAO::executeQuery($queryString, $params);
945
946 // process records
947 while ($crmDAO->fetch()) {
948 $groupId = $crmDAO->civicrm_custom_group_id;
949 $fieldId = $crmDAO->civicrm_custom_field_id;
950
951 // create an array for groups if it does not exist
952 if (!array_key_exists($groupId, $groupTree)) {
953 $groupTree[$groupId] = array();
954 $groupTree[$groupId]['id'] = $groupId;
955
956 foreach ($tableData['civicrm_custom_group'] as $v) {
957 $fullField = "civicrm_custom_group_" . $v;
958
959 if ($v == 'id' || is_null($crmDAO->$fullField)) {
960 continue;
961 }
962
963 $groupTree[$groupId][$v] = $crmDAO->$fullField;
964 }
965
966 $groupTree[$groupId]['fields'] = array();
967 }
968
969 // add the fields now (note - the query row will always contain a field)
970 $groupTree[$groupId]['fields'][$fieldId] = array();
971 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
972
973 foreach ($tableData['civicrm_custom_field'] as $v) {
974 $fullField = "civicrm_custom_field_" . $v;
975 if ($v == 'id' || is_null($crmDAO->$fullField)) {
976 continue;
977 }
978 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
979 }
980 }
981
982 return $groupTree;
983 }
984
985 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
986 // for Group's
987 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
988
989 // get 'Tab' and 'Tab with table' groups
990 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
991 $customGroupDAO->whereAdd("is_active = 1");
992
993 // add whereAdd for entity type
994 self::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
995
996 $groups = array();
997
998 $permissionClause = CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW, NULL, TRUE);
999 $customGroupDAO->whereAdd($permissionClause);
1000
1001 // order by weight
1002 $customGroupDAO->orderBy('weight');
1003 $customGroupDAO->find();
1004
1005 // process each group with menu tab
1006 while ($customGroupDAO->fetch()) {
1007 $group = array();
1008 $group['id'] = $customGroupDAO->id;
1009 $group['path'] = $path;
1010 $group['title'] = "$customGroupDAO->title";
1011 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1012 $group['extra'] = array('gid' => $customGroupDAO->id);
1013 $group['table_name'] = $customGroupDAO->table_name;
1014 $groups[] = $group;
1015 }
1016
1017 return $groups;
1018 }
1019
1020 /**
1021 * Get the table name for the entity type
1022 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1023 * tableName is 'civicrm_contact'
1024 *
1025 * @param string $entityType what entity are we extending here ?
1026 *
1027 * @return string $tableName
1028 *
1029 * @access private
1030 * @static
1031 *
1032 */
1033 private static function _getTableName($entityType) {
1034 $tableName = '';
1035 switch ($entityType) {
1036 case 'Contact':
1037 case 'Individual':
1038 case 'Household':
1039 case 'Organization':
1040 $tableName = 'civicrm_contact';
1041 break;
1042
1043 case 'Contribution':
1044 $tableName = 'civicrm_contribution';
1045 break;
1046
1047 case 'Group':
1048 $tableName = 'civicrm_group';
1049 break;
1050 // DRAFTING: Verify if we cannot make it pluggable
1051
1052 case 'Activity':
1053 $tableName = 'civicrm_activity';
1054 break;
1055
1056 case 'Relationship':
1057 $tableName = 'civicrm_relationship';
1058 break;
1059
1060 case 'Membership':
1061 $tableName = 'civicrm_membership';
1062 break;
1063
1064 case 'Participant':
1065 $tableName = 'civicrm_participant';
1066 break;
1067
1068 case 'Event':
1069 $tableName = 'civicrm_event';
1070 break;
1071
1072 case 'Grant':
1073 $tableName = 'civicrm_grant';
1074 break;
1075 // need to add cases for Location, Address
1076 }
1077
1078 return $tableName;
1079 }
1080
1081 /**
1082 * Get a list of custom groups which extend a given entity type.
1083 * If there are custom-groups which only apply to certain subtypes,
1084 * those WILL be included.
1085 *
1086 * @param $entityType string
1087 * @return CRM_Core_DAO_CustomGroup
1088 */
1089 static function getAllCustomGroupsByBaseEntity($entityType) {
1090 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1091 self::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1092 return $customGroupDAO;
1093 }
1094
1095 /**
1096 * Add the whereAdd clause for the DAO depending on the type of entity
1097 * the custom group is extending.
1098 *
1099 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
1100 * @param string $entityType - what entity are we extending here ?
1101 *
1102 * @return void
1103 *
1104 * @access private
1105 * @static
1106 *
1107 */
1108 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1109 $addSubtypeClause = FALSE;
1110
1111 switch ($entityType) {
1112 case 'Contact':
1113 // if contact, get all related to contact
1114 $extendList = "'Contact','Individual','Household','Organization'";
1115 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1116 if (!$allSubtypes) {
1117 $addSubtypeClause = TRUE;
1118 }
1119 break;
1120
1121 case 'Individual':
1122 case 'Household':
1123 case 'Organization':
1124 // is I/H/O then get I/H/O and contact
1125 $extendList = "'Contact','$entityType'";
1126 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1127 if (!$allSubtypes) {
1128 $addSubtypeClause = TRUE;
1129 }
1130 break;
1131
1132 case 'Location':
1133 case 'Address':
1134 case 'Activity':
1135 case 'Contribution':
1136 case 'Membership':
1137 case 'Participant':
1138 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1139 break;
1140 }
1141
1142 if ($addSubtypeClause) {
1143 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact::getContactSubType($entityID) : FALSE;
1144
1145 if (!empty($csType)) {
1146 $subtypeClause = array();
1147 foreach ($csType as $subtype) {
1148 $subtype = CRM_Core_DAO::VALUE_SEPARATOR . $subtype . CRM_Core_DAO::VALUE_SEPARATOR;
1149 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1150 }
1151 $subtypeClause[] = "extends_entity_column_value IS NULL";
1152 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) . " )");
1153 }
1154 else {
1155 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1156 }
1157 }
1158 }
1159
1160 /**
1161 * Delete the Custom Group.
1162 *
1163 * @param $group object the DAO custom group object
1164 * @param $force boolean whether to force the deletion, even if there are custom fields
1165 *
1166 * @return boolean false if field exists for this group, true if group gets deleted.
1167 *
1168 * @access public
1169 * @static
1170 *
1171 */
1172 public static function deleteGroup($group, $force = FALSE) {
1173
1174 //check wheter this contain any custom fields
1175 $customField = new CRM_Core_DAO_CustomField();
1176 $customField->custom_group_id = $group->id;
1177 $customField->find();
1178
1179 // return early if there are custom fields and we're not
1180 // forcing the delete, otherwise delete the fields one by one
1181 while ($customField->fetch()) {
1182 if (!$force) {
1183 return FALSE;
1184 }
1185 CRM_Core_BAO_CustomField::deleteField($customField);
1186 }
1187
1188 // drop the table associated with this custom group
1189 CRM_Core_BAO_SchemaHandler::dropTable($group->table_name);
1190
1191 //delete custom group
1192 $group->delete();
1193
1194 CRM_Utils_Hook::post('delete', 'CustomGroup', $group->id, $group);
1195
1196 return TRUE;
1197 }
1198
1199 static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action::NONE) {
1200 foreach ($groupTree as $id => $group) {
1201 if (!isset($group['fields'])) {
1202 continue;
1203 }
1204 $groupId = CRM_Utils_Array::value('id', $group);
1205 foreach ($group['fields'] as $field) {
1206 if (CRM_Utils_Array::value('element_value', $field) !== NULL) {
1207 $value = $field['element_value'];
1208 }
1209 elseif (CRM_Utils_Array::value('default_value', $field) !== NULL &&
1210 ($action != CRM_Core_Action::UPDATE ||
1211 // CRM-7548
1212 !array_key_exists('element_value', $field)
1213 )
1214 ) {
1215 $value = $viewMode ? NULL : $field['default_value'];
1216 }
1217 else {
1218 continue;
1219 }
1220
1221 $fieldId = $field['id'];
1222 $elementName = $field['element_name'];
1223 switch ($field['html_type']) {
1224 case 'Multi-Select':
1225 case 'AdvMulti-Select':
1226 case 'CheckBox':
1227 $defaults[$elementName] = array();
1228 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($field['id'], $inactiveNeeded);
1229 if ($viewMode) {
1230 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1));
1231 if (isset($value)) {
1232 foreach ($customOption as $customValue => $customLabel) {
1233 if (in_array($customValue, $checkedData)) {
1234 if ($field['html_type'] == 'CheckBox') {
1235 $defaults[$elementName][$customValue] = 1;
1236 }
1237 else {
1238 $defaults[$elementName][$customValue] = $customValue;
1239 }
1240 }
1241 else {
1242 $defaults[$elementName][$customValue] = 0;
1243 }
1244 }
1245 }
1246 }
1247 else {
1248 if (isset($field['customValue']['data'])) {
1249 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($field['customValue']['data'], 1, -1));
1250 foreach ($customOption as $val) {
1251 if (in_array($val['value'], $checkedData)) {
1252 if ($field['html_type'] == 'CheckBox') {
1253 $defaults[$elementName][$val['value']] = 1;
1254 }
1255 else {
1256 $defaults[$elementName][$val['value']] = $val['value'];
1257 }
1258 }
1259 else {
1260 $defaults[$elementName][$val['value']] = 0;
1261 }
1262 }
1263 }
1264 else {
1265 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($value, 1, -1));
1266 foreach ($customOption as $val) {
1267 if (in_array($val['value'], $checkedValue)) {
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 }
1276 }
1277 }
1278 break;
1279
1280 case 'Select Date':
1281 if (isset($value)) {
1282 if (empty($field['time_format'])) {
1283 list($defaults[$elementName]) = CRM_Utils_Date::setDateDefaults($value, NULL,
1284 $field['date_format']
1285 );
1286 }
1287 else {
1288 $timeElement = $elementName . '_time';
1289 if (substr($elementName, -1) == ']') {
1290 $timeElement = substr($elementName, 0, -1) . '_time]';
1291 }
1292 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1293 }
1294 }
1295 break;
1296
1297 case 'Multi-Select Country':
1298 case 'Multi-Select State/Province':
1299 if (isset($value)) {
1300 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1301 foreach ($checkedValue as $val) {
1302 if ($val) {
1303 $defaults[$elementName][$val] = $val;
1304 }
1305 }
1306 }
1307 break;
1308
1309 case 'Select Country':
1310 if ($value) {
1311 $defaults[$elementName] = $value;
1312 }
1313 else {
1314 $config = CRM_Core_Config::singleton();
1315 $defaults[$elementName] = $config->defaultContactCountry;
1316 }
1317 break;
1318
1319 case 'Autocomplete-Select':
1320 $hiddenEleName = $elementName . '_id';
1321 if (substr($elementName, -1) == ']') {
1322 $hiddenEleName = substr($elementName, 0, -1) . '_id]';
1323 }
1324 if ($field['data_type'] == "ContactReference") {
1325 if (is_numeric($value)) {
1326 $defaults[$hiddenEleName] = $value;
1327 $defaults[$elementName] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1328 }
1329 }
1330 else {
1331 $defaults[$elementName] = $value;
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 * @param object $form page object
1775 * @param array $groupTree associated array
1776 * @param boolean $returnCount true if customValue count needs to be returned
1777 */
1778 static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1779 $details = array();
1780 foreach ($groupTree as $key => $group) {
1781 if ($key === 'info') {
1782 continue;
1783 }
1784
1785 foreach ($group['fields'] as $k => $properties) {
1786 $groupID = $group['id'];
1787 if (!empty($properties['customValue'])) {
1788 foreach ($properties['customValue'] as $values) {
1789 if (!empty($customValueId) && $customValueId != $values['id']) {
1790 continue;
1791 }
1792 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array::value('title', $group);
1793 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array::value('name', $group);
1794 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array::value('help_pre', $group);
1795 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array::value('help_post', $group);
1796 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array::value('collapse_display', $group);
1797 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array::value('collapse_adv_display', $group);
1798 $details[$groupID][$values['id']]['fields'][$k] = array('field_title' => CRM_Utils_Array::value('label', $properties),
1799 'field_type' => CRM_Utils_Array::value('html_type',
1800 $properties
1801 ),
1802 'field_data_type' => CRM_Utils_Array::value('data_type',
1803 $properties
1804 ),
1805 'field_value' => self::formatCustomValues($values,
1806 $properties
1807 ),
1808 'options_per_line' => CRM_Utils_Array::value('options_per_line',
1809 $properties
1810 ),
1811 );
1812 // also return contact reference contact id if user has view all or edit all contacts perm
1813 if ((CRM_Core_Permission::check('view all contacts') || CRM_Core_Permission::check('edit all contacts'))
1814 && $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] == 'ContactReference'
1815 ) {
1816 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array::value('data', $values);
1817 }
1818 }
1819 }
1820 else {
1821 $details[$groupID][0]['title'] = CRM_Utils_Array::value('title', $group);
1822 $details[$groupID][0]['name'] = CRM_Utils_Array::value('name', $group);
1823 $details[$groupID][0]['help_pre'] = CRM_Utils_Array::value('help_pre', $group);
1824 $details[$groupID][0]['help_post'] = CRM_Utils_Array::value('help_post', $group);
1825 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array::value('collapse_display', $group);
1826 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array::value('collapse_adv_display', $group);
1827 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array::value('label', $properties));
1828 }
1829 }
1830 }
1831
1832 if ($returnCount) {
1833 //return a single value count if group id is passed to function
1834 //else return a groupId and count mapped array
1835 if (!empty($gID)){
1836 return count($details[$gID]);
1837 }
1838 else {
1839 $countValue = array();
1840 foreach( $details as $key => $value ) {
1841 $countValue[$key] = count($details[$key]);
1842 }
1843 return $countValue;
1844 }
1845 }
1846 else {
1847 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1848 return $details;
1849 }
1850 }
1851
1852 /**
1853 * Format custom value according to data, view mode
1854 *
1855 * @param array $values associated array of custom values
1856 * @param array $field associated array
1857 * @param boolean $dncOptionPerLine true if optionPerLine should not be consider
1858 *
1859 */
1860 static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1861 $value = $values['data'];
1862
1863 //changed isset CRM-4601
1864 if (CRM_Utils_System::isNull($value)) {
1865 return;
1866 }
1867
1868 $htmlType = CRM_Utils_Array::value('html_type', $field);
1869 $dataType = CRM_Utils_Array::value('data_type', $field);
1870 $option_group_id = CRM_Utils_Array::value('option_group_id', $field);
1871 $timeFormat = CRM_Utils_Array::value('time_format', $field);
1872 $optionPerLine = CRM_Utils_Array::value('options_per_line', $field);
1873
1874 $freezeString = "";
1875 $freezeStringChecked = "";
1876
1877 switch ($dataType) {
1878 case 'Date':
1879 $customTimeFormat = '';
1880 $customFormat = NULL;
1881
1882 switch ($timeFormat) {
1883 case 1:
1884 $customTimeFormat = '%l:%M %P';
1885 break;
1886
1887 case 2:
1888 $customTimeFormat = '%H:%M';
1889 break;
1890
1891 default:
1892 // if time is not selected remove time from value
1893 $value = substr($value, 0, 10);
1894 }
1895
1896 $supportableFormats = array(
1897 'mm/dd' => "%B %E%f $customTimeFormat",
1898 'dd-mm' => "%E%f %B $customTimeFormat",
1899 'yy' => "%Y $customTimeFormat",
1900 'M yy' => "%b %Y $customTimeFormat",
1901 'yy-mm' => "%Y-%m $customTimeFormat"
1902 );
1903
1904 if ($format = CRM_Utils_Array::value('date_format', $field)) {
1905 if (array_key_exists($format, $supportableFormats)) {
1906 $customFormat = $supportableFormats["$format"];
1907 }
1908 }
1909
1910 $retValue = CRM_Utils_Date::customFormat($value, $customFormat);
1911 break;
1912
1913 case 'Boolean':
1914 if ($value == '1') {
1915 $retValue = $freezeStringChecked . ts('Yes') . "\n";
1916 }
1917 else {
1918 $retValue = $freezeStringChecked . ts('No') . "\n";
1919 }
1920 break;
1921
1922 case 'Link':
1923 if ($value) {
1924 $retValue = CRM_Utils_System::formatWikiURL($value);
1925 }
1926 break;
1927
1928 case 'File':
1929 $retValue = $values;
1930 break;
1931
1932 case 'ContactReference':
1933 if (!empty($values['data'])) {
1934 $retValue = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
1935 }
1936 break;
1937
1938 case 'Memo':
1939 $retValue = $value;
1940 break;
1941
1942 case 'Float':
1943 if ($htmlType == 'Text') {
1944 $retValue = (float)$value;
1945 break;
1946 }
1947 case 'Money':
1948 if ($htmlType == 'Text') {
1949 $retValue = CRM_Utils_Money::format($value, NULL, '%a');
1950 break;
1951 }
1952 case 'String':
1953 case 'Int':
1954 if (in_array($htmlType, array('Text', 'TextArea'))) {
1955 $retValue = $value;
1956 break;
1957 }
1958 // note that if its not text / textarea, the code falls thru and executes
1959 // the below case also
1960 case 'StateProvince':
1961 case 'Country':
1962 $options = array();
1963 $coDAO = NULL;
1964
1965 //added check for Multi-Select in the below if-statement
1966 $customData[] = $value;
1967
1968 //form custom data for multiple-valued custom data
1969 switch ($htmlType) {
1970 case 'Multi-Select Country':
1971 case 'Select Country':
1972 $customData = $value;
1973 if (!is_array($value)) {
1974 $customData = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1975 }
1976 $query = "
1977 SELECT id as value, name as label
1978 FROM civicrm_country";
1979 $coDAO = CRM_Core_DAO::executeQuery($query);
1980 break;
1981
1982 case 'Select State/Province':
1983 case 'Multi-Select State/Province':
1984 $customData = $value;
1985 if (!is_array($value)) {
1986 $customData = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1987 }
1988
1989 $query = "
1990 SELECT id as value, name as label
1991 FROM civicrm_state_province";
1992 $coDAO = CRM_Core_DAO::executeQuery($query);
1993 break;
1994
1995 case 'Select':
1996 $customData = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1997 if ($option_group_id) {
1998 $options = CRM_Core_BAO_OptionValue::getOptionValuesAssocArray($option_group_id);
1999 }
2000 break;
2001
2002 case 'CheckBox':
2003 case 'AdvMulti-Select':
2004 case 'Multi-Select':
2005 $customData = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2006 default:
2007 if ($option_group_id) {
2008 $options = CRM_Core_BAO_OptionValue::getOptionValuesAssocArray($option_group_id);
2009 }
2010 }
2011
2012 if (is_object($coDAO)) {
2013 while ($coDAO->fetch()) {
2014 if ($dataType == 'Country') {
2015 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2016 // and already extracted to .pot files.
2017 $options[$coDAO->value] = ts($coDAO->label, array('context' => 'country'));
2018 }
2019 elseif ($dataType == 'StateProvince') {
2020 $options[$coDAO->value] = ts($coDAO->label, array('context' => 'province'));
2021 }
2022 else {
2023 $options[$coDAO->value] = $coDAO->label;
2024 }
2025 }
2026 }
2027
2028 CRM_Utils_Hook::customFieldOptions($field['id'], $options, FALSE);
2029
2030 $retValue = NULL;
2031 foreach ($options as $optionValue => $optionLabel) {
2032 if ($dataType == 'Money') {
2033 foreach ($customData as $k => $v) {
2034 $customData[] = CRM_Utils_Money::format($v, NULL, '%a');
2035 }
2036 }
2037
2038 //to show only values that are checked
2039 if (in_array((string) $optionValue, $customData)) {
2040 $checked = in_array($optionValue, $customData) ? $freezeStringChecked : $freezeString;
2041 if (!$optionPerLine || $dncOptionPerLine) {
2042 if ($retValue) {
2043 $retValue .= ", ";
2044 }
2045 $retValue .= $checked . $optionLabel;
2046 }
2047 else {
2048 $retValue[] = $checked . $optionLabel;
2049 }
2050 }
2051 }
2052 break;
2053 }
2054
2055 //special case for option per line formatting
2056 if ($optionPerLine > 1 && is_array($retValue)) {
2057 $rowCounter = 0;
2058 $fieldCounter = 0;
2059 $displayValues = array();
2060 $displayString = '';
2061 foreach ($retValue as $val) {
2062 if ($displayString) {
2063 $displayString .= ", ";
2064 }
2065
2066 $displayString .= $val;
2067 $rowCounter++;
2068 $fieldCounter++;
2069
2070 if (($rowCounter == $optionPerLine) || ($fieldCounter == count($retValue))) {
2071 $displayValues[] = $displayString;
2072 $displayString = '';
2073 $rowCounter = 0;
2074 }
2075 }
2076 $retValue = $displayValues;
2077 }
2078
2079 $retValue = isset($retValue) ? $retValue : NULL;
2080 return $retValue;
2081 }
2082
2083 /**
2084 * Get the custom group titles by custom field ids.
2085 *
2086 * @param array $fieldIds - array of custom field ids.
2087 *
2088 * @return array $groupLabels - array consisting of groups and fields labels with ids.
2089 * @access public
2090 */
2091 public static function getGroupTitles($fieldIds) {
2092 if (!is_array($fieldIds) && empty($fieldIds)) {
2093 return;
2094 }
2095
2096 $groupLabels = array();
2097 $fIds = "(" . implode(',', $fieldIds) . ")";
2098
2099 $query = "
2100 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2101 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2102 FROM civicrm_custom_group, civicrm_custom_field
2103 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2104 AND civicrm_custom_field.id IN {$fIds}";
2105
2106 $dao = CRM_Core_DAO::executeQuery($query);
2107 while ($dao->fetch()) {
2108 $groupLabels[$dao->fieldID] = array(
2109 'fieldID' => $dao->fieldID,
2110 'fieldLabel' => $dao->fieldLabel,
2111 'groupID' => $dao->groupID,
2112 'groupTitle' => $dao->groupTitle,
2113 );
2114 }
2115
2116 return $groupLabels;
2117 }
2118
2119 static function dropAllTables() {
2120 $query = "SELECT table_name FROM civicrm_custom_group";
2121 $dao = CRM_Core_DAO::executeQuery($query);
2122
2123 while ($dao->fetch()) {
2124 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2125 CRM_Core_DAO::executeQuery($query);
2126 }
2127 }
2128
2129 /**
2130 * Check whether custom group is empty or not.
2131 *
2132 * @param int $gID - custom group id.
2133 *
2134 * @return boolean true if empty otherwise false.
2135 * @access public
2136 */
2137 static function isGroupEmpty($gID) {
2138 if (!$gID) {
2139 return;
2140 }
2141
2142 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
2143 $gID,
2144 'table_name'
2145 );
2146
2147 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2148 $value = CRM_Core_DAO::singleValueQuery($query);
2149
2150 if (empty($value)) {
2151 return TRUE;
2152 }
2153
2154 return FALSE;
2155 }
2156
2157 /**
2158 * Get the list of types for objects that a custom group extends to.
2159 *
2160 * @param array $types - var which should have the list appended.
2161 *
2162 * @return array of types.
2163 * @access public
2164 */
2165 static function getExtendedObjectTypes(&$types = array( )) {
2166 static $flag = FALSE, $objTypes = array();
2167
2168 if (!$flag) {
2169 $extendObjs = array();
2170 CRM_Core_OptionValue::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2171
2172 foreach ($extendObjs as $ovId => $ovValues) {
2173 if ($ovValues['description']) {
2174 // description is expected to be a callback func to subtypes
2175 list($callback, $args) = explode(';', trim($ovValues['description']));
2176
2177 if (empty($args)) {
2178 $args = array();
2179 }
2180
2181 if (!is_array($args)) {
2182 CRM_Core_Error::fatal('Arg is not of type array');
2183 }
2184
2185 list($className) = explode('::', $callback);
2186 require_once (str_replace('_',DIRECTORY_SEPARATOR, $className) . '.php');
2187
2188 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2189 }
2190 }
2191 $flag = TRUE;
2192 }
2193
2194 $types = array_merge($types, $objTypes);
2195 return $objTypes;
2196 }
2197
2198 static function hasReachedMaxLimit($customGroupId, $entityId) {
2199 //check whether the group is multiple
2200 $isMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2201 $isMultiple = ($isMultiple) ? TRUE : FALSE;
2202 $hasReachedMax = FALSE;
2203 if ($isMultiple &&
2204 ($maxMultiple = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))) {
2205 if (!$maxMultiple) {
2206 $hasReachedMax = FALSE;
2207 } else {
2208 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2209 //count the number of entries for a entity
2210 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2211 $params = array(1 => array($entityId, 'Integer'));
2212 $count = CRM_Core_DAO::singleValueQuery($sql, $params);
2213
2214 if ($count >= $maxMultiple) {
2215 $hasReachedMax = TRUE;
2216 }
2217 }
2218 }
2219 return $hasReachedMax;
2220 }
2221
2222 static function getMultipleFieldGroup() {
2223 $multipleGroup = array();
2224 $dao = new CRM_Core_DAO_CustomGroup();
2225 $dao->is_multiple = 1 ;
2226 $dao->find();
2227 while($dao->fetch()) {
2228 $multipleGroup[$dao->id] = $dao->title;
2229 }
2230 return $multipleGroup;
2231 }
2232 }
2233