3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 $form
321 * @param int $entityID
322 * @param int $groupID
323 * @param string $subType
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.)
333 * The returned array is keyed by group id and has the custom group table fields
334 * and a subkey 'fields' holding the specific custom fields.
335 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
336 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
338 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
339 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
340 * With caching the performance impact would be small & the function would be cleaner
342 public static function &getTree(
354 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
358 $strSelect = $strFrom = $strWhere = $orderBy = '';
359 $tableData = array();
361 // using tableData to build the queryString
363 'civicrm_custom_field' => array(
383 'civicrm_custom_group' => array(
393 'extends_entity_column_id',
394 'extends_entity_column_value',
401 foreach ($tableData as $tableName => $tableColumn) {
402 foreach ($tableColumn as $columnName) {
403 $alias = $tableName . "_" . $columnName;
404 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
407 $strSelect = "SELECT " . implode(', ', $select);
409 // from, where, order by
411 FROM civicrm_custom_group
412 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
415 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
416 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
417 $entityType == 'Household'
419 $in = "'$entityType', 'Contact'";
421 elseif (strpos($entityType, "'") !== FALSE) {
422 // this allows the calling function to send in multiple entity types
427 $in = "'$entityType'";
432 if (is_array($subType)) {
433 $subType = implode(',', $subType);
435 if (strpos($subType, ',')) {
436 $subTypeParts = explode(',', $subType);
437 $subTypeClauses = array();
438 foreach ($subTypeParts as $subTypePart) {
439 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
.
440 trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) .
441 CRM_Core_DAO
::VALUE_SEPARATOR
;
442 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
446 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
449 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) .
450 " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
454 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
.
455 trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) .
456 CRM_Core_DAO
::VALUE_SEPARATOR
;
459 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
462 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
463 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
468 WHERE civicrm_custom_group.is_active = 1
469 AND civicrm_custom_field.is_active = 1
470 AND civicrm_custom_group.extends IN ($in)
474 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
479 WHERE civicrm_custom_group.is_active = 1
480 AND civicrm_custom_field.is_active = 1
481 AND civicrm_custom_group.extends IN ($in)
484 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
490 // since we want a specific group id we add it to the where clause
491 $strWhere .= " AND civicrm_custom_group.id = %1";
492 $params[1] = array($groupID, 'Integer');
495 // since groupID is false we need to show all Inline groups
496 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
499 // ensure that the user has access to these custom groups
500 $strWhere .= " AND " .
501 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
502 'civicrm_custom_group.'
506 ORDER BY civicrm_custom_group.weight,
507 civicrm_custom_group.title,
508 civicrm_custom_field.weight,
509 civicrm_custom_field.label
512 // final query string
513 $queryString = "$strSelect $strFrom $strWhere $orderBy";
515 // lets see if we can retrieve the groupTree from cache
516 $cacheString = $queryString;
518 $cacheString .= "_{$groupID}";
521 $cacheString .= "_Inline";
524 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
525 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
526 $cache = CRM_Utils_Cache
::singleton();
527 $tablesWithEntityData = array();
529 $groupTree = $cache->get($cacheKey);
530 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
533 if (empty($groupTree)) {
534 $groupTree = $multipleFieldGroups = array();
535 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
536 $customValueTables = array();
539 while ($crmDAO->fetch()) {
541 $groupID = $crmDAO->civicrm_custom_group_id
;
542 $fieldId = $crmDAO->civicrm_custom_field_id
;
543 if ($crmDAO->civicrm_custom_group_is_multiple
) {
544 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
546 // create an array for groups if it does not exist
547 if (!array_key_exists($groupID, $groupTree)) {
548 $groupTree[$groupID] = array();
549 $groupTree[$groupID]['id'] = $groupID;
551 // populate the group information
552 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
553 $fullFieldName = "civicrm_custom_group_$fieldName";
554 if ($fieldName == 'id' ||
555 is_null($crmDAO->$fullFieldName)
560 if ($fieldName == 'extends_entity_column_value' && $subType) {
561 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
563 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
565 $groupTree[$groupID]['fields'] = array();
567 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
570 // add the fields now (note - the query row will always contain a field)
571 // we only reset this once, since multiple values come is as multiple rows
572 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
573 $groupTree[$groupID]['fields'][$fieldId] = array();
576 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
577 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
578 // populate information for a custom field
579 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
580 $fullFieldName = "civicrm_custom_field_$fieldName";
581 if ($fieldName == 'id' ||
582 is_null($crmDAO->$fullFieldName)
586 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
590 if (!empty($customValueTables)) {
591 $groupTree['info'] = array('tables' => $customValueTables);
594 $cache->set($cacheKey, $groupTree);
595 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
597 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
598 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
599 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
600 $singleFieldTables = array();
601 // now that we have all the groups and fields, lets get the values
602 // since we need to know the table and field names
603 // add info to groupTree
605 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
606 !empty($groupTree['info']['tables'])
608 $select = $from = $where = array();
609 $groupTree['info']['where'] = NULL;
611 foreach ($groupTree['info']['tables'] as $table => $fields) {
612 $groupTree['info']['from'][] = $table;
614 "{$table}.id as {$table}_id",
615 "{$table}.entity_id as {$table}_entity_id",
617 foreach ($fields as $column => $dontCare) {
618 $select[] = "{$table}.{$column} as {$table}_{$column}";
620 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
622 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
623 if (in_array($table, $multipleFieldGroups) &&
624 self
::customGroupDataExistsForEntity($entityID, $table)
626 $entityMultipleSelectClauses[$table] = $select;
629 $singleFieldTables[] = $table;
630 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
635 if ($entityID && !empty($singleFieldTables)) {
636 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
638 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
639 if (!empty($multipleFieldTablesWithEntityData)) {
640 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
648 * Check whether the custom group has any data for the given entity.
651 * @param int $entityID
652 * Id of entity for whom we are checking data for.
653 * @param string $table
654 * Table that we are checking.
656 * @param bool $getCount
659 * does this entity have data in this custom table
661 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
665 WHERE entity_id = $entityID
667 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
669 return $recordExists;
671 return $recordExists ?
TRUE : FALSE;
675 * Build the group tree for Custom fields which are not 'is_multiple'
677 * The combination of all these fields in one query with a 'using' join was not working for
678 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
679 * mechanism as it seemed to be acceptable in this context
681 * @param array $groupTree
682 * (reference) group tree array which is being built.
683 * @param int $entityID
684 * Id of entity for whom the tree is being build up.
685 * @param array $entitySingleSelectClauses
686 * Array of select clauses relevant to the entity.
687 * @param array $singleFieldTablesWithEntityData
688 * Array of tables in which this entity has data.
690 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
691 $select = implode(', ', $entitySingleSelectClauses);
692 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
693 foreach ($singleFieldTablesWithEntityData as $table) {
694 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
700 WHERE first.entity_id = $entityID
702 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
706 * Build the group tree for Custom fields which are 'is_multiple'
708 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
710 * @param array $groupTree
711 * (reference) group tree array which is being built.
712 * @param int $entityID
713 * Id of entity for whom the tree is being build up.
714 * @param array $entityMultipleSelectClauses
715 * Array of select clauses relevant to the entity.
716 * @param array $multipleFieldTablesWithEntityData
717 * Array of tables in which this entity has data.
719 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData) {
720 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
721 $select = implode(',', $selectClauses);
725 WHERE entity_id = $entityID
727 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
732 * Build the tree entity data - starting from a query retrieving the custom fields build the group
733 * tree data for the relevant entity (entity is included in the query).
735 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
737 * @param array $groupTree
738 * (reference) group tree array which is being built.
739 * @param string $query
740 * @param array $includedTables
741 * Tables to include - required because the function (for historical reasons).
742 * iterates through the group tree
744 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables) {
745 $dao = CRM_Core_DAO
::executeQuery($query);
746 while ($dao->fetch()) {
747 foreach ($groupTree as $groupID => $group) {
748 if ($groupID === 'info') {
751 $table = $groupTree[$groupID]['table_name'];
752 //working from the groupTree instead of the table list means we have to iterate & exclude.
753 // this could possibly be re-written as other parts of the function have been refactored
754 // for now we just check if the given table is to be included in this function
755 if (!in_array($table, $includedTables)) {
758 foreach ($group['fields'] as $fieldID => $dontCare) {
759 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
766 * Build the entity-specific custom data into the group tree on a per-field basis
769 * Object representing the custom field to be populated into the groupTree.
770 * @param array $groupTree
771 * (reference) the group tree being build.
772 * @param string $table
774 * @param int $groupID
776 * @param int $fieldID
779 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID) {
780 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
781 $idName = "{$table}_id";
782 $fieldName = "{$table}_{$column}";
783 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
784 if ($dataType == 'File') {
785 if (isset($dao->$fieldName)) {
786 $config = CRM_Core_Config
::singleton();
787 $fileDAO = new CRM_Core_DAO_File();
788 $fileDAO->id
= $dao->$fieldName;
790 if ($fileDAO->find(TRUE)) {
791 $entityIDName = "{$table}_entity_id";
792 $customValue['id'] = $dao->$idName;
793 $customValue['data'] = $fileDAO->uri
;
794 $customValue['fid'] = $fileDAO->id
;
795 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
796 $customValue['displayURL'] = NULL;
797 $deleteExtra = ts('Are you sure you want to delete attached file.');
799 CRM_Core_Action
::DELETE
=> array(
800 'name' => ts('Delete Attached File'),
801 'url' => 'civicrm/file',
802 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
803 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
804 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
807 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
808 CRM_Core_Action
::DELETE
,
810 'id' => $fileDAO->id
,
811 'eid' => $dao->$entityIDName,
816 'file.manage.delete',
820 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
821 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
822 if ($fileDAO->mime_type
== "image/jpeg" ||
823 $fileDAO->mime_type
== "image/pjpeg" ||
824 $fileDAO->mime_type
== "image/gif" ||
825 $fileDAO->mime_type
== "image/x-png" ||
826 $fileDAO->mime_type
== "image/png"
828 $customValue['displayURL'] = $customValue['fileURL'];
829 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
834 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
836 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId, NULL, NULL);
837 if ($path && file_exists($path)) {
838 list($imageWidth, $imageHeight) = getimagesize($path);
839 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
840 $customValue['imageThumbWidth'] = $imageThumbWidth;
841 $customValue['imageThumbHeight'] = $imageThumbHeight;
847 $customValue = array(
848 'id' => $dao->$idName,
854 $customValue = array(
855 'id' => $dao->$idName,
856 'data' => $dao->$fieldName,
860 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
861 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
863 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
864 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
867 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
872 * Get the group title.
880 public static function getTitle($id) {
881 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
885 * Get custom group details for a group.
887 * An array containing custom group details (including their custom field) is returned.
889 * @param int $groupId
890 * Group id whose details are needed.
891 * @param bool $searchable
892 * Is this field searchable.
893 * @param array $extends
894 * Which table does it extend if any.
896 * @param null $inSelector
899 * array consisting of all group and field details
901 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
903 $groupTree = array();
904 $select = $from = $where = $orderBy = '';
906 $tableData = array();
908 // using tableData to build the queryString
910 'civicrm_custom_field' => array(
934 'civicrm_custom_group' => array(
941 'collapse_adv_display',
943 'extends_entity_column_value',
952 foreach ($tableData as $tableName => $tableColumn) {
953 foreach ($tableColumn as $columnName) {
954 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
957 $select = 'SELECT ' . implode(', ', $s);
959 // from, where, order by
960 $from = " FROM civicrm_custom_field, civicrm_custom_group";
961 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
962 AND civicrm_custom_group.is_active = 1
963 AND civicrm_custom_field.is_active = 1 ";
965 $params[1] = array($groupId, 'Integer');
966 $where .= " AND civicrm_custom_group.id = %1";
970 $where .= " AND civicrm_custom_field.is_searchable = 1";
974 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
979 foreach ($extends as $e) {
980 $clause[] = "civicrm_custom_group.extends = '$e'";
982 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
984 //include case activities customdata if case is enabled
985 if (in_array('Activity', $extends)) {
986 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
987 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
988 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
992 // ensure that the user has access to these custom groups
994 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
995 'civicrm_custom_group.'
998 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1000 // final query string
1001 $queryString = $select . $from . $where . $orderBy;
1004 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1007 while ($crmDAO->fetch()) {
1008 $groupId = $crmDAO->civicrm_custom_group_id
;
1009 $fieldId = $crmDAO->civicrm_custom_field_id
;
1011 // create an array for groups if it does not exist
1012 if (!array_key_exists($groupId, $groupTree)) {
1013 $groupTree[$groupId] = array();
1014 $groupTree[$groupId]['id'] = $groupId;
1016 foreach ($tableData['civicrm_custom_group'] as $v) {
1017 $fullField = "civicrm_custom_group_" . $v;
1019 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1023 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1026 $groupTree[$groupId]['fields'] = array();
1029 // add the fields now (note - the query row will always contain a field)
1030 $groupTree[$groupId]['fields'][$fieldId] = array();
1031 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1033 foreach ($tableData['civicrm_custom_field'] as $v) {
1034 $fullField = "civicrm_custom_field_" . $v;
1035 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1038 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1046 * @param $entityType
1048 * @param string $cidToken
1052 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1054 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1056 // get 'Tab' and 'Tab with table' groups
1057 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1058 $customGroupDAO->whereAdd("is_active = 1");
1060 // add whereAdd for entity type
1061 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1065 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1066 $customGroupDAO->whereAdd($permissionClause);
1069 $customGroupDAO->orderBy('weight');
1070 $customGroupDAO->find();
1072 // process each group with menu tab
1073 while ($customGroupDAO->fetch()) {
1075 $group['id'] = $customGroupDAO->id
;
1076 $group['path'] = $path;
1077 $group['title'] = "$customGroupDAO->title";
1078 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1079 $group['extra'] = array('gid' => $customGroupDAO->id
);
1080 $group['table_name'] = $customGroupDAO->table_name
;
1081 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1089 * Get the table name for the entity type
1090 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1091 * tableName is 'civicrm_contact'
1093 * @param string $entityType
1094 * What entity are we extending here ?.
1099 * @see _apachesolr_civiAttachments_dereference_file_parent
1101 public static function getTableNameByEntityName($entityType) {
1103 switch ($entityType) {
1107 case 'Organization':
1108 $tableName = 'civicrm_contact';
1111 case 'Contribution':
1112 $tableName = 'civicrm_contribution';
1116 $tableName = 'civicrm_group';
1119 // DRAFTING: Verify if we cannot make it pluggable
1122 $tableName = 'civicrm_activity';
1125 case 'Relationship':
1126 $tableName = 'civicrm_relationship';
1130 $tableName = 'civicrm_membership';
1134 $tableName = 'civicrm_participant';
1138 $tableName = 'civicrm_event';
1142 $tableName = 'civicrm_grant';
1145 // need to add cases for Location, Address
1152 * Get a list of custom groups which extend a given entity type.
1153 * If there are custom-groups which only apply to certain subtypes,
1154 * those WILL be included.
1156 * @param string $entityType
1158 * @return CRM_Core_DAO_CustomGroup
1160 public static function getAllCustomGroupsByBaseEntity($entityType) {
1161 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1162 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1163 return $customGroupDAO;
1167 * Add the whereAdd clause for the DAO depending on the type of entity
1168 * the custom group is extending.
1170 * @param object $customGroupDAO
1171 * @param string $entityType
1172 * What entity are we extending here ?.
1174 * @param int $entityID
1175 * @param bool $allSubtypes
1177 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1178 $addSubtypeClause = FALSE;
1180 switch ($entityType) {
1182 // if contact, get all related to contact
1183 $extendList = "'Contact','Individual','Household','Organization'";
1184 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1185 if (!$allSubtypes) {
1186 $addSubtypeClause = TRUE;
1192 case 'Organization':
1193 // is I/H/O then get I/H/O and contact
1194 $extendList = "'Contact','$entityType'";
1195 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1196 if (!$allSubtypes) {
1197 $addSubtypeClause = TRUE;
1205 case 'Contribution':
1208 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1212 if ($addSubtypeClause) {
1213 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1215 if (!empty($csType)) {
1216 $subtypeClause = array();
1217 foreach ($csType as $subtype) {
1218 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1219 CRM_Core_DAO
::VALUE_SEPARATOR
;
1220 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1222 $subtypeClause[] = "extends_entity_column_value IS NULL";
1223 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1227 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1233 * Delete the Custom Group.
1235 * @param CRM_Core_BAO_CustomGroup $group
1236 * Custom group object.
1237 * @param bool $force
1238 * whether to force the deletion, even if there are custom fields.
1241 * False if field exists for this group, true if group gets deleted.
1243 public static function deleteGroup($group, $force = FALSE) {
1245 //check whether this contain any custom fields
1246 $customField = new CRM_Core_DAO_CustomField();
1247 $customField->custom_group_id
= $group->id
;
1248 $customField->find();
1250 // return early if there are custom fields and we're not
1251 // forcing the delete, otherwise delete the fields one by one
1252 while ($customField->fetch()) {
1256 CRM_Core_BAO_CustomField
::deleteField($customField);
1259 // drop the table associated with this custom group
1260 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1262 //delete custom group
1265 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1273 * @param array $groupTree
1274 * @param array $defaults
1275 * @param bool $viewMode
1276 * @param bool $inactiveNeeded
1277 * @param int $action
1279 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1280 foreach ($groupTree as $id => $group) {
1281 if (!isset($group['fields'])) {
1284 foreach ($group['fields'] as $field) {
1285 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1286 $value = $field['element_value'];
1288 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1289 ($action != CRM_Core_Action
::UPDATE ||
1291 !array_key_exists('element_value', $field)
1294 $value = $viewMode ?
NULL : $field['default_value'];
1300 if (empty($field['element_name'])) {
1304 $elementName = $field['element_name'];
1306 switch ($field['html_type']) {
1307 case 'Multi-Select':
1308 case 'AdvMulti-Select':
1310 $defaults[$elementName] = array();
1311 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1313 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1314 if (isset($value)) {
1315 foreach ($customOption as $customValue => $customLabel) {
1316 if (in_array($customValue, $checkedData)) {
1317 if ($field['html_type'] == 'CheckBox') {
1318 $defaults[$elementName][$customValue] = 1;
1321 $defaults[$elementName][$customValue] = $customValue;
1325 $defaults[$elementName][$customValue] = 0;
1331 if (isset($field['customValue']['data'])) {
1332 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1333 foreach ($customOption as $val) {
1334 if (in_array($val['value'], $checkedData)) {
1335 if ($field['html_type'] == 'CheckBox') {
1336 $defaults[$elementName][$val['value']] = 1;
1339 $defaults[$elementName][$val['value']] = $val['value'];
1343 $defaults[$elementName][$val['value']] = 0;
1348 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1349 foreach ($customOption as $val) {
1350 if (in_array($val['value'], $checkedValue)) {
1351 if ($field['html_type'] == 'CheckBox') {
1352 $defaults[$elementName][$val['value']] = 1;
1355 $defaults[$elementName][$val['value']] = $val['value'];
1364 if (isset($value)) {
1365 if (empty($field['time_format'])) {
1366 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1367 $field['date_format']
1371 $timeElement = $elementName . '_time';
1372 if (substr($elementName, -1) == ']') {
1373 $timeElement = substr($elementName, 0, -1) . '_time]';
1375 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1380 case 'Multi-Select Country':
1381 case 'Multi-Select State/Province':
1382 if (isset($value)) {
1383 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1384 foreach ($checkedValue as $val) {
1386 $defaults[$elementName][$val] = $val;
1392 case 'Select Country':
1394 $defaults[$elementName] = $value;
1397 $config = CRM_Core_Config
::singleton();
1398 $defaults[$elementName] = $config->defaultContactCountry
;
1403 if ($field['data_type'] == "Float") {
1404 $defaults[$elementName] = (float) $value;
1406 elseif ($field['data_type'] == 'Money' &&
1407 $field['html_type'] == 'Text'
1409 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1412 $defaults[$elementName] = $value;
1420 * PostProcess function.
1422 * @param array $groupTree
1423 * @param array $params
1424 * @param bool $skipFile
1426 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1427 // Get the Custom form values and groupTree
1428 // first reset all checkbox and radio data
1429 foreach ($groupTree as $groupID => $group) {
1430 if ($groupID === 'info') {
1433 foreach ($group['fields'] as $field) {
1434 $fieldId = $field['id'];
1436 //added Multi-Select option in the below if-statement
1437 if ($field['html_type'] == 'CheckBox' ||
1438 $field['html_type'] == 'Radio' ||
1439 $field['html_type'] == 'AdvMulti-Select' ||
1440 $field['html_type'] == 'Multi-Select'
1442 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1446 foreach ($params as $key => $val) {
1447 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1448 $match[1] == $field['id']
1454 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1455 // field exists in db so populate value from "form".
1456 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1459 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1461 //added for CheckBox
1465 $customValue = array_keys($v);
1466 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1467 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1468 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1471 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1475 //added for Advanced Multi-Select
1477 case 'AdvMulti-Select':
1478 //added for Multi-Select
1479 case 'Multi-Select':
1481 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1482 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1483 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1486 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1491 $date = CRM_Utils_Date
::processDate($v);
1492 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1500 //store the file in d/b
1501 $entityId = explode('=', $groupTree['info']['where'][0]);
1502 $fileParams = array('upload_date' => date('Ymdhis'));
1504 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1505 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1508 $fileParams['uri'] = $v['name'];
1509 $fileParams['mime_type'] = $v['type'];
1510 CRM_Core_BAO_File
::filePostProcess($v['name'],
1511 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1512 $groupTree[$groupID]['table_name'],
1517 'custom_' . $fieldId,
1521 $defaults = array();
1522 $paramsFile = array(
1523 'entity_table' => $groupTree[$groupID]['table_name'],
1524 'entity_id' => $entityId[1],
1527 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1532 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1536 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1544 * Generic function to build all the form elements for a specific group tree.
1546 * @param CRM_Core_Form $form
1548 * @param array $groupTree
1549 * The group tree object.
1550 * @param bool $inactiveNeeded
1551 * Return inactive custom groups.
1552 * @param string $prefix
1553 * Prefix for custom grouptree assigned to template.
1555 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1556 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1558 // this is fix for date field
1559 $form->assign('currentYear', date('Y'));
1561 foreach ($groupTree as $id => $group) {
1562 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1563 foreach ($group['fields'] as $field) {
1564 $required = CRM_Utils_Array
::value('is_required', $field);
1566 if ($field['data_type'] == 'File') {
1567 if (!empty($field['element_value']['data'])) {
1572 $fieldId = $field['id'];
1573 $elementName = $field['element_name'];
1574 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1580 * Extract the get params from the url, validate and store it in session.
1582 * @param CRM_Core_Form $form
1584 * @param string $type
1585 * The type of custom group we are using.
1589 public static function extractGetParams(&$form, $type) {
1594 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1595 $customValue = array();
1604 foreach ($groupTree as $group) {
1605 if (!isset($group['fields'])) {
1608 foreach ($group['fields'] as $key => $field) {
1609 $fieldName = 'custom_' . $key;
1610 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1614 if (!in_array($field['html_type'], $htmlType) ||
1615 $field['data_type'] == 'Boolean'
1617 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1619 if ($field['html_type'] == 'CheckBox' ||
1620 $field['html_type'] == 'AdvMulti-Select' ||
1621 $field['html_type'] == 'Multi-Select'
1623 $value = str_replace("|", ",", $value);
1624 $mulValues = explode(',', $value);
1625 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1627 foreach ($mulValues as $v1) {
1628 foreach ($customOption as $coID => $coValue) {
1629 if (strtolower(trim($coValue['label'])) ==
1630 strtolower(trim($v1))
1632 $val[$coValue['value']] = 1;
1644 elseif ($field['html_type'] == 'Select' ||
1645 ($field['html_type'] == 'Radio' &&
1646 $field['data_type'] != 'Boolean'
1649 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1650 foreach ($customOption as $customID => $coValue) {
1651 if (strtolower(trim($coValue['label'])) ==
1652 strtolower(trim($value))
1654 $value = $coValue['value'];
1659 elseif ($field['data_type'] == 'Date') {
1660 if (!empty($value)) {
1662 if (!empty($field['time_format'])) {
1663 $time = CRM_Utils_Request
::retrieve($fieldName .
1664 '_time', 'String', $form, FALSE, NULL, 'GET');
1666 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value .
1668 if (!empty($field['time_format'])) {
1669 $customValue[$fieldName . '_time'] = $time;
1676 $customValue[$fieldName] = $value;
1682 return $customValue;
1686 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1687 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1689 * @param int $customFieldId
1691 * @param array $removeCustomFieldTypes
1692 * Remove custom fields of a type eg: array("Individual") ;.
1695 * false if it matches else true
1697 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1698 $query = "SELECT cg.extends as extends
1699 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1700 WHERE cg.id = cf.custom_group_id
1702 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1704 $extends = CRM_Core_DAO
::singleValueQuery($query);
1706 if (in_array($extends, $removeCustomFieldTypes)) {
1718 public static function mapTableName($table) {
1723 case 'Organization':
1724 return 'civicrm_contact';
1727 return 'civicrm_activity';
1730 return 'civicrm_group';
1732 case 'Contribution':
1733 return 'civicrm_contribution';
1735 case 'Relationship':
1736 return 'civicrm_relationship';
1739 return 'civicrm_event';
1742 return 'civicrm_membership';
1745 case 'ParticipantRole':
1746 case 'ParticipantEventName':
1747 case 'ParticipantEventType':
1748 return 'civicrm_participant';
1751 return 'civicrm_grant';
1754 return 'civicrm_pledge';
1757 return 'civicrm_address';
1760 return 'civicrm_campaign';
1764 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1765 $qParams = array(1 => array($table, 'String'));
1766 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1769 return 'civicrm_contact';
1772 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1773 if (array_key_exists($table, $extendObjs)) {
1774 return $extendObjs[$table];
1776 CRM_Core_Error
::fatal();
1784 public static function createTable($group) {
1786 'name' => $group->table_name
,
1787 'is_multiple' => $group->is_multiple ?
1 : 0,
1788 'extends_name' => self
::mapTableName($group->extends),
1791 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1793 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1797 * Function returns formatted groupTree, sothat form can be easily build in template
1799 * @param array $groupTree
1800 * @param int $groupCount
1801 * Group count by default 1, but can varry for multiple value custom data.
1802 * @param object $form
1806 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1807 $formattedGroupTree = array();
1808 $uploadNames = array();
1810 foreach ($groupTree as $key => $value) {
1811 if ($key === 'info') {
1815 // add group information
1816 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1817 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1818 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1819 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1820 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1821 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1823 // this params needed of bulding multiple values
1824 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1825 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1826 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1827 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1828 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1829 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1831 // add field information
1832 foreach ($value['fields'] as $k => $properties) {
1833 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1834 if (isset($properties['customValue']) &&
1835 !CRM_Utils_System
::isNull($properties['customValue'])
1837 if (isset($properties['customValue'][$groupCount])) {
1838 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1839 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1840 if ($properties['data_type'] == 'File') {
1841 $properties['element_value'] = $properties['customValue'][$groupCount];
1842 $uploadNames[] = $properties['element_name'];
1845 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1849 unset($properties['customValue']);
1850 $formattedGroupTree[$key]['fields'][$k] = $properties;
1855 // hack for field type File
1856 $formUploadNames = $form->get('uploadNames');
1857 if (is_array($formUploadNames)) {
1858 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1861 $form->set('uploadNames', $uploadNames);
1864 return $formattedGroupTree;
1868 * Build custom data view.
1870 * @param CRM_Core_Form $form
1872 * @param array $groupTree
1873 * @param bool $returnCount
1874 * True if customValue count needs to be returned.
1876 * @param null $prefix
1877 * @param int $customValueId
1881 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1883 foreach ($groupTree as $key => $group) {
1884 if ($key === 'info') {
1888 foreach ($group['fields'] as $k => $properties) {
1889 $groupID = $group['id'];
1890 if (!empty($properties['customValue'])) {
1891 foreach ($properties['customValue'] as $values) {
1892 if (!empty($customValueId) && $customValueId != $values['id']) {
1895 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1896 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1897 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1898 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1899 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1900 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1901 $details[$groupID][$values['id']]['fields'][$k] = array(
1902 'field_title' => CRM_Utils_Array
::value('label', $properties),
1903 'field_type' => CRM_Utils_Array
::value('html_type',
1906 'field_data_type' => CRM_Utils_Array
::value('data_type',
1909 'field_value' => self
::formatCustomValues($values,
1912 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1916 // also return contact reference contact id if user has view all or edit all contacts perm
1917 if ((CRM_Core_Permission
::check('view all contacts') ||
1918 CRM_Core_Permission
::check('edit all contacts'))
1920 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1923 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1928 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1929 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1930 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1931 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1932 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1933 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1934 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1940 //return a single value count if group id is passed to function
1941 //else return a groupId and count mapped array
1943 return count($details[$gID]);
1946 $countValue = array();
1947 foreach ($details as $key => $value) {
1948 $countValue[$key] = count($details[$key]);
1954 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1960 * Format custom value according to data, view mode
1962 * @param array $values
1963 * Associated array of custom values.
1964 * @param array $field
1965 * @param bool $dncOptionPerLine
1966 * True if optionPerLine should not be consider.
1968 * @return array|null|string
1970 public static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1971 $value = $values['data'];
1973 //changed isset CRM-4601
1974 if (CRM_Utils_System
::isNull($value)) {
1978 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1979 $dataType = CRM_Utils_Array
::value('data_type', $field);
1980 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1981 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1982 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1985 $freezeStringChecked = "";
1987 switch ($dataType) {
1989 $customFormat = NULL;
1991 $actualPHPFormats = CRM_Core_SelectValues
::datePluginToPHPFormats();
1993 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
1994 if (array_key_exists($format, $actualPHPFormats)) {
1995 $customTimeFormat = (array) CRM_Utils_Array
::value($format, $actualPHPFormats);
1996 switch ($timeFormat) {
1998 $customTimeFormat[] = 'g:iA';
2002 $customTimeFormat[] = 'G:i';
2006 // if time is not selected remove time from value
2007 $value = substr($value, 0, 10);
2009 $customFormat = implode(" ", $customTimeFormat);
2012 $retValue = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
2016 if ($value == '1') {
2017 $retValue = $freezeStringChecked . ts('Yes') . "\n";
2020 $retValue = $freezeStringChecked . ts('No') . "\n";
2026 $retValue = CRM_Utils_System
::formatWikiURL($value);
2031 $retValue = $values;
2034 case 'ContactReference':
2035 if (!empty($values['data'])) {
2036 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
2045 if ($htmlType == 'Text') {
2046 $retValue = (float) $value;
2050 if ($htmlType == 'Text') {
2051 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2056 if (in_array($htmlType, array('Text', 'TextArea'))) {
2060 // note that if its not text / textarea, the code falls thru and executes
2061 // the below case also
2062 case 'StateProvince':
2067 //added check for Multi-Select in the below if-statement
2068 $customData[] = $value;
2070 //form custom data for multiple-valued custom data
2071 switch ($htmlType) {
2072 case 'Multi-Select Country':
2073 case 'Select Country':
2074 $customData = $value;
2075 if (!is_array($value)) {
2076 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2079 SELECT id as value, name as label
2080 FROM civicrm_country";
2081 $coDAO = CRM_Core_DAO
::executeQuery($query);
2084 case 'Select State/Province':
2085 case 'Multi-Select State/Province':
2086 $customData = $value;
2087 if (!is_array($value)) {
2088 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2092 SELECT id as value, name as label
2093 FROM civicrm_state_province";
2094 $coDAO = CRM_Core_DAO
::executeQuery($query);
2098 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2099 if ($option_group_id) {
2100 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2105 case 'AdvMulti-Select':
2106 case 'Multi-Select':
2107 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2109 if ($option_group_id) {
2110 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2114 if (is_object($coDAO)) {
2115 while ($coDAO->fetch()) {
2116 if ($dataType == 'Country') {
2117 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2118 // and already extracted to .pot files.
2119 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
2121 elseif ($dataType == 'StateProvince') {
2122 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
2125 $options[$coDAO->value
] = $coDAO->label
;
2130 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
2133 foreach ($options as $optionValue => $optionLabel) {
2134 if ($dataType == 'Money') {
2135 foreach ($customData as $k => $v) {
2136 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
2140 //to show only values that are checked
2141 if (in_array((string) $optionValue, $customData)) {
2142 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
2143 if (!$optionPerLine ||
$dncOptionPerLine) {
2147 $retValue .= $checked . $optionLabel;
2150 $retValue[] = $checked . $optionLabel;
2157 //special case for option per line formatting
2158 if ($optionPerLine > 1 && is_array($retValue)) {
2161 $displayValues = array();
2162 $displayString = '';
2163 foreach ($retValue as $val) {
2164 if ($displayString) {
2165 $displayString .= ", ";
2168 $displayString .= $val;
2172 if (($rowCounter == $optionPerLine) ||
2173 ($fieldCounter == count($retValue))
2175 $displayValues[] = $displayString;
2176 $displayString = '';
2180 $retValue = $displayValues;
2183 $retValue = isset($retValue) ?
$retValue : NULL;
2188 * Get the custom group titles by custom field ids.
2190 * @param array $fieldIds
2191 * Array of custom field ids.
2193 * @return array|NULL
2194 * array consisting of groups and fields labels with ids.
2196 public static function getGroupTitles($fieldIds) {
2197 if (!is_array($fieldIds) && empty($fieldIds)) {
2201 $groupLabels = array();
2202 $fIds = "(" . implode(',', $fieldIds) . ")";
2205 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2206 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2207 FROM civicrm_custom_group, civicrm_custom_field
2208 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2209 AND civicrm_custom_field.id IN {$fIds}";
2211 $dao = CRM_Core_DAO
::executeQuery($query);
2212 while ($dao->fetch()) {
2213 $groupLabels[$dao->fieldID
] = array(
2214 'fieldID' => $dao->fieldID
,
2215 'fieldLabel' => $dao->fieldLabel
,
2216 'groupID' => $dao->groupID
,
2217 'groupTitle' => $dao->groupTitle
,
2221 return $groupLabels;
2224 public static function dropAllTables() {
2225 $query = "SELECT table_name FROM civicrm_custom_group";
2226 $dao = CRM_Core_DAO
::executeQuery($query);
2228 while ($dao->fetch()) {
2229 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2230 CRM_Core_DAO
::executeQuery($query);
2235 * Check whether custom group is empty or not.
2241 * true if empty otherwise false.
2243 public static function isGroupEmpty($gID) {
2248 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2253 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2254 $value = CRM_Core_DAO
::singleValueQuery($query);
2256 if (empty($value)) {
2264 * Get the list of types for objects that a custom group extends to.
2266 * @param array $types
2267 * Var which should have the list appended.
2272 public static function getExtendedObjectTypes(&$types = array()) {
2273 static $flag = FALSE, $objTypes = array();
2276 $extendObjs = array();
2277 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2279 foreach ($extendObjs as $ovId => $ovValues) {
2280 if ($ovValues['description']) {
2281 // description is expected to be a callback func to subtypes
2282 list($callback, $args) = explode(';', trim($ovValues['description']));
2288 if (!is_array($args)) {
2289 CRM_Core_Error
::fatal('Arg is not of type array');
2292 list($className) = explode('::', $callback);
2293 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2296 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2302 $types = array_merge($types, $objTypes);
2307 * @param int $customGroupId
2308 * @param int $entityId
2312 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2313 //check whether the group is multiple
2314 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2315 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2316 $hasReachedMax = FALSE;
2318 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2320 if (!$maxMultiple) {
2321 $hasReachedMax = FALSE;
2324 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2325 //count the number of entries for a entity
2326 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2327 $params = array(1 => array($entityId, 'Integer'));
2328 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2330 if ($count >= $maxMultiple) {
2331 $hasReachedMax = TRUE;
2335 return $hasReachedMax;
2341 public static function getMultipleFieldGroup() {
2342 $multipleGroup = array();
2343 $dao = new CRM_Core_DAO_CustomGroup();
2344 $dao->is_multiple
= 1;
2346 while ($dao->fetch()) {
2347 $multipleGroup[$dao->id
] = $dao->title
;
2349 return $multipleGroup;