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 if (in_array($params['is_reserved'], array(TRUE, 1, '1'), TRUE)) {
169 $group->is_reserved
= $is_reserved;
171 $op = isset($params['id']) ?
'edit' : 'create';
172 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
174 // enclose the below in a transaction
175 $transaction = new CRM_Core_Transaction();
178 if (!isset($params['id'])) {
179 if (!isset($params['table_name'])) {
180 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 42));
181 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
183 $group->table_name
= $tableName;
184 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
190 // now create the table associated with this group
191 self
::createTable($group);
193 elseif ($oldTableName) {
194 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($oldTableName, CRM_Utils_Array
::value('is_multiple', $params));
197 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
198 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
202 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends'][0]));
204 $transaction->commit();
207 CRM_Utils_System
::flushCache();
210 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
213 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
220 * Takes a bunch of params that are needed to match certain criteria and
221 * retrieves the relevant objects. Typically the valid params are only
222 * contact_id. We'll tweak this function to be more full featured over a period
223 * of time. This is the inverse function of create. It also stores all the retrieved
224 * values in the default array
226 * @param array $params (reference ) an assoc array of name/value pairs
227 * @param array $defaults (reference ) an assoc array to hold the flattened values
229 * @return object CRM_Core_DAO_CustomGroup object
233 static function retrieve(&$params, &$defaults) {
234 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
238 * update the is_active flag in the db
240 * @param int $id id of the database record
241 * @param boolean $is_active value we want to set the is_active field
243 * @return Object DAO object on sucess, null otherwise
247 static function setIsActive($id, $is_active) {
249 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
252 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
255 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
259 * Determine if given entity (sub)type has any custom groups
261 * @param string $extends e.g. "Individual", "Activity"
262 * @param int $columnId e.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id
263 * @param string $columnValue e.g. "Student" or "3" or "3\05"; see extends_entity_column_value
267 public static function hasCustomGroup($extends, $columnId, $columnValue) {
268 $dao = new CRM_Core_DAO_CustomGroup();
269 $dao->extends = $extends;
270 $dao->extends_entity_column_id
= $columnId;
271 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
272 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
273 //$dao->extends_entity_column_value = $columnValue;
274 return $dao->find() ?
TRUE : FALSE;
278 * Determine if there are any CustomGroups for the given $activityTypeId.
279 * If none found, create one.
281 * @param int $activityTypeId
282 * @return bool TRUE if a group is found or created; FALSE on error
284 public static function autoCreateByActivityType($activityTypeId) {
285 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
288 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
291 'extends' => 'Activity',
292 'extends_entity_column_id' => NULL,
293 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
294 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
298 $result = civicrm_api('CustomGroup', 'create', $params);
299 return ! $result['is_error'];
303 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
304 * This may also include entity specific data values.
306 * An array containing all custom groups and their custom fields is returned.
308 * @param string $entityType - of the contact whose contact type is needed
309 * @param object $form - not used but required
310 * @param null $entityID
311 * @param null $groupID
312 * @param string $subType
313 * @param string $subName
314 * @param boolean $fromCache
316 * @param null $onlySubType
318 * @internal param int $entityId - optional - id of entity if we need to populate the tree with custom values.
319 * @internal param int $groupId - optional group id (if we need it for a single group only)
320 * - if groupId is 0 it gets for inline groups only
321 * - if groupId is -1 we get for all groups
322 * @return array $groupTree - array The returned array is keyed by group id and has the custom group table fields
323 * and a subkey 'fields' holding the specific custom fields.
324 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
325 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
327 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
328 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
329 * With caching the performance impact would be small & the function would be cleaner
335 public static function &getTree(
346 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
350 $strSelect = $strFrom = $strWhere = $orderBy = '';
351 $tableData = array();
353 // using tableData to build the queryString
355 'civicrm_custom_field' =>
376 'civicrm_custom_group' =>
387 'extends_entity_column_id',
388 'extends_entity_column_value',
395 foreach ($tableData as $tableName => $tableColumn) {
396 foreach ($tableColumn as $columnName) {
397 $alias = $tableName . "_" . $columnName;
398 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
401 $strSelect = "SELECT " . implode(', ', $select);
403 // from, where, order by
405 FROM civicrm_custom_group
406 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
409 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
410 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
$entityType == 'Household') {
411 $in = "'$entityType', 'Contact'";
413 elseif (strpos($entityType, "'") !== FALSE) {
414 // this allows the calling function to send in multiple entity types
419 $in = "'$entityType'";
424 if (is_array($subType)) {
425 $subType = implode(',', $subType);
427 if (strpos($subType, ',')) {
428 $subTypeParts = explode(',', $subType);
429 $subTypeClauses = array();
430 foreach ($subTypeParts as $subTypePart) {
431 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
432 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
436 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
439 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
443 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
446 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
449 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
450 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
455 WHERE civicrm_custom_group.is_active = 1
456 AND civicrm_custom_field.is_active = 1
457 AND civicrm_custom_group.extends IN ($in)
461 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
466 WHERE civicrm_custom_group.is_active = 1
467 AND civicrm_custom_field.is_active = 1
468 AND civicrm_custom_group.extends IN ($in)
469 AND civicrm_custom_group.extends_entity_column_value IS NULL
475 // since we want a specific group id we add it to the where clause
476 $strWhere .= " AND civicrm_custom_group.id = %1";
477 $params[1] = array($groupID, 'Integer');
480 // since groupID is false we need to show all Inline groups
481 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
484 // ensure that the user has access to these custom groups
485 $strWhere .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
486 'civicrm_custom_group.'
490 ORDER BY civicrm_custom_group.weight,
491 civicrm_custom_group.title,
492 civicrm_custom_field.weight,
493 civicrm_custom_field.label
496 // final query string
497 $queryString = "$strSelect $strFrom $strWhere $orderBy";
499 // lets see if we can retrieve the groupTree from cache
500 $cacheString = $queryString;
501 if ( $groupID > 0 ) {
502 $cacheString .= "_{$groupID}";
504 $cacheString .= "_Inline";
507 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
508 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
509 $cache = CRM_Utils_Cache
::singleton();
510 $tablesWithEntityData = array();
512 $groupTree = $cache->get($cacheKey);
513 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
516 if (empty($groupTree)) {
517 $groupTree = $multipleFieldGroups =array();
518 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
519 $customValueTables = array();
522 while ($crmDAO->fetch()) {
524 $groupID = $crmDAO->civicrm_custom_group_id
;
525 $fieldId = $crmDAO->civicrm_custom_field_id
;
526 if($crmDAO->civicrm_custom_group_is_multiple
){
527 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
529 // create an array for groups if it does not exist
530 if (!array_key_exists($groupID, $groupTree)) {
531 $groupTree[$groupID] = array();
532 $groupTree[$groupID]['id'] = $groupID;
534 // populate the group information
535 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
536 $fullFieldName = "civicrm_custom_group_$fieldName";
537 if ($fieldName == 'id' ||
538 is_null($crmDAO->$fullFieldName)
543 if ($fieldName == 'extends_entity_column_value' && $subType) {
544 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
546 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
548 $groupTree[$groupID]['fields'] = array();
550 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
553 // add the fields now (note - the query row will always contain a field)
554 // we only reset this once, since multiple values come is as multiple rows
555 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
556 $groupTree[$groupID]['fields'][$fieldId] = array();
559 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
560 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
561 // populate information for a custom field
562 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
563 $fullFieldName = "civicrm_custom_field_$fieldName";
564 if ($fieldName == 'id' ||
565 is_null($crmDAO->$fullFieldName)
569 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
573 if (!empty($customValueTables)) {
574 $groupTree['info'] = array('tables' => $customValueTables);
577 $cache->set($cacheKey, $groupTree);
578 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
580 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
581 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
582 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
583 $singleFieldTables = array();
584 // now that we have all the groups and fields, lets get the values
585 // since we need to know the table and field names
586 // add info to groupTree
588 if (isset($groupTree['info']) && !empty($groupTree['info']) && !empty($groupTree['info']['tables'])) {
589 $select = $from = $where = array();
590 $groupTree['info']['where'] = NULL;
592 foreach ($groupTree['info']['tables'] as $table => $fields) {
593 $groupTree['info']['from'][] = $table;
594 $select = array("{$table}.id as {$table}_id",
595 "{$table}.entity_id as {$table}_entity_id");
596 foreach ($fields as $column => $dontCare) {
597 $select[] = "{$table}.{$column} as {$table}_{$column}";
599 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
601 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
602 if(in_array($table, $multipleFieldGroups) && self
::customGroupDataExistsForEntity($entityID, $table)){
603 $entityMultipleSelectClauses[$table] = $select;
606 $singleFieldTables[] = $table;
607 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
612 if ($entityID && !empty($singleFieldTables)) {
613 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
615 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
616 if(!empty($multipleFieldTablesWithEntityData)){
617 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
625 * Check whether the custom group has any data for the given entity.
628 * @param integer $entityID id of entity for whom we are checking data for
629 * @param string $table table that we are checking
631 * @param bool $getCount
633 * @return boolean does this entity have data in this custom table
635 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE){
639 WHERE entity_id = $entityID
641 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
643 return $recordExists;
645 return $recordExists ?
TRUE : FALSE;
649 * Build the group tree for Custom fields which are not 'is_multiple'
651 * The combination of all these fields in one query with a 'using' join was not working for
652 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
653 * mechanism as it seemed to be acceptable in this context
655 * @param array $groupTree (reference) group tree array which is being built
656 * @param integer $entityID id of entity for whom the tree is being build up.
657 * @param array $entitySingleSelectClauses array of select clauses relevant to the entity
658 * @param array $singleFieldTablesWithEntityData array of tables in which this entity has data
660 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData){
661 $select = implode(', ', $entitySingleSelectClauses);
662 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
663 foreach ($singleFieldTablesWithEntityData as $table) {
664 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
670 WHERE first.entity_id = $entityID
672 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
676 * Build the group tree for Custom fields which are 'is_multiple'
678 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
680 * @param array $groupTree (reference) group tree array which is being built
681 * @param integer $entityID id of entity for whom the tree is being build up.
682 * @param array $entityMultipleSelectClauses array of select clauses relevant to the entity
683 * @param array $multipleFieldTablesWithEntityData array of tables in which this entity has data
685 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData){
686 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
687 $select = implode(',', $selectClauses);
691 WHERE entity_id = $entityID
693 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
698 * Build the tree entity data - starting from a query retrieving the custom fields build the group
699 * tree data for the relevant entity (entity is included in the query).
701 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
703 * @param array $groupTree (reference) group tree array which is being built
704 * @param string $query
705 * @param array $includedTables tables to include - required because the function (for historical reasons)
706 * iterates through the group tree
708 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables){
709 $dao = CRM_Core_DAO
::executeQuery($query);
710 while ($dao->fetch()) {
711 foreach ($groupTree as $groupID => $group) {
712 if ($groupID === 'info') {
715 $table = $groupTree[$groupID]['table_name'];
716 //working from the groupTree instead of the table list means we have to iterate & exclude.
717 // this could possibly be re-written as other parts of the function have been refactored
718 // for now we just check if the given table is to be included in this function
719 if( !in_array($table, $includedTables)){
722 foreach ($group['fields'] as $fieldID => $dontCare) {
723 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
730 * Build the entity-specific custom data into the group tree on a per-field basis
732 * @param object $dao object representing the custom field to be populated into the groupTree
733 * @param array $groupTree (reference) the group tree being build
734 * @param string $table table name
735 * @param unknown_type $groupID custom group ID
736 * @param unknown_type $fieldID custom field ID
738 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID){
739 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
740 $idName = "{$table}_id";
741 $fieldName = "{$table}_{$column}";
742 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
743 if ($dataType == 'File') {
744 if (isset($dao->$fieldName)) {
745 $config = CRM_Core_Config
::singleton();
746 $fileDAO = new CRM_Core_DAO_File();
747 $fileDAO->id
= $dao->$fieldName;
749 if ($fileDAO->find(TRUE)) {
750 $entityIDName = "{$table}_entity_id";
751 $customValue['id'] = $dao->$idName;
752 $customValue['data'] = $fileDAO->uri
;
753 $customValue['fid'] = $fileDAO->id
;
754 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
755 $customValue['displayURL'] = NULL;
756 $deleteExtra = ts('Are you sure you want to delete attached file.');
758 CRM_Core_Action
::DELETE
=>
760 'name' => ts('Delete Attached File'),
761 'url' => 'civicrm/file',
762 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
764 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
767 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
768 CRM_Core_Action
::DELETE
,
770 'id' => $fileDAO->id
,
771 'eid' => $dao->$entityIDName,
776 'file.manage.delete',
780 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
781 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
782 if ($fileDAO->mime_type
== "image/jpeg" ||
783 $fileDAO->mime_type
== "image/pjpeg" ||
784 $fileDAO->mime_type
== "image/gif" ||
785 $fileDAO->mime_type
== "image/x-png" ||
786 $fileDAO->mime_type
== "image/png"
788 $customValue['displayURL'] = $customValue['fileURL'];
789 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
794 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) . $fileDAO->uri
;
795 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId,
798 if ($path && file_exists($path)) {
799 list($imageWidth, $imageHeight) = getimagesize($path);
800 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
801 $customValue['imageThumbWidth'] = $imageThumbWidth;
802 $customValue['imageThumbHeight'] = $imageThumbHeight;
808 $customValue = array(
809 'id' => $dao->$idName,
815 $customValue = array(
816 'id' => $dao->$idName,
817 'data' => $dao->$fieldName,
821 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
822 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
824 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
825 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
828 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
833 * Get the group title.
835 * @param int $id id of group.
837 * @return string title
843 public static function getTitle($id) {
844 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
848 * Get custom group details for a group.
850 * An array containing custom group details (including their custom field) is returned.
852 * @param int $groupId - group id whose details are needed
853 * @param boolean $searchable - is this field searchable
854 * @param array $extends - which table does it extend if any
856 * @param null $inSelector
858 * @return array $groupTree - array consisting of all group and field details
864 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
866 $groupTree = array();
867 $select = $from = $where = $orderBy = '';
869 $tableData = array();
871 // using tableData to build the queryString
873 'civicrm_custom_field' =>
898 'civicrm_custom_group' =>
906 'collapse_adv_display',
908 'extends_entity_column_value',
917 foreach ($tableData as $tableName => $tableColumn) {
918 foreach ($tableColumn as $columnName) {
919 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
922 $select = 'SELECT ' . implode(', ', $s);
924 // from, where, order by
925 $from = " FROM civicrm_custom_field, civicrm_custom_group";
926 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
927 AND civicrm_custom_group.is_active = 1
928 AND civicrm_custom_field.is_active = 1 ";
930 $params[1] = array($groupId, 'Integer');
931 $where .= " AND civicrm_custom_group.id = %1";
935 $where .= " AND civicrm_custom_field.is_searchable = 1";
939 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
944 foreach ($extends as $e) {
945 $clause[] = "civicrm_custom_group.extends = '$e'";
947 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
949 //include case activities customdata if case is enabled
950 if (in_array('Activity', $extends)) {
951 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
952 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
953 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
957 // ensure that the user has access to these custom groups
958 $where .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
959 'civicrm_custom_group.'
962 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
964 // final query string
965 $queryString = $select . $from . $where . $orderBy;
968 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
971 while ($crmDAO->fetch()) {
972 $groupId = $crmDAO->civicrm_custom_group_id
;
973 $fieldId = $crmDAO->civicrm_custom_field_id
;
975 // create an array for groups if it does not exist
976 if (!array_key_exists($groupId, $groupTree)) {
977 $groupTree[$groupId] = array();
978 $groupTree[$groupId]['id'] = $groupId;
980 foreach ($tableData['civicrm_custom_group'] as $v) {
981 $fullField = "civicrm_custom_group_" . $v;
983 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
987 $groupTree[$groupId][$v] = $crmDAO->$fullField;
990 $groupTree[$groupId]['fields'] = array();
993 // add the fields now (note - the query row will always contain a field)
994 $groupTree[$groupId]['fields'][$fieldId] = array();
995 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
997 foreach ($tableData['civicrm_custom_field'] as $v) {
998 $fullField = "civicrm_custom_field_" . $v;
999 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1002 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1010 * @param $entityType
1012 * @param string $cidToken
1016 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1018 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1020 // get 'Tab' and 'Tab with table' groups
1021 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1022 $customGroupDAO->whereAdd("is_active = 1");
1024 // add whereAdd for entity type
1025 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1029 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1030 $customGroupDAO->whereAdd($permissionClause);
1033 $customGroupDAO->orderBy('weight');
1034 $customGroupDAO->find();
1036 // process each group with menu tab
1037 while ($customGroupDAO->fetch()) {
1039 $group['id'] = $customGroupDAO->id
;
1040 $group['path'] = $path;
1041 $group['title'] = "$customGroupDAO->title";
1042 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1043 $group['extra'] = array('gid' => $customGroupDAO->id
);
1044 $group['table_name'] = $customGroupDAO->table_name
;
1052 * Get the table name for the entity type
1053 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1054 * tableName is 'civicrm_contact'
1056 * @param string $entityType what entity are we extending here ?
1058 * @return string $tableName
1063 * @see _apachesolr_civiAttachments_dereference_file_parent
1065 public static function getTableNameByEntityName($entityType) {
1067 switch ($entityType) {
1071 case 'Organization':
1072 $tableName = 'civicrm_contact';
1075 case 'Contribution':
1076 $tableName = 'civicrm_contribution';
1080 $tableName = 'civicrm_group';
1082 // DRAFTING: Verify if we cannot make it pluggable
1085 $tableName = 'civicrm_activity';
1088 case 'Relationship':
1089 $tableName = 'civicrm_relationship';
1093 $tableName = 'civicrm_membership';
1097 $tableName = 'civicrm_participant';
1101 $tableName = 'civicrm_event';
1105 $tableName = 'civicrm_grant';
1107 // need to add cases for Location, Address
1114 * Get a list of custom groups which extend a given entity type.
1115 * If there are custom-groups which only apply to certain subtypes,
1116 * those WILL be included.
1118 * @param $entityType string
1119 * @return CRM_Core_DAO_CustomGroup
1121 static function getAllCustomGroupsByBaseEntity($entityType) {
1122 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1123 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1124 return $customGroupDAO;
1128 * Add the whereAdd clause for the DAO depending on the type of entity
1129 * the custom group is extending.
1131 * @param $customGroupDAO
1132 * @param string $entityType - what entity are we extending here ?
1134 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
1135 * @param bool $allSubtypes
1142 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1143 $addSubtypeClause = FALSE;
1145 switch ($entityType) {
1147 // if contact, get all related to contact
1148 $extendList = "'Contact','Individual','Household','Organization'";
1149 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1150 if (!$allSubtypes) {
1151 $addSubtypeClause = TRUE;
1157 case 'Organization':
1158 // is I/H/O then get I/H/O and contact
1159 $extendList = "'Contact','$entityType'";
1160 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1161 if (!$allSubtypes) {
1162 $addSubtypeClause = TRUE;
1170 case 'Contribution':
1173 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1177 if ($addSubtypeClause) {
1178 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1180 if (!empty($csType)) {
1181 $subtypeClause = array();
1182 foreach ($csType as $subtype) {
1183 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
1184 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1186 $subtypeClause[] = "extends_entity_column_value IS NULL";
1187 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) . " )");
1190 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1196 * Delete the Custom Group.
1198 * @param $group object the DAO custom group object
1199 * @param $force boolean whether to force the deletion, even if there are custom fields
1201 * @return boolean false if field exists for this group, true if group gets deleted.
1207 public static function deleteGroup($group, $force = FALSE) {
1209 //check wheter this contain any custom fields
1210 $customField = new CRM_Core_DAO_CustomField();
1211 $customField->custom_group_id
= $group->id
;
1212 $customField->find();
1214 // return early if there are custom fields and we're not
1215 // forcing the delete, otherwise delete the fields one by one
1216 while ($customField->fetch()) {
1220 CRM_Core_BAO_CustomField
::deleteField($customField);
1223 // drop the table associated with this custom group
1224 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1226 //delete custom group
1229 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1237 * @param bool $viewMode
1238 * @param bool $inactiveNeeded
1239 * @param int $action
1241 static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1242 foreach ($groupTree as $id => $group) {
1243 if (!isset($group['fields'])) {
1246 $groupId = CRM_Utils_Array
::value('id', $group);
1247 foreach ($group['fields'] as $field) {
1248 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1249 $value = $field['element_value'];
1251 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1252 ($action != CRM_Core_Action
::UPDATE ||
1254 !array_key_exists('element_value', $field)
1257 $value = $viewMode ?
NULL : $field['default_value'];
1263 $fieldId = $field['id'];
1264 if (!empty($field['element_name'])) {
1265 $elementName = $field['element_name'];
1267 switch ($field['html_type']) {
1268 case 'Multi-Select':
1269 case 'AdvMulti-Select':
1271 $defaults[$elementName] = array();
1272 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1274 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1275 if (isset($value)) {
1276 foreach ($customOption as $customValue => $customLabel) {
1277 if (in_array($customValue, $checkedData)) {
1278 if ($field['html_type'] == 'CheckBox') {
1279 $defaults[$elementName][$customValue] = 1;
1282 $defaults[$elementName][$customValue] = $customValue;
1286 $defaults[$elementName][$customValue] = 0;
1292 if (isset($field['customValue']['data'])) {
1293 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1294 foreach ($customOption as $val) {
1295 if (in_array($val['value'], $checkedData)) {
1296 if ($field['html_type'] == 'CheckBox') {
1297 $defaults[$elementName][$val['value']] = 1;
1300 $defaults[$elementName][$val['value']] = $val['value'];
1304 $defaults[$elementName][$val['value']] = 0;
1309 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1310 foreach ($customOption as $val) {
1311 if (in_array($val['value'], $checkedValue)) {
1312 if ($field['html_type'] == 'CheckBox') {
1313 $defaults[$elementName][$val['value']] = 1;
1316 $defaults[$elementName][$val['value']] = $val['value'];
1325 if (isset($value)) {
1326 if (empty($field['time_format'])) {
1327 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1328 $field['date_format']
1332 $timeElement = $elementName . '_time';
1333 if (substr($elementName, -1) == ']') {
1334 $timeElement = substr($elementName, 0, -1) . '_time]';
1336 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1341 case 'Multi-Select Country':
1342 case 'Multi-Select State/Province':
1343 if (isset($value)) {
1344 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1345 foreach ($checkedValue as $val) {
1347 $defaults[$elementName][$val] = $val;
1353 case 'Select Country':
1355 $defaults[$elementName] = $value;
1358 $config = CRM_Core_Config
::singleton();
1359 $defaults[$elementName] = $config->defaultContactCountry
;
1364 if ($field['data_type'] == "Float") {
1365 $defaults[$elementName] = (float)$value;
1367 elseif ($field['data_type'] == 'Money' &&
1368 $field['html_type'] == 'Text'
1370 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1373 $defaults[$elementName] = $value;
1383 * @param bool $skipFile
1385 static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1386 // Get the Custom form values and groupTree
1387 // first reset all checkbox and radio data
1388 foreach ($groupTree as $groupID => $group) {
1389 if ($groupID === 'info') {
1392 foreach ($group['fields'] as $field) {
1393 $fieldId = $field['id'];
1395 //added Multi-Select option in the below if-statement
1396 if ($field['html_type'] == 'CheckBox' ||
$field['html_type'] == 'Radio' ||
1397 $field['html_type'] == 'AdvMulti-Select' ||
$field['html_type'] == 'Multi-Select'
1399 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1403 foreach ($params as $key => $val) {
1404 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1405 $match[1] == $field['id']
1412 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1413 // field exists in db so populate value from "form".
1414 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1417 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1419 //added for CheckBox
1423 $customValue = array_keys($v);
1424 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1427 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1431 //added for Advanced Multi-Select
1433 case 'AdvMulti-Select':
1434 //added for Multi-Select
1435 case 'Multi-Select':
1437 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1440 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1445 $date = CRM_Utils_Date
::processDate($v);
1446 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1454 //store the file in d/b
1455 $entityId = explode('=', $groupTree['info']['where'][0]);
1456 $fileParams = array('upload_date' => date('Ymdhis'));
1458 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1459 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1462 $fileParams['uri'] = $v['name'];
1463 $fileParams['mime_type'] = $v['type'];
1464 CRM_Core_BAO_File
::filePostProcess($v['name'],
1465 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1466 $groupTree[$groupID]['table_name'],
1471 'custom_' . $fieldId,
1475 $defaults = array();
1476 $paramsFile = array(
1477 'entity_table' => $groupTree[$groupID]['table_name'],
1478 'entity_id' => $entityId[1],
1481 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1486 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1490 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1498 * generic function to build all the form elements for a specific group tree
1500 * @param object $form the form object
1501 * @param array $groupTree the group tree object
1502 * @param boolean $inactiveNeeded return inactive custom groups
1503 * @param string $prefix prefix for custom grouptree assigned to template
1509 static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '' ) {
1510 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1512 // this is fix for date field
1513 $form->assign('currentYear', date('Y'));
1515 foreach ($groupTree as $id => $group) {
1516 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1517 foreach ($group['fields'] as $field) {
1518 $required = CRM_Utils_Array
::value('is_required', $field);
1520 if ($field['data_type'] == 'File') {
1521 if (!empty($field['element_value']['data'])) {
1526 $fieldId = $field['id'];
1527 $elementName = $field['element_name'];
1528 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1531 if (!empty($form->_stateCountryMap
['state_province']) && !empty($form->_stateCountryMap
['country'])) {
1532 foreach ($form->_stateCountryMap
['state_province'] as $key => $value) {
1533 $stateCountryMap[$key]['state_province'] = $value;
1534 $stateCountryMap[$key]['country'] = $form->_stateCountryMap
['country'][$key];
1536 CRM_Core_BAO_Address
::addStateCountryMap($stateCountryMap);
1541 * Function to extract the get params from the url, validate
1542 * and store it in session
1544 * @param CRM_Core_Form $form the form object
1545 * @param string $type the type of custom group we are using
1551 static function extractGetParams(&$form, $type) {
1552 // if not GET params return
1557 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1558 $customValue = array();
1559 $htmlType = array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Select', 'Radio');
1561 foreach ($groupTree as $group) {
1562 if (!isset($group['fields'])) {
1565 foreach ($group['fields'] as $key => $field) {
1566 $fieldName = 'custom_' . $key;
1567 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1571 if (!in_array($field['html_type'], $htmlType) ||
1572 $field['data_type'] == 'Boolean'
1574 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1576 if ($field['html_type'] == 'CheckBox' ||
1577 $field['html_type'] == 'AdvMulti-Select' ||
1578 $field['html_type'] == 'Multi-Select'
1580 $value = str_replace("|", ",", $value);
1581 $mulValues = explode(',', $value);
1582 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1584 foreach ($mulValues as $v1) {
1585 foreach ($customOption as $coID => $coValue) {
1586 if (strtolower(trim($coValue['label'])) == strtolower(trim($v1))) {
1587 $val[$coValue['value']] = 1;
1599 elseif ($field['html_type'] == 'Select' ||
1600 ($field['html_type'] == 'Radio' &&
1601 $field['data_type'] != 'Boolean'
1604 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1605 foreach ($customOption as $customID => $coValue) {
1606 if (strtolower(trim($coValue['label'])) == strtolower(trim($value))) {
1607 $value = $coValue['value'];
1612 elseif ($field['data_type'] == 'Date') {
1613 if (!empty($value)) {
1615 if (!empty($field['time_format'])) {
1616 $time = CRM_Utils_Request
::retrieve($fieldName . '_time', 'String', $form, FALSE, NULL, 'GET');
1618 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value . ' ' . $time);
1619 if (!empty($field['time_format'])) {
1620 $customValue[$fieldName . '_time'] = $time;
1627 $customValue[$fieldName] = $value;
1633 return $customValue;
1637 * Function to check the type of custom field type (eg: Used for Individual, Contribution, etc)
1638 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1640 * @param int $customFieldId custom field id
1641 * @param array $removeCustomFieldTypes remove custom fields of a type eg: array("Individual") ;
1644 * @return boolean false if it matches else true
1648 static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1649 $query = "SELECT cg.extends as extends
1650 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1651 WHERE cg.id = cf.custom_group_id
1652 AND cf.id =" . CRM_Utils_Type
::escape($customFieldId, 'Integer');
1654 $extends = CRM_Core_DAO
::singleValueQuery($query);
1656 if (in_array($extends, $removeCustomFieldTypes)) {
1668 static function mapTableName($table) {
1673 case 'Organization':
1674 return 'civicrm_contact';
1677 return 'civicrm_activity';
1680 return 'civicrm_group';
1682 case 'Contribution':
1683 return 'civicrm_contribution';
1685 case 'Relationship':
1686 return 'civicrm_relationship';
1689 return 'civicrm_event';
1692 return 'civicrm_membership';
1695 case 'ParticipantRole':
1696 case 'ParticipantEventName':
1697 case 'ParticipantEventType':
1698 return 'civicrm_participant';
1701 return 'civicrm_grant';
1704 return 'civicrm_pledge';
1707 return 'civicrm_address';
1710 return 'civicrm_campaign';
1714 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1715 $qParams = array(1 => array($table, 'String'));
1716 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1719 return 'civicrm_contact';
1722 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1723 if (array_key_exists($table, $extendObjs)) {
1724 return $extendObjs[$table];
1726 CRM_Core_Error
::fatal();
1734 static function createTable($group) {
1736 'name' => $group->table_name
,
1737 'is_multiple' => $group->is_multiple ?
1 : 0,
1738 'extends_name' => self
::mapTableName($group->extends),
1741 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1743 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1747 * Function returns formatted groupTree, sothat form can be easily build in template
1749 * @param array $groupTree associated array
1750 * @param int $groupCount group count by default 1, but can varry for multiple value custom data
1751 * @param object form object
1753 * @return array $formattedGroupTree
1755 static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1756 $formattedGroupTree = array();
1757 $uploadNames = array();
1759 foreach ($groupTree as $key => $value) {
1760 if ($key === 'info') {
1764 // add group information
1765 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1766 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1767 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1768 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1769 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1770 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1772 // this params needed of bulding multiple values
1773 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1774 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1775 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1776 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1777 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1778 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1780 // add field information
1781 foreach ($value['fields'] as $k => $properties) {
1782 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1783 if (isset($properties['customValue']) && !CRM_Utils_System
::isNull($properties['customValue'])) {
1784 if (isset($properties['customValue'][$groupCount])) {
1785 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1786 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1787 if ($properties['data_type'] == 'File') {
1788 $properties['element_value'] = $properties['customValue'][$groupCount];
1789 $uploadNames[] = $properties['element_name'];
1792 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1796 unset($properties['customValue']);
1797 $formattedGroupTree[$key]['fields'][$k] = $properties;
1802 // hack for field type File
1803 $formUploadNames = $form->get('uploadNames');
1804 if (is_array($formUploadNames)) {
1805 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1808 $form->set('uploadNames', $uploadNames);
1811 return $formattedGroupTree;
1815 * Build custom data view
1817 * @param object $form page object
1818 * @param array $groupTree associated array
1819 * @param boolean $returnCount true if customValue count needs to be returned
1821 * @param null $prefix
1822 * @param null $customValueId
1826 static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1828 foreach ($groupTree as $key => $group) {
1829 if ($key === 'info') {
1833 foreach ($group['fields'] as $k => $properties) {
1834 $groupID = $group['id'];
1835 if (!empty($properties['customValue'])) {
1836 foreach ($properties['customValue'] as $values) {
1837 if (!empty($customValueId) && $customValueId != $values['id']) {
1840 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1841 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1842 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1843 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1844 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1845 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1846 $details[$groupID][$values['id']]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties),
1847 'field_type' => CRM_Utils_Array
::value('html_type',
1850 'field_data_type' => CRM_Utils_Array
::value('data_type',
1853 'field_value' => self
::formatCustomValues($values,
1856 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1860 // also return contact reference contact id if user has view all or edit all contacts perm
1861 if ((CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts'))
1862 && $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] == 'ContactReference'
1864 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1869 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1870 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1871 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1872 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1873 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1874 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1875 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1881 //return a single value count if group id is passed to function
1882 //else return a groupId and count mapped array
1884 return count($details[$gID]);
1887 $countValue = array();
1888 foreach( $details as $key => $value ) {
1889 $countValue[$key] = count($details[$key]);
1895 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1901 * Format custom value according to data, view mode
1903 * @param array $values associated array of custom values
1904 * @param array $field associated array
1905 * @param boolean $dncOptionPerLine true if optionPerLine should not be consider
1907 * @return array|null|string
1909 static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1910 $value = $values['data'];
1912 //changed isset CRM-4601
1913 if (CRM_Utils_System
::isNull($value)) {
1917 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1918 $dataType = CRM_Utils_Array
::value('data_type', $field);
1919 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1920 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1921 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1924 $freezeStringChecked = "";
1926 switch ($dataType) {
1928 $customTimeFormat = '';
1929 $customFormat = NULL;
1931 switch ($timeFormat) {
1933 $customTimeFormat = '%l:%M %P';
1937 $customTimeFormat = '%H:%M';
1941 // if time is not selected remove time from value
1942 $value = substr($value, 0, 10);
1945 $supportableFormats = array(
1946 'mm/dd' => "%B %E%f $customTimeFormat",
1947 'dd-mm' => "%E%f %B $customTimeFormat",
1948 'yy' => "%Y $customTimeFormat",
1949 'M yy' => "%b %Y $customTimeFormat",
1950 'yy-mm' => "%Y-%m $customTimeFormat"
1953 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
1954 if (array_key_exists($format, $supportableFormats)) {
1955 $customFormat = $supportableFormats["$format"];
1959 $retValue = CRM_Utils_Date
::customFormat($value, $customFormat);
1963 if ($value == '1') {
1964 $retValue = $freezeStringChecked . ts('Yes') . "\n";
1967 $retValue = $freezeStringChecked . ts('No') . "\n";
1973 $retValue = CRM_Utils_System
::formatWikiURL($value);
1978 $retValue = $values;
1981 case 'ContactReference':
1982 if (!empty($values['data'])) {
1983 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
1992 if ($htmlType == 'Text') {
1993 $retValue = (float)$value;
1997 if ($htmlType == 'Text') {
1998 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2003 if (in_array($htmlType, array('Text', 'TextArea'))) {
2007 // note that if its not text / textarea, the code falls thru and executes
2008 // the below case also
2009 case 'StateProvince':
2014 //added check for Multi-Select in the below if-statement
2015 $customData[] = $value;
2017 //form custom data for multiple-valued custom data
2018 switch ($htmlType) {
2019 case 'Multi-Select Country':
2020 case 'Select Country':
2021 $customData = $value;
2022 if (!is_array($value)) {
2023 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2026 SELECT id as value, name as label
2027 FROM civicrm_country";
2028 $coDAO = CRM_Core_DAO
::executeQuery($query);
2031 case 'Select State/Province':
2032 case 'Multi-Select State/Province':
2033 $customData = $value;
2034 if (!is_array($value)) {
2035 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2039 SELECT id as value, name as label
2040 FROM civicrm_state_province";
2041 $coDAO = CRM_Core_DAO
::executeQuery($query);
2045 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2046 if ($option_group_id) {
2047 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2052 case 'AdvMulti-Select':
2053 case 'Multi-Select':
2054 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2056 if ($option_group_id) {
2057 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2061 if (is_object($coDAO)) {
2062 while ($coDAO->fetch()) {
2063 if ($dataType == 'Country') {
2064 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2065 // and already extracted to .pot files.
2066 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
2068 elseif ($dataType == 'StateProvince') {
2069 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
2072 $options[$coDAO->value
] = $coDAO->label
;
2077 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
2080 foreach ($options as $optionValue => $optionLabel) {
2081 if ($dataType == 'Money') {
2082 foreach ($customData as $k => $v) {
2083 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
2087 //to show only values that are checked
2088 if (in_array((string) $optionValue, $customData)) {
2089 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
2090 if (!$optionPerLine ||
$dncOptionPerLine) {
2094 $retValue .= $checked . $optionLabel;
2097 $retValue[] = $checked . $optionLabel;
2104 //special case for option per line formatting
2105 if ($optionPerLine > 1 && is_array($retValue)) {
2108 $displayValues = array();
2109 $displayString = '';
2110 foreach ($retValue as $val) {
2111 if ($displayString) {
2112 $displayString .= ", ";
2115 $displayString .= $val;
2119 if (($rowCounter == $optionPerLine) ||
($fieldCounter == count($retValue))) {
2120 $displayValues[] = $displayString;
2121 $displayString = '';
2125 $retValue = $displayValues;
2128 $retValue = isset($retValue) ?
$retValue : NULL;
2133 * Get the custom group titles by custom field ids.
2135 * @param array $fieldIds - array of custom field ids.
2137 * @return array $groupLabels - array consisting of groups and fields labels with ids.
2140 public static function getGroupTitles($fieldIds) {
2141 if (!is_array($fieldIds) && empty($fieldIds)) {
2145 $groupLabels = array();
2146 $fIds = "(" . implode(',', $fieldIds) . ")";
2149 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2150 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2151 FROM civicrm_custom_group, civicrm_custom_field
2152 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2153 AND civicrm_custom_field.id IN {$fIds}";
2155 $dao = CRM_Core_DAO
::executeQuery($query);
2156 while ($dao->fetch()) {
2157 $groupLabels[$dao->fieldID
] = array(
2158 'fieldID' => $dao->fieldID
,
2159 'fieldLabel' => $dao->fieldLabel
,
2160 'groupID' => $dao->groupID
,
2161 'groupTitle' => $dao->groupTitle
,
2165 return $groupLabels;
2168 static function dropAllTables() {
2169 $query = "SELECT table_name FROM civicrm_custom_group";
2170 $dao = CRM_Core_DAO
::executeQuery($query);
2172 while ($dao->fetch()) {
2173 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2174 CRM_Core_DAO
::executeQuery($query);
2179 * Check whether custom group is empty or not.
2181 * @param int $gID - custom group id.
2183 * @return boolean true if empty otherwise false.
2186 static function isGroupEmpty($gID) {
2191 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2196 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2197 $value = CRM_Core_DAO
::singleValueQuery($query);
2199 if (empty($value)) {
2207 * Get the list of types for objects that a custom group extends to.
2209 * @param array $types - var which should have the list appended.
2211 * @return array of types.
2214 static function getExtendedObjectTypes(&$types = array( )) {
2215 static $flag = FALSE, $objTypes = array();
2218 $extendObjs = array();
2219 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2221 foreach ($extendObjs as $ovId => $ovValues) {
2222 if ($ovValues['description']) {
2223 // description is expected to be a callback func to subtypes
2224 list($callback, $args) = explode(';', trim($ovValues['description']));
2230 if (!is_array($args)) {
2231 CRM_Core_Error
::fatal('Arg is not of type array');
2234 list($className) = explode('::', $callback);
2235 require_once (str_replace('_',DIRECTORY_SEPARATOR
, $className) . '.php');
2237 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2243 $types = array_merge($types, $objTypes);
2248 * @param $customGroupId
2253 static function hasReachedMaxLimit($customGroupId, $entityId) {
2254 //check whether the group is multiple
2255 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2256 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2257 $hasReachedMax = FALSE;
2259 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))) {
2260 if (!$maxMultiple) {
2261 $hasReachedMax = FALSE;
2263 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2264 //count the number of entries for a entity
2265 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2266 $params = array(1 => array($entityId, 'Integer'));
2267 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2269 if ($count >= $maxMultiple) {
2270 $hasReachedMax = TRUE;
2274 return $hasReachedMax;
2280 static function getMultipleFieldGroup() {
2281 $multipleGroup = array();
2282 $dao = new CRM_Core_DAO_CustomGroup();
2283 $dao->is_multiple
= 1 ;
2285 while($dao->fetch()) {
2286 $multipleGroup[$dao->id
] = $dao->title
;
2288 return $multipleGroup;