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