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