3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2016
35 * Business object for managing custom data groups.
37 class CRM_Core_BAO_CustomGroup
extends CRM_Core_DAO_CustomGroup
{
42 public function __construct() {
43 parent
::__construct();
47 * Takes an associative array and creates a custom group object.
49 * This function is invoked from within the web form layer and also from the api layer
51 * @param array $params
52 * (reference) an assoc array of name/value pairs.
54 * @return CRM_Core_DAO_CustomGroup
56 public static function create(&$params) {
57 // create custom group dao, populate fields and then save.
58 $group = new CRM_Core_DAO_CustomGroup();
59 if (isset($params['title'])) {
60 $group->title
= $params['title'];
63 if (in_array($params['extends'][0],
66 'ParticipantEventName',
67 'ParticipantEventType',
70 $group->extends = 'Participant';
73 $group->extends = $params['extends'][0];
76 $group->extends_entity_column_id
= 'null';
78 $params['extends'][0] == 'ParticipantRole' ||
79 $params['extends'][0] == 'ParticipantEventName' ||
80 $params['extends'][0] == 'ParticipantEventType'
82 $group->extends_entity_column_id
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $params['extends'][0], 'value', 'name');
85 //this is format when form get submit.
86 $extendsChildType = CRM_Utils_Array
::value(1, $params['extends']);
87 //lets allow user to pass direct child type value, CRM-6893
88 if (!empty($params['extends_entity_column_value'])) {
89 $extendsChildType = $params['extends_entity_column_value'];
91 if (!CRM_Utils_System
::isNull($extendsChildType)) {
92 $extendsChildType = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendsChildType);
93 if (CRM_Utils_Array
::value(0, $params['extends']) == 'Relationship') {
94 $extendsChildType = str_replace(array('_a_b', '_b_a'), array(
97 ), $extendsChildType);
99 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
100 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType .
101 CRM_Core_DAO
::VALUE_SEPARATOR
;
105 $extendsChildType = 'null';
107 $group->extends_entity_column_value
= $extendsChildType;
109 if (isset($params['id'])) {
110 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
115 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
119 'collapse_adv_display',
125 foreach ($fields as $field) {
126 if (isset($params[$field]) ||
$field == 'is_multiple') {
127 $group->$field = CRM_Utils_Array
::value($field, $params, FALSE);
130 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
131 $params['max_multiple'] >= '0'
132 ) ?
$params['max_multiple'] : 'null' : 'null';
134 $tableName = $oldTableName = NULL;
135 if (isset($params['id'])) {
136 $group->id
= $params['id'];
137 //check whether custom group was changed from single-valued to multiple-valued
138 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
143 if ((!empty($params['is_multiple']) ||
$isMultiple) &&
144 ($params['is_multiple'] != $isMultiple)
146 $oldTableName = CRM_Core_DAO
::getFieldValue(
147 'CRM_Core_DAO_CustomGroup',
154 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
155 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
157 // we do this only once, so name never changes
158 if (isset($params['name'])) {
159 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
162 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
165 if (isset($params['table_name'])) {
166 $tableName = $params['table_name'];
168 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
169 // Bad idea. Prevent group creation because it might lead to a broken configuration.
170 CRM_Core_Error
::fatal(ts("Cannot create custom table because %1 is already a core table.", array('1' => $tableName)));
175 if (array_key_exists('is_reserved', $params)) {
176 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
178 $op = isset($params['id']) ?
'edit' : 'create';
179 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
181 // enclose the below in a transaction
182 $transaction = new CRM_Core_Transaction();
185 if (!isset($params['id'])) {
186 if (!isset($params['table_name'])) {
187 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 42));
188 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
190 $group->table_name
= $tableName;
191 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
197 // now create the table associated with this group
198 self
::createTable($group);
200 elseif ($oldTableName) {
201 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($oldTableName, CRM_Utils_Array
::value('is_multiple', $params));
204 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
205 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
209 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends'][0]));
211 $transaction->commit();
214 CRM_Utils_System
::flushCache();
217 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
220 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
227 * Fetch object based on array of properties.
229 * @param array $params
230 * (reference ) an assoc array of name/value pairs.
231 * @param array $defaults
232 * (reference ) an assoc array to hold the flattened values.
234 * @return CRM_Core_DAO_CustomGroup
236 public static function retrieve(&$params, &$defaults) {
237 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
241 * Update the is_active flag in the db.
244 * Id of the database record.
245 * @param bool $is_active
246 * Value we want to set the is_active field.
249 * DAO object on success, null otherwise
251 public static function setIsActive($id, $is_active) {
253 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
256 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
259 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
263 * Determine if given entity (sub)type has any custom groups
265 * @param string $extends
266 * E.g. "Individual", "Activity".
267 * @param int $columnId
268 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
269 * @param string $columnValue
270 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
274 public static function hasCustomGroup($extends, $columnId, $columnValue) {
275 $dao = new CRM_Core_DAO_CustomGroup();
276 $dao->extends = $extends;
277 $dao->extends_entity_column_id
= $columnId;
278 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
279 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
280 //$dao->extends_entity_column_value = $columnValue;
281 return $dao->find() ?
TRUE : FALSE;
285 * Determine if there are any CustomGroups for the given $activityTypeId.
286 * If none found, create one.
288 * @param int $activityTypeId
291 * TRUE if a group is found or created; FALSE on error
293 public static function autoCreateByActivityType($activityTypeId) {
294 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
297 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
300 'extends' => 'Activity',
301 'extends_entity_column_id' => NULL,
302 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
303 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
307 $result = civicrm_api('CustomGroup', 'create', $params);
308 return !$result['is_error'];
312 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
313 * This may also include entity specific data values.
315 * An array containing all custom groups and their custom fields is returned.
317 * @param string $entityType
318 * Of the contact whose contact type is needed.
319 * @param CRM_Core_Form $deprecated
321 * @param int $entityID
322 * @param int $groupID
323 * @param array $subTypes
324 * @param string $subName
325 * @param bool $fromCache
326 * @param bool $onlySubType
327 * Only return specified subtype or return specified subtype + unrestricted fields.
328 * @param bool $returnAll
329 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
330 * api - through which it is properly tested - so can be refactored with some comfort.)
332 * @param bool $checkPermission
335 * Custom field 'tree'.
337 * The returned array is keyed by group id and has the custom group table fields
338 * and a subkey 'fields' holding the specific custom fields.
339 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
340 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
342 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
343 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
344 * With caching the performance impact would be small & the function would be cleaner
346 public static function getTree(
356 $checkPermission = TRUE
359 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
361 if (!is_array($subTypes)) {
362 if (empty($subTypes)) {
366 if (stristr($subTypes, ',')) {
367 $subTypes = explode(',', $subTypes);
370 $subTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subTypes, CRM_Core_DAO
::VALUE_SEPARATOR
));
376 $strWhere = $orderBy = '';
378 // using tableData to build the queryString
380 'civicrm_custom_field' => array(
400 'civicrm_custom_group' => array(
411 'extends_entity_column_id',
412 'extends_entity_column_value',
419 foreach ($tableData as $tableName => $tableColumn) {
420 foreach ($tableColumn as $columnName) {
421 $alias = $tableName . "_" . $columnName;
422 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
425 $strSelect = "SELECT " . implode(', ', $select);
427 // from, where, order by
429 FROM civicrm_custom_group
430 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
433 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
434 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
435 $entityType == 'Household'
437 $in = "'$entityType', 'Contact'";
439 elseif (strpos($entityType, "'") !== FALSE) {
440 // this allows the calling function to send in multiple entity types
445 $in = "'$entityType'";
448 if (!empty($subTypes)) {
449 foreach ($subTypes as $key => $subType) {
450 $subTypeClauses[] = self
::whereListHas("civicrm_custom_group.extends_entity_column_value", self
::validateSubTypeByEntity($entityType, $subType));
452 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
454 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
458 WHERE civicrm_custom_group.is_active = 1
459 AND civicrm_custom_field.is_active = 1
460 AND civicrm_custom_group.extends IN ($in)
464 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
469 WHERE civicrm_custom_group.is_active = 1
470 AND civicrm_custom_field.is_active = 1
471 AND civicrm_custom_group.extends IN ($in)
474 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
480 // since we want a specific group id we add it to the where clause
481 $strWhere .= " AND civicrm_custom_group.id = %1";
482 $params[1] = array($groupID, 'Integer');
485 // since groupID is false we need to show all Inline groups
486 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
488 if ($checkPermission) {
489 // ensure that the user has access to these custom groups
490 $strWhere .= " AND " .
491 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
492 'civicrm_custom_group.'
497 ORDER BY civicrm_custom_group.weight,
498 civicrm_custom_group.title,
499 civicrm_custom_field.weight,
500 civicrm_custom_field.label
503 // final query string
504 $queryString = "$strSelect $strFrom $strWhere $orderBy";
506 // lets see if we can retrieve the groupTree from cache
507 $cacheString = $queryString;
509 $cacheString .= "_{$groupID}";
512 $cacheString .= "_Inline";
515 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
516 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
517 $cache = CRM_Utils_Cache
::singleton();
518 $tablesWithEntityData = array();
520 $groupTree = $cache->get($cacheKey);
521 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
524 if (empty($groupTree)) {
525 $groupTree = $multipleFieldGroups = array();
526 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
527 $customValueTables = array();
530 while ($crmDAO->fetch()) {
532 $groupID = $crmDAO->civicrm_custom_group_id
;
533 $fieldId = $crmDAO->civicrm_custom_field_id
;
534 if ($crmDAO->civicrm_custom_group_is_multiple
) {
535 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
537 // create an array for groups if it does not exist
538 if (!array_key_exists($groupID, $groupTree)) {
539 $groupTree[$groupID] = array();
540 $groupTree[$groupID]['id'] = $groupID;
542 // populate the group information
543 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
544 $fullFieldName = "civicrm_custom_group_$fieldName";
545 if ($fieldName == 'id' ||
546 is_null($crmDAO->$fullFieldName)
551 // This is an old bit of code - per the CRM number & probably does not work reliably if
552 // that one contact sub-type exists.
553 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
554 $groupTree[$groupID]['subtype'] = self
::validateSubTypeByEntity($entityType, $subType);
556 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
558 $groupTree[$groupID]['fields'] = array();
560 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
563 // add the fields now (note - the query row will always contain a field)
564 // we only reset this once, since multiple values come is as multiple rows
565 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
566 $groupTree[$groupID]['fields'][$fieldId] = array();
569 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
570 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
571 // populate information for a custom field
572 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
573 $fullFieldName = "civicrm_custom_field_$fieldName";
574 if ($fieldName == 'id' ||
575 is_null($crmDAO->$fullFieldName)
579 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
583 if (!empty($customValueTables)) {
584 $groupTree['info'] = array('tables' => $customValueTables);
587 $cache->set($cacheKey, $groupTree);
588 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
590 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
591 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
592 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
593 $singleFieldTables = array();
594 // now that we have all the groups and fields, lets get the values
595 // since we need to know the table and field names
596 // add info to groupTree
598 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
599 !empty($groupTree['info']['tables'])
601 $select = $from = $where = array();
602 $groupTree['info']['where'] = NULL;
604 foreach ($groupTree['info']['tables'] as $table => $fields) {
605 $groupTree['info']['from'][] = $table;
607 "{$table}.id as {$table}_id",
608 "{$table}.entity_id as {$table}_entity_id",
610 foreach ($fields as $column => $dontCare) {
611 $select[] = "{$table}.{$column} as {$table}_{$column}";
613 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
615 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
616 if (in_array($table, $multipleFieldGroups) &&
617 self
::customGroupDataExistsForEntity($entityID, $table)
619 $entityMultipleSelectClauses[$table] = $select;
622 $singleFieldTables[] = $table;
623 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
628 if ($entityID && !empty($singleFieldTables)) {
629 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
631 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
632 if (!empty($multipleFieldTablesWithEntityData)) {
633 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
641 * Clean and validate the filter before it is used in a db query.
643 * @param string $entityType
644 * @param string $subType
647 * @throws \CRM_Core_Exception
648 * @throws \CiviCRM_API3_Exception
650 protected static function validateSubTypeByEntity($entityType, $subType) {
651 $subType = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
652 if (is_numeric($subType)) {
656 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypeInfo(TRUE);
657 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
658 throw new CRM_Core_Exception('Invalid Entity Filter');
660 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo($entityType, TRUE);
661 if (!array_key_exists($subType, $subTypes)) {
662 throw new CRM_Core_Exception('Invalid Filter');
668 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
669 * a WHERE condition for rows that include $value. Use whereListHas().
671 * @param string $column
672 * @param string $value
673 * @param string $delimiter
677 static private function whereListHas($column, $value, $delimiter = CRM_Core_DAO
::VALUE_SEPARATOR
) {
678 $bareValue = trim($value, $delimiter); // ?
679 $escapedValue = CRM_Utils_Type
::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
680 return "($column LIKE \"$escapedValue\")";
684 * Check whether the custom group has any data for the given entity.
687 * @param int $entityID
688 * Id of entity for whom we are checking data for.
689 * @param string $table
690 * Table that we are checking.
692 * @param bool $getCount
695 * does this entity have data in this custom table
697 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
701 WHERE entity_id = $entityID
703 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
705 return $recordExists;
707 return $recordExists ?
TRUE : FALSE;
711 * Build the group tree for Custom fields which are not 'is_multiple'
713 * The combination of all these fields in one query with a 'using' join was not working for
714 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
715 * mechanism as it seemed to be acceptable in this context
717 * @param array $groupTree
718 * (reference) group tree array which is being built.
719 * @param int $entityID
720 * Id of entity for whom the tree is being build up.
721 * @param array $entitySingleSelectClauses
722 * Array of select clauses relevant to the entity.
723 * @param array $singleFieldTablesWithEntityData
724 * Array of tables in which this entity has data.
726 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
727 $select = implode(', ', $entitySingleSelectClauses);
728 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
729 foreach ($singleFieldTablesWithEntityData as $table) {
730 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
736 WHERE first.entity_id = $entityID
738 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
742 * Build the group tree for Custom fields which are 'is_multiple'
744 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
746 * @param array $groupTree
747 * (reference) group tree array which is being built.
748 * @param int $entityID
749 * Id of entity for whom the tree is being build up.
750 * @param array $entityMultipleSelectClauses
751 * Array of select clauses relevant to the entity.
752 * @param array $multipleFieldTablesWithEntityData
753 * Array of tables in which this entity has data.
755 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData) {
756 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
757 $select = implode(',', $selectClauses);
761 WHERE entity_id = $entityID
763 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
768 * Build the tree entity data - starting from a query retrieving the custom fields build the group
769 * tree data for the relevant entity (entity is included in the query).
771 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
773 * @param array $groupTree
774 * (reference) group tree array which is being built.
775 * @param string $query
776 * @param array $includedTables
777 * Tables to include - required because the function (for historical reasons).
778 * iterates through the group tree
780 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables) {
781 $dao = CRM_Core_DAO
::executeQuery($query);
782 while ($dao->fetch()) {
783 foreach ($groupTree as $groupID => $group) {
784 if ($groupID === 'info') {
787 $table = $groupTree[$groupID]['table_name'];
788 //working from the groupTree instead of the table list means we have to iterate & exclude.
789 // this could possibly be re-written as other parts of the function have been refactored
790 // for now we just check if the given table is to be included in this function
791 if (!in_array($table, $includedTables)) {
794 foreach ($group['fields'] as $fieldID => $dontCare) {
795 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
802 * Build the entity-specific custom data into the group tree on a per-field basis
805 * Object representing the custom field to be populated into the groupTree.
806 * @param array $groupTree
807 * (reference) the group tree being build.
808 * @param string $table
810 * @param int $groupID
812 * @param int $fieldID
815 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID) {
816 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
817 $idName = "{$table}_id";
818 $fieldName = "{$table}_{$column}";
819 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
820 if ($dataType == 'File') {
821 if (isset($dao->$fieldName)) {
822 $config = CRM_Core_Config
::singleton();
823 $fileDAO = new CRM_Core_DAO_File();
824 $fileDAO->id
= $dao->$fieldName;
826 if ($fileDAO->find(TRUE)) {
827 $entityIDName = "{$table}_entity_id";
828 $customValue['id'] = $dao->$idName;
829 $customValue['data'] = $fileDAO->uri
;
830 $customValue['fid'] = $fileDAO->id
;
831 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
832 $customValue['displayURL'] = NULL;
833 $deleteExtra = ts('Are you sure you want to delete attached file.');
835 CRM_Core_Action
::DELETE
=> array(
836 'name' => ts('Delete Attached File'),
837 'url' => 'civicrm/file',
838 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
839 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
840 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
843 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
844 CRM_Core_Action
::DELETE
,
846 'id' => $fileDAO->id
,
847 'eid' => $dao->$entityIDName,
852 'file.manage.delete',
856 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
857 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
858 if ($fileDAO->mime_type
== "image/jpeg" ||
859 $fileDAO->mime_type
== "image/pjpeg" ||
860 $fileDAO->mime_type
== "image/gif" ||
861 $fileDAO->mime_type
== "image/x-png" ||
862 $fileDAO->mime_type
== "image/png"
864 $customValue['displayURL'] = $customValue['fileURL'];
865 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
870 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
872 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId, NULL, NULL);
873 if ($path && file_exists($path)) {
874 list($imageWidth, $imageHeight) = getimagesize($path);
875 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
876 $customValue['imageThumbWidth'] = $imageThumbWidth;
877 $customValue['imageThumbHeight'] = $imageThumbHeight;
883 $customValue = array(
884 'id' => $dao->$idName,
890 $customValue = array(
891 'id' => $dao->$idName,
892 'data' => $dao->$fieldName,
896 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
897 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
899 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
900 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
903 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
908 * Get the group title.
916 public static function getTitle($id) {
917 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
921 * Get custom group details for a group.
923 * An array containing custom group details (including their custom field) is returned.
925 * @param int $groupId
926 * Group id whose details are needed.
927 * @param bool $searchable
928 * Is this field searchable.
929 * @param array $extends
930 * Which table does it extend if any.
932 * @param null $inSelector
935 * array consisting of all group and field details
937 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
939 $groupTree = array();
940 $select = $from = $where = $orderBy = '';
942 $tableData = array();
944 // using tableData to build the queryString
946 'civicrm_custom_field' => array(
970 'civicrm_custom_group' => array(
977 'collapse_adv_display',
979 'extends_entity_column_value',
988 foreach ($tableData as $tableName => $tableColumn) {
989 foreach ($tableColumn as $columnName) {
990 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
993 $select = 'SELECT ' . implode(', ', $s);
995 // from, where, order by
996 $from = " FROM civicrm_custom_field, civicrm_custom_group";
997 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
998 AND civicrm_custom_group.is_active = 1
999 AND civicrm_custom_field.is_active = 1 ";
1001 $params[1] = array($groupId, 'Integer');
1002 $where .= " AND civicrm_custom_group.id = %1";
1006 $where .= " AND civicrm_custom_field.is_searchable = 1";
1010 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
1015 foreach ($extends as $e) {
1016 $clause[] = "civicrm_custom_group.extends = '$e'";
1018 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1020 //include case activities customdata if case is enabled
1021 if (in_array('Activity', $extends)) {
1022 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1023 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1024 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
1028 // ensure that the user has access to these custom groups
1030 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1031 'civicrm_custom_group.'
1034 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1036 // final query string
1037 $queryString = $select . $from . $where . $orderBy;
1040 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1043 while ($crmDAO->fetch()) {
1044 $groupId = $crmDAO->civicrm_custom_group_id
;
1045 $fieldId = $crmDAO->civicrm_custom_field_id
;
1047 // create an array for groups if it does not exist
1048 if (!array_key_exists($groupId, $groupTree)) {
1049 $groupTree[$groupId] = array();
1050 $groupTree[$groupId]['id'] = $groupId;
1052 foreach ($tableData['civicrm_custom_group'] as $v) {
1053 $fullField = "civicrm_custom_group_" . $v;
1055 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1059 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1062 $groupTree[$groupId]['fields'] = array();
1065 // add the fields now (note - the query row will always contain a field)
1066 $groupTree[$groupId]['fields'][$fieldId] = array();
1067 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1069 foreach ($tableData['civicrm_custom_field'] as $v) {
1070 $fullField = "civicrm_custom_field_" . $v;
1071 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1074 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1082 * @param $entityType
1084 * @param string $cidToken
1088 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1090 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1092 // get 'Tab' and 'Tab with table' groups
1093 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1094 $customGroupDAO->whereAdd("is_active = 1");
1096 // add whereAdd for entity type
1097 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1101 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1102 $customGroupDAO->whereAdd($permissionClause);
1105 $customGroupDAO->orderBy('weight');
1106 $customGroupDAO->find();
1108 // process each group with menu tab
1109 while ($customGroupDAO->fetch()) {
1111 $group['id'] = $customGroupDAO->id
;
1112 $group['path'] = $path;
1113 $group['title'] = "$customGroupDAO->title";
1114 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1115 $group['extra'] = array('gid' => $customGroupDAO->id
);
1116 $group['table_name'] = $customGroupDAO->table_name
;
1117 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1125 * Get the table name for the entity type
1126 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1127 * tableName is 'civicrm_contact'
1129 * @param string $entityType
1130 * What entity are we extending here ?.
1135 * @see _apachesolr_civiAttachments_dereference_file_parent
1137 public static function getTableNameByEntityName($entityType) {
1139 switch ($entityType) {
1143 case 'Organization':
1144 $tableName = 'civicrm_contact';
1147 case 'Contribution':
1148 $tableName = 'civicrm_contribution';
1152 $tableName = 'civicrm_group';
1155 // DRAFTING: Verify if we cannot make it pluggable
1158 $tableName = 'civicrm_activity';
1161 case 'Relationship':
1162 $tableName = 'civicrm_relationship';
1166 $tableName = 'civicrm_membership';
1170 $tableName = 'civicrm_participant';
1174 $tableName = 'civicrm_event';
1178 $tableName = 'civicrm_grant';
1181 // need to add cases for Location, Address
1188 * Get a list of custom groups which extend a given entity type.
1189 * If there are custom-groups which only apply to certain subtypes,
1190 * those WILL be included.
1192 * @param string $entityType
1194 * @return CRM_Core_DAO_CustomGroup
1196 public static function getAllCustomGroupsByBaseEntity($entityType) {
1197 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1198 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1199 return $customGroupDAO;
1203 * Add the whereAdd clause for the DAO depending on the type of entity
1204 * the custom group is extending.
1206 * @param object $customGroupDAO
1207 * @param string $entityType
1208 * What entity are we extending here ?.
1210 * @param int $entityID
1211 * @param bool $allSubtypes
1213 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1214 $addSubtypeClause = FALSE;
1216 switch ($entityType) {
1218 // if contact, get all related to contact
1219 $extendList = "'Contact','Individual','Household','Organization'";
1220 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1221 if (!$allSubtypes) {
1222 $addSubtypeClause = TRUE;
1228 case 'Organization':
1229 // is I/H/O then get I/H/O and contact
1230 $extendList = "'Contact','$entityType'";
1231 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1232 if (!$allSubtypes) {
1233 $addSubtypeClause = TRUE;
1241 case 'Contribution':
1244 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1248 if ($addSubtypeClause) {
1249 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1251 if (!empty($csType)) {
1252 $subtypeClause = array();
1253 foreach ($csType as $subtype) {
1254 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1255 CRM_Core_DAO
::VALUE_SEPARATOR
;
1256 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1258 $subtypeClause[] = "extends_entity_column_value IS NULL";
1259 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1263 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1269 * Delete the Custom Group.
1271 * @param CRM_Core_BAO_CustomGroup $group
1272 * Custom group object.
1273 * @param bool $force
1274 * whether to force the deletion, even if there are custom fields.
1277 * False if field exists for this group, true if group gets deleted.
1279 public static function deleteGroup($group, $force = FALSE) {
1281 //check whether this contain any custom fields
1282 $customField = new CRM_Core_DAO_CustomField();
1283 $customField->custom_group_id
= $group->id
;
1284 $customField->find();
1286 // return early if there are custom fields and we're not
1287 // forcing the delete, otherwise delete the fields one by one
1288 while ($customField->fetch()) {
1292 CRM_Core_BAO_CustomField
::deleteField($customField);
1295 // drop the table associated with this custom group
1296 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1298 //delete custom group
1301 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1309 * @param array $groupTree
1310 * @param array $defaults
1311 * @param bool $viewMode
1312 * @param bool $inactiveNeeded
1313 * @param int $action
1315 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1316 foreach ($groupTree as $id => $group) {
1317 if (!isset($group['fields'])) {
1320 foreach ($group['fields'] as $field) {
1321 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1322 $value = $field['element_value'];
1324 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1325 ($action != CRM_Core_Action
::UPDATE ||
1327 !array_key_exists('element_value', $field)
1330 $value = $viewMode ?
NULL : $field['default_value'];
1336 if (empty($field['element_name'])) {
1340 $elementName = $field['element_name'];
1342 switch ($field['html_type']) {
1343 case 'Multi-Select':
1344 case 'AdvMulti-Select':
1346 $defaults[$elementName] = array();
1347 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1349 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1350 if (isset($value)) {
1351 foreach ($customOption as $customValue => $customLabel) {
1352 if (in_array($customValue, $checkedData)) {
1353 if ($field['html_type'] == 'CheckBox') {
1354 $defaults[$elementName][$customValue] = 1;
1357 $defaults[$elementName][$customValue] = $customValue;
1361 $defaults[$elementName][$customValue] = 0;
1367 if (isset($field['customValue']['data'])) {
1368 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1369 foreach ($customOption as $val) {
1370 if (in_array($val['value'], $checkedData)) {
1371 if ($field['html_type'] == 'CheckBox') {
1372 $defaults[$elementName][$val['value']] = 1;
1375 $defaults[$elementName][$val['value']] = $val['value'];
1379 $defaults[$elementName][$val['value']] = 0;
1384 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1385 foreach ($customOption as $val) {
1386 if (in_array($val['value'], $checkedValue)) {
1387 if ($field['html_type'] == 'CheckBox') {
1388 $defaults[$elementName][$val['value']] = 1;
1391 $defaults[$elementName][$val['value']] = $val['value'];
1399 case 'Multi-Select Country':
1400 case 'Multi-Select State/Province':
1401 if (isset($value)) {
1402 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1403 foreach ($checkedValue as $val) {
1405 $defaults[$elementName][$val] = $val;
1411 case 'Select Country':
1413 $defaults[$elementName] = $value;
1416 $config = CRM_Core_Config
::singleton();
1417 $defaults[$elementName] = $config->defaultContactCountry
;
1422 if ($field['data_type'] == "Float") {
1423 $defaults[$elementName] = (float) $value;
1425 elseif ($field['data_type'] == 'Money' &&
1426 $field['html_type'] == 'Text'
1428 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1431 $defaults[$elementName] = $value;
1439 * PostProcess function.
1441 * @param array $groupTree
1442 * @param array $params
1443 * @param bool $skipFile
1445 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1446 // Get the Custom form values and groupTree
1447 // first reset all checkbox and radio data
1448 foreach ($groupTree as $groupID => $group) {
1449 if ($groupID === 'info') {
1452 foreach ($group['fields'] as $field) {
1453 $fieldId = $field['id'];
1455 //added Multi-Select option in the below if-statement
1456 if ($field['html_type'] == 'CheckBox' ||
1457 $field['html_type'] == 'Radio' ||
1458 $field['html_type'] == 'AdvMulti-Select' ||
1459 $field['html_type'] == 'Multi-Select'
1461 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1465 foreach ($params as $key => $val) {
1466 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1467 $match[1] == $field['id']
1473 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1474 // field exists in db so populate value from "form".
1475 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1478 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1480 //added for CheckBox
1484 $customValue = array_keys($v);
1485 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1486 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1487 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1490 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1494 //added for Advanced Multi-Select
1496 case 'AdvMulti-Select':
1497 //added for Multi-Select
1498 case 'Multi-Select':
1500 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1501 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1502 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1505 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1510 $date = CRM_Utils_Date
::processDate($v);
1511 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1519 //store the file in d/b
1520 $entityId = explode('=', $groupTree['info']['where'][0]);
1521 $fileParams = array('upload_date' => date('YmdHis'));
1523 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1524 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1527 $fileParams['uri'] = $v['name'];
1528 $fileParams['mime_type'] = $v['type'];
1529 CRM_Core_BAO_File
::filePostProcess($v['name'],
1530 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1531 $groupTree[$groupID]['table_name'],
1536 'custom_' . $fieldId,
1540 $defaults = array();
1541 $paramsFile = array(
1542 'entity_table' => $groupTree[$groupID]['table_name'],
1543 'entity_id' => $entityId[1],
1546 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1551 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1555 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1563 * Generic function to build all the form elements for a specific group tree.
1565 * @param CRM_Core_Form $form
1567 * @param array $groupTree
1568 * The group tree object.
1569 * @param bool $inactiveNeeded
1570 * Return inactive custom groups.
1571 * @param string $prefix
1572 * Prefix for custom grouptree assigned to template.
1574 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1575 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1577 foreach ($groupTree as $id => $group) {
1578 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1579 foreach ($group['fields'] as $field) {
1580 $required = CRM_Utils_Array
::value('is_required', $field);
1582 if ($field['data_type'] == 'File') {
1583 if (!empty($field['element_value']['data'])) {
1588 $fieldId = $field['id'];
1589 $elementName = $field['element_name'];
1590 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $required);
1596 * Extract the get params from the url, validate and store it in session.
1598 * @param CRM_Core_Form $form
1600 * @param string $type
1601 * The type of custom group we are using.
1605 public static function extractGetParams(&$form, $type) {
1610 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type);
1611 $customValue = array();
1620 foreach ($groupTree as $group) {
1621 if (!isset($group['fields'])) {
1624 foreach ($group['fields'] as $key => $field) {
1625 $fieldName = 'custom_' . $key;
1626 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1630 if (!in_array($field['html_type'], $htmlType) ||
1631 $field['data_type'] == 'Boolean'
1633 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1635 if ($field['html_type'] == 'CheckBox' ||
1636 $field['html_type'] == 'AdvMulti-Select' ||
1637 $field['html_type'] == 'Multi-Select'
1639 $value = str_replace("|", ",", $value);
1640 $mulValues = explode(',', $value);
1641 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1643 foreach ($mulValues as $v1) {
1644 foreach ($customOption as $coID => $coValue) {
1645 if (strtolower(trim($coValue['label'])) ==
1646 strtolower(trim($v1))
1648 $val[$coValue['value']] = 1;
1660 elseif ($field['html_type'] == 'Select' ||
1661 ($field['html_type'] == 'Radio' &&
1662 $field['data_type'] != 'Boolean'
1665 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1666 foreach ($customOption as $customID => $coValue) {
1667 if (strtolower(trim($coValue['label'])) ==
1668 strtolower(trim($value))
1670 $value = $coValue['value'];
1675 elseif ($field['data_type'] == 'Date') {
1676 if (!empty($value)) {
1678 if (!empty($field['time_format'])) {
1679 $time = CRM_Utils_Request
::retrieve($fieldName .
1680 '_time', 'String', $form, FALSE, NULL, 'GET');
1682 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value .
1684 if (!empty($field['time_format'])) {
1685 $customValue[$fieldName . '_time'] = $time;
1692 $customValue[$fieldName] = $value;
1698 return $customValue;
1702 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1703 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1705 * @param int $customFieldId
1707 * @param array $removeCustomFieldTypes
1708 * Remove custom fields of a type eg: array("Individual") ;.
1711 * false if it matches else true
1713 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1714 $query = "SELECT cg.extends as extends
1715 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1716 WHERE cg.id = cf.custom_group_id
1718 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1720 $extends = CRM_Core_DAO
::singleValueQuery($query);
1722 if (in_array($extends, $removeCustomFieldTypes)) {
1734 public static function mapTableName($table) {
1739 case 'Organization':
1740 return 'civicrm_contact';
1743 return 'civicrm_activity';
1746 return 'civicrm_group';
1748 case 'Contribution':
1749 return 'civicrm_contribution';
1751 case 'ContributionRecur':
1752 return 'civicrm_contribution_recur';
1754 case 'Relationship':
1755 return 'civicrm_relationship';
1758 return 'civicrm_event';
1761 return 'civicrm_membership';
1764 case 'ParticipantRole':
1765 case 'ParticipantEventName':
1766 case 'ParticipantEventType':
1767 return 'civicrm_participant';
1770 return 'civicrm_grant';
1773 return 'civicrm_pledge';
1776 return 'civicrm_address';
1779 return 'civicrm_campaign';
1783 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1784 $qParams = array(1 => array($table, 'String'));
1785 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1788 return 'civicrm_contact';
1791 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1792 if (array_key_exists($table, $extendObjs)) {
1793 return $extendObjs[$table];
1795 CRM_Core_Error
::fatal();
1803 public static function createTable($group) {
1805 'name' => $group->table_name
,
1806 'is_multiple' => $group->is_multiple ?
1 : 0,
1807 'extends_name' => self
::mapTableName($group->extends),
1810 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1812 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1816 * Function returns formatted groupTree, sothat form can be easily build in template
1818 * @param array $groupTree
1819 * @param int $groupCount
1820 * Group count by default 1, but can varry for multiple value custom data.
1821 * @param object $form
1825 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NULL) {
1826 $formattedGroupTree = array();
1827 $uploadNames = array();
1829 foreach ($groupTree as $key => $value) {
1830 if ($key === 'info') {
1834 // add group information
1835 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1836 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1837 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1838 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1839 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1840 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1841 $formattedGroupTree[$key]['style'] = CRM_Utils_Array
::value('style', $value);
1843 // this params needed of bulding multiple values
1844 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1845 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1846 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1847 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1848 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1849 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1851 // add field information
1852 foreach ($value['fields'] as $k => $properties) {
1853 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1854 if (isset($properties['customValue']) &&
1855 !CRM_Utils_System
::isNull($properties['customValue'])
1857 if (isset($properties['customValue'][$groupCount])) {
1858 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1859 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1860 if ($properties['data_type'] == 'File') {
1861 $properties['element_value'] = $properties['customValue'][$groupCount];
1862 $uploadNames[] = $properties['element_name'];
1865 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1869 unset($properties['customValue']);
1870 $formattedGroupTree[$key]['fields'][$k] = $properties;
1875 // hack for field type File
1876 $formUploadNames = $form->get('uploadNames');
1877 if (is_array($formUploadNames)) {
1878 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1881 $form->set('uploadNames', $uploadNames);
1884 return $formattedGroupTree;
1888 * Build custom data view.
1890 * @param CRM_Core_Form $form
1892 * @param array $groupTree
1893 * @param bool $returnCount
1894 * True if customValue count needs to be returned.
1896 * @param null $prefix
1897 * @param int $customValueId
1898 * @param int $entityId
1902 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
1904 foreach ($groupTree as $key => $group) {
1905 if ($key === 'info') {
1909 foreach ($group['fields'] as $k => $properties) {
1910 $groupID = $group['id'];
1911 if (!empty($properties['customValue'])) {
1912 foreach ($properties['customValue'] as $values) {
1913 if (!empty($customValueId) && $customValueId != $values['id']) {
1916 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1917 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1918 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1919 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1920 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1921 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1922 $details[$groupID][$values['id']]['style'] = CRM_Utils_Array
::value('style', $group);
1923 $details[$groupID][$values['id']]['fields'][$k] = array(
1924 'field_title' => CRM_Utils_Array
::value('label', $properties),
1925 'field_type' => CRM_Utils_Array
::value('html_type', $properties),
1926 'field_data_type' => CRM_Utils_Array
::value('data_type', $properties),
1927 'field_value' => CRM_Core_BAO_CustomField
::displayValue($values['data'], $properties['id'], $entityId),
1928 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $properties),
1930 // also return contact reference contact id if user has view all or edit all contacts perm
1931 if ((CRM_Core_Permission
::check('view all contacts') ||
1932 CRM_Core_Permission
::check('edit all contacts'))
1934 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1937 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1942 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1943 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1944 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1945 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1946 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1947 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1948 $details[$groupID][0]['style'] = CRM_Utils_Array
::value('style', $group);
1949 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1955 //return a single value count if group id is passed to function
1956 //else return a groupId and count mapped array
1958 return count($details[$gID]);
1961 $countValue = array();
1962 foreach ($details as $key => $value) {
1963 $countValue[$key] = count($details[$key]);
1969 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1975 * Get the custom group titles by custom field ids.
1977 * @param array $fieldIds
1978 * Array of custom field ids.
1980 * @return array|NULL
1981 * array consisting of groups and fields labels with ids.
1983 public static function getGroupTitles($fieldIds) {
1984 if (!is_array($fieldIds) && empty($fieldIds)) {
1988 $groupLabels = array();
1989 $fIds = "(" . implode(',', $fieldIds) . ")";
1992 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
1993 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
1994 FROM civicrm_custom_group, civicrm_custom_field
1995 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
1996 AND civicrm_custom_field.id IN {$fIds}";
1998 $dao = CRM_Core_DAO
::executeQuery($query);
1999 while ($dao->fetch()) {
2000 $groupLabels[$dao->fieldID
] = array(
2001 'fieldID' => $dao->fieldID
,
2002 'fieldLabel' => $dao->fieldLabel
,
2003 'groupID' => $dao->groupID
,
2004 'groupTitle' => $dao->groupTitle
,
2008 return $groupLabels;
2011 public static function dropAllTables() {
2012 $query = "SELECT table_name FROM civicrm_custom_group";
2013 $dao = CRM_Core_DAO
::executeQuery($query);
2015 while ($dao->fetch()) {
2016 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2017 CRM_Core_DAO
::executeQuery($query);
2022 * Check whether custom group is empty or not.
2028 * true if empty otherwise false.
2030 public static function isGroupEmpty($gID) {
2035 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2040 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2041 $value = CRM_Core_DAO
::singleValueQuery($query);
2043 if (empty($value)) {
2051 * Get the list of types for objects that a custom group extends to.
2053 * @param array $types
2054 * Var which should have the list appended.
2059 public static function getExtendedObjectTypes(&$types = array()) {
2060 static $flag = FALSE, $objTypes = array();
2063 $extendObjs = array();
2064 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2066 foreach ($extendObjs as $ovId => $ovValues) {
2067 if ($ovValues['description']) {
2068 // description is expected to be a callback func to subtypes
2069 list($callback, $args) = explode(';', trim($ovValues['description']));
2075 if (!is_array($args)) {
2076 CRM_Core_Error
::fatal('Arg is not of type array');
2079 list($className) = explode('::', $callback);
2080 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2083 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2089 $types = array_merge($types, $objTypes);
2094 * @param int $customGroupId
2095 * @param int $entityId
2099 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2100 //check whether the group is multiple
2101 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2102 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2103 $hasReachedMax = FALSE;
2105 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2107 if (!$maxMultiple) {
2108 $hasReachedMax = FALSE;
2111 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2112 //count the number of entries for a entity
2113 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2114 $params = array(1 => array($entityId, 'Integer'));
2115 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2117 if ($count >= $maxMultiple) {
2118 $hasReachedMax = TRUE;
2122 return $hasReachedMax;
2128 public static function getMultipleFieldGroup() {
2129 $multipleGroup = array();
2130 $dao = new CRM_Core_DAO_CustomGroup();
2131 $dao->is_multiple
= 1;
2133 while ($dao->fetch()) {
2134 $multipleGroup[$dao->id
] = $dao->title
;
2136 return $multipleGroup;