3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
35 * Business object for managing custom data groups.
37 class CRM_Core_BAO_CustomGroup
extends CRM_Core_DAO_CustomGroup
{
42 public function __construct() {
43 parent
::__construct();
47 * Takes an associative array and creates a custom group object.
49 * This function is invoked from within the web form layer and also from the api layer
51 * @param array $params
52 * (reference) an assoc array of name/value pairs.
54 * @return CRM_Core_DAO_CustomGroup
56 public static function create(&$params) {
57 // create custom group dao, populate fields and then save.
58 $group = new CRM_Core_DAO_CustomGroup();
59 if (isset($params['title'])) {
60 $group->title
= $params['title'];
63 if (in_array($params['extends'][0],
66 'ParticipantEventName',
67 'ParticipantEventType',
70 $group->extends = 'Participant';
73 $group->extends = $params['extends'][0];
76 $group->extends_entity_column_id
= 'null';
78 $params['extends'][0] == 'ParticipantRole' ||
79 $params['extends'][0] == 'ParticipantEventName' ||
80 $params['extends'][0] == 'ParticipantEventType'
82 $group->extends_entity_column_id
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $params['extends'][0], 'value', 'name');
85 //this is format when form get submit.
86 $extendsChildType = CRM_Utils_Array
::value(1, $params['extends']);
87 //lets allow user to pass direct child type value, CRM-6893
88 if (!empty($params['extends_entity_column_value'])) {
89 $extendsChildType = $params['extends_entity_column_value'];
91 if (!CRM_Utils_System
::isNull($extendsChildType)) {
92 $extendsChildType = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendsChildType);
93 if (CRM_Utils_Array
::value(0, $params['extends']) == 'Relationship') {
94 $extendsChildType = str_replace(array('_a_b', '_b_a'), array(
97 ), $extendsChildType);
99 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
100 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType .
101 CRM_Core_DAO
::VALUE_SEPARATOR
;
105 $extendsChildType = 'null';
107 $group->extends_entity_column_value
= $extendsChildType;
109 if (isset($params['id'])) {
110 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
115 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
119 'collapse_adv_display',
125 foreach ($fields as $field) {
126 if (isset($params[$field]) ||
$field == 'is_multiple') {
127 $group->$field = CRM_Utils_Array
::value($field, $params, FALSE);
130 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
131 $params['max_multiple'] >= '0'
132 ) ?
$params['max_multiple'] : 'null' : 'null';
134 $tableName = $oldTableName = NULL;
135 if (isset($params['id'])) {
136 $group->id
= $params['id'];
137 //check whether custom group was changed from single-valued to multiple-valued
138 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
143 if ((!empty($params['is_multiple']) ||
$isMultiple) &&
144 ($params['is_multiple'] != $isMultiple)
146 $oldTableName = CRM_Core_DAO
::getFieldValue(
147 'CRM_Core_DAO_CustomGroup',
154 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
155 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
157 // we do this only once, so name never changes
158 if (isset($params['name'])) {
159 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
162 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
165 if (isset($params['table_name'])) {
166 $tableName = $params['table_name'];
168 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
169 // Bad idea. Prevent group creation because it might lead to a broken configuration.
170 CRM_Core_Error
::fatal(ts("Cannot create custom table because %1 is already a core table.", array('1' => $tableName)));
175 if (array_key_exists('is_reserved', $params)) {
176 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
178 $op = isset($params['id']) ?
'edit' : 'create';
179 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
181 // enclose the below in a transaction
182 $transaction = new CRM_Core_Transaction();
185 if (!isset($params['id'])) {
186 if (!isset($params['table_name'])) {
187 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 42));
188 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
190 $group->table_name
= $tableName;
191 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
197 // now create the table associated with this group
198 self
::createTable($group);
200 elseif ($oldTableName) {
201 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($oldTableName, CRM_Utils_Array
::value('is_multiple', $params));
204 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
205 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
209 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends'][0]));
211 $transaction->commit();
214 CRM_Utils_System
::flushCache();
217 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
220 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
227 * Fetch object based on array of properties.
229 * @param array $params
230 * (reference ) an assoc array of name/value pairs.
231 * @param array $defaults
232 * (reference ) an assoc array to hold the flattened values.
234 * @return CRM_Core_DAO_CustomGroup
236 public static function retrieve(&$params, &$defaults) {
237 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
241 * Update the is_active flag in the db.
244 * Id of the database record.
245 * @param bool $is_active
246 * Value we want to set the is_active field.
249 * DAO object on success, null otherwise
251 public static function setIsActive($id, $is_active) {
253 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
256 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
259 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
263 * Determine if given entity (sub)type has any custom groups
265 * @param string $extends
266 * E.g. "Individual", "Activity".
267 * @param int $columnId
268 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
269 * @param string $columnValue
270 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
274 public static function hasCustomGroup($extends, $columnId, $columnValue) {
275 $dao = new CRM_Core_DAO_CustomGroup();
276 $dao->extends = $extends;
277 $dao->extends_entity_column_id
= $columnId;
278 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
279 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
280 //$dao->extends_entity_column_value = $columnValue;
281 return $dao->find() ?
TRUE : FALSE;
285 * Determine if there are any CustomGroups for the given $activityTypeId.
286 * If none found, create one.
288 * @param int $activityTypeId
291 * TRUE if a group is found or created; FALSE on error
293 public static function autoCreateByActivityType($activityTypeId) {
294 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
297 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
300 'extends' => 'Activity',
301 'extends_entity_column_id' => NULL,
302 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
303 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
307 $result = civicrm_api('CustomGroup', 'create', $params);
308 return !$result['is_error'];
312 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
313 * This may also include entity specific data values.
315 * An array containing all custom groups and their custom fields is returned.
317 * @param string $entityType
318 * Of the contact whose contact type is needed.
319 * @param CRM_Core_Form $deprecated
321 * @param int $entityID
322 * @param int $groupID
323 * @param string $subType
324 * @param string $subName
325 * @param bool $fromCache
326 * @param bool $onlySubType
327 * Only return specified subtype or return specified subtype + unrestricted fields.
328 * @param bool $returnAll
329 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
330 * api - through which it is properly tested - so can be refactored with some comfort.)
332 * @param bool $checkPermission
335 * Custom field 'tree'.
337 * The returned array is keyed by group id and has the custom group table fields
338 * and a subkey 'fields' holding the specific custom fields.
339 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
340 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
342 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
343 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
344 * With caching the performance impact would be small & the function would be cleaner
346 public static function getTree(
356 $checkPermission = TRUE
359 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
363 $strSelect = $strFrom = $strWhere = $orderBy = '';
364 $tableData = array();
366 // using tableData to build the queryString
368 'civicrm_custom_field' => array(
388 'civicrm_custom_group' => array(
398 'extends_entity_column_id',
399 'extends_entity_column_value',
406 foreach ($tableData as $tableName => $tableColumn) {
407 foreach ($tableColumn as $columnName) {
408 $alias = $tableName . "_" . $columnName;
409 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
412 $strSelect = "SELECT " . implode(', ', $select);
414 // from, where, order by
416 FROM civicrm_custom_group
417 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
420 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
421 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
422 $entityType == 'Household'
424 $in = "'$entityType', 'Contact'";
426 elseif (strpos($entityType, "'") !== FALSE) {
427 // this allows the calling function to send in multiple entity types
432 $in = "'$entityType'";
437 if (is_array($subType)) {
438 $subType = implode(',', $subType);
440 if (strpos($subType, ',')) {
441 $subTypeParts = explode(',', $subType);
442 $subTypeClauses = array();
443 foreach ($subTypeParts as $subTypePart) {
444 // CRM-17984: Only filter by this input if valid.
445 $subTypePart = CRM_Utils_Type
::escape(trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
), 'Integer', FALSE);
447 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
.
449 CRM_Core_DAO
::VALUE_SEPARATOR
;
450 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
455 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
458 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) .
459 " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
463 // CRM-17984: Only filter by this input if valid.
464 $subType = CRM_Utils_Type
::escape(trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
), 'Integer', FALSE);
466 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
.
468 CRM_Core_DAO
::VALUE_SEPARATOR
;
471 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
474 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
475 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
480 if (empty($subTypeClause)) {
481 $subTypeClause = '1=1';
485 WHERE civicrm_custom_group.is_active = 1
486 AND civicrm_custom_field.is_active = 1
487 AND civicrm_custom_group.extends IN ($in)
491 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
496 WHERE civicrm_custom_group.is_active = 1
497 AND civicrm_custom_field.is_active = 1
498 AND civicrm_custom_group.extends IN ($in)
501 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
507 // since we want a specific group id we add it to the where clause
508 $strWhere .= " AND civicrm_custom_group.id = %1";
509 $params[1] = array($groupID, 'Integer');
512 // since groupID is false we need to show all Inline groups
513 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
515 if ($checkPermission) {
516 // ensure that the user has access to these custom groups
517 $strWhere .= " AND " .
518 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
519 'civicrm_custom_group.'
524 ORDER BY civicrm_custom_group.weight,
525 civicrm_custom_group.title,
526 civicrm_custom_field.weight,
527 civicrm_custom_field.label
530 // final query string
531 $queryString = "$strSelect $strFrom $strWhere $orderBy";
533 // lets see if we can retrieve the groupTree from cache
534 $cacheString = $queryString;
536 $cacheString .= "_{$groupID}";
539 $cacheString .= "_Inline";
542 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
543 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
544 $cache = CRM_Utils_Cache
::singleton();
545 $tablesWithEntityData = array();
547 $groupTree = $cache->get($cacheKey);
548 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
551 if (empty($groupTree)) {
552 $groupTree = $multipleFieldGroups = array();
553 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
554 $customValueTables = array();
557 while ($crmDAO->fetch()) {
559 $groupID = $crmDAO->civicrm_custom_group_id
;
560 $fieldId = $crmDAO->civicrm_custom_field_id
;
561 if ($crmDAO->civicrm_custom_group_is_multiple
) {
562 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
564 // create an array for groups if it does not exist
565 if (!array_key_exists($groupID, $groupTree)) {
566 $groupTree[$groupID] = array();
567 $groupTree[$groupID]['id'] = $groupID;
569 // populate the group information
570 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
571 $fullFieldName = "civicrm_custom_group_$fieldName";
572 if ($fieldName == 'id' ||
573 is_null($crmDAO->$fullFieldName)
578 if ($fieldName == 'extends_entity_column_value' && $subType) {
579 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
581 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
583 $groupTree[$groupID]['fields'] = array();
585 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
588 // add the fields now (note - the query row will always contain a field)
589 // we only reset this once, since multiple values come is as multiple rows
590 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
591 $groupTree[$groupID]['fields'][$fieldId] = array();
594 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
595 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
596 // populate information for a custom field
597 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
598 $fullFieldName = "civicrm_custom_field_$fieldName";
599 if ($fieldName == 'id' ||
600 is_null($crmDAO->$fullFieldName)
604 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
608 if (!empty($customValueTables)) {
609 $groupTree['info'] = array('tables' => $customValueTables);
612 $cache->set($cacheKey, $groupTree);
613 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
615 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
616 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
617 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
618 $singleFieldTables = array();
619 // now that we have all the groups and fields, lets get the values
620 // since we need to know the table and field names
621 // add info to groupTree
623 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
624 !empty($groupTree['info']['tables'])
626 $select = $from = $where = array();
627 $groupTree['info']['where'] = NULL;
629 foreach ($groupTree['info']['tables'] as $table => $fields) {
630 $groupTree['info']['from'][] = $table;
632 "{$table}.id as {$table}_id",
633 "{$table}.entity_id as {$table}_entity_id",
635 foreach ($fields as $column => $dontCare) {
636 $select[] = "{$table}.{$column} as {$table}_{$column}";
638 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
640 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
641 if (in_array($table, $multipleFieldGroups) &&
642 self
::customGroupDataExistsForEntity($entityID, $table)
644 $entityMultipleSelectClauses[$table] = $select;
647 $singleFieldTables[] = $table;
648 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
653 if ($entityID && !empty($singleFieldTables)) {
654 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
656 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
657 if (!empty($multipleFieldTablesWithEntityData)) {
658 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
666 * Check whether the custom group has any data for the given entity.
669 * @param int $entityID
670 * Id of entity for whom we are checking data for.
671 * @param string $table
672 * Table that we are checking.
674 * @param bool $getCount
677 * does this entity have data in this custom table
679 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
683 WHERE entity_id = $entityID
685 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
687 return $recordExists;
689 return $recordExists ?
TRUE : FALSE;
693 * Build the group tree for Custom fields which are not 'is_multiple'
695 * The combination of all these fields in one query with a 'using' join was not working for
696 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
697 * mechanism as it seemed to be acceptable in this context
699 * @param array $groupTree
700 * (reference) group tree array which is being built.
701 * @param int $entityID
702 * Id of entity for whom the tree is being build up.
703 * @param array $entitySingleSelectClauses
704 * Array of select clauses relevant to the entity.
705 * @param array $singleFieldTablesWithEntityData
706 * Array of tables in which this entity has data.
708 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
709 $select = implode(', ', $entitySingleSelectClauses);
710 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
711 foreach ($singleFieldTablesWithEntityData as $table) {
712 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
718 WHERE first.entity_id = $entityID
720 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
724 * Build the group tree for Custom fields which are 'is_multiple'
726 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
728 * @param array $groupTree
729 * (reference) group tree array which is being built.
730 * @param int $entityID
731 * Id of entity for whom the tree is being build up.
732 * @param array $entityMultipleSelectClauses
733 * Array of select clauses relevant to the entity.
734 * @param array $multipleFieldTablesWithEntityData
735 * Array of tables in which this entity has data.
737 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData) {
738 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
739 $select = implode(',', $selectClauses);
743 WHERE entity_id = $entityID
745 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
750 * Build the tree entity data - starting from a query retrieving the custom fields build the group
751 * tree data for the relevant entity (entity is included in the query).
753 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
755 * @param array $groupTree
756 * (reference) group tree array which is being built.
757 * @param string $query
758 * @param array $includedTables
759 * Tables to include - required because the function (for historical reasons).
760 * iterates through the group tree
762 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables) {
763 $dao = CRM_Core_DAO
::executeQuery($query);
764 while ($dao->fetch()) {
765 foreach ($groupTree as $groupID => $group) {
766 if ($groupID === 'info') {
769 $table = $groupTree[$groupID]['table_name'];
770 //working from the groupTree instead of the table list means we have to iterate & exclude.
771 // this could possibly be re-written as other parts of the function have been refactored
772 // for now we just check if the given table is to be included in this function
773 if (!in_array($table, $includedTables)) {
776 foreach ($group['fields'] as $fieldID => $dontCare) {
777 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
784 * Build the entity-specific custom data into the group tree on a per-field basis
787 * Object representing the custom field to be populated into the groupTree.
788 * @param array $groupTree
789 * (reference) the group tree being build.
790 * @param string $table
792 * @param int $groupID
794 * @param int $fieldID
797 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID) {
798 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
799 $idName = "{$table}_id";
800 $fieldName = "{$table}_{$column}";
801 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
802 if ($dataType == 'File') {
803 if (isset($dao->$fieldName)) {
804 $config = CRM_Core_Config
::singleton();
805 $fileDAO = new CRM_Core_DAO_File();
806 $fileDAO->id
= $dao->$fieldName;
808 if ($fileDAO->find(TRUE)) {
809 $entityIDName = "{$table}_entity_id";
810 $customValue['id'] = $dao->$idName;
811 $customValue['data'] = $fileDAO->uri
;
812 $customValue['fid'] = $fileDAO->id
;
813 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
814 $customValue['displayURL'] = NULL;
815 $deleteExtra = ts('Are you sure you want to delete attached file.');
817 CRM_Core_Action
::DELETE
=> array(
818 'name' => ts('Delete Attached File'),
819 'url' => 'civicrm/file',
820 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
821 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
822 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
825 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
826 CRM_Core_Action
::DELETE
,
828 'id' => $fileDAO->id
,
829 'eid' => $dao->$entityIDName,
834 'file.manage.delete',
838 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
839 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
840 if ($fileDAO->mime_type
== "image/jpeg" ||
841 $fileDAO->mime_type
== "image/pjpeg" ||
842 $fileDAO->mime_type
== "image/gif" ||
843 $fileDAO->mime_type
== "image/x-png" ||
844 $fileDAO->mime_type
== "image/png"
846 $customValue['displayURL'] = $customValue['fileURL'];
847 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
852 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
854 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId, NULL, NULL);
855 if ($path && file_exists($path)) {
856 list($imageWidth, $imageHeight) = getimagesize($path);
857 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
858 $customValue['imageThumbWidth'] = $imageThumbWidth;
859 $customValue['imageThumbHeight'] = $imageThumbHeight;
865 $customValue = array(
866 'id' => $dao->$idName,
872 $customValue = array(
873 'id' => $dao->$idName,
874 'data' => $dao->$fieldName,
878 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
879 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
881 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
882 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
885 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
890 * Get the group title.
898 public static function getTitle($id) {
899 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
903 * Get custom group details for a group.
905 * An array containing custom group details (including their custom field) is returned.
907 * @param int $groupId
908 * Group id whose details are needed.
909 * @param bool $searchable
910 * Is this field searchable.
911 * @param array $extends
912 * Which table does it extend if any.
914 * @param null $inSelector
917 * array consisting of all group and field details
919 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
921 $groupTree = array();
922 $select = $from = $where = $orderBy = '';
924 $tableData = array();
926 // using tableData to build the queryString
928 'civicrm_custom_field' => array(
952 'civicrm_custom_group' => array(
959 'collapse_adv_display',
961 'extends_entity_column_value',
970 foreach ($tableData as $tableName => $tableColumn) {
971 foreach ($tableColumn as $columnName) {
972 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
975 $select = 'SELECT ' . implode(', ', $s);
977 // from, where, order by
978 $from = " FROM civicrm_custom_field, civicrm_custom_group";
979 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
980 AND civicrm_custom_group.is_active = 1
981 AND civicrm_custom_field.is_active = 1 ";
983 $params[1] = array($groupId, 'Integer');
984 $where .= " AND civicrm_custom_group.id = %1";
988 $where .= " AND civicrm_custom_field.is_searchable = 1";
992 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
997 foreach ($extends as $e) {
998 $clause[] = "civicrm_custom_group.extends = '$e'";
1000 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1002 //include case activities customdata if case is enabled
1003 if (in_array('Activity', $extends)) {
1004 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1005 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1006 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
1010 // ensure that the user has access to these custom groups
1012 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1013 'civicrm_custom_group.'
1016 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1018 // final query string
1019 $queryString = $select . $from . $where . $orderBy;
1022 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1025 while ($crmDAO->fetch()) {
1026 $groupId = $crmDAO->civicrm_custom_group_id
;
1027 $fieldId = $crmDAO->civicrm_custom_field_id
;
1029 // create an array for groups if it does not exist
1030 if (!array_key_exists($groupId, $groupTree)) {
1031 $groupTree[$groupId] = array();
1032 $groupTree[$groupId]['id'] = $groupId;
1034 foreach ($tableData['civicrm_custom_group'] as $v) {
1035 $fullField = "civicrm_custom_group_" . $v;
1037 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1041 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1044 $groupTree[$groupId]['fields'] = array();
1047 // add the fields now (note - the query row will always contain a field)
1048 $groupTree[$groupId]['fields'][$fieldId] = array();
1049 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1051 foreach ($tableData['civicrm_custom_field'] as $v) {
1052 $fullField = "civicrm_custom_field_" . $v;
1053 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1056 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1064 * @param $entityType
1066 * @param string $cidToken
1070 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1072 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1074 // get 'Tab' and 'Tab with table' groups
1075 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1076 $customGroupDAO->whereAdd("is_active = 1");
1078 // add whereAdd for entity type
1079 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1083 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1084 $customGroupDAO->whereAdd($permissionClause);
1087 $customGroupDAO->orderBy('weight');
1088 $customGroupDAO->find();
1090 // process each group with menu tab
1091 while ($customGroupDAO->fetch()) {
1093 $group['id'] = $customGroupDAO->id
;
1094 $group['path'] = $path;
1095 $group['title'] = "$customGroupDAO->title";
1096 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1097 $group['extra'] = array('gid' => $customGroupDAO->id
);
1098 $group['table_name'] = $customGroupDAO->table_name
;
1099 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1107 * Get the table name for the entity type
1108 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1109 * tableName is 'civicrm_contact'
1111 * @param string $entityType
1112 * What entity are we extending here ?.
1117 * @see _apachesolr_civiAttachments_dereference_file_parent
1119 public static function getTableNameByEntityName($entityType) {
1121 switch ($entityType) {
1125 case 'Organization':
1126 $tableName = 'civicrm_contact';
1129 case 'Contribution':
1130 $tableName = 'civicrm_contribution';
1134 $tableName = 'civicrm_group';
1137 // DRAFTING: Verify if we cannot make it pluggable
1140 $tableName = 'civicrm_activity';
1143 case 'Relationship':
1144 $tableName = 'civicrm_relationship';
1148 $tableName = 'civicrm_membership';
1152 $tableName = 'civicrm_participant';
1156 $tableName = 'civicrm_event';
1160 $tableName = 'civicrm_grant';
1163 // need to add cases for Location, Address
1170 * Get a list of custom groups which extend a given entity type.
1171 * If there are custom-groups which only apply to certain subtypes,
1172 * those WILL be included.
1174 * @param string $entityType
1176 * @return CRM_Core_DAO_CustomGroup
1178 public static function getAllCustomGroupsByBaseEntity($entityType) {
1179 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1180 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1181 return $customGroupDAO;
1185 * Add the whereAdd clause for the DAO depending on the type of entity
1186 * the custom group is extending.
1188 * @param object $customGroupDAO
1189 * @param string $entityType
1190 * What entity are we extending here ?.
1192 * @param int $entityID
1193 * @param bool $allSubtypes
1195 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1196 $addSubtypeClause = FALSE;
1198 switch ($entityType) {
1200 // if contact, get all related to contact
1201 $extendList = "'Contact','Individual','Household','Organization'";
1202 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1203 if (!$allSubtypes) {
1204 $addSubtypeClause = TRUE;
1210 case 'Organization':
1211 // is I/H/O then get I/H/O and contact
1212 $extendList = "'Contact','$entityType'";
1213 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1214 if (!$allSubtypes) {
1215 $addSubtypeClause = TRUE;
1223 case 'Contribution':
1226 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1230 if ($addSubtypeClause) {
1231 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1233 if (!empty($csType)) {
1234 $subtypeClause = array();
1235 foreach ($csType as $subtype) {
1236 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1237 CRM_Core_DAO
::VALUE_SEPARATOR
;
1238 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1240 $subtypeClause[] = "extends_entity_column_value IS NULL";
1241 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1245 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1251 * Delete the Custom Group.
1253 * @param CRM_Core_BAO_CustomGroup $group
1254 * Custom group object.
1255 * @param bool $force
1256 * whether to force the deletion, even if there are custom fields.
1259 * False if field exists for this group, true if group gets deleted.
1261 public static function deleteGroup($group, $force = FALSE) {
1263 //check whether this contain any custom fields
1264 $customField = new CRM_Core_DAO_CustomField();
1265 $customField->custom_group_id
= $group->id
;
1266 $customField->find();
1268 // return early if there are custom fields and we're not
1269 // forcing the delete, otherwise delete the fields one by one
1270 while ($customField->fetch()) {
1274 CRM_Core_BAO_CustomField
::deleteField($customField);
1277 // drop the table associated with this custom group
1278 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1280 //delete custom group
1283 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1291 * @param array $groupTree
1292 * @param array $defaults
1293 * @param bool $viewMode
1294 * @param bool $inactiveNeeded
1295 * @param int $action
1297 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1298 foreach ($groupTree as $id => $group) {
1299 if (!isset($group['fields'])) {
1302 foreach ($group['fields'] as $field) {
1303 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1304 $value = $field['element_value'];
1306 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1307 ($action != CRM_Core_Action
::UPDATE ||
1309 !array_key_exists('element_value', $field)
1312 $value = $viewMode ?
NULL : $field['default_value'];
1318 if (empty($field['element_name'])) {
1322 $elementName = $field['element_name'];
1324 switch ($field['html_type']) {
1325 case 'Multi-Select':
1326 case 'AdvMulti-Select':
1328 $defaults[$elementName] = array();
1329 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1331 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1332 if (isset($value)) {
1333 foreach ($customOption as $customValue => $customLabel) {
1334 if (in_array($customValue, $checkedData)) {
1335 if ($field['html_type'] == 'CheckBox') {
1336 $defaults[$elementName][$customValue] = 1;
1339 $defaults[$elementName][$customValue] = $customValue;
1343 $defaults[$elementName][$customValue] = 0;
1349 if (isset($field['customValue']['data'])) {
1350 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1351 foreach ($customOption as $val) {
1352 if (in_array($val['value'], $checkedData)) {
1353 if ($field['html_type'] == 'CheckBox') {
1354 $defaults[$elementName][$val['value']] = 1;
1357 $defaults[$elementName][$val['value']] = $val['value'];
1361 $defaults[$elementName][$val['value']] = 0;
1366 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1367 foreach ($customOption as $val) {
1368 if (in_array($val['value'], $checkedValue)) {
1369 if ($field['html_type'] == 'CheckBox') {
1370 $defaults[$elementName][$val['value']] = 1;
1373 $defaults[$elementName][$val['value']] = $val['value'];
1381 case 'Multi-Select Country':
1382 case 'Multi-Select State/Province':
1383 if (isset($value)) {
1384 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1385 foreach ($checkedValue as $val) {
1387 $defaults[$elementName][$val] = $val;
1393 case 'Select Country':
1395 $defaults[$elementName] = $value;
1398 $config = CRM_Core_Config
::singleton();
1399 $defaults[$elementName] = $config->defaultContactCountry
;
1404 if ($field['data_type'] == "Float") {
1405 $defaults[$elementName] = (float) $value;
1407 elseif ($field['data_type'] == 'Money' &&
1408 $field['html_type'] == 'Text'
1410 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1413 $defaults[$elementName] = $value;
1421 * PostProcess function.
1423 * @param array $groupTree
1424 * @param array $params
1425 * @param bool $skipFile
1427 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1428 // Get the Custom form values and groupTree
1429 // first reset all checkbox and radio data
1430 foreach ($groupTree as $groupID => $group) {
1431 if ($groupID === 'info') {
1434 foreach ($group['fields'] as $field) {
1435 $fieldId = $field['id'];
1437 //added Multi-Select option in the below if-statement
1438 if ($field['html_type'] == 'CheckBox' ||
1439 $field['html_type'] == 'Radio' ||
1440 $field['html_type'] == 'AdvMulti-Select' ||
1441 $field['html_type'] == 'Multi-Select'
1443 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1447 foreach ($params as $key => $val) {
1448 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1449 $match[1] == $field['id']
1455 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1456 // field exists in db so populate value from "form".
1457 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1460 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1462 //added for CheckBox
1466 $customValue = array_keys($v);
1467 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1468 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1469 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1472 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1476 //added for Advanced Multi-Select
1478 case 'AdvMulti-Select':
1479 //added for Multi-Select
1480 case 'Multi-Select':
1482 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1483 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1484 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1487 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1492 $date = CRM_Utils_Date
::processDate($v);
1493 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1501 //store the file in d/b
1502 $entityId = explode('=', $groupTree['info']['where'][0]);
1503 $fileParams = array('upload_date' => date('Ymdhis'));
1505 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1506 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1509 $fileParams['uri'] = $v['name'];
1510 $fileParams['mime_type'] = $v['type'];
1511 CRM_Core_BAO_File
::filePostProcess($v['name'],
1512 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1513 $groupTree[$groupID]['table_name'],
1518 'custom_' . $fieldId,
1522 $defaults = array();
1523 $paramsFile = array(
1524 'entity_table' => $groupTree[$groupID]['table_name'],
1525 'entity_id' => $entityId[1],
1528 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1533 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1537 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1545 * Generic function to build all the form elements for a specific group tree.
1547 * @param CRM_Core_Form $form
1549 * @param array $groupTree
1550 * The group tree object.
1551 * @param bool $inactiveNeeded
1552 * Return inactive custom groups.
1553 * @param string $prefix
1554 * Prefix for custom grouptree assigned to template.
1556 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1557 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1559 foreach ($groupTree as $id => $group) {
1560 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1561 foreach ($group['fields'] as $field) {
1562 $required = CRM_Utils_Array
::value('is_required', $field);
1564 if ($field['data_type'] == 'File') {
1565 if (!empty($field['element_value']['data'])) {
1570 $fieldId = $field['id'];
1571 $elementName = $field['element_name'];
1572 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $required);
1578 * Extract the get params from the url, validate and store it in session.
1580 * @param CRM_Core_Form $form
1582 * @param string $type
1583 * The type of custom group we are using.
1587 public static function extractGetParams(&$form, $type) {
1592 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1593 $customValue = array();
1602 foreach ($groupTree as $group) {
1603 if (!isset($group['fields'])) {
1606 foreach ($group['fields'] as $key => $field) {
1607 $fieldName = 'custom_' . $key;
1608 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1612 if (!in_array($field['html_type'], $htmlType) ||
1613 $field['data_type'] == 'Boolean'
1615 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1617 if ($field['html_type'] == 'CheckBox' ||
1618 $field['html_type'] == 'AdvMulti-Select' ||
1619 $field['html_type'] == 'Multi-Select'
1621 $value = str_replace("|", ",", $value);
1622 $mulValues = explode(',', $value);
1623 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1625 foreach ($mulValues as $v1) {
1626 foreach ($customOption as $coID => $coValue) {
1627 if (strtolower(trim($coValue['label'])) ==
1628 strtolower(trim($v1))
1630 $val[$coValue['value']] = 1;
1642 elseif ($field['html_type'] == 'Select' ||
1643 ($field['html_type'] == 'Radio' &&
1644 $field['data_type'] != 'Boolean'
1647 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1648 foreach ($customOption as $customID => $coValue) {
1649 if (strtolower(trim($coValue['label'])) ==
1650 strtolower(trim($value))
1652 $value = $coValue['value'];
1657 elseif ($field['data_type'] == 'Date') {
1658 if (!empty($value)) {
1660 if (!empty($field['time_format'])) {
1661 $time = CRM_Utils_Request
::retrieve($fieldName .
1662 '_time', 'String', $form, FALSE, NULL, 'GET');
1664 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value .
1666 if (!empty($field['time_format'])) {
1667 $customValue[$fieldName . '_time'] = $time;
1674 $customValue[$fieldName] = $value;
1680 return $customValue;
1684 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1685 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1687 * @param int $customFieldId
1689 * @param array $removeCustomFieldTypes
1690 * Remove custom fields of a type eg: array("Individual") ;.
1693 * false if it matches else true
1695 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1696 $query = "SELECT cg.extends as extends
1697 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1698 WHERE cg.id = cf.custom_group_id
1700 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1702 $extends = CRM_Core_DAO
::singleValueQuery($query);
1704 if (in_array($extends, $removeCustomFieldTypes)) {
1716 public static function mapTableName($table) {
1721 case 'Organization':
1722 return 'civicrm_contact';
1725 return 'civicrm_activity';
1728 return 'civicrm_group';
1730 case 'Contribution':
1731 return 'civicrm_contribution';
1733 case 'ContributionRecur':
1734 return 'civicrm_contribution_recur';
1736 case 'Relationship':
1737 return 'civicrm_relationship';
1740 return 'civicrm_event';
1743 return 'civicrm_membership';
1746 case 'ParticipantRole':
1747 case 'ParticipantEventName':
1748 case 'ParticipantEventType':
1749 return 'civicrm_participant';
1752 return 'civicrm_grant';
1755 return 'civicrm_pledge';
1758 return 'civicrm_address';
1761 return 'civicrm_campaign';
1765 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1766 $qParams = array(1 => array($table, 'String'));
1767 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1770 return 'civicrm_contact';
1773 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1774 if (array_key_exists($table, $extendObjs)) {
1775 return $extendObjs[$table];
1777 CRM_Core_Error
::fatal();
1785 public static function createTable($group) {
1787 'name' => $group->table_name
,
1788 'is_multiple' => $group->is_multiple ?
1 : 0,
1789 'extends_name' => self
::mapTableName($group->extends),
1792 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1794 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1798 * Function returns formatted groupTree, sothat form can be easily build in template
1800 * @param array $groupTree
1801 * @param int $groupCount
1802 * Group count by default 1, but can varry for multiple value custom data.
1803 * @param object $form
1807 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1808 $formattedGroupTree = array();
1809 $uploadNames = array();
1811 foreach ($groupTree as $key => $value) {
1812 if ($key === 'info') {
1816 // add group information
1817 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1818 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1819 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1820 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1821 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1822 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1824 // this params needed of bulding multiple values
1825 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1826 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1827 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1828 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1829 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1830 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1832 // add field information
1833 foreach ($value['fields'] as $k => $properties) {
1834 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1835 if (isset($properties['customValue']) &&
1836 !CRM_Utils_System
::isNull($properties['customValue'])
1838 if (isset($properties['customValue'][$groupCount])) {
1839 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1840 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1841 if ($properties['data_type'] == 'File') {
1842 $properties['element_value'] = $properties['customValue'][$groupCount];
1843 $uploadNames[] = $properties['element_name'];
1846 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1850 unset($properties['customValue']);
1851 $formattedGroupTree[$key]['fields'][$k] = $properties;
1856 // hack for field type File
1857 $formUploadNames = $form->get('uploadNames');
1858 if (is_array($formUploadNames)) {
1859 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1862 $form->set('uploadNames', $uploadNames);
1865 return $formattedGroupTree;
1869 * Build custom data view.
1871 * @param CRM_Core_Form $form
1873 * @param array $groupTree
1874 * @param bool $returnCount
1875 * True if customValue count needs to be returned.
1877 * @param null $prefix
1878 * @param int $customValueId
1879 * @param int $entityId
1883 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
1885 foreach ($groupTree as $key => $group) {
1886 if ($key === 'info') {
1890 foreach ($group['fields'] as $k => $properties) {
1891 $groupID = $group['id'];
1892 if (!empty($properties['customValue'])) {
1893 foreach ($properties['customValue'] as $values) {
1894 if (!empty($customValueId) && $customValueId != $values['id']) {
1897 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1898 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1899 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1900 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1901 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1902 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1903 $details[$groupID][$values['id']]['fields'][$k] = array(
1904 'field_title' => CRM_Utils_Array
::value('label', $properties),
1905 'field_type' => CRM_Utils_Array
::value('html_type', $properties),
1906 'field_data_type' => CRM_Utils_Array
::value('data_type', $properties),
1907 'field_value' => CRM_Core_BAO_CustomField
::displayValue($values['data'], $properties['id'], $entityId),
1908 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $properties),
1910 // also return contact reference contact id if user has view all or edit all contacts perm
1911 if ((CRM_Core_Permission
::check('view all contacts') ||
1912 CRM_Core_Permission
::check('edit all contacts'))
1914 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1917 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1922 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1923 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1924 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1925 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1926 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1927 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1928 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1934 //return a single value count if group id is passed to function
1935 //else return a groupId and count mapped array
1937 return count($details[$gID]);
1940 $countValue = array();
1941 foreach ($details as $key => $value) {
1942 $countValue[$key] = count($details[$key]);
1948 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1954 * Get the custom group titles by custom field ids.
1956 * @param array $fieldIds
1957 * Array of custom field ids.
1959 * @return array|NULL
1960 * array consisting of groups and fields labels with ids.
1962 public static function getGroupTitles($fieldIds) {
1963 if (!is_array($fieldIds) && empty($fieldIds)) {
1967 $groupLabels = array();
1968 $fIds = "(" . implode(',', $fieldIds) . ")";
1971 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
1972 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
1973 FROM civicrm_custom_group, civicrm_custom_field
1974 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
1975 AND civicrm_custom_field.id IN {$fIds}";
1977 $dao = CRM_Core_DAO
::executeQuery($query);
1978 while ($dao->fetch()) {
1979 $groupLabels[$dao->fieldID
] = array(
1980 'fieldID' => $dao->fieldID
,
1981 'fieldLabel' => $dao->fieldLabel
,
1982 'groupID' => $dao->groupID
,
1983 'groupTitle' => $dao->groupTitle
,
1987 return $groupLabels;
1990 public static function dropAllTables() {
1991 $query = "SELECT table_name FROM civicrm_custom_group";
1992 $dao = CRM_Core_DAO
::executeQuery($query);
1994 while ($dao->fetch()) {
1995 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
1996 CRM_Core_DAO
::executeQuery($query);
2001 * Check whether custom group is empty or not.
2007 * true if empty otherwise false.
2009 public static function isGroupEmpty($gID) {
2014 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2019 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2020 $value = CRM_Core_DAO
::singleValueQuery($query);
2022 if (empty($value)) {
2030 * Get the list of types for objects that a custom group extends to.
2032 * @param array $types
2033 * Var which should have the list appended.
2038 public static function getExtendedObjectTypes(&$types = array()) {
2039 static $flag = FALSE, $objTypes = array();
2042 $extendObjs = array();
2043 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2045 foreach ($extendObjs as $ovId => $ovValues) {
2046 if ($ovValues['description']) {
2047 // description is expected to be a callback func to subtypes
2048 list($callback, $args) = explode(';', trim($ovValues['description']));
2054 if (!is_array($args)) {
2055 CRM_Core_Error
::fatal('Arg is not of type array');
2058 list($className) = explode('::', $callback);
2059 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2062 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2068 $types = array_merge($types, $objTypes);
2073 * @param int $customGroupId
2074 * @param int $entityId
2078 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2079 //check whether the group is multiple
2080 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2081 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2082 $hasReachedMax = FALSE;
2084 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2086 if (!$maxMultiple) {
2087 $hasReachedMax = FALSE;
2090 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2091 //count the number of entries for a entity
2092 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2093 $params = array(1 => array($entityId, 'Integer'));
2094 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2096 if ($count >= $maxMultiple) {
2097 $hasReachedMax = TRUE;
2101 return $hasReachedMax;
2107 public static function getMultipleFieldGroup() {
2108 $multipleGroup = array();
2109 $dao = new CRM_Core_DAO_CustomGroup();
2110 $dao->is_multiple
= 1;
2112 while ($dao->fetch()) {
2113 $multipleGroup[$dao->id
] = $dao->title
;
2115 return $multipleGroup;