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