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 (!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 // 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' =>
360 'civicrm_custom_group' =>
371 'extends_entity_column_id',
372 'extends_entity_column_value',
379 foreach ($tableData as $tableName => $tableColumn) {
380 foreach ($tableColumn as $columnName) {
381 $alias = $tableName . "_" . $columnName;
382 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
385 $strSelect = "SELECT " . implode(', ', $select);
387 // from, where, order by
389 FROM civicrm_custom_group
390 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
393 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
394 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
$entityType == 'Household') {
395 $in = "'$entityType', 'Contact'";
397 elseif (strpos($entityType, "'") !== FALSE) {
398 // this allows the calling function to send in multiple entity types
403 $in = "'$entityType'";
408 if (is_array($subType)) {
409 $subType = implode(',', $subType);
411 if (strpos($subType, ',')) {
412 $subTypeParts = explode(',', $subType);
413 $subTypeClauses = array();
414 foreach ($subTypeParts as $subTypePart) {
415 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
416 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
420 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
423 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
427 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
430 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
433 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
434 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
439 WHERE civicrm_custom_group.is_active = 1
440 AND civicrm_custom_field.is_active = 1
441 AND civicrm_custom_group.extends IN ($in)
445 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
450 WHERE civicrm_custom_group.is_active = 1
451 AND civicrm_custom_field.is_active = 1
452 AND civicrm_custom_group.extends IN ($in)
453 AND civicrm_custom_group.extends_entity_column_value IS NULL
459 // since we want a specific group id we add it to the where clause
460 $strWhere .= " AND civicrm_custom_group.id = %1";
461 $params[1] = array($groupID, 'Integer');
464 // since groupID is false we need to show all Inline groups
465 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
468 // ensure that the user has access to these custom groups
469 $strWhere .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
470 'civicrm_custom_group.'
474 ORDER BY civicrm_custom_group.weight,
475 civicrm_custom_group.title,
476 civicrm_custom_field.weight,
477 civicrm_custom_field.label
480 // final query string
481 $queryString = "$strSelect $strFrom $strWhere $orderBy";
483 // lets see if we can retrieve the groupTree from cache
484 $cacheString = $queryString;
485 if ( $groupID > 0 ) {
486 $cacheString .= "_{$groupID}";
488 $cacheString .= "_Inline";
491 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
492 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
493 $cache = CRM_Utils_Cache
::singleton();
494 $tablesWithEntityData = array();
496 $groupTree = $cache->get($cacheKey);
497 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
500 if (empty($groupTree)) {
501 $groupTree = $multipleFieldGroups =array();
502 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
503 $customValueTables = array();
506 while ($crmDAO->fetch()) {
508 $groupID = $crmDAO->civicrm_custom_group_id
;
509 $fieldId = $crmDAO->civicrm_custom_field_id
;
510 if($crmDAO->civicrm_custom_group_is_multiple
){
511 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
513 // create an array for groups if it does not exist
514 if (!array_key_exists($groupID, $groupTree)) {
515 $groupTree[$groupID] = array();
516 $groupTree[$groupID]['id'] = $groupID;
518 // populate the group information
519 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
520 $fullFieldName = "civicrm_custom_group_$fieldName";
521 if ($fieldName == 'id' ||
522 is_null($crmDAO->$fullFieldName)
527 if ($fieldName == 'extends_entity_column_value' && $subType) {
528 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
530 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
532 $groupTree[$groupID]['fields'] = array();
534 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
537 // add the fields now (note - the query row will always contain a field)
538 // we only reset this once, since multiple values come is as multiple rows
539 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
540 $groupTree[$groupID]['fields'][$fieldId] = array();
543 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
544 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
545 // populate information for a custom field
546 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
547 $fullFieldName = "civicrm_custom_field_$fieldName";
548 if ($fieldName == 'id' ||
549 is_null($crmDAO->$fullFieldName)
553 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
557 if (!empty($customValueTables)) {
558 $groupTree['info'] = array('tables' => $customValueTables);
561 $cache->set($cacheKey, $groupTree);
562 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
564 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
565 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
566 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
567 $singleFieldTables = array();
568 // now that we have all the groups and fields, lets get the values
569 // since we need to know the table and field names
570 // add info to groupTree
572 if (isset($groupTree['info']) && !empty($groupTree['info']) && !empty($groupTree['info']['tables'])) {
573 $select = $from = $where = array();
574 $groupTree['info']['where'] = NULL;
576 foreach ($groupTree['info']['tables'] as $table => $fields) {
577 $groupTree['info']['from'][] = $table;
578 $select = array("{$table}.id as {$table}_id",
579 "{$table}.entity_id as {$table}_entity_id");
580 foreach ($fields as $column => $dontCare) {
581 $select[] = "{$table}.{$column} as {$table}_{$column}";
583 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
585 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
586 if(in_array($table, $multipleFieldGroups) && self
::customGroupDataExistsForEntity($entityID, $table)){
587 $entityMultipleSelectClauses[$table] = $select;
590 $singleFieldTables[] = $table;
591 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
596 if ($entityID && !empty($singleFieldTables)) {
597 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
599 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
600 if(!empty($multipleFieldTablesWithEntityData)){
601 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
609 * Check whether the custom group has any data for the given entity.
612 * @param integer $entityID id of entity for whom we are checking data for
613 * @param string $table table that we are checking
615 * @return boolean does this entity have data in this custom table
617 static public function customGroupDataExistsForEntity($entityID, $table){
621 WHERE entity_id = $entityID
623 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
624 return $recordExists ?
TRUE : FALSE;
628 * Build the group tree for Custom fields which are not 'is_multiple'
630 * The combination of all these fields in one query with a 'using' join was not working for
631 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
632 * mechanism as it seemed to be acceptable in this context
634 * @param array $groupTree (reference) group tree array which is being built
635 * @param integer $entityID id of entity for whom the tree is being build up.
636 * @param array $entitySingleSelectClauses array of select clauses relevant to the entity
637 * @param array $singleFieldTablesWithEntityData array of tables in which this entity has data
639 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData){
640 $select = implode(', ', $entitySingleSelectClauses);
641 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
642 foreach ($singleFieldTablesWithEntityData as $table) {
643 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
649 WHERE first.entity_id = $entityID
651 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
655 * Build the group tree for Custom fields which are 'is_multiple'
657 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
659 * @param array $groupTree (reference) group tree array which is being built
660 * @param integer $entityID id of entity for whom the tree is being build up.
661 * @param array $entityMultipleSelectClauses array of select clauses relevant to the entity
662 * @param array $multipleFieldTablesWithEntityData array of tables in which this entity has data
664 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData){
665 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
666 $select = implode(',', $selectClauses);
670 WHERE entity_id = $entityID
672 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
677 * Build the tree entity data - starting from a query retrieving the custom fields build the group
678 * tree data for the relevant entity (entity is included in the query).
680 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
682 * @param array $groupTree (reference) group tree array which is being built
683 * @param string $query
684 * @param array $includedTables tables to include - required because the function (for historical reasons)
685 * iterates through the group tree
687 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables){
688 $dao = CRM_Core_DAO
::executeQuery($query);
689 while ($dao->fetch()) {
690 foreach ($groupTree as $groupID => $group) {
691 if ($groupID === 'info') {
694 $table = $groupTree[$groupID]['table_name'];
695 //working from the groupTree instead of the table list means we have to iterate & exclude.
696 // this could possibly be re-written as other parts of the function have been refactored
697 // for now we just check if the given table is to be included in this function
698 if( !in_array($table, $includedTables)){
701 foreach ($group['fields'] as $fieldID => $dontCare) {
702 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
709 * Build the entity-specific custom data into the group tree on a per-field basis
711 * @param object $dao object representing the custom field to be populated into the groupTree
712 * @param array $groupTree (reference) the group tree being build
713 * @param string $table table name
714 * @param unknown_type $groupID custom group ID
715 * @param unknown_type $fieldID custom field ID
717 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID){
718 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
719 $idName = "{$table}_id";
720 $fieldName = "{$table}_{$column}";
721 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
722 if ($dataType == 'File') {
723 if (isset($dao->$fieldName)) {
724 $config = CRM_Core_Config
::singleton();
725 $fileDAO = new CRM_Core_DAO_File();
726 $fileDAO->id
= $dao->$fieldName;
728 if ($fileDAO->find(TRUE)) {
729 $entityIDName = "{$table}_entity_id";
730 $customValue['id'] = $dao->$idName;
731 $customValue['data'] = $fileDAO->uri
;
732 $customValue['fid'] = $fileDAO->id
;
733 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
734 $customValue['displayURL'] = NULL;
735 $deleteExtra = ts('Are you sure you want to delete attached file.');
737 CRM_Core_Action
::DELETE
=>
739 'name' => ts('Delete Attached File'),
740 'url' => 'civicrm/file',
741 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
743 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
746 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
747 CRM_Core_Action
::DELETE
,
749 'id' => $fileDAO->id
,
750 'eid' => $dao->$entityIDName,
755 'file.manage.delete',
759 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
760 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
761 if ($fileDAO->mime_type
== "image/jpeg" ||
762 $fileDAO->mime_type
== "image/pjpeg" ||
763 $fileDAO->mime_type
== "image/gif" ||
764 $fileDAO->mime_type
== "image/x-png" ||
765 $fileDAO->mime_type
== "image/png"
767 $customValue['displayURL'] = $customValue['fileURL'];
768 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
773 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) . $fileDAO->uri
;
774 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId,
777 list($imageWidth, $imageHeight) = getimagesize($path);
778 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
779 $customValue['imageThumbWidth'] = $imageThumbWidth;
780 $customValue['imageThumbHeight'] = $imageThumbHeight;
785 $customValue = array(
786 'id' => $dao->$idName,
792 $customValue = array(
793 'id' => $dao->$idName,
794 'data' => $dao->$fieldName,
798 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
799 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
801 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
802 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
805 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
810 * Get the group title.
812 * @param int $id id of group.
814 * @return string title
820 public static function getTitle($id) {
821 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
825 * Get custom group details for a group.
827 * An array containing custom group details (including their custom field) is returned.
829 * @param int $groupId - group id whose details are needed
830 * @param boolean $searchable - is this field searchable
831 * @param array $extends - which table does it extend if any
833 * @return array $groupTree - array consisting of all group and field details
840 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
842 $groupTree = array();
843 $select = $from = $where = $orderBy = '';
845 $tableData = array();
847 // using tableData to build the queryString
849 'civicrm_custom_field' =>
874 'civicrm_custom_group' =>
882 'collapse_adv_display',
884 'extends_entity_column_value',
893 foreach ($tableData as $tableName => $tableColumn) {
894 foreach ($tableColumn as $columnName) {
895 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
898 $select = 'SELECT ' . implode(', ', $s);
900 // from, where, order by
901 $from = " FROM civicrm_custom_field, civicrm_custom_group";
902 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
903 AND civicrm_custom_group.is_active = 1
904 AND civicrm_custom_field.is_active = 1 ";
906 $params[1] = array($groupId, 'Integer');
907 $where .= " AND civicrm_custom_group.id = %1";
911 $where .= " AND civicrm_custom_field.is_searchable = 1";
915 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
920 foreach ($extends as $e) {
921 $clause[] = "civicrm_custom_group.extends = '$e'";
923 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
925 //include case activities customdata if case is enabled
926 if (in_array('Activity', $extends)) {
927 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
928 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
929 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
933 // ensure that the user has access to these custom groups
934 $where .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
935 'civicrm_custom_group.'
938 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
940 // final query string
941 $queryString = $select . $from . $where . $orderBy;
944 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
947 while ($crmDAO->fetch()) {
948 $groupId = $crmDAO->civicrm_custom_group_id
;
949 $fieldId = $crmDAO->civicrm_custom_field_id
;
951 // create an array for groups if it does not exist
952 if (!array_key_exists($groupId, $groupTree)) {
953 $groupTree[$groupId] = array();
954 $groupTree[$groupId]['id'] = $groupId;
956 foreach ($tableData['civicrm_custom_group'] as $v) {
957 $fullField = "civicrm_custom_group_" . $v;
959 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
963 $groupTree[$groupId][$v] = $crmDAO->$fullField;
966 $groupTree[$groupId]['fields'] = array();
969 // add the fields now (note - the query row will always contain a field)
970 $groupTree[$groupId]['fields'][$fieldId] = array();
971 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
973 foreach ($tableData['civicrm_custom_field'] as $v) {
974 $fullField = "civicrm_custom_field_" . $v;
975 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
978 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
985 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
987 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
989 // get 'Tab' and 'Tab with table' groups
990 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
991 $customGroupDAO->whereAdd("is_active = 1");
993 // add whereAdd for entity type
994 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
998 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
999 $customGroupDAO->whereAdd($permissionClause);
1002 $customGroupDAO->orderBy('weight');
1003 $customGroupDAO->find();
1005 // process each group with menu tab
1006 while ($customGroupDAO->fetch()) {
1008 $group['id'] = $customGroupDAO->id
;
1009 $group['path'] = $path;
1010 $group['title'] = "$customGroupDAO->title";
1011 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1012 $group['extra'] = array('gid' => $customGroupDAO->id
);
1013 $group['table_name'] = $customGroupDAO->table_name
;
1021 * Get the table name for the entity type
1022 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1023 * tableName is 'civicrm_contact'
1025 * @param string $entityType what entity are we extending here ?
1027 * @return string $tableName
1033 private static function _getTableName($entityType) {
1035 switch ($entityType) {
1039 case 'Organization':
1040 $tableName = 'civicrm_contact';
1043 case 'Contribution':
1044 $tableName = 'civicrm_contribution';
1048 $tableName = 'civicrm_group';
1050 // DRAFTING: Verify if we cannot make it pluggable
1053 $tableName = 'civicrm_activity';
1056 case 'Relationship':
1057 $tableName = 'civicrm_relationship';
1061 $tableName = 'civicrm_membership';
1065 $tableName = 'civicrm_participant';
1069 $tableName = 'civicrm_event';
1073 $tableName = 'civicrm_grant';
1075 // need to add cases for Location, Address
1082 * Get a list of custom groups which extend a given entity type.
1083 * If there are custom-groups which only apply to certain subtypes,
1084 * those WILL be included.
1086 * @param $entityType string
1087 * @return CRM_Core_DAO_CustomGroup
1089 static function getAllCustomGroupsByBaseEntity($entityType) {
1090 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1091 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1092 return $customGroupDAO;
1096 * Add the whereAdd clause for the DAO depending on the type of entity
1097 * the custom group is extending.
1099 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
1100 * @param string $entityType - what entity are we extending here ?
1108 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1109 $addSubtypeClause = FALSE;
1111 switch ($entityType) {
1113 // if contact, get all related to contact
1114 $extendList = "'Contact','Individual','Household','Organization'";
1115 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1116 if (!$allSubtypes) {
1117 $addSubtypeClause = TRUE;
1123 case 'Organization':
1124 // is I/H/O then get I/H/O and contact
1125 $extendList = "'Contact','$entityType'";
1126 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1127 if (!$allSubtypes) {
1128 $addSubtypeClause = TRUE;
1135 case 'Contribution':
1138 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1142 if ($addSubtypeClause) {
1143 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1145 if (!empty($csType)) {
1146 $subtypeClause = array();
1147 foreach ($csType as $subtype) {
1148 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
1149 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1151 $subtypeClause[] = "extends_entity_column_value IS NULL";
1152 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) . " )");
1155 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1161 * Delete the Custom Group.
1163 * @param $group object the DAO custom group object
1164 * @param $force boolean whether to force the deletion, even if there are custom fields
1166 * @return boolean false if field exists for this group, true if group gets deleted.
1172 public static function deleteGroup($group, $force = FALSE) {
1174 //check wheter this contain any custom fields
1175 $customField = new CRM_Core_DAO_CustomField();
1176 $customField->custom_group_id
= $group->id
;
1177 $customField->find();
1179 // return early if there are custom fields and we're not
1180 // forcing the delete, otherwise delete the fields one by one
1181 while ($customField->fetch()) {
1185 CRM_Core_BAO_CustomField
::deleteField($customField);
1188 // drop the table associated with this custom group
1189 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1191 //delete custom group
1194 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1199 static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1200 foreach ($groupTree as $id => $group) {
1201 if (!isset($group['fields'])) {
1204 $groupId = CRM_Utils_Array
::value('id', $group);
1205 foreach ($group['fields'] as $field) {
1206 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1207 $value = $field['element_value'];
1209 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1210 ($action != CRM_Core_Action
::UPDATE ||
1212 !array_key_exists('element_value', $field)
1215 $value = $viewMode ?
NULL : $field['default_value'];
1221 $fieldId = $field['id'];
1222 $elementName = $field['element_name'];
1223 switch ($field['html_type']) {
1224 case 'Multi-Select':
1225 case 'AdvMulti-Select':
1227 $defaults[$elementName] = array();
1228 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1230 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1231 if (isset($value)) {
1232 foreach ($customOption as $customValue => $customLabel) {
1233 if (in_array($customValue, $checkedData)) {
1234 if ($field['html_type'] == 'CheckBox') {
1235 $defaults[$elementName][$customValue] = 1;
1238 $defaults[$elementName][$customValue] = $customValue;
1242 $defaults[$elementName][$customValue] = 0;
1248 if (isset($field['customValue']['data'])) {
1249 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1250 foreach ($customOption as $val) {
1251 if (in_array($val['value'], $checkedData)) {
1252 if ($field['html_type'] == 'CheckBox') {
1253 $defaults[$elementName][$val['value']] = 1;
1256 $defaults[$elementName][$val['value']] = $val['value'];
1260 $defaults[$elementName][$val['value']] = 0;
1265 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1266 foreach ($customOption as $val) {
1267 if (in_array($val['value'], $checkedValue)) {
1268 if ($field['html_type'] == 'CheckBox') {
1269 $defaults[$elementName][$val['value']] = 1;
1272 $defaults[$elementName][$val['value']] = $val['value'];
1281 if (isset($value)) {
1282 if (empty($field['time_format'])) {
1283 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1284 $field['date_format']
1288 $timeElement = $elementName . '_time';
1289 if (substr($elementName, -1) == ']') {
1290 $timeElement = substr($elementName, 0, -1) . '_time]';
1292 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1297 case 'Multi-Select Country':
1298 case 'Multi-Select State/Province':
1299 if (isset($value)) {
1300 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1301 foreach ($checkedValue as $val) {
1303 $defaults[$elementName][$val] = $val;
1309 case 'Select Country':
1311 $defaults[$elementName] = $value;
1314 $config = CRM_Core_Config
::singleton();
1315 $defaults[$elementName] = $config->defaultContactCountry
;
1319 case 'Autocomplete-Select':
1320 $hiddenEleName = $elementName . '_id';
1321 if (substr($elementName, -1) == ']') {
1322 $hiddenEleName = substr($elementName, 0, -1) . '_id]';
1324 if ($field['data_type'] == "ContactReference") {
1325 if (is_numeric($value)) {
1326 $defaults[$hiddenEleName] = $value;
1327 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1331 $defaults[$elementName] = $value;
1336 if ($field['data_type'] == "Float") {
1337 $defaults[$elementName] = (float)$value;
1339 elseif ($field['data_type'] == 'Money' &&
1340 $field['html_type'] == 'Text'
1342 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1345 $defaults[$elementName] = $value;
1352 static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1353 // Get the Custom form values and groupTree
1354 // first reset all checkbox and radio data
1355 foreach ($groupTree as $groupID => $group) {
1356 if ($groupID === 'info') {
1359 foreach ($group['fields'] as $field) {
1360 $fieldId = $field['id'];
1362 //added Multi-Select option in the below if-statement
1363 if ($field['html_type'] == 'CheckBox' ||
$field['html_type'] == 'Radio' ||
1364 $field['html_type'] == 'AdvMulti-Select' ||
$field['html_type'] == 'Multi-Select'
1366 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1370 foreach ($params as $key => $val) {
1371 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1372 $match[1] == $field['id']
1379 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1380 // field exists in db so populate value from "form".
1381 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1384 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1386 //added for CheckBox
1390 $customValue = array_keys($v);
1391 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1394 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1398 //added for Advanced Multi-Select
1400 case 'AdvMulti-Select':
1401 //added for Multi-Select
1402 case 'Multi-Select':
1404 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1407 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1412 $date = CRM_Utils_Date
::processDate($v);
1413 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1421 //store the file in d/b
1422 $entityId = explode('=', $groupTree['info']['where'][0]);
1423 $fileParams = array('upload_date' => date('Ymdhis'));
1425 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1426 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1429 $fileParams['uri'] = $v['name'];
1430 $fileParams['mime_type'] = $v['type'];
1431 CRM_Core_BAO_File
::filePostProcess($v['name'],
1432 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1433 $groupTree[$groupID]['table_name'],
1438 'custom_' . $fieldId,
1442 $defaults = array();
1443 $paramsFile = array(
1444 'entity_table' => $groupTree[$groupID]['table_name'],
1445 'entity_id' => $entityId[1],
1448 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1453 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1457 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1465 * generic function to build all the form elements for a specific group tree
1467 * @param object $form the form object
1468 * @param array $groupTree the group tree object
1469 * @param boolean $inactiveNeeded return inactive custom groups
1470 * @param string $prefix prefix for custom grouptree assigned to template
1476 static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '' ) {
1477 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1479 // this is fix for date field
1480 $form->assign('currentYear', date('Y'));
1482 foreach ($groupTree as $id => $group) {
1483 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1484 foreach ($group['fields'] as $field) {
1485 $required = CRM_Utils_Array
::value('is_required', $field);
1487 if ($field['data_type'] == 'File') {
1488 if (!empty($field['element_value']['data'])) {
1493 $fieldId = $field['id'];
1494 $elementName = $field['element_name'];
1495 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1498 if (!empty($form->_stateCountryMap
['state_province']) && !empty($form->_stateCountryMap
['country'])) {
1499 foreach ($form->_stateCountryMap
['state_province'] as $key => $value) {
1500 $stateCountryMap[$key]['state_province'] = $value;
1501 $stateCountryMap[$key]['country'] = $form->_stateCountryMap
['country'][$key];
1503 CRM_Core_BAO_Address
::addStateCountryMap($stateCountryMap);
1508 * Function to extract the get params from the url, validate
1509 * and store it in session
1511 * @param CRM_Core_Form $form the form object
1512 * @param string $type the type of custom group we are using
1518 static function extractGetParams(&$form, $type) {
1519 // if not GET params return
1524 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1525 $customValue = array();
1526 $htmlType = array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Select', 'Radio');
1528 foreach ($groupTree as $group) {
1529 if (!isset($group['fields'])) {
1532 foreach ($group['fields'] as $key => $field) {
1533 $fieldName = 'custom_' . $key;
1534 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1538 if (!in_array($field['html_type'], $htmlType) ||
1539 $field['data_type'] == 'Boolean'
1541 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1543 if ($field['html_type'] == 'CheckBox' ||
1544 $field['html_type'] == 'AdvMulti-Select' ||
1545 $field['html_type'] == 'Multi-Select'
1547 $value = str_replace("|", ",", $value);
1548 $mulValues = explode(',', $value);
1549 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1551 foreach ($mulValues as $v1) {
1552 foreach ($customOption as $coID => $coValue) {
1553 if (strtolower(trim($coValue['label'])) == strtolower(trim($v1))) {
1554 $val[$coValue['value']] = 1;
1566 elseif ($field['html_type'] == 'Select' ||
1567 ($field['html_type'] == 'Radio' &&
1568 $field['data_type'] != 'Boolean'
1571 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1572 foreach ($customOption as $customID => $coValue) {
1573 if (strtolower(trim($coValue['label'])) == strtolower(trim($value))) {
1574 $value = $coValue['value'];
1579 elseif ($field['data_type'] == 'Date') {
1580 if (!empty($value)) {
1582 if (!empty($field['time_format'])) {
1583 $time = CRM_Utils_Request
::retrieve($fieldName . '_time', 'String', $form, FALSE, NULL, 'GET');
1585 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value . ' ' . $time);
1586 if (!empty($field['time_format'])) {
1587 $customValue[$fieldName . '_time'] = $time;
1594 $customValue[$fieldName] = $value;
1600 return $customValue;
1604 * Function to check the type of custom field type (eg: Used for Individual, Contribution, etc)
1605 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1607 * @param int $customFieldId custom field id
1608 * @param array $removeCustomFieldTypes remove custom fields of a type eg: array("Individual") ;
1611 * @return boolean false if it matches else true
1615 static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1616 $query = "SELECT cg.extends as extends
1617 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1618 WHERE cg.id = cf.custom_group_id
1619 AND cf.id =" . CRM_Utils_Type
::escape($customFieldId, 'Integer');
1621 $extends = CRM_Core_DAO
::singleValueQuery($query);
1623 if (in_array($extends, $removeCustomFieldTypes)) {
1629 static function mapTableName($table) {
1634 case 'Organization':
1635 return 'civicrm_contact';
1638 return 'civicrm_activity';
1641 return 'civicrm_group';
1643 case 'Contribution':
1644 return 'civicrm_contribution';
1646 case 'Relationship':
1647 return 'civicrm_relationship';
1650 return 'civicrm_event';
1653 return 'civicrm_membership';
1656 case 'ParticipantRole':
1657 case 'ParticipantEventName':
1658 case 'ParticipantEventType':
1659 return 'civicrm_participant';
1662 return 'civicrm_grant';
1665 return 'civicrm_pledge';
1668 return 'civicrm_address';
1671 return 'civicrm_campaign';
1675 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1676 $qParams = array(1 => array($table, 'String'));
1677 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1680 return 'civicrm_contact';
1683 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1684 if (array_key_exists($table, $extendObjs)) {
1685 return $extendObjs[$table];
1687 CRM_Core_Error
::fatal();
1692 static function createTable($group) {
1694 'name' => $group->table_name
,
1695 'is_multiple' => $group->is_multiple ?
1 : 0,
1696 'extends_name' => self
::mapTableName($group->extends),
1699 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1701 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1705 * Function returns formatted groupTree, sothat form can be easily build in template
1707 * @param array $groupTree associated array
1708 * @param int $groupCount group count by default 1, but can varry for multiple value custom data
1709 * @param object form object
1711 * @return array $formattedGroupTree
1713 static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1714 $formattedGroupTree = array();
1715 $uploadNames = array();
1717 foreach ($groupTree as $key => $value) {
1718 if ($key === 'info') {
1722 // add group information
1723 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1724 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1725 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1726 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1727 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1728 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1730 // this params needed of bulding multiple values
1731 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1732 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1733 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1734 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1735 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1736 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1738 // add field information
1739 foreach ($value['fields'] as $k => $properties) {
1740 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1741 if (isset($properties['customValue']) && !CRM_Utils_system
::isNull($properties['customValue'])) {
1742 if (isset($properties['customValue'][$groupCount])) {
1743 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1744 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1745 if ($properties['data_type'] == 'File') {
1746 $properties['element_value'] = $properties['customValue'][$groupCount];
1747 $uploadNames[] = $properties['element_name'];
1750 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1754 unset($properties['customValue']);
1755 $formattedGroupTree[$key]['fields'][$k] = $properties;
1760 // hack for field type File
1761 $formUploadNames = $form->get('uploadNames');
1762 if (is_array($formUploadNames)) {
1763 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1766 $form->set('uploadNames', $uploadNames);
1769 return $formattedGroupTree;
1773 * Build custom data view
1774 * @param object $form page object
1775 * @param array $groupTree associated array
1776 * @param boolean $returnCount true if customValue count needs to be returned
1778 static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1780 foreach ($groupTree as $key => $group) {
1781 if ($key === 'info') {
1785 foreach ($group['fields'] as $k => $properties) {
1786 $groupID = $group['id'];
1787 if (!empty($properties['customValue'])) {
1788 foreach ($properties['customValue'] as $values) {
1789 if (!empty($customValueId) && $customValueId != $values['id']) {
1792 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1793 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1794 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1795 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1796 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1797 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1798 $details[$groupID][$values['id']]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties),
1799 'field_type' => CRM_Utils_Array
::value('html_type',
1802 'field_data_type' => CRM_Utils_Array
::value('data_type',
1805 'field_value' => self
::formatCustomValues($values,
1808 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1812 // also return contact reference contact id if user has view all or edit all contacts perm
1813 if ((CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts'))
1814 && $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] == 'ContactReference'
1816 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1821 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1822 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1823 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1824 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1825 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1826 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1827 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1833 //return a single value count if group id is passed to function
1834 //else return a groupId and count mapped array
1836 return count($details[$gID]);
1839 $countValue = array();
1840 foreach( $details as $key => $value ) {
1841 $countValue[$key] = count($details[$key]);
1847 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1853 * Format custom value according to data, view mode
1855 * @param array $values associated array of custom values
1856 * @param array $field associated array
1857 * @param boolean $dncOptionPerLine true if optionPerLine should not be consider
1860 static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1861 $value = $values['data'];
1863 //changed isset CRM-4601
1864 if (CRM_Utils_System
::isNull($value)) {
1868 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1869 $dataType = CRM_Utils_Array
::value('data_type', $field);
1870 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1871 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1872 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1875 $freezeStringChecked = "";
1877 switch ($dataType) {
1879 $customTimeFormat = '';
1880 $customFormat = NULL;
1882 switch ($timeFormat) {
1884 $customTimeFormat = '%l:%M %P';
1888 $customTimeFormat = '%H:%M';
1892 // if time is not selected remove time from value
1893 $value = substr($value, 0, 10);
1896 $supportableFormats = array(
1897 'mm/dd' => "%B %E%f $customTimeFormat",
1898 'dd-mm' => "%E%f %B $customTimeFormat",
1899 'yy' => "%Y $customTimeFormat",
1900 'M yy' => "%b %Y $customTimeFormat",
1901 'yy-mm' => "%Y-%m $customTimeFormat"
1904 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
1905 if (array_key_exists($format, $supportableFormats)) {
1906 $customFormat = $supportableFormats["$format"];
1910 $retValue = CRM_Utils_Date
::customFormat($value, $customFormat);
1914 if ($value == '1') {
1915 $retValue = $freezeStringChecked . ts('Yes') . "\n";
1918 $retValue = $freezeStringChecked . ts('No') . "\n";
1924 $retValue = CRM_Utils_System
::formatWikiURL($value);
1929 $retValue = $values;
1932 case 'ContactReference':
1933 if (!empty($values['data'])) {
1934 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
1943 if ($htmlType == 'Text') {
1944 $retValue = (float)$value;
1948 if ($htmlType == 'Text') {
1949 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1954 if (in_array($htmlType, array('Text', 'TextArea'))) {
1958 // note that if its not text / textarea, the code falls thru and executes
1959 // the below case also
1960 case 'StateProvince':
1965 //added check for Multi-Select in the below if-statement
1966 $customData[] = $value;
1968 //form custom data for multiple-valued custom data
1969 switch ($htmlType) {
1970 case 'Multi-Select Country':
1971 case 'Select Country':
1972 $customData = $value;
1973 if (!is_array($value)) {
1974 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1977 SELECT id as value, name as label
1978 FROM civicrm_country";
1979 $coDAO = CRM_Core_DAO
::executeQuery($query);
1982 case 'Select State/Province':
1983 case 'Multi-Select State/Province':
1984 $customData = $value;
1985 if (!is_array($value)) {
1986 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1990 SELECT id as value, name as label
1991 FROM civicrm_state_province";
1992 $coDAO = CRM_Core_DAO
::executeQuery($query);
1996 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1997 if ($option_group_id) {
1998 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2003 case 'AdvMulti-Select':
2004 case 'Multi-Select':
2005 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2007 if ($option_group_id) {
2008 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2012 if (is_object($coDAO)) {
2013 while ($coDAO->fetch()) {
2014 if ($dataType == 'Country') {
2015 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2016 // and already extracted to .pot files.
2017 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
2019 elseif ($dataType == 'StateProvince') {
2020 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
2023 $options[$coDAO->value
] = $coDAO->label
;
2028 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
2031 foreach ($options as $optionValue => $optionLabel) {
2032 if ($dataType == 'Money') {
2033 foreach ($customData as $k => $v) {
2034 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
2038 //to show only values that are checked
2039 if (in_array((string) $optionValue, $customData)) {
2040 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
2041 if (!$optionPerLine ||
$dncOptionPerLine) {
2045 $retValue .= $checked . $optionLabel;
2048 $retValue[] = $checked . $optionLabel;
2055 //special case for option per line formatting
2056 if ($optionPerLine > 1 && is_array($retValue)) {
2059 $displayValues = array();
2060 $displayString = '';
2061 foreach ($retValue as $val) {
2062 if ($displayString) {
2063 $displayString .= ", ";
2066 $displayString .= $val;
2070 if (($rowCounter == $optionPerLine) ||
($fieldCounter == count($retValue))) {
2071 $displayValues[] = $displayString;
2072 $displayString = '';
2076 $retValue = $displayValues;
2079 $retValue = isset($retValue) ?
$retValue : NULL;
2084 * Get the custom group titles by custom field ids.
2086 * @param array $fieldIds - array of custom field ids.
2088 * @return array $groupLabels - array consisting of groups and fields labels with ids.
2091 public static function getGroupTitles($fieldIds) {
2092 if (!is_array($fieldIds) && empty($fieldIds)) {
2096 $groupLabels = array();
2097 $fIds = "(" . implode(',', $fieldIds) . ")";
2100 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2101 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2102 FROM civicrm_custom_group, civicrm_custom_field
2103 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2104 AND civicrm_custom_field.id IN {$fIds}";
2106 $dao = CRM_Core_DAO
::executeQuery($query);
2107 while ($dao->fetch()) {
2108 $groupLabels[$dao->fieldID
] = array(
2109 'fieldID' => $dao->fieldID
,
2110 'fieldLabel' => $dao->fieldLabel
,
2111 'groupID' => $dao->groupID
,
2112 'groupTitle' => $dao->groupTitle
,
2116 return $groupLabels;
2119 static function dropAllTables() {
2120 $query = "SELECT table_name FROM civicrm_custom_group";
2121 $dao = CRM_Core_DAO
::executeQuery($query);
2123 while ($dao->fetch()) {
2124 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2125 CRM_Core_DAO
::executeQuery($query);
2130 * Check whether custom group is empty or not.
2132 * @param int $gID - custom group id.
2134 * @return boolean true if empty otherwise false.
2137 static function isGroupEmpty($gID) {
2142 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2147 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2148 $value = CRM_Core_DAO
::singleValueQuery($query);
2150 if (empty($value)) {
2158 * Get the list of types for objects that a custom group extends to.
2160 * @param array $types - var which should have the list appended.
2162 * @return array of types.
2165 static function getExtendedObjectTypes(&$types = array( )) {
2166 static $flag = FALSE, $objTypes = array();
2169 $extendObjs = array();
2170 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2172 foreach ($extendObjs as $ovId => $ovValues) {
2173 if ($ovValues['description']) {
2174 // description is expected to be a callback func to subtypes
2175 list($callback, $args) = explode(';', trim($ovValues['description']));
2181 if (!is_array($args)) {
2182 CRM_Core_Error
::fatal('Arg is not of type array');
2185 list($className) = explode('::', $callback);
2186 require_once (str_replace('_',DIRECTORY_SEPARATOR
, $className) . '.php');
2188 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2194 $types = array_merge($types, $objTypes);
2198 static function hasReachedMaxLimit($customGroupId, $entityId) {
2199 //check whether the group is multiple
2200 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2201 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2202 $hasReachedMax = FALSE;
2204 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))) {
2205 if (!$maxMultiple) {
2206 $hasReachedMax = FALSE;
2208 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2209 //count the number of entries for a entity
2210 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2211 $params = array(1 => array($entityId, 'Integer'));
2212 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2214 if ($count >= $maxMultiple) {
2215 $hasReachedMax = TRUE;
2219 return $hasReachedMax;
2222 static function getMultipleFieldGroup() {
2223 $multipleGroup = array();
2224 $dao = new CRM_Core_DAO_CustomGroup();
2225 $dao->is_multiple
= 1 ;
2227 while($dao->fetch()) {
2228 $multipleGroup[$dao->id
] = $dao->title
;
2230 return $multipleGroup;