3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * Business object for managing custom data groups
40 class CRM_Core_BAO_CustomGroup
extends CRM_Core_DAO_CustomGroup
{
45 function __construct() {
46 parent
::__construct();
50 * takes an associative array and creates a custom group object
52 * This function is invoked from within the web form layer and also from the api layer
54 * @param array $params (reference) an assoc array of name/value pairs
56 * @return object CRM_Core_DAO_CustomGroup object
60 static function create(&$params) {
61 // create custom group dao, populate fields and then save.
62 $group = new CRM_Core_DAO_CustomGroup();
63 $group->title
= $params['title'];
65 if (in_array($params['extends'][0],
68 'ParticipantEventName',
69 'ParticipantEventType',
72 $group->extends = 'Participant';
75 $group->extends = $params['extends'][0];
78 $group->extends_entity_column_id
= 'null';
80 $params['extends'][0] == 'ParticipantRole' ||
81 $params['extends'][0] == 'ParticipantEventName' ||
82 $params['extends'][0] == 'ParticipantEventType'
84 $group->extends_entity_column_id
=
85 CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $params['extends'][0], 'value', 'name');
88 //this is format when form get submit.
89 $extendsChildType = CRM_Utils_Array
::value(1, $params['extends']);
90 //lets allow user to pass direct child type value, CRM-6893
91 if (!empty($params['extends_entity_column_value'])) {
92 $extendsChildType = $params['extends_entity_column_value'];
94 if (!CRM_Utils_System
::isNull($extendsChildType)) {
95 $extendsChildType = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendsChildType);
96 if (CRM_Utils_Array
::value(0, $params['extends']) == 'Relationship') {
97 $extendsChildType = str_replace(array('_a_b', '_b_a'), array('', ''), $extendsChildType);
99 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
100 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType . CRM_Core_DAO
::VALUE_SEPARATOR
;
104 $extendsChildType = 'null';
106 $group->extends_entity_column_value
= $extendsChildType;
108 if (isset($params['id'])) {
109 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
114 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
115 $fields = array('style', 'collapse_display', 'collapse_adv_display', 'help_pre', 'help_post', 'is_active', 'is_multiple');
116 foreach ($fields as $field) {
117 $group->$field = CRM_Utils_Array
::value($field, $params, FALSE);
119 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
120 $params['max_multiple'] >= '0'
121 ) ?
$params['max_multiple'] : 'null' : 'null';
123 $tableName = $oldTableName = NULL;
124 if (isset($params['id'])) {
125 $group->id
= $params['id'];
126 //check whether custom group was changed from single-valued to multiple-valued
127 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
132 if ((!empty($params['is_multiple']) ||
$isMultiple) &&
133 ($params['is_multiple'] != $isMultiple)
135 $oldTableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
142 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
143 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
145 // we do this only once, so name never changes
146 if (isset($params['name'])) {
147 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
150 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
153 if (isset($params['table_name'])) {
154 $tableName = $params['table_name'];
156 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
157 // Bad idea. Prevent group creation because it might lead to a broken configuration.
158 CRM_Core_Error
::fatal(ts("Cannot create custom table because %1 is already a core table.", array('1' => $tableName)));
163 // 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
256 public static function hasCustomGroup($extends, $columnId, $columnValue) {
257 $dao = new CRM_Core_DAO_CustomGroup();
258 $dao->extends = $extends;
259 $dao->extends_entity_column_id
= $columnId;
260 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
261 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
262 //$dao->extends_entity_column_value = $columnValue;
263 return $dao->find() ?
TRUE : FALSE;
267 * Determine if there are any CustomGroups for the given $activityTypeId.
268 * If none found, create one.
270 * @param int $activityTypeId
271 * @return bool TRUE if a group is found or created; FALSE on error
273 public static function autoCreateByActivityType($activityTypeId) {
274 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
277 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
280 'extends' => 'Activity',
281 'extends_entity_column_id' => NULL,
282 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
283 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
287 $result = civicrm_api('CustomGroup', 'create', $params);
288 return ! $result['is_error'];
292 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
293 * This may also include entity specific data values.
295 * An array containing all custom groups and their custom fields is returned.
297 * @param string $entityType - of the contact whose contact type is needed
298 * @param object $form - not used but required
299 * @param null $entityID
300 * @param null $groupID
301 * @param string $subType
302 * @param string $subName
303 * @param boolean $fromCache
305 * @param null $onlySubType
307 * @internal param int $entityId - optional - id of entity if we need to populate the tree with custom values.
308 * @internal param int $groupId - optional group id (if we need it for a single group only)
309 * - if groupId is 0 it gets for inline groups only
310 * - if groupId is -1 we get for all groups
311 * @return array $groupTree - array The returned array is keyed by group id and has the custom group table fields
312 * and a subkey 'fields' holding the specific custom fields.
313 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
314 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
316 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
317 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
318 * With caching the performance impact would be small & the function would be cleaner
324 public static function &getTree(
335 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
339 $strSelect = $strFrom = $strWhere = $orderBy = '';
340 $tableData = array();
342 // using tableData to build the queryString
344 'civicrm_custom_field' =>
365 'civicrm_custom_group' =>
376 'extends_entity_column_id',
377 'extends_entity_column_value',
384 foreach ($tableData as $tableName => $tableColumn) {
385 foreach ($tableColumn as $columnName) {
386 $alias = $tableName . "_" . $columnName;
387 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
390 $strSelect = "SELECT " . implode(', ', $select);
392 // from, where, order by
394 FROM civicrm_custom_group
395 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
398 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
399 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
$entityType == 'Household') {
400 $in = "'$entityType', 'Contact'";
402 elseif (strpos($entityType, "'") !== FALSE) {
403 // this allows the calling function to send in multiple entity types
408 $in = "'$entityType'";
413 if (is_array($subType)) {
414 $subType = implode(',', $subType);
416 if (strpos($subType, ',')) {
417 $subTypeParts = explode(',', $subType);
418 $subTypeClauses = array();
419 foreach ($subTypeParts as $subTypePart) {
420 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
421 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
425 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
428 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
432 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
435 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
438 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
439 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
444 WHERE civicrm_custom_group.is_active = 1
445 AND civicrm_custom_field.is_active = 1
446 AND civicrm_custom_group.extends IN ($in)
450 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
455 WHERE civicrm_custom_group.is_active = 1
456 AND civicrm_custom_field.is_active = 1
457 AND civicrm_custom_group.extends IN ($in)
458 AND civicrm_custom_group.extends_entity_column_value IS NULL
464 // since we want a specific group id we add it to the where clause
465 $strWhere .= " AND civicrm_custom_group.id = %1";
466 $params[1] = array($groupID, 'Integer');
469 // since groupID is false we need to show all Inline groups
470 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
473 // ensure that the user has access to these custom groups
474 $strWhere .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
475 'civicrm_custom_group.'
479 ORDER BY civicrm_custom_group.weight,
480 civicrm_custom_group.title,
481 civicrm_custom_field.weight,
482 civicrm_custom_field.label
485 // final query string
486 $queryString = "$strSelect $strFrom $strWhere $orderBy";
488 // lets see if we can retrieve the groupTree from cache
489 $cacheString = $queryString;
490 if ( $groupID > 0 ) {
491 $cacheString .= "_{$groupID}";
493 $cacheString .= "_Inline";
496 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
497 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
498 $cache = CRM_Utils_Cache
::singleton();
499 $tablesWithEntityData = array();
501 $groupTree = $cache->get($cacheKey);
502 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
505 if (empty($groupTree)) {
506 $groupTree = $multipleFieldGroups =array();
507 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
508 $customValueTables = array();
511 while ($crmDAO->fetch()) {
513 $groupID = $crmDAO->civicrm_custom_group_id
;
514 $fieldId = $crmDAO->civicrm_custom_field_id
;
515 if($crmDAO->civicrm_custom_group_is_multiple
){
516 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
518 // create an array for groups if it does not exist
519 if (!array_key_exists($groupID, $groupTree)) {
520 $groupTree[$groupID] = array();
521 $groupTree[$groupID]['id'] = $groupID;
523 // populate the group information
524 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
525 $fullFieldName = "civicrm_custom_group_$fieldName";
526 if ($fieldName == 'id' ||
527 is_null($crmDAO->$fullFieldName)
532 if ($fieldName == 'extends_entity_column_value' && $subType) {
533 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
535 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
537 $groupTree[$groupID]['fields'] = array();
539 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
542 // add the fields now (note - the query row will always contain a field)
543 // we only reset this once, since multiple values come is as multiple rows
544 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
545 $groupTree[$groupID]['fields'][$fieldId] = array();
548 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
549 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
550 // populate information for a custom field
551 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
552 $fullFieldName = "civicrm_custom_field_$fieldName";
553 if ($fieldName == 'id' ||
554 is_null($crmDAO->$fullFieldName)
558 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
562 if (!empty($customValueTables)) {
563 $groupTree['info'] = array('tables' => $customValueTables);
566 $cache->set($cacheKey, $groupTree);
567 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
569 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
570 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
571 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
572 $singleFieldTables = array();
573 // now that we have all the groups and fields, lets get the values
574 // since we need to know the table and field names
575 // add info to groupTree
577 if (isset($groupTree['info']) && !empty($groupTree['info']) && !empty($groupTree['info']['tables'])) {
578 $select = $from = $where = array();
579 $groupTree['info']['where'] = NULL;
581 foreach ($groupTree['info']['tables'] as $table => $fields) {
582 $groupTree['info']['from'][] = $table;
583 $select = array("{$table}.id as {$table}_id",
584 "{$table}.entity_id as {$table}_entity_id");
585 foreach ($fields as $column => $dontCare) {
586 $select[] = "{$table}.{$column} as {$table}_{$column}";
588 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
590 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
591 if(in_array($table, $multipleFieldGroups) && self
::customGroupDataExistsForEntity($entityID, $table)){
592 $entityMultipleSelectClauses[$table] = $select;
595 $singleFieldTables[] = $table;
596 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
601 if ($entityID && !empty($singleFieldTables)) {
602 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
604 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
605 if(!empty($multipleFieldTablesWithEntityData)){
606 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
614 * Check whether the custom group has any data for the given entity.
617 * @param integer $entityID id of entity for whom we are checking data for
618 * @param string $table table that we are checking
620 * @param bool $getCount
622 * @return boolean does this entity have data in this custom table
624 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE){
628 WHERE entity_id = $entityID
630 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
632 return $recordExists;
634 return $recordExists ?
TRUE : FALSE;
638 * Build the group tree for Custom fields which are not 'is_multiple'
640 * The combination of all these fields in one query with a 'using' join was not working for
641 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
642 * mechanism as it seemed to be acceptable in this context
644 * @param array $groupTree (reference) group tree array which is being built
645 * @param integer $entityID id of entity for whom the tree is being build up.
646 * @param array $entitySingleSelectClauses array of select clauses relevant to the entity
647 * @param array $singleFieldTablesWithEntityData array of tables in which this entity has data
649 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData){
650 $select = implode(', ', $entitySingleSelectClauses);
651 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
652 foreach ($singleFieldTablesWithEntityData as $table) {
653 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
659 WHERE first.entity_id = $entityID
661 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
665 * Build the group tree for Custom fields which are 'is_multiple'
667 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
669 * @param array $groupTree (reference) group tree array which is being built
670 * @param integer $entityID id of entity for whom the tree is being build up.
671 * @param array $entityMultipleSelectClauses array of select clauses relevant to the entity
672 * @param array $multipleFieldTablesWithEntityData array of tables in which this entity has data
674 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData){
675 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
676 $select = implode(',', $selectClauses);
680 WHERE entity_id = $entityID
682 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
687 * Build the tree entity data - starting from a query retrieving the custom fields build the group
688 * tree data for the relevant entity (entity is included in the query).
690 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
692 * @param array $groupTree (reference) group tree array which is being built
693 * @param string $query
694 * @param array $includedTables tables to include - required because the function (for historical reasons)
695 * iterates through the group tree
697 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables){
698 $dao = CRM_Core_DAO
::executeQuery($query);
699 while ($dao->fetch()) {
700 foreach ($groupTree as $groupID => $group) {
701 if ($groupID === 'info') {
704 $table = $groupTree[$groupID]['table_name'];
705 //working from the groupTree instead of the table list means we have to iterate & exclude.
706 // this could possibly be re-written as other parts of the function have been refactored
707 // for now we just check if the given table is to be included in this function
708 if( !in_array($table, $includedTables)){
711 foreach ($group['fields'] as $fieldID => $dontCare) {
712 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
719 * Build the entity-specific custom data into the group tree on a per-field basis
721 * @param object $dao object representing the custom field to be populated into the groupTree
722 * @param array $groupTree (reference) the group tree being build
723 * @param string $table table name
724 * @param unknown_type $groupID custom group ID
725 * @param unknown_type $fieldID custom field ID
727 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID){
728 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
729 $idName = "{$table}_id";
730 $fieldName = "{$table}_{$column}";
731 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
732 if ($dataType == 'File') {
733 if (isset($dao->$fieldName)) {
734 $config = CRM_Core_Config
::singleton();
735 $fileDAO = new CRM_Core_DAO_File();
736 $fileDAO->id
= $dao->$fieldName;
738 if ($fileDAO->find(TRUE)) {
739 $entityIDName = "{$table}_entity_id";
740 $customValue['id'] = $dao->$idName;
741 $customValue['data'] = $fileDAO->uri
;
742 $customValue['fid'] = $fileDAO->id
;
743 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
744 $customValue['displayURL'] = NULL;
745 $deleteExtra = ts('Are you sure you want to delete attached file.');
747 CRM_Core_Action
::DELETE
=>
749 'name' => ts('Delete Attached File'),
750 'url' => 'civicrm/file',
751 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
753 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
756 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
757 CRM_Core_Action
::DELETE
,
759 'id' => $fileDAO->id
,
760 'eid' => $dao->$entityIDName,
765 'file.manage.delete',
769 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
770 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
771 if ($fileDAO->mime_type
== "image/jpeg" ||
772 $fileDAO->mime_type
== "image/pjpeg" ||
773 $fileDAO->mime_type
== "image/gif" ||
774 $fileDAO->mime_type
== "image/x-png" ||
775 $fileDAO->mime_type
== "image/png"
777 $customValue['displayURL'] = $customValue['fileURL'];
778 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
783 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) . $fileDAO->uri
;
784 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId,
787 if ($path && file_exists($path)) {
788 list($imageWidth, $imageHeight) = getimagesize($path);
789 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
790 $customValue['imageThumbWidth'] = $imageThumbWidth;
791 $customValue['imageThumbHeight'] = $imageThumbHeight;
797 $customValue = array(
798 'id' => $dao->$idName,
804 $customValue = array(
805 'id' => $dao->$idName,
806 'data' => $dao->$fieldName,
810 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
811 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
813 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
814 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
817 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
822 * Get the group title.
824 * @param int $id id of group.
826 * @return string title
832 public static function getTitle($id) {
833 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
837 * Get custom group details for a group.
839 * An array containing custom group details (including their custom field) is returned.
841 * @param int $groupId - group id whose details are needed
842 * @param boolean $searchable - is this field searchable
843 * @param array $extends - which table does it extend if any
845 * @param null $inSelector
847 * @return array $groupTree - array consisting of all group and field details
853 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
855 $groupTree = array();
856 $select = $from = $where = $orderBy = '';
858 $tableData = array();
860 // using tableData to build the queryString
862 'civicrm_custom_field' =>
887 'civicrm_custom_group' =>
895 'collapse_adv_display',
897 'extends_entity_column_value',
906 foreach ($tableData as $tableName => $tableColumn) {
907 foreach ($tableColumn as $columnName) {
908 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
911 $select = 'SELECT ' . implode(', ', $s);
913 // from, where, order by
914 $from = " FROM civicrm_custom_field, civicrm_custom_group";
915 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
916 AND civicrm_custom_group.is_active = 1
917 AND civicrm_custom_field.is_active = 1 ";
919 $params[1] = array($groupId, 'Integer');
920 $where .= " AND civicrm_custom_group.id = %1";
924 $where .= " AND civicrm_custom_field.is_searchable = 1";
928 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
933 foreach ($extends as $e) {
934 $clause[] = "civicrm_custom_group.extends = '$e'";
936 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
938 //include case activities customdata if case is enabled
939 if (in_array('Activity', $extends)) {
940 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
941 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
942 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
946 // ensure that the user has access to these custom groups
947 $where .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
948 'civicrm_custom_group.'
951 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
953 // final query string
954 $queryString = $select . $from . $where . $orderBy;
957 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
960 while ($crmDAO->fetch()) {
961 $groupId = $crmDAO->civicrm_custom_group_id
;
962 $fieldId = $crmDAO->civicrm_custom_field_id
;
964 // create an array for groups if it does not exist
965 if (!array_key_exists($groupId, $groupTree)) {
966 $groupTree[$groupId] = array();
967 $groupTree[$groupId]['id'] = $groupId;
969 foreach ($tableData['civicrm_custom_group'] as $v) {
970 $fullField = "civicrm_custom_group_" . $v;
972 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
976 $groupTree[$groupId][$v] = $crmDAO->$fullField;
979 $groupTree[$groupId]['fields'] = array();
982 // add the fields now (note - the query row will always contain a field)
983 $groupTree[$groupId]['fields'][$fieldId] = array();
984 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
986 foreach ($tableData['civicrm_custom_field'] as $v) {
987 $fullField = "civicrm_custom_field_" . $v;
988 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
991 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1001 * @param string $cidToken
1005 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1007 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1009 // get 'Tab' and 'Tab with table' groups
1010 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1011 $customGroupDAO->whereAdd("is_active = 1");
1013 // add whereAdd for entity type
1014 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1018 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1019 $customGroupDAO->whereAdd($permissionClause);
1022 $customGroupDAO->orderBy('weight');
1023 $customGroupDAO->find();
1025 // process each group with menu tab
1026 while ($customGroupDAO->fetch()) {
1028 $group['id'] = $customGroupDAO->id
;
1029 $group['path'] = $path;
1030 $group['title'] = "$customGroupDAO->title";
1031 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1032 $group['extra'] = array('gid' => $customGroupDAO->id
);
1033 $group['table_name'] = $customGroupDAO->table_name
;
1041 * Get the table name for the entity type
1042 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1043 * tableName is 'civicrm_contact'
1045 * @param string $entityType what entity are we extending here ?
1047 * @return string $tableName
1053 private static function _getTableName($entityType) {
1055 switch ($entityType) {
1059 case 'Organization':
1060 $tableName = 'civicrm_contact';
1063 case 'Contribution':
1064 $tableName = 'civicrm_contribution';
1068 $tableName = 'civicrm_group';
1070 // DRAFTING: Verify if we cannot make it pluggable
1073 $tableName = 'civicrm_activity';
1076 case 'Relationship':
1077 $tableName = 'civicrm_relationship';
1081 $tableName = 'civicrm_membership';
1085 $tableName = 'civicrm_participant';
1089 $tableName = 'civicrm_event';
1093 $tableName = 'civicrm_grant';
1095 // need to add cases for Location, Address
1102 * Get a list of custom groups which extend a given entity type.
1103 * If there are custom-groups which only apply to certain subtypes,
1104 * those WILL be included.
1106 * @param $entityType string
1107 * @return CRM_Core_DAO_CustomGroup
1109 static function getAllCustomGroupsByBaseEntity($entityType) {
1110 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1111 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1112 return $customGroupDAO;
1116 * Add the whereAdd clause for the DAO depending on the type of entity
1117 * the custom group is extending.
1119 * @param $customGroupDAO
1120 * @param string $entityType - what entity are we extending here ?
1122 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
1123 * @param bool $allSubtypes
1130 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1131 $addSubtypeClause = FALSE;
1133 switch ($entityType) {
1135 // if contact, get all related to contact
1136 $extendList = "'Contact','Individual','Household','Organization'";
1137 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1138 if (!$allSubtypes) {
1139 $addSubtypeClause = TRUE;
1145 case 'Organization':
1146 // is I/H/O then get I/H/O and contact
1147 $extendList = "'Contact','$entityType'";
1148 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1149 if (!$allSubtypes) {
1150 $addSubtypeClause = TRUE;
1158 case 'Contribution':
1161 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1165 if ($addSubtypeClause) {
1166 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1168 if (!empty($csType)) {
1169 $subtypeClause = array();
1170 foreach ($csType as $subtype) {
1171 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
1172 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1174 $subtypeClause[] = "extends_entity_column_value IS NULL";
1175 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) . " )");
1178 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1184 * Delete the Custom Group.
1186 * @param $group object the DAO custom group object
1187 * @param $force boolean whether to force the deletion, even if there are custom fields
1189 * @return boolean false if field exists for this group, true if group gets deleted.
1195 public static function deleteGroup($group, $force = FALSE) {
1197 //check wheter this contain any custom fields
1198 $customField = new CRM_Core_DAO_CustomField();
1199 $customField->custom_group_id
= $group->id
;
1200 $customField->find();
1202 // return early if there are custom fields and we're not
1203 // forcing the delete, otherwise delete the fields one by one
1204 while ($customField->fetch()) {
1208 CRM_Core_BAO_CustomField
::deleteField($customField);
1211 // drop the table associated with this custom group
1212 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1214 //delete custom group
1217 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1225 * @param bool $viewMode
1226 * @param bool $inactiveNeeded
1227 * @param int $action
1229 static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1230 foreach ($groupTree as $id => $group) {
1231 if (!isset($group['fields'])) {
1234 $groupId = CRM_Utils_Array
::value('id', $group);
1235 foreach ($group['fields'] as $field) {
1236 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1237 $value = $field['element_value'];
1239 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1240 ($action != CRM_Core_Action
::UPDATE ||
1242 !array_key_exists('element_value', $field)
1245 $value = $viewMode ?
NULL : $field['default_value'];
1251 $fieldId = $field['id'];
1252 $elementName = $field['element_name'];
1253 switch ($field['html_type']) {
1254 case 'Multi-Select':
1255 case 'AdvMulti-Select':
1257 $defaults[$elementName] = array();
1258 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1260 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1261 if (isset($value)) {
1262 foreach ($customOption as $customValue => $customLabel) {
1263 if (in_array($customValue, $checkedData)) {
1264 if ($field['html_type'] == 'CheckBox') {
1265 $defaults[$elementName][$customValue] = 1;
1268 $defaults[$elementName][$customValue] = $customValue;
1272 $defaults[$elementName][$customValue] = 0;
1278 if (isset($field['customValue']['data'])) {
1279 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1280 foreach ($customOption as $val) {
1281 if (in_array($val['value'], $checkedData)) {
1282 if ($field['html_type'] == 'CheckBox') {
1283 $defaults[$elementName][$val['value']] = 1;
1286 $defaults[$elementName][$val['value']] = $val['value'];
1290 $defaults[$elementName][$val['value']] = 0;
1295 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1296 foreach ($customOption as $val) {
1297 if (in_array($val['value'], $checkedValue)) {
1298 if ($field['html_type'] == 'CheckBox') {
1299 $defaults[$elementName][$val['value']] = 1;
1302 $defaults[$elementName][$val['value']] = $val['value'];
1311 if (isset($value)) {
1312 if (empty($field['time_format'])) {
1313 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1314 $field['date_format']
1318 $timeElement = $elementName . '_time';
1319 if (substr($elementName, -1) == ']') {
1320 $timeElement = substr($elementName, 0, -1) . '_time]';
1322 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1327 case 'Multi-Select Country':
1328 case 'Multi-Select State/Province':
1329 if (isset($value)) {
1330 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1331 foreach ($checkedValue as $val) {
1333 $defaults[$elementName][$val] = $val;
1339 case 'Select Country':
1341 $defaults[$elementName] = $value;
1344 $config = CRM_Core_Config
::singleton();
1345 $defaults[$elementName] = $config->defaultContactCountry
;
1350 if ($field['data_type'] == "Float") {
1351 $defaults[$elementName] = (float)$value;
1353 elseif ($field['data_type'] == 'Money' &&
1354 $field['html_type'] == 'Text'
1356 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1359 $defaults[$elementName] = $value;
1369 * @param bool $skipFile
1371 static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1372 // Get the Custom form values and groupTree
1373 // first reset all checkbox and radio data
1374 foreach ($groupTree as $groupID => $group) {
1375 if ($groupID === 'info') {
1378 foreach ($group['fields'] as $field) {
1379 $fieldId = $field['id'];
1381 //added Multi-Select option in the below if-statement
1382 if ($field['html_type'] == 'CheckBox' ||
$field['html_type'] == 'Radio' ||
1383 $field['html_type'] == 'AdvMulti-Select' ||
$field['html_type'] == 'Multi-Select'
1385 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1389 foreach ($params as $key => $val) {
1390 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1391 $match[1] == $field['id']
1398 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1399 // field exists in db so populate value from "form".
1400 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1403 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1405 //added for CheckBox
1409 $customValue = array_keys($v);
1410 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1413 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1417 //added for Advanced Multi-Select
1419 case 'AdvMulti-Select':
1420 //added for Multi-Select
1421 case 'Multi-Select':
1423 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1426 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1431 $date = CRM_Utils_Date
::processDate($v);
1432 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1440 //store the file in d/b
1441 $entityId = explode('=', $groupTree['info']['where'][0]);
1442 $fileParams = array('upload_date' => date('Ymdhis'));
1444 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1445 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1448 $fileParams['uri'] = $v['name'];
1449 $fileParams['mime_type'] = $v['type'];
1450 CRM_Core_BAO_File
::filePostProcess($v['name'],
1451 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1452 $groupTree[$groupID]['table_name'],
1457 'custom_' . $fieldId,
1461 $defaults = array();
1462 $paramsFile = array(
1463 'entity_table' => $groupTree[$groupID]['table_name'],
1464 'entity_id' => $entityId[1],
1467 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1472 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1476 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1484 * generic function to build all the form elements for a specific group tree
1486 * @param object $form the form object
1487 * @param array $groupTree the group tree object
1488 * @param boolean $inactiveNeeded return inactive custom groups
1489 * @param string $prefix prefix for custom grouptree assigned to template
1495 static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '' ) {
1496 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1498 // this is fix for date field
1499 $form->assign('currentYear', date('Y'));
1501 foreach ($groupTree as $id => $group) {
1502 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1503 foreach ($group['fields'] as $field) {
1504 $required = CRM_Utils_Array
::value('is_required', $field);
1506 if ($field['data_type'] == 'File') {
1507 if (!empty($field['element_value']['data'])) {
1512 $fieldId = $field['id'];
1513 $elementName = $field['element_name'];
1514 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1517 if (!empty($form->_stateCountryMap
['state_province']) && !empty($form->_stateCountryMap
['country'])) {
1518 foreach ($form->_stateCountryMap
['state_province'] as $key => $value) {
1519 $stateCountryMap[$key]['state_province'] = $value;
1520 $stateCountryMap[$key]['country'] = $form->_stateCountryMap
['country'][$key];
1522 CRM_Core_BAO_Address
::addStateCountryMap($stateCountryMap);
1527 * Function to extract the get params from the url, validate
1528 * and store it in session
1530 * @param CRM_Core_Form $form the form object
1531 * @param string $type the type of custom group we are using
1537 static function extractGetParams(&$form, $type) {
1538 // if not GET params return
1543 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1544 $customValue = array();
1545 $htmlType = array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Select', 'Radio');
1547 foreach ($groupTree as $group) {
1548 if (!isset($group['fields'])) {
1551 foreach ($group['fields'] as $key => $field) {
1552 $fieldName = 'custom_' . $key;
1553 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1557 if (!in_array($field['html_type'], $htmlType) ||
1558 $field['data_type'] == 'Boolean'
1560 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1562 if ($field['html_type'] == 'CheckBox' ||
1563 $field['html_type'] == 'AdvMulti-Select' ||
1564 $field['html_type'] == 'Multi-Select'
1566 $value = str_replace("|", ",", $value);
1567 $mulValues = explode(',', $value);
1568 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1570 foreach ($mulValues as $v1) {
1571 foreach ($customOption as $coID => $coValue) {
1572 if (strtolower(trim($coValue['label'])) == strtolower(trim($v1))) {
1573 $val[$coValue['value']] = 1;
1585 elseif ($field['html_type'] == 'Select' ||
1586 ($field['html_type'] == 'Radio' &&
1587 $field['data_type'] != 'Boolean'
1590 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1591 foreach ($customOption as $customID => $coValue) {
1592 if (strtolower(trim($coValue['label'])) == strtolower(trim($value))) {
1593 $value = $coValue['value'];
1598 elseif ($field['data_type'] == 'Date') {
1599 if (!empty($value)) {
1601 if (!empty($field['time_format'])) {
1602 $time = CRM_Utils_Request
::retrieve($fieldName . '_time', 'String', $form, FALSE, NULL, 'GET');
1604 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value . ' ' . $time);
1605 if (!empty($field['time_format'])) {
1606 $customValue[$fieldName . '_time'] = $time;
1613 $customValue[$fieldName] = $value;
1619 return $customValue;
1623 * Function to check the type of custom field type (eg: Used for Individual, Contribution, etc)
1624 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1626 * @param int $customFieldId custom field id
1627 * @param array $removeCustomFieldTypes remove custom fields of a type eg: array("Individual") ;
1630 * @return boolean false if it matches else true
1634 static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1635 $query = "SELECT cg.extends as extends
1636 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1637 WHERE cg.id = cf.custom_group_id
1638 AND cf.id =" . CRM_Utils_Type
::escape($customFieldId, 'Integer');
1640 $extends = CRM_Core_DAO
::singleValueQuery($query);
1642 if (in_array($extends, $removeCustomFieldTypes)) {
1654 static function mapTableName($table) {
1659 case 'Organization':
1660 return 'civicrm_contact';
1663 return 'civicrm_activity';
1666 return 'civicrm_group';
1668 case 'Contribution':
1669 return 'civicrm_contribution';
1671 case 'Relationship':
1672 return 'civicrm_relationship';
1675 return 'civicrm_event';
1678 return 'civicrm_membership';
1681 case 'ParticipantRole':
1682 case 'ParticipantEventName':
1683 case 'ParticipantEventType':
1684 return 'civicrm_participant';
1687 return 'civicrm_grant';
1690 return 'civicrm_pledge';
1693 return 'civicrm_address';
1696 return 'civicrm_campaign';
1700 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1701 $qParams = array(1 => array($table, 'String'));
1702 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1705 return 'civicrm_contact';
1708 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1709 if (array_key_exists($table, $extendObjs)) {
1710 return $extendObjs[$table];
1712 CRM_Core_Error
::fatal();
1720 static function createTable($group) {
1722 'name' => $group->table_name
,
1723 'is_multiple' => $group->is_multiple ?
1 : 0,
1724 'extends_name' => self
::mapTableName($group->extends),
1727 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1729 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1733 * Function returns formatted groupTree, sothat form can be easily build in template
1735 * @param array $groupTree associated array
1736 * @param int $groupCount group count by default 1, but can varry for multiple value custom data
1737 * @param object form object
1739 * @return array $formattedGroupTree
1741 static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1742 $formattedGroupTree = array();
1743 $uploadNames = array();
1745 foreach ($groupTree as $key => $value) {
1746 if ($key === 'info') {
1750 // add group information
1751 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1752 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1753 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1754 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1755 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1756 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1758 // this params needed of bulding multiple values
1759 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1760 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1761 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1762 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1763 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1764 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1766 // add field information
1767 foreach ($value['fields'] as $k => $properties) {
1768 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1769 if (isset($properties['customValue']) && !CRM_Utils_System
::isNull($properties['customValue'])) {
1770 if (isset($properties['customValue'][$groupCount])) {
1771 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1772 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1773 if ($properties['data_type'] == 'File') {
1774 $properties['element_value'] = $properties['customValue'][$groupCount];
1775 $uploadNames[] = $properties['element_name'];
1778 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1782 unset($properties['customValue']);
1783 $formattedGroupTree[$key]['fields'][$k] = $properties;
1788 // hack for field type File
1789 $formUploadNames = $form->get('uploadNames');
1790 if (is_array($formUploadNames)) {
1791 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1794 $form->set('uploadNames', $uploadNames);
1797 return $formattedGroupTree;
1801 * Build custom data view
1803 * @param object $form page object
1804 * @param array $groupTree associated array
1805 * @param boolean $returnCount true if customValue count needs to be returned
1807 * @param null $prefix
1808 * @param null $customValueId
1812 static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1814 foreach ($groupTree as $key => $group) {
1815 if ($key === 'info') {
1819 foreach ($group['fields'] as $k => $properties) {
1820 $groupID = $group['id'];
1821 if (!empty($properties['customValue'])) {
1822 foreach ($properties['customValue'] as $values) {
1823 if (!empty($customValueId) && $customValueId != $values['id']) {
1826 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1827 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1828 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1829 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1830 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1831 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1832 $details[$groupID][$values['id']]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties),
1833 'field_type' => CRM_Utils_Array
::value('html_type',
1836 'field_data_type' => CRM_Utils_Array
::value('data_type',
1839 'field_value' => self
::formatCustomValues($values,
1842 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1846 // also return contact reference contact id if user has view all or edit all contacts perm
1847 if ((CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts'))
1848 && $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] == 'ContactReference'
1850 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1855 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1856 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1857 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1858 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1859 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1860 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1861 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1867 //return a single value count if group id is passed to function
1868 //else return a groupId and count mapped array
1870 return count($details[$gID]);
1873 $countValue = array();
1874 foreach( $details as $key => $value ) {
1875 $countValue[$key] = count($details[$key]);
1881 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1887 * Format custom value according to data, view mode
1889 * @param array $values associated array of custom values
1890 * @param array $field associated array
1891 * @param boolean $dncOptionPerLine true if optionPerLine should not be consider
1893 * @return array|null|string
1895 static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1896 $value = $values['data'];
1898 //changed isset CRM-4601
1899 if (CRM_Utils_System
::isNull($value)) {
1903 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1904 $dataType = CRM_Utils_Array
::value('data_type', $field);
1905 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1906 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1907 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1910 $freezeStringChecked = "";
1912 switch ($dataType) {
1914 $customTimeFormat = '';
1915 $customFormat = NULL;
1917 switch ($timeFormat) {
1919 $customTimeFormat = '%l:%M %P';
1923 $customTimeFormat = '%H:%M';
1927 // if time is not selected remove time from value
1928 $value = substr($value, 0, 10);
1931 $supportableFormats = array(
1932 'mm/dd' => "%B %E%f $customTimeFormat",
1933 'dd-mm' => "%E%f %B $customTimeFormat",
1934 'yy' => "%Y $customTimeFormat",
1935 'M yy' => "%b %Y $customTimeFormat",
1936 'yy-mm' => "%Y-%m $customTimeFormat"
1939 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
1940 if (array_key_exists($format, $supportableFormats)) {
1941 $customFormat = $supportableFormats["$format"];
1945 $retValue = CRM_Utils_Date
::customFormat($value, $customFormat);
1949 if ($value == '1') {
1950 $retValue = $freezeStringChecked . ts('Yes') . "\n";
1953 $retValue = $freezeStringChecked . ts('No') . "\n";
1959 $retValue = CRM_Utils_System
::formatWikiURL($value);
1964 $retValue = $values;
1967 case 'ContactReference':
1968 if (!empty($values['data'])) {
1969 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
1978 if ($htmlType == 'Text') {
1979 $retValue = (float)$value;
1983 if ($htmlType == 'Text') {
1984 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1989 if (in_array($htmlType, array('Text', 'TextArea'))) {
1993 // note that if its not text / textarea, the code falls thru and executes
1994 // the below case also
1995 case 'StateProvince':
2000 //added check for Multi-Select in the below if-statement
2001 $customData[] = $value;
2003 //form custom data for multiple-valued custom data
2004 switch ($htmlType) {
2005 case 'Multi-Select Country':
2006 case 'Select Country':
2007 $customData = $value;
2008 if (!is_array($value)) {
2009 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2012 SELECT id as value, name as label
2013 FROM civicrm_country";
2014 $coDAO = CRM_Core_DAO
::executeQuery($query);
2017 case 'Select State/Province':
2018 case 'Multi-Select State/Province':
2019 $customData = $value;
2020 if (!is_array($value)) {
2021 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2025 SELECT id as value, name as label
2026 FROM civicrm_state_province";
2027 $coDAO = CRM_Core_DAO
::executeQuery($query);
2031 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2032 if ($option_group_id) {
2033 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2038 case 'AdvMulti-Select':
2039 case 'Multi-Select':
2040 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2042 if ($option_group_id) {
2043 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2047 if (is_object($coDAO)) {
2048 while ($coDAO->fetch()) {
2049 if ($dataType == 'Country') {
2050 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2051 // and already extracted to .pot files.
2052 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
2054 elseif ($dataType == 'StateProvince') {
2055 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
2058 $options[$coDAO->value
] = $coDAO->label
;
2063 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
2066 foreach ($options as $optionValue => $optionLabel) {
2067 if ($dataType == 'Money') {
2068 foreach ($customData as $k => $v) {
2069 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
2073 //to show only values that are checked
2074 if (in_array((string) $optionValue, $customData)) {
2075 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
2076 if (!$optionPerLine ||
$dncOptionPerLine) {
2080 $retValue .= $checked . $optionLabel;
2083 $retValue[] = $checked . $optionLabel;
2090 //special case for option per line formatting
2091 if ($optionPerLine > 1 && is_array($retValue)) {
2094 $displayValues = array();
2095 $displayString = '';
2096 foreach ($retValue as $val) {
2097 if ($displayString) {
2098 $displayString .= ", ";
2101 $displayString .= $val;
2105 if (($rowCounter == $optionPerLine) ||
($fieldCounter == count($retValue))) {
2106 $displayValues[] = $displayString;
2107 $displayString = '';
2111 $retValue = $displayValues;
2114 $retValue = isset($retValue) ?
$retValue : NULL;
2119 * Get the custom group titles by custom field ids.
2121 * @param array $fieldIds - array of custom field ids.
2123 * @return array $groupLabels - array consisting of groups and fields labels with ids.
2126 public static function getGroupTitles($fieldIds) {
2127 if (!is_array($fieldIds) && empty($fieldIds)) {
2131 $groupLabels = array();
2132 $fIds = "(" . implode(',', $fieldIds) . ")";
2135 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2136 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2137 FROM civicrm_custom_group, civicrm_custom_field
2138 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2139 AND civicrm_custom_field.id IN {$fIds}";
2141 $dao = CRM_Core_DAO
::executeQuery($query);
2142 while ($dao->fetch()) {
2143 $groupLabels[$dao->fieldID
] = array(
2144 'fieldID' => $dao->fieldID
,
2145 'fieldLabel' => $dao->fieldLabel
,
2146 'groupID' => $dao->groupID
,
2147 'groupTitle' => $dao->groupTitle
,
2151 return $groupLabels;
2154 static function dropAllTables() {
2155 $query = "SELECT table_name FROM civicrm_custom_group";
2156 $dao = CRM_Core_DAO
::executeQuery($query);
2158 while ($dao->fetch()) {
2159 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2160 CRM_Core_DAO
::executeQuery($query);
2165 * Check whether custom group is empty or not.
2167 * @param int $gID - custom group id.
2169 * @return boolean true if empty otherwise false.
2172 static function isGroupEmpty($gID) {
2177 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2182 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2183 $value = CRM_Core_DAO
::singleValueQuery($query);
2185 if (empty($value)) {
2193 * Get the list of types for objects that a custom group extends to.
2195 * @param array $types - var which should have the list appended.
2197 * @return array of types.
2200 static function getExtendedObjectTypes(&$types = array( )) {
2201 static $flag = FALSE, $objTypes = array();
2204 $extendObjs = array();
2205 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2207 foreach ($extendObjs as $ovId => $ovValues) {
2208 if ($ovValues['description']) {
2209 // description is expected to be a callback func to subtypes
2210 list($callback, $args) = explode(';', trim($ovValues['description']));
2216 if (!is_array($args)) {
2217 CRM_Core_Error
::fatal('Arg is not of type array');
2220 list($className) = explode('::', $callback);
2221 require_once (str_replace('_',DIRECTORY_SEPARATOR
, $className) . '.php');
2223 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2229 $types = array_merge($types, $objTypes);
2234 * @param $customGroupId
2239 static function hasReachedMaxLimit($customGroupId, $entityId) {
2240 //check whether the group is multiple
2241 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2242 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2243 $hasReachedMax = FALSE;
2245 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))) {
2246 if (!$maxMultiple) {
2247 $hasReachedMax = FALSE;
2249 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2250 //count the number of entries for a entity
2251 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2252 $params = array(1 => array($entityId, 'Integer'));
2253 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2255 if ($count >= $maxMultiple) {
2256 $hasReachedMax = TRUE;
2260 return $hasReachedMax;
2266 static function getMultipleFieldGroup() {
2267 $multipleGroup = array();
2268 $dao = new CRM_Core_DAO_CustomGroup();
2269 $dao->is_multiple
= 1 ;
2271 while($dao->fetch()) {
2272 $multipleGroup[$dao->id
] = $dao->title
;
2274 return $multipleGroup;