3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 (CRM_Utils_Array
::value('extends_entity_column_value', $params)) {
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 ((CRM_Utils_Array
::value('is_multiple', $params) ||
$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 // enclose the below in a transaction
164 $transaction = new CRM_Core_Transaction();
167 if (!isset($params['id'])) {
168 if (!isset($params['table_name'])) {
169 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 42));
170 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
172 $group->table_name
= $tableName;
173 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
179 // now create the table associated with this group
180 self
::createTable($group);
182 elseif ($oldTableName) {
183 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($oldTableName, CRM_Utils_Array
::value('is_multiple', $params));
186 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
187 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
191 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends'][0]));
193 $transaction->commit();
196 CRM_Utils_System
::flushCache();
199 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
202 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
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
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
218 * @return object CRM_Core_DAO_CustomGroup object
222 static function retrieve(&$params, &$defaults) {
223 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
227 * update the is_active flag in the db
229 * @param int $id id of the database record
230 * @param boolean $is_active value we want to set the is_active field
232 * @return Object DAO object on sucess, null otherwise
236 static function setIsActive($id, $is_active) {
238 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
241 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
244 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
248 * Determine if given entity (sub)type has any custom groups
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
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;
265 * Determine if there are any CustomGroups for the given $activityTypeId.
266 * If none found, create one.
268 * @param int $activityTypeId
269 * @return bool TRUE if a group is found or created; FALSE on error
271 public static function autoCreateByActivityType($activityTypeId) {
272 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
275 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
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])),
285 $result = civicrm_api('CustomGroup', 'create', $params);
286 return ! $result['is_error'];
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.
293 * An array containing all custom groups and their custom fields is returned.
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
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'
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
319 public static function &getTree(
330 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
334 $strSelect = $strFrom = $strWhere = $orderBy = '';
335 $tableData = array();
337 // using tableData to build the queryString
339 'civicrm_custom_field' =>
359 'civicrm_custom_group' =>
370 'extends_entity_column_id',
371 'extends_entity_column_value',
378 foreach ($tableData as $tableName => $tableColumn) {
379 foreach ($tableColumn as $columnName) {
380 $alias = $tableName . "_" . $columnName;
381 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
384 $strSelect = "SELECT " . implode(', ', $select);
386 // from, where, order by
388 FROM civicrm_custom_group
389 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
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'";
396 elseif (strpos($entityType, "'") !== FALSE) {
397 // this allows the calling function to send in multiple entity types
402 $in = "'$entityType'";
407 if (is_array($subType)) {
408 $subType = implode(',', $subType);
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%'";
419 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
422 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
426 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
429 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
432 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
433 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
438 WHERE civicrm_custom_group.is_active = 1
439 AND civicrm_custom_field.is_active = 1
440 AND civicrm_custom_group.extends IN ($in)
444 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
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
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');
463 // since groupID is false we need to show all Inline groups
464 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
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.'
473 ORDER BY civicrm_custom_group.weight,
474 civicrm_custom_group.title,
475 civicrm_custom_field.weight,
476 civicrm_custom_field.label
479 // final query string
480 $queryString = "$strSelect $strFrom $strWhere $orderBy";
482 // lets see if we can retrieve the groupTree from cache
483 $cacheString = $queryString;
484 if ( $groupID > 0 ) {
485 $cacheString .= "_{$groupID}";
487 $cacheString .= "_Inline";
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();
495 $groupTree = $cache->get($cacheKey);
496 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
499 if (empty($groupTree)) {
500 $groupTree = $multipleFieldGroups =array();
501 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
502 $customValueTables = array();
505 while ($crmDAO->fetch()) {
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
;
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;
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)
526 if ($fieldName == 'extends_entity_column_value' && $subType) {
527 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
529 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
531 $groupTree[$groupID]['fields'] = array();
533 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
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();
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)
552 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
556 if (!empty($customValueTables)) {
557 $groupTree['info'] = array('tables' => $customValueTables);
560 $cache->set($cacheKey, $groupTree);
561 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
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
571 if (isset($groupTree['info']) && !empty($groupTree['info']) && !empty($groupTree['info']['tables'])) {
572 $select = $from = $where = array();
573 $groupTree['info']['where'] = NULL;
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}";
582 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
584 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
585 if(in_array($table, $multipleFieldGroups) && self
::customGroupDataExistsForEntity($entityID, $table)){
586 $entityMultipleSelectClauses[$table] = $select;
589 $singleFieldTables[] = $table;
590 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
595 if ($entityID && !empty($singleFieldTables)) {
596 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
598 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
599 if(!empty($multipleFieldTablesWithEntityData)){
600 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
608 * Check whether the custom group has any data for the given entity.
611 * @param integer $entityID id of entity for whom we are checking data for
612 * @param string $table table that we are checking
614 * @return boolean does this entity have data in this custom table
616 static public function customGroupDataExistsForEntity($entityID, $table){
620 WHERE entity_id = $entityID
622 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
623 return $recordExists ?
TRUE : FALSE;
627 * Build the group tree for Custom fields which are not 'is_multiple'
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
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
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)";
648 WHERE first.entity_id = $entityID
650 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
654 * Build the group tree for Custom fields which are 'is_multiple'
656 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
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
663 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData){
664 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
665 $select = implode(',', $selectClauses);
669 WHERE entity_id = $entityID
671 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
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).
679 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
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
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') {
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)){
700 foreach ($group['fields'] as $fieldID => $dontCare) {
701 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
708 * Build the entity-specific custom data into the group tree on a per-field basis
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
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;
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.');
736 CRM_Core_Action
::DELETE
=>
738 'name' => ts('Delete Attached File'),
739 'url' => 'civicrm/file',
740 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
742 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
745 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
746 CRM_Core_Action
::DELETE
,
748 'id' => $fileDAO->id
,
749 'eid' => $dao->$entityIDName,
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"
761 $customValue['displayURL'] = $customValue['fileURL'];
762 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
767 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) . $fileDAO->uri
;
768 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId,
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;
779 $customValue = array(
780 'id' => $dao->$idName,
786 $customValue = array(
787 'id' => $dao->$idName,
788 'data' => $dao->$fieldName,
792 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
793 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
795 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
796 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
799 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
804 * Get the group title.
806 * @param int $id id of group.
808 * @return string title
814 public static function getTitle($id) {
815 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
819 * Get custom group details for a group.
821 * An array containing custom group details (including their custom field) is returned.
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
827 * @return array $groupTree - array consisting of all group and field details
834 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL) {
836 $groupTree = array();
837 $select = $from = $where = $orderBy = '';
839 $tableData = array();
841 // using tableData to build the queryString
843 'civicrm_custom_field' =>
867 'civicrm_custom_group' =>
875 'collapse_adv_display',
877 'extends_entity_column_value',
885 foreach ($tableData as $tableName => $tableColumn) {
886 foreach ($tableColumn as $columnName) {
887 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
890 $select = 'SELECT ' . implode(', ', $s);
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 ";
898 $params[1] = array($groupId, 'Integer');
899 $where .= " AND civicrm_custom_group.id = %1";
903 $where .= " AND civicrm_custom_field.is_searchable = 1";
908 foreach ($extends as $e) {
909 $clause[] = "civicrm_custom_group.extends = '$e'";
911 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
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');
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.'
926 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
928 // final query string
929 $queryString = $select . $from . $where . $orderBy;
932 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
935 while ($crmDAO->fetch()) {
936 $groupId = $crmDAO->civicrm_custom_group_id
;
937 $fieldId = $crmDAO->civicrm_custom_field_id
;
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;
944 foreach ($tableData['civicrm_custom_group'] as $v) {
945 $fullField = "civicrm_custom_group_" . $v;
947 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
951 $groupTree[$groupId][$v] = $crmDAO->$fullField;
954 $groupTree[$groupId]['fields'] = array();
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;
961 foreach ($tableData['civicrm_custom_field'] as $v) {
962 $fullField = "civicrm_custom_field_" . $v;
963 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
966 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
973 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
975 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
977 // get only 'Tab' groups
978 $customGroupDAO->whereAdd("style = 'Tab'");
979 $customGroupDAO->whereAdd("is_active = 1");
981 // add whereAdd for entity type
982 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
986 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
987 $customGroupDAO->whereAdd($permissionClause);
990 $customGroupDAO->orderBy('weight');
991 $customGroupDAO->find();
993 // process each group with menu tab
994 while ($customGroupDAO->fetch()) {
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
;
1009 * Get the table name for the entity type
1010 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1011 * tableName is 'civicrm_contact'
1013 * @param string $entityType what entity are we extending here ?
1015 * @return string $tableName
1021 private static function _getTableName($entityType) {
1023 switch ($entityType) {
1027 case 'Organization':
1028 $tableName = 'civicrm_contact';
1031 case 'Contribution':
1032 $tableName = 'civicrm_contribution';
1036 $tableName = 'civicrm_group';
1038 // DRAFTING: Verify if we cannot make it pluggable
1041 $tableName = 'civicrm_activity';
1044 case 'Relationship':
1045 $tableName = 'civicrm_relationship';
1049 $tableName = 'civicrm_membership';
1053 $tableName = 'civicrm_participant';
1057 $tableName = 'civicrm_event';
1061 $tableName = 'civicrm_grant';
1063 // need to add cases for Location, Address
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.
1074 * @param $entityType string
1075 * @return CRM_Core_DAO_CustomGroup
1077 static function getAllCustomGroupsByBaseEntity($entityType) {
1078 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1079 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1080 return $customGroupDAO;
1084 * Add the whereAdd clause for the DAO depending on the type of entity
1085 * the custom group is extending.
1087 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
1088 * @param string $entityType - what entity are we extending here ?
1096 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1097 $addSubtypeClause = FALSE;
1099 switch ($entityType) {
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;
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;
1123 case 'Contribution':
1126 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1130 if ($addSubtypeClause) {
1131 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
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}%'";
1139 $subtypeClause[] = "extends_entity_column_value IS NULL";
1140 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) . " )");
1143 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1149 * Delete the Custom Group.
1151 * @param $group object the DAO custom group object
1152 * @param $force boolean whether to force the deletion, even if there are custom fields
1154 * @return boolean false if field exists for this group, true if group gets deleted.
1160 public static function deleteGroup($group, $force = FALSE) {
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();
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()) {
1173 CRM_Core_BAO_CustomField
::deleteField($customField);
1176 // drop the table associated with this custom group
1177 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1179 //delete custom group
1182 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
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'])) {
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'];
1197 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1198 ($action != CRM_Core_Action
::UPDATE ||
1200 !array_key_exists('element_value', $field)
1203 $value = $viewMode ?
NULL : $field['default_value'];
1209 $fieldId = $field['id'];
1210 $elementName = $field['element_name'];
1211 switch ($field['html_type']) {
1212 case 'Multi-Select':
1213 case 'AdvMulti-Select':
1215 $defaults[$elementName] = array();
1216 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
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;
1226 $defaults[$elementName][$customValue] = $customValue;
1230 $defaults[$elementName][$customValue] = 0;
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;
1244 $defaults[$elementName][$val['value']] = $val['value'];
1248 $defaults[$elementName][$val['value']] = 0;
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;
1260 $defaults[$elementName][$val['value']] = $val['value'];
1269 if (isset($value)) {
1270 if (empty($field['time_format'])) {
1271 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1272 $field['date_format']
1276 $timeElement = $elementName . '_time';
1277 if (substr($elementName, -1) == ']') {
1278 $timeElement = substr($elementName, 0, -1) . '_time]';
1280 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
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) {
1291 $defaults[$elementName][$val] = $val;
1297 case 'Select Country':
1299 $defaults[$elementName] = $value;
1302 $config = CRM_Core_Config
::singleton();
1303 $defaults[$elementName] = $config->defaultContactCountry
;
1307 case 'Autocomplete-Select':
1308 $hiddenEleName = $elementName . '_id';
1309 if (substr($elementName, -1) == ']') {
1310 $hiddenEleName = substr($elementName, 0, -1) . '_id]';
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');
1319 $label = CRM_Core_BAO_CustomOption
::getOptionLabel($field['id'], $value);
1320 $defaults[$hiddenEleName] = $value;
1321 $defaults[$elementName] = $label;
1326 if ($field['data_type'] == "Float") {
1327 $defaults[$elementName] = (float)$value;
1329 elseif ($field['data_type'] == 'Money' &&
1330 $field['html_type'] == 'Text'
1332 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1335 $defaults[$elementName] = $value;
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') {
1349 foreach ($group['fields'] as $field) {
1350 $fieldId = $field['id'];
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'
1356 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1360 foreach ($params as $key => $val) {
1361 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1362 $match[1] == $field['id']
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();
1374 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1376 //added for CheckBox
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
;
1384 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1388 //added for Advanced Multi-Select
1390 case 'AdvMulti-Select':
1391 //added for Multi-Select
1392 case 'Multi-Select':
1394 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1397 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1402 $date = CRM_Utils_Date
::processDate($v);
1403 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1411 //store the file in d/b
1412 $entityId = explode('=', $groupTree['info']['where'][0]);
1413 $fileParams = array('upload_date' => date('Ymdhis'));
1415 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1416 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
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'],
1428 'custom_' . $fieldId,
1432 $defaults = array();
1433 $paramsFile = array(
1434 'entity_table' => $groupTree[$groupID]['table_name'],
1435 'entity_id' => $entityId[1],
1438 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1443 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1447 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1455 * generic function to build all the form elements for a specific group tree
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
1466 static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '' ) {
1467 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1469 // this is fix for date field
1470 $form->assign('currentYear', date('Y'));
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);
1477 if ($field['data_type'] == 'File') {
1478 if (!empty($field['element_value']['data'])) {
1483 $fieldId = $field['id'];
1484 $elementName = $field['element_name'];
1485 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1491 * Function to extract the get params from the url, validate
1492 * and store it in session
1494 * @param CRM_Core_Form $form the form object
1495 * @param string $type the type of custom group we are using
1501 static function extractGetParams(&$form, $type) {
1502 // if not GET params return
1507 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1508 $customValue = array();
1509 $htmlType = array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Select', 'Radio');
1511 foreach ($groupTree as $group) {
1512 if (!isset($group['fields'])) {
1515 foreach ($group['fields'] as $key => $field) {
1516 $fieldName = 'custom_' . $key;
1517 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1521 if (!in_array($field['html_type'], $htmlType) ||
1522 $field['data_type'] == 'Boolean'
1524 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1526 if ($field['html_type'] == 'CheckBox' ||
1527 $field['html_type'] == 'AdvMulti-Select' ||
1528 $field['html_type'] == 'Multi-Select'
1530 $value = str_replace("|", ",", $value);
1531 $mulValues = explode(',', $value);
1532 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
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;
1549 elseif ($field['html_type'] == 'Select' ||
1550 ($field['html_type'] == 'Radio' &&
1551 $field['data_type'] != 'Boolean'
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'];
1562 elseif ($field['data_type'] == 'Date') {
1563 if (!empty($value)) {
1565 if (CRM_Utils_Array
::value('time_format', $field)) {
1566 $time = CRM_Utils_Request
::retrieve($fieldName . '_time', 'String', $form, FALSE, NULL, 'GET');
1568 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value . ' ' . $time);
1569 if (CRM_Utils_Array
::value('time_format', $field)) {
1570 $customValue[$fieldName . '_time'] = $time;
1577 $customValue[$fieldName] = $value;
1583 return $customValue;
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 )
1590 * @param int $customFieldId custom field id
1591 * @param array $removeCustomFieldTypes remove custom fields of a type eg: array("Individual") ;
1594 * @return boolean false if it matches else true
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');
1604 $extends = CRM_Core_DAO
::singleValueQuery($query);
1606 if (in_array($extends, $removeCustomFieldTypes)) {
1612 static function mapTableName($table) {
1617 case 'Organization':
1618 return 'civicrm_contact';
1621 return 'civicrm_activity';
1624 return 'civicrm_group';
1626 case 'Contribution':
1627 return 'civicrm_contribution';
1629 case 'Relationship':
1630 return 'civicrm_relationship';
1633 return 'civicrm_event';
1636 return 'civicrm_membership';
1639 case 'ParticipantRole':
1640 case 'ParticipantEventName':
1641 case 'ParticipantEventType':
1642 return 'civicrm_participant';
1645 return 'civicrm_grant';
1648 return 'civicrm_pledge';
1651 return 'civicrm_address';
1654 return 'civicrm_campaign';
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);
1663 return 'civicrm_contact';
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];
1670 CRM_Core_Error
::fatal();
1675 static function createTable($group) {
1677 'name' => $group->table_name
,
1678 'is_multiple' => $group->is_multiple ?
1 : 0,
1679 'extends_name' => self
::mapTableName($group->extends),
1682 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1684 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1688 * Function returns formatted groupTree, sothat form can be easily build in template
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
1694 * @return array $formattedGroupTree
1696 static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1697 $formattedGroupTree = array();
1698 $uploadNames = array();
1700 foreach ($groupTree as $key => $value) {
1701 if ($key === 'info') {
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);
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);
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'];
1733 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1737 unset($properties['customValue']);
1738 $formattedGroupTree[$key]['fields'][$k] = $properties;
1743 // hack for field type File
1744 $formUploadNames = $form->get('uploadNames');
1745 if (is_array($formUploadNames)) {
1746 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1749 $form->set('uploadNames', $uploadNames);
1752 return $formattedGroupTree;
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
1761 static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL) {
1764 foreach ($groupTree as $key => $group) {
1765 if ($key === 'info') {
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',
1783 'field_data_type' => CRM_Utils_Array
::value('data_type',
1786 'field_value' => self
::formatCustomValues($values,
1789 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
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'
1797 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
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));
1814 //return a single value count if group id is passed to function
1815 //else return a groupId and count mapped array
1817 return count($details[$gID]);
1820 $countValue = array();
1821 foreach( $details as $key => $value ) {
1822 $countValue[$key] = count($details[$key]);
1828 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1834 * Format custom value according to data, view mode
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
1841 static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1842 $value = $values['data'];
1844 //changed isset CRM-4601
1845 if (CRM_Utils_System
::isNull($value)) {
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);
1856 $freezeStringChecked = "";
1858 switch ($dataType) {
1860 $customTimeFormat = '';
1861 $customFormat = NULL;
1863 switch ($timeFormat) {
1865 $customTimeFormat = '%l:%M %P';
1869 $customTimeFormat = '%H:%M';
1873 // if time is not selected remove time from value
1874 $value = substr($value, 0, 10);
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"
1885 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
1886 if (array_key_exists($format, $supportableFormats)) {
1887 $customFormat = $supportableFormats["$format"];
1891 $retValue = CRM_Utils_Date
::customFormat($value, $customFormat);
1895 if ($value == '1') {
1896 $retValue = $freezeStringChecked . ts('Yes') . "\n";
1899 $retValue = $freezeStringChecked . ts('No') . "\n";
1905 $retValue = CRM_Utils_System
::formatWikiURL($value);
1910 $retValue = $values;
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');
1924 if ($htmlType == 'Text') {
1925 $retValue = (float)$value;
1929 if ($htmlType == 'Text') {
1930 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1935 if (in_array($htmlType, array('Text', 'TextArea'))) {
1939 // note that if its not text / textarea, the code falls thru and executes
1940 // the below case also
1941 case 'StateProvince':
1946 //added check for Multi-Select in the below if-statement
1947 $customData[] = $value;
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);
1958 SELECT id as value, name as label
1959 FROM civicrm_country";
1960 $coDAO = CRM_Core_DAO
::executeQuery($query);
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);
1971 SELECT id as value, name as label
1972 FROM civicrm_state_province";
1973 $coDAO = CRM_Core_DAO
::executeQuery($query);
1977 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1978 if ($option_group_id) {
1979 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
1984 case 'AdvMulti-Select':
1985 case 'Multi-Select':
1986 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1988 if ($option_group_id) {
1989 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
1993 if (is_object($coDAO)) {
1994 while ($coDAO->fetch()) {
1995 $options[$coDAO->value
] = $coDAO->label
;
1999 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
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');
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) {
2016 $retValue .= $checked . $optionLabel;
2019 $retValue[] = $checked . $optionLabel;
2026 //special case for option per line formatting
2027 if ($optionPerLine > 1 && is_array($retValue)) {
2030 $displayValues = array();
2031 $displayString = '';
2032 foreach ($retValue as $val) {
2033 if ($displayString) {
2034 $displayString .= ", ";
2037 $displayString .= $val;
2041 if (($rowCounter == $optionPerLine) ||
($fieldCounter == count($retValue))) {
2042 $displayValues[] = $displayString;
2043 $displayString = '';
2047 $retValue = $displayValues;
2050 $retValue = isset($retValue) ?
$retValue : NULL;
2055 * Get the custom group titles by custom field ids.
2057 * @param array $fieldIds - array of custom field ids.
2059 * @return array $groupLabels - array consisting of groups and fields labels with ids.
2062 public static function getGroupTitles($fieldIds) {
2063 if (!is_array($fieldIds) && empty($fieldIds)) {
2067 $groupLabels = array();
2068 $fIds = "(" . implode(',', $fieldIds) . ")";
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}";
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
,
2087 return $groupLabels;
2090 static function dropAllTables() {
2091 $query = "SELECT table_name FROM civicrm_custom_group";
2092 $dao = CRM_Core_DAO
::executeQuery($query);
2094 while ($dao->fetch()) {
2095 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2096 CRM_Core_DAO
::executeQuery($query);
2101 * Check whether custom group is empty or not.
2103 * @param int $gID - custom group id.
2105 * @return boolean true if empty otherwise false.
2108 static function isGroupEmpty($gID) {
2113 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2118 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2119 $value = CRM_Core_DAO
::singleValueQuery($query);
2121 if (empty($value)) {
2129 * Get the list of types for objects that a custom group extends to.
2131 * @param array $types - var which should have the list appended.
2133 * @return array of types.
2136 static function getExtendedObjectTypes(&$types = array( )) {
2137 static $flag = FALSE, $objTypes = array();
2140 $extendObjs = array();
2141 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
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']));
2152 if (!is_array($args)) {
2153 CRM_Core_Error
::fatal('Arg is not of type array');
2156 list($className) = explode('::', $callback);
2157 require_once (str_replace('_',DIRECTORY_SEPARATOR
, $className) . '.php');
2159 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2165 $types = array_merge($types, $objTypes);
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;
2175 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))) {
2176 if (!$maxMultiple) {
2177 $hasReachedMax = FALSE;
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);
2185 if ($count >= $maxMultiple) {
2186 $hasReachedMax = TRUE;
2190 return $hasReachedMax;