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