3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 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 (reference) an assoc array of name/value pairs
56 * @return CRM_Core_DAO_CustomGroup object
60 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 (reference ) an assoc array of name/value pairs
230 * @param array $defaults (reference ) an assoc array to hold the flattened values
232 * @return CRM_Core_DAO_CustomGroup object
236 static function retrieve(&$params, &$defaults) {
237 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
241 * Update the is_active flag in the db
243 * @param int $id id of the database record
244 * @param boolean $is_active value we want to set the is_active field
246 * @return Object DAO object on sucess, null otherwise
250 static function setIsActive($id, $is_active) {
252 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
255 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
258 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
262 * Determine if given entity (sub)type has any custom groups
264 * @param string $extends e.g. "Individual", "Activity"
265 * @param int $columnId e.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id
266 * @param string $columnValue e.g. "Student" or "3" or "3\05"; see extends_entity_column_value
270 public static function hasCustomGroup($extends, $columnId, $columnValue) {
271 $dao = new CRM_Core_DAO_CustomGroup();
272 $dao->extends = $extends;
273 $dao->extends_entity_column_id
= $columnId;
275 CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) .
276 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
288 * @return bool TRUE if a group is found or created; FALSE on error
290 public static function autoCreateByActivityType($activityTypeId) {
291 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
294 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
297 'extends' => 'Activity',
298 'extends_entity_column_id' => NULL,
299 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
300 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
304 $result = civicrm_api('CustomGroup', 'create', $params);
305 return !$result['is_error'];
309 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
310 * This may also include entity specific data values.
312 * An array containing all custom groups and their custom fields is returned.
314 * @param string $entityType - of the contact whose contact type is needed
315 * @param CRM_Core_Form $form - not used but required
316 * @param int $entityID
317 * @param int $groupID
318 * @param string $subType
319 * @param string $subName
320 * @param bool $fromCache
321 * @param bool $onlySubType
323 * @return array $groupTree - array The returned array is keyed by group id and has the custom group table fields
324 * and a subkey 'fields' holding the specific custom fields.
325 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
326 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
328 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
329 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
330 * With caching the performance impact would be small & the function would be cleaner
336 public static function &getTree(
347 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
351 $strSelect = $strFrom = $strWhere = $orderBy = '';
352 $tableData = array();
354 // using tableData to build the queryString
356 'civicrm_custom_field' => array(
376 'civicrm_custom_group' => array(
386 'extends_entity_column_id',
387 'extends_entity_column_value',
394 foreach ($tableData as $tableName => $tableColumn) {
395 foreach ($tableColumn as $columnName) {
396 $alias = $tableName . "_" . $columnName;
397 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
400 $strSelect = "SELECT " . implode(', ', $select);
402 // from, where, order by
404 FROM civicrm_custom_group
405 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
408 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
409 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
410 $entityType == 'Household'
412 $in = "'$entityType', 'Contact'";
414 elseif (strpos($entityType, "'") !== FALSE) {
415 // this allows the calling function to send in multiple entity types
420 $in = "'$entityType'";
425 if (is_array($subType)) {
426 $subType = implode(',', $subType);
428 if (strpos($subType, ',')) {
429 $subTypeParts = explode(',', $subType);
430 $subTypeClauses = array();
431 foreach ($subTypeParts as $subTypePart) {
432 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
.
433 trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) .
434 CRM_Core_DAO
::VALUE_SEPARATOR
;
435 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
439 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
442 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) .
443 " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
447 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
.
448 trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) .
449 CRM_Core_DAO
::VALUE_SEPARATOR
;
452 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
455 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
456 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
461 WHERE civicrm_custom_group.is_active = 1
462 AND civicrm_custom_field.is_active = 1
463 AND civicrm_custom_group.extends IN ($in)
467 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
472 WHERE civicrm_custom_group.is_active = 1
473 AND civicrm_custom_field.is_active = 1
474 AND civicrm_custom_group.extends IN ($in)
475 AND civicrm_custom_group.extends_entity_column_value IS NULL
481 // since we want a specific group id we add it to the where clause
482 $strWhere .= " AND civicrm_custom_group.id = %1";
483 $params[1] = array($groupID, 'Integer');
486 // since groupID is false we need to show all Inline groups
487 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
490 // ensure that the user has access to these custom groups
491 $strWhere .= " AND " .
492 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
493 'civicrm_custom_group.'
497 ORDER BY civicrm_custom_group.weight,
498 civicrm_custom_group.title,
499 civicrm_custom_field.weight,
500 civicrm_custom_field.label
503 // final query string
504 $queryString = "$strSelect $strFrom $strWhere $orderBy";
506 // lets see if we can retrieve the groupTree from cache
507 $cacheString = $queryString;
509 $cacheString .= "_{$groupID}";
512 $cacheString .= "_Inline";
515 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
516 $multipleFieldGroupCacheKey =
517 "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 integer $entityID id of entity for whom we are checking data for
644 * @param string $table table that we are checking
646 * @param bool $getCount
648 * @return boolean does this entity have data in this custom table
650 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
654 WHERE entity_id = $entityID
656 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
658 return $recordExists;
660 return $recordExists ?
TRUE : FALSE;
664 * Build the group tree for Custom fields which are not 'is_multiple'
666 * The combination of all these fields in one query with a 'using' join was not working for
667 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
668 * mechanism as it seemed to be acceptable in this context
670 * @param array $groupTree (reference) group tree array which is being built
671 * @param integer $entityID id of entity for whom the tree is being build up.
672 * @param array $entitySingleSelectClauses array of select clauses relevant to the entity
673 * @param array $singleFieldTablesWithEntityData array of tables in which this entity has data
675 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
676 $select = implode(', ', $entitySingleSelectClauses);
677 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
678 foreach ($singleFieldTablesWithEntityData as $table) {
679 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
685 WHERE first.entity_id = $entityID
687 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
691 * Build the group tree for Custom fields which are 'is_multiple'
693 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
695 * @param array $groupTree (reference) group tree array which is being built
696 * @param integer $entityID id of entity for whom the tree is being build up.
697 * @param array $entityMultipleSelectClauses array of select clauses relevant to the entity
698 * @param array $multipleFieldTablesWithEntityData array of tables in which this entity has data
700 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData) {
701 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
702 $select = implode(',', $selectClauses);
706 WHERE entity_id = $entityID
708 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
713 * Build the tree entity data - starting from a query retrieving the custom fields build the group
714 * tree data for the relevant entity (entity is included in the query).
716 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
718 * @param array $groupTree (reference) group tree array which is being built
719 * @param string $query
720 * @param array $includedTables tables to include - required because the function (for historical reasons)
721 * iterates through the group tree
723 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables) {
724 $dao = CRM_Core_DAO
::executeQuery($query);
725 while ($dao->fetch()) {
726 foreach ($groupTree as $groupID => $group) {
727 if ($groupID === 'info') {
730 $table = $groupTree[$groupID]['table_name'];
731 //working from the groupTree instead of the table list means we have to iterate & exclude.
732 // this could possibly be re-written as other parts of the function have been refactored
733 // for now we just check if the given table is to be included in this function
734 if (!in_array($table, $includedTables)) {
737 foreach ($group['fields'] as $fieldID => $dontCare) {
738 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
745 * Build the entity-specific custom data into the group tree on a per-field basis
747 * @param object $dao object representing the custom field to be populated into the groupTree
748 * @param array $groupTree (reference) the group tree being build
749 * @param string $table table name
750 * @param unknown_type $groupID custom group ID
751 * @param unknown_type $fieldID custom field ID
753 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID) {
754 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
755 $idName = "{$table}_id";
756 $fieldName = "{$table}_{$column}";
757 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
758 if ($dataType == 'File') {
759 if (isset($dao->$fieldName)) {
760 $config = CRM_Core_Config
::singleton();
761 $fileDAO = new CRM_Core_DAO_File();
762 $fileDAO->id
= $dao->$fieldName;
764 if ($fileDAO->find(TRUE)) {
765 $entityIDName = "{$table}_entity_id";
766 $customValue['id'] = $dao->$idName;
767 $customValue['data'] = $fileDAO->uri
;
768 $customValue['fid'] = $fileDAO->id
;
769 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
770 $customValue['displayURL'] = NULL;
771 $deleteExtra = ts('Are you sure you want to delete attached file.');
773 CRM_Core_Action
::DELETE
=> array(
774 'name' => ts('Delete Attached File'),
775 'url' => 'civicrm/file',
776 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
777 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra .
778 '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
781 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
782 CRM_Core_Action
::DELETE
,
784 'id' => $fileDAO->id
,
785 'eid' => $dao->$entityIDName,
790 'file.manage.delete',
794 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
795 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
796 if ($fileDAO->mime_type
== "image/jpeg" ||
797 $fileDAO->mime_type
== "image/pjpeg" ||
798 $fileDAO->mime_type
== "image/gif" ||
799 $fileDAO->mime_type
== "image/x-png" ||
800 $fileDAO->mime_type
== "image/png"
802 $customValue['displayURL'] = $customValue['fileURL'];
803 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
808 $customValue['imageURL'] =
809 str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
811 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId,
814 if ($path && file_exists($path)) {
815 list($imageWidth, $imageHeight) = getimagesize($path);
816 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
817 $customValue['imageThumbWidth'] = $imageThumbWidth;
818 $customValue['imageThumbHeight'] = $imageThumbHeight;
824 $customValue = array(
825 'id' => $dao->$idName,
831 $customValue = array(
832 'id' => $dao->$idName,
833 'data' => $dao->$fieldName,
837 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
838 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
840 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
841 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
844 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
849 * Get the group title.
851 * @param int $id id of group.
853 * @return string title
859 public static function getTitle($id) {
860 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
864 * Get custom group details for a group.
866 * An array containing custom group details (including their custom field) is returned.
868 * @param int $groupId - group id whose details are needed
869 * @param boolean $searchable - is this field searchable
870 * @param array $extends - which table does it extend if any
872 * @param null $inSelector
874 * @return array $groupTree - array consisting of all group and field details
880 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
882 $groupTree = array();
883 $select = $from = $where = $orderBy = '';
885 $tableData = array();
887 // using tableData to build the queryString
889 'civicrm_custom_field' => array(
913 'civicrm_custom_group' => array(
920 'collapse_adv_display',
922 'extends_entity_column_value',
931 foreach ($tableData as $tableName => $tableColumn) {
932 foreach ($tableColumn as $columnName) {
933 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
936 $select = 'SELECT ' . implode(', ', $s);
938 // from, where, order by
939 $from = " FROM civicrm_custom_field, civicrm_custom_group";
940 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
941 AND civicrm_custom_group.is_active = 1
942 AND civicrm_custom_field.is_active = 1 ";
944 $params[1] = array($groupId, 'Integer');
945 $where .= " AND civicrm_custom_group.id = %1";
949 $where .= " AND civicrm_custom_field.is_searchable = 1";
953 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
958 foreach ($extends as $e) {
959 $clause[] = "civicrm_custom_group.extends = '$e'";
961 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
963 //include case activities customdata if case is enabled
964 if (in_array('Activity', $extends)) {
965 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
966 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
967 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
971 // ensure that the user has access to these custom groups
973 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
974 'civicrm_custom_group.'
977 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
979 // final query string
980 $queryString = $select . $from . $where . $orderBy;
983 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
986 while ($crmDAO->fetch()) {
987 $groupId = $crmDAO->civicrm_custom_group_id
;
988 $fieldId = $crmDAO->civicrm_custom_field_id
;
990 // create an array for groups if it does not exist
991 if (!array_key_exists($groupId, $groupTree)) {
992 $groupTree[$groupId] = array();
993 $groupTree[$groupId]['id'] = $groupId;
995 foreach ($tableData['civicrm_custom_group'] as $v) {
996 $fullField = "civicrm_custom_group_" . $v;
998 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1002 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1005 $groupTree[$groupId]['fields'] = array();
1008 // add the fields now (note - the query row will always contain a field)
1009 $groupTree[$groupId]['fields'][$fieldId] = array();
1010 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1012 foreach ($tableData['civicrm_custom_field'] as $v) {
1013 $fullField = "civicrm_custom_field_" . $v;
1014 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1017 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1025 * @param $entityType
1027 * @param string $cidToken
1031 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1033 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1035 // get 'Tab' and 'Tab with table' groups
1036 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1037 $customGroupDAO->whereAdd("is_active = 1");
1039 // add whereAdd for entity type
1040 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1044 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1045 $customGroupDAO->whereAdd($permissionClause);
1048 $customGroupDAO->orderBy('weight');
1049 $customGroupDAO->find();
1051 // process each group with menu tab
1052 while ($customGroupDAO->fetch()) {
1054 $group['id'] = $customGroupDAO->id
;
1055 $group['path'] = $path;
1056 $group['title'] = "$customGroupDAO->title";
1057 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1058 $group['extra'] = array('gid' => $customGroupDAO->id
);
1059 $group['table_name'] = $customGroupDAO->table_name
;
1060 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1068 * Get the table name for the entity type
1069 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1070 * tableName is 'civicrm_contact'
1072 * @param string $entityType what entity are we extending here ?
1074 * @return string $tableName
1079 * @see _apachesolr_civiAttachments_dereference_file_parent
1081 public static function getTableNameByEntityName($entityType) {
1083 switch ($entityType) {
1087 case 'Organization':
1088 $tableName = 'civicrm_contact';
1091 case 'Contribution':
1092 $tableName = 'civicrm_contribution';
1096 $tableName = 'civicrm_group';
1098 // DRAFTING: Verify if we cannot make it pluggable
1101 $tableName = 'civicrm_activity';
1104 case 'Relationship':
1105 $tableName = 'civicrm_relationship';
1109 $tableName = 'civicrm_membership';
1113 $tableName = 'civicrm_participant';
1117 $tableName = 'civicrm_event';
1121 $tableName = 'civicrm_grant';
1123 // need to add cases for Location, Address
1130 * Get a list of custom groups which extend a given entity type.
1131 * If there are custom-groups which only apply to certain subtypes,
1132 * those WILL be included.
1134 * @param $entityType string
1136 * @return CRM_Core_DAO_CustomGroup
1138 static function getAllCustomGroupsByBaseEntity($entityType) {
1139 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1140 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1141 return $customGroupDAO;
1145 * Add the whereAdd clause for the DAO depending on the type of entity
1146 * the custom group is extending.
1148 * @param $customGroupDAO
1149 * @param string $entityType - what entity are we extending here ?
1151 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
1152 * @param bool $allSubtypes
1159 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1160 $addSubtypeClause = FALSE;
1162 switch ($entityType) {
1164 // if contact, get all related to contact
1165 $extendList = "'Contact','Individual','Household','Organization'";
1166 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1167 if (!$allSubtypes) {
1168 $addSubtypeClause = TRUE;
1174 case 'Organization':
1175 // is I/H/O then get I/H/O and contact
1176 $extendList = "'Contact','$entityType'";
1177 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1178 if (!$allSubtypes) {
1179 $addSubtypeClause = TRUE;
1187 case 'Contribution':
1190 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1194 if ($addSubtypeClause) {
1195 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1197 if (!empty($csType)) {
1198 $subtypeClause = array();
1199 foreach ($csType as $subtype) {
1200 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1201 CRM_Core_DAO
::VALUE_SEPARATOR
;
1202 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1204 $subtypeClause[] = "extends_entity_column_value IS NULL";
1205 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1209 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1215 * Delete the Custom Group.
1217 * @param $group object the DAO custom group object
1218 * @param $force boolean whether to force the deletion, even if there are custom fields
1220 * @return boolean false if field exists for this group, true if group gets deleted.
1226 public static function deleteGroup($group, $force = FALSE) {
1228 //check wheter this contain any custom fields
1229 $customField = new CRM_Core_DAO_CustomField();
1230 $customField->custom_group_id
= $group->id
;
1231 $customField->find();
1233 // return early if there are custom fields and we're not
1234 // forcing the delete, otherwise delete the fields one by one
1235 while ($customField->fetch()) {
1239 CRM_Core_BAO_CustomField
::deleteField($customField);
1242 // drop the table associated with this custom group
1243 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1245 //delete custom group
1248 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1256 * @param bool $viewMode
1257 * @param bool $inactiveNeeded
1258 * @param int $action
1260 static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1261 foreach ($groupTree as $id => $group) {
1262 if (!isset($group['fields'])) {
1265 foreach ($group['fields'] as $field) {
1266 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1267 $value = $field['element_value'];
1269 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1270 ($action != CRM_Core_Action
::UPDATE ||
1272 !array_key_exists('element_value', $field)
1275 $value = $viewMode ?
NULL : $field['default_value'];
1281 if (!empty($field['element_name'])) {
1282 $elementName = $field['element_name'];
1284 switch ($field['html_type']) {
1285 case 'Multi-Select':
1286 case 'AdvMulti-Select':
1288 $defaults[$elementName] = array();
1289 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1291 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1292 if (isset($value)) {
1293 foreach ($customOption as $customValue => $customLabel) {
1294 if (in_array($customValue, $checkedData)) {
1295 if ($field['html_type'] == 'CheckBox') {
1296 $defaults[$elementName][$customValue] = 1;
1299 $defaults[$elementName][$customValue] = $customValue;
1303 $defaults[$elementName][$customValue] = 0;
1309 if (isset($field['customValue']['data'])) {
1310 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1311 foreach ($customOption as $val) {
1312 if (in_array($val['value'], $checkedData)) {
1313 if ($field['html_type'] == 'CheckBox') {
1314 $defaults[$elementName][$val['value']] = 1;
1317 $defaults[$elementName][$val['value']] = $val['value'];
1321 $defaults[$elementName][$val['value']] = 0;
1326 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1327 foreach ($customOption as $val) {
1328 if (in_array($val['value'], $checkedValue)) {
1329 if ($field['html_type'] == 'CheckBox') {
1330 $defaults[$elementName][$val['value']] = 1;
1333 $defaults[$elementName][$val['value']] = $val['value'];
1342 if (isset($value)) {
1343 if (empty($field['time_format'])) {
1344 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1345 $field['date_format']
1349 $timeElement = $elementName . '_time';
1350 if (substr($elementName, -1) == ']') {
1351 $timeElement = substr($elementName, 0, -1) . '_time]';
1353 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1358 case 'Multi-Select Country':
1359 case 'Multi-Select State/Province':
1360 if (isset($value)) {
1361 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1362 foreach ($checkedValue as $val) {
1364 $defaults[$elementName][$val] = $val;
1370 case 'Select Country':
1372 $defaults[$elementName] = $value;
1375 $config = CRM_Core_Config
::singleton();
1376 $defaults[$elementName] = $config->defaultContactCountry
;
1381 if ($field['data_type'] == "Float") {
1382 $defaults[$elementName] = (float) $value;
1384 elseif ($field['data_type'] == 'Money' &&
1385 $field['html_type'] == 'Text'
1387 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1390 $defaults[$elementName] = $value;
1399 * @param array $params
1400 * @param bool $skipFile
1402 static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1403 // Get the Custom form values and groupTree
1404 // first reset all checkbox and radio data
1405 foreach ($groupTree as $groupID => $group) {
1406 if ($groupID === 'info') {
1409 foreach ($group['fields'] as $field) {
1410 $fieldId = $field['id'];
1412 //added Multi-Select option in the below if-statement
1413 if ($field['html_type'] == 'CheckBox' ||
1414 $field['html_type'] == 'Radio' ||
1415 $field['html_type'] == 'AdvMulti-Select' ||
1416 $field['html_type'] == 'Multi-Select'
1418 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1422 foreach ($params as $key => $val) {
1423 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1424 $match[1] == $field['id']
1431 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1432 // field exists in db so populate value from "form".
1433 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1436 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1438 //added for CheckBox
1442 $customValue = array_keys($v);
1443 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] =
1444 CRM_Core_DAO
::VALUE_SEPARATOR
.
1445 implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue) .
1446 CRM_Core_DAO
::VALUE_SEPARATOR
;
1449 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1453 //added for Advanced Multi-Select
1455 case 'AdvMulti-Select':
1456 //added for Multi-Select
1457 case 'Multi-Select':
1459 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] =
1460 CRM_Core_DAO
::VALUE_SEPARATOR
.
1461 implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v) .
1462 CRM_Core_DAO
::VALUE_SEPARATOR
;
1465 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1470 $date = CRM_Utils_Date
::processDate($v);
1471 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1479 //store the file in d/b
1480 $entityId = explode('=', $groupTree['info']['where'][0]);
1481 $fileParams = array('upload_date' => date('Ymdhis'));
1483 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1484 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1487 $fileParams['uri'] = $v['name'];
1488 $fileParams['mime_type'] = $v['type'];
1489 CRM_Core_BAO_File
::filePostProcess($v['name'],
1490 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1491 $groupTree[$groupID]['table_name'],
1496 'custom_' . $fieldId,
1500 $defaults = array();
1501 $paramsFile = array(
1502 'entity_table' => $groupTree[$groupID]['table_name'],
1503 'entity_id' => $entityId[1],
1506 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1511 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1515 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1523 * Generic function to build all the form elements for a specific group tree
1525 * @param CRM_Core_Form $form the form object
1526 * @param array $groupTree the group tree object
1527 * @param boolean $inactiveNeeded return inactive custom groups
1528 * @param string $prefix prefix for custom grouptree assigned to template
1534 static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1535 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1537 // this is fix for date field
1538 $form->assign('currentYear', date('Y'));
1540 foreach ($groupTree as $id => $group) {
1541 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1542 foreach ($group['fields'] as $field) {
1543 $required = CRM_Utils_Array
::value('is_required', $field);
1545 if ($field['data_type'] == 'File') {
1546 if (!empty($field['element_value']['data'])) {
1551 $fieldId = $field['id'];
1552 $elementName = $field['element_name'];
1553 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1559 * Extract the get params from the url, validate
1560 * and store it in session
1562 * @param CRM_Core_Form $form the form object
1563 * @param string $type the type of custom group we are using
1569 static function extractGetParams(&$form, $type) {
1574 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1575 $customValue = array();
1584 foreach ($groupTree as $group) {
1585 if (!isset($group['fields'])) {
1588 foreach ($group['fields'] as $key => $field) {
1589 $fieldName = 'custom_' . $key;
1590 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1594 if (!in_array($field['html_type'], $htmlType) ||
1595 $field['data_type'] == 'Boolean'
1597 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1599 if ($field['html_type'] == 'CheckBox' ||
1600 $field['html_type'] == 'AdvMulti-Select' ||
1601 $field['html_type'] == 'Multi-Select'
1603 $value = str_replace("|", ",", $value);
1604 $mulValues = explode(',', $value);
1605 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1607 foreach ($mulValues as $v1) {
1608 foreach ($customOption as $coID => $coValue) {
1609 if (strtolower(trim($coValue['label'])) ==
1610 strtolower(trim($v1))
1612 $val[$coValue['value']] = 1;
1624 elseif ($field['html_type'] == 'Select' ||
1625 ($field['html_type'] == 'Radio' &&
1626 $field['data_type'] != 'Boolean'
1629 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1630 foreach ($customOption as $customID => $coValue) {
1631 if (strtolower(trim($coValue['label'])) ==
1632 strtolower(trim($value))
1634 $value = $coValue['value'];
1639 elseif ($field['data_type'] == 'Date') {
1640 if (!empty($value)) {
1642 if (!empty($field['time_format'])) {
1643 $time = CRM_Utils_Request
::retrieve($fieldName .
1644 '_time', 'String', $form, FALSE, NULL, 'GET');
1646 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value .
1648 if (!empty($field['time_format'])) {
1649 $customValue[$fieldName . '_time'] = $time;
1656 $customValue[$fieldName] = $value;
1662 return $customValue;
1666 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1667 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1669 * @param int $customFieldId custom field id
1670 * @param array $removeCustomFieldTypes remove custom fields of a type eg: array("Individual") ;
1673 * @return boolean false if it matches else true
1677 static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1678 $query = "SELECT cg.extends as extends
1679 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1680 WHERE cg.id = cf.custom_group_id
1682 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1684 $extends = CRM_Core_DAO
::singleValueQuery($query);
1686 if (in_array($extends, $removeCustomFieldTypes)) {
1698 static function mapTableName($table) {
1703 case 'Organization':
1704 return 'civicrm_contact';
1707 return 'civicrm_activity';
1710 return 'civicrm_group';
1712 case 'Contribution':
1713 return 'civicrm_contribution';
1715 case 'Relationship':
1716 return 'civicrm_relationship';
1719 return 'civicrm_event';
1722 return 'civicrm_membership';
1725 case 'ParticipantRole':
1726 case 'ParticipantEventName':
1727 case 'ParticipantEventType':
1728 return 'civicrm_participant';
1731 return 'civicrm_grant';
1734 return 'civicrm_pledge';
1737 return 'civicrm_address';
1740 return 'civicrm_campaign';
1744 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1745 $qParams = array(1 => array($table, 'String'));
1746 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1749 return 'civicrm_contact';
1752 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1753 if (array_key_exists($table, $extendObjs)) {
1754 return $extendObjs[$table];
1756 CRM_Core_Error
::fatal();
1764 static function createTable($group) {
1766 'name' => $group->table_name
,
1767 'is_multiple' => $group->is_multiple ?
1 : 0,
1768 'extends_name' => self
::mapTableName($group->extends),
1771 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1773 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1777 * Function returns formatted groupTree, sothat form can be easily build in template
1779 * @param array $groupTree associated array
1780 * @param int $groupCount group count by default 1, but can varry for multiple value custom data
1781 * @param object form object
1783 * @return array $formattedGroupTree
1785 static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1786 $formattedGroupTree = array();
1787 $uploadNames = array();
1789 foreach ($groupTree as $key => $value) {
1790 if ($key === 'info') {
1794 // add group information
1795 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1796 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1797 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1798 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1799 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1800 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1802 // this params needed of bulding multiple values
1803 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1804 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1805 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1806 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1807 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1808 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1810 // add field information
1811 foreach ($value['fields'] as $k => $properties) {
1812 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1813 if (isset($properties['customValue']) &&
1814 !CRM_Utils_System
::isNull($properties['customValue'])
1816 if (isset($properties['customValue'][$groupCount])) {
1817 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1818 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1819 if ($properties['data_type'] == 'File') {
1820 $properties['element_value'] = $properties['customValue'][$groupCount];
1821 $uploadNames[] = $properties['element_name'];
1824 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1828 unset($properties['customValue']);
1829 $formattedGroupTree[$key]['fields'][$k] = $properties;
1834 // hack for field type File
1835 $formUploadNames = $form->get('uploadNames');
1836 if (is_array($formUploadNames)) {
1837 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1840 $form->set('uploadNames', $uploadNames);
1843 return $formattedGroupTree;
1847 * Build custom data view
1849 * @param CRM_Core_Form $form page object
1850 * @param array $groupTree associated array
1851 * @param boolean $returnCount true if customValue count needs to be returned
1853 * @param null $prefix
1854 * @param int $customValueId
1858 static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1860 foreach ($groupTree as $key => $group) {
1861 if ($key === 'info') {
1865 foreach ($group['fields'] as $k => $properties) {
1866 $groupID = $group['id'];
1867 if (!empty($properties['customValue'])) {
1868 foreach ($properties['customValue'] as $values) {
1869 if (!empty($customValueId) && $customValueId != $values['id']) {
1872 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1873 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1874 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1875 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1876 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1877 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1878 $details[$groupID][$values['id']]['fields'][$k] = array(
1879 'field_title' => CRM_Utils_Array
::value('label', $properties),
1880 'field_type' => CRM_Utils_Array
::value('html_type',
1883 'field_data_type' => CRM_Utils_Array
::value('data_type',
1886 'field_value' => self
::formatCustomValues($values,
1889 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1893 // also return contact reference contact id if user has view all or edit all contacts perm
1894 if ((CRM_Core_Permission
::check('view all contacts') ||
1895 CRM_Core_Permission
::check('edit all contacts'))
1897 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1900 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1905 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1906 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1907 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1908 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1909 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1910 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1911 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1917 //return a single value count if group id is passed to function
1918 //else return a groupId and count mapped array
1920 return count($details[$gID]);
1923 $countValue = array();
1924 foreach ($details as $key => $value) {
1925 $countValue[$key] = count($details[$key]);
1931 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1937 * Format custom value according to data, view mode
1939 * @param array $values associated array of custom values
1940 * @param array $field associated array
1941 * @param boolean $dncOptionPerLine true if optionPerLine should not be consider
1943 * @return array|null|string
1945 static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1946 $value = $values['data'];
1948 //changed isset CRM-4601
1949 if (CRM_Utils_System
::isNull($value)) {
1953 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1954 $dataType = CRM_Utils_Array
::value('data_type', $field);
1955 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1956 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1957 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1960 $freezeStringChecked = "";
1962 switch ($dataType) {
1964 $customTimeFormat = '';
1965 $customFormat = NULL;
1967 switch ($timeFormat) {
1969 $customTimeFormat = '%l:%M %P';
1973 $customTimeFormat = '%H:%M';
1977 // if time is not selected remove time from value
1978 $value = substr($value, 0, 10);
1981 $supportableFormats = array(
1982 'mm/dd' => "%B %E%f $customTimeFormat",
1983 'dd-mm' => "%E%f %B $customTimeFormat",
1984 'yy' => "%Y $customTimeFormat",
1985 'M yy' => "%b %Y $customTimeFormat",
1986 'yy-mm' => "%Y-%m $customTimeFormat"
1989 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
1990 if (array_key_exists($format, $supportableFormats)) {
1991 $customFormat = $supportableFormats["$format"];
1995 $retValue = CRM_Utils_Date
::customFormat($value, $customFormat);
1999 if ($value == '1') {
2000 $retValue = $freezeStringChecked . ts('Yes') . "\n";
2003 $retValue = $freezeStringChecked . ts('No') . "\n";
2009 $retValue = CRM_Utils_System
::formatWikiURL($value);
2014 $retValue = $values;
2017 case 'ContactReference':
2018 if (!empty($values['data'])) {
2019 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
2028 if ($htmlType == 'Text') {
2029 $retValue = (float) $value;
2033 if ($htmlType == 'Text') {
2034 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2039 if (in_array($htmlType, array('Text', 'TextArea'))) {
2043 // note that if its not text / textarea, the code falls thru and executes
2044 // the below case also
2045 case 'StateProvince':
2050 //added check for Multi-Select in the below if-statement
2051 $customData[] = $value;
2053 //form custom data for multiple-valued custom data
2054 switch ($htmlType) {
2055 case 'Multi-Select Country':
2056 case 'Select Country':
2057 $customData = $value;
2058 if (!is_array($value)) {
2059 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2062 SELECT id as value, name as label
2063 FROM civicrm_country";
2064 $coDAO = CRM_Core_DAO
::executeQuery($query);
2067 case 'Select State/Province':
2068 case 'Multi-Select State/Province':
2069 $customData = $value;
2070 if (!is_array($value)) {
2071 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2075 SELECT id as value, name as label
2076 FROM civicrm_state_province";
2077 $coDAO = CRM_Core_DAO
::executeQuery($query);
2081 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2082 if ($option_group_id) {
2083 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2088 case 'AdvMulti-Select':
2089 case 'Multi-Select':
2090 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2092 if ($option_group_id) {
2093 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2097 if (is_object($coDAO)) {
2098 while ($coDAO->fetch()) {
2099 if ($dataType == 'Country') {
2100 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2101 // and already extracted to .pot files.
2102 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
2104 elseif ($dataType == 'StateProvince') {
2105 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
2108 $options[$coDAO->value
] = $coDAO->label
;
2113 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
2116 foreach ($options as $optionValue => $optionLabel) {
2117 if ($dataType == 'Money') {
2118 foreach ($customData as $k => $v) {
2119 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
2123 //to show only values that are checked
2124 if (in_array((string) $optionValue, $customData)) {
2125 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
2126 if (!$optionPerLine ||
$dncOptionPerLine) {
2130 $retValue .= $checked . $optionLabel;
2133 $retValue[] = $checked . $optionLabel;
2140 //special case for option per line formatting
2141 if ($optionPerLine > 1 && is_array($retValue)) {
2144 $displayValues = array();
2145 $displayString = '';
2146 foreach ($retValue as $val) {
2147 if ($displayString) {
2148 $displayString .= ", ";
2151 $displayString .= $val;
2155 if (($rowCounter == $optionPerLine) ||
2156 ($fieldCounter == count($retValue))
2158 $displayValues[] = $displayString;
2159 $displayString = '';
2163 $retValue = $displayValues;
2166 $retValue = isset($retValue) ?
$retValue : NULL;
2171 * Get the custom group titles by custom field ids.
2173 * @param array $fieldIds - array of custom field ids.
2175 * @return array $groupLabels - array consisting of groups and fields labels with ids.
2178 public static function getGroupTitles($fieldIds) {
2179 if (!is_array($fieldIds) && empty($fieldIds)) {
2183 $groupLabels = array();
2184 $fIds = "(" . implode(',', $fieldIds) . ")";
2187 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2188 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2189 FROM civicrm_custom_group, civicrm_custom_field
2190 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2191 AND civicrm_custom_field.id IN {$fIds}";
2193 $dao = CRM_Core_DAO
::executeQuery($query);
2194 while ($dao->fetch()) {
2195 $groupLabels[$dao->fieldID
] = array(
2196 'fieldID' => $dao->fieldID
,
2197 'fieldLabel' => $dao->fieldLabel
,
2198 'groupID' => $dao->groupID
,
2199 'groupTitle' => $dao->groupTitle
,
2203 return $groupLabels;
2206 static function dropAllTables() {
2207 $query = "SELECT table_name FROM civicrm_custom_group";
2208 $dao = CRM_Core_DAO
::executeQuery($query);
2210 while ($dao->fetch()) {
2211 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2212 CRM_Core_DAO
::executeQuery($query);
2217 * Check whether custom group is empty or not.
2219 * @param int $gID - custom group id.
2221 * @return boolean true if empty otherwise false.
2224 static function isGroupEmpty($gID) {
2229 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2234 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2235 $value = CRM_Core_DAO
::singleValueQuery($query);
2237 if (empty($value)) {
2245 * Get the list of types for objects that a custom group extends to.
2247 * @param array $types - var which should have the list appended.
2249 * @return array of types.
2252 static function getExtendedObjectTypes(&$types = array()) {
2253 static $flag = FALSE, $objTypes = array();
2256 $extendObjs = array();
2257 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2259 foreach ($extendObjs as $ovId => $ovValues) {
2260 if ($ovValues['description']) {
2261 // description is expected to be a callback func to subtypes
2262 list($callback, $args) = explode(';', trim($ovValues['description']));
2268 if (!is_array($args)) {
2269 CRM_Core_Error
::fatal('Arg is not of type array');
2272 list($className) = explode('::', $callback);
2273 require_once(str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2276 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2282 $types = array_merge($types, $objTypes);
2287 * @param int $customGroupId
2288 * @param int $entityId
2292 static function hasReachedMaxLimit($customGroupId, $entityId) {
2293 //check whether the group is multiple
2294 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2295 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2296 $hasReachedMax = FALSE;
2298 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2300 if (!$maxMultiple) {
2301 $hasReachedMax = FALSE;
2304 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2305 //count the number of entries for a entity
2306 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2307 $params = array(1 => array($entityId, 'Integer'));
2308 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2310 if ($count >= $maxMultiple) {
2311 $hasReachedMax = TRUE;
2315 return $hasReachedMax;
2321 static function getMultipleFieldGroup() {
2322 $multipleGroup = array();
2323 $dao = new CRM_Core_DAO_CustomGroup();
2324 $dao->is_multiple
= 1;
2326 while ($dao->fetch()) {
2327 $multipleGroup[$dao->id
] = $dao->title
;
2329 return $multipleGroup;