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 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 * Fetch object based on array of properties
217 * @param array $params (reference ) an assoc array of name/value pairs
218 * @param array $defaults (reference ) an assoc array to hold the flattened values
220 * @return CRM_Core_DAO_CustomGroup object
224 static function retrieve(&$params, &$defaults) {
225 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
229 * Update the is_active flag in the db
231 * @param int $id id of the database record
232 * @param boolean $is_active value we want to set the is_active field
234 * @return Object DAO object on sucess, null otherwise
238 static function setIsActive($id, $is_active) {
240 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
243 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
246 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
250 * Determine if given entity (sub)type has any custom groups
252 * @param string $extends e.g. "Individual", "Activity"
253 * @param int $columnId e.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id
254 * @param string $columnValue e.g. "Student" or "3" or "3\05"; see extends_entity_column_value
258 public static function hasCustomGroup($extends, $columnId, $columnValue) {
259 $dao = new CRM_Core_DAO_CustomGroup();
260 $dao->extends = $extends;
261 $dao->extends_entity_column_id
= $columnId;
262 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
263 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
264 //$dao->extends_entity_column_value = $columnValue;
265 return $dao->find() ?
TRUE : FALSE;
269 * Determine if there are any CustomGroups for the given $activityTypeId.
270 * If none found, create one.
272 * @param int $activityTypeId
273 * @return bool TRUE if a group is found or created; FALSE on error
275 public static function autoCreateByActivityType($activityTypeId) {
276 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
279 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
282 'extends' => 'Activity',
283 'extends_entity_column_id' => NULL,
284 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
285 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
289 $result = civicrm_api('CustomGroup', 'create', $params);
290 return ! $result['is_error'];
294 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
295 * This may also include entity specific data values.
297 * An array containing all custom groups and their custom fields is returned.
299 * @param string $entityType - of the contact whose contact type is needed
300 * @param CRM_Core_Form $form - not used but required
301 * @param int $entityID
302 * @param int $groupID
303 * @param string $subType
304 * @param string $subName
305 * @param bool $fromCache
306 * @param bool $onlySubType
308 * @return array $groupTree - array The returned array is keyed by group id and has the custom group table fields
309 * and a subkey 'fields' holding the specific custom fields.
310 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
311 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
313 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
314 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
315 * With caching the performance impact would be small & the function would be cleaner
321 public static function &getTree(
332 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
336 $strSelect = $strFrom = $strWhere = $orderBy = '';
337 $tableData = array();
339 // using tableData to build the queryString
341 'civicrm_custom_field' =>
362 'civicrm_custom_group' =>
373 'extends_entity_column_id',
374 'extends_entity_column_value',
381 foreach ($tableData as $tableName => $tableColumn) {
382 foreach ($tableColumn as $columnName) {
383 $alias = $tableName . "_" . $columnName;
384 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
387 $strSelect = "SELECT " . implode(', ', $select);
389 // from, where, order by
391 FROM civicrm_custom_group
392 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
395 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
396 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
$entityType == 'Household') {
397 $in = "'$entityType', 'Contact'";
399 elseif (strpos($entityType, "'") !== FALSE) {
400 // this allows the calling function to send in multiple entity types
405 $in = "'$entityType'";
410 if (is_array($subType)) {
411 $subType = implode(',', $subType);
413 if (strpos($subType, ',')) {
414 $subTypeParts = explode(',', $subType);
415 $subTypeClauses = array();
416 foreach ($subTypeParts as $subTypePart) {
417 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
418 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
422 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
425 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
429 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
432 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
435 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
436 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
441 WHERE civicrm_custom_group.is_active = 1
442 AND civicrm_custom_field.is_active = 1
443 AND civicrm_custom_group.extends IN ($in)
447 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
452 WHERE civicrm_custom_group.is_active = 1
453 AND civicrm_custom_field.is_active = 1
454 AND civicrm_custom_group.extends IN ($in)
455 AND civicrm_custom_group.extends_entity_column_value IS NULL
461 // since we want a specific group id we add it to the where clause
462 $strWhere .= " AND civicrm_custom_group.id = %1";
463 $params[1] = array($groupID, 'Integer');
466 // since groupID is false we need to show all Inline groups
467 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
470 // ensure that the user has access to these custom groups
471 $strWhere .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
472 'civicrm_custom_group.'
476 ORDER BY civicrm_custom_group.weight,
477 civicrm_custom_group.title,
478 civicrm_custom_field.weight,
479 civicrm_custom_field.label
482 // final query string
483 $queryString = "$strSelect $strFrom $strWhere $orderBy";
485 // lets see if we can retrieve the groupTree from cache
486 $cacheString = $queryString;
487 if ( $groupID > 0 ) {
488 $cacheString .= "_{$groupID}";
490 $cacheString .= "_Inline";
493 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
494 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
495 $cache = CRM_Utils_Cache
::singleton();
496 $tablesWithEntityData = array();
498 $groupTree = $cache->get($cacheKey);
499 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
502 if (empty($groupTree)) {
503 $groupTree = $multipleFieldGroups =array();
504 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
505 $customValueTables = array();
508 while ($crmDAO->fetch()) {
510 $groupID = $crmDAO->civicrm_custom_group_id
;
511 $fieldId = $crmDAO->civicrm_custom_field_id
;
512 if($crmDAO->civicrm_custom_group_is_multiple
){
513 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
515 // create an array for groups if it does not exist
516 if (!array_key_exists($groupID, $groupTree)) {
517 $groupTree[$groupID] = array();
518 $groupTree[$groupID]['id'] = $groupID;
520 // populate the group information
521 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
522 $fullFieldName = "civicrm_custom_group_$fieldName";
523 if ($fieldName == 'id' ||
524 is_null($crmDAO->$fullFieldName)
529 if ($fieldName == 'extends_entity_column_value' && $subType) {
530 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
532 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
534 $groupTree[$groupID]['fields'] = array();
536 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
539 // add the fields now (note - the query row will always contain a field)
540 // we only reset this once, since multiple values come is as multiple rows
541 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
542 $groupTree[$groupID]['fields'][$fieldId] = array();
545 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
546 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
547 // populate information for a custom field
548 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
549 $fullFieldName = "civicrm_custom_field_$fieldName";
550 if ($fieldName == 'id' ||
551 is_null($crmDAO->$fullFieldName)
555 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
559 if (!empty($customValueTables)) {
560 $groupTree['info'] = array('tables' => $customValueTables);
563 $cache->set($cacheKey, $groupTree);
564 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
566 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
567 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
568 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
569 $singleFieldTables = array();
570 // now that we have all the groups and fields, lets get the values
571 // since we need to know the table and field names
572 // add info to groupTree
574 if (isset($groupTree['info']) && !empty($groupTree['info']) && !empty($groupTree['info']['tables'])) {
575 $select = $from = $where = array();
576 $groupTree['info']['where'] = NULL;
578 foreach ($groupTree['info']['tables'] as $table => $fields) {
579 $groupTree['info']['from'][] = $table;
580 $select = array("{$table}.id as {$table}_id",
581 "{$table}.entity_id as {$table}_entity_id");
582 foreach ($fields as $column => $dontCare) {
583 $select[] = "{$table}.{$column} as {$table}_{$column}";
585 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
587 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
588 if(in_array($table, $multipleFieldGroups) && self
::customGroupDataExistsForEntity($entityID, $table)){
589 $entityMultipleSelectClauses[$table] = $select;
592 $singleFieldTables[] = $table;
593 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
598 if ($entityID && !empty($singleFieldTables)) {
599 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
601 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
602 if(!empty($multipleFieldTablesWithEntityData)){
603 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
611 * Check whether the custom group has any data for the given entity.
614 * @param integer $entityID id of entity for whom we are checking data for
615 * @param string $table table that we are checking
617 * @param bool $getCount
619 * @return boolean does this entity have data in this custom table
621 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE){
625 WHERE entity_id = $entityID
627 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
629 return $recordExists;
631 return $recordExists ?
TRUE : FALSE;
635 * Build the group tree for Custom fields which are not 'is_multiple'
637 * The combination of all these fields in one query with a 'using' join was not working for
638 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
639 * mechanism as it seemed to be acceptable in this context
641 * @param array $groupTree (reference) group tree array which is being built
642 * @param integer $entityID id of entity for whom the tree is being build up.
643 * @param array $entitySingleSelectClauses array of select clauses relevant to the entity
644 * @param array $singleFieldTablesWithEntityData array of tables in which this entity has data
646 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData){
647 $select = implode(', ', $entitySingleSelectClauses);
648 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
649 foreach ($singleFieldTablesWithEntityData as $table) {
650 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
656 WHERE first.entity_id = $entityID
658 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
662 * Build the group tree for Custom fields which are 'is_multiple'
664 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
666 * @param array $groupTree (reference) group tree array which is being built
667 * @param integer $entityID id of entity for whom the tree is being build up.
668 * @param array $entityMultipleSelectClauses array of select clauses relevant to the entity
669 * @param array $multipleFieldTablesWithEntityData array of tables in which this entity has data
671 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData){
672 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
673 $select = implode(',', $selectClauses);
677 WHERE entity_id = $entityID
679 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
684 * Build the tree entity data - starting from a query retrieving the custom fields build the group
685 * tree data for the relevant entity (entity is included in the query).
687 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
689 * @param array $groupTree (reference) group tree array which is being built
690 * @param string $query
691 * @param array $includedTables tables to include - required because the function (for historical reasons)
692 * iterates through the group tree
694 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables){
695 $dao = CRM_Core_DAO
::executeQuery($query);
696 while ($dao->fetch()) {
697 foreach ($groupTree as $groupID => $group) {
698 if ($groupID === 'info') {
701 $table = $groupTree[$groupID]['table_name'];
702 //working from the groupTree instead of the table list means we have to iterate & exclude.
703 // this could possibly be re-written as other parts of the function have been refactored
704 // for now we just check if the given table is to be included in this function
705 if( !in_array($table, $includedTables)){
708 foreach ($group['fields'] as $fieldID => $dontCare) {
709 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
716 * Build the entity-specific custom data into the group tree on a per-field basis
718 * @param object $dao object representing the custom field to be populated into the groupTree
719 * @param array $groupTree (reference) the group tree being build
720 * @param string $table table name
721 * @param unknown_type $groupID custom group ID
722 * @param unknown_type $fieldID custom field ID
724 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID){
725 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
726 $idName = "{$table}_id";
727 $fieldName = "{$table}_{$column}";
728 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
729 if ($dataType == 'File') {
730 if (isset($dao->$fieldName)) {
731 $config = CRM_Core_Config
::singleton();
732 $fileDAO = new CRM_Core_DAO_File();
733 $fileDAO->id
= $dao->$fieldName;
735 if ($fileDAO->find(TRUE)) {
736 $entityIDName = "{$table}_entity_id";
737 $customValue['id'] = $dao->$idName;
738 $customValue['data'] = $fileDAO->uri
;
739 $customValue['fid'] = $fileDAO->id
;
740 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
741 $customValue['displayURL'] = NULL;
742 $deleteExtra = ts('Are you sure you want to delete attached file.');
744 CRM_Core_Action
::DELETE
=>
746 'name' => ts('Delete Attached File'),
747 'url' => 'civicrm/file',
748 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
750 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
753 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
754 CRM_Core_Action
::DELETE
,
756 'id' => $fileDAO->id
,
757 'eid' => $dao->$entityIDName,
762 'file.manage.delete',
766 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
767 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
768 if ($fileDAO->mime_type
== "image/jpeg" ||
769 $fileDAO->mime_type
== "image/pjpeg" ||
770 $fileDAO->mime_type
== "image/gif" ||
771 $fileDAO->mime_type
== "image/x-png" ||
772 $fileDAO->mime_type
== "image/png"
774 $customValue['displayURL'] = $customValue['fileURL'];
775 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
780 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) . $fileDAO->uri
;
781 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId,
784 if ($path && file_exists($path)) {
785 list($imageWidth, $imageHeight) = getimagesize($path);
786 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
787 $customValue['imageThumbWidth'] = $imageThumbWidth;
788 $customValue['imageThumbHeight'] = $imageThumbHeight;
794 $customValue = array(
795 'id' => $dao->$idName,
801 $customValue = array(
802 'id' => $dao->$idName,
803 'data' => $dao->$fieldName,
807 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
808 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
810 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
811 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
814 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
819 * Get the group title.
821 * @param int $id id of group.
823 * @return string title
829 public static function getTitle($id) {
830 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
834 * Get custom group details for a group.
836 * An array containing custom group details (including their custom field) is returned.
838 * @param int $groupId - group id whose details are needed
839 * @param boolean $searchable - is this field searchable
840 * @param array $extends - which table does it extend if any
842 * @param null $inSelector
844 * @return array $groupTree - array consisting of all group and field details
850 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
852 $groupTree = array();
853 $select = $from = $where = $orderBy = '';
855 $tableData = array();
857 // using tableData to build the queryString
859 'civicrm_custom_field' =>
884 'civicrm_custom_group' =>
892 'collapse_adv_display',
894 'extends_entity_column_value',
903 foreach ($tableData as $tableName => $tableColumn) {
904 foreach ($tableColumn as $columnName) {
905 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
908 $select = 'SELECT ' . implode(', ', $s);
910 // from, where, order by
911 $from = " FROM civicrm_custom_field, civicrm_custom_group";
912 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
913 AND civicrm_custom_group.is_active = 1
914 AND civicrm_custom_field.is_active = 1 ";
916 $params[1] = array($groupId, 'Integer');
917 $where .= " AND civicrm_custom_group.id = %1";
921 $where .= " AND civicrm_custom_field.is_searchable = 1";
925 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
930 foreach ($extends as $e) {
931 $clause[] = "civicrm_custom_group.extends = '$e'";
933 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
935 //include case activities customdata if case is enabled
936 if (in_array('Activity', $extends)) {
937 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
938 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
939 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
943 // ensure that the user has access to these custom groups
944 $where .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
945 'civicrm_custom_group.'
948 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
950 // final query string
951 $queryString = $select . $from . $where . $orderBy;
954 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
957 while ($crmDAO->fetch()) {
958 $groupId = $crmDAO->civicrm_custom_group_id
;
959 $fieldId = $crmDAO->civicrm_custom_field_id
;
961 // create an array for groups if it does not exist
962 if (!array_key_exists($groupId, $groupTree)) {
963 $groupTree[$groupId] = array();
964 $groupTree[$groupId]['id'] = $groupId;
966 foreach ($tableData['civicrm_custom_group'] as $v) {
967 $fullField = "civicrm_custom_group_" . $v;
969 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
973 $groupTree[$groupId][$v] = $crmDAO->$fullField;
976 $groupTree[$groupId]['fields'] = array();
979 // add the fields now (note - the query row will always contain a field)
980 $groupTree[$groupId]['fields'][$fieldId] = array();
981 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
983 foreach ($tableData['civicrm_custom_field'] as $v) {
984 $fullField = "civicrm_custom_field_" . $v;
985 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
988 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
998 * @param string $cidToken
1002 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1004 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1006 // get 'Tab' and 'Tab with table' groups
1007 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1008 $customGroupDAO->whereAdd("is_active = 1");
1010 // add whereAdd for entity type
1011 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1015 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1016 $customGroupDAO->whereAdd($permissionClause);
1019 $customGroupDAO->orderBy('weight');
1020 $customGroupDAO->find();
1022 // process each group with menu tab
1023 while ($customGroupDAO->fetch()) {
1025 $group['id'] = $customGroupDAO->id
;
1026 $group['path'] = $path;
1027 $group['title'] = "$customGroupDAO->title";
1028 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1029 $group['extra'] = array('gid' => $customGroupDAO->id
);
1030 $group['table_name'] = $customGroupDAO->table_name
;
1031 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1039 * Get the table name for the entity type
1040 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1041 * tableName is 'civicrm_contact'
1043 * @param string $entityType what entity are we extending here ?
1045 * @return string $tableName
1050 * @see _apachesolr_civiAttachments_dereference_file_parent
1052 public static function getTableNameByEntityName($entityType) {
1054 switch ($entityType) {
1058 case 'Organization':
1059 $tableName = 'civicrm_contact';
1062 case 'Contribution':
1063 $tableName = 'civicrm_contribution';
1067 $tableName = 'civicrm_group';
1069 // DRAFTING: Verify if we cannot make it pluggable
1072 $tableName = 'civicrm_activity';
1075 case 'Relationship':
1076 $tableName = 'civicrm_relationship';
1080 $tableName = 'civicrm_membership';
1084 $tableName = 'civicrm_participant';
1088 $tableName = 'civicrm_event';
1092 $tableName = 'civicrm_grant';
1094 // need to add cases for Location, Address
1101 * Get a list of custom groups which extend a given entity type.
1102 * If there are custom-groups which only apply to certain subtypes,
1103 * those WILL be included.
1105 * @param $entityType string
1106 * @return CRM_Core_DAO_CustomGroup
1108 static function getAllCustomGroupsByBaseEntity($entityType) {
1109 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1110 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1111 return $customGroupDAO;
1115 * Add the whereAdd clause for the DAO depending on the type of entity
1116 * the custom group is extending.
1118 * @param $customGroupDAO
1119 * @param string $entityType - what entity are we extending here ?
1121 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
1122 * @param bool $allSubtypes
1129 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1130 $addSubtypeClause = FALSE;
1132 switch ($entityType) {
1134 // if contact, get all related to contact
1135 $extendList = "'Contact','Individual','Household','Organization'";
1136 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1137 if (!$allSubtypes) {
1138 $addSubtypeClause = TRUE;
1144 case 'Organization':
1145 // is I/H/O then get I/H/O and contact
1146 $extendList = "'Contact','$entityType'";
1147 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1148 if (!$allSubtypes) {
1149 $addSubtypeClause = TRUE;
1157 case 'Contribution':
1160 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1164 if ($addSubtypeClause) {
1165 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1167 if (!empty($csType)) {
1168 $subtypeClause = array();
1169 foreach ($csType as $subtype) {
1170 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
1171 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1173 $subtypeClause[] = "extends_entity_column_value IS NULL";
1174 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) . " )");
1177 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1183 * Delete the Custom Group.
1185 * @param $group object the DAO custom group object
1186 * @param $force boolean whether to force the deletion, even if there are custom fields
1188 * @return boolean false if field exists for this group, true if group gets deleted.
1194 public static function deleteGroup($group, $force = FALSE) {
1196 //check wheter this contain any custom fields
1197 $customField = new CRM_Core_DAO_CustomField();
1198 $customField->custom_group_id
= $group->id
;
1199 $customField->find();
1201 // return early if there are custom fields and we're not
1202 // forcing the delete, otherwise delete the fields one by one
1203 while ($customField->fetch()) {
1207 CRM_Core_BAO_CustomField
::deleteField($customField);
1210 // drop the table associated with this custom group
1211 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1213 //delete custom group
1216 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1224 * @param bool $viewMode
1225 * @param bool $inactiveNeeded
1226 * @param int $action
1228 static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1229 foreach ($groupTree as $id => $group) {
1230 if (!isset($group['fields'])) {
1233 foreach ($group['fields'] as $field) {
1234 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1235 $value = $field['element_value'];
1237 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1238 ($action != CRM_Core_Action
::UPDATE ||
1240 !array_key_exists('element_value', $field)
1243 $value = $viewMode ?
NULL : $field['default_value'];
1249 if (!empty($field['element_name'])) {
1250 $elementName = $field['element_name'];
1252 switch ($field['html_type']) {
1253 case 'Multi-Select':
1254 case 'AdvMulti-Select':
1256 $defaults[$elementName] = array();
1257 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1259 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1260 if (isset($value)) {
1261 foreach ($customOption as $customValue => $customLabel) {
1262 if (in_array($customValue, $checkedData)) {
1263 if ($field['html_type'] == 'CheckBox') {
1264 $defaults[$elementName][$customValue] = 1;
1267 $defaults[$elementName][$customValue] = $customValue;
1271 $defaults[$elementName][$customValue] = 0;
1277 if (isset($field['customValue']['data'])) {
1278 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1279 foreach ($customOption as $val) {
1280 if (in_array($val['value'], $checkedData)) {
1281 if ($field['html_type'] == 'CheckBox') {
1282 $defaults[$elementName][$val['value']] = 1;
1285 $defaults[$elementName][$val['value']] = $val['value'];
1289 $defaults[$elementName][$val['value']] = 0;
1294 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1295 foreach ($customOption as $val) {
1296 if (in_array($val['value'], $checkedValue)) {
1297 if ($field['html_type'] == 'CheckBox') {
1298 $defaults[$elementName][$val['value']] = 1;
1301 $defaults[$elementName][$val['value']] = $val['value'];
1310 if (isset($value)) {
1311 if (empty($field['time_format'])) {
1312 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1313 $field['date_format']
1317 $timeElement = $elementName . '_time';
1318 if (substr($elementName, -1) == ']') {
1319 $timeElement = substr($elementName, 0, -1) . '_time]';
1321 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1326 case 'Multi-Select Country':
1327 case 'Multi-Select State/Province':
1328 if (isset($value)) {
1329 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1330 foreach ($checkedValue as $val) {
1332 $defaults[$elementName][$val] = $val;
1338 case 'Select Country':
1340 $defaults[$elementName] = $value;
1343 $config = CRM_Core_Config
::singleton();
1344 $defaults[$elementName] = $config->defaultContactCountry
;
1349 if ($field['data_type'] == "Float") {
1350 $defaults[$elementName] = (float)$value;
1352 elseif ($field['data_type'] == 'Money' &&
1353 $field['html_type'] == 'Text'
1355 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1358 $defaults[$elementName] = $value;
1367 * @param array $params
1368 * @param bool $skipFile
1370 static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1371 // Get the Custom form values and groupTree
1372 // first reset all checkbox and radio data
1373 foreach ($groupTree as $groupID => $group) {
1374 if ($groupID === 'info') {
1377 foreach ($group['fields'] as $field) {
1378 $fieldId = $field['id'];
1380 //added Multi-Select option in the below if-statement
1381 if ($field['html_type'] == 'CheckBox' ||
$field['html_type'] == 'Radio' ||
1382 $field['html_type'] == 'AdvMulti-Select' ||
$field['html_type'] == 'Multi-Select'
1384 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1388 foreach ($params as $key => $val) {
1389 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1390 $match[1] == $field['id']
1397 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1398 // field exists in db so populate value from "form".
1399 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1402 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1404 //added for CheckBox
1408 $customValue = array_keys($v);
1409 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1412 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1416 //added for Advanced Multi-Select
1418 case 'AdvMulti-Select':
1419 //added for Multi-Select
1420 case 'Multi-Select':
1422 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1425 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1430 $date = CRM_Utils_Date
::processDate($v);
1431 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1439 //store the file in d/b
1440 $entityId = explode('=', $groupTree['info']['where'][0]);
1441 $fileParams = array('upload_date' => date('Ymdhis'));
1443 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1444 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1447 $fileParams['uri'] = $v['name'];
1448 $fileParams['mime_type'] = $v['type'];
1449 CRM_Core_BAO_File
::filePostProcess($v['name'],
1450 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1451 $groupTree[$groupID]['table_name'],
1456 'custom_' . $fieldId,
1460 $defaults = array();
1461 $paramsFile = array(
1462 'entity_table' => $groupTree[$groupID]['table_name'],
1463 'entity_id' => $entityId[1],
1466 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1471 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1475 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1483 * Generic function to build all the form elements for a specific group tree
1485 * @param CRM_Core_Form $form the form object
1486 * @param array $groupTree the group tree object
1487 * @param boolean $inactiveNeeded return inactive custom groups
1488 * @param string $prefix prefix for custom grouptree assigned to template
1494 static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '' ) {
1495 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1497 // this is fix for date field
1498 $form->assign('currentYear', date('Y'));
1500 foreach ($groupTree as $id => $group) {
1501 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1502 foreach ($group['fields'] as $field) {
1503 $required = CRM_Utils_Array
::value('is_required', $field);
1505 if ($field['data_type'] == 'File') {
1506 if (!empty($field['element_value']['data'])) {
1511 $fieldId = $field['id'];
1512 $elementName = $field['element_name'];
1513 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1519 * Extract the get params from the url, validate
1520 * and store it in session
1522 * @param CRM_Core_Form $form the form object
1523 * @param string $type the type of custom group we are using
1529 static function extractGetParams(&$form, $type) {
1534 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1535 $customValue = array();
1536 $htmlType = array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Select', 'Radio');
1538 foreach ($groupTree as $group) {
1539 if (!isset($group['fields'])) {
1542 foreach ($group['fields'] as $key => $field) {
1543 $fieldName = 'custom_' . $key;
1544 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1548 if (!in_array($field['html_type'], $htmlType) ||
1549 $field['data_type'] == 'Boolean'
1551 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1553 if ($field['html_type'] == 'CheckBox' ||
1554 $field['html_type'] == 'AdvMulti-Select' ||
1555 $field['html_type'] == 'Multi-Select'
1557 $value = str_replace("|", ",", $value);
1558 $mulValues = explode(',', $value);
1559 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1561 foreach ($mulValues as $v1) {
1562 foreach ($customOption as $coID => $coValue) {
1563 if (strtolower(trim($coValue['label'])) == strtolower(trim($v1))) {
1564 $val[$coValue['value']] = 1;
1576 elseif ($field['html_type'] == 'Select' ||
1577 ($field['html_type'] == 'Radio' &&
1578 $field['data_type'] != 'Boolean'
1581 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1582 foreach ($customOption as $customID => $coValue) {
1583 if (strtolower(trim($coValue['label'])) == strtolower(trim($value))) {
1584 $value = $coValue['value'];
1589 elseif ($field['data_type'] == 'Date') {
1590 if (!empty($value)) {
1592 if (!empty($field['time_format'])) {
1593 $time = CRM_Utils_Request
::retrieve($fieldName . '_time', 'String', $form, FALSE, NULL, 'GET');
1595 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value . ' ' . $time);
1596 if (!empty($field['time_format'])) {
1597 $customValue[$fieldName . '_time'] = $time;
1604 $customValue[$fieldName] = $value;
1610 return $customValue;
1614 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1615 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1617 * @param int $customFieldId custom field id
1618 * @param array $removeCustomFieldTypes remove custom fields of a type eg: array("Individual") ;
1621 * @return boolean false if it matches else true
1625 static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1626 $query = "SELECT cg.extends as extends
1627 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1628 WHERE cg.id = cf.custom_group_id
1629 AND cf.id =" . CRM_Utils_Type
::escape($customFieldId, 'Integer');
1631 $extends = CRM_Core_DAO
::singleValueQuery($query);
1633 if (in_array($extends, $removeCustomFieldTypes)) {
1645 static function mapTableName($table) {
1650 case 'Organization':
1651 return 'civicrm_contact';
1654 return 'civicrm_activity';
1657 return 'civicrm_group';
1659 case 'Contribution':
1660 return 'civicrm_contribution';
1662 case 'Relationship':
1663 return 'civicrm_relationship';
1666 return 'civicrm_event';
1669 return 'civicrm_membership';
1672 case 'ParticipantRole':
1673 case 'ParticipantEventName':
1674 case 'ParticipantEventType':
1675 return 'civicrm_participant';
1678 return 'civicrm_grant';
1681 return 'civicrm_pledge';
1684 return 'civicrm_address';
1687 return 'civicrm_campaign';
1691 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1692 $qParams = array(1 => array($table, 'String'));
1693 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1696 return 'civicrm_contact';
1699 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1700 if (array_key_exists($table, $extendObjs)) {
1701 return $extendObjs[$table];
1703 CRM_Core_Error
::fatal();
1711 static function createTable($group) {
1713 'name' => $group->table_name
,
1714 'is_multiple' => $group->is_multiple ?
1 : 0,
1715 'extends_name' => self
::mapTableName($group->extends),
1718 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1720 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1724 * Function returns formatted groupTree, sothat form can be easily build in template
1726 * @param array $groupTree associated array
1727 * @param int $groupCount group count by default 1, but can varry for multiple value custom data
1728 * @param object form object
1730 * @return array $formattedGroupTree
1732 static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1733 $formattedGroupTree = array();
1734 $uploadNames = array();
1736 foreach ($groupTree as $key => $value) {
1737 if ($key === 'info') {
1741 // add group information
1742 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1743 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1744 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1745 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1746 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1747 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1749 // this params needed of bulding multiple values
1750 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1751 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1752 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1753 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1754 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1755 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1757 // add field information
1758 foreach ($value['fields'] as $k => $properties) {
1759 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1760 if (isset($properties['customValue']) && !CRM_Utils_System
::isNull($properties['customValue'])) {
1761 if (isset($properties['customValue'][$groupCount])) {
1762 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1763 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1764 if ($properties['data_type'] == 'File') {
1765 $properties['element_value'] = $properties['customValue'][$groupCount];
1766 $uploadNames[] = $properties['element_name'];
1769 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1773 unset($properties['customValue']);
1774 $formattedGroupTree[$key]['fields'][$k] = $properties;
1779 // hack for field type File
1780 $formUploadNames = $form->get('uploadNames');
1781 if (is_array($formUploadNames)) {
1782 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1785 $form->set('uploadNames', $uploadNames);
1788 return $formattedGroupTree;
1792 * Build custom data view
1794 * @param CRM_Core_Form $form page object
1795 * @param array $groupTree associated array
1796 * @param boolean $returnCount true if customValue count needs to be returned
1798 * @param null $prefix
1799 * @param int $customValueId
1803 static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1805 foreach ($groupTree as $key => $group) {
1806 if ($key === 'info') {
1810 foreach ($group['fields'] as $k => $properties) {
1811 $groupID = $group['id'];
1812 if (!empty($properties['customValue'])) {
1813 foreach ($properties['customValue'] as $values) {
1814 if (!empty($customValueId) && $customValueId != $values['id']) {
1817 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1818 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1819 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1820 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1821 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1822 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1823 $details[$groupID][$values['id']]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties),
1824 'field_type' => CRM_Utils_Array
::value('html_type',
1827 'field_data_type' => CRM_Utils_Array
::value('data_type',
1830 'field_value' => self
::formatCustomValues($values,
1833 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1837 // also return contact reference contact id if user has view all or edit all contacts perm
1838 if ((CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts'))
1839 && $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] == 'ContactReference'
1841 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1846 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1847 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1848 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1849 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1850 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1851 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1852 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1858 //return a single value count if group id is passed to function
1859 //else return a groupId and count mapped array
1861 return count($details[$gID]);
1864 $countValue = array();
1865 foreach( $details as $key => $value ) {
1866 $countValue[$key] = count($details[$key]);
1872 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1878 * Format custom value according to data, view mode
1880 * @param array $values associated array of custom values
1881 * @param array $field associated array
1882 * @param boolean $dncOptionPerLine true if optionPerLine should not be consider
1884 * @return array|null|string
1886 static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1887 $value = $values['data'];
1889 //changed isset CRM-4601
1890 if (CRM_Utils_System
::isNull($value)) {
1894 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1895 $dataType = CRM_Utils_Array
::value('data_type', $field);
1896 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1897 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1898 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1901 $freezeStringChecked = "";
1903 switch ($dataType) {
1905 $customTimeFormat = '';
1906 $customFormat = NULL;
1908 switch ($timeFormat) {
1910 $customTimeFormat = '%l:%M %P';
1914 $customTimeFormat = '%H:%M';
1918 // if time is not selected remove time from value
1919 $value = substr($value, 0, 10);
1922 $supportableFormats = array(
1923 'mm/dd' => "%B %E%f $customTimeFormat",
1924 'dd-mm' => "%E%f %B $customTimeFormat",
1925 'yy' => "%Y $customTimeFormat",
1926 'M yy' => "%b %Y $customTimeFormat",
1927 'yy-mm' => "%Y-%m $customTimeFormat"
1930 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
1931 if (array_key_exists($format, $supportableFormats)) {
1932 $customFormat = $supportableFormats["$format"];
1936 $retValue = CRM_Utils_Date
::customFormat($value, $customFormat);
1940 if ($value == '1') {
1941 $retValue = $freezeStringChecked . ts('Yes') . "\n";
1944 $retValue = $freezeStringChecked . ts('No') . "\n";
1950 $retValue = CRM_Utils_System
::formatWikiURL($value);
1955 $retValue = $values;
1958 case 'ContactReference':
1959 if (!empty($values['data'])) {
1960 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
1969 if ($htmlType == 'Text') {
1970 $retValue = (float)$value;
1974 if ($htmlType == 'Text') {
1975 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1980 if (in_array($htmlType, array('Text', 'TextArea'))) {
1984 // note that if its not text / textarea, the code falls thru and executes
1985 // the below case also
1986 case 'StateProvince':
1991 //added check for Multi-Select in the below if-statement
1992 $customData[] = $value;
1994 //form custom data for multiple-valued custom data
1995 switch ($htmlType) {
1996 case 'Multi-Select Country':
1997 case 'Select Country':
1998 $customData = $value;
1999 if (!is_array($value)) {
2000 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2003 SELECT id as value, name as label
2004 FROM civicrm_country";
2005 $coDAO = CRM_Core_DAO
::executeQuery($query);
2008 case 'Select State/Province':
2009 case 'Multi-Select State/Province':
2010 $customData = $value;
2011 if (!is_array($value)) {
2012 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2016 SELECT id as value, name as label
2017 FROM civicrm_state_province";
2018 $coDAO = CRM_Core_DAO
::executeQuery($query);
2022 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2023 if ($option_group_id) {
2024 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2029 case 'AdvMulti-Select':
2030 case 'Multi-Select':
2031 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2033 if ($option_group_id) {
2034 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2038 if (is_object($coDAO)) {
2039 while ($coDAO->fetch()) {
2040 if ($dataType == 'Country') {
2041 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2042 // and already extracted to .pot files.
2043 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
2045 elseif ($dataType == 'StateProvince') {
2046 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
2049 $options[$coDAO->value
] = $coDAO->label
;
2054 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
2057 foreach ($options as $optionValue => $optionLabel) {
2058 if ($dataType == 'Money') {
2059 foreach ($customData as $k => $v) {
2060 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
2064 //to show only values that are checked
2065 if (in_array((string) $optionValue, $customData)) {
2066 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
2067 if (!$optionPerLine ||
$dncOptionPerLine) {
2071 $retValue .= $checked . $optionLabel;
2074 $retValue[] = $checked . $optionLabel;
2081 //special case for option per line formatting
2082 if ($optionPerLine > 1 && is_array($retValue)) {
2085 $displayValues = array();
2086 $displayString = '';
2087 foreach ($retValue as $val) {
2088 if ($displayString) {
2089 $displayString .= ", ";
2092 $displayString .= $val;
2096 if (($rowCounter == $optionPerLine) ||
($fieldCounter == count($retValue))) {
2097 $displayValues[] = $displayString;
2098 $displayString = '';
2102 $retValue = $displayValues;
2105 $retValue = isset($retValue) ?
$retValue : NULL;
2110 * Get the custom group titles by custom field ids.
2112 * @param array $fieldIds - array of custom field ids.
2114 * @return array $groupLabels - array consisting of groups and fields labels with ids.
2117 public static function getGroupTitles($fieldIds) {
2118 if (!is_array($fieldIds) && empty($fieldIds)) {
2122 $groupLabels = array();
2123 $fIds = "(" . implode(',', $fieldIds) . ")";
2126 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2127 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2128 FROM civicrm_custom_group, civicrm_custom_field
2129 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2130 AND civicrm_custom_field.id IN {$fIds}";
2132 $dao = CRM_Core_DAO
::executeQuery($query);
2133 while ($dao->fetch()) {
2134 $groupLabels[$dao->fieldID
] = array(
2135 'fieldID' => $dao->fieldID
,
2136 'fieldLabel' => $dao->fieldLabel
,
2137 'groupID' => $dao->groupID
,
2138 'groupTitle' => $dao->groupTitle
,
2142 return $groupLabels;
2145 static function dropAllTables() {
2146 $query = "SELECT table_name FROM civicrm_custom_group";
2147 $dao = CRM_Core_DAO
::executeQuery($query);
2149 while ($dao->fetch()) {
2150 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2151 CRM_Core_DAO
::executeQuery($query);
2156 * Check whether custom group is empty or not.
2158 * @param int $gID - custom group id.
2160 * @return boolean true if empty otherwise false.
2163 static function isGroupEmpty($gID) {
2168 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2173 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2174 $value = CRM_Core_DAO
::singleValueQuery($query);
2176 if (empty($value)) {
2184 * Get the list of types for objects that a custom group extends to.
2186 * @param array $types - var which should have the list appended.
2188 * @return array of types.
2191 static function getExtendedObjectTypes(&$types = array( )) {
2192 static $flag = FALSE, $objTypes = array();
2195 $extendObjs = array();
2196 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2198 foreach ($extendObjs as $ovId => $ovValues) {
2199 if ($ovValues['description']) {
2200 // description is expected to be a callback func to subtypes
2201 list($callback, $args) = explode(';', trim($ovValues['description']));
2207 if (!is_array($args)) {
2208 CRM_Core_Error
::fatal('Arg is not of type array');
2211 list($className) = explode('::', $callback);
2212 require_once (str_replace('_',DIRECTORY_SEPARATOR
, $className) . '.php');
2214 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2220 $types = array_merge($types, $objTypes);
2225 * @param int $customGroupId
2226 * @param int $entityId
2230 static function hasReachedMaxLimit($customGroupId, $entityId) {
2231 //check whether the group is multiple
2232 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2233 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2234 $hasReachedMax = FALSE;
2236 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))) {
2237 if (!$maxMultiple) {
2238 $hasReachedMax = FALSE;
2240 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2241 //count the number of entries for a entity
2242 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2243 $params = array(1 => array($entityId, 'Integer'));
2244 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2246 if ($count >= $maxMultiple) {
2247 $hasReachedMax = TRUE;
2251 return $hasReachedMax;
2257 static function getMultipleFieldGroup() {
2258 $multipleGroup = array();
2259 $dao = new CRM_Core_DAO_CustomGroup();
2260 $dao->is_multiple
= 1 ;
2262 while($dao->fetch()) {
2263 $multipleGroup[$dao->id
] = $dao->title
;
2265 return $multipleGroup;