3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * Business object for managing custom data groups
40 class CRM_Core_BAO_CustomGroup
extends CRM_Core_DAO_CustomGroup
{
45 function __construct() {
46 parent
::__construct();
50 * takes an associative array and creates a custom group object
52 * This function is invoked from within the web form layer and also from the api layer
54 * @param array $params (reference) an assoc array of name/value pairs
56 * @return object CRM_Core_DAO_CustomGroup object
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'];
65 if (in_array($params['extends'][0],
68 'ParticipantEventName',
69 'ParticipantEventType',
72 $group->extends = 'Participant';
75 $group->extends = $params['extends'][0];
78 $group->extends_entity_column_id
= 'null';
80 $params['extends'][0] == 'ParticipantRole' ||
81 $params['extends'][0] == 'ParticipantEventName' ||
82 $params['extends'][0] == 'ParticipantEventType'
84 $group->extends_entity_column_id
=
85 CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $params['extends'][0], 'value', 'name');
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'];
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);
99 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
100 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType . CRM_Core_DAO
::VALUE_SEPARATOR
;
104 $extendsChildType = 'null';
106 $group->extends_entity_column_value
= $extendsChildType;
108 if (isset($params['id'])) {
109 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
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);
119 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
120 $params['max_multiple'] >= '0'
121 ) ?
$params['max_multiple'] : 'null' : 'null';
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',
132 if ((!empty($params['is_multiple']) ||
$isMultiple) &&
133 ($params['is_multiple'] != $isMultiple)
135 $oldTableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
142 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
143 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
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);
150 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
153 if (isset($params['table_name'])) {
154 $tableName = $params['table_name'];
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)));
163 if (array_key_exists('is_reserved', $params)) {
164 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
166 $op = isset($params['id']) ?
'edit' : 'create';
167 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
169 // enclose the below in a transaction
170 $transaction = new CRM_Core_Transaction();
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}";
178 $group->table_name
= $tableName;
179 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
185 // now create the table associated with this group
186 self
::createTable($group);
188 elseif ($oldTableName) {
189 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($oldTableName, CRM_Utils_Array
::value('is_multiple', $params));
192 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
193 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
197 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends'][0]));
199 $transaction->commit();
202 CRM_Utils_System
::flushCache();
205 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
208 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
215 * Takes a bunch of params that are needed to match certain criteria and
216 * retrieves the relevant objects. Typically the valid params are only
217 * contact_id. We'll tweak this function to be more full featured over a period
218 * of time. This is the inverse function of create. It also stores all the retrieved
219 * values in the default array
221 * @param array $params (reference ) an assoc array of name/value pairs
222 * @param array $defaults (reference ) an assoc array to hold the flattened values
224 * @return object CRM_Core_DAO_CustomGroup object
228 static function retrieve(&$params, &$defaults) {
229 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
233 * update the is_active flag in the db
235 * @param int $id id of the database record
236 * @param boolean $is_active value we want to set the is_active field
238 * @return Object DAO object on sucess, null otherwise
242 static function setIsActive($id, $is_active) {
244 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
247 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
250 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
254 * Determine if given entity (sub)type has any custom groups
256 * @param string $extends e.g. "Individual", "Activity"
257 * @param int $columnId e.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id
258 * @param string $columnValue e.g. "Student" or "3" or "3\05"; see extends_entity_column_value
262 public static function hasCustomGroup($extends, $columnId, $columnValue) {
263 $dao = new CRM_Core_DAO_CustomGroup();
264 $dao->extends = $extends;
265 $dao->extends_entity_column_id
= $columnId;
266 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
267 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
268 //$dao->extends_entity_column_value = $columnValue;
269 return $dao->find() ?
TRUE : FALSE;
273 * Determine if there are any CustomGroups for the given $activityTypeId.
274 * If none found, create one.
276 * @param int $activityTypeId
277 * @return bool TRUE if a group is found or created; FALSE on error
279 public static function autoCreateByActivityType($activityTypeId) {
280 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
283 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
286 'extends' => 'Activity',
287 'extends_entity_column_id' => NULL,
288 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
289 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
293 $result = civicrm_api('CustomGroup', 'create', $params);
294 return ! $result['is_error'];
298 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
299 * This may also include entity specific data values.
301 * An array containing all custom groups and their custom fields is returned.
303 * @param string $entityType - of the contact whose contact type is needed
304 * @param object $form - not used but required
305 * @param null $entityID
306 * @param null $groupID
307 * @param string $subType
308 * @param string $subName
309 * @param boolean $fromCache
311 * @param null $onlySubType
313 * @internal param int $entityId - optional - id of entity if we need to populate the tree with custom values.
314 * @internal param int $groupId - optional group id (if we need it for a single group only)
315 * - if groupId is 0 it gets for inline groups only
316 * - if groupId is -1 we get for all groups
317 * @return array $groupTree - array The returned array is keyed by group id and has the custom group table fields
318 * and a subkey 'fields' holding the specific custom fields.
319 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
320 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
322 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
323 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
324 * With caching the performance impact would be small & the function would be cleaner
330 public static function &getTree(
341 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
345 $strSelect = $strFrom = $strWhere = $orderBy = '';
346 $tableData = array();
348 // using tableData to build the queryString
350 'civicrm_custom_field' =>
371 'civicrm_custom_group' =>
382 'extends_entity_column_id',
383 'extends_entity_column_value',
390 foreach ($tableData as $tableName => $tableColumn) {
391 foreach ($tableColumn as $columnName) {
392 $alias = $tableName . "_" . $columnName;
393 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
396 $strSelect = "SELECT " . implode(', ', $select);
398 // from, where, order by
400 FROM civicrm_custom_group
401 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
404 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
405 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
$entityType == 'Household') {
406 $in = "'$entityType', 'Contact'";
408 elseif (strpos($entityType, "'") !== FALSE) {
409 // this allows the calling function to send in multiple entity types
414 $in = "'$entityType'";
419 if (is_array($subType)) {
420 $subType = implode(',', $subType);
422 if (strpos($subType, ',')) {
423 $subTypeParts = explode(',', $subType);
424 $subTypeClauses = array();
425 foreach ($subTypeParts as $subTypePart) {
426 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
427 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
431 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
434 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
438 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
441 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
444 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
445 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
450 WHERE civicrm_custom_group.is_active = 1
451 AND civicrm_custom_field.is_active = 1
452 AND civicrm_custom_group.extends IN ($in)
456 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
461 WHERE civicrm_custom_group.is_active = 1
462 AND civicrm_custom_field.is_active = 1
463 AND civicrm_custom_group.extends IN ($in)
464 AND civicrm_custom_group.extends_entity_column_value IS NULL
470 // since we want a specific group id we add it to the where clause
471 $strWhere .= " AND civicrm_custom_group.id = %1";
472 $params[1] = array($groupID, 'Integer');
475 // since groupID is false we need to show all Inline groups
476 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
479 // ensure that the user has access to these custom groups
480 $strWhere .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
481 'civicrm_custom_group.'
485 ORDER BY civicrm_custom_group.weight,
486 civicrm_custom_group.title,
487 civicrm_custom_field.weight,
488 civicrm_custom_field.label
491 // final query string
492 $queryString = "$strSelect $strFrom $strWhere $orderBy";
494 // lets see if we can retrieve the groupTree from cache
495 $cacheString = $queryString;
496 if ( $groupID > 0 ) {
497 $cacheString .= "_{$groupID}";
499 $cacheString .= "_Inline";
502 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
503 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
504 $cache = CRM_Utils_Cache
::singleton();
505 $tablesWithEntityData = array();
507 $groupTree = $cache->get($cacheKey);
508 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
511 if (empty($groupTree)) {
512 $groupTree = $multipleFieldGroups =array();
513 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
514 $customValueTables = array();
517 while ($crmDAO->fetch()) {
519 $groupID = $crmDAO->civicrm_custom_group_id
;
520 $fieldId = $crmDAO->civicrm_custom_field_id
;
521 if($crmDAO->civicrm_custom_group_is_multiple
){
522 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
524 // create an array for groups if it does not exist
525 if (!array_key_exists($groupID, $groupTree)) {
526 $groupTree[$groupID] = array();
527 $groupTree[$groupID]['id'] = $groupID;
529 // populate the group information
530 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
531 $fullFieldName = "civicrm_custom_group_$fieldName";
532 if ($fieldName == 'id' ||
533 is_null($crmDAO->$fullFieldName)
538 if ($fieldName == 'extends_entity_column_value' && $subType) {
539 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
541 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
543 $groupTree[$groupID]['fields'] = array();
545 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
548 // add the fields now (note - the query row will always contain a field)
549 // we only reset this once, since multiple values come is as multiple rows
550 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
551 $groupTree[$groupID]['fields'][$fieldId] = array();
554 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
555 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
556 // populate information for a custom field
557 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
558 $fullFieldName = "civicrm_custom_field_$fieldName";
559 if ($fieldName == 'id' ||
560 is_null($crmDAO->$fullFieldName)
564 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
568 if (!empty($customValueTables)) {
569 $groupTree['info'] = array('tables' => $customValueTables);
572 $cache->set($cacheKey, $groupTree);
573 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
575 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
576 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
577 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
578 $singleFieldTables = array();
579 // now that we have all the groups and fields, lets get the values
580 // since we need to know the table and field names
581 // add info to groupTree
583 if (isset($groupTree['info']) && !empty($groupTree['info']) && !empty($groupTree['info']['tables'])) {
584 $select = $from = $where = array();
585 $groupTree['info']['where'] = NULL;
587 foreach ($groupTree['info']['tables'] as $table => $fields) {
588 $groupTree['info']['from'][] = $table;
589 $select = array("{$table}.id as {$table}_id",
590 "{$table}.entity_id as {$table}_entity_id");
591 foreach ($fields as $column => $dontCare) {
592 $select[] = "{$table}.{$column} as {$table}_{$column}";
594 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
596 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
597 if(in_array($table, $multipleFieldGroups) && self
::customGroupDataExistsForEntity($entityID, $table)){
598 $entityMultipleSelectClauses[$table] = $select;
601 $singleFieldTables[] = $table;
602 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
607 if ($entityID && !empty($singleFieldTables)) {
608 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
610 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
611 if(!empty($multipleFieldTablesWithEntityData)){
612 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
620 * Check whether the custom group has any data for the given entity.
623 * @param integer $entityID id of entity for whom we are checking data for
624 * @param string $table table that we are checking
626 * @param bool $getCount
628 * @return boolean does this entity have data in this custom table
630 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE){
634 WHERE entity_id = $entityID
636 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
638 return $recordExists;
640 return $recordExists ?
TRUE : FALSE;
644 * Build the group tree for Custom fields which are not 'is_multiple'
646 * The combination of all these fields in one query with a 'using' join was not working for
647 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
648 * mechanism as it seemed to be acceptable in this context
650 * @param array $groupTree (reference) group tree array which is being built
651 * @param integer $entityID id of entity for whom the tree is being build up.
652 * @param array $entitySingleSelectClauses array of select clauses relevant to the entity
653 * @param array $singleFieldTablesWithEntityData array of tables in which this entity has data
655 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData){
656 $select = implode(', ', $entitySingleSelectClauses);
657 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
658 foreach ($singleFieldTablesWithEntityData as $table) {
659 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
665 WHERE first.entity_id = $entityID
667 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
671 * Build the group tree for Custom fields which are 'is_multiple'
673 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
675 * @param array $groupTree (reference) group tree array which is being built
676 * @param integer $entityID id of entity for whom the tree is being build up.
677 * @param array $entityMultipleSelectClauses array of select clauses relevant to the entity
678 * @param array $multipleFieldTablesWithEntityData array of tables in which this entity has data
680 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData){
681 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
682 $select = implode(',', $selectClauses);
686 WHERE entity_id = $entityID
688 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
693 * Build the tree entity data - starting from a query retrieving the custom fields build the group
694 * tree data for the relevant entity (entity is included in the query).
696 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
698 * @param array $groupTree (reference) group tree array which is being built
699 * @param string $query
700 * @param array $includedTables tables to include - required because the function (for historical reasons)
701 * iterates through the group tree
703 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables){
704 $dao = CRM_Core_DAO
::executeQuery($query);
705 while ($dao->fetch()) {
706 foreach ($groupTree as $groupID => $group) {
707 if ($groupID === 'info') {
710 $table = $groupTree[$groupID]['table_name'];
711 //working from the groupTree instead of the table list means we have to iterate & exclude.
712 // this could possibly be re-written as other parts of the function have been refactored
713 // for now we just check if the given table is to be included in this function
714 if( !in_array($table, $includedTables)){
717 foreach ($group['fields'] as $fieldID => $dontCare) {
718 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
725 * Build the entity-specific custom data into the group tree on a per-field basis
727 * @param object $dao object representing the custom field to be populated into the groupTree
728 * @param array $groupTree (reference) the group tree being build
729 * @param string $table table name
730 * @param unknown_type $groupID custom group ID
731 * @param unknown_type $fieldID custom field ID
733 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID){
734 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
735 $idName = "{$table}_id";
736 $fieldName = "{$table}_{$column}";
737 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
738 if ($dataType == 'File') {
739 if (isset($dao->$fieldName)) {
740 $config = CRM_Core_Config
::singleton();
741 $fileDAO = new CRM_Core_DAO_File();
742 $fileDAO->id
= $dao->$fieldName;
744 if ($fileDAO->find(TRUE)) {
745 $entityIDName = "{$table}_entity_id";
746 $customValue['id'] = $dao->$idName;
747 $customValue['data'] = $fileDAO->uri
;
748 $customValue['fid'] = $fileDAO->id
;
749 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
750 $customValue['displayURL'] = NULL;
751 $deleteExtra = ts('Are you sure you want to delete attached file.');
753 CRM_Core_Action
::DELETE
=>
755 'name' => ts('Delete Attached File'),
756 'url' => 'civicrm/file',
757 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
759 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
762 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
763 CRM_Core_Action
::DELETE
,
765 'id' => $fileDAO->id
,
766 'eid' => $dao->$entityIDName,
771 'file.manage.delete',
775 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
776 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
777 if ($fileDAO->mime_type
== "image/jpeg" ||
778 $fileDAO->mime_type
== "image/pjpeg" ||
779 $fileDAO->mime_type
== "image/gif" ||
780 $fileDAO->mime_type
== "image/x-png" ||
781 $fileDAO->mime_type
== "image/png"
783 $customValue['displayURL'] = $customValue['fileURL'];
784 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
789 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) . $fileDAO->uri
;
790 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId,
793 if ($path && file_exists($path)) {
794 list($imageWidth, $imageHeight) = getimagesize($path);
795 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
796 $customValue['imageThumbWidth'] = $imageThumbWidth;
797 $customValue['imageThumbHeight'] = $imageThumbHeight;
803 $customValue = array(
804 'id' => $dao->$idName,
810 $customValue = array(
811 'id' => $dao->$idName,
812 'data' => $dao->$fieldName,
816 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
817 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
819 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
820 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
823 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
828 * Get the group title.
830 * @param int $id id of group.
832 * @return string title
838 public static function getTitle($id) {
839 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
843 * Get custom group details for a group.
845 * An array containing custom group details (including their custom field) is returned.
847 * @param int $groupId - group id whose details are needed
848 * @param boolean $searchable - is this field searchable
849 * @param array $extends - which table does it extend if any
851 * @param null $inSelector
853 * @return array $groupTree - array consisting of all group and field details
859 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
861 $groupTree = array();
862 $select = $from = $where = $orderBy = '';
864 $tableData = array();
866 // using tableData to build the queryString
868 'civicrm_custom_field' =>
893 'civicrm_custom_group' =>
901 'collapse_adv_display',
903 'extends_entity_column_value',
912 foreach ($tableData as $tableName => $tableColumn) {
913 foreach ($tableColumn as $columnName) {
914 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
917 $select = 'SELECT ' . implode(', ', $s);
919 // from, where, order by
920 $from = " FROM civicrm_custom_field, civicrm_custom_group";
921 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
922 AND civicrm_custom_group.is_active = 1
923 AND civicrm_custom_field.is_active = 1 ";
925 $params[1] = array($groupId, 'Integer');
926 $where .= " AND civicrm_custom_group.id = %1";
930 $where .= " AND civicrm_custom_field.is_searchable = 1";
934 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
939 foreach ($extends as $e) {
940 $clause[] = "civicrm_custom_group.extends = '$e'";
942 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
944 //include case activities customdata if case is enabled
945 if (in_array('Activity', $extends)) {
946 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
947 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
948 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
952 // ensure that the user has access to these custom groups
953 $where .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
954 'civicrm_custom_group.'
957 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
959 // final query string
960 $queryString = $select . $from . $where . $orderBy;
963 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
966 while ($crmDAO->fetch()) {
967 $groupId = $crmDAO->civicrm_custom_group_id
;
968 $fieldId = $crmDAO->civicrm_custom_field_id
;
970 // create an array for groups if it does not exist
971 if (!array_key_exists($groupId, $groupTree)) {
972 $groupTree[$groupId] = array();
973 $groupTree[$groupId]['id'] = $groupId;
975 foreach ($tableData['civicrm_custom_group'] as $v) {
976 $fullField = "civicrm_custom_group_" . $v;
978 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
982 $groupTree[$groupId][$v] = $crmDAO->$fullField;
985 $groupTree[$groupId]['fields'] = array();
988 // add the fields now (note - the query row will always contain a field)
989 $groupTree[$groupId]['fields'][$fieldId] = array();
990 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
992 foreach ($tableData['civicrm_custom_field'] as $v) {
993 $fullField = "civicrm_custom_field_" . $v;
994 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
997 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1005 * @param $entityType
1007 * @param string $cidToken
1011 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1013 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1015 // get 'Tab' and 'Tab with table' groups
1016 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1017 $customGroupDAO->whereAdd("is_active = 1");
1019 // add whereAdd for entity type
1020 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1024 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1025 $customGroupDAO->whereAdd($permissionClause);
1028 $customGroupDAO->orderBy('weight');
1029 $customGroupDAO->find();
1031 // process each group with menu tab
1032 while ($customGroupDAO->fetch()) {
1034 $group['id'] = $customGroupDAO->id
;
1035 $group['path'] = $path;
1036 $group['title'] = "$customGroupDAO->title";
1037 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1038 $group['extra'] = array('gid' => $customGroupDAO->id
);
1039 $group['table_name'] = $customGroupDAO->table_name
;
1047 * Get the table name for the entity type
1048 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1049 * tableName is 'civicrm_contact'
1051 * @param string $entityType what entity are we extending here ?
1053 * @return string $tableName
1058 * @see _apachesolr_civiAttachments_dereference_file_parent
1060 public static function getTableNameByEntityName($entityType) {
1062 switch ($entityType) {
1066 case 'Organization':
1067 $tableName = 'civicrm_contact';
1070 case 'Contribution':
1071 $tableName = 'civicrm_contribution';
1075 $tableName = 'civicrm_group';
1077 // DRAFTING: Verify if we cannot make it pluggable
1080 $tableName = 'civicrm_activity';
1083 case 'Relationship':
1084 $tableName = 'civicrm_relationship';
1088 $tableName = 'civicrm_membership';
1092 $tableName = 'civicrm_participant';
1096 $tableName = 'civicrm_event';
1100 $tableName = 'civicrm_grant';
1102 // need to add cases for Location, Address
1109 * Get a list of custom groups which extend a given entity type.
1110 * If there are custom-groups which only apply to certain subtypes,
1111 * those WILL be included.
1113 * @param $entityType string
1114 * @return CRM_Core_DAO_CustomGroup
1116 static function getAllCustomGroupsByBaseEntity($entityType) {
1117 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1118 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1119 return $customGroupDAO;
1123 * Add the whereAdd clause for the DAO depending on the type of entity
1124 * the custom group is extending.
1126 * @param $customGroupDAO
1127 * @param string $entityType - what entity are we extending here ?
1129 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
1130 * @param bool $allSubtypes
1137 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1138 $addSubtypeClause = FALSE;
1140 switch ($entityType) {
1142 // if contact, get all related to contact
1143 $extendList = "'Contact','Individual','Household','Organization'";
1144 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1145 if (!$allSubtypes) {
1146 $addSubtypeClause = TRUE;
1152 case 'Organization':
1153 // is I/H/O then get I/H/O and contact
1154 $extendList = "'Contact','$entityType'";
1155 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1156 if (!$allSubtypes) {
1157 $addSubtypeClause = TRUE;
1165 case 'Contribution':
1168 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1172 if ($addSubtypeClause) {
1173 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1175 if (!empty($csType)) {
1176 $subtypeClause = array();
1177 foreach ($csType as $subtype) {
1178 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
1179 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1181 $subtypeClause[] = "extends_entity_column_value IS NULL";
1182 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) . " )");
1185 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1191 * Delete the Custom Group.
1193 * @param $group object the DAO custom group object
1194 * @param $force boolean whether to force the deletion, even if there are custom fields
1196 * @return boolean false if field exists for this group, true if group gets deleted.
1202 public static function deleteGroup($group, $force = FALSE) {
1204 //check wheter this contain any custom fields
1205 $customField = new CRM_Core_DAO_CustomField();
1206 $customField->custom_group_id
= $group->id
;
1207 $customField->find();
1209 // return early if there are custom fields and we're not
1210 // forcing the delete, otherwise delete the fields one by one
1211 while ($customField->fetch()) {
1215 CRM_Core_BAO_CustomField
::deleteField($customField);
1218 // drop the table associated with this custom group
1219 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1221 //delete custom group
1224 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1232 * @param bool $viewMode
1233 * @param bool $inactiveNeeded
1234 * @param int $action
1236 static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1237 foreach ($groupTree as $id => $group) {
1238 if (!isset($group['fields'])) {
1241 foreach ($group['fields'] as $field) {
1242 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1243 $value = $field['element_value'];
1245 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1246 ($action != CRM_Core_Action
::UPDATE ||
1248 !array_key_exists('element_value', $field)
1251 $value = $viewMode ?
NULL : $field['default_value'];
1257 if (!empty($field['element_name'])) {
1258 $elementName = $field['element_name'];
1260 switch ($field['html_type']) {
1261 case 'Multi-Select':
1262 case 'AdvMulti-Select':
1264 $defaults[$elementName] = array();
1265 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1267 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1268 if (isset($value)) {
1269 foreach ($customOption as $customValue => $customLabel) {
1270 if (in_array($customValue, $checkedData)) {
1271 if ($field['html_type'] == 'CheckBox') {
1272 $defaults[$elementName][$customValue] = 1;
1275 $defaults[$elementName][$customValue] = $customValue;
1279 $defaults[$elementName][$customValue] = 0;
1285 if (isset($field['customValue']['data'])) {
1286 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1287 foreach ($customOption as $val) {
1288 if (in_array($val['value'], $checkedData)) {
1289 if ($field['html_type'] == 'CheckBox') {
1290 $defaults[$elementName][$val['value']] = 1;
1293 $defaults[$elementName][$val['value']] = $val['value'];
1297 $defaults[$elementName][$val['value']] = 0;
1302 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1303 foreach ($customOption as $val) {
1304 if (in_array($val['value'], $checkedValue)) {
1305 if ($field['html_type'] == 'CheckBox') {
1306 $defaults[$elementName][$val['value']] = 1;
1309 $defaults[$elementName][$val['value']] = $val['value'];
1318 if (isset($value)) {
1319 if (empty($field['time_format'])) {
1320 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1321 $field['date_format']
1325 $timeElement = $elementName . '_time';
1326 if (substr($elementName, -1) == ']') {
1327 $timeElement = substr($elementName, 0, -1) . '_time]';
1329 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1334 case 'Multi-Select Country':
1335 case 'Multi-Select State/Province':
1336 if (isset($value)) {
1337 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1338 foreach ($checkedValue as $val) {
1340 $defaults[$elementName][$val] = $val;
1346 case 'Select Country':
1348 $defaults[$elementName] = $value;
1351 $config = CRM_Core_Config
::singleton();
1352 $defaults[$elementName] = $config->defaultContactCountry
;
1357 if ($field['data_type'] == "Float") {
1358 $defaults[$elementName] = (float)$value;
1360 elseif ($field['data_type'] == 'Money' &&
1361 $field['html_type'] == 'Text'
1363 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1366 $defaults[$elementName] = $value;
1376 * @param bool $skipFile
1378 static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1379 // Get the Custom form values and groupTree
1380 // first reset all checkbox and radio data
1381 foreach ($groupTree as $groupID => $group) {
1382 if ($groupID === 'info') {
1385 foreach ($group['fields'] as $field) {
1386 $fieldId = $field['id'];
1388 //added Multi-Select option in the below if-statement
1389 if ($field['html_type'] == 'CheckBox' ||
$field['html_type'] == 'Radio' ||
1390 $field['html_type'] == 'AdvMulti-Select' ||
$field['html_type'] == 'Multi-Select'
1392 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1396 foreach ($params as $key => $val) {
1397 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1398 $match[1] == $field['id']
1405 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1406 // field exists in db so populate value from "form".
1407 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1410 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1412 //added for CheckBox
1416 $customValue = array_keys($v);
1417 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1420 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1424 //added for Advanced Multi-Select
1426 case 'AdvMulti-Select':
1427 //added for Multi-Select
1428 case 'Multi-Select':
1430 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1433 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1438 $date = CRM_Utils_Date
::processDate($v);
1439 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1447 //store the file in d/b
1448 $entityId = explode('=', $groupTree['info']['where'][0]);
1449 $fileParams = array('upload_date' => date('Ymdhis'));
1451 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1452 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1455 $fileParams['uri'] = $v['name'];
1456 $fileParams['mime_type'] = $v['type'];
1457 CRM_Core_BAO_File
::filePostProcess($v['name'],
1458 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1459 $groupTree[$groupID]['table_name'],
1464 'custom_' . $fieldId,
1468 $defaults = array();
1469 $paramsFile = array(
1470 'entity_table' => $groupTree[$groupID]['table_name'],
1471 'entity_id' => $entityId[1],
1474 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1479 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1483 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1491 * generic function to build all the form elements for a specific group tree
1493 * @param object $form the form object
1494 * @param array $groupTree the group tree object
1495 * @param boolean $inactiveNeeded return inactive custom groups
1496 * @param string $prefix prefix for custom grouptree assigned to template
1502 static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '' ) {
1503 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1505 // this is fix for date field
1506 $form->assign('currentYear', date('Y'));
1508 foreach ($groupTree as $id => $group) {
1509 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1510 foreach ($group['fields'] as $field) {
1511 $required = CRM_Utils_Array
::value('is_required', $field);
1513 if ($field['data_type'] == 'File') {
1514 if (!empty($field['element_value']['data'])) {
1519 $fieldId = $field['id'];
1520 $elementName = $field['element_name'];
1521 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1524 if (!empty($form->_stateCountryMap
['state_province']) && !empty($form->_stateCountryMap
['country'])) {
1525 foreach ($form->_stateCountryMap
['state_province'] as $key => $value) {
1526 $stateCountryMap[$key]['state_province'] = $value;
1527 $stateCountryMap[$key]['country'] = $form->_stateCountryMap
['country'][$key];
1529 CRM_Core_BAO_Address
::addStateCountryMap($stateCountryMap);
1534 * Function to extract the get params from the url, validate
1535 * and store it in session
1537 * @param CRM_Core_Form $form the form object
1538 * @param string $type the type of custom group we are using
1544 static function extractGetParams(&$form, $type) {
1545 // if not GET params return
1550 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1551 $customValue = array();
1552 $htmlType = array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Select', 'Radio');
1554 foreach ($groupTree as $group) {
1555 if (!isset($group['fields'])) {
1558 foreach ($group['fields'] as $key => $field) {
1559 $fieldName = 'custom_' . $key;
1560 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1564 if (!in_array($field['html_type'], $htmlType) ||
1565 $field['data_type'] == 'Boolean'
1567 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1569 if ($field['html_type'] == 'CheckBox' ||
1570 $field['html_type'] == 'AdvMulti-Select' ||
1571 $field['html_type'] == 'Multi-Select'
1573 $value = str_replace("|", ",", $value);
1574 $mulValues = explode(',', $value);
1575 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1577 foreach ($mulValues as $v1) {
1578 foreach ($customOption as $coID => $coValue) {
1579 if (strtolower(trim($coValue['label'])) == strtolower(trim($v1))) {
1580 $val[$coValue['value']] = 1;
1592 elseif ($field['html_type'] == 'Select' ||
1593 ($field['html_type'] == 'Radio' &&
1594 $field['data_type'] != 'Boolean'
1597 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1598 foreach ($customOption as $customID => $coValue) {
1599 if (strtolower(trim($coValue['label'])) == strtolower(trim($value))) {
1600 $value = $coValue['value'];
1605 elseif ($field['data_type'] == 'Date') {
1606 if (!empty($value)) {
1608 if (!empty($field['time_format'])) {
1609 $time = CRM_Utils_Request
::retrieve($fieldName . '_time', 'String', $form, FALSE, NULL, 'GET');
1611 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value . ' ' . $time);
1612 if (!empty($field['time_format'])) {
1613 $customValue[$fieldName . '_time'] = $time;
1620 $customValue[$fieldName] = $value;
1626 return $customValue;
1630 * Function to check the type of custom field type (eg: Used for Individual, Contribution, etc)
1631 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1633 * @param int $customFieldId custom field id
1634 * @param array $removeCustomFieldTypes remove custom fields of a type eg: array("Individual") ;
1637 * @return boolean false if it matches else true
1641 static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1642 $query = "SELECT cg.extends as extends
1643 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1644 WHERE cg.id = cf.custom_group_id
1645 AND cf.id =" . CRM_Utils_Type
::escape($customFieldId, 'Integer');
1647 $extends = CRM_Core_DAO
::singleValueQuery($query);
1649 if (in_array($extends, $removeCustomFieldTypes)) {
1661 static function mapTableName($table) {
1666 case 'Organization':
1667 return 'civicrm_contact';
1670 return 'civicrm_activity';
1673 return 'civicrm_group';
1675 case 'Contribution':
1676 return 'civicrm_contribution';
1678 case 'Relationship':
1679 return 'civicrm_relationship';
1682 return 'civicrm_event';
1685 return 'civicrm_membership';
1688 case 'ParticipantRole':
1689 case 'ParticipantEventName':
1690 case 'ParticipantEventType':
1691 return 'civicrm_participant';
1694 return 'civicrm_grant';
1697 return 'civicrm_pledge';
1700 return 'civicrm_address';
1703 return 'civicrm_campaign';
1707 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1708 $qParams = array(1 => array($table, 'String'));
1709 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1712 return 'civicrm_contact';
1715 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1716 if (array_key_exists($table, $extendObjs)) {
1717 return $extendObjs[$table];
1719 CRM_Core_Error
::fatal();
1727 static function createTable($group) {
1729 'name' => $group->table_name
,
1730 'is_multiple' => $group->is_multiple ?
1 : 0,
1731 'extends_name' => self
::mapTableName($group->extends),
1734 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1736 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1740 * Function returns formatted groupTree, sothat form can be easily build in template
1742 * @param array $groupTree associated array
1743 * @param int $groupCount group count by default 1, but can varry for multiple value custom data
1744 * @param object form object
1746 * @return array $formattedGroupTree
1748 static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1749 $formattedGroupTree = array();
1750 $uploadNames = array();
1752 foreach ($groupTree as $key => $value) {
1753 if ($key === 'info') {
1757 // add group information
1758 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1759 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1760 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1761 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1762 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1763 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1765 // this params needed of bulding multiple values
1766 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1767 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1768 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1769 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1770 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1771 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1773 // add field information
1774 foreach ($value['fields'] as $k => $properties) {
1775 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1776 if (isset($properties['customValue']) && !CRM_Utils_System
::isNull($properties['customValue'])) {
1777 if (isset($properties['customValue'][$groupCount])) {
1778 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1779 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1780 if ($properties['data_type'] == 'File') {
1781 $properties['element_value'] = $properties['customValue'][$groupCount];
1782 $uploadNames[] = $properties['element_name'];
1785 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1789 unset($properties['customValue']);
1790 $formattedGroupTree[$key]['fields'][$k] = $properties;
1795 // hack for field type File
1796 $formUploadNames = $form->get('uploadNames');
1797 if (is_array($formUploadNames)) {
1798 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1801 $form->set('uploadNames', $uploadNames);
1804 return $formattedGroupTree;
1808 * Build custom data view
1810 * @param object $form page object
1811 * @param array $groupTree associated array
1812 * @param boolean $returnCount true if customValue count needs to be returned
1814 * @param null $prefix
1815 * @param null $customValueId
1819 static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1821 foreach ($groupTree as $key => $group) {
1822 if ($key === 'info') {
1826 foreach ($group['fields'] as $k => $properties) {
1827 $groupID = $group['id'];
1828 if (!empty($properties['customValue'])) {
1829 foreach ($properties['customValue'] as $values) {
1830 if (!empty($customValueId) && $customValueId != $values['id']) {
1833 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1834 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1835 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1836 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1837 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1838 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1839 $details[$groupID][$values['id']]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties),
1840 'field_type' => CRM_Utils_Array
::value('html_type',
1843 'field_data_type' => CRM_Utils_Array
::value('data_type',
1846 'field_value' => self
::formatCustomValues($values,
1849 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1853 // also return contact reference contact id if user has view all or edit all contacts perm
1854 if ((CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts'))
1855 && $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] == 'ContactReference'
1857 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1862 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1863 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1864 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1865 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1866 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1867 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1868 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1874 //return a single value count if group id is passed to function
1875 //else return a groupId and count mapped array
1877 return count($details[$gID]);
1880 $countValue = array();
1881 foreach( $details as $key => $value ) {
1882 $countValue[$key] = count($details[$key]);
1888 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1894 * Format custom value according to data, view mode
1896 * @param array $values associated array of custom values
1897 * @param array $field associated array
1898 * @param boolean $dncOptionPerLine true if optionPerLine should not be consider
1900 * @return array|null|string
1902 static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1903 $value = $values['data'];
1905 //changed isset CRM-4601
1906 if (CRM_Utils_System
::isNull($value)) {
1910 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1911 $dataType = CRM_Utils_Array
::value('data_type', $field);
1912 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1913 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1914 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1917 $freezeStringChecked = "";
1919 switch ($dataType) {
1921 $customTimeFormat = '';
1922 $customFormat = NULL;
1924 switch ($timeFormat) {
1926 $customTimeFormat = '%l:%M %P';
1930 $customTimeFormat = '%H:%M';
1934 // if time is not selected remove time from value
1935 $value = substr($value, 0, 10);
1938 $supportableFormats = array(
1939 'mm/dd' => "%B %E%f $customTimeFormat",
1940 'dd-mm' => "%E%f %B $customTimeFormat",
1941 'yy' => "%Y $customTimeFormat",
1942 'M yy' => "%b %Y $customTimeFormat",
1943 'yy-mm' => "%Y-%m $customTimeFormat"
1946 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
1947 if (array_key_exists($format, $supportableFormats)) {
1948 $customFormat = $supportableFormats["$format"];
1952 $retValue = CRM_Utils_Date
::customFormat($value, $customFormat);
1956 if ($value == '1') {
1957 $retValue = $freezeStringChecked . ts('Yes') . "\n";
1960 $retValue = $freezeStringChecked . ts('No') . "\n";
1966 $retValue = CRM_Utils_System
::formatWikiURL($value);
1971 $retValue = $values;
1974 case 'ContactReference':
1975 if (!empty($values['data'])) {
1976 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
1985 if ($htmlType == 'Text') {
1986 $retValue = (float)$value;
1990 if ($htmlType == 'Text') {
1991 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1996 if (in_array($htmlType, array('Text', 'TextArea'))) {
2000 // note that if its not text / textarea, the code falls thru and executes
2001 // the below case also
2002 case 'StateProvince':
2007 //added check for Multi-Select in the below if-statement
2008 $customData[] = $value;
2010 //form custom data for multiple-valued custom data
2011 switch ($htmlType) {
2012 case 'Multi-Select Country':
2013 case 'Select Country':
2014 $customData = $value;
2015 if (!is_array($value)) {
2016 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2019 SELECT id as value, name as label
2020 FROM civicrm_country";
2021 $coDAO = CRM_Core_DAO
::executeQuery($query);
2024 case 'Select State/Province':
2025 case 'Multi-Select State/Province':
2026 $customData = $value;
2027 if (!is_array($value)) {
2028 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2032 SELECT id as value, name as label
2033 FROM civicrm_state_province";
2034 $coDAO = CRM_Core_DAO
::executeQuery($query);
2038 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2039 if ($option_group_id) {
2040 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2045 case 'AdvMulti-Select':
2046 case 'Multi-Select':
2047 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2049 if ($option_group_id) {
2050 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2054 if (is_object($coDAO)) {
2055 while ($coDAO->fetch()) {
2056 if ($dataType == 'Country') {
2057 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2058 // and already extracted to .pot files.
2059 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
2061 elseif ($dataType == 'StateProvince') {
2062 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
2065 $options[$coDAO->value
] = $coDAO->label
;
2070 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
2073 foreach ($options as $optionValue => $optionLabel) {
2074 if ($dataType == 'Money') {
2075 foreach ($customData as $k => $v) {
2076 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
2080 //to show only values that are checked
2081 if (in_array((string) $optionValue, $customData)) {
2082 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
2083 if (!$optionPerLine ||
$dncOptionPerLine) {
2087 $retValue .= $checked . $optionLabel;
2090 $retValue[] = $checked . $optionLabel;
2097 //special case for option per line formatting
2098 if ($optionPerLine > 1 && is_array($retValue)) {
2101 $displayValues = array();
2102 $displayString = '';
2103 foreach ($retValue as $val) {
2104 if ($displayString) {
2105 $displayString .= ", ";
2108 $displayString .= $val;
2112 if (($rowCounter == $optionPerLine) ||
($fieldCounter == count($retValue))) {
2113 $displayValues[] = $displayString;
2114 $displayString = '';
2118 $retValue = $displayValues;
2121 $retValue = isset($retValue) ?
$retValue : NULL;
2126 * Get the custom group titles by custom field ids.
2128 * @param array $fieldIds - array of custom field ids.
2130 * @return array $groupLabels - array consisting of groups and fields labels with ids.
2133 public static function getGroupTitles($fieldIds) {
2134 if (!is_array($fieldIds) && empty($fieldIds)) {
2138 $groupLabels = array();
2139 $fIds = "(" . implode(',', $fieldIds) . ")";
2142 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2143 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2144 FROM civicrm_custom_group, civicrm_custom_field
2145 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2146 AND civicrm_custom_field.id IN {$fIds}";
2148 $dao = CRM_Core_DAO
::executeQuery($query);
2149 while ($dao->fetch()) {
2150 $groupLabels[$dao->fieldID
] = array(
2151 'fieldID' => $dao->fieldID
,
2152 'fieldLabel' => $dao->fieldLabel
,
2153 'groupID' => $dao->groupID
,
2154 'groupTitle' => $dao->groupTitle
,
2158 return $groupLabels;
2161 static function dropAllTables() {
2162 $query = "SELECT table_name FROM civicrm_custom_group";
2163 $dao = CRM_Core_DAO
::executeQuery($query);
2165 while ($dao->fetch()) {
2166 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2167 CRM_Core_DAO
::executeQuery($query);
2172 * Check whether custom group is empty or not.
2174 * @param int $gID - custom group id.
2176 * @return boolean true if empty otherwise false.
2179 static function isGroupEmpty($gID) {
2184 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2189 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2190 $value = CRM_Core_DAO
::singleValueQuery($query);
2192 if (empty($value)) {
2200 * Get the list of types for objects that a custom group extends to.
2202 * @param array $types - var which should have the list appended.
2204 * @return array of types.
2207 static function getExtendedObjectTypes(&$types = array( )) {
2208 static $flag = FALSE, $objTypes = array();
2211 $extendObjs = array();
2212 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2214 foreach ($extendObjs as $ovId => $ovValues) {
2215 if ($ovValues['description']) {
2216 // description is expected to be a callback func to subtypes
2217 list($callback, $args) = explode(';', trim($ovValues['description']));
2223 if (!is_array($args)) {
2224 CRM_Core_Error
::fatal('Arg is not of type array');
2227 list($className) = explode('::', $callback);
2228 require_once (str_replace('_',DIRECTORY_SEPARATOR
, $className) . '.php');
2230 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2236 $types = array_merge($types, $objTypes);
2241 * @param $customGroupId
2246 static function hasReachedMaxLimit($customGroupId, $entityId) {
2247 //check whether the group is multiple
2248 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2249 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2250 $hasReachedMax = FALSE;
2252 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))) {
2253 if (!$maxMultiple) {
2254 $hasReachedMax = FALSE;
2256 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2257 //count the number of entries for a entity
2258 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2259 $params = array(1 => array($entityId, 'Integer'));
2260 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2262 if ($count >= $maxMultiple) {
2263 $hasReachedMax = TRUE;
2267 return $hasReachedMax;
2273 static function getMultipleFieldGroup() {
2274 $multipleGroup = array();
2275 $dao = new CRM_Core_DAO_CustomGroup();
2276 $dao->is_multiple
= 1 ;
2278 while($dao->fetch()) {
2279 $multipleGroup[$dao->id
] = $dao->title
;
2281 return $multipleGroup;