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