3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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
333 * @param varchar $singleRecord
334 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
337 * Custom field 'tree'.
339 * The returned array is keyed by group id and has the custom group table fields
340 * and a subkey 'fields' holding the specific custom fields.
341 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
342 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
344 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
345 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
346 * With caching the performance impact would be small & the function would be cleaner
348 public static function getTree(
358 $checkPermission = TRUE,
362 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
364 if (!is_array($subTypes)) {
365 if (empty($subTypes)) {
369 if (stristr($subTypes, ',')) {
370 $subTypes = explode(',', $subTypes);
373 $subTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($subTypes, CRM_Core_DAO
::VALUE_SEPARATOR
));
379 $strWhere = $orderBy = '';
381 // using tableData to build the queryString
383 'civicrm_custom_field' => array(
403 'civicrm_custom_group' => array(
414 'extends_entity_column_id',
415 'extends_entity_column_value',
422 foreach ($tableData as $tableName => $tableColumn) {
423 foreach ($tableColumn as $columnName) {
424 $alias = $tableName . "_" . $columnName;
425 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
428 $strSelect = "SELECT " . implode(', ', $select);
430 // from, where, order by
432 FROM civicrm_custom_group
433 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
436 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
437 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
438 $entityType == 'Household'
440 $in = "'$entityType', 'Contact'";
442 elseif (strpos($entityType, "'") !== FALSE) {
443 // this allows the calling function to send in multiple entity types
448 $in = "'$entityType'";
451 if (!empty($subTypes)) {
452 foreach ($subTypes as $key => $subType) {
453 $subTypeClauses[] = self
::whereListHas("civicrm_custom_group.extends_entity_column_value", self
::validateSubTypeByEntity($entityType, $subType));
455 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
457 $subTypeClause = '(' . $subTypeClause . ' OR civicrm_custom_group.extends_entity_column_value IS NULL )';
461 WHERE civicrm_custom_group.is_active = 1
462 AND civicrm_custom_field.is_active = 1
463 AND civicrm_custom_group.extends IN ($in)
467 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
472 WHERE civicrm_custom_group.is_active = 1
473 AND civicrm_custom_field.is_active = 1
474 AND civicrm_custom_group.extends IN ($in)
477 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
483 // since we want a specific group id we add it to the where clause
484 $strWhere .= " AND civicrm_custom_group.id = %1";
485 $params[1] = array($groupID, 'Integer');
488 // since groupID is false we need to show all Inline groups
489 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
491 if ($checkPermission) {
492 // ensure that the user has access to these custom groups
493 $strWhere .= " AND " .
494 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
495 'civicrm_custom_group.'
500 ORDER BY civicrm_custom_group.weight,
501 civicrm_custom_group.title,
502 civicrm_custom_field.weight,
503 civicrm_custom_field.label
506 // final query string
507 $queryString = "$strSelect $strFrom $strWhere $orderBy";
509 // lets see if we can retrieve the groupTree from cache
510 $cacheString = $queryString;
512 $cacheString .= "_{$groupID}";
515 $cacheString .= "_Inline";
518 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
519 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
520 $cache = CRM_Utils_Cache
::singleton();
521 $tablesWithEntityData = array();
523 $groupTree = $cache->get($cacheKey);
524 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
527 if (empty($groupTree)) {
528 $groupTree = $multipleFieldGroups = array();
529 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
530 $customValueTables = array();
533 while ($crmDAO->fetch()) {
535 $groupID = $crmDAO->civicrm_custom_group_id
;
536 $fieldId = $crmDAO->civicrm_custom_field_id
;
537 if ($crmDAO->civicrm_custom_group_is_multiple
) {
538 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
540 // create an array for groups if it does not exist
541 if (!array_key_exists($groupID, $groupTree)) {
542 $groupTree[$groupID] = array();
543 $groupTree[$groupID]['id'] = $groupID;
545 // populate the group information
546 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
547 $fullFieldName = "civicrm_custom_group_$fieldName";
548 if ($fieldName == 'id' ||
549 is_null($crmDAO->$fullFieldName)
554 // This is an old bit of code - per the CRM number & probably does not work reliably if
555 // that one contact sub-type exists.
556 if ($fieldName == 'extends_entity_column_value' && !empty($subTypes[0])) {
557 $groupTree[$groupID]['subtype'] = self
::validateSubTypeByEntity($entityType, $subType);
559 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
561 $groupTree[$groupID]['fields'] = array();
563 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
566 // add the fields now (note - the query row will always contain a field)
567 // we only reset this once, since multiple values come is as multiple rows
568 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
569 $groupTree[$groupID]['fields'][$fieldId] = array();
572 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
573 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
574 // populate information for a custom field
575 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
576 $fullFieldName = "civicrm_custom_field_$fieldName";
577 if ($fieldName == 'id' ||
578 is_null($crmDAO->$fullFieldName)
582 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
586 if (!empty($customValueTables)) {
587 $groupTree['info'] = array('tables' => $customValueTables);
590 $cache->set($cacheKey, $groupTree);
591 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
593 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
594 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
595 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
596 $singleFieldTables = array();
597 // now that we have all the groups and fields, lets get the values
598 // since we need to know the table and field names
599 // add info to groupTree
601 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
602 !empty($groupTree['info']['tables']) && $singleRecord != 'new'
604 $select = $from = $where = array();
605 $groupTree['info']['where'] = NULL;
607 foreach ($groupTree['info']['tables'] as $table => $fields) {
608 $groupTree['info']['from'][] = $table;
610 "{$table}.id as {$table}_id",
611 "{$table}.entity_id as {$table}_entity_id",
613 foreach ($fields as $column => $dontCare) {
614 $select[] = "{$table}.{$column} as {$table}_{$column}";
616 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
618 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
619 if (in_array($table, $multipleFieldGroups) &&
620 self
::customGroupDataExistsForEntity($entityID, $table)
622 $entityMultipleSelectClauses[$table] = $select;
625 $singleFieldTables[] = $table;
626 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
631 if ($entityID && !empty($singleFieldTables)) {
632 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
634 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
635 if (!empty($multipleFieldTablesWithEntityData)) {
636 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord);
644 * Clean and validate the filter before it is used in a db query.
646 * @param string $entityType
647 * @param string $subType
650 * @throws \CRM_Core_Exception
651 * @throws \CiviCRM_API3_Exception
653 protected static function validateSubTypeByEntity($entityType, $subType) {
654 $subType = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
655 if (is_numeric($subType)) {
659 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypeInfo(TRUE);
660 $contactTypes = array_merge($contactTypes, array('Event' => 1));
662 if ($entityType != 'Contact' && !array_key_exists($entityType, $contactTypes)) {
663 throw new CRM_Core_Exception('Invalid Entity Filter');
665 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo($entityType, TRUE);
666 $subTypes = array_merge($subTypes, CRM_Event_PseudoConstant
::eventType());
667 if (!array_key_exists($subType, $subTypes)) {
668 throw new CRM_Core_Exception('Invalid Filter');
674 * Suppose you have a SQL column, $column, which includes a delimited list, and you want
675 * a WHERE condition for rows that include $value. Use whereListHas().
677 * @param string $column
678 * @param string $value
679 * @param string $delimiter
683 static private function whereListHas($column, $value, $delimiter = CRM_Core_DAO
::VALUE_SEPARATOR
) {
684 $bareValue = trim($value, $delimiter); // ?
685 $escapedValue = CRM_Utils_Type
::escape("%{$delimiter}{$bareValue}{$delimiter}%", 'String', FALSE);
686 return "($column LIKE \"$escapedValue\")";
690 * Check whether the custom group has any data for the given entity.
693 * @param int $entityID
694 * Id of entity for whom we are checking data for.
695 * @param string $table
696 * Table that we are checking.
698 * @param bool $getCount
701 * does this entity have data in this custom table
703 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
707 WHERE entity_id = $entityID
709 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
711 return $recordExists;
713 return $recordExists ?
TRUE : FALSE;
717 * Build the group tree for Custom fields which are not 'is_multiple'
719 * The combination of all these fields in one query with a 'using' join was not working for
720 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
721 * mechanism as it seemed to be acceptable in this context
723 * @param array $groupTree
724 * (reference) group tree array which is being built.
725 * @param int $entityID
726 * Id of entity for whom the tree is being build up.
727 * @param array $entitySingleSelectClauses
728 * Array of select clauses relevant to the entity.
729 * @param array $singleFieldTablesWithEntityData
730 * Array of tables in which this entity has data.
732 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
733 $select = implode(', ', $entitySingleSelectClauses);
734 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
735 foreach ($singleFieldTablesWithEntityData as $table) {
736 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
742 WHERE first.entity_id = $entityID
744 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
748 * Build the group tree for Custom fields which are 'is_multiple'
750 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
752 * @param array $groupTree
753 * (reference) group tree array which is being built.
754 * @param int $entityID
755 * Id of entity for whom the tree is being build up.
756 * @param array $entityMultipleSelectClauses
757 * Array of select clauses relevant to the entity.
758 * @param array $multipleFieldTablesWithEntityData
759 * Array of tables in which this entity has data.
760 * @param varchar $singleRecord
761 * holds 'new' or id if view/edit/copy form for a single record is being loaded.
763 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData, $singleRecord = NULL) {
764 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
765 $select = implode(',', $selectClauses);
769 WHERE entity_id = $entityID
772 $offset = $singleRecord - 1;
773 $query .= " LIMIT {$offset}, 1";
775 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table), $singleRecord);
780 * Build the tree entity data - starting from a query retrieving the custom fields build the group
781 * tree data for the relevant entity (entity is included in the query).
783 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
785 * @param array $groupTree
786 * (reference) group tree array which is being built.
787 * @param string $query
788 * @param array $includedTables
789 * Tables to include - required because the function (for historical reasons).
790 * iterates through the group tree
791 * @param varchar $singleRecord
792 * holds 'new' OR id if view/edit/copy form for a single record is being loaded.
794 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables, $singleRecord = NULL) {
795 $dao = CRM_Core_DAO
::executeQuery($query);
796 while ($dao->fetch()) {
797 foreach ($groupTree as $groupID => $group) {
798 if ($groupID === 'info') {
801 $table = $groupTree[$groupID]['table_name'];
802 //working from the groupTree instead of the table list means we have to iterate & exclude.
803 // this could possibly be re-written as other parts of the function have been refactored
804 // for now we just check if the given table is to be included in this function
805 if (!in_array($table, $includedTables)) {
808 foreach ($group['fields'] as $fieldID => $dontCare) {
809 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID, $singleRecord);
816 * Build the entity-specific custom data into the group tree on a per-field basis
819 * Object representing the custom field to be populated into the groupTree.
820 * @param array $groupTree
821 * (reference) the group tree being build.
822 * @param string $table
824 * @param int $groupID
826 * @param int $fieldID
828 * @param varchar $singleRecord
829 * holds 'new' or id if loading view/edit/copy for a single record.
831 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID, $singleRecord = NULL) {
832 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
833 $idName = "{$table}_id";
834 $fieldName = "{$table}_{$column}";
835 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
836 if ($dataType == 'File') {
837 if (isset($dao->$fieldName)) {
838 $config = CRM_Core_Config
::singleton();
839 $fileDAO = new CRM_Core_DAO_File();
840 $fileDAO->id
= $dao->$fieldName;
842 if ($fileDAO->find(TRUE)) {
843 $entityIDName = "{$table}_entity_id";
844 $customValue['id'] = $dao->$idName;
845 $customValue['data'] = $fileDAO->uri
;
846 $customValue['fid'] = $fileDAO->id
;
847 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
848 $customValue['displayURL'] = NULL;
849 $deleteExtra = ts('Are you sure you want to delete attached file.');
851 CRM_Core_Action
::DELETE
=> array(
852 'name' => ts('Delete Attached File'),
853 'url' => 'civicrm/file',
854 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
855 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
856 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
859 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
860 CRM_Core_Action
::DELETE
,
862 'id' => $fileDAO->id
,
863 'eid' => $dao->$entityIDName,
868 'file.manage.delete',
872 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
873 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
874 if ($fileDAO->mime_type
== "image/jpeg" ||
875 $fileDAO->mime_type
== "image/pjpeg" ||
876 $fileDAO->mime_type
== "image/gif" ||
877 $fileDAO->mime_type
== "image/x-png" ||
878 $fileDAO->mime_type
== "image/png"
880 $customValue['displayURL'] = $customValue['fileURL'];
881 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
886 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
888 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId, NULL, NULL);
889 if ($path && file_exists($path)) {
890 list($imageWidth, $imageHeight) = getimagesize($path);
891 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
892 $customValue['imageThumbWidth'] = $imageThumbWidth;
893 $customValue['imageThumbHeight'] = $imageThumbHeight;
899 $customValue = array(
900 'id' => $dao->$idName,
906 $customValue = array(
907 'id' => $dao->$idName,
908 'data' => $dao->$fieldName,
912 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
913 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
915 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue']) && !empty($singleRecord)) {
916 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array($singleRecord => $customValue);
918 elseif (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
919 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
922 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
927 * Get the group title.
935 public static function getTitle($id) {
936 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
940 * Get custom group details for a group.
942 * An array containing custom group details (including their custom field) is returned.
944 * @param int $groupId
945 * Group id whose details are needed.
946 * @param bool $searchable
947 * Is this field searchable.
948 * @param array $extends
949 * Which table does it extend if any.
951 * @param null $inSelector
954 * array consisting of all group and field details
956 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
958 $groupTree = array();
959 $select = $from = $where = $orderBy = '';
961 $tableData = array();
963 // using tableData to build the queryString
965 'civicrm_custom_field' => array(
989 'civicrm_custom_group' => array(
996 'collapse_adv_display',
998 'extends_entity_column_value',
1007 foreach ($tableData as $tableName => $tableColumn) {
1008 foreach ($tableColumn as $columnName) {
1009 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
1012 $select = 'SELECT ' . implode(', ', $s);
1014 // from, where, order by
1015 $from = " FROM civicrm_custom_field, civicrm_custom_group";
1016 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
1017 AND civicrm_custom_group.is_active = 1
1018 AND civicrm_custom_field.is_active = 1 ";
1020 $params[1] = array($groupId, 'Integer');
1021 $where .= " AND civicrm_custom_group.id = %1";
1025 $where .= " AND civicrm_custom_field.is_searchable = 1";
1029 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
1034 foreach ($extends as $e) {
1035 $clause[] = "civicrm_custom_group.extends = '$e'";
1037 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
1039 //include case activities customdata if case is enabled
1040 if (in_array('Activity', $extends)) {
1041 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
1042 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
1043 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
1047 // ensure that the user has access to these custom groups
1049 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1050 'civicrm_custom_group.'
1053 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1055 // final query string
1056 $queryString = $select . $from . $where . $orderBy;
1059 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1062 while ($crmDAO->fetch()) {
1063 $groupId = $crmDAO->civicrm_custom_group_id
;
1064 $fieldId = $crmDAO->civicrm_custom_field_id
;
1066 // create an array for groups if it does not exist
1067 if (!array_key_exists($groupId, $groupTree)) {
1068 $groupTree[$groupId] = array();
1069 $groupTree[$groupId]['id'] = $groupId;
1071 foreach ($tableData['civicrm_custom_group'] as $v) {
1072 $fullField = "civicrm_custom_group_" . $v;
1074 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1078 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1081 $groupTree[$groupId]['fields'] = array();
1084 // add the fields now (note - the query row will always contain a field)
1085 $groupTree[$groupId]['fields'][$fieldId] = array();
1086 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1088 foreach ($tableData['civicrm_custom_field'] as $v) {
1089 $fullField = "civicrm_custom_field_" . $v;
1090 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1093 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1101 * @param $entityType
1103 * @param string $cidToken
1107 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1109 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1111 // get 'Tab' and 'Tab with table' groups
1112 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1113 $customGroupDAO->whereAdd("is_active = 1");
1115 // add whereAdd for entity type
1116 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1120 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1121 $customGroupDAO->whereAdd($permissionClause);
1124 $customGroupDAO->orderBy('weight');
1125 $customGroupDAO->find();
1127 // process each group with menu tab
1128 while ($customGroupDAO->fetch()) {
1130 $group['id'] = $customGroupDAO->id
;
1131 $group['path'] = $path;
1132 $group['title'] = "$customGroupDAO->title";
1133 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1134 $group['extra'] = array('gid' => $customGroupDAO->id
);
1135 $group['table_name'] = $customGroupDAO->table_name
;
1136 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1144 * Get the table name for the entity type
1145 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1146 * tableName is 'civicrm_contact'
1148 * @param string $entityType
1149 * What entity are we extending here ?.
1154 * @see _apachesolr_civiAttachments_dereference_file_parent
1156 public static function getTableNameByEntityName($entityType) {
1158 switch ($entityType) {
1162 case 'Organization':
1163 $tableName = 'civicrm_contact';
1166 case 'Contribution':
1167 $tableName = 'civicrm_contribution';
1171 $tableName = 'civicrm_group';
1174 // DRAFTING: Verify if we cannot make it pluggable
1177 $tableName = 'civicrm_activity';
1180 case 'Relationship':
1181 $tableName = 'civicrm_relationship';
1185 $tableName = 'civicrm_membership';
1189 $tableName = 'civicrm_participant';
1193 $tableName = 'civicrm_event';
1197 $tableName = 'civicrm_grant';
1200 // need to add cases for Location, Address
1207 * Get a list of custom groups which extend a given entity type.
1208 * If there are custom-groups which only apply to certain subtypes,
1209 * those WILL be included.
1211 * @param string $entityType
1213 * @return CRM_Core_DAO_CustomGroup
1215 public static function getAllCustomGroupsByBaseEntity($entityType) {
1216 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1217 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1218 return $customGroupDAO;
1222 * Add the whereAdd clause for the DAO depending on the type of entity
1223 * the custom group is extending.
1225 * @param object $customGroupDAO
1226 * @param string $entityType
1227 * What entity are we extending here ?.
1229 * @param int $entityID
1230 * @param bool $allSubtypes
1232 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1233 $addSubtypeClause = FALSE;
1235 switch ($entityType) {
1237 // if contact, get all related to contact
1238 $extendList = "'Contact','Individual','Household','Organization'";
1239 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1240 if (!$allSubtypes) {
1241 $addSubtypeClause = TRUE;
1247 case 'Organization':
1248 // is I/H/O then get I/H/O and contact
1249 $extendList = "'Contact','$entityType'";
1250 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1251 if (!$allSubtypes) {
1252 $addSubtypeClause = TRUE;
1260 case 'Contribution':
1263 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1267 if ($addSubtypeClause) {
1268 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1270 if (!empty($csType)) {
1271 $subtypeClause = array();
1272 foreach ($csType as $subtype) {
1273 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1274 CRM_Core_DAO
::VALUE_SEPARATOR
;
1275 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1277 $subtypeClause[] = "extends_entity_column_value IS NULL";
1278 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1282 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1288 * Delete the Custom Group.
1290 * @param CRM_Core_BAO_CustomGroup $group
1291 * Custom group object.
1292 * @param bool $force
1293 * whether to force the deletion, even if there are custom fields.
1296 * False if field exists for this group, true if group gets deleted.
1298 public static function deleteGroup($group, $force = FALSE) {
1300 //check whether this contain any custom fields
1301 $customField = new CRM_Core_DAO_CustomField();
1302 $customField->custom_group_id
= $group->id
;
1303 $customField->find();
1305 // return early if there are custom fields and we're not
1306 // forcing the delete, otherwise delete the fields one by one
1307 while ($customField->fetch()) {
1311 CRM_Core_BAO_CustomField
::deleteField($customField);
1314 // drop the table associated with this custom group
1315 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1317 //delete custom group
1320 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1328 * @param array $groupTree
1329 * @param array $defaults
1330 * @param bool $viewMode
1331 * @param bool $inactiveNeeded
1332 * @param int $action
1334 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1335 foreach ($groupTree as $id => $group) {
1336 if (!isset($group['fields'])) {
1339 foreach ($group['fields'] as $field) {
1340 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1341 $value = $field['element_value'];
1343 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1344 ($action != CRM_Core_Action
::UPDATE ||
1346 !array_key_exists('element_value', $field)
1349 $value = $viewMode ?
NULL : $field['default_value'];
1355 if (empty($field['element_name'])) {
1359 $elementName = $field['element_name'];
1361 switch ($field['html_type']) {
1362 case 'Multi-Select':
1363 case 'AdvMulti-Select':
1365 $defaults[$elementName] = array();
1366 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1368 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1369 if (isset($value)) {
1370 foreach ($customOption as $customValue => $customLabel) {
1371 if (in_array($customValue, $checkedData)) {
1372 if ($field['html_type'] == 'CheckBox') {
1373 $defaults[$elementName][$customValue] = 1;
1376 $defaults[$elementName][$customValue] = $customValue;
1380 $defaults[$elementName][$customValue] = 0;
1386 if (isset($field['customValue']['data'])) {
1387 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1388 foreach ($customOption as $val) {
1389 if (in_array($val['value'], $checkedData)) {
1390 if ($field['html_type'] == 'CheckBox') {
1391 $defaults[$elementName][$val['value']] = 1;
1394 $defaults[$elementName][$val['value']] = $val['value'];
1398 $defaults[$elementName][$val['value']] = 0;
1403 if (is_array($value) && count($value)) {
1404 CRM_Utils_Array
::formatArrayKeys($value);
1405 $checkedValue = $value;
1408 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1410 foreach ($customOption as $val) {
1411 if (in_array($val['value'], $checkedValue)) {
1412 if ($field['html_type'] == 'CheckBox') {
1413 $defaults[$elementName][$val['value']] = 1;
1416 $defaults[$elementName][$val['value']] = $val['value'];
1424 case 'Multi-Select Country':
1425 case 'Multi-Select State/Province':
1426 if (isset($value)) {
1427 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1428 foreach ($checkedValue as $val) {
1430 $defaults[$elementName][$val] = $val;
1436 case 'Select Country':
1438 $defaults[$elementName] = $value;
1441 $config = CRM_Core_Config
::singleton();
1442 $defaults[$elementName] = $config->defaultContactCountry
;
1447 if ($field['data_type'] == "Float") {
1448 $defaults[$elementName] = (float) $value;
1450 elseif ($field['data_type'] == 'Money' &&
1451 $field['html_type'] == 'Text'
1453 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1456 $defaults[$elementName] = $value;
1464 * PostProcess function.
1466 * @param array $groupTree
1467 * @param array $params
1468 * @param bool $skipFile
1470 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1471 // Get the Custom form values and groupTree
1472 // first reset all checkbox and radio data
1473 foreach ($groupTree as $groupID => $group) {
1474 if ($groupID === 'info') {
1477 foreach ($group['fields'] as $field) {
1478 $fieldId = $field['id'];
1480 //added Multi-Select option in the below if-statement
1481 if ($field['html_type'] == 'CheckBox' ||
1482 $field['html_type'] == 'Radio' ||
1483 $field['html_type'] == 'AdvMulti-Select' ||
1484 $field['html_type'] == 'Multi-Select'
1486 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1490 foreach ($params as $key => $val) {
1491 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1492 $match[1] == $field['id']
1498 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1499 // field exists in db so populate value from "form".
1500 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1503 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1505 //added for CheckBox
1509 $customValue = array_keys($v);
1510 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1511 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1512 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1515 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1519 //added for Advanced Multi-Select
1521 case 'AdvMulti-Select':
1522 //added for Multi-Select
1523 case 'Multi-Select':
1525 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1526 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1527 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1530 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1535 $date = CRM_Utils_Date
::processDate($v);
1536 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1544 //store the file in d/b
1545 $entityId = explode('=', $groupTree['info']['where'][0]);
1546 $fileParams = array('upload_date' => date('YmdHis'));
1548 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1549 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1552 $fileParams['uri'] = $v['name'];
1553 $fileParams['mime_type'] = $v['type'];
1554 CRM_Core_BAO_File
::filePostProcess($v['name'],
1555 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1556 $groupTree[$groupID]['table_name'],
1561 'custom_' . $fieldId,
1565 $defaults = array();
1566 $paramsFile = array(
1567 'entity_table' => $groupTree[$groupID]['table_name'],
1568 'entity_id' => $entityId[1],
1571 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1576 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1580 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1588 * Generic function to build all the form elements for a specific group tree.
1590 * @param CRM_Core_Form $form
1592 * @param array $groupTree
1593 * The group tree object.
1594 * @param bool $inactiveNeeded
1595 * Return inactive custom groups.
1596 * @param string $prefix
1597 * Prefix for custom grouptree assigned to template.
1599 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1600 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1602 foreach ($groupTree as $id => $group) {
1603 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1604 foreach ($group['fields'] as $field) {
1605 $required = CRM_Utils_Array
::value('is_required', $field);
1607 if ($field['data_type'] == 'File') {
1608 if (!empty($field['element_value']['data'])) {
1613 $fieldId = $field['id'];
1614 $elementName = $field['element_name'];
1615 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $required);
1621 * Extract the get params from the url, validate and store it in session.
1623 * @param CRM_Core_Form $form
1625 * @param string $type
1626 * The type of custom group we are using.
1630 public static function extractGetParams(&$form, $type) {
1635 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type);
1636 $customValue = array();
1645 foreach ($groupTree as $group) {
1646 if (!isset($group['fields'])) {
1649 foreach ($group['fields'] as $key => $field) {
1650 $fieldName = 'custom_' . $key;
1651 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1655 if (!in_array($field['html_type'], $htmlType) ||
1656 $field['data_type'] == 'Boolean'
1658 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1660 if ($field['html_type'] == 'CheckBox' ||
1661 $field['html_type'] == 'AdvMulti-Select' ||
1662 $field['html_type'] == 'Multi-Select'
1664 $value = str_replace("|", ",", $value);
1665 $mulValues = explode(',', $value);
1666 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1668 foreach ($mulValues as $v1) {
1669 foreach ($customOption as $coID => $coValue) {
1670 if (strtolower(trim($coValue['label'])) ==
1671 strtolower(trim($v1))
1673 $val[$coValue['value']] = 1;
1685 elseif ($field['html_type'] == 'Select' ||
1686 ($field['html_type'] == 'Radio' &&
1687 $field['data_type'] != 'Boolean'
1690 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1691 foreach ($customOption as $customID => $coValue) {
1692 if (strtolower(trim($coValue['label'])) ==
1693 strtolower(trim($value))
1695 $value = $coValue['value'];
1700 elseif ($field['data_type'] == 'Date') {
1701 if (!empty($value)) {
1703 if (!empty($field['time_format'])) {
1704 $time = CRM_Utils_Request
::retrieve($fieldName .
1705 '_time', 'String', $form, FALSE, NULL, 'GET');
1707 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value .
1709 if (!empty($field['time_format'])) {
1710 $customValue[$fieldName . '_time'] = $time;
1717 $customValue[$fieldName] = $value;
1723 return $customValue;
1727 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1728 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1730 * @param int $customFieldId
1732 * @param array $removeCustomFieldTypes
1733 * Remove custom fields of a type eg: array("Individual") ;.
1736 * false if it matches else true
1738 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1739 $query = "SELECT cg.extends as extends
1740 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1741 WHERE cg.id = cf.custom_group_id
1743 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1745 $extends = CRM_Core_DAO
::singleValueQuery($query);
1747 if (in_array($extends, $removeCustomFieldTypes)) {
1759 public static function mapTableName($table) {
1764 case 'Organization':
1765 return 'civicrm_contact';
1768 return 'civicrm_activity';
1771 return 'civicrm_group';
1773 case 'Contribution':
1774 return 'civicrm_contribution';
1776 case 'ContributionRecur':
1777 return 'civicrm_contribution_recur';
1779 case 'Relationship':
1780 return 'civicrm_relationship';
1783 return 'civicrm_event';
1786 return 'civicrm_membership';
1789 case 'ParticipantRole':
1790 case 'ParticipantEventName':
1791 case 'ParticipantEventType':
1792 return 'civicrm_participant';
1795 return 'civicrm_grant';
1798 return 'civicrm_pledge';
1801 return 'civicrm_address';
1804 return 'civicrm_campaign';
1808 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1809 $qParams = array(1 => array($table, 'String'));
1810 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1813 return 'civicrm_contact';
1816 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1817 if (array_key_exists($table, $extendObjs)) {
1818 return $extendObjs[$table];
1820 CRM_Core_Error
::fatal();
1828 public static function createTable($group) {
1830 'name' => $group->table_name
,
1831 'is_multiple' => $group->is_multiple ?
1 : 0,
1832 'extends_name' => self
::mapTableName($group->extends),
1835 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1837 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1841 * Function returns formatted groupTree, sothat form can be easily build in template
1843 * @param array $groupTree
1844 * @param int $groupCount
1845 * Group count by default 1, but can varry for multiple value custom data.
1846 * @param object $form
1850 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form = NULL) {
1851 $formattedGroupTree = array();
1852 $uploadNames = $formValues = array();
1854 // retrieve qf key from url
1855 $qfKey = CRM_Utils_Request
::retrieve('qf', 'String');
1857 // fetch submitted custom field values later use to set as a default values
1859 $submittedValues = CRM_Core_BAO_Cache
::getItem('custom data', $qfKey);
1862 foreach ($groupTree as $key => $value) {
1863 if ($key === 'info') {
1867 // add group information
1868 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1869 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1870 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1871 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1872 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1873 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1874 $formattedGroupTree[$key]['style'] = CRM_Utils_Array
::value('style', $value);
1876 // this params needed of bulding multiple values
1877 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1878 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1879 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1880 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1881 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1882 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1884 // add field information
1885 foreach ($value['fields'] as $k => $properties) {
1886 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1887 if ($value = CRM_Utils_Request
::retrieve($properties['element_name'], 'String', $form, FALSE, NULL, 'POST')) {
1888 $formValues[$properties['element_name']] = $value;
1890 elseif (isset($submittedValues[$properties['element_name']])) {
1891 $properties['element_value'] = $submittedValues[$properties['element_name']];
1893 if (isset($properties['customValue']) &&
1894 !CRM_Utils_System
::isNull($properties['customValue']) &&
1895 !isset($properties['element_value'])
1897 if (isset($properties['customValue'][$groupCount])) {
1898 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1899 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1900 if ($properties['data_type'] == 'File') {
1901 $properties['element_value'] = $properties['customValue'][$groupCount];
1902 $uploadNames[] = $properties['element_name'];
1905 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1909 unset($properties['customValue']);
1910 $formattedGroupTree[$key]['fields'][$k] = $properties;
1915 if (count($formValues)) {
1916 $qf = $form->get('qfKey');
1917 $form->assign('qfKey', $qf);
1918 CRM_Core_BAO_Cache
::setItem($formValues, 'custom data', $qf);
1921 // hack for field type File
1922 $formUploadNames = $form->get('uploadNames');
1923 if (is_array($formUploadNames)) {
1924 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1927 $form->set('uploadNames', $uploadNames);
1930 return $formattedGroupTree;
1934 * Build custom data view.
1936 * @param CRM_Core_Form $form
1938 * @param array $groupTree
1939 * @param bool $returnCount
1940 * True if customValue count needs to be returned.
1942 * @param null $prefix
1943 * @param int $customValueId
1944 * @param int $entityId
1948 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL, $entityId = NULL) {
1950 foreach ($groupTree as $key => $group) {
1951 if ($key === 'info') {
1955 foreach ($group['fields'] as $k => $properties) {
1956 $groupID = $group['id'];
1957 if (!empty($properties['customValue'])) {
1958 foreach ($properties['customValue'] as $values) {
1959 if (!empty($customValueId) && $customValueId != $values['id']) {
1962 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1963 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1964 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1965 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1966 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1967 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1968 $details[$groupID][$values['id']]['style'] = CRM_Utils_Array
::value('style', $group);
1969 $details[$groupID][$values['id']]['fields'][$k] = array(
1970 'field_title' => CRM_Utils_Array
::value('label', $properties),
1971 'field_type' => CRM_Utils_Array
::value('html_type', $properties),
1972 'field_data_type' => CRM_Utils_Array
::value('data_type', $properties),
1973 'field_value' => CRM_Core_BAO_CustomField
::displayValue($values['data'], $properties['id'], $entityId),
1974 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $properties),
1976 // editable = whether this set contains any non-read-only fields
1977 if (!isset($details[$groupID][$values['id']]['editable'])) {
1978 $details[$groupID][$values['id']]['editable'] = FALSE;
1980 if (empty($properties['is_view'])) {
1981 $details[$groupID][$values['id']]['editable'] = TRUE;
1983 // also return contact reference contact id if user has view all or edit all contacts perm
1984 if ((CRM_Core_Permission
::check('view all contacts') ||
1985 CRM_Core_Permission
::check('edit all contacts'))
1987 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1990 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1995 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1996 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1997 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1998 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1999 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
2000 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
2001 $details[$groupID][0]['style'] = CRM_Utils_Array
::value('style', $group);
2002 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
2008 //return a single value count if group id is passed to function
2009 //else return a groupId and count mapped array
2011 return count($details[$gID]);
2014 $countValue = array();
2015 foreach ($details as $key => $value) {
2016 $countValue[$key] = count($details[$key]);
2022 $form->assign_by_ref("{$prefix}viewCustomData", $details);
2028 * Get the custom group titles by custom field ids.
2030 * @param array $fieldIds
2031 * Array of custom field ids.
2033 * @return array|NULL
2034 * array consisting of groups and fields labels with ids.
2036 public static function getGroupTitles($fieldIds) {
2037 if (!is_array($fieldIds) && empty($fieldIds)) {
2041 $groupLabels = array();
2042 $fIds = "(" . implode(',', $fieldIds) . ")";
2045 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2046 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2047 FROM civicrm_custom_group, civicrm_custom_field
2048 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2049 AND civicrm_custom_field.id IN {$fIds}";
2051 $dao = CRM_Core_DAO
::executeQuery($query);
2052 while ($dao->fetch()) {
2053 $groupLabels[$dao->fieldID
] = array(
2054 'fieldID' => $dao->fieldID
,
2055 'fieldLabel' => $dao->fieldLabel
,
2056 'groupID' => $dao->groupID
,
2057 'groupTitle' => $dao->groupTitle
,
2061 return $groupLabels;
2064 public static function dropAllTables() {
2065 $query = "SELECT table_name FROM civicrm_custom_group";
2066 $dao = CRM_Core_DAO
::executeQuery($query);
2068 while ($dao->fetch()) {
2069 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2070 CRM_Core_DAO
::executeQuery($query);
2075 * Check whether custom group is empty or not.
2081 * true if empty otherwise false.
2083 public static function isGroupEmpty($gID) {
2088 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2093 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2094 $value = CRM_Core_DAO
::singleValueQuery($query);
2096 if (empty($value)) {
2104 * Get the list of types for objects that a custom group extends to.
2106 * @param array $types
2107 * Var which should have the list appended.
2112 public static function getExtendedObjectTypes(&$types = array()) {
2113 static $flag = FALSE, $objTypes = array();
2116 $extendObjs = array();
2117 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2119 foreach ($extendObjs as $ovId => $ovValues) {
2120 if ($ovValues['description']) {
2121 // description is expected to be a callback func to subtypes
2122 list($callback, $args) = explode(';', trim($ovValues['description']));
2128 if (!is_array($args)) {
2129 CRM_Core_Error
::fatal('Arg is not of type array');
2132 list($className) = explode('::', $callback);
2133 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2136 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2142 $types = array_merge($types, $objTypes);
2147 * @param int $customGroupId
2148 * @param int $entityId
2152 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2153 //check whether the group is multiple
2154 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2155 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2156 $hasReachedMax = FALSE;
2158 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2160 if (!$maxMultiple) {
2161 $hasReachedMax = FALSE;
2164 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2165 //count the number of entries for a entity
2166 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2167 $params = array(1 => array($entityId, 'Integer'));
2168 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2170 if ($count >= $maxMultiple) {
2171 $hasReachedMax = TRUE;
2175 return $hasReachedMax;
2181 public static function getMultipleFieldGroup() {
2182 $multipleGroup = array();
2183 $dao = new CRM_Core_DAO_CustomGroup();
2184 $dao->is_multiple
= 1;
2185 $dao->is_active
= 1;
2187 while ($dao->fetch()) {
2188 $multipleGroup[$dao->id
] = $dao->title
;
2190 return $multipleGroup;