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