3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 * Business object for managing custom data groups
40 class CRM_Core_BAO_CustomGroup
extends CRM_Core_DAO_CustomGroup
{
45 public function __construct() {
46 parent
::__construct();
50 * Takes an associative array and creates a custom group object
52 * This function is invoked from within the web form layer and also from the api layer
54 * @param array $params
55 * (reference) an assoc array of name/value pairs.
57 * @return CRM_Core_DAO_CustomGroup
60 public static function create(&$params) {
61 // create custom group dao, populate fields and then save.
62 $group = new CRM_Core_DAO_CustomGroup();
63 $group->title
= $params['title'];
65 if (in_array($params['extends'][0],
68 'ParticipantEventName',
69 'ParticipantEventType',
72 $group->extends = 'Participant';
75 $group->extends = $params['extends'][0];
78 $group->extends_entity_column_id
= 'null';
80 $params['extends'][0] == 'ParticipantRole' ||
81 $params['extends'][0] == 'ParticipantEventName' ||
82 $params['extends'][0] == 'ParticipantEventType'
84 $group->extends_entity_column_id
=
85 CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $params['extends'][0], 'value', 'name');
88 //this is format when form get submit.
89 $extendsChildType = CRM_Utils_Array
::value(1, $params['extends']);
90 //lets allow user to pass direct child type value, CRM-6893
91 if (!empty($params['extends_entity_column_value'])) {
92 $extendsChildType = $params['extends_entity_column_value'];
94 if (!CRM_Utils_System
::isNull($extendsChildType)) {
95 $extendsChildType = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendsChildType);
96 if (CRM_Utils_Array
::value(0, $params['extends']) == 'Relationship') {
97 $extendsChildType = str_replace(array('_a_b', '_b_a'), array(
100 ), $extendsChildType);
102 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
103 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType .
104 CRM_Core_DAO
::VALUE_SEPARATOR
;
108 $extendsChildType = 'null';
110 $group->extends_entity_column_value
= $extendsChildType;
112 if (isset($params['id'])) {
113 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
118 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
122 'collapse_adv_display',
128 foreach ($fields as $field) {
129 $group->$field = CRM_Utils_Array
::value($field, $params, FALSE);
131 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
132 $params['max_multiple'] >= '0'
133 ) ?
$params['max_multiple'] : 'null' : 'null';
135 $tableName = $oldTableName = NULL;
136 if (isset($params['id'])) {
137 $group->id
= $params['id'];
138 //check whether custom group was changed from single-valued to multiple-valued
139 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
144 if ((!empty($params['is_multiple']) ||
$isMultiple) &&
145 ($params['is_multiple'] != $isMultiple)
147 $oldTableName = CRM_Core_DAO
::getFieldValue('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
237 public static function retrieve(&$params, &$defaults) {
238 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
242 * Update the is_active flag in the db
245 * Id of the database record.
246 * @param bool $is_activeValue we want to set the is_active field.
247 * Value we want to set the is_active field.
250 * DAO object on sucess, null otherwise
253 public static function setIsActive($id, $is_active) {
255 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
258 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
261 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
265 * Determine if given entity (sub)type has any custom groups
267 * @param string $extends
268 * E.g. "Individual", "Activity".
269 * @param int $columnId
270 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
271 * @param string $columnValue
272 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
276 public static function hasCustomGroup($extends, $columnId, $columnValue) {
277 $dao = new CRM_Core_DAO_CustomGroup();
278 $dao->extends = $extends;
279 $dao->extends_entity_column_id
= $columnId;
281 CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) .
282 CRM_Core_DAO
::VALUE_SEPARATOR
;
283 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
284 //$dao->extends_entity_column_value = $columnValue;
285 return $dao->find() ?
TRUE : FALSE;
289 * Determine if there are any CustomGroups for the given $activityTypeId.
290 * If none found, create one.
292 * @param int $activityTypeId
295 * TRUE if a group is found or created; FALSE on error
297 public static function autoCreateByActivityType($activityTypeId) {
298 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
301 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
304 'extends' => 'Activity',
305 'extends_entity_column_id' => NULL,
306 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
307 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
311 $result = civicrm_api('CustomGroup', 'create', $params);
312 return !$result['is_error'];
316 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
317 * This may also include entity specific data values.
319 * An array containing all custom groups and their custom fields is returned.
321 * @param string $entityType
322 * Of the contact whose contact type is needed.
323 * @param CRM_Core_Form $form
324 * Not used but required.
325 * @param int $entityID
326 * @param int $groupID
327 * @param string $subType
328 * @param string $subName
329 * @param bool $fromCache
330 * @param bool $onlySubType
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
344 public static function &getTree(
355 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
359 $strSelect = $strFrom = $strWhere = $orderBy = '';
360 $tableData = array();
362 // using tableData to build the queryString
364 'civicrm_custom_field' => array(
384 'civicrm_custom_group' => array(
394 'extends_entity_column_id',
395 'extends_entity_column_value',
402 foreach ($tableData as $tableName => $tableColumn) {
403 foreach ($tableColumn as $columnName) {
404 $alias = $tableName . "_" . $columnName;
405 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
408 $strSelect = "SELECT " . implode(', ', $select);
410 // from, where, order by
412 FROM civicrm_custom_group
413 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
416 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
417 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
418 $entityType == 'Household'
420 $in = "'$entityType', 'Contact'";
422 elseif (strpos($entityType, "'") !== FALSE) {
423 // this allows the calling function to send in multiple entity types
428 $in = "'$entityType'";
433 if (is_array($subType)) {
434 $subType = implode(',', $subType);
436 if (strpos($subType, ',')) {
437 $subTypeParts = explode(',', $subType);
438 $subTypeClauses = array();
439 foreach ($subTypeParts as $subTypePart) {
440 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
.
441 trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) .
442 CRM_Core_DAO
::VALUE_SEPARATOR
;
443 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
447 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
450 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) .
451 " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
455 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
.
456 trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) .
457 CRM_Core_DAO
::VALUE_SEPARATOR
;
460 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
463 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
464 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
469 WHERE civicrm_custom_group.is_active = 1
470 AND civicrm_custom_field.is_active = 1
471 AND civicrm_custom_group.extends IN ($in)
475 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
480 WHERE civicrm_custom_group.is_active = 1
481 AND civicrm_custom_field.is_active = 1
482 AND civicrm_custom_group.extends IN ($in)
483 AND civicrm_custom_group.extends_entity_column_value IS NULL
489 // since we want a specific group id we add it to the where clause
490 $strWhere .= " AND civicrm_custom_group.id = %1";
491 $params[1] = array($groupID, 'Integer');
494 // since groupID is false we need to show all Inline groups
495 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
498 // ensure that the user has access to these custom groups
499 $strWhere .= " AND " .
500 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
501 'civicrm_custom_group.'
505 ORDER BY civicrm_custom_group.weight,
506 civicrm_custom_group.title,
507 civicrm_custom_field.weight,
508 civicrm_custom_field.label
511 // final query string
512 $queryString = "$strSelect $strFrom $strWhere $orderBy";
514 // lets see if we can retrieve the groupTree from cache
515 $cacheString = $queryString;
517 $cacheString .= "_{$groupID}";
520 $cacheString .= "_Inline";
523 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
524 $multipleFieldGroupCacheKey =
525 "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 unknown_type $groupID
776 * @param unknown_type $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'] =
835 str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
837 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId,
840 if ($path && file_exists($path)) {
841 list($imageWidth, $imageHeight) = getimagesize($path);
842 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
843 $customValue['imageThumbWidth'] = $imageThumbWidth;
844 $customValue['imageThumbHeight'] = $imageThumbHeight;
850 $customValue = array(
851 'id' => $dao->$idName,
857 $customValue = array(
858 'id' => $dao->$idName,
859 'data' => $dao->$fieldName,
863 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
864 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
866 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
867 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
870 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
875 * Get the group title.
885 public static function getTitle($id) {
886 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
890 * Get custom group details for a group.
892 * An array containing custom group details (including their custom field) is returned.
894 * @param int $groupId
895 * Group id whose details are needed.
896 * @param bool $searchable
897 * Is this field searchable.
898 * @param array $extends
899 * Which table does it extend if any.
901 * @param null $inSelector
904 * array consisting of all group and field details
909 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
911 $groupTree = array();
912 $select = $from = $where = $orderBy = '';
914 $tableData = array();
916 // using tableData to build the queryString
918 'civicrm_custom_field' => array(
942 'civicrm_custom_group' => array(
949 'collapse_adv_display',
951 'extends_entity_column_value',
960 foreach ($tableData as $tableName => $tableColumn) {
961 foreach ($tableColumn as $columnName) {
962 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
965 $select = 'SELECT ' . implode(', ', $s);
967 // from, where, order by
968 $from = " FROM civicrm_custom_field, civicrm_custom_group";
969 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
970 AND civicrm_custom_group.is_active = 1
971 AND civicrm_custom_field.is_active = 1 ";
973 $params[1] = array($groupId, 'Integer');
974 $where .= " AND civicrm_custom_group.id = %1";
978 $where .= " AND civicrm_custom_field.is_searchable = 1";
982 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
987 foreach ($extends as $e) {
988 $clause[] = "civicrm_custom_group.extends = '$e'";
990 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
992 //include case activities customdata if case is enabled
993 if (in_array('Activity', $extends)) {
994 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
995 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
996 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
1000 // ensure that the user has access to these custom groups
1002 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1003 'civicrm_custom_group.'
1006 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1008 // final query string
1009 $queryString = $select . $from . $where . $orderBy;
1012 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1015 while ($crmDAO->fetch()) {
1016 $groupId = $crmDAO->civicrm_custom_group_id
;
1017 $fieldId = $crmDAO->civicrm_custom_field_id
;
1019 // create an array for groups if it does not exist
1020 if (!array_key_exists($groupId, $groupTree)) {
1021 $groupTree[$groupId] = array();
1022 $groupTree[$groupId]['id'] = $groupId;
1024 foreach ($tableData['civicrm_custom_group'] as $v) {
1025 $fullField = "civicrm_custom_group_" . $v;
1027 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1031 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1034 $groupTree[$groupId]['fields'] = array();
1037 // add the fields now (note - the query row will always contain a field)
1038 $groupTree[$groupId]['fields'][$fieldId] = array();
1039 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1041 foreach ($tableData['civicrm_custom_field'] as $v) {
1042 $fullField = "civicrm_custom_field_" . $v;
1043 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1046 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1054 * @param $entityType
1056 * @param string $cidToken
1060 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1062 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1064 // get 'Tab' and 'Tab with table' groups
1065 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1066 $customGroupDAO->whereAdd("is_active = 1");
1068 // add whereAdd for entity type
1069 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1073 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1074 $customGroupDAO->whereAdd($permissionClause);
1077 $customGroupDAO->orderBy('weight');
1078 $customGroupDAO->find();
1080 // process each group with menu tab
1081 while ($customGroupDAO->fetch()) {
1083 $group['id'] = $customGroupDAO->id
;
1084 $group['path'] = $path;
1085 $group['title'] = "$customGroupDAO->title";
1086 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1087 $group['extra'] = array('gid' => $customGroupDAO->id
);
1088 $group['table_name'] = $customGroupDAO->table_name
;
1089 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1097 * Get the table name for the entity type
1098 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1099 * tableName is 'civicrm_contact'
1101 * @param string $entityType
1102 * What entity are we extending here ?.
1108 * @see _apachesolr_civiAttachments_dereference_file_parent
1110 public static function getTableNameByEntityName($entityType) {
1112 switch ($entityType) {
1116 case 'Organization':
1117 $tableName = 'civicrm_contact';
1120 case 'Contribution':
1121 $tableName = 'civicrm_contribution';
1125 $tableName = 'civicrm_group';
1128 // DRAFTING: Verify if we cannot make it pluggable
1131 $tableName = 'civicrm_activity';
1134 case 'Relationship':
1135 $tableName = 'civicrm_relationship';
1139 $tableName = 'civicrm_membership';
1143 $tableName = 'civicrm_participant';
1147 $tableName = 'civicrm_event';
1151 $tableName = 'civicrm_grant';
1154 // need to add cases for Location, Address
1161 * Get a list of custom groups which extend a given entity type.
1162 * If there are custom-groups which only apply to certain subtypes,
1163 * those WILL be included.
1165 * @param string $entityType
1167 * @return CRM_Core_DAO_CustomGroup
1169 public static function getAllCustomGroupsByBaseEntity($entityType) {
1170 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1171 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1172 return $customGroupDAO;
1176 * Add the whereAdd clause for the DAO depending on the type of entity
1177 * the custom group is extending.
1179 * @param $customGroupDAO
1180 * @param string $entityType
1181 * What entity are we extending here ?.
1183 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
1184 * @param bool $allSubtypes
1190 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1191 $addSubtypeClause = FALSE;
1193 switch ($entityType) {
1195 // if contact, get all related to contact
1196 $extendList = "'Contact','Individual','Household','Organization'";
1197 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1198 if (!$allSubtypes) {
1199 $addSubtypeClause = TRUE;
1205 case 'Organization':
1206 // is I/H/O then get I/H/O and contact
1207 $extendList = "'Contact','$entityType'";
1208 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1209 if (!$allSubtypes) {
1210 $addSubtypeClause = TRUE;
1218 case 'Contribution':
1221 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1225 if ($addSubtypeClause) {
1226 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1228 if (!empty($csType)) {
1229 $subtypeClause = array();
1230 foreach ($csType as $subtype) {
1231 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1232 CRM_Core_DAO
::VALUE_SEPARATOR
;
1233 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1235 $subtypeClause[] = "extends_entity_column_value IS NULL";
1236 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1240 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1246 * Delete the Custom Group.
1249 * Object the DAO custom group object.
1250 * @param bool $force
1251 * whether to force the deletion, even if there are custom fields.
1254 * false if field exists for this group, true if group gets deleted.
1258 public static function deleteGroup($group, $force = FALSE) {
1260 //check wheter this contain any custom fields
1261 $customField = new CRM_Core_DAO_CustomField();
1262 $customField->custom_group_id
= $group->id
;
1263 $customField->find();
1265 // return early if there are custom fields and we're not
1266 // forcing the delete, otherwise delete the fields one by one
1267 while ($customField->fetch()) {
1271 CRM_Core_BAO_CustomField
::deleteField($customField);
1274 // drop the table associated with this custom group
1275 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1277 //delete custom group
1280 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1288 * @param bool $viewMode
1289 * @param bool $inactiveNeeded
1290 * @param int $action
1292 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1293 foreach ($groupTree as $id => $group) {
1294 if (!isset($group['fields'])) {
1297 foreach ($group['fields'] as $field) {
1298 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1299 $value = $field['element_value'];
1301 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1302 ($action != CRM_Core_Action
::UPDATE ||
1304 !array_key_exists('element_value', $field)
1307 $value = $viewMode ?
NULL : $field['default_value'];
1313 if (!empty($field['element_name'])) {
1314 $elementName = $field['element_name'];
1316 switch ($field['html_type']) {
1317 case 'Multi-Select':
1318 case 'AdvMulti-Select':
1320 $defaults[$elementName] = array();
1321 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1323 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1324 if (isset($value)) {
1325 foreach ($customOption as $customValue => $customLabel) {
1326 if (in_array($customValue, $checkedData)) {
1327 if ($field['html_type'] == 'CheckBox') {
1328 $defaults[$elementName][$customValue] = 1;
1331 $defaults[$elementName][$customValue] = $customValue;
1335 $defaults[$elementName][$customValue] = 0;
1341 if (isset($field['customValue']['data'])) {
1342 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1343 foreach ($customOption as $val) {
1344 if (in_array($val['value'], $checkedData)) {
1345 if ($field['html_type'] == 'CheckBox') {
1346 $defaults[$elementName][$val['value']] = 1;
1349 $defaults[$elementName][$val['value']] = $val['value'];
1353 $defaults[$elementName][$val['value']] = 0;
1358 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1359 foreach ($customOption as $val) {
1360 if (in_array($val['value'], $checkedValue)) {
1361 if ($field['html_type'] == 'CheckBox') {
1362 $defaults[$elementName][$val['value']] = 1;
1365 $defaults[$elementName][$val['value']] = $val['value'];
1374 if (isset($value)) {
1375 if (empty($field['time_format'])) {
1376 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1377 $field['date_format']
1381 $timeElement = $elementName . '_time';
1382 if (substr($elementName, -1) == ']') {
1383 $timeElement = substr($elementName, 0, -1) . '_time]';
1385 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1390 case 'Multi-Select Country':
1391 case 'Multi-Select State/Province':
1392 if (isset($value)) {
1393 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1394 foreach ($checkedValue as $val) {
1396 $defaults[$elementName][$val] = $val;
1402 case 'Select Country':
1404 $defaults[$elementName] = $value;
1407 $config = CRM_Core_Config
::singleton();
1408 $defaults[$elementName] = $config->defaultContactCountry
;
1413 if ($field['data_type'] == "Float") {
1414 $defaults[$elementName] = (float) $value;
1416 elseif ($field['data_type'] == 'Money' &&
1417 $field['html_type'] == 'Text'
1419 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1422 $defaults[$elementName] = $value;
1431 * @param array $params
1432 * @param bool $skipFile
1434 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1435 // Get the Custom form values and groupTree
1436 // first reset all checkbox and radio data
1437 foreach ($groupTree as $groupID => $group) {
1438 if ($groupID === 'info') {
1441 foreach ($group['fields'] as $field) {
1442 $fieldId = $field['id'];
1444 //added Multi-Select option in the below if-statement
1445 if ($field['html_type'] == 'CheckBox' ||
1446 $field['html_type'] == 'Radio' ||
1447 $field['html_type'] == 'AdvMulti-Select' ||
1448 $field['html_type'] == 'Multi-Select'
1450 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1454 foreach ($params as $key => $val) {
1455 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1456 $match[1] == $field['id']
1462 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1463 // field exists in db so populate value from "form".
1464 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1467 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1469 //added for CheckBox
1473 $customValue = array_keys($v);
1474 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] =
1475 CRM_Core_DAO
::VALUE_SEPARATOR
.
1476 implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue) .
1477 CRM_Core_DAO
::VALUE_SEPARATOR
;
1480 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1484 //added for Advanced Multi-Select
1486 case 'AdvMulti-Select':
1487 //added for Multi-Select
1488 case 'Multi-Select':
1490 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] =
1491 CRM_Core_DAO
::VALUE_SEPARATOR
.
1492 implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v) .
1493 CRM_Core_DAO
::VALUE_SEPARATOR
;
1496 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1501 $date = CRM_Utils_Date
::processDate($v);
1502 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1510 //store the file in d/b
1511 $entityId = explode('=', $groupTree['info']['where'][0]);
1512 $fileParams = array('upload_date' => date('Ymdhis'));
1514 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1515 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1518 $fileParams['uri'] = $v['name'];
1519 $fileParams['mime_type'] = $v['type'];
1520 CRM_Core_BAO_File
::filePostProcess($v['name'],
1521 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1522 $groupTree[$groupID]['table_name'],
1527 'custom_' . $fieldId,
1531 $defaults = array();
1532 $paramsFile = array(
1533 'entity_table' => $groupTree[$groupID]['table_name'],
1534 'entity_id' => $entityId[1],
1537 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1542 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1546 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1554 * Generic function to build all the form elements for a specific group tree
1556 * @param CRM_Core_Form $form
1558 * @param array $groupTree
1559 * The group tree object.
1560 * @param bool $inactiveNeeded
1561 * Return inactive custom groups.
1562 * @param string $prefix
1563 * Prefix for custom grouptree assigned to template.
1568 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1569 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1571 // this is fix for date field
1572 $form->assign('currentYear', date('Y'));
1574 foreach ($groupTree as $id => $group) {
1575 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1576 foreach ($group['fields'] as $field) {
1577 $required = CRM_Utils_Array
::value('is_required', $field);
1579 if ($field['data_type'] == 'File') {
1580 if (!empty($field['element_value']['data'])) {
1585 $fieldId = $field['id'];
1586 $elementName = $field['element_name'];
1587 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1593 * Extract the get params from the url, validate
1594 * and store it in session
1596 * @param CRM_Core_Form $form
1598 * @param string $type
1599 * The type of custom group we are using.
1604 public static function extractGetParams(&$form, $type) {
1609 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1610 $customValue = array();
1619 foreach ($groupTree as $group) {
1620 if (!isset($group['fields'])) {
1623 foreach ($group['fields'] as $key => $field) {
1624 $fieldName = 'custom_' . $key;
1625 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1629 if (!in_array($field['html_type'], $htmlType) ||
1630 $field['data_type'] == 'Boolean'
1632 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1634 if ($field['html_type'] == 'CheckBox' ||
1635 $field['html_type'] == 'AdvMulti-Select' ||
1636 $field['html_type'] == 'Multi-Select'
1638 $value = str_replace("|", ",", $value);
1639 $mulValues = explode(',', $value);
1640 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1642 foreach ($mulValues as $v1) {
1643 foreach ($customOption as $coID => $coValue) {
1644 if (strtolower(trim($coValue['label'])) ==
1645 strtolower(trim($v1))
1647 $val[$coValue['value']] = 1;
1659 elseif ($field['html_type'] == 'Select' ||
1660 ($field['html_type'] == 'Radio' &&
1661 $field['data_type'] != 'Boolean'
1664 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1665 foreach ($customOption as $customID => $coValue) {
1666 if (strtolower(trim($coValue['label'])) ==
1667 strtolower(trim($value))
1669 $value = $coValue['value'];
1674 elseif ($field['data_type'] == 'Date') {
1675 if (!empty($value)) {
1677 if (!empty($field['time_format'])) {
1678 $time = CRM_Utils_Request
::retrieve($fieldName .
1679 '_time', 'String', $form, FALSE, NULL, 'GET');
1681 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value .
1683 if (!empty($field['time_format'])) {
1684 $customValue[$fieldName . '_time'] = $time;
1691 $customValue[$fieldName] = $value;
1697 return $customValue;
1701 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1702 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1704 * @param int $customFieldId
1706 * @param array $removeCustomFieldTypes
1707 * Remove custom fields of a type eg: array("Individual") ;.
1711 * false if it matches else true
1714 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1715 $query = "SELECT cg.extends as extends
1716 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1717 WHERE cg.id = cf.custom_group_id
1719 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1721 $extends = CRM_Core_DAO
::singleValueQuery($query);
1723 if (in_array($extends, $removeCustomFieldTypes)) {
1735 public static function mapTableName($table) {
1740 case 'Organization':
1741 return 'civicrm_contact';
1744 return 'civicrm_activity';
1747 return 'civicrm_group';
1749 case 'Contribution':
1750 return 'civicrm_contribution';
1752 case 'Relationship':
1753 return 'civicrm_relationship';
1756 return 'civicrm_event';
1759 return 'civicrm_membership';
1762 case 'ParticipantRole':
1763 case 'ParticipantEventName':
1764 case 'ParticipantEventType':
1765 return 'civicrm_participant';
1768 return 'civicrm_grant';
1771 return 'civicrm_pledge';
1774 return 'civicrm_address';
1777 return 'civicrm_campaign';
1781 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1782 $qParams = array(1 => array($table, 'String'));
1783 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1786 return 'civicrm_contact';
1789 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1790 if (array_key_exists($table, $extendObjs)) {
1791 return $extendObjs[$table];
1793 CRM_Core_Error
::fatal();
1801 public static function createTable($group) {
1803 'name' => $group->table_name
,
1804 'is_multiple' => $group->is_multiple ?
1 : 0,
1805 'extends_name' => self
::mapTableName($group->extends),
1808 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1810 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1814 * Function returns formatted groupTree, sothat form can be easily build in template
1816 * @param array $groupTree
1817 * @param int $groupCount
1818 * Group count by default 1, but can varry for multiple value custom data.
1819 * @param object form object
1823 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1824 $formattedGroupTree = array();
1825 $uploadNames = array();
1827 foreach ($groupTree as $key => $value) {
1828 if ($key === 'info') {
1832 // add group information
1833 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1834 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1835 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1836 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1837 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1838 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1840 // this params needed of bulding multiple values
1841 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1842 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1843 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1844 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1845 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1846 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1848 // add field information
1849 foreach ($value['fields'] as $k => $properties) {
1850 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1851 if (isset($properties['customValue']) &&
1852 !CRM_Utils_System
::isNull($properties['customValue'])
1854 if (isset($properties['customValue'][$groupCount])) {
1855 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1856 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1857 if ($properties['data_type'] == 'File') {
1858 $properties['element_value'] = $properties['customValue'][$groupCount];
1859 $uploadNames[] = $properties['element_name'];
1862 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1866 unset($properties['customValue']);
1867 $formattedGroupTree[$key]['fields'][$k] = $properties;
1872 // hack for field type File
1873 $formUploadNames = $form->get('uploadNames');
1874 if (is_array($formUploadNames)) {
1875 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1878 $form->set('uploadNames', $uploadNames);
1881 return $formattedGroupTree;
1885 * Build custom data view
1887 * @param CRM_Core_Form $form
1889 * @param array $groupTree
1890 * @param bool $returnCount
1891 * True if customValue count needs to be returned.
1893 * @param null $prefix
1894 * @param int $customValueId
1898 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1900 foreach ($groupTree as $key => $group) {
1901 if ($key === 'info') {
1905 foreach ($group['fields'] as $k => $properties) {
1906 $groupID = $group['id'];
1907 if (!empty($properties['customValue'])) {
1908 foreach ($properties['customValue'] as $values) {
1909 if (!empty($customValueId) && $customValueId != $values['id']) {
1912 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1913 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1914 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1915 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1916 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1917 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1918 $details[$groupID][$values['id']]['fields'][$k] = array(
1919 'field_title' => CRM_Utils_Array
::value('label', $properties),
1920 'field_type' => CRM_Utils_Array
::value('html_type',
1923 'field_data_type' => CRM_Utils_Array
::value('data_type',
1926 'field_value' => self
::formatCustomValues($values,
1929 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1933 // also return contact reference contact id if user has view all or edit all contacts perm
1934 if ((CRM_Core_Permission
::check('view all contacts') ||
1935 CRM_Core_Permission
::check('edit all contacts'))
1937 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1940 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1945 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1946 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1947 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1948 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1949 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1950 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1951 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1957 //return a single value count if group id is passed to function
1958 //else return a groupId and count mapped array
1960 return count($details[$gID]);
1963 $countValue = array();
1964 foreach ($details as $key => $value) {
1965 $countValue[$key] = count($details[$key]);
1971 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1977 * Format custom value according to data, view mode
1979 * @param array $values
1980 * Associated array of custom values.
1981 * @param array $field
1982 * @param bool $dncOptionPerLine
1983 * True if optionPerLine should not be consider.
1985 * @return array|null|string
1987 public static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1988 $value = $values['data'];
1990 //changed isset CRM-4601
1991 if (CRM_Utils_System
::isNull($value)) {
1995 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1996 $dataType = CRM_Utils_Array
::value('data_type', $field);
1997 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1998 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1999 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
2002 $freezeStringChecked = "";
2004 switch ($dataType) {
2006 $customTimeFormat = '';
2007 $customFormat = NULL;
2009 switch ($timeFormat) {
2011 $customTimeFormat = '%l:%M %P';
2015 $customTimeFormat = '%H:%M';
2019 // if time is not selected remove time from value
2020 $value = substr($value, 0, 10);
2023 $supportableFormats = array(
2024 'mm/dd' => "%B %E%f $customTimeFormat",
2025 'dd-mm' => "%E%f %B $customTimeFormat",
2026 'yy' => "%Y $customTimeFormat",
2027 'M yy' => "%b %Y $customTimeFormat",
2028 'yy-mm' => "%Y-%m $customTimeFormat",
2031 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
2032 if (array_key_exists($format, $supportableFormats)) {
2033 $customFormat = $supportableFormats["$format"];
2037 $retValue = CRM_Utils_Date
::customFormat($value, $customFormat);
2041 if ($value == '1') {
2042 $retValue = $freezeStringChecked . ts('Yes') . "\n";
2045 $retValue = $freezeStringChecked . ts('No') . "\n";
2051 $retValue = CRM_Utils_System
::formatWikiURL($value);
2056 $retValue = $values;
2059 case 'ContactReference':
2060 if (!empty($values['data'])) {
2061 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
2070 if ($htmlType == 'Text') {
2071 $retValue = (float) $value;
2075 if ($htmlType == 'Text') {
2076 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2081 if (in_array($htmlType, array('Text', 'TextArea'))) {
2085 // note that if its not text / textarea, the code falls thru and executes
2086 // the below case also
2087 case 'StateProvince':
2092 //added check for Multi-Select in the below if-statement
2093 $customData[] = $value;
2095 //form custom data for multiple-valued custom data
2096 switch ($htmlType) {
2097 case 'Multi-Select Country':
2098 case 'Select Country':
2099 $customData = $value;
2100 if (!is_array($value)) {
2101 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2104 SELECT id as value, name as label
2105 FROM civicrm_country";
2106 $coDAO = CRM_Core_DAO
::executeQuery($query);
2109 case 'Select State/Province':
2110 case 'Multi-Select State/Province':
2111 $customData = $value;
2112 if (!is_array($value)) {
2113 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2117 SELECT id as value, name as label
2118 FROM civicrm_state_province";
2119 $coDAO = CRM_Core_DAO
::executeQuery($query);
2123 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2124 if ($option_group_id) {
2125 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2130 case 'AdvMulti-Select':
2131 case 'Multi-Select':
2132 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2134 if ($option_group_id) {
2135 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2139 if (is_object($coDAO)) {
2140 while ($coDAO->fetch()) {
2141 if ($dataType == 'Country') {
2142 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2143 // and already extracted to .pot files.
2144 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
2146 elseif ($dataType == 'StateProvince') {
2147 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
2150 $options[$coDAO->value
] = $coDAO->label
;
2155 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
2158 foreach ($options as $optionValue => $optionLabel) {
2159 if ($dataType == 'Money') {
2160 foreach ($customData as $k => $v) {
2161 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
2165 //to show only values that are checked
2166 if (in_array((string) $optionValue, $customData)) {
2167 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
2168 if (!$optionPerLine ||
$dncOptionPerLine) {
2172 $retValue .= $checked . $optionLabel;
2175 $retValue[] = $checked . $optionLabel;
2182 //special case for option per line formatting
2183 if ($optionPerLine > 1 && is_array($retValue)) {
2186 $displayValues = array();
2187 $displayString = '';
2188 foreach ($retValue as $val) {
2189 if ($displayString) {
2190 $displayString .= ", ";
2193 $displayString .= $val;
2197 if (($rowCounter == $optionPerLine) ||
2198 ($fieldCounter == count($retValue))
2200 $displayValues[] = $displayString;
2201 $displayString = '';
2205 $retValue = $displayValues;
2208 $retValue = isset($retValue) ?
$retValue : NULL;
2213 * Get the custom group titles by custom field ids.
2215 * @param array $fieldIds
2216 * Array of custom field ids.
2219 * array consisting of groups and fields labels with ids.
2221 public static function getGroupTitles($fieldIds) {
2222 if (!is_array($fieldIds) && empty($fieldIds)) {
2226 $groupLabels = array();
2227 $fIds = "(" . implode(',', $fieldIds) . ")";
2230 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2231 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2232 FROM civicrm_custom_group, civicrm_custom_field
2233 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2234 AND civicrm_custom_field.id IN {$fIds}";
2236 $dao = CRM_Core_DAO
::executeQuery($query);
2237 while ($dao->fetch()) {
2238 $groupLabels[$dao->fieldID
] = array(
2239 'fieldID' => $dao->fieldID
,
2240 'fieldLabel' => $dao->fieldLabel
,
2241 'groupID' => $dao->groupID
,
2242 'groupTitle' => $dao->groupTitle
,
2246 return $groupLabels;
2249 public static function dropAllTables() {
2250 $query = "SELECT table_name FROM civicrm_custom_group";
2251 $dao = CRM_Core_DAO
::executeQuery($query);
2253 while ($dao->fetch()) {
2254 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2255 CRM_Core_DAO
::executeQuery($query);
2260 * Check whether custom group is empty or not.
2266 * true if empty otherwise false.
2268 public static function isGroupEmpty($gID) {
2273 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2278 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2279 $value = CRM_Core_DAO
::singleValueQuery($query);
2281 if (empty($value)) {
2289 * Get the list of types for objects that a custom group extends to.
2291 * @param array $types
2292 * Var which should have the list appended.
2297 public static function getExtendedObjectTypes(&$types = array()) {
2298 static $flag = FALSE, $objTypes = array();
2301 $extendObjs = array();
2302 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2304 foreach ($extendObjs as $ovId => $ovValues) {
2305 if ($ovValues['description']) {
2306 // description is expected to be a callback func to subtypes
2307 list($callback, $args) = explode(';', trim($ovValues['description']));
2313 if (!is_array($args)) {
2314 CRM_Core_Error
::fatal('Arg is not of type array');
2317 list($className) = explode('::', $callback);
2318 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2321 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2327 $types = array_merge($types, $objTypes);
2332 * @param int $customGroupId
2333 * @param int $entityId
2337 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2338 //check whether the group is multiple
2339 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2340 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2341 $hasReachedMax = FALSE;
2343 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2345 if (!$maxMultiple) {
2346 $hasReachedMax = FALSE;
2349 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2350 //count the number of entries for a entity
2351 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2352 $params = array(1 => array($entityId, 'Integer'));
2353 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2355 if ($count >= $maxMultiple) {
2356 $hasReachedMax = TRUE;
2360 return $hasReachedMax;
2366 public static function getMultipleFieldGroup() {
2367 $multipleGroup = array();
2368 $dao = new CRM_Core_DAO_CustomGroup();
2369 $dao->is_multiple
= 1;
2371 while ($dao->fetch()) {
2372 $multipleGroup[$dao->id
] = $dao->title
;
2374 return $multipleGroup;