3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 $current_db_version = CRM_Core_DAO
::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config
::domainID());
126 $is_public_version = $current_db_version >= '4.7.19' ?
1 : 0;
127 if ($is_public_version) {
128 $fields[] = 'is_public';
130 foreach ($fields as $field) {
131 if (isset($params[$field]) ||
$field == 'is_multiple') {
132 $group->$field = CRM_Utils_Array
::value($field, $params, FALSE);
135 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
136 $params['max_multiple'] >= '0'
137 ) ?
$params['max_multiple'] : 'null' : 'null';
139 $tableName = $oldTableName = NULL;
140 if (isset($params['id'])) {
141 $group->id
= $params['id'];
142 //check whether custom group was changed from single-valued to multiple-valued
143 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
148 if ((!empty($params['is_multiple']) ||
$isMultiple) &&
149 ($params['is_multiple'] != $isMultiple)
151 $oldTableName = CRM_Core_DAO
::getFieldValue(
152 'CRM_Core_DAO_CustomGroup',
159 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
160 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
162 // we do this only once, so name never changes
163 if (isset($params['name'])) {
164 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
167 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
170 if (isset($params['table_name'])) {
171 $tableName = $params['table_name'];
173 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
174 // Bad idea. Prevent group creation because it might lead to a broken configuration.
175 CRM_Core_Error
::fatal(ts("Cannot create custom table because %1 is already a core table.", array('1' => $tableName)));
180 if (array_key_exists('is_reserved', $params)) {
181 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
183 $op = isset($params['id']) ?
'edit' : 'create';
184 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
186 // enclose the below in a transaction
187 $transaction = new CRM_Core_Transaction();
190 if (!isset($params['id'])) {
191 if (!isset($params['table_name'])) {
192 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 13));
193 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
195 $group->table_name
= $tableName;
196 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
202 // now create the table associated with this group
203 self
::createTable($group);
205 elseif ($oldTableName) {
206 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($oldTableName, CRM_Utils_Array
::value('is_multiple', $params));
209 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
210 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
214 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends'][0]));
216 $transaction->commit();
219 CRM_Utils_System
::flushCache();
222 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
225 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
232 * Fetch object based on array of properties.
234 * @param array $params
235 * (reference ) an assoc array of name/value pairs.
236 * @param array $defaults
237 * (reference ) an assoc array to hold the flattened values.
239 * @return CRM_Core_DAO_CustomGroup
241 public static function retrieve(&$params, &$defaults) {
242 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
246 * Update the is_active flag in the db.
249 * Id of the database record.
250 * @param bool $is_active
251 * Value we want to set the is_active field.
254 * DAO object on success, null otherwise
256 public static function setIsActive($id, $is_active) {
258 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
261 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
264 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
268 * Determine if given entity (sub)type has any custom groups
270 * @param string $extends
271 * E.g. "Individual", "Activity".
272 * @param int $columnId
273 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
274 * @param string $columnValue
275 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
279 public static function hasCustomGroup($extends, $columnId, $columnValue) {
280 $dao = new CRM_Core_DAO_CustomGroup();
281 $dao->extends = $extends;
282 $dao->extends_entity_column_id
= $columnId;
283 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
284 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
285 //$dao->extends_entity_column_value = $columnValue;
286 return $dao->find() ?
TRUE : FALSE;
290 * Determine if there are any CustomGroups for the given $activityTypeId.
291 * If none found, create one.
293 * @param int $activityTypeId
296 * TRUE if a group is found or created; FALSE on error
298 public static function autoCreateByActivityType($activityTypeId) {
299 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
302 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
305 'extends' => 'Activity',
306 'extends_entity_column_id' => NULL,
307 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
308 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
312 $result = civicrm_api('CustomGroup', 'create', $params);
313 return !$result['is_error'];
317 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
318 * This may also include entity specific data values.
320 * An array containing all custom groups and their custom fields is returned.
322 * @param string $entityType
323 * Of the contact whose contact type is needed.
324 * @param array $toReturn
325 * What data should be returned. ['custom_group' => ['id', 'name', etc.], 'custom_field' => ['id', 'label', etc.]]
326 * @param int $entityID
327 * @param int $groupID
328 * @param array $subTypes
329 * @param string $subName
330 * @param bool $fromCache
331 * @param bool $onlySubType
332 * Only return specified subtype or return specified subtype + unrestricted fields.
333 * @param bool $returnAll
334 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
335 * api - through which it is properly tested - so can be refactored with some comfort.)
337 * @param bool $checkPermission
338 * @param string|int $singleRecord
339 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
340 * @param bool $showPublicOnly
343 * Custom field 'tree'.
345 * The returned array is keyed by group id and has the custom group table fields
346 * and a subkey 'fields' holding the specific custom fields.
347 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
348 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
350 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
351 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
352 * With caching the performance impact would be small & the function would be cleaner
354 public static function getTree(
364 $checkPermission = TRUE,
365 $singleRecord = NULL,
366 $showPublicOnly = FALSE
369 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
371 if (!is_array($subTypes)) {
372 if (empty($subTypes)) {
376 if (stristr($subTypes, ',')) {
377 $subTypes = explode(',', $subTypes);
380 $subTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subTypes, CRM_Core_DAO
::VALUE_SEPARATOR
));
386 $strWhere = $orderBy = '';
388 // legacy hardcoded list of data to return
390 'custom_field' => array(
411 'custom_group' => array(
422 'extends_entity_column_id',
423 'extends_entity_column_value',
427 $current_db_version = CRM_Core_DAO
::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config
::domainID());
428 $is_public_version = $current_db_version >= '4.7.19' ?
1 : 0;
429 if ($is_public_version) {
430 $tableData['custom_group'][] = 'is_public';
432 if (!$toReturn ||
!is_array($toReturn)) {
433 $toReturn = $tableData;
436 // Supply defaults and remove unknown array keys
437 $toReturn = array_intersect_key(array_filter($toReturn) +
$tableData, $tableData);
438 // Merge in required fields that we must have
439 $toReturn['custom_field'] = array_unique(array_merge($toReturn['custom_field'], array('id', 'column_name', 'data_type')));
440 $toReturn['custom_group'] = array_unique(array_merge($toReturn['custom_group'], array('id', 'is_multiple', 'table_name', 'name')));
441 // Validate return fields
442 $toReturn['custom_field'] = array_intersect($toReturn['custom_field'], array_keys(CRM_Core_DAO_CustomField
::fieldKeys()));
443 $toReturn['custom_group'] = array_intersect($toReturn['custom_group'], array_keys(CRM_Core_DAO_CustomGroup
::fieldKeys()));
448 foreach ($toReturn as $tableName => $tableColumn) {
449 foreach ($tableColumn as $columnName) {
450 $select[] = "civicrm_{$tableName}.{$columnName} as civicrm_{$tableName}_{$columnName}";
453 $strSelect = "SELECT " . implode(', ', $select);
455 // from, where, order by
457 FROM civicrm_custom_group
458 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
461 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
462 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
463 $entityType == 'Household'
465 $in = "'$entityType', 'Contact'";
467 elseif (strpos($entityType, "'") !== FALSE) {
468 // this allows the calling function to send in multiple entity types
473 $in = "'$entityType'";
476 if (!empty($subTypes)) {
477 foreach ($subTypes as $key => $subType) {
478 $subTypeClauses[] = self
::whereListHas("civicrm_custom_group.extends_entity_column_value", self
::validateSubTypeByEntity($entityType, $subType));
480 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
482 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
486 WHERE civicrm_custom_group.is_active = 1
487 AND civicrm_custom_field.is_active = 1
488 AND civicrm_custom_group.extends IN ($in)
492 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
497 WHERE civicrm_custom_group.is_active = 1
498 AND civicrm_custom_field.is_active = 1
499 AND civicrm_custom_group.extends IN ($in)
502 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
508 // since we want a specific group id we add it to the where clause
509 $strWhere .= " AND civicrm_custom_group.id = %1";
510 $params[1] = array($groupID, 'Integer');
513 // since groupID is false we need to show all Inline groups
514 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
516 if ($checkPermission) {
517 // ensure that the user has access to these custom groups
518 $strWhere .= " AND " .
519 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
520 'civicrm_custom_group.'
524 if ($showPublicOnly && $is_public_version) {
525 $strWhere .= "AND civicrm_custom_group.is_public = 1";
529 ORDER BY civicrm_custom_group.weight,
530 civicrm_custom_group.title,
531 civicrm_custom_field.weight,
532 civicrm_custom_field.label
535 // final query string
536 $queryString = "$strSelect $strFrom $strWhere $orderBy";
538 // lets see if we can retrieve the groupTree from cache
539 $cacheString = $queryString;
541 $cacheString .= "_{$groupID}";
544 $cacheString .= "_Inline";
547 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
548 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
549 $cache = CRM_Utils_Cache
::singleton();
550 $tablesWithEntityData = array();
552 $groupTree = $cache->get($cacheKey);
553 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
556 if (empty($groupTree)) {
557 $groupTree = $multipleFieldGroups = array();
558 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
559 $customValueTables = array();
562 while ($crmDAO->fetch()) {
564 $groupID = $crmDAO->civicrm_custom_group_id
;
565 $fieldId = $crmDAO->civicrm_custom_field_id
;
566 if ($crmDAO->civicrm_custom_group_is_multiple
) {
567 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
569 // create an array for groups if it does not exist
570 if (!array_key_exists($groupID, $groupTree)) {
571 $groupTree[$groupID] = array();
572 $groupTree[$groupID]['id'] = $groupID;
574 // populate the group information
575 foreach ($toReturn['custom_group'] as $fieldName) {
576 $fullFieldName = "civicrm_custom_group_$fieldName";
577 if ($fieldName == 'id' ||
578 is_null($crmDAO->$fullFieldName)
583 // This is an old bit of code - per the CRM number & probably does not work reliably if
584 // that one contact sub-type exists.
585 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
586 $groupTree[$groupID]['subtype'] = self
::validateSubTypeByEntity($entityType, $subType);
588 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
590 $groupTree[$groupID]['fields'] = array();
592 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
595 // add the fields now (note - the query row will always contain a field)
596 // we only reset this once, since multiple values come is as multiple rows
597 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
598 $groupTree[$groupID]['fields'][$fieldId] = array();
601 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
602 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
603 // populate information for a custom field
604 foreach ($toReturn['custom_field'] as $fieldName) {
605 $fullFieldName = "civicrm_custom_field_$fieldName";
606 if ($fieldName == 'id' ||
607 is_null($crmDAO->$fullFieldName)
611 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
615 if (!empty($customValueTables)) {
616 $groupTree['info'] = array('tables' => $customValueTables);
619 $cache->set($cacheKey, $groupTree);
620 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
622 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
623 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
624 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
625 $singleFieldTables = array();
626 // now that we have all the groups and fields, lets get the values
627 // since we need to know the table and field names
628 // add info to groupTree
630 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
631 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
633 $select = $from = $where = array();
634 $groupTree['info']['where'] = NULL;
636 foreach ($groupTree['info']['tables'] as $table => $fields) {
637 $groupTree['info']['from'][] = $table;
639 "{$table}.id as {$table}_id",
640 "{$table}.entity_id as {$table}_entity_id",
642 foreach ($fields as $column => $dontCare) {
643 $select[] = "{$table}.{$column} as {$table}_{$column}";
645 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
647 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
648 if (in_array($table, $multipleFieldGroups) &&
649 self
::customGroupDataExistsForEntity($entityID, $table)
651 $entityMultipleSelectClauses[$table] = $select;
654 $singleFieldTables[] = $table;
655 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
660 if ($entityID && !empty($singleFieldTables)) {
661 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
663 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
664 if (!empty($multipleFieldTablesWithEntityData)) {
665 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
673 * Clean and validate the filter before it is used in a db query.
675 * @param string $entityType
676 * @param string $subType
679 * @throws \CRM_Core_Exception
680 * @throws \CiviCRM_API3_Exception
682 protected static function validateSubTypeByEntity($entityType, $subType) {
683 $subType = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
684 if (is_numeric($subType)) {
688 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypeInfo(TRUE);
689 $contactTypes = array_merge($contactTypes, array('Event' => 1));
691 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
692 throw new CRM_Core_Exception('Invalid Entity Filter');
694 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo($entityType, TRUE);
695 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant
::eventType());
696 if (!array_key_exists($subType, $subTypes)) {
697 throw new CRM_Core_Exception('Invalid Filter');
703 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
704 * a WHERE condition for rows that include $value. Use whereListHas().
706 * @param string $column
707 * @param string $value
708 * @param string $delimiter
712 static private function whereListHas($column, $value, $delimiter = CRM_Core_DAO
::VALUE_SEPARATOR
) {
713 $bareValue = trim($value, $delimiter); // ?
714 $escapedValue = CRM_Utils_Type
::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
715 return "($column LIKE \"$escapedValue\")";
719 * Check whether the custom group has any data for the given entity.
722 * @param int $entityID
723 * Id of entity for whom we are checking data for.
724 * @param string $table
725 * Table that we are checking.
727 * @param bool $getCount
730 * does this entity have data in this custom table
732 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
736 WHERE entity_id = $entityID
738 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
740 return $recordExists;
742 return $recordExists ?
TRUE : FALSE;
746 * Build the group tree for Custom fields which are not 'is_multiple'
748 * The combination of all these fields in one query with a 'using' join was not working for
749 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
750 * mechanism as it seemed to be acceptable in this context
752 * @param array $groupTree
753 * (reference) group tree array which is being built.
754 * @param int $entityID
755 * Id of entity for whom the tree is being build up.
756 * @param array $entitySingleSelectClauses
757 * Array of select clauses relevant to the entity.
758 * @param array $singleFieldTablesWithEntityData
759 * Array of tables in which this entity has data.
761 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
762 $select = implode(', ', $entitySingleSelectClauses);
763 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
764 foreach ($singleFieldTablesWithEntityData as $table) {
765 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
771 WHERE first.entity_id = $entityID
773 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
777 * Build the group tree for Custom fields which are 'is_multiple'
779 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
781 * @param array $groupTree
782 * (reference) group tree array which is being built.
783 * @param int $entityID
784 * Id of entity for whom the tree is being build up.
785 * @param array $entityMultipleSelectClauses
786 * Array of select clauses relevant to the entity.
787 * @param array $multipleFieldTablesWithEntityData
788 * Array of tables in which this entity has data.
789 * @param varchar $singleRecord
790 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
792 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
793 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
794 $select = implode(',', $selectClauses);
798 WHERE entity_id = $entityID
801 $offset = $singleRecord - 1;
802 $query .= " LIMIT {$offset}, 1";
804 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table), $singleRecord);
809 * Build the tree entity data - starting from a query retrieving the custom fields build the group
810 * tree data for the relevant entity (entity is included in the query).
812 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
814 * @param array $groupTree
815 * (reference) group tree array which is being built.
816 * @param string $query
817 * @param array $includedTables
818 * Tables to include - required because the function (for historical reasons).
819 * iterates through the group tree
820 * @param varchar $singleRecord
821 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
823 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
824 $dao = CRM_Core_DAO
::executeQuery($query);
825 while ($dao->fetch()) {
826 foreach ($groupTree as $groupID => $group) {
827 if ($groupID === 'info') {
830 $table = $groupTree[$groupID]['table_name'];
831 //working from the groupTree instead of the table list means we have to iterate & exclude.
832 // this could possibly be re-written as other parts of the function have been refactored
833 // for now we just check if the given table is to be included in this function
834 if (!in_array($table, $includedTables)) {
837 foreach ($group['fields'] as $fieldID => $dontCare) {
838 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
845 * Build the entity-specific custom data into the group tree on a per-field basis
848 * Object representing the custom field to be populated into the groupTree.
849 * @param array $groupTree
850 * (reference) the group tree being build.
851 * @param string $table
853 * @param int $groupID
855 * @param int $fieldID
857 * @param varchar $singleRecord
858 * holds 'new' or id if loading view/edit/copy for a single record.
860 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
861 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
862 $idName = "{$table}_id";
863 $fieldName = "{$table}_{$column}";
864 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
865 if ($dataType == 'File') {
866 if (isset($dao->$fieldName)) {
867 $config = CRM_Core_Config
::singleton();
868 $fileDAO = new CRM_Core_DAO_File();
869 $fileDAO->id
= $dao->$fieldName;
871 if ($fileDAO->find(TRUE)) {
872 $entityIDName = "{$table}_entity_id";
873 $customValue['id'] = $dao->$idName;
874 $customValue['data'] = $fileDAO->uri
;
875 $customValue['fid'] = $fileDAO->id
;
876 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
877 $customValue['displayURL'] = NULL;
878 $deleteExtra = ts('Are you sure you want to delete attached file.');
880 CRM_Core_Action
::DELETE
=> array(
881 'name' => ts('Delete Attached File'),
882 'url' => 'civicrm/file',
883 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
884 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
885 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
888 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
889 CRM_Core_Action
::DELETE
,
891 'id' => $fileDAO->id
,
892 'eid' => $dao->$entityIDName,
897 'file.manage.delete',
901 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
902 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
903 if ($fileDAO->mime_type
== "image/jpeg" ||
904 $fileDAO->mime_type
== "image/pjpeg" ||
905 $fileDAO->mime_type
== "image/gif" ||
906 $fileDAO->mime_type
== "image/x-png" ||
907 $fileDAO->mime_type
== "image/png"
909 $customValue['displayURL'] = $customValue['fileURL'];
910 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
915 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
917 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId, NULL, NULL);
918 if ($path && file_exists($path)) {
919 list($imageWidth, $imageHeight) = getimagesize($path);
920 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
921 $customValue['imageThumbWidth'] = $imageThumbWidth;
922 $customValue['imageThumbHeight'] = $imageThumbHeight;
928 $customValue = array(
929 'id' => $dao->$idName,
935 $customValue = array(
936 'id' => $dao->$idName,
937 'data' => $dao->$fieldName,
941 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
942 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
944 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
945 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array($singleRecord => $customValue);
947 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
948 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
951 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
956 * Get the group title.
964 public static function getTitle($id) {
965 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
969 * Get custom group details for a group.
971 * An array containing custom group details (including their custom field) is returned.
973 * @param int $groupId
974 * Group id whose details are needed.
975 * @param bool $searchable
976 * Is this field searchable.
977 * @param array $extends
978 * Which table does it extend if any.
980 * @param null $inSelector
983 * array consisting of all group and field details
985 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
987 $groupTree = array();
988 $select = $from = $where = $orderBy = '';
990 $tableData = array();
992 // using tableData to build the queryString
994 'civicrm_custom_field' => array(
1018 'civicrm_custom_group' => array(
1025 'collapse_adv_display',
1027 'extends_entity_column_value',
1035 foreach ($tableData as $tableName => $tableColumn) {
1036 foreach ($tableColumn as $columnName) {
1037 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
1040 $select = 'SELECT ' . implode(', ', $s);
1042 // from, where, order by
1043 $from = " FROM civicrm_custom_field, civicrm_custom_group";
1044 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
1045 AND civicrm_custom_group.is_active = 1
1046 AND civicrm_custom_field.is_active = 1 ";
1048 $params[1] = array($groupId, 'Integer');
1049 $where .= " AND civicrm_custom_group.id = %1";
1053 $where .= " AND civicrm_custom_field.is_searchable = 1";
1057 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
1062 foreach ($extends as $e) {
1063 $clause[] = "civicrm_custom_group.extends = '$e'";
1065 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1067 //include case activities customdata if case is enabled
1068 if (in_array('Activity', $extends)) {
1069 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1070 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1071 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
1075 // ensure that the user has access to these custom groups
1077 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1078 'civicrm_custom_group.'
1081 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1083 // final query string
1084 $queryString = $select . $from . $where . $orderBy;
1087 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1090 while ($crmDAO->fetch()) {
1091 $groupId = $crmDAO->civicrm_custom_group_id
;
1092 $fieldId = $crmDAO->civicrm_custom_field_id
;
1094 // create an array for groups if it does not exist
1095 if (!array_key_exists($groupId, $groupTree)) {
1096 $groupTree[$groupId] = array();
1097 $groupTree[$groupId]['id'] = $groupId;
1099 foreach ($tableData['civicrm_custom_group'] as $v) {
1100 $fullField = "civicrm_custom_group_" . $v;
1102 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1106 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1109 $groupTree[$groupId]['fields'] = array();
1112 // add the fields now (note - the query row will always contain a field)
1113 $groupTree[$groupId]['fields'][$fieldId] = array();
1114 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1116 foreach ($tableData['civicrm_custom_field'] as $v) {
1117 $fullField = "civicrm_custom_field_" . $v;
1118 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1121 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1129 * @param $entityType
1131 * @param string $cidToken
1135 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1137 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1139 // get 'Tab' and 'Tab with table' groups
1140 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1141 $customGroupDAO->whereAdd("is_active = 1");
1143 // add whereAdd for entity type
1144 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1148 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1149 $customGroupDAO->whereAdd($permissionClause);
1152 $customGroupDAO->orderBy('weight');
1153 $customGroupDAO->find();
1155 // process each group with menu tab
1156 while ($customGroupDAO->fetch()) {
1158 $group['id'] = $customGroupDAO->id
;
1159 $group['path'] = $path;
1160 $group['title'] = "$customGroupDAO->title";
1161 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1162 $group['extra'] = array('gid' => $customGroupDAO->id
);
1163 $group['table_name'] = $customGroupDAO->table_name
;
1164 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1172 * Get the table name for the entity type
1173 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1174 * tableName is 'civicrm_contact'
1176 * @param string $entityType
1177 * What entity are we extending here ?.
1182 * @see _apachesolr_civiAttachments_dereference_file_parent
1184 public static function getTableNameByEntityName($entityType) {
1186 switch ($entityType) {
1190 case 'Organization':
1191 $tableName = 'civicrm_contact';
1194 case 'Contribution':
1195 $tableName = 'civicrm_contribution';
1199 $tableName = 'civicrm_group';
1202 // DRAFTING: Verify if we cannot make it pluggable
1205 $tableName = 'civicrm_activity';
1208 case 'Relationship':
1209 $tableName = 'civicrm_relationship';
1213 $tableName = 'civicrm_membership';
1217 $tableName = 'civicrm_participant';
1221 $tableName = 'civicrm_event';
1225 $tableName = 'civicrm_grant';
1228 // need to add cases for Location, Address
1235 * Get a list of custom groups which extend a given entity type.
1236 * If there are custom-groups which only apply to certain subtypes,
1237 * those WILL be included.
1239 * @param string $entityType
1241 * @return CRM_Core_DAO_CustomGroup
1243 public static function getAllCustomGroupsByBaseEntity($entityType) {
1244 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1245 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1246 return $customGroupDAO;
1250 * Add the whereAdd clause for the DAO depending on the type of entity
1251 * the custom group is extending.
1253 * @param object $customGroupDAO
1254 * @param string $entityType
1255 * What entity are we extending here ?.
1257 * @param int $entityID
1258 * @param bool $allSubtypes
1260 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1261 $addSubtypeClause = FALSE;
1263 switch ($entityType) {
1265 // if contact, get all related to contact
1266 $extendList = "'Contact','Individual','Household','Organization'";
1267 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1268 if (!$allSubtypes) {
1269 $addSubtypeClause = TRUE;
1275 case 'Organization':
1276 // is I/H/O then get I/H/O and contact
1277 $extendList = "'Contact','$entityType'";
1278 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1279 if (!$allSubtypes) {
1280 $addSubtypeClause = TRUE;
1288 case 'Contribution':
1291 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1295 if ($addSubtypeClause) {
1296 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1298 if (!empty($csType)) {
1299 $subtypeClause = array();
1300 foreach ($csType as $subtype) {
1301 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1302 CRM_Core_DAO
::VALUE_SEPARATOR
;
1303 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1305 $subtypeClause[] = "extends_entity_column_value IS NULL";
1306 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1310 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1316 * Delete the Custom Group.
1318 * @param CRM_Core_BAO_CustomGroup $group
1319 * Custom group object.
1320 * @param bool $force
1321 * whether to force the deletion, even if there are custom fields.
1324 * False if field exists for this group, true if group gets deleted.
1326 public static function deleteGroup($group, $force = FALSE) {
1328 //check whether this contain any custom fields
1329 $customField = new CRM_Core_DAO_CustomField();
1330 $customField->custom_group_id
= $group->id
;
1331 $customField->find();
1333 // return early if there are custom fields and we're not
1334 // forcing the delete, otherwise delete the fields one by one
1335 while ($customField->fetch()) {
1339 CRM_Core_BAO_CustomField
::deleteField($customField);
1342 // drop the table associated with this custom group
1343 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1345 //delete custom group
1348 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1356 * @param array $groupTree
1357 * @param array $defaults
1358 * @param bool $viewMode
1359 * @param bool $inactiveNeeded
1360 * @param int $action
1362 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1363 foreach ($groupTree as $id => $group) {
1364 if (!isset($group['fields'])) {
1367 foreach ($group['fields'] as $field) {
1368 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1369 $value = $field['element_value'];
1371 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1372 ($action != CRM_Core_Action
::UPDATE ||
1374 !array_key_exists('element_value', $field)
1377 $value = $viewMode ?
NULL : $field['default_value'];
1383 if (empty($field['element_name'])) {
1387 $elementName = $field['element_name'];
1389 switch ($field['html_type']) {
1390 case 'Multi-Select':
1391 case 'AdvMulti-Select':
1393 $defaults[$elementName] = array();
1394 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1396 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1397 if (isset($value)) {
1398 foreach ($customOption as $customValue => $customLabel) {
1399 if (in_array($customValue, $checkedData)) {
1400 if ($field['html_type'] == 'CheckBox') {
1401 $defaults[$elementName][$customValue] = 1;
1404 $defaults[$elementName][$customValue] = $customValue;
1408 $defaults[$elementName][$customValue] = 0;
1414 if (isset($field['customValue']['data'])) {
1415 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1416 foreach ($customOption as $val) {
1417 if (in_array($val['value'], $checkedData)) {
1418 if ($field['html_type'] == 'CheckBox') {
1419 $defaults[$elementName][$val['value']] = 1;
1422 $defaults[$elementName][$val['value']] = $val['value'];
1426 $defaults[$elementName][$val['value']] = 0;
1431 if (is_array($value) && count($value)) {
1432 CRM_Utils_Array
::formatArrayKeys($value);
1433 $checkedValue = $value;
1436 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1438 foreach ($customOption as $val) {
1439 if (in_array($val['value'], $checkedValue)) {
1440 if ($field['html_type'] == 'CheckBox') {
1441 $defaults[$elementName][$val['value']] = 1;
1444 $defaults[$elementName][$val['value']] = $val['value'];
1452 case 'Multi-Select Country':
1453 case 'Multi-Select State/Province':
1454 if (isset($value)) {
1455 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1456 foreach ($checkedValue as $val) {
1458 $defaults[$elementName][$val] = $val;
1464 case 'Select Country':
1466 $defaults[$elementName] = $value;
1469 $config = CRM_Core_Config
::singleton();
1470 $defaults[$elementName] = $config->defaultContactCountry
;
1475 if ($field['data_type'] == "Float") {
1476 $defaults[$elementName] = (float) $value;
1478 elseif ($field['data_type'] == 'Money' &&
1479 $field['html_type'] == 'Text'
1481 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1484 $defaults[$elementName] = $value;
1492 * PostProcess function.
1494 * @param array $groupTree
1495 * @param array $params
1496 * @param bool $skipFile
1498 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1499 // Get the Custom form values and groupTree
1500 // first reset all checkbox and radio data
1501 foreach ($groupTree as $groupID => $group) {
1502 if ($groupID === 'info') {
1505 foreach ($group['fields'] as $field) {
1506 $fieldId = $field['id'];
1508 //added Multi-Select option in the below if-statement
1509 if ($field['html_type'] == 'CheckBox' ||
1510 $field['html_type'] == 'Radio' ||
1511 $field['html_type'] == 'AdvMulti-Select' ||
1512 $field['html_type'] == 'Multi-Select'
1514 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1518 foreach ($params as $key => $val) {
1519 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1520 $match[1] == $field['id']
1526 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1527 // field exists in db so populate value from "form".
1528 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1531 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1533 //added for CheckBox
1537 $customValue = array_keys($v);
1538 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1539 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1540 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1543 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1547 //added for Advanced Multi-Select
1549 case 'AdvMulti-Select':
1550 //added for Multi-Select
1551 case 'Multi-Select':
1553 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1554 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1555 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1558 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1563 $date = CRM_Utils_Date
::processDate($v);
1564 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1572 //store the file in d/b
1573 $entityId = explode('=', $groupTree['info']['where'][0]);
1574 $fileParams = array('upload_date' => date('YmdHis'));
1576 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1577 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1580 $fileParams['uri'] = $v['name'];
1581 $fileParams['mime_type'] = $v['type'];
1582 CRM_Core_BAO_File
::filePostProcess($v['name'],
1583 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1584 $groupTree[$groupID]['table_name'],
1589 'custom_' . $fieldId,
1593 $defaults = array();
1594 $paramsFile = array(
1595 'entity_table' => $groupTree[$groupID]['table_name'],
1596 'entity_id' => $entityId[1],
1599 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1604 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1608 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1616 * Generic function to build all the form elements for a specific group tree.
1618 * @param CRM_Core_Form $form
1620 * @param array $groupTree
1621 * The group tree object.
1622 * @param bool $inactiveNeeded
1623 * Return inactive custom groups.
1624 * @param string $prefix
1625 * Prefix for custom grouptree assigned to template.
1627 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1628 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1630 foreach ($groupTree as $id => $group) {
1631 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1632 foreach ($group['fields'] as $field) {
1633 $required = CRM_Utils_Array
::value('is_required', $field);
1635 if ($field['data_type'] == 'File') {
1636 if (!empty($field['element_value']['data'])) {
1641 $fieldId = $field['id'];
1642 $elementName = $field['element_name'];
1643 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $required);
1649 * Extract the get params from the url, validate and store it in session.
1651 * @param CRM_Core_Form $form
1653 * @param string $type
1654 * The type of custom group we are using.
1658 public static function extractGetParams(&$form, $type) {
1663 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type);
1664 $customValue = array();
1673 foreach ($groupTree as $group) {
1674 if (!isset($group['fields'])) {
1677 foreach ($group['fields'] as $key => $field) {
1678 $fieldName = 'custom_' . $key;
1679 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1683 if (!in_array($field['html_type'], $htmlType) ||
1684 $field['data_type'] == 'Boolean'
1686 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1688 if ($field['html_type'] == 'CheckBox' ||
1689 $field['html_type'] == 'AdvMulti-Select' ||
1690 $field['html_type'] == 'Multi-Select'
1692 $value = str_replace("|", ",", $value);
1693 $mulValues = explode(',', $value);
1694 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1696 foreach ($mulValues as $v1) {
1697 foreach ($customOption as $coID => $coValue) {
1698 if (strtolower(trim($coValue['label'])) ==
1699 strtolower(trim($v1))
1701 $val[$coValue['value']] = 1;
1713 elseif ($field['html_type'] == 'Select' ||
1714 ($field['html_type'] == 'Radio' &&
1715 $field['data_type'] != 'Boolean'
1718 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1719 foreach ($customOption as $customID => $coValue) {
1720 if (strtolower(trim($coValue['label'])) ==
1721 strtolower(trim($value))
1723 $value = $coValue['value'];
1728 elseif ($field['data_type'] == 'Date') {
1729 if (!empty($value)) {
1731 if (!empty($field['time_format'])) {
1732 $time = CRM_Utils_Request
::retrieve($fieldName .
1733 '_time', 'String', $form, FALSE, NULL, 'GET');
1735 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value .
1737 if (!empty($field['time_format'])) {
1738 $customValue[$fieldName . '_time'] = $time;
1745 $customValue[$fieldName] = $value;
1751 return $customValue;
1755 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1756 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1758 * @param int $customFieldId
1760 * @param array $removeCustomFieldTypes
1761 * Remove custom fields of a type eg: array("Individual") ;.
1764 * false if it matches else true
1766 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1767 $query = "SELECT cg.extends as extends
1768 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1769 WHERE cg.id = cf.custom_group_id
1771 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1773 $extends = CRM_Core_DAO
::singleValueQuery($query);
1775 if (in_array($extends, $removeCustomFieldTypes)) {
1787 public static function mapTableName($table) {
1792 case 'Organization':
1793 return 'civicrm_contact';
1796 return 'civicrm_activity';
1799 return 'civicrm_group';
1801 case 'Contribution':
1802 return 'civicrm_contribution';
1804 case 'ContributionRecur':
1805 return 'civicrm_contribution_recur';
1807 case 'Relationship':
1808 return 'civicrm_relationship';
1811 return 'civicrm_event';
1814 return 'civicrm_membership';
1817 case 'ParticipantRole':
1818 case 'ParticipantEventName':
1819 case 'ParticipantEventType':
1820 return 'civicrm_participant';
1823 return 'civicrm_grant';
1826 return 'civicrm_pledge';
1829 return 'civicrm_address';
1832 return 'civicrm_campaign';
1836 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1837 $qParams = array(1 => array($table, 'String'));
1838 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1841 return 'civicrm_contact';
1844 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1845 if (array_key_exists($table, $extendObjs)) {
1846 return $extendObjs[$table];
1848 CRM_Core_Error
::fatal();
1856 public static function createTable($group) {
1858 'name' => $group->table_name
,
1859 'is_multiple' => $group->is_multiple ?
1 : 0,
1860 'extends_name' => self
::mapTableName($group->extends),
1863 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1865 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1869 * Function returns formatted groupTree, sothat form can be easily build in template
1871 * @param array $groupTree
1872 * @param int $groupCount
1873 * Group count by default 1, but can varry for multiple value custom data.
1874 * @param object $form
1878 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NULL) {
1879 $formattedGroupTree = array();
1880 $uploadNames = $formValues = array();
1882 // retrieve qf key from url
1883 $qfKey = CRM_Utils_Request
::retrieve('qf', 'String');
1885 // fetch submitted custom field values later use to set as a default values
1887 $submittedValues = CRM_Core_BAO_Cache
::getItem('custom data', $qfKey);
1890 foreach ($groupTree as $key => $value) {
1891 if ($key === 'info') {
1895 // add group information
1896 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1897 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1898 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1899 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1900 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1901 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1902 $formattedGroupTree[$key]['style'] = CRM_Utils_Array
::value('style', $value);
1904 // this params needed of bulding multiple values
1905 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1906 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1907 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1908 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1909 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1910 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1912 // add field information
1913 foreach ($value['fields'] as $k => $properties) {
1914 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1915 if (isset($properties['customValue']) &&
1916 !CRM_Utils_System
::isNull($properties['customValue']) &&
1917 !isset($properties['element_value'])
1919 if (isset($properties['customValue'][$groupCount])) {
1920 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1921 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1922 if ($properties['data_type'] == 'File') {
1923 $properties['element_value'] = $properties['customValue'][$groupCount];
1924 $uploadNames[] = $properties['element_name'];
1927 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1931 if ($value = CRM_Utils_Request
::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1932 $formValues[$properties['element_name']] = $value;
1934 elseif (isset($submittedValues[$properties['element_name']])) {
1935 $properties['element_value'] = $submittedValues[$properties['element_name']];
1937 unset($properties['customValue']);
1938 $formattedGroupTree[$key]['fields'][$k] = $properties;
1943 if (count($formValues)) {
1944 $qf = $form->get('qfKey');
1945 $form->assign('qfKey', $qf);
1946 CRM_Core_BAO_Cache
::setItem($formValues, 'custom data', $qf);
1949 // hack for field type File
1950 $formUploadNames = $form->get('uploadNames');
1951 if (is_array($formUploadNames)) {
1952 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1955 $form->set('uploadNames', $uploadNames);
1958 return $formattedGroupTree;
1962 * Build custom data view.
1964 * @param CRM_Core_Form|CRM_Core_Page $form
1966 * @param array $groupTree
1967 * @param bool $returnCount
1968 * True if customValue count needs to be returned.
1970 * @param null $prefix
1971 * @param int $customValueId
1972 * @param int $entityId
1975 * @throws \Exception
1977 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
1979 foreach ($groupTree as $key => $group) {
1980 if ($key === 'info') {
1984 foreach ($group['fields'] as $k => $properties) {
1985 $groupID = $group['id'];
1986 if (!empty($properties['customValue'])) {
1987 foreach ($properties['customValue'] as $values) {
1988 if (!empty($customValueId) && $customValueId != $values['id']) {
1991 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1992 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1993 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1994 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1995 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1996 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1997 $details[$groupID][$values['id']]['style'] = CRM_Utils_Array
::value('style', $group);
1998 $details[$groupID][$values['id']]['fields'][$k] = array(
1999 'field_title' => CRM_Utils_Array
::value('label', $properties),
2000 'field_type' => CRM_Utils_Array
::value('html_type', $properties),
2001 'field_data_type' => CRM_Utils_Array
::value('data_type', $properties),
2002 'field_value' => CRM_Core_BAO_CustomField
::displayValue($values['data'], $properties['id'], $entityId),
2003 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $properties),
2005 // editable = whether this set contains any non-read-only fields
2006 if (!isset($details[$groupID][$values['id']]['editable'])) {
2007 $details[$groupID][$values['id']]['editable'] = FALSE;
2009 if (empty($properties['is_view'])) {
2010 $details[$groupID][$values['id']]['editable'] = TRUE;
2012 // also return contact reference contact id if user has view all or edit all contacts perm
2013 if ((CRM_Core_Permission
::check('view all contacts') ||
2014 CRM_Core_Permission
::check('edit all contacts'))
2016 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
2019 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
2024 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
2025 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
2026 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
2027 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
2028 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
2029 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
2030 $details[$groupID][0]['style'] = CRM_Utils_Array
::value('style', $group);
2031 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
2037 //return a single value count if group id is passed to function
2038 //else return a groupId and count mapped array
2040 return count($details[$gID]);
2043 $countValue = array();
2044 foreach ($details as $key => $value) {
2045 $countValue[$key] = count($details[$key]);
2051 $form->assign_by_ref("{$prefix}viewCustomData", $details);
2057 * Get the custom group titles by custom field ids.
2059 * @param array $fieldIds
2060 * Array of custom field ids.
2062 * @return array|NULL
2063 * array consisting of groups and fields labels with ids.
2065 public static function getGroupTitles($fieldIds) {
2066 if (!is_array($fieldIds) && empty($fieldIds)) {
2070 $groupLabels = array();
2071 $fIds = "(" . implode(',', $fieldIds) . ")";
2074 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2075 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2076 FROM civicrm_custom_group, civicrm_custom_field
2077 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2078 AND civicrm_custom_field.id IN {$fIds}";
2080 $dao = CRM_Core_DAO
::executeQuery($query);
2081 while ($dao->fetch()) {
2082 $groupLabels[$dao->fieldID
] = array(
2083 'fieldID' => $dao->fieldID
,
2084 'fieldLabel' => $dao->fieldLabel
,
2085 'groupID' => $dao->groupID
,
2086 'groupTitle' => $dao->groupTitle
,
2090 return $groupLabels;
2093 public static function dropAllTables() {
2094 $query = "SELECT table_name FROM civicrm_custom_group";
2095 $dao = CRM_Core_DAO
::executeQuery($query);
2097 while ($dao->fetch()) {
2098 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2099 CRM_Core_DAO
::executeQuery($query);
2104 * Check whether custom group is empty or not.
2110 * true if empty otherwise false.
2112 public static function isGroupEmpty($gID) {
2117 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2122 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2123 $value = CRM_Core_DAO
::singleValueQuery($query);
2125 if (empty($value)) {
2133 * Get the list of types for objects that a custom group extends to.
2135 * @param array $types
2136 * Var which should have the list appended.
2141 public static function getExtendedObjectTypes(&$types = array()) {
2142 static $flag = FALSE, $objTypes = array();
2145 $extendObjs = array();
2146 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2148 foreach ($extendObjs as $ovId => $ovValues) {
2149 if ($ovValues['description']) {
2150 // description is expected to be a callback func to subtypes
2151 list($callback, $args) = explode(';', trim($ovValues['description']));
2157 if (!is_array($args)) {
2158 CRM_Core_Error
::fatal('Arg is not of type array');
2161 list($className) = explode('::', $callback);
2162 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2165 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2171 $types = array_merge($types, $objTypes);
2176 * @param int $customGroupId
2177 * @param int $entityId
2181 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2182 //check whether the group is multiple
2183 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2184 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2185 $hasReachedMax = FALSE;
2187 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2189 if (!$maxMultiple) {
2190 $hasReachedMax = FALSE;
2193 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2194 //count the number of entries for a entity
2195 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2196 $params = array(1 => array($entityId, 'Integer'));
2197 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2199 if ($count >= $maxMultiple) {
2200 $hasReachedMax = TRUE;
2204 return $hasReachedMax;
2210 public static function getMultipleFieldGroup() {
2211 $multipleGroup = array();
2212 $dao = new CRM_Core_DAO_CustomGroup();
2213 $dao->is_multiple
= 1;
2214 $dao->is_active
= 1;
2216 while ($dao->fetch()) {
2217 $multipleGroup[$dao->id
] = $dao->title
;
2219 return $multipleGroup;