3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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
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
59 public static function create(&$params) {
60 // create custom group dao, populate fields and then save.
61 $group = new CRM_Core_DAO_CustomGroup();
62 $group->title
= $params['title'];
64 if (in_array($params['extends'][0],
67 'ParticipantEventName',
68 'ParticipantEventType',
71 $group->extends = 'Participant';
74 $group->extends = $params['extends'][0];
77 $group->extends_entity_column_id
= 'null';
79 $params['extends'][0] == 'ParticipantRole' ||
80 $params['extends'][0] == 'ParticipantEventName' ||
81 $params['extends'][0] == 'ParticipantEventType'
83 $group->extends_entity_column_id
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $params['extends'][0], 'value', 'name');
86 //this is format when form get submit.
87 $extendsChildType = CRM_Utils_Array
::value(1, $params['extends']);
88 //lets allow user to pass direct child type value, CRM-6893
89 if (!empty($params['extends_entity_column_value'])) {
90 $extendsChildType = $params['extends_entity_column_value'];
92 if (!CRM_Utils_System
::isNull($extendsChildType)) {
93 $extendsChildType = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendsChildType);
94 if (CRM_Utils_Array
::value(0, $params['extends']) == 'Relationship') {
95 $extendsChildType = str_replace(array('_a_b', '_b_a'), array(
98 ), $extendsChildType);
100 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
101 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType .
102 CRM_Core_DAO
::VALUE_SEPARATOR
;
106 $extendsChildType = 'null';
108 $group->extends_entity_column_value
= $extendsChildType;
110 if (isset($params['id'])) {
111 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
116 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
120 'collapse_adv_display',
126 foreach ($fields as $field) {
127 $group->$field = CRM_Utils_Array
::value($field, $params, FALSE);
129 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
130 $params['max_multiple'] >= '0'
131 ) ?
$params['max_multiple'] : 'null' : 'null';
133 $tableName = $oldTableName = NULL;
134 if (isset($params['id'])) {
135 $group->id
= $params['id'];
136 //check whether custom group was changed from single-valued to multiple-valued
137 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
142 if ((!empty($params['is_multiple']) ||
$isMultiple) &&
143 ($params['is_multiple'] != $isMultiple)
145 $oldTableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
152 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
153 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
155 // we do this only once, so name never changes
156 if (isset($params['name'])) {
157 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
160 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
163 if (isset($params['table_name'])) {
164 $tableName = $params['table_name'];
166 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
167 // Bad idea. Prevent group creation because it might lead to a broken configuration.
168 CRM_Core_Error
::fatal(ts("Cannot create custom table because %1 is already a core table.", array('1' => $tableName)));
173 if (array_key_exists('is_reserved', $params)) {
174 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
176 $op = isset($params['id']) ?
'edit' : 'create';
177 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
179 // enclose the below in a transaction
180 $transaction = new CRM_Core_Transaction();
183 if (!isset($params['id'])) {
184 if (!isset($params['table_name'])) {
185 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 42));
186 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
188 $group->table_name
= $tableName;
189 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
195 // now create the table associated with this group
196 self
::createTable($group);
198 elseif ($oldTableName) {
199 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($oldTableName, CRM_Utils_Array
::value('is_multiple', $params));
202 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
203 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
207 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends'][0]));
209 $transaction->commit();
212 CRM_Utils_System
::flushCache();
215 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
218 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
225 * Fetch object based on array of properties.
227 * @param array $params
228 * (reference ) an assoc array of name/value pairs.
229 * @param array $defaults
230 * (reference ) an assoc array to hold the flattened values.
232 * @return CRM_Core_DAO_CustomGroup
234 public static function retrieve(&$params, &$defaults) {
235 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
239 * Update the is_active flag in the db.
242 * Id of the database record.
243 * @param bool $is_active
244 * Value we want to set the is_active field.
247 * DAO object on sucess, null otherwise
249 public static function setIsActive($id, $is_active) {
251 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
254 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
257 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
261 * Determine if given entity (sub)type has any custom groups
263 * @param string $extends
264 * E.g. "Individual", "Activity".
265 * @param int $columnId
266 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
267 * @param string $columnValue
268 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
272 public static function hasCustomGroup($extends, $columnId, $columnValue) {
273 $dao = new CRM_Core_DAO_CustomGroup();
274 $dao->extends = $extends;
275 $dao->extends_entity_column_id
= $columnId;
276 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
277 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
278 //$dao->extends_entity_column_value = $columnValue;
279 return $dao->find() ?
TRUE : FALSE;
283 * Determine if there are any CustomGroups for the given $activityTypeId.
284 * If none found, create one.
286 * @param int $activityTypeId
289 * TRUE if a group is found or created; FALSE on error
291 public static function autoCreateByActivityType($activityTypeId) {
292 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
295 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
298 'extends' => 'Activity',
299 'extends_entity_column_id' => NULL,
300 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
301 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
305 $result = civicrm_api('CustomGroup', 'create', $params);
306 return !$result['is_error'];
310 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
311 * This may also include entity specific data values.
313 * An array containing all custom groups and their custom fields is returned.
315 * @param string $entityType
316 * Of the contact whose contact type is needed.
317 * @param CRM_Core_Form $form
318 * Not used but required.
319 * @param int $entityID
320 * @param int $groupID
321 * @param string $subType
322 * @param string $subName
323 * @param bool $fromCache
324 * @param bool $onlySubType
327 * The returned array is keyed by group id and has the custom group table fields
328 * and a subkey 'fields' holding the specific custom fields.
329 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
330 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
332 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
333 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
334 * With caching the performance impact would be small & the function would be cleaner
337 public static function &getTree(
348 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
352 $strSelect = $strFrom = $strWhere = $orderBy = '';
353 $tableData = array();
355 // using tableData to build the queryString
357 'civicrm_custom_field' => array(
377 'civicrm_custom_group' => array(
387 'extends_entity_column_id',
388 'extends_entity_column_value',
395 foreach ($tableData as $tableName => $tableColumn) {
396 foreach ($tableColumn as $columnName) {
397 $alias = $tableName . "_" . $columnName;
398 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
401 $strSelect = "SELECT " . implode(', ', $select);
403 // from, where, order by
405 FROM civicrm_custom_group
406 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
409 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
410 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
411 $entityType == 'Household'
413 $in = "'$entityType', 'Contact'";
415 elseif (strpos($entityType, "'") !== FALSE) {
416 // this allows the calling function to send in multiple entity types
421 $in = "'$entityType'";
426 if (is_array($subType)) {
427 $subType = implode(',', $subType);
429 if (strpos($subType, ',')) {
430 $subTypeParts = explode(',', $subType);
431 $subTypeClauses = array();
432 foreach ($subTypeParts as $subTypePart) {
433 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
.
434 trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) .
435 CRM_Core_DAO
::VALUE_SEPARATOR
;
436 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
440 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
443 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) .
444 " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
448 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
.
449 trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) .
450 CRM_Core_DAO
::VALUE_SEPARATOR
;
453 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
456 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
457 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
462 WHERE civicrm_custom_group.is_active = 1
463 AND civicrm_custom_field.is_active = 1
464 AND civicrm_custom_group.extends IN ($in)
468 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
473 WHERE civicrm_custom_group.is_active = 1
474 AND civicrm_custom_field.is_active = 1
475 AND civicrm_custom_group.extends IN ($in)
476 AND civicrm_custom_group.extends_entity_column_value IS NULL
482 // since we want a specific group id we add it to the where clause
483 $strWhere .= " AND civicrm_custom_group.id = %1";
484 $params[1] = array($groupID, 'Integer');
487 // since groupID is false we need to show all Inline groups
488 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
491 // ensure that the user has access to these custom groups
492 $strWhere .= " AND " .
493 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
494 'civicrm_custom_group.'
498 ORDER BY civicrm_custom_group.weight,
499 civicrm_custom_group.title,
500 civicrm_custom_field.weight,
501 civicrm_custom_field.label
504 // final query string
505 $queryString = "$strSelect $strFrom $strWhere $orderBy";
507 // lets see if we can retrieve the groupTree from cache
508 $cacheString = $queryString;
510 $cacheString .= "_{$groupID}";
513 $cacheString .= "_Inline";
516 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
517 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
518 $cache = CRM_Utils_Cache
::singleton();
519 $tablesWithEntityData = array();
521 $groupTree = $cache->get($cacheKey);
522 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
525 if (empty($groupTree)) {
526 $groupTree = $multipleFieldGroups = array();
527 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
528 $customValueTables = array();
531 while ($crmDAO->fetch()) {
533 $groupID = $crmDAO->civicrm_custom_group_id
;
534 $fieldId = $crmDAO->civicrm_custom_field_id
;
535 if ($crmDAO->civicrm_custom_group_is_multiple
) {
536 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
538 // create an array for groups if it does not exist
539 if (!array_key_exists($groupID, $groupTree)) {
540 $groupTree[$groupID] = array();
541 $groupTree[$groupID]['id'] = $groupID;
543 // populate the group information
544 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
545 $fullFieldName = "civicrm_custom_group_$fieldName";
546 if ($fieldName == 'id' ||
547 is_null($crmDAO->$fullFieldName)
552 if ($fieldName == 'extends_entity_column_value' && $subType) {
553 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
555 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
557 $groupTree[$groupID]['fields'] = array();
559 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
562 // add the fields now (note - the query row will always contain a field)
563 // we only reset this once, since multiple values come is as multiple rows
564 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
565 $groupTree[$groupID]['fields'][$fieldId] = array();
568 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
569 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
570 // populate information for a custom field
571 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
572 $fullFieldName = "civicrm_custom_field_$fieldName";
573 if ($fieldName == 'id' ||
574 is_null($crmDAO->$fullFieldName)
578 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
582 if (!empty($customValueTables)) {
583 $groupTree['info'] = array('tables' => $customValueTables);
586 $cache->set($cacheKey, $groupTree);
587 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
589 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
590 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
591 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
592 $singleFieldTables = array();
593 // now that we have all the groups and fields, lets get the values
594 // since we need to know the table and field names
595 // add info to groupTree
597 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
598 !empty($groupTree['info']['tables'])
600 $select = $from = $where = array();
601 $groupTree['info']['where'] = NULL;
603 foreach ($groupTree['info']['tables'] as $table => $fields) {
604 $groupTree['info']['from'][] = $table;
606 "{$table}.id as {$table}_id",
607 "{$table}.entity_id as {$table}_entity_id",
609 foreach ($fields as $column => $dontCare) {
610 $select[] = "{$table}.{$column} as {$table}_{$column}";
612 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
614 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
615 if (in_array($table, $multipleFieldGroups) &&
616 self
::customGroupDataExistsForEntity($entityID, $table)
618 $entityMultipleSelectClauses[$table] = $select;
621 $singleFieldTables[] = $table;
622 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
627 if ($entityID && !empty($singleFieldTables)) {
628 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
630 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
631 if (!empty($multipleFieldTablesWithEntityData)) {
632 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
640 * Check whether the custom group has any data for the given entity.
643 * @param int $entityID
644 * Id of entity for whom we are checking data for.
645 * @param string $table
646 * Table that we are checking.
648 * @param bool $getCount
651 * does this entity have data in this custom table
653 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
657 WHERE entity_id = $entityID
659 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
661 return $recordExists;
663 return $recordExists ?
TRUE : FALSE;
667 * Build the group tree for Custom fields which are not 'is_multiple'
669 * The combination of all these fields in one query with a 'using' join was not working for
670 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
671 * mechanism as it seemed to be acceptable in this context
673 * @param array $groupTree
674 * (reference) group tree array which is being built.
675 * @param int $entityID
676 * Id of entity for whom the tree is being build up.
677 * @param array $entitySingleSelectClauses
678 * Array of select clauses relevant to the entity.
679 * @param array $singleFieldTablesWithEntityData
680 * Array of tables in which this entity has data.
682 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
683 $select = implode(', ', $entitySingleSelectClauses);
684 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
685 foreach ($singleFieldTablesWithEntityData as $table) {
686 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
692 WHERE first.entity_id = $entityID
694 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
698 * Build the group tree for Custom fields which are 'is_multiple'
700 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
702 * @param array $groupTree
703 * (reference) group tree array which is being built.
704 * @param int $entityID
705 * Id of entity for whom the tree is being build up.
706 * @param array $entityMultipleSelectClauses
707 * Array of select clauses relevant to the entity.
708 * @param array $multipleFieldTablesWithEntityData
709 * Array of tables in which this entity has data.
711 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData) {
712 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
713 $select = implode(',', $selectClauses);
717 WHERE entity_id = $entityID
719 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
724 * Build the tree entity data - starting from a query retrieving the custom fields build the group
725 * tree data for the relevant entity (entity is included in the query).
727 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
729 * @param array $groupTree
730 * (reference) group tree array which is being built.
731 * @param string $query
732 * @param array $includedTables
733 * Tables to include - required because the function (for historical reasons).
734 * iterates through the group tree
736 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables) {
737 $dao = CRM_Core_DAO
::executeQuery($query);
738 while ($dao->fetch()) {
739 foreach ($groupTree as $groupID => $group) {
740 if ($groupID === 'info') {
743 $table = $groupTree[$groupID]['table_name'];
744 //working from the groupTree instead of the table list means we have to iterate & exclude.
745 // this could possibly be re-written as other parts of the function have been refactored
746 // for now we just check if the given table is to be included in this function
747 if (!in_array($table, $includedTables)) {
750 foreach ($group['fields'] as $fieldID => $dontCare) {
751 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
758 * Build the entity-specific custom data into the group tree on a per-field basis
761 * Object representing the custom field to be populated into the groupTree.
762 * @param array $groupTree
763 * (reference) the group tree being build.
764 * @param string $table
766 * @param unknown_type $groupID
768 * @param unknown_type $fieldID
771 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID) {
772 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
773 $idName = "{$table}_id";
774 $fieldName = "{$table}_{$column}";
775 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
776 if ($dataType == 'File') {
777 if (isset($dao->$fieldName)) {
778 $config = CRM_Core_Config
::singleton();
779 $fileDAO = new CRM_Core_DAO_File();
780 $fileDAO->id
= $dao->$fieldName;
782 if ($fileDAO->find(TRUE)) {
783 $entityIDName = "{$table}_entity_id";
784 $customValue['id'] = $dao->$idName;
785 $customValue['data'] = $fileDAO->uri
;
786 $customValue['fid'] = $fileDAO->id
;
787 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
788 $customValue['displayURL'] = NULL;
789 $deleteExtra = ts('Are you sure you want to delete attached file.');
791 CRM_Core_Action
::DELETE
=> array(
792 'name' => ts('Delete Attached File'),
793 'url' => 'civicrm/file',
794 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
795 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
796 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
799 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
800 CRM_Core_Action
::DELETE
,
802 'id' => $fileDAO->id
,
803 'eid' => $dao->$entityIDName,
808 'file.manage.delete',
812 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
813 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
814 if ($fileDAO->mime_type
== "image/jpeg" ||
815 $fileDAO->mime_type
== "image/pjpeg" ||
816 $fileDAO->mime_type
== "image/gif" ||
817 $fileDAO->mime_type
== "image/x-png" ||
818 $fileDAO->mime_type
== "image/png"
820 $customValue['displayURL'] = $customValue['fileURL'];
821 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
826 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
828 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId, NULL, NULL);
829 if ($path && file_exists($path)) {
830 list($imageWidth, $imageHeight) = getimagesize($path);
831 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
832 $customValue['imageThumbWidth'] = $imageThumbWidth;
833 $customValue['imageThumbHeight'] = $imageThumbHeight;
839 $customValue = array(
840 'id' => $dao->$idName,
846 $customValue = array(
847 'id' => $dao->$idName,
848 'data' => $dao->$fieldName,
852 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
853 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
855 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
856 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
859 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
864 * Get the group title.
873 public static function getTitle($id) {
874 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
878 * Get custom group details for a group.
880 * An array containing custom group details (including their custom field) is returned.
882 * @param int $groupId
883 * Group id whose details are needed.
884 * @param bool $searchable
885 * Is this field searchable.
886 * @param array $extends
887 * Which table does it extend if any.
889 * @param null $inSelector
892 * array consisting of all group and field details
896 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
898 $groupTree = array();
899 $select = $from = $where = $orderBy = '';
901 $tableData = array();
903 // using tableData to build the queryString
905 'civicrm_custom_field' => array(
929 'civicrm_custom_group' => array(
936 'collapse_adv_display',
938 'extends_entity_column_value',
947 foreach ($tableData as $tableName => $tableColumn) {
948 foreach ($tableColumn as $columnName) {
949 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
952 $select = 'SELECT ' . implode(', ', $s);
954 // from, where, order by
955 $from = " FROM civicrm_custom_field, civicrm_custom_group";
956 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
957 AND civicrm_custom_group.is_active = 1
958 AND civicrm_custom_field.is_active = 1 ";
960 $params[1] = array($groupId, 'Integer');
961 $where .= " AND civicrm_custom_group.id = %1";
965 $where .= " AND civicrm_custom_field.is_searchable = 1";
969 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
974 foreach ($extends as $e) {
975 $clause[] = "civicrm_custom_group.extends = '$e'";
977 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
979 //include case activities customdata if case is enabled
980 if (in_array('Activity', $extends)) {
981 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
982 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
983 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
987 // ensure that the user has access to these custom groups
989 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
990 'civicrm_custom_group.'
993 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
995 // final query string
996 $queryString = $select . $from . $where . $orderBy;
999 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1002 while ($crmDAO->fetch()) {
1003 $groupId = $crmDAO->civicrm_custom_group_id
;
1004 $fieldId = $crmDAO->civicrm_custom_field_id
;
1006 // create an array for groups if it does not exist
1007 if (!array_key_exists($groupId, $groupTree)) {
1008 $groupTree[$groupId] = array();
1009 $groupTree[$groupId]['id'] = $groupId;
1011 foreach ($tableData['civicrm_custom_group'] as $v) {
1012 $fullField = "civicrm_custom_group_" . $v;
1014 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1018 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1021 $groupTree[$groupId]['fields'] = array();
1024 // add the fields now (note - the query row will always contain a field)
1025 $groupTree[$groupId]['fields'][$fieldId] = array();
1026 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1028 foreach ($tableData['civicrm_custom_field'] as $v) {
1029 $fullField = "civicrm_custom_field_" . $v;
1030 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1033 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1041 * @param $entityType
1043 * @param string $cidToken
1047 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1049 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1051 // get 'Tab' and 'Tab with table' groups
1052 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1053 $customGroupDAO->whereAdd("is_active = 1");
1055 // add whereAdd for entity type
1056 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1060 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1061 $customGroupDAO->whereAdd($permissionClause);
1064 $customGroupDAO->orderBy('weight');
1065 $customGroupDAO->find();
1067 // process each group with menu tab
1068 while ($customGroupDAO->fetch()) {
1070 $group['id'] = $customGroupDAO->id
;
1071 $group['path'] = $path;
1072 $group['title'] = "$customGroupDAO->title";
1073 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1074 $group['extra'] = array('gid' => $customGroupDAO->id
);
1075 $group['table_name'] = $customGroupDAO->table_name
;
1076 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1084 * Get the table name for the entity type
1085 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1086 * tableName is 'civicrm_contact'
1088 * @param string $entityType
1089 * What entity are we extending here ?.
1094 * @see _apachesolr_civiAttachments_dereference_file_parent
1096 public static function getTableNameByEntityName($entityType) {
1098 switch ($entityType) {
1102 case 'Organization':
1103 $tableName = 'civicrm_contact';
1106 case 'Contribution':
1107 $tableName = 'civicrm_contribution';
1111 $tableName = 'civicrm_group';
1114 // DRAFTING: Verify if we cannot make it pluggable
1117 $tableName = 'civicrm_activity';
1120 case 'Relationship':
1121 $tableName = 'civicrm_relationship';
1125 $tableName = 'civicrm_membership';
1129 $tableName = 'civicrm_participant';
1133 $tableName = 'civicrm_event';
1137 $tableName = 'civicrm_grant';
1140 // need to add cases for Location, Address
1147 * Get a list of custom groups which extend a given entity type.
1148 * If there are custom-groups which only apply to certain subtypes,
1149 * those WILL be included.
1151 * @param string $entityType
1153 * @return CRM_Core_DAO_CustomGroup
1155 public static function getAllCustomGroupsByBaseEntity($entityType) {
1156 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1157 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1158 return $customGroupDAO;
1162 * Add the whereAdd clause for the DAO depending on the type of entity
1163 * the custom group is extending.
1165 * @param object $customGroupDAO
1166 * @param string $entityType
1167 * What entity are we extending here ?.
1169 * @param int $entityID
1170 * @param bool $allSubtypes
1175 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1176 $addSubtypeClause = FALSE;
1178 switch ($entityType) {
1180 // if contact, get all related to contact
1181 $extendList = "'Contact','Individual','Household','Organization'";
1182 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1183 if (!$allSubtypes) {
1184 $addSubtypeClause = TRUE;
1190 case 'Organization':
1191 // is I/H/O then get I/H/O and contact
1192 $extendList = "'Contact','$entityType'";
1193 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1194 if (!$allSubtypes) {
1195 $addSubtypeClause = TRUE;
1203 case 'Contribution':
1206 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1210 if ($addSubtypeClause) {
1211 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1213 if (!empty($csType)) {
1214 $subtypeClause = array();
1215 foreach ($csType as $subtype) {
1216 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1217 CRM_Core_DAO
::VALUE_SEPARATOR
;
1218 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1220 $subtypeClause[] = "extends_entity_column_value IS NULL";
1221 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1225 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1231 * Delete the Custom Group.
1234 * Object the DAO custom group object.
1235 * @param bool $force
1236 * whether to force the deletion, even if there are custom fields.
1239 * false if field exists for this group, true if group gets deleted.
1241 public static function deleteGroup($group, $force = FALSE) {
1243 //check wheter this contain any custom fields
1244 $customField = new CRM_Core_DAO_CustomField();
1245 $customField->custom_group_id
= $group->id
;
1246 $customField->find();
1248 // return early if there are custom fields and we're not
1249 // forcing the delete, otherwise delete the fields one by one
1250 while ($customField->fetch()) {
1254 CRM_Core_BAO_CustomField
::deleteField($customField);
1257 // drop the table associated with this custom group
1258 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1260 //delete custom group
1263 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1271 * @param bool $viewMode
1272 * @param bool $inactiveNeeded
1273 * @param int $action
1275 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1276 foreach ($groupTree as $id => $group) {
1277 if (!isset($group['fields'])) {
1280 foreach ($group['fields'] as $field) {
1281 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1282 $value = $field['element_value'];
1284 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1285 ($action != CRM_Core_Action
::UPDATE ||
1287 !array_key_exists('element_value', $field)
1290 $value = $viewMode ?
NULL : $field['default_value'];
1296 if (!empty($field['element_name'])) {
1297 $elementName = $field['element_name'];
1299 switch ($field['html_type']) {
1300 case 'Multi-Select':
1301 case 'AdvMulti-Select':
1303 $defaults[$elementName] = array();
1304 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1306 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1307 if (isset($value)) {
1308 foreach ($customOption as $customValue => $customLabel) {
1309 if (in_array($customValue, $checkedData)) {
1310 if ($field['html_type'] == 'CheckBox') {
1311 $defaults[$elementName][$customValue] = 1;
1314 $defaults[$elementName][$customValue] = $customValue;
1318 $defaults[$elementName][$customValue] = 0;
1324 if (isset($field['customValue']['data'])) {
1325 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1326 foreach ($customOption as $val) {
1327 if (in_array($val['value'], $checkedData)) {
1328 if ($field['html_type'] == 'CheckBox') {
1329 $defaults[$elementName][$val['value']] = 1;
1332 $defaults[$elementName][$val['value']] = $val['value'];
1336 $defaults[$elementName][$val['value']] = 0;
1341 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1342 foreach ($customOption as $val) {
1343 if (in_array($val['value'], $checkedValue)) {
1344 if ($field['html_type'] == 'CheckBox') {
1345 $defaults[$elementName][$val['value']] = 1;
1348 $defaults[$elementName][$val['value']] = $val['value'];
1357 if (isset($value)) {
1358 if (empty($field['time_format'])) {
1359 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1360 $field['date_format']
1364 $timeElement = $elementName . '_time';
1365 if (substr($elementName, -1) == ']') {
1366 $timeElement = substr($elementName, 0, -1) . '_time]';
1368 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1373 case 'Multi-Select Country':
1374 case 'Multi-Select State/Province':
1375 if (isset($value)) {
1376 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1377 foreach ($checkedValue as $val) {
1379 $defaults[$elementName][$val] = $val;
1385 case 'Select Country':
1387 $defaults[$elementName] = $value;
1390 $config = CRM_Core_Config
::singleton();
1391 $defaults[$elementName] = $config->defaultContactCountry
;
1396 if ($field['data_type'] == "Float") {
1397 $defaults[$elementName] = (float) $value;
1399 elseif ($field['data_type'] == 'Money' &&
1400 $field['html_type'] == 'Text'
1402 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1405 $defaults[$elementName] = $value;
1414 * @param array $params
1415 * @param bool $skipFile
1417 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1418 // Get the Custom form values and groupTree
1419 // first reset all checkbox and radio data
1420 foreach ($groupTree as $groupID => $group) {
1421 if ($groupID === 'info') {
1424 foreach ($group['fields'] as $field) {
1425 $fieldId = $field['id'];
1427 //added Multi-Select option in the below if-statement
1428 if ($field['html_type'] == 'CheckBox' ||
1429 $field['html_type'] == 'Radio' ||
1430 $field['html_type'] == 'AdvMulti-Select' ||
1431 $field['html_type'] == 'Multi-Select'
1433 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1437 foreach ($params as $key => $val) {
1438 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1439 $match[1] == $field['id']
1445 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1446 // field exists in db so populate value from "form".
1447 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1450 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1452 //added for CheckBox
1456 $customValue = array_keys($v);
1457 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1458 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1459 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1462 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1466 //added for Advanced Multi-Select
1468 case 'AdvMulti-Select':
1469 //added for Multi-Select
1470 case 'Multi-Select':
1472 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1473 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1474 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1477 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1482 $date = CRM_Utils_Date
::processDate($v);
1483 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1491 //store the file in d/b
1492 $entityId = explode('=', $groupTree['info']['where'][0]);
1493 $fileParams = array('upload_date' => date('Ymdhis'));
1495 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1496 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1499 $fileParams['uri'] = $v['name'];
1500 $fileParams['mime_type'] = $v['type'];
1501 CRM_Core_BAO_File
::filePostProcess($v['name'],
1502 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1503 $groupTree[$groupID]['table_name'],
1508 'custom_' . $fieldId,
1512 $defaults = array();
1513 $paramsFile = array(
1514 'entity_table' => $groupTree[$groupID]['table_name'],
1515 'entity_id' => $entityId[1],
1518 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1523 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1527 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1535 * Generic function to build all the form elements for a specific group tree.
1537 * @param CRM_Core_Form $form
1539 * @param array $groupTree
1540 * The group tree object.
1541 * @param bool $inactiveNeeded
1542 * Return inactive custom groups.
1543 * @param string $prefix
1544 * Prefix for custom grouptree assigned to template.
1548 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1549 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1551 // this is fix for date field
1552 $form->assign('currentYear', date('Y'));
1554 foreach ($groupTree as $id => $group) {
1555 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1556 foreach ($group['fields'] as $field) {
1557 $required = CRM_Utils_Array
::value('is_required', $field);
1559 if ($field['data_type'] == 'File') {
1560 if (!empty($field['element_value']['data'])) {
1565 $fieldId = $field['id'];
1566 $elementName = $field['element_name'];
1567 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1573 * Extract the get params from the url, validate
1574 * and store it in session
1576 * @param CRM_Core_Form $form
1578 * @param string $type
1579 * The type of custom group we are using.
1583 public static function extractGetParams(&$form, $type) {
1588 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1589 $customValue = array();
1598 foreach ($groupTree as $group) {
1599 if (!isset($group['fields'])) {
1602 foreach ($group['fields'] as $key => $field) {
1603 $fieldName = 'custom_' . $key;
1604 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1608 if (!in_array($field['html_type'], $htmlType) ||
1609 $field['data_type'] == 'Boolean'
1611 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1613 if ($field['html_type'] == 'CheckBox' ||
1614 $field['html_type'] == 'AdvMulti-Select' ||
1615 $field['html_type'] == 'Multi-Select'
1617 $value = str_replace("|", ",", $value);
1618 $mulValues = explode(',', $value);
1619 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1621 foreach ($mulValues as $v1) {
1622 foreach ($customOption as $coID => $coValue) {
1623 if (strtolower(trim($coValue['label'])) ==
1624 strtolower(trim($v1))
1626 $val[$coValue['value']] = 1;
1638 elseif ($field['html_type'] == 'Select' ||
1639 ($field['html_type'] == 'Radio' &&
1640 $field['data_type'] != 'Boolean'
1643 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1644 foreach ($customOption as $customID => $coValue) {
1645 if (strtolower(trim($coValue['label'])) ==
1646 strtolower(trim($value))
1648 $value = $coValue['value'];
1653 elseif ($field['data_type'] == 'Date') {
1654 if (!empty($value)) {
1656 if (!empty($field['time_format'])) {
1657 $time = CRM_Utils_Request
::retrieve($fieldName .
1658 '_time', 'String', $form, FALSE, NULL, 'GET');
1660 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value .
1662 if (!empty($field['time_format'])) {
1663 $customValue[$fieldName . '_time'] = $time;
1670 $customValue[$fieldName] = $value;
1676 return $customValue;
1680 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1681 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1683 * @param int $customFieldId
1685 * @param array $removeCustomFieldTypes
1686 * Remove custom fields of a type eg: array("Individual") ;.
1689 * false if it matches else true
1691 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1692 $query = "SELECT cg.extends as extends
1693 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1694 WHERE cg.id = cf.custom_group_id
1696 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1698 $extends = CRM_Core_DAO
::singleValueQuery($query);
1700 if (in_array($extends, $removeCustomFieldTypes)) {
1712 public static function mapTableName($table) {
1717 case 'Organization':
1718 return 'civicrm_contact';
1721 return 'civicrm_activity';
1724 return 'civicrm_group';
1726 case 'Contribution':
1727 return 'civicrm_contribution';
1729 case 'Relationship':
1730 return 'civicrm_relationship';
1733 return 'civicrm_event';
1736 return 'civicrm_membership';
1739 case 'ParticipantRole':
1740 case 'ParticipantEventName':
1741 case 'ParticipantEventType':
1742 return 'civicrm_participant';
1745 return 'civicrm_grant';
1748 return 'civicrm_pledge';
1751 return 'civicrm_address';
1754 return 'civicrm_campaign';
1758 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1759 $qParams = array(1 => array($table, 'String'));
1760 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1763 return 'civicrm_contact';
1766 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1767 if (array_key_exists($table, $extendObjs)) {
1768 return $extendObjs[$table];
1770 CRM_Core_Error
::fatal();
1778 public static function createTable($group) {
1780 'name' => $group->table_name
,
1781 'is_multiple' => $group->is_multiple ?
1 : 0,
1782 'extends_name' => self
::mapTableName($group->extends),
1785 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1787 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1791 * Function returns formatted groupTree, sothat form can be easily build in template
1793 * @param array $groupTree
1794 * @param int $groupCount
1795 * Group count by default 1, but can varry for multiple value custom data.
1796 * @param object $form
1800 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1801 $formattedGroupTree = array();
1802 $uploadNames = array();
1804 foreach ($groupTree as $key => $value) {
1805 if ($key === 'info') {
1809 // add group information
1810 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1811 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1812 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1813 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1814 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1815 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1817 // this params needed of bulding multiple values
1818 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1819 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1820 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1821 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1822 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1823 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1825 // add field information
1826 foreach ($value['fields'] as $k => $properties) {
1827 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1828 if (isset($properties['customValue']) &&
1829 !CRM_Utils_System
::isNull($properties['customValue'])
1831 if (isset($properties['customValue'][$groupCount])) {
1832 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1833 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1834 if ($properties['data_type'] == 'File') {
1835 $properties['element_value'] = $properties['customValue'][$groupCount];
1836 $uploadNames[] = $properties['element_name'];
1839 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1843 unset($properties['customValue']);
1844 $formattedGroupTree[$key]['fields'][$k] = $properties;
1849 // hack for field type File
1850 $formUploadNames = $form->get('uploadNames');
1851 if (is_array($formUploadNames)) {
1852 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1855 $form->set('uploadNames', $uploadNames);
1858 return $formattedGroupTree;
1862 * Build custom data view.
1864 * @param CRM_Core_Form $form
1866 * @param array $groupTree
1867 * @param bool $returnCount
1868 * True if customValue count needs to be returned.
1870 * @param null $prefix
1871 * @param int $customValueId
1875 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1877 foreach ($groupTree as $key => $group) {
1878 if ($key === 'info') {
1882 foreach ($group['fields'] as $k => $properties) {
1883 $groupID = $group['id'];
1884 if (!empty($properties['customValue'])) {
1885 foreach ($properties['customValue'] as $values) {
1886 if (!empty($customValueId) && $customValueId != $values['id']) {
1889 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1890 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1891 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1892 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1893 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1894 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1895 $details[$groupID][$values['id']]['fields'][$k] = array(
1896 'field_title' => CRM_Utils_Array
::value('label', $properties),
1897 'field_type' => CRM_Utils_Array
::value('html_type',
1900 'field_data_type' => CRM_Utils_Array
::value('data_type',
1903 'field_value' => self
::formatCustomValues($values,
1906 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1910 // also return contact reference contact id if user has view all or edit all contacts perm
1911 if ((CRM_Core_Permission
::check('view all contacts') ||
1912 CRM_Core_Permission
::check('edit all contacts'))
1914 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1917 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1922 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1923 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1924 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1925 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1926 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1927 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1928 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1934 //return a single value count if group id is passed to function
1935 //else return a groupId and count mapped array
1937 return count($details[$gID]);
1940 $countValue = array();
1941 foreach ($details as $key => $value) {
1942 $countValue[$key] = count($details[$key]);
1948 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1954 * Format custom value according to data, view mode
1956 * @param array $values
1957 * Associated array of custom values.
1958 * @param array $field
1959 * @param bool $dncOptionPerLine
1960 * True if optionPerLine should not be consider.
1962 * @return array|null|string
1964 public static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1965 $value = $values['data'];
1967 //changed isset CRM-4601
1968 if (CRM_Utils_System
::isNull($value)) {
1972 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1973 $dataType = CRM_Utils_Array
::value('data_type', $field);
1974 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1975 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1976 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1979 $freezeStringChecked = "";
1981 switch ($dataType) {
1983 $customFormat = NULL;
1985 $actualPHPFormats = CRM_Core_SelectValues
::datePluginToPHPFormats();
1987 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
1988 if (array_key_exists($format, $actualPHPFormats)) {
1989 $customTimeFormat = (array) CRM_Utils_Array
::value($format, $actualPHPFormats);
1990 switch ($timeFormat) {
1992 $customTimeFormat[] = 'g:iA';
1996 $customTimeFormat[] = 'G:i';
2000 // if time is not selected remove time from value
2001 $value = substr($value, 0, 10);
2003 $customFormat = implode(" ", $customTimeFormat);
2006 $retValue = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
2010 if ($value == '1') {
2011 $retValue = $freezeStringChecked . ts('Yes') . "\n";
2014 $retValue = $freezeStringChecked . ts('No') . "\n";
2020 $retValue = CRM_Utils_System
::formatWikiURL($value);
2025 $retValue = $values;
2028 case 'ContactReference':
2029 if (!empty($values['data'])) {
2030 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
2039 if ($htmlType == 'Text') {
2040 $retValue = (float) $value;
2044 if ($htmlType == 'Text') {
2045 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2050 if (in_array($htmlType, array('Text', 'TextArea'))) {
2054 // note that if its not text / textarea, the code falls thru and executes
2055 // the below case also
2056 case 'StateProvince':
2061 //added check for Multi-Select in the below if-statement
2062 $customData[] = $value;
2064 //form custom data for multiple-valued custom data
2065 switch ($htmlType) {
2066 case 'Multi-Select Country':
2067 case 'Select Country':
2068 $customData = $value;
2069 if (!is_array($value)) {
2070 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2073 SELECT id as value, name as label
2074 FROM civicrm_country";
2075 $coDAO = CRM_Core_DAO
::executeQuery($query);
2078 case 'Select State/Province':
2079 case 'Multi-Select State/Province':
2080 $customData = $value;
2081 if (!is_array($value)) {
2082 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2086 SELECT id as value, name as label
2087 FROM civicrm_state_province";
2088 $coDAO = CRM_Core_DAO
::executeQuery($query);
2092 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2093 if ($option_group_id) {
2094 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2099 case 'AdvMulti-Select':
2100 case 'Multi-Select':
2101 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2103 if ($option_group_id) {
2104 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2108 if (is_object($coDAO)) {
2109 while ($coDAO->fetch()) {
2110 if ($dataType == 'Country') {
2111 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2112 // and already extracted to .pot files.
2113 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
2115 elseif ($dataType == 'StateProvince') {
2116 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
2119 $options[$coDAO->value
] = $coDAO->label
;
2124 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
2127 foreach ($options as $optionValue => $optionLabel) {
2128 if ($dataType == 'Money') {
2129 foreach ($customData as $k => $v) {
2130 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
2134 //to show only values that are checked
2135 if (in_array((string) $optionValue, $customData)) {
2136 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
2137 if (!$optionPerLine ||
$dncOptionPerLine) {
2141 $retValue .= $checked . $optionLabel;
2144 $retValue[] = $checked . $optionLabel;
2151 //special case for option per line formatting
2152 if ($optionPerLine > 1 && is_array($retValue)) {
2155 $displayValues = array();
2156 $displayString = '';
2157 foreach ($retValue as $val) {
2158 if ($displayString) {
2159 $displayString .= ", ";
2162 $displayString .= $val;
2166 if (($rowCounter == $optionPerLine) ||
2167 ($fieldCounter == count($retValue))
2169 $displayValues[] = $displayString;
2170 $displayString = '';
2174 $retValue = $displayValues;
2177 $retValue = isset($retValue) ?
$retValue : NULL;
2182 * Get the custom group titles by custom field ids.
2184 * @param array $fieldIds
2185 * Array of custom field ids.
2187 * @return array|NULL
2188 * array consisting of groups and fields labels with ids.
2190 public static function getGroupTitles($fieldIds) {
2191 if (!is_array($fieldIds) && empty($fieldIds)) {
2195 $groupLabels = array();
2196 $fIds = "(" . implode(',', $fieldIds) . ")";
2199 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2200 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2201 FROM civicrm_custom_group, civicrm_custom_field
2202 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2203 AND civicrm_custom_field.id IN {$fIds}";
2205 $dao = CRM_Core_DAO
::executeQuery($query);
2206 while ($dao->fetch()) {
2207 $groupLabels[$dao->fieldID
] = array(
2208 'fieldID' => $dao->fieldID
,
2209 'fieldLabel' => $dao->fieldLabel
,
2210 'groupID' => $dao->groupID
,
2211 'groupTitle' => $dao->groupTitle
,
2215 return $groupLabels;
2218 public static function dropAllTables() {
2219 $query = "SELECT table_name FROM civicrm_custom_group";
2220 $dao = CRM_Core_DAO
::executeQuery($query);
2222 while ($dao->fetch()) {
2223 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2224 CRM_Core_DAO
::executeQuery($query);
2229 * Check whether custom group is empty or not.
2235 * true if empty otherwise false.
2237 public static function isGroupEmpty($gID) {
2242 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2247 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2248 $value = CRM_Core_DAO
::singleValueQuery($query);
2250 if (empty($value)) {
2258 * Get the list of types for objects that a custom group extends to.
2260 * @param array $types
2261 * Var which should have the list appended.
2266 public static function getExtendedObjectTypes(&$types = array()) {
2267 static $flag = FALSE, $objTypes = array();
2270 $extendObjs = array();
2271 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2273 foreach ($extendObjs as $ovId => $ovValues) {
2274 if ($ovValues['description']) {
2275 // description is expected to be a callback func to subtypes
2276 list($callback, $args) = explode(';', trim($ovValues['description']));
2282 if (!is_array($args)) {
2283 CRM_Core_Error
::fatal('Arg is not of type array');
2286 list($className) = explode('::', $callback);
2287 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2290 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2296 $types = array_merge($types, $objTypes);
2301 * @param int $customGroupId
2302 * @param int $entityId
2306 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2307 //check whether the group is multiple
2308 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2309 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2310 $hasReachedMax = FALSE;
2312 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2314 if (!$maxMultiple) {
2315 $hasReachedMax = FALSE;
2318 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2319 //count the number of entries for a entity
2320 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2321 $params = array(1 => array($entityId, 'Integer'));
2322 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2324 if ($count >= $maxMultiple) {
2325 $hasReachedMax = TRUE;
2329 return $hasReachedMax;
2335 public static function getMultipleFieldGroup() {
2336 $multipleGroup = array();
2337 $dao = new CRM_Core_DAO_CustomGroup();
2338 $dao->is_multiple
= 1;
2340 while ($dao->fetch()) {
2341 $multipleGroup[$dao->id
] = $dao->title
;
2343 return $multipleGroup;