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 $extends = CRM_Utils_Array
::value('extends', $params, []);
64 $extendsEntity = CRM_Utils_Array
::value(0, $extends);
66 $participantEntities = array(
68 'ParticipantEventName',
69 'ParticipantEventType',
72 if (in_array($extendsEntity, $participantEntities)) {
73 $group->extends = 'Participant';
76 $group->extends = $extendsEntity;
79 $group->extends_entity_column_id
= 'null';
80 if (in_array($extendsEntity, $participantEntities)
82 $group->extends_entity_column_id
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $extendsEntity, 'value', 'name');
85 //this is format when form get submit.
86 $extendsChildType = CRM_Utils_Array
::value(1, $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, $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])) {
132 $group->$field = $params[$field];
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 = $tableNameNeedingIndexUpdate = NULL;
140 if (isset($params['id'])) {
141 $group->id
= $params['id'];
143 if (isset($params['is_multiple'])) {
144 //check whether custom group was changed from single-valued to multiple-valued
145 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
150 // dev/core#227 Fix issue where is_multiple in params maybe an empty string if checkbox is not rendered on the form.
151 $paramsIsMultiple = empty($params['is_multiple']) ?
0 : 1;
152 if ($paramsIsMultiple != $isMultiple) {
153 $tableNameNeedingIndexUpdate = CRM_Core_DAO
::getFieldValue(
154 'CRM_Core_DAO_CustomGroup',
162 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
163 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
165 // we do this only once, so name never changes
166 if (isset($params['name'])) {
167 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
170 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
173 if (isset($params['table_name'])) {
174 $tableName = $params['table_name'];
176 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
177 // Bad idea. Prevent group creation because it might lead to a broken configuration.
178 CRM_Core_Error
::fatal(ts("Cannot create custom table because %1 is already a core table.", array('1' => $tableName)));
183 if (array_key_exists('is_reserved', $params)) {
184 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
186 $op = isset($params['id']) ?
'edit' : 'create';
187 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
189 // enclose the below in a transaction
190 $transaction = new CRM_Core_Transaction();
193 if (!isset($params['id'])) {
194 if (!isset($params['table_name'])) {
195 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 13));
196 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
198 $group->table_name
= $tableName;
199 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
205 // now create the table associated with this group
206 self
::createTable($group);
208 elseif ($tableNameNeedingIndexUpdate) {
209 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($tableNameNeedingIndexUpdate, CRM_Utils_Array
::value('is_multiple', $params));
212 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
213 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
217 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($extendsEntity));
219 $transaction->commit();
222 CRM_Utils_System
::flushCache();
225 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
228 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
235 * Fetch object based on array of properties.
237 * @param array $params
238 * (reference ) an assoc array of name/value pairs.
239 * @param array $defaults
240 * (reference ) an assoc array to hold the flattened values.
242 * @return CRM_Core_DAO_CustomGroup
244 public static function retrieve(&$params, &$defaults) {
245 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
249 * Update the is_active flag in the db.
252 * Id of the database record.
253 * @param bool $is_active
254 * Value we want to set the is_active field.
257 * true if we found and updated the object, else false
259 public static function setIsActive($id, $is_active) {
261 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
264 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
267 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
271 * Determine if given entity (sub)type has any custom groups
273 * @param string $extends
274 * E.g. "Individual", "Activity".
275 * @param int $columnId
276 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
277 * @param string $columnValue
278 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
282 public static function hasCustomGroup($extends, $columnId, $columnValue) {
283 $dao = new CRM_Core_DAO_CustomGroup();
284 $dao->extends = $extends;
285 $dao->extends_entity_column_id
= $columnId;
286 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
287 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
288 //$dao->extends_entity_column_value = $columnValue;
289 return $dao->find() ?
TRUE : FALSE;
293 * Determine if there are any CustomGroups for the given $activityTypeId.
294 * If none found, create one.
296 * @param int $activityTypeId
299 * TRUE if a group is found or created; FALSE on error
301 public static function autoCreateByActivityType($activityTypeId) {
302 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
305 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
308 'extends' => 'Activity',
309 'extends_entity_column_id' => NULL,
310 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
311 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
315 $result = civicrm_api('CustomGroup', 'create', $params);
316 return !$result['is_error'];
320 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
321 * This may also include entity specific data values.
323 * An array containing all custom groups and their custom fields is returned.
325 * @param string $entityType
326 * Of the contact whose contact type is needed.
327 * @param array $toReturn
328 * What data should be returned. ['custom_group' => ['id', 'name', etc.], 'custom_field' => ['id', 'label', etc.]]
329 * @param int $entityID
330 * @param int $groupID
331 * @param array $subTypes
332 * @param string $subName
333 * @param bool $fromCache
334 * @param bool $onlySubType
335 * Only return specified subtype or return specified subtype + unrestricted fields.
336 * @param bool $returnAll
337 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
338 * api - through which it is properly tested - so can be refactored with some comfort.)
340 * @param bool $checkPermission
341 * @param string|int $singleRecord
342 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
343 * @param bool $showPublicOnly
346 * Custom field 'tree'.
348 * The returned array is keyed by group id and has the custom group table fields
349 * and a subkey 'fields' holding the specific custom fields.
350 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
351 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
353 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
354 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
355 * With caching the performance impact would be small & the function would be cleaner
357 public static function getTree(
367 $checkPermission = TRUE,
368 $singleRecord = NULL,
369 $showPublicOnly = FALSE
372 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
374 if (!is_array($subTypes)) {
375 if (empty($subTypes)) {
379 if (stristr($subTypes, ',')) {
380 $subTypes = explode(',', $subTypes);
383 $subTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subTypes, CRM_Core_DAO
::VALUE_SEPARATOR
));
389 $strWhere = $orderBy = '';
391 // legacy hardcoded list of data to return
393 'custom_field' => array(
414 'custom_group' => array(
425 'extends_entity_column_id',
426 'extends_entity_column_value',
430 $current_db_version = CRM_Core_DAO
::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config
::domainID());
431 $is_public_version = $current_db_version >= '4.7.19' ?
1 : 0;
432 if ($is_public_version) {
433 $tableData['custom_group'][] = 'is_public';
435 if (!$toReturn ||
!is_array($toReturn)) {
436 $toReturn = $tableData;
439 // Supply defaults and remove unknown array keys
440 $toReturn = array_intersect_key(array_filter($toReturn) +
$tableData, $tableData);
441 // Merge in required fields that we must have
442 $toReturn['custom_field'] = array_unique(array_merge($toReturn['custom_field'], array('id', 'column_name', 'data_type')));
443 $toReturn['custom_group'] = array_unique(array_merge($toReturn['custom_group'], array('id', 'is_multiple', 'table_name', 'name')));
444 // Validate return fields
445 $toReturn['custom_field'] = array_intersect($toReturn['custom_field'], array_keys(CRM_Core_DAO_CustomField
::fieldKeys()));
446 $toReturn['custom_group'] = array_intersect($toReturn['custom_group'], array_keys(CRM_Core_DAO_CustomGroup
::fieldKeys()));
451 foreach ($toReturn as $tableName => $tableColumn) {
452 foreach ($tableColumn as $columnName) {
453 $select[] = "civicrm_{$tableName}.{$columnName} as civicrm_{$tableName}_{$columnName}";
456 $strSelect = "SELECT " . implode(', ', $select);
458 // from, where, order by
460 FROM civicrm_custom_group
461 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
464 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
465 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
466 $entityType == 'Household'
468 $in = "'$entityType', 'Contact'";
470 elseif (strpos($entityType, "'") !== FALSE) {
471 // this allows the calling function to send in multiple entity types
476 $in = "'$entityType'";
481 if (!empty($subTypes)) {
482 foreach ($subTypes as $key => $subType) {
483 $subTypeClauses[] = self
::whereListHas("civicrm_custom_group.extends_entity_column_value", self
::validateSubTypeByEntity($entityType, $subType));
485 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
487 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
491 WHERE civicrm_custom_group.is_active = 1
492 AND civicrm_custom_field.is_active = 1
493 AND civicrm_custom_group.extends IN ($in)
497 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = %{$sqlParamKey}";
498 $params[$sqlParamKey] = array($subName, 'String');
499 $sqlParamKey = $sqlParamKey +
1;
504 WHERE civicrm_custom_group.is_active = 1
505 AND civicrm_custom_field.is_active = 1
506 AND civicrm_custom_group.extends IN ($in)
509 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
514 // since we want a specific group id we add it to the where clause
515 $strWhere .= " AND civicrm_custom_group.id = %{$sqlParamKey}";
516 $params[$sqlParamKey] = array($groupID, 'Integer');
519 // since groupID is false we need to show all Inline groups
520 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
522 if ($checkPermission) {
523 // ensure that the user has access to these custom groups
524 $strWhere .= " AND " .
525 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
526 'civicrm_custom_group.'
530 if ($showPublicOnly && $is_public_version) {
531 $strWhere .= "AND civicrm_custom_group.is_public = 1";
535 ORDER BY civicrm_custom_group.weight,
536 civicrm_custom_group.title,
537 civicrm_custom_field.weight,
538 civicrm_custom_field.label
541 // final query string
542 $queryString = "$strSelect $strFrom $strWhere $orderBy";
544 // lets see if we can retrieve the groupTree from cache
545 $cacheString = $queryString;
547 $cacheString .= "_{$groupID}";
550 $cacheString .= "_Inline";
553 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
554 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
555 $cache = CRM_Utils_Cache
::singleton();
556 $tablesWithEntityData = array();
558 $groupTree = $cache->get($cacheKey);
559 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
562 if (empty($groupTree)) {
563 $groupTree = $multipleFieldGroups = array();
564 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
565 $customValueTables = array();
568 while ($crmDAO->fetch()) {
570 $groupID = $crmDAO->civicrm_custom_group_id
;
571 $fieldId = $crmDAO->civicrm_custom_field_id
;
572 if ($crmDAO->civicrm_custom_group_is_multiple
) {
573 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
575 // create an array for groups if it does not exist
576 if (!array_key_exists($groupID, $groupTree)) {
577 $groupTree[$groupID] = array();
578 $groupTree[$groupID]['id'] = $groupID;
580 // populate the group information
581 foreach ($toReturn['custom_group'] as $fieldName) {
582 $fullFieldName = "civicrm_custom_group_$fieldName";
583 if ($fieldName == 'id' ||
584 is_null($crmDAO->$fullFieldName)
589 // This is an old bit of code - per the CRM number & probably does not work reliably if
590 // that one contact sub-type exists.
591 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
592 $groupTree[$groupID]['subtype'] = self
::validateSubTypeByEntity($entityType, $subType);
594 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
596 $groupTree[$groupID]['fields'] = array();
598 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
601 // add the fields now (note - the query row will always contain a field)
602 // we only reset this once, since multiple values come is as multiple rows
603 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
604 $groupTree[$groupID]['fields'][$fieldId] = array();
607 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
608 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
609 // populate information for a custom field
610 foreach ($toReturn['custom_field'] as $fieldName) {
611 $fullFieldName = "civicrm_custom_field_$fieldName";
612 if ($fieldName == 'id' ||
613 is_null($crmDAO->$fullFieldName)
617 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
621 if (!empty($customValueTables)) {
622 $groupTree['info'] = array('tables' => $customValueTables);
625 $cache->set($cacheKey, $groupTree);
626 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
628 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
629 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
630 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
631 $singleFieldTables = array();
632 // now that we have all the groups and fields, lets get the values
633 // since we need to know the table and field names
634 // add info to groupTree
636 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
637 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
639 $select = $from = $where = array();
640 $groupTree['info']['where'] = NULL;
642 foreach ($groupTree['info']['tables'] as $table => $fields) {
643 $groupTree['info']['from'][] = $table;
645 "{$table}.id as {$table}_id",
646 "{$table}.entity_id as {$table}_entity_id",
648 foreach ($fields as $column => $dontCare) {
649 $select[] = "{$table}.{$column} as {$table}_{$column}";
651 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
653 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
654 if (in_array($table, $multipleFieldGroups) &&
655 self
::customGroupDataExistsForEntity($entityID, $table)
657 $entityMultipleSelectClauses[$table] = $select;
660 $singleFieldTables[] = $table;
661 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
666 if ($entityID && !empty($singleFieldTables)) {
667 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
669 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
670 if (!empty($multipleFieldTablesWithEntityData)) {
671 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
679 * Clean and validate the filter before it is used in a db query.
681 * @param string $entityType
682 * @param string $subType
685 * @throws \CRM_Core_Exception
686 * @throws \CiviCRM_API3_Exception
688 protected static function validateSubTypeByEntity($entityType, $subType) {
689 $subType = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
690 if (is_numeric($subType)) {
694 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypeInfo(TRUE);
695 $contactTypes = array_merge($contactTypes, array('Event' => 1));
697 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
698 throw new CRM_Core_Exception('Invalid Entity Filter');
700 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo($entityType, TRUE);
701 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant
::eventType());
702 if (!array_key_exists($subType, $subTypes)) {
703 throw new CRM_Core_Exception('Invalid Filter');
709 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
710 * a WHERE condition for rows that include $value. Use whereListHas().
712 * @param string $column
713 * @param string $value
714 * @param string $delimiter
718 static private function whereListHas($column, $value, $delimiter = CRM_Core_DAO
::VALUE_SEPARATOR
) {
719 $bareValue = trim($value, $delimiter); // ?
720 $escapedValue = CRM_Utils_Type
::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
721 return "($column LIKE \"$escapedValue\")";
725 * Check whether the custom group has any data for the given entity.
728 * @param int $entityID
729 * Id of entity for whom we are checking data for.
730 * @param string $table
731 * Table that we are checking.
733 * @param bool $getCount
736 * does this entity have data in this custom table
738 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
742 WHERE entity_id = $entityID
744 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
746 return $recordExists;
748 return $recordExists ?
TRUE : FALSE;
752 * Build the group tree for Custom fields which are not 'is_multiple'
754 * The combination of all these fields in one query with a 'using' join was not working for
755 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
756 * mechanism as it seemed to be acceptable in this context
758 * @param array $groupTree
759 * (reference) group tree array which is being built.
760 * @param int $entityID
761 * Id of entity for whom the tree is being build up.
762 * @param array $entitySingleSelectClauses
763 * Array of select clauses relevant to the entity.
764 * @param array $singleFieldTablesWithEntityData
765 * Array of tables in which this entity has data.
767 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
768 $select = implode(', ', $entitySingleSelectClauses);
769 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
770 foreach ($singleFieldTablesWithEntityData as $table) {
771 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
777 WHERE first.entity_id = $entityID
779 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
783 * Build the group tree for Custom fields which are 'is_multiple'
785 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
787 * @param array $groupTree
788 * (reference) group tree array which is being built.
789 * @param int $entityID
790 * Id of entity for whom the tree is being build up.
791 * @param array $entityMultipleSelectClauses
792 * Array of select clauses relevant to the entity.
793 * @param array $multipleFieldTablesWithEntityData
794 * Array of tables in which this entity has data.
795 * @param varchar $singleRecord
796 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
798 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
799 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
800 $select = implode(',', $selectClauses);
804 WHERE entity_id = $entityID
807 $offset = $singleRecord - 1;
808 $query .= " LIMIT {$offset}, 1";
810 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table), $singleRecord);
815 * Build the tree entity data - starting from a query retrieving the custom fields build the group
816 * tree data for the relevant entity (entity is included in the query).
818 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
820 * @param array $groupTree
821 * (reference) group tree array which is being built.
822 * @param string $query
823 * @param array $includedTables
824 * Tables to include - required because the function (for historical reasons).
825 * iterates through the group tree
826 * @param varchar $singleRecord
827 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
829 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
830 $dao = CRM_Core_DAO
::executeQuery($query);
831 while ($dao->fetch()) {
832 foreach ($groupTree as $groupID => $group) {
833 if ($groupID === 'info') {
836 $table = $groupTree[$groupID]['table_name'];
837 //working from the groupTree instead of the table list means we have to iterate & exclude.
838 // this could possibly be re-written as other parts of the function have been refactored
839 // for now we just check if the given table is to be included in this function
840 if (!in_array($table, $includedTables)) {
843 foreach ($group['fields'] as $fieldID => $dontCare) {
844 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
851 * Build the entity-specific custom data into the group tree on a per-field basis
854 * Object representing the custom field to be populated into the groupTree.
855 * @param array $groupTree
856 * (reference) the group tree being build.
857 * @param string $table
859 * @param int $groupID
861 * @param int $fieldID
863 * @param varchar $singleRecord
864 * holds 'new' or id if loading view/edit/copy for a single record.
866 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
867 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
868 $idName = "{$table}_id";
869 $fieldName = "{$table}_{$column}";
870 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
871 if ($dataType == 'File') {
872 if (isset($dao->$fieldName)) {
873 $config = CRM_Core_Config
::singleton();
874 $fileDAO = new CRM_Core_DAO_File();
875 $fileDAO->id
= $dao->$fieldName;
877 if ($fileDAO->find(TRUE)) {
878 $entityIDName = "{$table}_entity_id";
879 $customValue['id'] = $dao->$idName;
880 $customValue['data'] = $fileDAO->uri
;
881 $customValue['fid'] = $fileDAO->id
;
882 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
883 $customValue['displayURL'] = NULL;
884 $deleteExtra = ts('Are you sure you want to delete attached file.');
886 CRM_Core_Action
::DELETE
=> array(
887 'name' => ts('Delete Attached File'),
888 'url' => 'civicrm/file',
889 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
890 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
891 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
894 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
895 CRM_Core_Action
::DELETE
,
897 'id' => $fileDAO->id
,
898 'eid' => $dao->$entityIDName,
903 'file.manage.delete',
907 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
908 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
909 if ($fileDAO->mime_type
== "image/jpeg" ||
910 $fileDAO->mime_type
== "image/pjpeg" ||
911 $fileDAO->mime_type
== "image/gif" ||
912 $fileDAO->mime_type
== "image/x-png" ||
913 $fileDAO->mime_type
== "image/png"
915 $customValue['displayURL'] = $customValue['fileURL'];
916 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
921 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
923 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId, NULL, NULL);
924 if ($path && file_exists($path)) {
925 list($imageWidth, $imageHeight) = getimagesize($path);
926 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
927 $customValue['imageThumbWidth'] = $imageThumbWidth;
928 $customValue['imageThumbHeight'] = $imageThumbHeight;
934 $customValue = array(
935 'id' => $dao->$idName,
941 $customValue = array(
942 'id' => $dao->$idName,
943 'data' => $dao->$fieldName,
947 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
948 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
950 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
951 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array($singleRecord => $customValue);
953 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
954 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
957 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
962 * Get the group title.
970 public static function getTitle($id) {
971 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
975 * Get custom group details for a group.
977 * An array containing custom group details (including their custom field) is returned.
979 * @param int $groupId
980 * Group id whose details are needed.
981 * @param bool $searchable
982 * Is this field searchable.
983 * @param array $extends
984 * Which table does it extend if any.
986 * @param null $inSelector
989 * array consisting of all group and field details
991 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
993 $groupTree = array();
994 $select = $from = $where = $orderBy = '';
996 $tableData = array();
998 // using tableData to build the queryString
1000 'civicrm_custom_field' => array(
1024 'civicrm_custom_group' => array(
1031 'collapse_adv_display',
1033 'extends_entity_column_value',
1041 foreach ($tableData as $tableName => $tableColumn) {
1042 foreach ($tableColumn as $columnName) {
1043 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
1046 $select = 'SELECT ' . implode(', ', $s);
1048 // from, where, order by
1049 $from = " FROM civicrm_custom_field, civicrm_custom_group";
1050 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
1051 AND civicrm_custom_group.is_active = 1
1052 AND civicrm_custom_field.is_active = 1 ";
1054 $params[1] = array($groupId, 'Integer');
1055 $where .= " AND civicrm_custom_group.id = %1";
1059 $where .= " AND civicrm_custom_field.is_searchable = 1";
1063 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
1068 foreach ($extends as $e) {
1069 $clause[] = "civicrm_custom_group.extends = '$e'";
1071 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1073 //include case activities customdata if case is enabled
1074 if (in_array('Activity', $extends)) {
1075 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1076 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1077 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
1081 // ensure that the user has access to these custom groups
1083 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1084 'civicrm_custom_group.'
1087 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1089 // final query string
1090 $queryString = $select . $from . $where . $orderBy;
1093 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1096 while ($crmDAO->fetch()) {
1097 $groupId = $crmDAO->civicrm_custom_group_id
;
1098 $fieldId = $crmDAO->civicrm_custom_field_id
;
1100 // create an array for groups if it does not exist
1101 if (!array_key_exists($groupId, $groupTree)) {
1102 $groupTree[$groupId] = array();
1103 $groupTree[$groupId]['id'] = $groupId;
1105 foreach ($tableData['civicrm_custom_group'] as $v) {
1106 $fullField = "civicrm_custom_group_" . $v;
1108 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1112 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1115 $groupTree[$groupId]['fields'] = array();
1118 // add the fields now (note - the query row will always contain a field)
1119 $groupTree[$groupId]['fields'][$fieldId] = array();
1120 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1122 foreach ($tableData['civicrm_custom_field'] as $v) {
1123 $fullField = "civicrm_custom_field_" . $v;
1124 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1127 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1135 * @param $entityType
1137 * @param string $cidToken
1141 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1143 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1145 // get 'Tab' and 'Tab with table' groups
1146 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1147 $customGroupDAO->whereAdd("is_active = 1");
1149 // add whereAdd for entity type
1150 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1154 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1155 $customGroupDAO->whereAdd($permissionClause);
1158 $customGroupDAO->orderBy('weight');
1159 $customGroupDAO->find();
1161 // process each group with menu tab
1162 while ($customGroupDAO->fetch()) {
1164 $group['id'] = $customGroupDAO->id
;
1165 $group['path'] = $path;
1166 $group['title'] = "$customGroupDAO->title";
1167 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1168 $group['extra'] = array('gid' => $customGroupDAO->id
);
1169 $group['table_name'] = $customGroupDAO->table_name
;
1170 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1178 * Get the table name for the entity type
1179 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1180 * tableName is 'civicrm_contact'
1182 * @param string $entityType
1183 * What entity are we extending here ?.
1188 * @see _apachesolr_civiAttachments_dereference_file_parent
1190 public static function getTableNameByEntityName($entityType) {
1192 switch ($entityType) {
1196 case 'Organization':
1197 $tableName = 'civicrm_contact';
1200 case 'Contribution':
1201 $tableName = 'civicrm_contribution';
1205 $tableName = 'civicrm_group';
1208 // DRAFTING: Verify if we cannot make it pluggable
1211 $tableName = 'civicrm_activity';
1214 case 'Relationship':
1215 $tableName = 'civicrm_relationship';
1219 $tableName = 'civicrm_membership';
1223 $tableName = 'civicrm_participant';
1227 $tableName = 'civicrm_event';
1231 $tableName = 'civicrm_grant';
1234 // need to add cases for Location, Address
1241 * Get a list of custom groups which extend a given entity type.
1242 * If there are custom-groups which only apply to certain subtypes,
1243 * those WILL be included.
1245 * @param string $entityType
1247 * @return CRM_Core_DAO_CustomGroup
1249 public static function getAllCustomGroupsByBaseEntity($entityType) {
1250 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1251 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1252 return $customGroupDAO;
1256 * Add the whereAdd clause for the DAO depending on the type of entity
1257 * the custom group is extending.
1259 * @param object $customGroupDAO
1260 * @param string $entityType
1261 * What entity are we extending here ?.
1263 * @param int $entityID
1264 * @param bool $allSubtypes
1266 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1267 $addSubtypeClause = FALSE;
1268 // This function isn't really accessible with user data but since the string
1269 // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless
1271 $entityType = CRM_Core_DAO
::escapeString($entityType);
1273 switch ($entityType) {
1275 // if contact, get all related to contact
1276 $extendList = "'Contact','Individual','Household','Organization'";
1277 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1278 if (!$allSubtypes) {
1279 $addSubtypeClause = TRUE;
1285 case 'Organization':
1286 // is I/H/O then get I/H/O and contact
1287 $extendList = "'Contact','$entityType'";
1288 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1289 if (!$allSubtypes) {
1290 $addSubtypeClause = TRUE;
1295 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1299 if ($addSubtypeClause) {
1300 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1302 if (!empty($csType)) {
1303 $subtypeClause = array();
1304 foreach ($csType as $subtype) {
1305 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1306 CRM_Core_DAO
::VALUE_SEPARATOR
;
1307 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1309 $subtypeClause[] = "extends_entity_column_value IS NULL";
1310 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1314 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1320 * Delete the Custom Group.
1322 * @param CRM_Core_BAO_CustomGroup $group
1323 * Custom group object.
1324 * @param bool $force
1325 * whether to force the deletion, even if there are custom fields.
1328 * False if field exists for this group, true if group gets deleted.
1330 public static function deleteGroup($group, $force = FALSE) {
1332 //check whether this contain any custom fields
1333 $customField = new CRM_Core_DAO_CustomField();
1334 $customField->custom_group_id
= $group->id
;
1335 $customField->find();
1337 // return early if there are custom fields and we're not
1338 // forcing the delete, otherwise delete the fields one by one
1339 while ($customField->fetch()) {
1343 CRM_Core_BAO_CustomField
::deleteField($customField);
1346 // drop the table associated with this custom group
1347 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1349 //delete custom group
1352 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1360 * @param array $groupTree
1361 * @param array $defaults
1362 * @param bool $viewMode
1363 * @param bool $inactiveNeeded
1364 * @param int $action
1366 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1367 foreach ($groupTree as $id => $group) {
1368 if (!isset($group['fields'])) {
1371 foreach ($group['fields'] as $field) {
1372 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1373 $value = $field['element_value'];
1375 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1376 ($action != CRM_Core_Action
::UPDATE ||
1378 !array_key_exists('element_value', $field)
1381 $value = $viewMode ?
NULL : $field['default_value'];
1387 if (empty($field['element_name'])) {
1391 $elementName = $field['element_name'];
1393 switch ($field['html_type']) {
1394 case 'Multi-Select':
1396 $defaults[$elementName] = array();
1397 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1399 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1400 if (isset($value)) {
1401 foreach ($customOption as $customValue => $customLabel) {
1402 if (in_array($customValue, $checkedData)) {
1403 if ($field['html_type'] == 'CheckBox') {
1404 $defaults[$elementName][$customValue] = 1;
1407 $defaults[$elementName][$customValue] = $customValue;
1411 $defaults[$elementName][$customValue] = 0;
1417 if (isset($field['customValue']['data'])) {
1418 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1419 foreach ($customOption as $val) {
1420 if (in_array($val['value'], $checkedData)) {
1421 if ($field['html_type'] == 'CheckBox') {
1422 $defaults[$elementName][$val['value']] = 1;
1425 $defaults[$elementName][$val['value']] = $val['value'];
1429 $defaults[$elementName][$val['value']] = 0;
1434 if (is_array($value) && count($value)) {
1435 CRM_Utils_Array
::formatArrayKeys($value);
1436 $checkedValue = $value;
1439 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1441 foreach ($customOption as $val) {
1442 if (in_array($val['value'], $checkedValue)) {
1443 if ($field['html_type'] == 'CheckBox') {
1444 $defaults[$elementName][$val['value']] = 1;
1447 $defaults[$elementName][$val['value']] = $val['value'];
1455 case 'Multi-Select Country':
1456 case 'Multi-Select State/Province':
1457 if (isset($value)) {
1458 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1459 foreach ($checkedValue as $val) {
1461 $defaults[$elementName][$val] = $val;
1467 case 'Select Country':
1469 $defaults[$elementName] = $value;
1472 $config = CRM_Core_Config
::singleton();
1473 $defaults[$elementName] = $config->defaultContactCountry
;
1478 if ($field['data_type'] == "Float") {
1479 $defaults[$elementName] = (float) $value;
1481 elseif ($field['data_type'] == 'Money' &&
1482 $field['html_type'] == 'Text'
1484 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1487 $defaults[$elementName] = $value;
1495 * PostProcess function.
1497 * @param array $groupTree
1498 * @param array $params
1499 * @param bool $skipFile
1501 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1502 // Get the Custom form values and groupTree
1503 // first reset all checkbox and radio data
1504 foreach ($groupTree as $groupID => $group) {
1505 if ($groupID === 'info') {
1508 foreach ($group['fields'] as $field) {
1509 $fieldId = $field['id'];
1511 //added Multi-Select option in the below if-statement
1512 if ($field['html_type'] == 'CheckBox' ||
1513 $field['html_type'] == 'Radio' ||
1514 $field['html_type'] == 'Multi-Select'
1516 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1520 foreach ($params as $key => $val) {
1521 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1522 $match[1] == $field['id']
1528 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1529 // field exists in db so populate value from "form".
1530 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1533 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1535 //added for CheckBox
1539 $customValue = array_keys($v);
1540 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1541 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1542 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1545 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1549 case 'Multi-Select':
1551 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1552 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1553 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1556 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1561 $date = CRM_Utils_Date
::processDate($v);
1562 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1570 //store the file in d/b
1571 $entityId = explode('=', $groupTree['info']['where'][0]);
1572 $fileParams = array('upload_date' => date('YmdHis'));
1574 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1575 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1578 $fileParams['uri'] = $v['name'];
1579 $fileParams['mime_type'] = $v['type'];
1580 CRM_Core_BAO_File
::filePostProcess($v['name'],
1581 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1582 $groupTree[$groupID]['table_name'],
1587 'custom_' . $fieldId,
1591 $defaults = array();
1592 $paramsFile = array(
1593 'entity_table' => $groupTree[$groupID]['table_name'],
1594 'entity_id' => $entityId[1],
1597 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1602 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1606 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1614 * Generic function to build all the form elements for a specific group tree.
1616 * @param CRM_Core_Form $form
1618 * @param array $groupTree
1619 * The group tree object.
1620 * @param bool $inactiveNeeded
1621 * Return inactive custom groups.
1622 * @param string $prefix
1623 * Prefix for custom grouptree assigned to template.
1625 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1626 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1628 foreach ($groupTree as $id => $group) {
1629 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1630 foreach ($group['fields'] as $field) {
1631 $required = CRM_Utils_Array
::value('is_required', $field);
1633 if ($field['data_type'] == 'File') {
1634 if (!empty($field['element_value']['data'])) {
1639 $fieldId = $field['id'];
1640 $elementName = $field['element_name'];
1641 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $required);
1642 if ($form->getAction() == CRM_Core_Action
::VIEW
) {
1643 $form->getElement($elementName)->freeze();
1650 * Extract the get params from the url, validate and store it in session.
1652 * @param CRM_Core_Form $form
1654 * @param string $type
1655 * The type of custom group we are using.
1659 public static function extractGetParams(&$form, $type) {
1664 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type);
1665 $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'] == 'Multi-Select'
1691 $value = str_replace("|", ",", $value);
1692 $mulValues = explode(',', $value);
1693 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1695 foreach ($mulValues as $v1) {
1696 foreach ($customOption as $coID => $coValue) {
1697 if (strtolower(trim($coValue['label'])) ==
1698 strtolower(trim($v1))
1700 $val[$coValue['value']] = 1;
1712 elseif ($field['html_type'] == 'Select' ||
1713 ($field['html_type'] == 'Radio' &&
1714 $field['data_type'] != 'Boolean'
1717 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1718 foreach ($customOption as $customID => $coValue) {
1719 if (strtolower(trim($coValue['label'])) ==
1720 strtolower(trim($value))
1722 $value = $coValue['value'];
1727 elseif ($field['data_type'] == 'Date') {
1728 $valid = CRM_Utils_Rule
::date($value);
1732 $customValue[$fieldName] = $value;
1738 return $customValue;
1742 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1743 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1745 * @param int $customFieldId
1747 * @param array $removeCustomFieldTypes
1748 * Remove custom fields of a type eg: array("Individual") ;.
1751 * false if it matches else true
1753 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1754 $query = "SELECT cg.extends as extends
1755 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1756 WHERE cg.id = cf.custom_group_id
1758 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1760 $extends = CRM_Core_DAO
::singleValueQuery($query);
1762 if (in_array($extends, $removeCustomFieldTypes)) {
1774 public static function mapTableName($table) {
1779 case 'Organization':
1780 return 'civicrm_contact';
1783 return 'civicrm_activity';
1786 return 'civicrm_group';
1788 case 'Contribution':
1789 return 'civicrm_contribution';
1791 case 'ContributionRecur':
1792 return 'civicrm_contribution_recur';
1794 case 'Relationship':
1795 return 'civicrm_relationship';
1798 return 'civicrm_event';
1801 return 'civicrm_membership';
1804 case 'ParticipantRole':
1805 case 'ParticipantEventName':
1806 case 'ParticipantEventType':
1807 return 'civicrm_participant';
1810 return 'civicrm_grant';
1813 return 'civicrm_pledge';
1816 return 'civicrm_address';
1819 return 'civicrm_campaign';
1823 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1824 $qParams = array(1 => array($table, 'String'));
1825 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1828 return 'civicrm_contact';
1831 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1832 if (array_key_exists($table, $extendObjs)) {
1833 return $extendObjs[$table];
1835 CRM_Core_Error
::fatal();
1843 public static function createTable($group) {
1845 'name' => $group->table_name
,
1846 'is_multiple' => $group->is_multiple ?
1 : 0,
1847 'extends_name' => self
::mapTableName($group->extends),
1850 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1852 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1856 * Function returns formatted groupTree, sothat form can be easily build in template
1858 * @param array $groupTree
1859 * @param int $groupCount
1860 * Group count by default 1, but can varry for multiple value custom data.
1861 * @param object $form
1865 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NULL) {
1866 $formattedGroupTree = array();
1867 $uploadNames = $formValues = array();
1869 // retrieve qf key from url
1870 $qfKey = CRM_Utils_Request
::retrieve('qf', 'String');
1872 // fetch submitted custom field values later use to set as a default values
1874 $submittedValues = CRM_Core_BAO_Cache
::getItem('custom data', $qfKey);
1877 foreach ($groupTree as $key => $value) {
1878 if ($key === 'info') {
1882 // add group information
1883 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1884 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1885 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1886 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1887 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1888 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1889 $formattedGroupTree[$key]['style'] = CRM_Utils_Array
::value('style', $value);
1891 // this params needed of bulding multiple values
1892 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1893 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1894 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1895 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1896 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1897 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1899 // add field information
1900 foreach ($value['fields'] as $k => $properties) {
1901 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1902 if (isset($properties['customValue']) &&
1903 !CRM_Utils_System
::isNull($properties['customValue']) &&
1904 !isset($properties['element_value'])
1906 if (isset($properties['customValue'][$groupCount])) {
1907 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1908 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1909 if ($properties['data_type'] == 'File') {
1910 $properties['element_value'] = $properties['customValue'][$groupCount];
1911 $uploadNames[] = $properties['element_name'];
1914 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1918 if ($value = CRM_Utils_Request
::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1919 $formValues[$properties['element_name']] = $value;
1921 elseif (isset($submittedValues[$properties['element_name']])) {
1922 $properties['element_value'] = $submittedValues[$properties['element_name']];
1924 unset($properties['customValue']);
1925 $formattedGroupTree[$key]['fields'][$k] = $properties;
1930 if (count($formValues)) {
1931 $qf = $form->get('qfKey');
1932 $form->assign('qfKey', $qf);
1933 CRM_Core_BAO_Cache
::setItem($formValues, 'custom data', $qf);
1936 // hack for field type File
1937 $formUploadNames = $form->get('uploadNames');
1938 if (is_array($formUploadNames)) {
1939 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1942 $form->set('uploadNames', $uploadNames);
1945 return $formattedGroupTree;
1949 * Build custom data view.
1951 * @param CRM_Core_Form|CRM_Core_Page $form
1953 * @param array $groupTree
1954 * @param bool $returnCount
1955 * True if customValue count needs to be returned.
1957 * @param null $prefix
1958 * @param int $customValueId
1959 * @param int $entityId
1962 * @throws \Exception
1964 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
1966 foreach ($groupTree as $key => $group) {
1967 if ($key === 'info') {
1971 foreach ($group['fields'] as $k => $properties) {
1972 $groupID = $group['id'];
1973 if (!empty($properties['customValue'])) {
1974 foreach ($properties['customValue'] as $values) {
1975 if (!empty($customValueId) && $customValueId != $values['id']) {
1978 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1979 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1980 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1981 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1982 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1983 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1984 $details[$groupID][$values['id']]['style'] = CRM_Utils_Array
::value('style', $group);
1985 $details[$groupID][$values['id']]['fields'][$k] = array(
1986 'field_title' => CRM_Utils_Array
::value('label', $properties),
1987 'field_type' => CRM_Utils_Array
::value('html_type', $properties),
1988 'field_data_type' => CRM_Utils_Array
::value('data_type', $properties),
1989 'field_value' => CRM_Core_BAO_CustomField
::displayValue($values['data'], $properties['id'], $entityId),
1990 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $properties),
1992 // editable = whether this set contains any non-read-only fields
1993 if (!isset($details[$groupID][$values['id']]['editable'])) {
1994 $details[$groupID][$values['id']]['editable'] = FALSE;
1996 if (empty($properties['is_view'])) {
1997 $details[$groupID][$values['id']]['editable'] = TRUE;
1999 // also return contact reference contact id if user has view all or edit all contacts perm
2000 if ((CRM_Core_Permission
::check('view all contacts') ||
2001 CRM_Core_Permission
::check('edit all contacts'))
2003 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
2006 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
2011 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
2012 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
2013 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
2014 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
2015 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
2016 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
2017 $details[$groupID][0]['style'] = CRM_Utils_Array
::value('style', $group);
2018 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
2024 //return a single value count if group id is passed to function
2025 //else return a groupId and count mapped array
2027 return count($details[$gID]);
2030 $countValue = array();
2031 foreach ($details as $key => $value) {
2032 $countValue[$key] = count($details[$key]);
2038 $form->assign_by_ref("{$prefix}viewCustomData", $details);
2044 * Get the custom group titles by custom field ids.
2046 * @param array $fieldIds
2047 * Array of custom field ids.
2049 * @return array|NULL
2050 * array consisting of groups and fields labels with ids.
2052 public static function getGroupTitles($fieldIds) {
2053 if (!is_array($fieldIds) && empty($fieldIds)) {
2057 $groupLabels = array();
2058 $fIds = "(" . implode(',', $fieldIds) . ")";
2061 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2062 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2063 FROM civicrm_custom_group, civicrm_custom_field
2064 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2065 AND civicrm_custom_field.id IN {$fIds}";
2067 $dao = CRM_Core_DAO
::executeQuery($query);
2068 while ($dao->fetch()) {
2069 $groupLabels[$dao->fieldID
] = array(
2070 'fieldID' => $dao->fieldID
,
2071 'fieldLabel' => $dao->fieldLabel
,
2072 'groupID' => $dao->groupID
,
2073 'groupTitle' => $dao->groupTitle
,
2077 return $groupLabels;
2080 public static function dropAllTables() {
2081 $query = "SELECT table_name FROM civicrm_custom_group";
2082 $dao = CRM_Core_DAO
::executeQuery($query);
2084 while ($dao->fetch()) {
2085 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2086 CRM_Core_DAO
::executeQuery($query);
2091 * Check whether custom group is empty or not.
2097 * true if empty otherwise false.
2099 public static function isGroupEmpty($gID) {
2104 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2109 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2110 $value = CRM_Core_DAO
::singleValueQuery($query);
2112 if (empty($value)) {
2120 * Get the list of types for objects that a custom group extends to.
2122 * @param array $types
2123 * Var which should have the list appended.
2128 public static function getExtendedObjectTypes(&$types = array()) {
2129 static $flag = FALSE, $objTypes = array();
2132 $extendObjs = array();
2133 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2135 foreach ($extendObjs as $ovId => $ovValues) {
2136 if ($ovValues['description']) {
2137 // description is expected to be a callback func to subtypes
2138 list($callback, $args) = explode(';', trim($ovValues['description']));
2144 if (!is_array($args)) {
2145 CRM_Core_Error
::fatal('Arg is not of type array');
2148 list($className) = explode('::', $callback);
2149 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2152 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2158 $types = array_merge($types, $objTypes);
2163 * @param int $customGroupId
2164 * @param int $entityId
2168 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2169 //check whether the group is multiple
2170 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2171 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2172 $hasReachedMax = FALSE;
2174 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2176 if (!$maxMultiple) {
2177 $hasReachedMax = FALSE;
2180 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2181 //count the number of entries for a entity
2182 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2183 $params = array(1 => array($entityId, 'Integer'));
2184 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2186 if ($count >= $maxMultiple) {
2187 $hasReachedMax = TRUE;
2191 return $hasReachedMax;
2197 public static function getMultipleFieldGroup() {
2198 $multipleGroup = array();
2199 $dao = new CRM_Core_DAO_CustomGroup();
2200 $dao->is_multiple
= 1;
2201 $dao->is_active
= 1;
2203 while ($dao->fetch()) {
2204 $multipleGroup[$dao->id
] = $dao->title
;
2206 return $multipleGroup;