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