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 * DAO object on success, null otherwise
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'";
479 if (!empty($subTypes)) {
480 foreach ($subTypes as $key => $subType) {
481 $subTypeClauses[] = self
::whereListHas("civicrm_custom_group.extends_entity_column_value", self
::validateSubTypeByEntity($entityType, $subType));
483 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
485 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
489 WHERE civicrm_custom_group.is_active = 1
490 AND civicrm_custom_field.is_active = 1
491 AND civicrm_custom_group.extends IN ($in)
495 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
500 WHERE civicrm_custom_group.is_active = 1
501 AND civicrm_custom_field.is_active = 1
502 AND civicrm_custom_group.extends IN ($in)
505 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
511 // since we want a specific group id we add it to the where clause
512 $strWhere .= " AND civicrm_custom_group.id = %1";
513 $params[1] = array($groupID, 'Integer');
516 // since groupID is false we need to show all Inline groups
517 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
519 if ($checkPermission) {
520 // ensure that the user has access to these custom groups
521 $strWhere .= " AND " .
522 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
523 'civicrm_custom_group.'
527 if ($showPublicOnly && $is_public_version) {
528 $strWhere .= "AND civicrm_custom_group.is_public = 1";
532 ORDER BY civicrm_custom_group.weight,
533 civicrm_custom_group.title,
534 civicrm_custom_field.weight,
535 civicrm_custom_field.label
538 // final query string
539 $queryString = "$strSelect $strFrom $strWhere $orderBy";
541 // lets see if we can retrieve the groupTree from cache
542 $cacheString = $queryString;
544 $cacheString .= "_{$groupID}";
547 $cacheString .= "_Inline";
550 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
551 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
552 $cache = CRM_Utils_Cache
::singleton();
553 $tablesWithEntityData = array();
555 $groupTree = $cache->get($cacheKey);
556 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
559 if (empty($groupTree)) {
560 $groupTree = $multipleFieldGroups = array();
561 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
562 $customValueTables = array();
565 while ($crmDAO->fetch()) {
567 $groupID = $crmDAO->civicrm_custom_group_id
;
568 $fieldId = $crmDAO->civicrm_custom_field_id
;
569 if ($crmDAO->civicrm_custom_group_is_multiple
) {
570 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
572 // create an array for groups if it does not exist
573 if (!array_key_exists($groupID, $groupTree)) {
574 $groupTree[$groupID] = array();
575 $groupTree[$groupID]['id'] = $groupID;
577 // populate the group information
578 foreach ($toReturn['custom_group'] as $fieldName) {
579 $fullFieldName = "civicrm_custom_group_$fieldName";
580 if ($fieldName == 'id' ||
581 is_null($crmDAO->$fullFieldName)
586 // This is an old bit of code - per the CRM number & probably does not work reliably if
587 // that one contact sub-type exists.
588 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
589 $groupTree[$groupID]['subtype'] = self
::validateSubTypeByEntity($entityType, $subType);
591 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
593 $groupTree[$groupID]['fields'] = array();
595 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
598 // add the fields now (note - the query row will always contain a field)
599 // we only reset this once, since multiple values come is as multiple rows
600 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
601 $groupTree[$groupID]['fields'][$fieldId] = array();
604 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
605 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
606 // populate information for a custom field
607 foreach ($toReturn['custom_field'] as $fieldName) {
608 $fullFieldName = "civicrm_custom_field_$fieldName";
609 if ($fieldName == 'id' ||
610 is_null($crmDAO->$fullFieldName)
614 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
618 if (!empty($customValueTables)) {
619 $groupTree['info'] = array('tables' => $customValueTables);
622 $cache->set($cacheKey, $groupTree);
623 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
625 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
626 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
627 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
628 $singleFieldTables = array();
629 // now that we have all the groups and fields, lets get the values
630 // since we need to know the table and field names
631 // add info to groupTree
633 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
634 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
636 $select = $from = $where = array();
637 $groupTree['info']['where'] = NULL;
639 foreach ($groupTree['info']['tables'] as $table => $fields) {
640 $groupTree['info']['from'][] = $table;
642 "{$table}.id as {$table}_id",
643 "{$table}.entity_id as {$table}_entity_id",
645 foreach ($fields as $column => $dontCare) {
646 $select[] = "{$table}.{$column} as {$table}_{$column}";
648 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
650 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
651 if (in_array($table, $multipleFieldGroups) &&
652 self
::customGroupDataExistsForEntity($entityID, $table)
654 $entityMultipleSelectClauses[$table] = $select;
657 $singleFieldTables[] = $table;
658 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
663 if ($entityID && !empty($singleFieldTables)) {
664 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
666 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
667 if (!empty($multipleFieldTablesWithEntityData)) {
668 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
676 * Clean and validate the filter before it is used in a db query.
678 * @param string $entityType
679 * @param string $subType
682 * @throws \CRM_Core_Exception
683 * @throws \CiviCRM_API3_Exception
685 protected static function validateSubTypeByEntity($entityType, $subType) {
686 $subType = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
687 if (is_numeric($subType)) {
691 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypeInfo(TRUE);
692 $contactTypes = array_merge($contactTypes, array('Event' => 1));
694 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
695 throw new CRM_Core_Exception('Invalid Entity Filter');
697 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo($entityType, TRUE);
698 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant
::eventType());
699 if (!array_key_exists($subType, $subTypes)) {
700 throw new CRM_Core_Exception('Invalid Filter');
706 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
707 * a WHERE condition for rows that include $value. Use whereListHas().
709 * @param string $column
710 * @param string $value
711 * @param string $delimiter
715 static private function whereListHas($column, $value, $delimiter = CRM_Core_DAO
::VALUE_SEPARATOR
) {
716 $bareValue = trim($value, $delimiter); // ?
717 $escapedValue = CRM_Utils_Type
::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
718 return "($column LIKE \"$escapedValue\")";
722 * Check whether the custom group has any data for the given entity.
725 * @param int $entityID
726 * Id of entity for whom we are checking data for.
727 * @param string $table
728 * Table that we are checking.
730 * @param bool $getCount
733 * does this entity have data in this custom table
735 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
739 WHERE entity_id = $entityID
741 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
743 return $recordExists;
745 return $recordExists ?
TRUE : FALSE;
749 * Build the group tree for Custom fields which are not 'is_multiple'
751 * The combination of all these fields in one query with a 'using' join was not working for
752 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
753 * mechanism as it seemed to be acceptable in this context
755 * @param array $groupTree
756 * (reference) group tree array which is being built.
757 * @param int $entityID
758 * Id of entity for whom the tree is being build up.
759 * @param array $entitySingleSelectClauses
760 * Array of select clauses relevant to the entity.
761 * @param array $singleFieldTablesWithEntityData
762 * Array of tables in which this entity has data.
764 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
765 $select = implode(', ', $entitySingleSelectClauses);
766 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
767 foreach ($singleFieldTablesWithEntityData as $table) {
768 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
774 WHERE first.entity_id = $entityID
776 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
780 * Build the group tree for Custom fields which are 'is_multiple'
782 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
784 * @param array $groupTree
785 * (reference) group tree array which is being built.
786 * @param int $entityID
787 * Id of entity for whom the tree is being build up.
788 * @param array $entityMultipleSelectClauses
789 * Array of select clauses relevant to the entity.
790 * @param array $multipleFieldTablesWithEntityData
791 * Array of tables in which this entity has data.
792 * @param varchar $singleRecord
793 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
795 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
796 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
797 $select = implode(',', $selectClauses);
801 WHERE entity_id = $entityID
804 $offset = $singleRecord - 1;
805 $query .= " LIMIT {$offset}, 1";
807 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table), $singleRecord);
812 * Build the tree entity data - starting from a query retrieving the custom fields build the group
813 * tree data for the relevant entity (entity is included in the query).
815 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
817 * @param array $groupTree
818 * (reference) group tree array which is being built.
819 * @param string $query
820 * @param array $includedTables
821 * Tables to include - required because the function (for historical reasons).
822 * iterates through the group tree
823 * @param varchar $singleRecord
824 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
826 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
827 $dao = CRM_Core_DAO
::executeQuery($query);
828 while ($dao->fetch()) {
829 foreach ($groupTree as $groupID => $group) {
830 if ($groupID === 'info') {
833 $table = $groupTree[$groupID]['table_name'];
834 //working from the groupTree instead of the table list means we have to iterate & exclude.
835 // this could possibly be re-written as other parts of the function have been refactored
836 // for now we just check if the given table is to be included in this function
837 if (!in_array($table, $includedTables)) {
840 foreach ($group['fields'] as $fieldID => $dontCare) {
841 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
848 * Build the entity-specific custom data into the group tree on a per-field basis
851 * Object representing the custom field to be populated into the groupTree.
852 * @param array $groupTree
853 * (reference) the group tree being build.
854 * @param string $table
856 * @param int $groupID
858 * @param int $fieldID
860 * @param varchar $singleRecord
861 * holds 'new' or id if loading view/edit/copy for a single record.
863 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
864 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
865 $idName = "{$table}_id";
866 $fieldName = "{$table}_{$column}";
867 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
868 if ($dataType == 'File') {
869 if (isset($dao->$fieldName)) {
870 $config = CRM_Core_Config
::singleton();
871 $fileDAO = new CRM_Core_DAO_File();
872 $fileDAO->id
= $dao->$fieldName;
874 if ($fileDAO->find(TRUE)) {
875 $entityIDName = "{$table}_entity_id";
876 $customValue['id'] = $dao->$idName;
877 $customValue['data'] = $fileDAO->uri
;
878 $customValue['fid'] = $fileDAO->id
;
879 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
880 $customValue['displayURL'] = NULL;
881 $deleteExtra = ts('Are you sure you want to delete attached file.');
883 CRM_Core_Action
::DELETE
=> array(
884 'name' => ts('Delete Attached File'),
885 'url' => 'civicrm/file',
886 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
887 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
888 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
891 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
892 CRM_Core_Action
::DELETE
,
894 'id' => $fileDAO->id
,
895 'eid' => $dao->$entityIDName,
900 'file.manage.delete',
904 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
905 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
906 if ($fileDAO->mime_type
== "image/jpeg" ||
907 $fileDAO->mime_type
== "image/pjpeg" ||
908 $fileDAO->mime_type
== "image/gif" ||
909 $fileDAO->mime_type
== "image/x-png" ||
910 $fileDAO->mime_type
== "image/png"
912 $customValue['displayURL'] = $customValue['fileURL'];
913 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
918 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
920 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId, NULL, NULL);
921 if ($path && file_exists($path)) {
922 list($imageWidth, $imageHeight) = getimagesize($path);
923 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
924 $customValue['imageThumbWidth'] = $imageThumbWidth;
925 $customValue['imageThumbHeight'] = $imageThumbHeight;
931 $customValue = array(
932 'id' => $dao->$idName,
938 $customValue = array(
939 'id' => $dao->$idName,
940 'data' => $dao->$fieldName,
944 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
945 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
947 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
948 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array($singleRecord => $customValue);
950 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
951 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
954 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
959 * Get the group title.
967 public static function getTitle($id) {
968 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
972 * Get custom group details for a group.
974 * An array containing custom group details (including their custom field) is returned.
976 * @param int $groupId
977 * Group id whose details are needed.
978 * @param bool $searchable
979 * Is this field searchable.
980 * @param array $extends
981 * Which table does it extend if any.
983 * @param null $inSelector
986 * array consisting of all group and field details
988 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
990 $groupTree = array();
991 $select = $from = $where = $orderBy = '';
993 $tableData = array();
995 // using tableData to build the queryString
997 'civicrm_custom_field' => array(
1021 'civicrm_custom_group' => array(
1028 'collapse_adv_display',
1030 'extends_entity_column_value',
1038 foreach ($tableData as $tableName => $tableColumn) {
1039 foreach ($tableColumn as $columnName) {
1040 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
1043 $select = 'SELECT ' . implode(', ', $s);
1045 // from, where, order by
1046 $from = " FROM civicrm_custom_field, civicrm_custom_group";
1047 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
1048 AND civicrm_custom_group.is_active = 1
1049 AND civicrm_custom_field.is_active = 1 ";
1051 $params[1] = array($groupId, 'Integer');
1052 $where .= " AND civicrm_custom_group.id = %1";
1056 $where .= " AND civicrm_custom_field.is_searchable = 1";
1060 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
1065 foreach ($extends as $e) {
1066 $clause[] = "civicrm_custom_group.extends = '$e'";
1068 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1070 //include case activities customdata if case is enabled
1071 if (in_array('Activity', $extends)) {
1072 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1073 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1074 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
1078 // ensure that the user has access to these custom groups
1080 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1081 'civicrm_custom_group.'
1084 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1086 // final query string
1087 $queryString = $select . $from . $where . $orderBy;
1090 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1093 while ($crmDAO->fetch()) {
1094 $groupId = $crmDAO->civicrm_custom_group_id
;
1095 $fieldId = $crmDAO->civicrm_custom_field_id
;
1097 // create an array for groups if it does not exist
1098 if (!array_key_exists($groupId, $groupTree)) {
1099 $groupTree[$groupId] = array();
1100 $groupTree[$groupId]['id'] = $groupId;
1102 foreach ($tableData['civicrm_custom_group'] as $v) {
1103 $fullField = "civicrm_custom_group_" . $v;
1105 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1109 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1112 $groupTree[$groupId]['fields'] = array();
1115 // add the fields now (note - the query row will always contain a field)
1116 $groupTree[$groupId]['fields'][$fieldId] = array();
1117 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1119 foreach ($tableData['civicrm_custom_field'] as $v) {
1120 $fullField = "civicrm_custom_field_" . $v;
1121 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1124 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1132 * @param $entityType
1134 * @param string $cidToken
1138 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1140 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1142 // get 'Tab' and 'Tab with table' groups
1143 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1144 $customGroupDAO->whereAdd("is_active = 1");
1146 // add whereAdd for entity type
1147 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1151 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1152 $customGroupDAO->whereAdd($permissionClause);
1155 $customGroupDAO->orderBy('weight');
1156 $customGroupDAO->find();
1158 // process each group with menu tab
1159 while ($customGroupDAO->fetch()) {
1161 $group['id'] = $customGroupDAO->id
;
1162 $group['path'] = $path;
1163 $group['title'] = "$customGroupDAO->title";
1164 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1165 $group['extra'] = array('gid' => $customGroupDAO->id
);
1166 $group['table_name'] = $customGroupDAO->table_name
;
1167 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1175 * Get the table name for the entity type
1176 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1177 * tableName is 'civicrm_contact'
1179 * @param string $entityType
1180 * What entity are we extending here ?.
1185 * @see _apachesolr_civiAttachments_dereference_file_parent
1187 public static function getTableNameByEntityName($entityType) {
1189 switch ($entityType) {
1193 case 'Organization':
1194 $tableName = 'civicrm_contact';
1197 case 'Contribution':
1198 $tableName = 'civicrm_contribution';
1202 $tableName = 'civicrm_group';
1205 // DRAFTING: Verify if we cannot make it pluggable
1208 $tableName = 'civicrm_activity';
1211 case 'Relationship':
1212 $tableName = 'civicrm_relationship';
1216 $tableName = 'civicrm_membership';
1220 $tableName = 'civicrm_participant';
1224 $tableName = 'civicrm_event';
1228 $tableName = 'civicrm_grant';
1231 // need to add cases for Location, Address
1238 * Get a list of custom groups which extend a given entity type.
1239 * If there are custom-groups which only apply to certain subtypes,
1240 * those WILL be included.
1242 * @param string $entityType
1244 * @return CRM_Core_DAO_CustomGroup
1246 public static function getAllCustomGroupsByBaseEntity($entityType) {
1247 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1248 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1249 return $customGroupDAO;
1253 * Add the whereAdd clause for the DAO depending on the type of entity
1254 * the custom group is extending.
1256 * @param object $customGroupDAO
1257 * @param string $entityType
1258 * What entity are we extending here ?.
1260 * @param int $entityID
1261 * @param bool $allSubtypes
1263 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1264 $addSubtypeClause = FALSE;
1265 // This function isn't really accessible with user data but since the string
1266 // is not passed as a param to the query CRM_Core_DAO::escapeString seems like a harmless
1268 $entityType = CRM_Core_DAO
::escapeString($entityType);
1270 switch ($entityType) {
1272 // if contact, get all related to contact
1273 $extendList = "'Contact','Individual','Household','Organization'";
1274 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1275 if (!$allSubtypes) {
1276 $addSubtypeClause = TRUE;
1282 case 'Organization':
1283 // is I/H/O then get I/H/O and contact
1284 $extendList = "'Contact','$entityType'";
1285 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1286 if (!$allSubtypes) {
1287 $addSubtypeClause = TRUE;
1292 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1296 if ($addSubtypeClause) {
1297 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1299 if (!empty($csType)) {
1300 $subtypeClause = array();
1301 foreach ($csType as $subtype) {
1302 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1303 CRM_Core_DAO
::VALUE_SEPARATOR
;
1304 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1306 $subtypeClause[] = "extends_entity_column_value IS NULL";
1307 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1311 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1317 * Delete the Custom Group.
1319 * @param CRM_Core_BAO_CustomGroup $group
1320 * Custom group object.
1321 * @param bool $force
1322 * whether to force the deletion, even if there are custom fields.
1325 * False if field exists for this group, true if group gets deleted.
1327 public static function deleteGroup($group, $force = FALSE) {
1329 //check whether this contain any custom fields
1330 $customField = new CRM_Core_DAO_CustomField();
1331 $customField->custom_group_id
= $group->id
;
1332 $customField->find();
1334 // return early if there are custom fields and we're not
1335 // forcing the delete, otherwise delete the fields one by one
1336 while ($customField->fetch()) {
1340 CRM_Core_BAO_CustomField
::deleteField($customField);
1343 // drop the table associated with this custom group
1344 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1346 //delete custom group
1349 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1357 * @param array $groupTree
1358 * @param array $defaults
1359 * @param bool $viewMode
1360 * @param bool $inactiveNeeded
1361 * @param int $action
1363 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1364 foreach ($groupTree as $id => $group) {
1365 if (!isset($group['fields'])) {
1368 foreach ($group['fields'] as $field) {
1369 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1370 $value = $field['element_value'];
1372 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1373 ($action != CRM_Core_Action
::UPDATE ||
1375 !array_key_exists('element_value', $field)
1378 $value = $viewMode ?
NULL : $field['default_value'];
1384 if (empty($field['element_name'])) {
1388 $elementName = $field['element_name'];
1390 switch ($field['html_type']) {
1391 case 'Multi-Select':
1393 $defaults[$elementName] = array();
1394 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1396 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1397 if (isset($value)) {
1398 foreach ($customOption as $customValue => $customLabel) {
1399 if (in_array($customValue, $checkedData)) {
1400 if ($field['html_type'] == 'CheckBox') {
1401 $defaults[$elementName][$customValue] = 1;
1404 $defaults[$elementName][$customValue] = $customValue;
1408 $defaults[$elementName][$customValue] = 0;
1414 if (isset($field['customValue']['data'])) {
1415 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1416 foreach ($customOption as $val) {
1417 if (in_array($val['value'], $checkedData)) {
1418 if ($field['html_type'] == 'CheckBox') {
1419 $defaults[$elementName][$val['value']] = 1;
1422 $defaults[$elementName][$val['value']] = $val['value'];
1426 $defaults[$elementName][$val['value']] = 0;
1431 if (is_array($value) && count($value)) {
1432 CRM_Utils_Array
::formatArrayKeys($value);
1433 $checkedValue = $value;
1436 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1438 foreach ($customOption as $val) {
1439 if (in_array($val['value'], $checkedValue)) {
1440 if ($field['html_type'] == 'CheckBox') {
1441 $defaults[$elementName][$val['value']] = 1;
1444 $defaults[$elementName][$val['value']] = $val['value'];
1452 case 'Multi-Select Country':
1453 case 'Multi-Select State/Province':
1454 if (isset($value)) {
1455 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1456 foreach ($checkedValue as $val) {
1458 $defaults[$elementName][$val] = $val;
1464 case 'Select Country':
1466 $defaults[$elementName] = $value;
1469 $config = CRM_Core_Config
::singleton();
1470 $defaults[$elementName] = $config->defaultContactCountry
;
1475 if ($field['data_type'] == "Float") {
1476 $defaults[$elementName] = (float) $value;
1478 elseif ($field['data_type'] == 'Money' &&
1479 $field['html_type'] == 'Text'
1481 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1484 $defaults[$elementName] = $value;
1492 * PostProcess function.
1494 * @param array $groupTree
1495 * @param array $params
1496 * @param bool $skipFile
1498 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1499 // Get the Custom form values and groupTree
1500 // first reset all checkbox and radio data
1501 foreach ($groupTree as $groupID => $group) {
1502 if ($groupID === 'info') {
1505 foreach ($group['fields'] as $field) {
1506 $fieldId = $field['id'];
1508 //added Multi-Select option in the below if-statement
1509 if ($field['html_type'] == 'CheckBox' ||
1510 $field['html_type'] == 'Radio' ||
1511 $field['html_type'] == 'Multi-Select'
1513 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1517 foreach ($params as $key => $val) {
1518 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1519 $match[1] == $field['id']
1525 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1526 // field exists in db so populate value from "form".
1527 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1530 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1532 //added for CheckBox
1536 $customValue = array_keys($v);
1537 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1538 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1539 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1542 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1546 case 'Multi-Select':
1548 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1549 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1550 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1553 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1558 $date = CRM_Utils_Date
::processDate($v);
1559 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1567 //store the file in d/b
1568 $entityId = explode('=', $groupTree['info']['where'][0]);
1569 $fileParams = array('upload_date' => date('YmdHis'));
1571 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1572 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1575 $fileParams['uri'] = $v['name'];
1576 $fileParams['mime_type'] = $v['type'];
1577 CRM_Core_BAO_File
::filePostProcess($v['name'],
1578 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1579 $groupTree[$groupID]['table_name'],
1584 'custom_' . $fieldId,
1588 $defaults = array();
1589 $paramsFile = array(
1590 'entity_table' => $groupTree[$groupID]['table_name'],
1591 'entity_id' => $entityId[1],
1594 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1599 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1603 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1611 * Generic function to build all the form elements for a specific group tree.
1613 * @param CRM_Core_Form $form
1615 * @param array $groupTree
1616 * The group tree object.
1617 * @param bool $inactiveNeeded
1618 * Return inactive custom groups.
1619 * @param string $prefix
1620 * Prefix for custom grouptree assigned to template.
1622 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1623 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1625 foreach ($groupTree as $id => $group) {
1626 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1627 foreach ($group['fields'] as $field) {
1628 $required = CRM_Utils_Array
::value('is_required', $field);
1630 if ($field['data_type'] == 'File') {
1631 if (!empty($field['element_value']['data'])) {
1636 $fieldId = $field['id'];
1637 $elementName = $field['element_name'];
1638 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $required);
1644 * Extract the get params from the url, validate and store it in session.
1646 * @param CRM_Core_Form $form
1648 * @param string $type
1649 * The type of custom group we are using.
1653 public static function extractGetParams(&$form, $type) {
1658 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type);
1659 $customValue = array();
1667 foreach ($groupTree as $group) {
1668 if (!isset($group['fields'])) {
1671 foreach ($group['fields'] as $key => $field) {
1672 $fieldName = 'custom_' . $key;
1673 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1677 if (!in_array($field['html_type'], $htmlType) ||
1678 $field['data_type'] == 'Boolean'
1680 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1682 if ($field['html_type'] == 'CheckBox' ||
1683 $field['html_type'] == 'Multi-Select'
1685 $value = str_replace("|", ",", $value);
1686 $mulValues = explode(',', $value);
1687 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1689 foreach ($mulValues as $v1) {
1690 foreach ($customOption as $coID => $coValue) {
1691 if (strtolower(trim($coValue['label'])) ==
1692 strtolower(trim($v1))
1694 $val[$coValue['value']] = 1;
1706 elseif ($field['html_type'] == 'Select' ||
1707 ($field['html_type'] == 'Radio' &&
1708 $field['data_type'] != 'Boolean'
1711 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1712 foreach ($customOption as $customID => $coValue) {
1713 if (strtolower(trim($coValue['label'])) ==
1714 strtolower(trim($value))
1716 $value = $coValue['value'];
1721 elseif ($field['data_type'] == 'Date') {
1722 $valid = CRM_Utils_Rule
::date($value);
1726 $customValue[$fieldName] = $value;
1732 return $customValue;
1736 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1737 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1739 * @param int $customFieldId
1741 * @param array $removeCustomFieldTypes
1742 * Remove custom fields of a type eg: array("Individual") ;.
1745 * false if it matches else true
1747 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1748 $query = "SELECT cg.extends as extends
1749 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1750 WHERE cg.id = cf.custom_group_id
1752 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1754 $extends = CRM_Core_DAO
::singleValueQuery($query);
1756 if (in_array($extends, $removeCustomFieldTypes)) {
1768 public static function mapTableName($table) {
1773 case 'Organization':
1774 return 'civicrm_contact';
1777 return 'civicrm_activity';
1780 return 'civicrm_group';
1782 case 'Contribution':
1783 return 'civicrm_contribution';
1785 case 'ContributionRecur':
1786 return 'civicrm_contribution_recur';
1788 case 'Relationship':
1789 return 'civicrm_relationship';
1792 return 'civicrm_event';
1795 return 'civicrm_membership';
1798 case 'ParticipantRole':
1799 case 'ParticipantEventName':
1800 case 'ParticipantEventType':
1801 return 'civicrm_participant';
1804 return 'civicrm_grant';
1807 return 'civicrm_pledge';
1810 return 'civicrm_address';
1813 return 'civicrm_campaign';
1817 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1818 $qParams = array(1 => array($table, 'String'));
1819 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1822 return 'civicrm_contact';
1825 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1826 if (array_key_exists($table, $extendObjs)) {
1827 return $extendObjs[$table];
1829 CRM_Core_Error
::fatal();
1837 public static function createTable($group) {
1839 'name' => $group->table_name
,
1840 'is_multiple' => $group->is_multiple ?
1 : 0,
1841 'extends_name' => self
::mapTableName($group->extends),
1844 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1846 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1850 * Function returns formatted groupTree, sothat form can be easily build in template
1852 * @param array $groupTree
1853 * @param int $groupCount
1854 * Group count by default 1, but can varry for multiple value custom data.
1855 * @param object $form
1859 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NULL) {
1860 $formattedGroupTree = array();
1861 $uploadNames = $formValues = array();
1863 // retrieve qf key from url
1864 $qfKey = CRM_Utils_Request
::retrieve('qf', 'String');
1866 // fetch submitted custom field values later use to set as a default values
1868 $submittedValues = CRM_Core_BAO_Cache
::getItem('custom data', $qfKey);
1871 foreach ($groupTree as $key => $value) {
1872 if ($key === 'info') {
1876 // add group information
1877 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1878 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1879 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1880 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1881 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1882 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1883 $formattedGroupTree[$key]['style'] = CRM_Utils_Array
::value('style', $value);
1885 // this params needed of bulding multiple values
1886 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1887 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1888 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1889 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1890 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1891 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1893 // add field information
1894 foreach ($value['fields'] as $k => $properties) {
1895 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1896 if (isset($properties['customValue']) &&
1897 !CRM_Utils_System
::isNull($properties['customValue']) &&
1898 !isset($properties['element_value'])
1900 if (isset($properties['customValue'][$groupCount])) {
1901 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1902 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1903 if ($properties['data_type'] == 'File') {
1904 $properties['element_value'] = $properties['customValue'][$groupCount];
1905 $uploadNames[] = $properties['element_name'];
1908 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1912 if ($value = CRM_Utils_Request
::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1913 $formValues[$properties['element_name']] = $value;
1915 elseif (isset($submittedValues[$properties['element_name']])) {
1916 $properties['element_value'] = $submittedValues[$properties['element_name']];
1918 unset($properties['customValue']);
1919 $formattedGroupTree[$key]['fields'][$k] = $properties;
1924 if (count($formValues)) {
1925 $qf = $form->get('qfKey');
1926 $form->assign('qfKey', $qf);
1927 CRM_Core_BAO_Cache
::setItem($formValues, 'custom data', $qf);
1930 // hack for field type File
1931 $formUploadNames = $form->get('uploadNames');
1932 if (is_array($formUploadNames)) {
1933 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1936 $form->set('uploadNames', $uploadNames);
1939 return $formattedGroupTree;
1943 * Build custom data view.
1945 * @param CRM_Core_Form|CRM_Core_Page $form
1947 * @param array $groupTree
1948 * @param bool $returnCount
1949 * True if customValue count needs to be returned.
1951 * @param null $prefix
1952 * @param int $customValueId
1953 * @param int $entityId
1956 * @throws \Exception
1958 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
1960 foreach ($groupTree as $key => $group) {
1961 if ($key === 'info') {
1965 foreach ($group['fields'] as $k => $properties) {
1966 $groupID = $group['id'];
1967 if (!empty($properties['customValue'])) {
1968 foreach ($properties['customValue'] as $values) {
1969 if (!empty($customValueId) && $customValueId != $values['id']) {
1972 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1973 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1974 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1975 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1976 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1977 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1978 $details[$groupID][$values['id']]['style'] = CRM_Utils_Array
::value('style', $group);
1979 $details[$groupID][$values['id']]['fields'][$k] = array(
1980 'field_title' => CRM_Utils_Array
::value('label', $properties),
1981 'field_type' => CRM_Utils_Array
::value('html_type', $properties),
1982 'field_data_type' => CRM_Utils_Array
::value('data_type', $properties),
1983 'field_value' => CRM_Core_BAO_CustomField
::displayValue($values['data'], $properties['id'], $entityId),
1984 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $properties),
1986 // editable = whether this set contains any non-read-only fields
1987 if (!isset($details[$groupID][$values['id']]['editable'])) {
1988 $details[$groupID][$values['id']]['editable'] = FALSE;
1990 if (empty($properties['is_view'])) {
1991 $details[$groupID][$values['id']]['editable'] = TRUE;
1993 // also return contact reference contact id if user has view all or edit all contacts perm
1994 if ((CRM_Core_Permission
::check('view all contacts') ||
1995 CRM_Core_Permission
::check('edit all contacts'))
1997 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
2000 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
2005 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
2006 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
2007 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
2008 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
2009 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
2010 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
2011 $details[$groupID][0]['style'] = CRM_Utils_Array
::value('style', $group);
2012 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
2018 //return a single value count if group id is passed to function
2019 //else return a groupId and count mapped array
2021 return count($details[$gID]);
2024 $countValue = array();
2025 foreach ($details as $key => $value) {
2026 $countValue[$key] = count($details[$key]);
2032 $form->assign_by_ref("{$prefix}viewCustomData", $details);
2038 * Get the custom group titles by custom field ids.
2040 * @param array $fieldIds
2041 * Array of custom field ids.
2043 * @return array|NULL
2044 * array consisting of groups and fields labels with ids.
2046 public static function getGroupTitles($fieldIds) {
2047 if (!is_array($fieldIds) && empty($fieldIds)) {
2051 $groupLabels = array();
2052 $fIds = "(" . implode(',', $fieldIds) . ")";
2055 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2056 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2057 FROM civicrm_custom_group, civicrm_custom_field
2058 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2059 AND civicrm_custom_field.id IN {$fIds}";
2061 $dao = CRM_Core_DAO
::executeQuery($query);
2062 while ($dao->fetch()) {
2063 $groupLabels[$dao->fieldID
] = array(
2064 'fieldID' => $dao->fieldID
,
2065 'fieldLabel' => $dao->fieldLabel
,
2066 'groupID' => $dao->groupID
,
2067 'groupTitle' => $dao->groupTitle
,
2071 return $groupLabels;
2074 public static function dropAllTables() {
2075 $query = "SELECT table_name FROM civicrm_custom_group";
2076 $dao = CRM_Core_DAO
::executeQuery($query);
2078 while ($dao->fetch()) {
2079 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2080 CRM_Core_DAO
::executeQuery($query);
2085 * Check whether custom group is empty or not.
2091 * true if empty otherwise false.
2093 public static function isGroupEmpty($gID) {
2098 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2103 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2104 $value = CRM_Core_DAO
::singleValueQuery($query);
2106 if (empty($value)) {
2114 * Get the list of types for objects that a custom group extends to.
2116 * @param array $types
2117 * Var which should have the list appended.
2122 public static function getExtendedObjectTypes(&$types = array()) {
2123 static $flag = FALSE, $objTypes = array();
2126 $extendObjs = array();
2127 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2129 foreach ($extendObjs as $ovId => $ovValues) {
2130 if ($ovValues['description']) {
2131 // description is expected to be a callback func to subtypes
2132 list($callback, $args) = explode(';', trim($ovValues['description']));
2138 if (!is_array($args)) {
2139 CRM_Core_Error
::fatal('Arg is not of type array');
2142 list($className) = explode('::', $callback);
2143 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2146 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2152 $types = array_merge($types, $objTypes);
2157 * @param int $customGroupId
2158 * @param int $entityId
2162 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2163 //check whether the group is multiple
2164 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2165 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2166 $hasReachedMax = FALSE;
2168 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2170 if (!$maxMultiple) {
2171 $hasReachedMax = FALSE;
2174 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2175 //count the number of entries for a entity
2176 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2177 $params = array(1 => array($entityId, 'Integer'));
2178 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2180 if ($count >= $maxMultiple) {
2181 $hasReachedMax = TRUE;
2185 return $hasReachedMax;
2191 public static function getMultipleFieldGroup() {
2192 $multipleGroup = array();
2193 $dao = new CRM_Core_DAO_CustomGroup();
2194 $dao->is_multiple
= 1;
2195 $dao->is_active
= 1;
2197 while ($dao->fetch()) {
2198 $multipleGroup[$dao->id
] = $dao->title
;
2200 return $multipleGroup;