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