3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * Business object for managing custom data groups
40 class CRM_Core_BAO_CustomGroup
extends CRM_Core_DAO_CustomGroup
{
45 function __construct() {
46 parent
::__construct();
50 * takes an associative array and creates a custom group object
52 * This function is invoked from within the web form layer and also from the api layer
54 * @param array $params (reference) an assoc array of name/value pairs
56 * @return object CRM_Core_DAO_CustomGroup object
60 static function create(&$params) {
61 // create custom group dao, populate fields and then save.
62 $group = new CRM_Core_DAO_CustomGroup();
63 $group->title
= $params['title'];
65 if (in_array($params['extends'][0],
68 'ParticipantEventName',
69 'ParticipantEventType',
72 $group->extends = 'Participant';
75 $group->extends = $params['extends'][0];
78 $group->extends_entity_column_id
= 'null';
80 $params['extends'][0] == 'ParticipantRole' ||
81 $params['extends'][0] == 'ParticipantEventName' ||
82 $params['extends'][0] == 'ParticipantEventType'
84 $group->extends_entity_column_id
=
85 CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $params['extends'][0], 'value', 'name');
88 //this is format when form get submit.
89 $extendsChildType = CRM_Utils_Array
::value(1, $params['extends']);
90 //lets allow user to pass direct child type value, CRM-6893
91 if (!empty($params['extends_entity_column_value'])) {
92 $extendsChildType = $params['extends_entity_column_value'];
94 if (!CRM_Utils_System
::isNull($extendsChildType)) {
95 $extendsChildType = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendsChildType);
96 if (CRM_Utils_Array
::value(0, $params['extends']) == 'Relationship') {
97 $extendsChildType = str_replace(array('_a_b', '_b_a'), array('', ''), $extendsChildType);
99 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
100 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType . CRM_Core_DAO
::VALUE_SEPARATOR
;
104 $extendsChildType = 'null';
106 $group->extends_entity_column_value
= $extendsChildType;
108 if (isset($params['id'])) {
109 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
114 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
115 $fields = array('style', 'collapse_display', 'collapse_adv_display', 'help_pre', 'help_post', 'is_active', 'is_multiple');
116 foreach ($fields as $field) {
117 $group->$field = CRM_Utils_Array
::value($field, $params, FALSE);
119 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
120 $params['max_multiple'] >= '0'
121 ) ?
$params['max_multiple'] : 'null' : 'null';
123 $tableName = $oldTableName = NULL;
124 if (isset($params['id'])) {
125 $group->id
= $params['id'];
126 //check whether custom group was changed from single-valued to multiple-valued
127 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
132 if ((!empty($params['is_multiple']) ||
$isMultiple) &&
133 ($params['is_multiple'] != $isMultiple)
135 $oldTableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
142 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
143 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
145 // we do this only once, so name never changes
146 if (isset($params['name'])) {
147 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
150 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
153 if (isset($params['table_name'])) {
154 $tableName = $params['table_name'];
156 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
157 // Bad idea. Prevent group creation because it might lead to a broken configuration.
158 CRM_Core_Error
::fatal(ts("Cannot create custom table because %1 is already a core table.", array('1' => $tableName)));
163 if (array_key_exists('is_reserved', $params)) {
164 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
166 $op = isset($params['id']) ?
'edit' : 'create';
167 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
169 // enclose the below in a transaction
170 $transaction = new CRM_Core_Transaction();
173 if (!isset($params['id'])) {
174 if (!isset($params['table_name'])) {
175 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 42));
176 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
178 $group->table_name
= $tableName;
179 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
185 // now create the table associated with this group
186 self
::createTable($group);
188 elseif ($oldTableName) {
189 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($oldTableName, CRM_Utils_Array
::value('is_multiple', $params));
192 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
193 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
197 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends'][0]));
199 $transaction->commit();
202 CRM_Utils_System
::flushCache();
205 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
208 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
215 * Takes a bunch of params that are needed to match certain criteria and
216 * retrieves the relevant objects. Typically the valid params are only
217 * contact_id. We'll tweak this function to be more full featured over a period
218 * of time. This is the inverse function of create. It also stores all the retrieved
219 * values in the default array
221 * @param array $params (reference ) an assoc array of name/value pairs
222 * @param array $defaults (reference ) an assoc array to hold the flattened values
224 * @return object CRM_Core_DAO_CustomGroup object
228 static function retrieve(&$params, &$defaults) {
229 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
233 * update the is_active flag in the db
235 * @param int $id id of the database record
236 * @param boolean $is_active value we want to set the is_active field
238 * @return Object DAO object on sucess, null otherwise
242 static function setIsActive($id, $is_active) {
244 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
247 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
250 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
254 * Determine if given entity (sub)type has any custom groups
256 * @param string $extends e.g. "Individual", "Activity"
257 * @param int $columnId e.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id
258 * @param string $columnValue e.g. "Student" or "3" or "3\05"; see extends_entity_column_value
262 public static function hasCustomGroup($extends, $columnId, $columnValue) {
263 $dao = new CRM_Core_DAO_CustomGroup();
264 $dao->extends = $extends;
265 $dao->extends_entity_column_id
= $columnId;
266 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
267 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
268 //$dao->extends_entity_column_value = $columnValue;
269 return $dao->find() ?
TRUE : FALSE;
273 * Determine if there are any CustomGroups for the given $activityTypeId.
274 * If none found, create one.
276 * @param int $activityTypeId
277 * @return bool TRUE if a group is found or created; FALSE on error
279 public static function autoCreateByActivityType($activityTypeId) {
280 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
283 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
286 'extends' => 'Activity',
287 'extends_entity_column_id' => NULL,
288 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
289 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
293 $result = civicrm_api('CustomGroup', 'create', $params);
294 return ! $result['is_error'];
298 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
299 * This may also include entity specific data values.
301 * An array containing all custom groups and their custom fields is returned.
303 * @param string $entityType - of the contact whose contact type is needed
304 * @param object $form - not used but required
305 * @param null $entityID
306 * @param null $groupID
307 * @param string $subType
308 * @param string $subName
309 * @param boolean $fromCache
311 * @param null $onlySubType
313 * @internal param int $entityId - optional - id of entity if we need to populate the tree with custom values.
314 * @internal param int $groupId - optional group id (if we need it for a single group only)
315 * - if groupId is 0 it gets for inline groups only
316 * - if groupId is -1 we get for all groups
317 * @return array $groupTree - array The returned array is keyed by group id and has the custom group table fields
318 * and a subkey 'fields' holding the specific custom fields.
319 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
320 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
322 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
323 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
324 * With caching the performance impact would be small & the function would be cleaner
330 public static function &getTree(
341 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
345 $strSelect = $strFrom = $strWhere = $orderBy = '';
346 $tableData = array();
348 // using tableData to build the queryString
350 'civicrm_custom_field' =>
371 'civicrm_custom_group' =>
382 'extends_entity_column_id',
383 'extends_entity_column_value',
390 foreach ($tableData as $tableName => $tableColumn) {
391 foreach ($tableColumn as $columnName) {
392 $alias = $tableName . "_" . $columnName;
393 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
396 $strSelect = "SELECT " . implode(', ', $select);
398 // from, where, order by
400 FROM civicrm_custom_group
401 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
404 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
405 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
$entityType == 'Household') {
406 $in = "'$entityType', 'Contact'";
408 elseif (strpos($entityType, "'") !== FALSE) {
409 // this allows the calling function to send in multiple entity types
414 $in = "'$entityType'";
419 if (is_array($subType)) {
420 $subType = implode(',', $subType);
422 if (strpos($subType, ',')) {
423 $subTypeParts = explode(',', $subType);
424 $subTypeClauses = array();
425 foreach ($subTypeParts as $subTypePart) {
426 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
427 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
431 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
434 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
438 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
441 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
444 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
445 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
450 WHERE civicrm_custom_group.is_active = 1
451 AND civicrm_custom_field.is_active = 1
452 AND civicrm_custom_group.extends IN ($in)
456 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
461 WHERE civicrm_custom_group.is_active = 1
462 AND civicrm_custom_field.is_active = 1
463 AND civicrm_custom_group.extends IN ($in)
464 AND civicrm_custom_group.extends_entity_column_value IS NULL
470 // since we want a specific group id we add it to the where clause
471 $strWhere .= " AND civicrm_custom_group.id = %1";
472 $params[1] = array($groupID, 'Integer');
475 // since groupID is false we need to show all Inline groups
476 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
479 // ensure that the user has access to these custom groups
480 $strWhere .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
481 'civicrm_custom_group.'
485 ORDER BY civicrm_custom_group.weight,
486 civicrm_custom_group.title,
487 civicrm_custom_field.weight,
488 civicrm_custom_field.label
491 // final query string
492 $queryString = "$strSelect $strFrom $strWhere $orderBy";
494 // lets see if we can retrieve the groupTree from cache
495 $cacheString = $queryString;
496 if ( $groupID > 0 ) {
497 $cacheString .= "_{$groupID}";
499 $cacheString .= "_Inline";
502 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
503 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
504 $cache = CRM_Utils_Cache
::singleton();
505 $tablesWithEntityData = array();
507 $groupTree = $cache->get($cacheKey);
508 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
511 if (empty($groupTree)) {
512 $groupTree = $multipleFieldGroups =array();
513 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
514 $customValueTables = array();
517 while ($crmDAO->fetch()) {
519 $groupID = $crmDAO->civicrm_custom_group_id
;
520 $fieldId = $crmDAO->civicrm_custom_field_id
;
521 if($crmDAO->civicrm_custom_group_is_multiple
){
522 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
524 // create an array for groups if it does not exist
525 if (!array_key_exists($groupID, $groupTree)) {
526 $groupTree[$groupID] = array();
527 $groupTree[$groupID]['id'] = $groupID;
529 // populate the group information
530 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
531 $fullFieldName = "civicrm_custom_group_$fieldName";
532 if ($fieldName == 'id' ||
533 is_null($crmDAO->$fullFieldName)
538 if ($fieldName == 'extends_entity_column_value' && $subType) {
539 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
541 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
543 $groupTree[$groupID]['fields'] = array();
545 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
548 // add the fields now (note - the query row will always contain a field)
549 // we only reset this once, since multiple values come is as multiple rows
550 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
551 $groupTree[$groupID]['fields'][$fieldId] = array();
554 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
555 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
556 // populate information for a custom field
557 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
558 $fullFieldName = "civicrm_custom_field_$fieldName";
559 if ($fieldName == 'id' ||
560 is_null($crmDAO->$fullFieldName)
564 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
568 if (!empty($customValueTables)) {
569 $groupTree['info'] = array('tables' => $customValueTables);
572 $cache->set($cacheKey, $groupTree);
573 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
575 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
576 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
577 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
578 $singleFieldTables = array();
579 // now that we have all the groups and fields, lets get the values
580 // since we need to know the table and field names
581 // add info to groupTree
583 if (isset($groupTree['info']) && !empty($groupTree['info']) && !empty($groupTree['info']['tables'])) {
584 $select = $from = $where = array();
585 $groupTree['info']['where'] = NULL;
587 foreach ($groupTree['info']['tables'] as $table => $fields) {
588 $groupTree['info']['from'][] = $table;
589 $select = array("{$table}.id as {$table}_id",
590 "{$table}.entity_id as {$table}_entity_id");
591 foreach ($fields as $column => $dontCare) {
592 $select[] = "{$table}.{$column} as {$table}_{$column}";
594 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
596 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
597 if(in_array($table, $multipleFieldGroups) && self
::customGroupDataExistsForEntity($entityID, $table)){
598 $entityMultipleSelectClauses[$table] = $select;
601 $singleFieldTables[] = $table;
602 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
607 if ($entityID && !empty($singleFieldTables)) {
608 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
610 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
611 if(!empty($multipleFieldTablesWithEntityData)){
612 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
620 * Check whether the custom group has any data for the given entity.
623 * @param integer $entityID id of entity for whom we are checking data for
624 * @param string $table table that we are checking
626 * @param bool $getCount
628 * @return boolean does this entity have data in this custom table
630 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE){
634 WHERE entity_id = $entityID
636 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
638 return $recordExists;
640 return $recordExists ?
TRUE : FALSE;
644 * Build the group tree for Custom fields which are not 'is_multiple'
646 * The combination of all these fields in one query with a 'using' join was not working for
647 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
648 * mechanism as it seemed to be acceptable in this context
650 * @param array $groupTree (reference) group tree array which is being built
651 * @param integer $entityID id of entity for whom the tree is being build up.
652 * @param array $entitySingleSelectClauses array of select clauses relevant to the entity
653 * @param array $singleFieldTablesWithEntityData array of tables in which this entity has data
655 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData){
656 $select = implode(', ', $entitySingleSelectClauses);
657 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
658 foreach ($singleFieldTablesWithEntityData as $table) {
659 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
665 WHERE first.entity_id = $entityID
667 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
671 * Build the group tree for Custom fields which are 'is_multiple'
673 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
675 * @param array $groupTree (reference) group tree array which is being built
676 * @param integer $entityID id of entity for whom the tree is being build up.
677 * @param array $entityMultipleSelectClauses array of select clauses relevant to the entity
678 * @param array $multipleFieldTablesWithEntityData array of tables in which this entity has data
680 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData){
681 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
682 $select = implode(',', $selectClauses);
686 WHERE entity_id = $entityID
688 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
693 * Build the tree entity data - starting from a query retrieving the custom fields build the group
694 * tree data for the relevant entity (entity is included in the query).
696 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
698 * @param array $groupTree (reference) group tree array which is being built
699 * @param string $query
700 * @param array $includedTables tables to include - required because the function (for historical reasons)
701 * iterates through the group tree
703 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables){
704 $dao = CRM_Core_DAO
::executeQuery($query);
705 while ($dao->fetch()) {
706 foreach ($groupTree as $groupID => $group) {
707 if ($groupID === 'info') {
710 $table = $groupTree[$groupID]['table_name'];
711 //working from the groupTree instead of the table list means we have to iterate & exclude.
712 // this could possibly be re-written as other parts of the function have been refactored
713 // for now we just check if the given table is to be included in this function
714 if( !in_array($table, $includedTables)){
717 foreach ($group['fields'] as $fieldID => $dontCare) {
718 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
725 * Build the entity-specific custom data into the group tree on a per-field basis
727 * @param object $dao object representing the custom field to be populated into the groupTree
728 * @param array $groupTree (reference) the group tree being build
729 * @param string $table table name
730 * @param unknown_type $groupID custom group ID
731 * @param unknown_type $fieldID custom field ID
733 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID){
734 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
735 $idName = "{$table}_id";
736 $fieldName = "{$table}_{$column}";
737 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
738 if ($dataType == 'File') {
739 if (isset($dao->$fieldName)) {
740 $config = CRM_Core_Config
::singleton();
741 $fileDAO = new CRM_Core_DAO_File();
742 $fileDAO->id
= $dao->$fieldName;
744 if ($fileDAO->find(TRUE)) {
745 $entityIDName = "{$table}_entity_id";
746 $customValue['id'] = $dao->$idName;
747 $customValue['data'] = $fileDAO->uri
;
748 $customValue['fid'] = $fileDAO->id
;
749 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
750 $customValue['displayURL'] = NULL;
751 $deleteExtra = ts('Are you sure you want to delete attached file.');
753 CRM_Core_Action
::DELETE
=>
755 'name' => ts('Delete Attached File'),
756 'url' => 'civicrm/file',
757 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
759 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
762 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
763 CRM_Core_Action
::DELETE
,
765 'id' => $fileDAO->id
,
766 'eid' => $dao->$entityIDName,
771 'file.manage.delete',
775 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
776 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
777 if ($fileDAO->mime_type
== "image/jpeg" ||
778 $fileDAO->mime_type
== "image/pjpeg" ||
779 $fileDAO->mime_type
== "image/gif" ||
780 $fileDAO->mime_type
== "image/x-png" ||
781 $fileDAO->mime_type
== "image/png"
783 $customValue['displayURL'] = $customValue['fileURL'];
784 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
789 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) . $fileDAO->uri
;
790 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId,
793 if ($path && file_exists($path)) {
794 list($imageWidth, $imageHeight) = getimagesize($path);
795 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
796 $customValue['imageThumbWidth'] = $imageThumbWidth;
797 $customValue['imageThumbHeight'] = $imageThumbHeight;
803 $customValue = array(
804 'id' => $dao->$idName,
810 $customValue = array(
811 'id' => $dao->$idName,
812 'data' => $dao->$fieldName,
816 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
817 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
819 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
820 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
823 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
828 * Get the group title.
830 * @param int $id id of group.
832 * @return string title
838 public static function getTitle($id) {
839 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
843 * Get custom group details for a group.
845 * An array containing custom group details (including their custom field) is returned.
847 * @param int $groupId - group id whose details are needed
848 * @param boolean $searchable - is this field searchable
849 * @param array $extends - which table does it extend if any
851 * @param null $inSelector
853 * @return array $groupTree - array consisting of all group and field details
859 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
861 $groupTree = array();
862 $select = $from = $where = $orderBy = '';
864 $tableData = array();
866 // using tableData to build the queryString
868 'civicrm_custom_field' =>
893 'civicrm_custom_group' =>
901 'collapse_adv_display',
903 'extends_entity_column_value',
912 foreach ($tableData as $tableName => $tableColumn) {
913 foreach ($tableColumn as $columnName) {
914 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
917 $select = 'SELECT ' . implode(', ', $s);
919 // from, where, order by
920 $from = " FROM civicrm_custom_field, civicrm_custom_group";
921 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
922 AND civicrm_custom_group.is_active = 1
923 AND civicrm_custom_field.is_active = 1 ";
925 $params[1] = array($groupId, 'Integer');
926 $where .= " AND civicrm_custom_group.id = %1";
930 $where .= " AND civicrm_custom_field.is_searchable = 1";
934 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
939 foreach ($extends as $e) {
940 $clause[] = "civicrm_custom_group.extends = '$e'";
942 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
944 //include case activities customdata if case is enabled
945 if (in_array('Activity', $extends)) {
946 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
947 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
948 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
952 // ensure that the user has access to these custom groups
953 $where .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
954 'civicrm_custom_group.'
957 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
959 // final query string
960 $queryString = $select . $from . $where . $orderBy;
963 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
966 while ($crmDAO->fetch()) {
967 $groupId = $crmDAO->civicrm_custom_group_id
;
968 $fieldId = $crmDAO->civicrm_custom_field_id
;
970 // create an array for groups if it does not exist
971 if (!array_key_exists($groupId, $groupTree)) {
972 $groupTree[$groupId] = array();
973 $groupTree[$groupId]['id'] = $groupId;
975 foreach ($tableData['civicrm_custom_group'] as $v) {
976 $fullField = "civicrm_custom_group_" . $v;
978 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
982 $groupTree[$groupId][$v] = $crmDAO->$fullField;
985 $groupTree[$groupId]['fields'] = array();
988 // add the fields now (note - the query row will always contain a field)
989 $groupTree[$groupId]['fields'][$fieldId] = array();
990 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
992 foreach ($tableData['civicrm_custom_field'] as $v) {
993 $fullField = "civicrm_custom_field_" . $v;
994 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
997 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1005 * @param $entityType
1007 * @param string $cidToken
1011 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1013 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1015 // get 'Tab' and 'Tab with table' groups
1016 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1017 $customGroupDAO->whereAdd("is_active = 1");
1019 // add whereAdd for entity type
1020 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1024 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1025 $customGroupDAO->whereAdd($permissionClause);
1028 $customGroupDAO->orderBy('weight');
1029 $customGroupDAO->find();
1031 // process each group with menu tab
1032 while ($customGroupDAO->fetch()) {
1034 $group['id'] = $customGroupDAO->id
;
1035 $group['path'] = $path;
1036 $group['title'] = "$customGroupDAO->title";
1037 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1038 $group['extra'] = array('gid' => $customGroupDAO->id
);
1039 $group['table_name'] = $customGroupDAO->table_name
;
1040 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1048 * Get the table name for the entity type
1049 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1050 * tableName is 'civicrm_contact'
1052 * @param string $entityType what entity are we extending here ?
1054 * @return string $tableName
1059 * @see _apachesolr_civiAttachments_dereference_file_parent
1061 public static function getTableNameByEntityName($entityType) {
1063 switch ($entityType) {
1067 case 'Organization':
1068 $tableName = 'civicrm_contact';
1071 case 'Contribution':
1072 $tableName = 'civicrm_contribution';
1076 $tableName = 'civicrm_group';
1078 // DRAFTING: Verify if we cannot make it pluggable
1081 $tableName = 'civicrm_activity';
1084 case 'Relationship':
1085 $tableName = 'civicrm_relationship';
1089 $tableName = 'civicrm_membership';
1093 $tableName = 'civicrm_participant';
1097 $tableName = 'civicrm_event';
1101 $tableName = 'civicrm_grant';
1103 // need to add cases for Location, Address
1110 * Get a list of custom groups which extend a given entity type.
1111 * If there are custom-groups which only apply to certain subtypes,
1112 * those WILL be included.
1114 * @param $entityType string
1115 * @return CRM_Core_DAO_CustomGroup
1117 static function getAllCustomGroupsByBaseEntity($entityType) {
1118 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1119 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1120 return $customGroupDAO;
1124 * Add the whereAdd clause for the DAO depending on the type of entity
1125 * the custom group is extending.
1127 * @param $customGroupDAO
1128 * @param string $entityType - what entity are we extending here ?
1130 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
1131 * @param bool $allSubtypes
1138 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1139 $addSubtypeClause = FALSE;
1141 switch ($entityType) {
1143 // if contact, get all related to contact
1144 $extendList = "'Contact','Individual','Household','Organization'";
1145 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1146 if (!$allSubtypes) {
1147 $addSubtypeClause = TRUE;
1153 case 'Organization':
1154 // is I/H/O then get I/H/O and contact
1155 $extendList = "'Contact','$entityType'";
1156 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1157 if (!$allSubtypes) {
1158 $addSubtypeClause = TRUE;
1166 case 'Contribution':
1169 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1173 if ($addSubtypeClause) {
1174 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1176 if (!empty($csType)) {
1177 $subtypeClause = array();
1178 foreach ($csType as $subtype) {
1179 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
1180 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1182 $subtypeClause[] = "extends_entity_column_value IS NULL";
1183 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) . " )");
1186 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1192 * Delete the Custom Group.
1194 * @param $group object the DAO custom group object
1195 * @param $force boolean whether to force the deletion, even if there are custom fields
1197 * @return boolean false if field exists for this group, true if group gets deleted.
1203 public static function deleteGroup($group, $force = FALSE) {
1205 //check wheter this contain any custom fields
1206 $customField = new CRM_Core_DAO_CustomField();
1207 $customField->custom_group_id
= $group->id
;
1208 $customField->find();
1210 // return early if there are custom fields and we're not
1211 // forcing the delete, otherwise delete the fields one by one
1212 while ($customField->fetch()) {
1216 CRM_Core_BAO_CustomField
::deleteField($customField);
1219 // drop the table associated with this custom group
1220 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1222 //delete custom group
1225 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1233 * @param bool $viewMode
1234 * @param bool $inactiveNeeded
1235 * @param int $action
1237 static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1238 foreach ($groupTree as $id => $group) {
1239 if (!isset($group['fields'])) {
1242 foreach ($group['fields'] as $field) {
1243 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1244 $value = $field['element_value'];
1246 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1247 ($action != CRM_Core_Action
::UPDATE ||
1249 !array_key_exists('element_value', $field)
1252 $value = $viewMode ?
NULL : $field['default_value'];
1258 if (!empty($field['element_name'])) {
1259 $elementName = $field['element_name'];
1261 switch ($field['html_type']) {
1262 case 'Multi-Select':
1263 case 'AdvMulti-Select':
1265 $defaults[$elementName] = array();
1266 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1268 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1269 if (isset($value)) {
1270 foreach ($customOption as $customValue => $customLabel) {
1271 if (in_array($customValue, $checkedData)) {
1272 if ($field['html_type'] == 'CheckBox') {
1273 $defaults[$elementName][$customValue] = 1;
1276 $defaults[$elementName][$customValue] = $customValue;
1280 $defaults[$elementName][$customValue] = 0;
1286 if (isset($field['customValue']['data'])) {
1287 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1288 foreach ($customOption as $val) {
1289 if (in_array($val['value'], $checkedData)) {
1290 if ($field['html_type'] == 'CheckBox') {
1291 $defaults[$elementName][$val['value']] = 1;
1294 $defaults[$elementName][$val['value']] = $val['value'];
1298 $defaults[$elementName][$val['value']] = 0;
1303 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1304 foreach ($customOption as $val) {
1305 if (in_array($val['value'], $checkedValue)) {
1306 if ($field['html_type'] == 'CheckBox') {
1307 $defaults[$elementName][$val['value']] = 1;
1310 $defaults[$elementName][$val['value']] = $val['value'];
1319 if (isset($value)) {
1320 if (empty($field['time_format'])) {
1321 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1322 $field['date_format']
1326 $timeElement = $elementName . '_time';
1327 if (substr($elementName, -1) == ']') {
1328 $timeElement = substr($elementName, 0, -1) . '_time]';
1330 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1335 case 'Multi-Select Country':
1336 case 'Multi-Select State/Province':
1337 if (isset($value)) {
1338 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1339 foreach ($checkedValue as $val) {
1341 $defaults[$elementName][$val] = $val;
1347 case 'Select Country':
1349 $defaults[$elementName] = $value;
1352 $config = CRM_Core_Config
::singleton();
1353 $defaults[$elementName] = $config->defaultContactCountry
;
1358 if ($field['data_type'] == "Float") {
1359 $defaults[$elementName] = (float)$value;
1361 elseif ($field['data_type'] == 'Money' &&
1362 $field['html_type'] == 'Text'
1364 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1367 $defaults[$elementName] = $value;
1377 * @param bool $skipFile
1379 static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1380 // Get the Custom form values and groupTree
1381 // first reset all checkbox and radio data
1382 foreach ($groupTree as $groupID => $group) {
1383 if ($groupID === 'info') {
1386 foreach ($group['fields'] as $field) {
1387 $fieldId = $field['id'];
1389 //added Multi-Select option in the below if-statement
1390 if ($field['html_type'] == 'CheckBox' ||
$field['html_type'] == 'Radio' ||
1391 $field['html_type'] == 'AdvMulti-Select' ||
$field['html_type'] == 'Multi-Select'
1393 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1397 foreach ($params as $key => $val) {
1398 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1399 $match[1] == $field['id']
1406 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1407 // field exists in db so populate value from "form".
1408 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1411 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1413 //added for CheckBox
1417 $customValue = array_keys($v);
1418 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1421 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1425 //added for Advanced Multi-Select
1427 case 'AdvMulti-Select':
1428 //added for Multi-Select
1429 case 'Multi-Select':
1431 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1434 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1439 $date = CRM_Utils_Date
::processDate($v);
1440 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1448 //store the file in d/b
1449 $entityId = explode('=', $groupTree['info']['where'][0]);
1450 $fileParams = array('upload_date' => date('Ymdhis'));
1452 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1453 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1456 $fileParams['uri'] = $v['name'];
1457 $fileParams['mime_type'] = $v['type'];
1458 CRM_Core_BAO_File
::filePostProcess($v['name'],
1459 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1460 $groupTree[$groupID]['table_name'],
1465 'custom_' . $fieldId,
1469 $defaults = array();
1470 $paramsFile = array(
1471 'entity_table' => $groupTree[$groupID]['table_name'],
1472 'entity_id' => $entityId[1],
1475 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1480 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1484 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1492 * generic function to build all the form elements for a specific group tree
1494 * @param object $form the form object
1495 * @param array $groupTree the group tree object
1496 * @param boolean $inactiveNeeded return inactive custom groups
1497 * @param string $prefix prefix for custom grouptree assigned to template
1503 static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '' ) {
1504 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1506 // this is fix for date field
1507 $form->assign('currentYear', date('Y'));
1509 foreach ($groupTree as $id => $group) {
1510 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1511 foreach ($group['fields'] as $field) {
1512 $required = CRM_Utils_Array
::value('is_required', $field);
1514 if ($field['data_type'] == 'File') {
1515 if (!empty($field['element_value']['data'])) {
1520 $fieldId = $field['id'];
1521 $elementName = $field['element_name'];
1522 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1528 * Function to extract the get params from the url, validate
1529 * and store it in session
1531 * @param CRM_Core_Form $form the form object
1532 * @param string $type the type of custom group we are using
1538 static function extractGetParams(&$form, $type) {
1539 // if not GET params return
1544 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1545 $customValue = array();
1546 $htmlType = array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Select', 'Radio');
1548 foreach ($groupTree as $group) {
1549 if (!isset($group['fields'])) {
1552 foreach ($group['fields'] as $key => $field) {
1553 $fieldName = 'custom_' . $key;
1554 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1558 if (!in_array($field['html_type'], $htmlType) ||
1559 $field['data_type'] == 'Boolean'
1561 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1563 if ($field['html_type'] == 'CheckBox' ||
1564 $field['html_type'] == 'AdvMulti-Select' ||
1565 $field['html_type'] == 'Multi-Select'
1567 $value = str_replace("|", ",", $value);
1568 $mulValues = explode(',', $value);
1569 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1571 foreach ($mulValues as $v1) {
1572 foreach ($customOption as $coID => $coValue) {
1573 if (strtolower(trim($coValue['label'])) == strtolower(trim($v1))) {
1574 $val[$coValue['value']] = 1;
1586 elseif ($field['html_type'] == 'Select' ||
1587 ($field['html_type'] == 'Radio' &&
1588 $field['data_type'] != 'Boolean'
1591 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1592 foreach ($customOption as $customID => $coValue) {
1593 if (strtolower(trim($coValue['label'])) == strtolower(trim($value))) {
1594 $value = $coValue['value'];
1599 elseif ($field['data_type'] == 'Date') {
1600 if (!empty($value)) {
1602 if (!empty($field['time_format'])) {
1603 $time = CRM_Utils_Request
::retrieve($fieldName . '_time', 'String', $form, FALSE, NULL, 'GET');
1605 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value . ' ' . $time);
1606 if (!empty($field['time_format'])) {
1607 $customValue[$fieldName . '_time'] = $time;
1614 $customValue[$fieldName] = $value;
1620 return $customValue;
1624 * Function to check the type of custom field type (eg: Used for Individual, Contribution, etc)
1625 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1627 * @param int $customFieldId custom field id
1628 * @param array $removeCustomFieldTypes remove custom fields of a type eg: array("Individual") ;
1631 * @return boolean false if it matches else true
1635 static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1636 $query = "SELECT cg.extends as extends
1637 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1638 WHERE cg.id = cf.custom_group_id
1639 AND cf.id =" . CRM_Utils_Type
::escape($customFieldId, 'Integer');
1641 $extends = CRM_Core_DAO
::singleValueQuery($query);
1643 if (in_array($extends, $removeCustomFieldTypes)) {
1655 static function mapTableName($table) {
1660 case 'Organization':
1661 return 'civicrm_contact';
1664 return 'civicrm_activity';
1667 return 'civicrm_group';
1669 case 'Contribution':
1670 return 'civicrm_contribution';
1672 case 'Relationship':
1673 return 'civicrm_relationship';
1676 return 'civicrm_event';
1679 return 'civicrm_membership';
1682 case 'ParticipantRole':
1683 case 'ParticipantEventName':
1684 case 'ParticipantEventType':
1685 return 'civicrm_participant';
1688 return 'civicrm_grant';
1691 return 'civicrm_pledge';
1694 return 'civicrm_address';
1697 return 'civicrm_campaign';
1701 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1702 $qParams = array(1 => array($table, 'String'));
1703 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1706 return 'civicrm_contact';
1709 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1710 if (array_key_exists($table, $extendObjs)) {
1711 return $extendObjs[$table];
1713 CRM_Core_Error
::fatal();
1721 static function createTable($group) {
1723 'name' => $group->table_name
,
1724 'is_multiple' => $group->is_multiple ?
1 : 0,
1725 'extends_name' => self
::mapTableName($group->extends),
1728 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1730 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1734 * Function returns formatted groupTree, sothat form can be easily build in template
1736 * @param array $groupTree associated array
1737 * @param int $groupCount group count by default 1, but can varry for multiple value custom data
1738 * @param object form object
1740 * @return array $formattedGroupTree
1742 static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1743 $formattedGroupTree = array();
1744 $uploadNames = array();
1746 foreach ($groupTree as $key => $value) {
1747 if ($key === 'info') {
1751 // add group information
1752 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1753 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1754 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1755 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1756 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1757 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1759 // this params needed of bulding multiple values
1760 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1761 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1762 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1763 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1764 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1765 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1767 // add field information
1768 foreach ($value['fields'] as $k => $properties) {
1769 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1770 if (isset($properties['customValue']) && !CRM_Utils_System
::isNull($properties['customValue'])) {
1771 if (isset($properties['customValue'][$groupCount])) {
1772 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1773 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1774 if ($properties['data_type'] == 'File') {
1775 $properties['element_value'] = $properties['customValue'][$groupCount];
1776 $uploadNames[] = $properties['element_name'];
1779 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1783 unset($properties['customValue']);
1784 $formattedGroupTree[$key]['fields'][$k] = $properties;
1789 // hack for field type File
1790 $formUploadNames = $form->get('uploadNames');
1791 if (is_array($formUploadNames)) {
1792 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1795 $form->set('uploadNames', $uploadNames);
1798 return $formattedGroupTree;
1802 * Build custom data view
1804 * @param object $form page object
1805 * @param array $groupTree associated array
1806 * @param boolean $returnCount true if customValue count needs to be returned
1808 * @param null $prefix
1809 * @param null $customValueId
1813 static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1815 foreach ($groupTree as $key => $group) {
1816 if ($key === 'info') {
1820 foreach ($group['fields'] as $k => $properties) {
1821 $groupID = $group['id'];
1822 if (!empty($properties['customValue'])) {
1823 foreach ($properties['customValue'] as $values) {
1824 if (!empty($customValueId) && $customValueId != $values['id']) {
1827 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1828 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1829 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1830 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1831 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1832 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1833 $details[$groupID][$values['id']]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties),
1834 'field_type' => CRM_Utils_Array
::value('html_type',
1837 'field_data_type' => CRM_Utils_Array
::value('data_type',
1840 'field_value' => self
::formatCustomValues($values,
1843 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1847 // also return contact reference contact id if user has view all or edit all contacts perm
1848 if ((CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts'))
1849 && $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] == 'ContactReference'
1851 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1856 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1857 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1858 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1859 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1860 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1861 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1862 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1868 //return a single value count if group id is passed to function
1869 //else return a groupId and count mapped array
1871 return count($details[$gID]);
1874 $countValue = array();
1875 foreach( $details as $key => $value ) {
1876 $countValue[$key] = count($details[$key]);
1882 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1888 * Format custom value according to data, view mode
1890 * @param array $values associated array of custom values
1891 * @param array $field associated array
1892 * @param boolean $dncOptionPerLine true if optionPerLine should not be consider
1894 * @return array|null|string
1896 static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1897 $value = $values['data'];
1899 //changed isset CRM-4601
1900 if (CRM_Utils_System
::isNull($value)) {
1904 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1905 $dataType = CRM_Utils_Array
::value('data_type', $field);
1906 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1907 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1908 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1911 $freezeStringChecked = "";
1913 switch ($dataType) {
1915 $customTimeFormat = '';
1916 $customFormat = NULL;
1918 switch ($timeFormat) {
1920 $customTimeFormat = '%l:%M %P';
1924 $customTimeFormat = '%H:%M';
1928 // if time is not selected remove time from value
1929 $value = substr($value, 0, 10);
1932 $supportableFormats = array(
1933 'mm/dd' => "%B %E%f $customTimeFormat",
1934 'dd-mm' => "%E%f %B $customTimeFormat",
1935 'yy' => "%Y $customTimeFormat",
1936 'M yy' => "%b %Y $customTimeFormat",
1937 'yy-mm' => "%Y-%m $customTimeFormat"
1940 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
1941 if (array_key_exists($format, $supportableFormats)) {
1942 $customFormat = $supportableFormats["$format"];
1946 $retValue = CRM_Utils_Date
::customFormat($value, $customFormat);
1950 if ($value == '1') {
1951 $retValue = $freezeStringChecked . ts('Yes') . "\n";
1954 $retValue = $freezeStringChecked . ts('No') . "\n";
1960 $retValue = CRM_Utils_System
::formatWikiURL($value);
1965 $retValue = $values;
1968 case 'ContactReference':
1969 if (!empty($values['data'])) {
1970 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
1979 if ($htmlType == 'Text') {
1980 $retValue = (float)$value;
1984 if ($htmlType == 'Text') {
1985 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1990 if (in_array($htmlType, array('Text', 'TextArea'))) {
1994 // note that if its not text / textarea, the code falls thru and executes
1995 // the below case also
1996 case 'StateProvince':
2001 //added check for Multi-Select in the below if-statement
2002 $customData[] = $value;
2004 //form custom data for multiple-valued custom data
2005 switch ($htmlType) {
2006 case 'Multi-Select Country':
2007 case 'Select Country':
2008 $customData = $value;
2009 if (!is_array($value)) {
2010 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2013 SELECT id as value, name as label
2014 FROM civicrm_country";
2015 $coDAO = CRM_Core_DAO
::executeQuery($query);
2018 case 'Select State/Province':
2019 case 'Multi-Select State/Province':
2020 $customData = $value;
2021 if (!is_array($value)) {
2022 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2026 SELECT id as value, name as label
2027 FROM civicrm_state_province";
2028 $coDAO = CRM_Core_DAO
::executeQuery($query);
2032 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2033 if ($option_group_id) {
2034 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2039 case 'AdvMulti-Select':
2040 case 'Multi-Select':
2041 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2043 if ($option_group_id) {
2044 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2048 if (is_object($coDAO)) {
2049 while ($coDAO->fetch()) {
2050 if ($dataType == 'Country') {
2051 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2052 // and already extracted to .pot files.
2053 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
2055 elseif ($dataType == 'StateProvince') {
2056 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
2059 $options[$coDAO->value
] = $coDAO->label
;
2064 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
2067 foreach ($options as $optionValue => $optionLabel) {
2068 if ($dataType == 'Money') {
2069 foreach ($customData as $k => $v) {
2070 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
2074 //to show only values that are checked
2075 if (in_array((string) $optionValue, $customData)) {
2076 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
2077 if (!$optionPerLine ||
$dncOptionPerLine) {
2081 $retValue .= $checked . $optionLabel;
2084 $retValue[] = $checked . $optionLabel;
2091 //special case for option per line formatting
2092 if ($optionPerLine > 1 && is_array($retValue)) {
2095 $displayValues = array();
2096 $displayString = '';
2097 foreach ($retValue as $val) {
2098 if ($displayString) {
2099 $displayString .= ", ";
2102 $displayString .= $val;
2106 if (($rowCounter == $optionPerLine) ||
($fieldCounter == count($retValue))) {
2107 $displayValues[] = $displayString;
2108 $displayString = '';
2112 $retValue = $displayValues;
2115 $retValue = isset($retValue) ?
$retValue : NULL;
2120 * Get the custom group titles by custom field ids.
2122 * @param array $fieldIds - array of custom field ids.
2124 * @return array $groupLabels - array consisting of groups and fields labels with ids.
2127 public static function getGroupTitles($fieldIds) {
2128 if (!is_array($fieldIds) && empty($fieldIds)) {
2132 $groupLabels = array();
2133 $fIds = "(" . implode(',', $fieldIds) . ")";
2136 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2137 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2138 FROM civicrm_custom_group, civicrm_custom_field
2139 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2140 AND civicrm_custom_field.id IN {$fIds}";
2142 $dao = CRM_Core_DAO
::executeQuery($query);
2143 while ($dao->fetch()) {
2144 $groupLabels[$dao->fieldID
] = array(
2145 'fieldID' => $dao->fieldID
,
2146 'fieldLabel' => $dao->fieldLabel
,
2147 'groupID' => $dao->groupID
,
2148 'groupTitle' => $dao->groupTitle
,
2152 return $groupLabels;
2155 static function dropAllTables() {
2156 $query = "SELECT table_name FROM civicrm_custom_group";
2157 $dao = CRM_Core_DAO
::executeQuery($query);
2159 while ($dao->fetch()) {
2160 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2161 CRM_Core_DAO
::executeQuery($query);
2166 * Check whether custom group is empty or not.
2168 * @param int $gID - custom group id.
2170 * @return boolean true if empty otherwise false.
2173 static function isGroupEmpty($gID) {
2178 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2183 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2184 $value = CRM_Core_DAO
::singleValueQuery($query);
2186 if (empty($value)) {
2194 * Get the list of types for objects that a custom group extends to.
2196 * @param array $types - var which should have the list appended.
2198 * @return array of types.
2201 static function getExtendedObjectTypes(&$types = array( )) {
2202 static $flag = FALSE, $objTypes = array();
2205 $extendObjs = array();
2206 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2208 foreach ($extendObjs as $ovId => $ovValues) {
2209 if ($ovValues['description']) {
2210 // description is expected to be a callback func to subtypes
2211 list($callback, $args) = explode(';', trim($ovValues['description']));
2217 if (!is_array($args)) {
2218 CRM_Core_Error
::fatal('Arg is not of type array');
2221 list($className) = explode('::', $callback);
2222 require_once (str_replace('_',DIRECTORY_SEPARATOR
, $className) . '.php');
2224 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2230 $types = array_merge($types, $objTypes);
2235 * @param $customGroupId
2240 static function hasReachedMaxLimit($customGroupId, $entityId) {
2241 //check whether the group is multiple
2242 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2243 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2244 $hasReachedMax = FALSE;
2246 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))) {
2247 if (!$maxMultiple) {
2248 $hasReachedMax = FALSE;
2250 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2251 //count the number of entries for a entity
2252 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2253 $params = array(1 => array($entityId, 'Integer'));
2254 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2256 if ($count >= $maxMultiple) {
2257 $hasReachedMax = TRUE;
2261 return $hasReachedMax;
2267 static function getMultipleFieldGroup() {
2268 $multipleGroup = array();
2269 $dao = new CRM_Core_DAO_CustomGroup();
2270 $dao->is_multiple
= 1 ;
2272 while($dao->fetch()) {
2273 $multipleGroup[$dao->id
] = $dao->title
;
2275 return $multipleGroup;