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