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