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 if ($params['is_multiple'] != $isMultiple) {
151 $tableNameNeedingIndexUpdate = CRM_Core_DAO
::getFieldValue(
152 'CRM_Core_DAO_CustomGroup',
160 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
161 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
163 // we do this only once, so name never changes
164 if (isset($params['name'])) {
165 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
168 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
171 if (isset($params['table_name'])) {
172 $tableName = $params['table_name'];
174 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
175 // Bad idea. Prevent group creation because it might lead to a broken configuration.
176 CRM_Core_Error
::fatal(ts("Cannot create custom table because %1 is already a core table.", array('1' => $tableName)));
181 if (array_key_exists('is_reserved', $params)) {
182 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
184 $op = isset($params['id']) ?
'edit' : 'create';
185 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
187 // enclose the below in a transaction
188 $transaction = new CRM_Core_Transaction();
191 if (!isset($params['id'])) {
192 if (!isset($params['table_name'])) {
193 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 13));
194 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
196 $group->table_name
= $tableName;
197 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
203 // now create the table associated with this group
204 self
::createTable($group);
206 elseif ($tableNameNeedingIndexUpdate) {
207 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($tableNameNeedingIndexUpdate, CRM_Utils_Array
::value('is_multiple', $params));
210 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
211 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
215 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($extendsEntity));
217 $transaction->commit();
220 CRM_Utils_System
::flushCache();
223 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
226 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
233 * Fetch object based on array of properties.
235 * @param array $params
236 * (reference ) an assoc array of name/value pairs.
237 * @param array $defaults
238 * (reference ) an assoc array to hold the flattened values.
240 * @return CRM_Core_DAO_CustomGroup
242 public static function retrieve(&$params, &$defaults) {
243 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
247 * Update the is_active flag in the db.
250 * Id of the database record.
251 * @param bool $is_active
252 * Value we want to set the is_active field.
255 * DAO object on success, null otherwise
257 public static function setIsActive($id, $is_active) {
259 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
262 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
265 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
269 * Determine if given entity (sub)type has any custom groups
271 * @param string $extends
272 * E.g. "Individual", "Activity".
273 * @param int $columnId
274 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
275 * @param string $columnValue
276 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
280 public static function hasCustomGroup($extends, $columnId, $columnValue) {
281 $dao = new CRM_Core_DAO_CustomGroup();
282 $dao->extends = $extends;
283 $dao->extends_entity_column_id
= $columnId;
284 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
285 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
286 //$dao->extends_entity_column_value = $columnValue;
287 return $dao->find() ?
TRUE : FALSE;
291 * Determine if there are any CustomGroups for the given $activityTypeId.
292 * If none found, create one.
294 * @param int $activityTypeId
297 * TRUE if a group is found or created; FALSE on error
299 public static function autoCreateByActivityType($activityTypeId) {
300 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
303 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
306 'extends' => 'Activity',
307 'extends_entity_column_id' => NULL,
308 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
309 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
313 $result = civicrm_api('CustomGroup', 'create', $params);
314 return !$result['is_error'];
318 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
319 * This may also include entity specific data values.
321 * An array containing all custom groups and their custom fields is returned.
323 * @param string $entityType
324 * Of the contact whose contact type is needed.
325 * @param array $toReturn
326 * What data should be returned. ['custom_group' => ['id', 'name', etc.], 'custom_field' => ['id', 'label', etc.]]
327 * @param int $entityID
328 * @param int $groupID
329 * @param array $subTypes
330 * @param string $subName
331 * @param bool $fromCache
332 * @param bool $onlySubType
333 * Only return specified subtype or return specified subtype + unrestricted fields.
334 * @param bool $returnAll
335 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
336 * api - through which it is properly tested - so can be refactored with some comfort.)
338 * @param bool $checkPermission
339 * @param string|int $singleRecord
340 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
341 * @param bool $showPublicOnly
344 * Custom field 'tree'.
346 * The returned array is keyed by group id and has the custom group table fields
347 * and a subkey 'fields' holding the specific custom fields.
348 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
349 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
351 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
352 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
353 * With caching the performance impact would be small & the function would be cleaner
355 public static function getTree(
365 $checkPermission = TRUE,
366 $singleRecord = NULL,
367 $showPublicOnly = FALSE
370 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
372 if (!is_array($subTypes)) {
373 if (empty($subTypes)) {
377 if (stristr($subTypes, ',')) {
378 $subTypes = explode(',', $subTypes);
381 $subTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subTypes, CRM_Core_DAO
::VALUE_SEPARATOR
));
387 $strWhere = $orderBy = '';
389 // legacy hardcoded list of data to return
391 'custom_field' => array(
412 'custom_group' => array(
423 'extends_entity_column_id',
424 'extends_entity_column_value',
428 $current_db_version = CRM_Core_DAO
::singleValueQuery("SELECT version FROM civicrm_domain WHERE id = " . CRM_Core_Config
::domainID());
429 $is_public_version = $current_db_version >= '4.7.19' ?
1 : 0;
430 if ($is_public_version) {
431 $tableData['custom_group'][] = 'is_public';
433 if (!$toReturn ||
!is_array($toReturn)) {
434 $toReturn = $tableData;
437 // Supply defaults and remove unknown array keys
438 $toReturn = array_intersect_key(array_filter($toReturn) +
$tableData, $tableData);
439 // Merge in required fields that we must have
440 $toReturn['custom_field'] = array_unique(array_merge($toReturn['custom_field'], array('id', 'column_name', 'data_type')));
441 $toReturn['custom_group'] = array_unique(array_merge($toReturn['custom_group'], array('id', 'is_multiple', 'table_name', 'name')));
442 // Validate return fields
443 $toReturn['custom_field'] = array_intersect($toReturn['custom_field'], array_keys(CRM_Core_DAO_CustomField
::fieldKeys()));
444 $toReturn['custom_group'] = array_intersect($toReturn['custom_group'], array_keys(CRM_Core_DAO_CustomGroup
::fieldKeys()));
449 foreach ($toReturn as $tableName => $tableColumn) {
450 foreach ($tableColumn as $columnName) {
451 $select[] = "civicrm_{$tableName}.{$columnName} as civicrm_{$tableName}_{$columnName}";
454 $strSelect = "SELECT " . implode(', ', $select);
456 // from, where, order by
458 FROM civicrm_custom_group
459 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
462 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
463 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
464 $entityType == 'Household'
466 $in = "'$entityType', 'Contact'";
468 elseif (strpos($entityType, "'") !== FALSE) {
469 // this allows the calling function to send in multiple entity types
474 $in = "'$entityType'";
477 if (!empty($subTypes)) {
478 foreach ($subTypes as $key => $subType) {
479 $subTypeClauses[] = self
::whereListHas("civicrm_custom_group.extends_entity_column_value", self
::validateSubTypeByEntity($entityType, $subType));
481 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
483 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
487 WHERE civicrm_custom_group.is_active = 1
488 AND civicrm_custom_field.is_active = 1
489 AND civicrm_custom_group.extends IN ($in)
493 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
498 WHERE civicrm_custom_group.is_active = 1
499 AND civicrm_custom_field.is_active = 1
500 AND civicrm_custom_group.extends IN ($in)
503 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
509 // since we want a specific group id we add it to the where clause
510 $strWhere .= " AND civicrm_custom_group.id = %1";
511 $params[1] = array($groupID, 'Integer');
514 // since groupID is false we need to show all Inline groups
515 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
517 if ($checkPermission) {
518 // ensure that the user has access to these custom groups
519 $strWhere .= " AND " .
520 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
521 'civicrm_custom_group.'
525 if ($showPublicOnly && $is_public_version) {
526 $strWhere .= "AND civicrm_custom_group.is_public = 1";
530 ORDER BY civicrm_custom_group.weight,
531 civicrm_custom_group.title,
532 civicrm_custom_field.weight,
533 civicrm_custom_field.label
536 // final query string
537 $queryString = "$strSelect $strFrom $strWhere $orderBy";
539 // lets see if we can retrieve the groupTree from cache
540 $cacheString = $queryString;
542 $cacheString .= "_{$groupID}";
545 $cacheString .= "_Inline";
548 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
549 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
550 $cache = CRM_Utils_Cache
::singleton();
551 $tablesWithEntityData = array();
553 $groupTree = $cache->get($cacheKey);
554 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
557 if (empty($groupTree)) {
558 $groupTree = $multipleFieldGroups = array();
559 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
560 $customValueTables = array();
563 while ($crmDAO->fetch()) {
565 $groupID = $crmDAO->civicrm_custom_group_id
;
566 $fieldId = $crmDAO->civicrm_custom_field_id
;
567 if ($crmDAO->civicrm_custom_group_is_multiple
) {
568 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
570 // create an array for groups if it does not exist
571 if (!array_key_exists($groupID, $groupTree)) {
572 $groupTree[$groupID] = array();
573 $groupTree[$groupID]['id'] = $groupID;
575 // populate the group information
576 foreach ($toReturn['custom_group'] as $fieldName) {
577 $fullFieldName = "civicrm_custom_group_$fieldName";
578 if ($fieldName == 'id' ||
579 is_null($crmDAO->$fullFieldName)
584 // This is an old bit of code - per the CRM number & probably does not work reliably if
585 // that one contact sub-type exists.
586 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
587 $groupTree[$groupID]['subtype'] = self
::validateSubTypeByEntity($entityType, $subType);
589 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
591 $groupTree[$groupID]['fields'] = array();
593 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
596 // add the fields now (note - the query row will always contain a field)
597 // we only reset this once, since multiple values come is as multiple rows
598 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
599 $groupTree[$groupID]['fields'][$fieldId] = array();
602 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
603 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
604 // populate information for a custom field
605 foreach ($toReturn['custom_field'] as $fieldName) {
606 $fullFieldName = "civicrm_custom_field_$fieldName";
607 if ($fieldName == 'id' ||
608 is_null($crmDAO->$fullFieldName)
612 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
616 if (!empty($customValueTables)) {
617 $groupTree['info'] = array('tables' => $customValueTables);
620 $cache->set($cacheKey, $groupTree);
621 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
623 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
624 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
625 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
626 $singleFieldTables = array();
627 // now that we have all the groups and fields, lets get the values
628 // since we need to know the table and field names
629 // add info to groupTree
631 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
632 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
634 $select = $from = $where = array();
635 $groupTree['info']['where'] = NULL;
637 foreach ($groupTree['info']['tables'] as $table => $fields) {
638 $groupTree['info']['from'][] = $table;
640 "{$table}.id as {$table}_id",
641 "{$table}.entity_id as {$table}_entity_id",
643 foreach ($fields as $column => $dontCare) {
644 $select[] = "{$table}.{$column} as {$table}_{$column}";
646 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
648 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
649 if (in_array($table, $multipleFieldGroups) &&
650 self
::customGroupDataExistsForEntity($entityID, $table)
652 $entityMultipleSelectClauses[$table] = $select;
655 $singleFieldTables[] = $table;
656 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
661 if ($entityID && !empty($singleFieldTables)) {
662 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
664 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
665 if (!empty($multipleFieldTablesWithEntityData)) {
666 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
674 * Clean and validate the filter before it is used in a db query.
676 * @param string $entityType
677 * @param string $subType
680 * @throws \CRM_Core_Exception
681 * @throws \CiviCRM_API3_Exception
683 protected static function validateSubTypeByEntity($entityType, $subType) {
684 $subType = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
685 if (is_numeric($subType)) {
689 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypeInfo(TRUE);
690 $contactTypes = array_merge($contactTypes, array('Event' => 1));
692 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
693 throw new CRM_Core_Exception('Invalid Entity Filter');
695 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo($entityType, TRUE);
696 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant
::eventType());
697 if (!array_key_exists($subType, $subTypes)) {
698 throw new CRM_Core_Exception('Invalid Filter');
704 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
705 * a WHERE condition for rows that include $value. Use whereListHas().
707 * @param string $column
708 * @param string $value
709 * @param string $delimiter
713 static private function whereListHas($column, $value, $delimiter = CRM_Core_DAO
::VALUE_SEPARATOR
) {
714 $bareValue = trim($value, $delimiter); // ?
715 $escapedValue = CRM_Utils_Type
::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
716 return "($column LIKE \"$escapedValue\")";
720 * Check whether the custom group has any data for the given entity.
723 * @param int $entityID
724 * Id of entity for whom we are checking data for.
725 * @param string $table
726 * Table that we are checking.
728 * @param bool $getCount
731 * does this entity have data in this custom table
733 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
737 WHERE entity_id = $entityID
739 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
741 return $recordExists;
743 return $recordExists ?
TRUE : FALSE;
747 * Build the group tree for Custom fields which are not 'is_multiple'
749 * The combination of all these fields in one query with a 'using' join was not working for
750 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
751 * mechanism as it seemed to be acceptable in this context
753 * @param array $groupTree
754 * (reference) group tree array which is being built.
755 * @param int $entityID
756 * Id of entity for whom the tree is being build up.
757 * @param array $entitySingleSelectClauses
758 * Array of select clauses relevant to the entity.
759 * @param array $singleFieldTablesWithEntityData
760 * Array of tables in which this entity has data.
762 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
763 $select = implode(', ', $entitySingleSelectClauses);
764 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
765 foreach ($singleFieldTablesWithEntityData as $table) {
766 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
772 WHERE first.entity_id = $entityID
774 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
778 * Build the group tree for Custom fields which are 'is_multiple'
780 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
782 * @param array $groupTree
783 * (reference) group tree array which is being built.
784 * @param int $entityID
785 * Id of entity for whom the tree is being build up.
786 * @param array $entityMultipleSelectClauses
787 * Array of select clauses relevant to the entity.
788 * @param array $multipleFieldTablesWithEntityData
789 * Array of tables in which this entity has data.
790 * @param varchar $singleRecord
791 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
793 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
794 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
795 $select = implode(',', $selectClauses);
799 WHERE entity_id = $entityID
802 $offset = $singleRecord - 1;
803 $query .= " LIMIT {$offset}, 1";
805 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table), $singleRecord);
810 * Build the tree entity data - starting from a query retrieving the custom fields build the group
811 * tree data for the relevant entity (entity is included in the query).
813 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
815 * @param array $groupTree
816 * (reference) group tree array which is being built.
817 * @param string $query
818 * @param array $includedTables
819 * Tables to include - required because the function (for historical reasons).
820 * iterates through the group tree
821 * @param varchar $singleRecord
822 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
824 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
825 $dao = CRM_Core_DAO
::executeQuery($query);
826 while ($dao->fetch()) {
827 foreach ($groupTree as $groupID => $group) {
828 if ($groupID === 'info') {
831 $table = $groupTree[$groupID]['table_name'];
832 //working from the groupTree instead of the table list means we have to iterate & exclude.
833 // this could possibly be re-written as other parts of the function have been refactored
834 // for now we just check if the given table is to be included in this function
835 if (!in_array($table, $includedTables)) {
838 foreach ($group['fields'] as $fieldID => $dontCare) {
839 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
846 * Build the entity-specific custom data into the group tree on a per-field basis
849 * Object representing the custom field to be populated into the groupTree.
850 * @param array $groupTree
851 * (reference) the group tree being build.
852 * @param string $table
854 * @param int $groupID
856 * @param int $fieldID
858 * @param varchar $singleRecord
859 * holds 'new' or id if loading view/edit/copy for a single record.
861 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
862 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
863 $idName = "{$table}_id";
864 $fieldName = "{$table}_{$column}";
865 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
866 if ($dataType == 'File') {
867 if (isset($dao->$fieldName)) {
868 $config = CRM_Core_Config
::singleton();
869 $fileDAO = new CRM_Core_DAO_File();
870 $fileDAO->id
= $dao->$fieldName;
872 if ($fileDAO->find(TRUE)) {
873 $entityIDName = "{$table}_entity_id";
874 $customValue['id'] = $dao->$idName;
875 $customValue['data'] = $fileDAO->uri
;
876 $customValue['fid'] = $fileDAO->id
;
877 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
878 $customValue['displayURL'] = NULL;
879 $deleteExtra = ts('Are you sure you want to delete attached file.');
881 CRM_Core_Action
::DELETE
=> array(
882 'name' => ts('Delete Attached File'),
883 'url' => 'civicrm/file',
884 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
885 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
886 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
889 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
890 CRM_Core_Action
::DELETE
,
892 'id' => $fileDAO->id
,
893 'eid' => $dao->$entityIDName,
898 'file.manage.delete',
902 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
903 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
904 if ($fileDAO->mime_type
== "image/jpeg" ||
905 $fileDAO->mime_type
== "image/pjpeg" ||
906 $fileDAO->mime_type
== "image/gif" ||
907 $fileDAO->mime_type
== "image/x-png" ||
908 $fileDAO->mime_type
== "image/png"
910 $customValue['displayURL'] = $customValue['fileURL'];
911 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
916 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
918 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId, NULL, NULL);
919 if ($path && file_exists($path)) {
920 list($imageWidth, $imageHeight) = getimagesize($path);
921 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
922 $customValue['imageThumbWidth'] = $imageThumbWidth;
923 $customValue['imageThumbHeight'] = $imageThumbHeight;
929 $customValue = array(
930 'id' => $dao->$idName,
936 $customValue = array(
937 'id' => $dao->$idName,
938 'data' => $dao->$fieldName,
942 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
943 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
945 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
946 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array($singleRecord => $customValue);
948 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
949 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
952 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
957 * Get the group title.
965 public static function getTitle($id) {
966 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
970 * Get custom group details for a group.
972 * An array containing custom group details (including their custom field) is returned.
974 * @param int $groupId
975 * Group id whose details are needed.
976 * @param bool $searchable
977 * Is this field searchable.
978 * @param array $extends
979 * Which table does it extend if any.
981 * @param null $inSelector
984 * array consisting of all group and field details
986 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
988 $groupTree = array();
989 $select = $from = $where = $orderBy = '';
991 $tableData = array();
993 // using tableData to build the queryString
995 'civicrm_custom_field' => array(
1019 'civicrm_custom_group' => array(
1026 'collapse_adv_display',
1028 'extends_entity_column_value',
1036 foreach ($tableData as $tableName => $tableColumn) {
1037 foreach ($tableColumn as $columnName) {
1038 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
1041 $select = 'SELECT ' . implode(', ', $s);
1043 // from, where, order by
1044 $from = " FROM civicrm_custom_field, civicrm_custom_group";
1045 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
1046 AND civicrm_custom_group.is_active = 1
1047 AND civicrm_custom_field.is_active = 1 ";
1049 $params[1] = array($groupId, 'Integer');
1050 $where .= " AND civicrm_custom_group.id = %1";
1054 $where .= " AND civicrm_custom_field.is_searchable = 1";
1058 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
1063 foreach ($extends as $e) {
1064 $clause[] = "civicrm_custom_group.extends = '$e'";
1066 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1068 //include case activities customdata if case is enabled
1069 if (in_array('Activity', $extends)) {
1070 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1071 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1072 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
1076 // ensure that the user has access to these custom groups
1078 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1079 'civicrm_custom_group.'
1082 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1084 // final query string
1085 $queryString = $select . $from . $where . $orderBy;
1088 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1091 while ($crmDAO->fetch()) {
1092 $groupId = $crmDAO->civicrm_custom_group_id
;
1093 $fieldId = $crmDAO->civicrm_custom_field_id
;
1095 // create an array for groups if it does not exist
1096 if (!array_key_exists($groupId, $groupTree)) {
1097 $groupTree[$groupId] = array();
1098 $groupTree[$groupId]['id'] = $groupId;
1100 foreach ($tableData['civicrm_custom_group'] as $v) {
1101 $fullField = "civicrm_custom_group_" . $v;
1103 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1107 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1110 $groupTree[$groupId]['fields'] = array();
1113 // add the fields now (note - the query row will always contain a field)
1114 $groupTree[$groupId]['fields'][$fieldId] = array();
1115 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1117 foreach ($tableData['civicrm_custom_field'] as $v) {
1118 $fullField = "civicrm_custom_field_" . $v;
1119 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1122 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1130 * @param $entityType
1132 * @param string $cidToken
1136 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1138 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1140 // get 'Tab' and 'Tab with table' groups
1141 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1142 $customGroupDAO->whereAdd("is_active = 1");
1144 // add whereAdd for entity type
1145 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1149 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1150 $customGroupDAO->whereAdd($permissionClause);
1153 $customGroupDAO->orderBy('weight');
1154 $customGroupDAO->find();
1156 // process each group with menu tab
1157 while ($customGroupDAO->fetch()) {
1159 $group['id'] = $customGroupDAO->id
;
1160 $group['path'] = $path;
1161 $group['title'] = "$customGroupDAO->title";
1162 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1163 $group['extra'] = array('gid' => $customGroupDAO->id
);
1164 $group['table_name'] = $customGroupDAO->table_name
;
1165 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1173 * Get the table name for the entity type
1174 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1175 * tableName is 'civicrm_contact'
1177 * @param string $entityType
1178 * What entity are we extending here ?.
1183 * @see _apachesolr_civiAttachments_dereference_file_parent
1185 public static function getTableNameByEntityName($entityType) {
1187 switch ($entityType) {
1191 case 'Organization':
1192 $tableName = 'civicrm_contact';
1195 case 'Contribution':
1196 $tableName = 'civicrm_contribution';
1200 $tableName = 'civicrm_group';
1203 // DRAFTING: Verify if we cannot make it pluggable
1206 $tableName = 'civicrm_activity';
1209 case 'Relationship':
1210 $tableName = 'civicrm_relationship';
1214 $tableName = 'civicrm_membership';
1218 $tableName = 'civicrm_participant';
1222 $tableName = 'civicrm_event';
1226 $tableName = 'civicrm_grant';
1229 // need to add cases for Location, Address
1236 * Get a list of custom groups which extend a given entity type.
1237 * If there are custom-groups which only apply to certain subtypes,
1238 * those WILL be included.
1240 * @param string $entityType
1242 * @return CRM_Core_DAO_CustomGroup
1244 public static function getAllCustomGroupsByBaseEntity($entityType) {
1245 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1246 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1247 return $customGroupDAO;
1251 * Add the whereAdd clause for the DAO depending on the type of entity
1252 * the custom group is extending.
1254 * @param object $customGroupDAO
1255 * @param string $entityType
1256 * What entity are we extending here ?.
1258 * @param int $entityID
1259 * @param bool $allSubtypes
1261 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1262 $addSubtypeClause = FALSE;
1263 // This function isn't really accessible with user data but since the string
1264 // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless
1266 $entityType = CRM_Core_DAO
::escapeString($entityType);
1268 switch ($entityType) {
1270 // if contact, get all related to contact
1271 $extendList = "'Contact','Individual','Household','Organization'";
1272 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1273 if (!$allSubtypes) {
1274 $addSubtypeClause = TRUE;
1280 case 'Organization':
1281 // is I/H/O then get I/H/O and contact
1282 $extendList = "'Contact','$entityType'";
1283 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1284 if (!$allSubtypes) {
1285 $addSubtypeClause = TRUE;
1290 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1294 if ($addSubtypeClause) {
1295 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1297 if (!empty($csType)) {
1298 $subtypeClause = array();
1299 foreach ($csType as $subtype) {
1300 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1301 CRM_Core_DAO
::VALUE_SEPARATOR
;
1302 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1304 $subtypeClause[] = "extends_entity_column_value IS NULL";
1305 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1309 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1315 * Delete the Custom Group.
1317 * @param CRM_Core_BAO_CustomGroup $group
1318 * Custom group object.
1319 * @param bool $force
1320 * whether to force the deletion, even if there are custom fields.
1323 * False if field exists for this group, true if group gets deleted.
1325 public static function deleteGroup($group, $force = FALSE) {
1327 //check whether this contain any custom fields
1328 $customField = new CRM_Core_DAO_CustomField();
1329 $customField->custom_group_id
= $group->id
;
1330 $customField->find();
1332 // return early if there are custom fields and we're not
1333 // forcing the delete, otherwise delete the fields one by one
1334 while ($customField->fetch()) {
1338 CRM_Core_BAO_CustomField
::deleteField($customField);
1341 // drop the table associated with this custom group
1342 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1344 //delete custom group
1347 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1355 * @param array $groupTree
1356 * @param array $defaults
1357 * @param bool $viewMode
1358 * @param bool $inactiveNeeded
1359 * @param int $action
1361 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1362 foreach ($groupTree as $id => $group) {
1363 if (!isset($group['fields'])) {
1366 foreach ($group['fields'] as $field) {
1367 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1368 $value = $field['element_value'];
1370 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1371 ($action != CRM_Core_Action
::UPDATE ||
1373 !array_key_exists('element_value', $field)
1376 $value = $viewMode ?
NULL : $field['default_value'];
1382 if (empty($field['element_name'])) {
1386 $elementName = $field['element_name'];
1388 switch ($field['html_type']) {
1389 case 'Multi-Select':
1391 $defaults[$elementName] = array();
1392 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1394 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1395 if (isset($value)) {
1396 foreach ($customOption as $customValue => $customLabel) {
1397 if (in_array($customValue, $checkedData)) {
1398 if ($field['html_type'] == 'CheckBox') {
1399 $defaults[$elementName][$customValue] = 1;
1402 $defaults[$elementName][$customValue] = $customValue;
1406 $defaults[$elementName][$customValue] = 0;
1412 if (isset($field['customValue']['data'])) {
1413 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1414 foreach ($customOption as $val) {
1415 if (in_array($val['value'], $checkedData)) {
1416 if ($field['html_type'] == 'CheckBox') {
1417 $defaults[$elementName][$val['value']] = 1;
1420 $defaults[$elementName][$val['value']] = $val['value'];
1424 $defaults[$elementName][$val['value']] = 0;
1429 if (is_array($value) && count($value)) {
1430 CRM_Utils_Array
::formatArrayKeys($value);
1431 $checkedValue = $value;
1434 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1436 foreach ($customOption as $val) {
1437 if (in_array($val['value'], $checkedValue)) {
1438 if ($field['html_type'] == 'CheckBox') {
1439 $defaults[$elementName][$val['value']] = 1;
1442 $defaults[$elementName][$val['value']] = $val['value'];
1450 case 'Multi-Select Country':
1451 case 'Multi-Select State/Province':
1452 if (isset($value)) {
1453 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1454 foreach ($checkedValue as $val) {
1456 $defaults[$elementName][$val] = $val;
1462 case 'Select Country':
1464 $defaults[$elementName] = $value;
1467 $config = CRM_Core_Config
::singleton();
1468 $defaults[$elementName] = $config->defaultContactCountry
;
1473 if ($field['data_type'] == "Float") {
1474 $defaults[$elementName] = (float) $value;
1476 elseif ($field['data_type'] == 'Money' &&
1477 $field['html_type'] == 'Text'
1479 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1482 $defaults[$elementName] = $value;
1490 * PostProcess function.
1492 * @param array $groupTree
1493 * @param array $params
1494 * @param bool $skipFile
1496 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1497 // Get the Custom form values and groupTree
1498 // first reset all checkbox and radio data
1499 foreach ($groupTree as $groupID => $group) {
1500 if ($groupID === 'info') {
1503 foreach ($group['fields'] as $field) {
1504 $fieldId = $field['id'];
1506 //added Multi-Select option in the below if-statement
1507 if ($field['html_type'] == 'CheckBox' ||
1508 $field['html_type'] == 'Radio' ||
1509 $field['html_type'] == 'Multi-Select'
1511 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1515 foreach ($params as $key => $val) {
1516 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1517 $match[1] == $field['id']
1523 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1524 // field exists in db so populate value from "form".
1525 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1528 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1530 //added for CheckBox
1534 $customValue = array_keys($v);
1535 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1536 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1537 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1540 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1544 case 'Multi-Select':
1546 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1547 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1548 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1551 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1556 $date = CRM_Utils_Date
::processDate($v);
1557 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1565 //store the file in d/b
1566 $entityId = explode('=', $groupTree['info']['where'][0]);
1567 $fileParams = array('upload_date' => date('YmdHis'));
1569 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1570 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1573 $fileParams['uri'] = $v['name'];
1574 $fileParams['mime_type'] = $v['type'];
1575 CRM_Core_BAO_File
::filePostProcess($v['name'],
1576 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1577 $groupTree[$groupID]['table_name'],
1582 'custom_' . $fieldId,
1586 $defaults = array();
1587 $paramsFile = array(
1588 'entity_table' => $groupTree[$groupID]['table_name'],
1589 'entity_id' => $entityId[1],
1592 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1597 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1601 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1609 * Generic function to build all the form elements for a specific group tree.
1611 * @param CRM_Core_Form $form
1613 * @param array $groupTree
1614 * The group tree object.
1615 * @param bool $inactiveNeeded
1616 * Return inactive custom groups.
1617 * @param string $prefix
1618 * Prefix for custom grouptree assigned to template.
1620 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1621 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1623 foreach ($groupTree as $id => $group) {
1624 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1625 foreach ($group['fields'] as $field) {
1626 $required = CRM_Utils_Array
::value('is_required', $field);
1628 if ($field['data_type'] == 'File') {
1629 if (!empty($field['element_value']['data'])) {
1634 $fieldId = $field['id'];
1635 $elementName = $field['element_name'];
1636 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $required);
1642 * Extract the get params from the url, validate and store it in session.
1644 * @param CRM_Core_Form $form
1646 * @param string $type
1647 * The type of custom group we are using.
1651 public static function extractGetParams(&$form, $type) {
1656 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type);
1657 $customValue = array();
1665 foreach ($groupTree as $group) {
1666 if (!isset($group['fields'])) {
1669 foreach ($group['fields'] as $key => $field) {
1670 $fieldName = 'custom_' . $key;
1671 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1675 if (!in_array($field['html_type'], $htmlType) ||
1676 $field['data_type'] == 'Boolean'
1678 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1680 if ($field['html_type'] == 'CheckBox' ||
1681 $field['html_type'] == 'Multi-Select'
1683 $value = str_replace("|", ",", $value);
1684 $mulValues = explode(',', $value);
1685 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1687 foreach ($mulValues as $v1) {
1688 foreach ($customOption as $coID => $coValue) {
1689 if (strtolower(trim($coValue['label'])) ==
1690 strtolower(trim($v1))
1692 $val[$coValue['value']] = 1;
1704 elseif ($field['html_type'] == 'Select' ||
1705 ($field['html_type'] == 'Radio' &&
1706 $field['data_type'] != 'Boolean'
1709 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1710 foreach ($customOption as $customID => $coValue) {
1711 if (strtolower(trim($coValue['label'])) ==
1712 strtolower(trim($value))
1714 $value = $coValue['value'];
1719 elseif ($field['data_type'] == 'Date') {
1720 $valid = CRM_Utils_Rule
::date($value);
1724 $customValue[$fieldName] = $value;
1730 return $customValue;
1734 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1735 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1737 * @param int $customFieldId
1739 * @param array $removeCustomFieldTypes
1740 * Remove custom fields of a type eg: array("Individual") ;.
1743 * false if it matches else true
1745 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1746 $query = "SELECT cg.extends as extends
1747 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1748 WHERE cg.id = cf.custom_group_id
1750 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1752 $extends = CRM_Core_DAO
::singleValueQuery($query);
1754 if (in_array($extends, $removeCustomFieldTypes)) {
1766 public static function mapTableName($table) {
1771 case 'Organization':
1772 return 'civicrm_contact';
1775 return 'civicrm_activity';
1778 return 'civicrm_group';
1780 case 'Contribution':
1781 return 'civicrm_contribution';
1783 case 'ContributionRecur':
1784 return 'civicrm_contribution_recur';
1786 case 'Relationship':
1787 return 'civicrm_relationship';
1790 return 'civicrm_event';
1793 return 'civicrm_membership';
1796 case 'ParticipantRole':
1797 case 'ParticipantEventName':
1798 case 'ParticipantEventType':
1799 return 'civicrm_participant';
1802 return 'civicrm_grant';
1805 return 'civicrm_pledge';
1808 return 'civicrm_address';
1811 return 'civicrm_campaign';
1815 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1816 $qParams = array(1 => array($table, 'String'));
1817 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1820 return 'civicrm_contact';
1823 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1824 if (array_key_exists($table, $extendObjs)) {
1825 return $extendObjs[$table];
1827 CRM_Core_Error
::fatal();
1835 public static function createTable($group) {
1837 'name' => $group->table_name
,
1838 'is_multiple' => $group->is_multiple ?
1 : 0,
1839 'extends_name' => self
::mapTableName($group->extends),
1842 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1844 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1848 * Function returns formatted groupTree, sothat form can be easily build in template
1850 * @param array $groupTree
1851 * @param int $groupCount
1852 * Group count by default 1, but can varry for multiple value custom data.
1853 * @param object $form
1857 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NULL) {
1858 $formattedGroupTree = array();
1859 $uploadNames = $formValues = array();
1861 // retrieve qf key from url
1862 $qfKey = CRM_Utils_Request
::retrieve('qf', 'String');
1864 // fetch submitted custom field values later use to set as a default values
1866 $submittedValues = CRM_Core_BAO_Cache
::getItem('custom data', $qfKey);
1869 foreach ($groupTree as $key => $value) {
1870 if ($key === 'info') {
1874 // add group information
1875 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1876 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1877 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1878 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1879 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1880 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1881 $formattedGroupTree[$key]['style'] = CRM_Utils_Array
::value('style', $value);
1883 // this params needed of bulding multiple values
1884 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1885 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1886 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1887 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1888 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1889 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1891 // add field information
1892 foreach ($value['fields'] as $k => $properties) {
1893 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1894 if (isset($properties['customValue']) &&
1895 !CRM_Utils_System
::isNull($properties['customValue']) &&
1896 !isset($properties['element_value'])
1898 if (isset($properties['customValue'][$groupCount])) {
1899 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1900 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1901 if ($properties['data_type'] == 'File') {
1902 $properties['element_value'] = $properties['customValue'][$groupCount];
1903 $uploadNames[] = $properties['element_name'];
1906 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1910 if ($value = CRM_Utils_Request
::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1911 $formValues[$properties['element_name']] = $value;
1913 elseif (isset($submittedValues[$properties['element_name']])) {
1914 $properties['element_value'] = $submittedValues[$properties['element_name']];
1916 unset($properties['customValue']);
1917 $formattedGroupTree[$key]['fields'][$k] = $properties;
1922 if (count($formValues)) {
1923 $qf = $form->get('qfKey');
1924 $form->assign('qfKey', $qf);
1925 CRM_Core_BAO_Cache
::setItem($formValues, 'custom data', $qf);
1928 // hack for field type File
1929 $formUploadNames = $form->get('uploadNames');
1930 if (is_array($formUploadNames)) {
1931 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1934 $form->set('uploadNames', $uploadNames);
1937 return $formattedGroupTree;
1941 * Build custom data view.
1943 * @param CRM_Core_Form|CRM_Core_Page $form
1945 * @param array $groupTree
1946 * @param bool $returnCount
1947 * True if customValue count needs to be returned.
1949 * @param null $prefix
1950 * @param int $customValueId
1951 * @param int $entityId
1954 * @throws \Exception
1956 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
1958 foreach ($groupTree as $key => $group) {
1959 if ($key === 'info') {
1963 foreach ($group['fields'] as $k => $properties) {
1964 $groupID = $group['id'];
1965 if (!empty($properties['customValue'])) {
1966 foreach ($properties['customValue'] as $values) {
1967 if (!empty($customValueId) && $customValueId != $values['id']) {
1970 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1971 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1972 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1973 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1974 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1975 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1976 $details[$groupID][$values['id']]['style'] = CRM_Utils_Array
::value('style', $group);
1977 $details[$groupID][$values['id']]['fields'][$k] = array(
1978 'field_title' => CRM_Utils_Array
::value('label', $properties),
1979 'field_type' => CRM_Utils_Array
::value('html_type', $properties),
1980 'field_data_type' => CRM_Utils_Array
::value('data_type', $properties),
1981 'field_value' => CRM_Core_BAO_CustomField
::displayValue($values['data'], $properties['id'], $entityId),
1982 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $properties),
1984 // editable = whether this set contains any non-read-only fields
1985 if (!isset($details[$groupID][$values['id']]['editable'])) {
1986 $details[$groupID][$values['id']]['editable'] = FALSE;
1988 if (empty($properties['is_view'])) {
1989 $details[$groupID][$values['id']]['editable'] = TRUE;
1991 // also return contact reference contact id if user has view all or edit all contacts perm
1992 if ((CRM_Core_Permission
::check('view all contacts') ||
1993 CRM_Core_Permission
::check('edit all contacts'))
1995 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1998 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
2003 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
2004 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
2005 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
2006 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
2007 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
2008 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
2009 $details[$groupID][0]['style'] = CRM_Utils_Array
::value('style', $group);
2010 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
2016 //return a single value count if group id is passed to function
2017 //else return a groupId and count mapped array
2019 return count($details[$gID]);
2022 $countValue = array();
2023 foreach ($details as $key => $value) {
2024 $countValue[$key] = count($details[$key]);
2030 $form->assign_by_ref("{$prefix}viewCustomData", $details);
2036 * Get the custom group titles by custom field ids.
2038 * @param array $fieldIds
2039 * Array of custom field ids.
2041 * @return array|NULL
2042 * array consisting of groups and fields labels with ids.
2044 public static function getGroupTitles($fieldIds) {
2045 if (!is_array($fieldIds) && empty($fieldIds)) {
2049 $groupLabels = array();
2050 $fIds = "(" . implode(',', $fieldIds) . ")";
2053 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2054 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2055 FROM civicrm_custom_group, civicrm_custom_field
2056 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2057 AND civicrm_custom_field.id IN {$fIds}";
2059 $dao = CRM_Core_DAO
::executeQuery($query);
2060 while ($dao->fetch()) {
2061 $groupLabels[$dao->fieldID
] = array(
2062 'fieldID' => $dao->fieldID
,
2063 'fieldLabel' => $dao->fieldLabel
,
2064 'groupID' => $dao->groupID
,
2065 'groupTitle' => $dao->groupTitle
,
2069 return $groupLabels;
2072 public static function dropAllTables() {
2073 $query = "SELECT table_name FROM civicrm_custom_group";
2074 $dao = CRM_Core_DAO
::executeQuery($query);
2076 while ($dao->fetch()) {
2077 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2078 CRM_Core_DAO
::executeQuery($query);
2083 * Check whether custom group is empty or not.
2089 * true if empty otherwise false.
2091 public static function isGroupEmpty($gID) {
2096 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2101 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2102 $value = CRM_Core_DAO
::singleValueQuery($query);
2104 if (empty($value)) {
2112 * Get the list of types for objects that a custom group extends to.
2114 * @param array $types
2115 * Var which should have the list appended.
2120 public static function getExtendedObjectTypes(&$types = array()) {
2121 static $flag = FALSE, $objTypes = array();
2124 $extendObjs = array();
2125 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2127 foreach ($extendObjs as $ovId => $ovValues) {
2128 if ($ovValues['description']) {
2129 // description is expected to be a callback func to subtypes
2130 list($callback, $args) = explode(';', trim($ovValues['description']));
2136 if (!is_array($args)) {
2137 CRM_Core_Error
::fatal('Arg is not of type array');
2140 list($className) = explode('::', $callback);
2141 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2144 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2150 $types = array_merge($types, $objTypes);
2155 * @param int $customGroupId
2156 * @param int $entityId
2160 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2161 //check whether the group is multiple
2162 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2163 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2164 $hasReachedMax = FALSE;
2166 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2168 if (!$maxMultiple) {
2169 $hasReachedMax = FALSE;
2172 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2173 //count the number of entries for a entity
2174 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2175 $params = array(1 => array($entityId, 'Integer'));
2176 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2178 if ($count >= $maxMultiple) {
2179 $hasReachedMax = TRUE;
2183 return $hasReachedMax;
2189 public static function getMultipleFieldGroup() {
2190 $multipleGroup = array();
2191 $dao = new CRM_Core_DAO_CustomGroup();
2192 $dao->is_multiple
= 1;
2193 $dao->is_active
= 1;
2195 while ($dao->fetch()) {
2196 $multipleGroup[$dao->id
] = $dao->title
;
2198 return $multipleGroup;