3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 object 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 (CRM_Utils_Array
::value('extends_entity_column_value', $params)) {
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('', ''), $extendsChildType);
99 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
100 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType . CRM_Core_DAO
::VALUE_SEPARATOR
;
104 $extendsChildType = 'null';
106 $group->extends_entity_column_value
= $extendsChildType;
108 if (isset($params['id'])) {
109 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
114 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
115 $fields = array('style', 'collapse_display', 'collapse_adv_display', 'help_pre', 'help_post', 'is_active', 'is_multiple');
116 foreach ($fields as $field) {
117 $group->$field = CRM_Utils_Array
::value($field, $params, FALSE);
119 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
120 $params['max_multiple'] >= '0'
121 ) ?
$params['max_multiple'] : 'null' : 'null';
123 $tableName = $oldTableName = NULL;
124 if (isset($params['id'])) {
125 $group->id
= $params['id'];
126 //check whether custom group was changed from single-valued to multiple-valued
127 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
132 if ((CRM_Utils_Array
::value('is_multiple', $params) ||
$isMultiple) &&
133 ($params['is_multiple'] != $isMultiple)
135 $oldTableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
142 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
143 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
145 // we do this only once, so name never changes
146 if (isset($params['name'])) {
147 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
150 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
153 if (isset($params['table_name'])) {
154 $tableName = $params['table_name'];
156 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
157 // Bad idea. Prevent group creation because it might lead to a broken configuration.
158 CRM_Core_Error
::fatal(ts("Cannot create custom table because %1 is already a core table.", array('1' => $tableName)));
163 // enclose the below in a transaction
164 $transaction = new CRM_Core_Transaction();
167 if (!isset($params['id'])) {
168 if (!isset($params['table_name'])) {
169 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 32));
170 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
172 $group->table_name
= $tableName;
173 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
179 // now create the table associated with this group
180 self
::createTable($group);
182 elseif ($oldTableName) {
183 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($oldTableName, CRM_Utils_Array
::value('is_multiple', $params));
186 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
187 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
191 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends'][0]));
193 $transaction->commit();
196 CRM_Utils_System
::flushCache();
199 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
202 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
209 * Takes a bunch of params that are needed to match certain criteria and
210 * retrieves the relevant objects. Typically the valid params are only
211 * contact_id. We'll tweak this function to be more full featured over a period
212 * of time. This is the inverse function of create. It also stores all the retrieved
213 * values in the default array
215 * @param array $params (reference ) an assoc array of name/value pairs
216 * @param array $defaults (reference ) an assoc array to hold the flattened values
218 * @return object CRM_Core_DAO_CustomGroup object
222 static function retrieve(&$params, &$defaults) {
223 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
227 * update the is_active flag in the db
229 * @param int $id id of the database record
230 * @param boolean $is_active value we want to set the is_active field
232 * @return Object DAO object on sucess, null otherwise
236 static function setIsActive($id, $is_active) {
238 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
241 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
244 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
248 * Determine if given entity (sub)type has any custom groups
250 * @param string $extends e.g. "Individual", "Activity"
251 * @param int $columnId e.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id
252 * @param string $columnValue e.g. "Student" or "3" or "3\05"; see extends_entity_column_value
254 public static function hasCustomGroup($extends, $columnId, $columnValue) {
255 $dao = new CRM_Core_DAO_CustomGroup();
256 $dao->extends = $extends;
257 $dao->extends_entity_column_id
= $columnId;
258 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
259 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
260 //$dao->extends_entity_column_value = $columnValue;
261 return $dao->find() ?
TRUE : FALSE;
265 * Determine if there are any CustomGroups for the given $activityTypeId.
266 * If none found, create one.
268 * @param int $activityTypeId
269 * @return bool TRUE if a group is found or created; FALSE on error
271 public static function autoCreateByActivityType($activityTypeId) {
272 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
275 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
278 'extends' => 'Activity',
279 'extends_entity_column_id' => NULL,
280 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
281 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
285 $result = civicrm_api('CustomGroup', 'create', $params);
286 return ! $result['is_error'];
290 * Get custom groups/fields for type of entity.
292 * An array containing all custom groups and their custom fields is returned.
294 * @param string $entityType - of the contact whose contact type is needed
295 * @param int $entityId - optional - id of entity if we need to populate the tree with custom values.
296 * @param int $groupId - optional group id (if we need it for a single group only)
297 * - if groupId is 0 it gets for inline groups only
298 * - if groupId is -1 we get for all groups
300 * @return array $groupTree - array consisting of all groups and fields and optionally populated with custom data values.
307 public static function &getTree($entityType,
316 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
320 $strSelect = $strFrom = $strWhere = $orderBy = '';
321 $tableData = array();
323 // using tableData to build the queryString
325 'civicrm_custom_field' =>
345 'civicrm_custom_group' =>
356 'extends_entity_column_id',
357 'extends_entity_column_value',
364 foreach ($tableData as $tableName => $tableColumn) {
365 foreach ($tableColumn as $columnName) {
366 $alias = $tableName . "_" . $columnName;
367 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
370 $strSelect = "SELECT " . implode(', ', $select);
372 // from, where, order by
374 FROM civicrm_custom_group
375 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
378 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
379 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
$entityType == 'Household') {
380 $in = "'$entityType', 'Contact'";
382 elseif (strpos($entityType, "'") !== FALSE) {
383 // this allows the calling function to send in multiple entity types
388 $in = "'$entityType'";
393 if (is_array($subType)) {
394 $subType = implode(',', $subType);
396 if (strpos($subType, ',')) {
397 $subTypeParts = explode(',', $subType);
398 $subTypeClauses = array();
399 foreach ($subTypeParts as $subTypePart) {
400 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
401 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
403 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
406 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
408 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
409 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
413 WHERE civicrm_custom_group.is_active = 1
414 AND civicrm_custom_field.is_active = 1
415 AND civicrm_custom_group.extends IN ($in)
419 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
424 WHERE civicrm_custom_group.is_active = 1
425 AND civicrm_custom_field.is_active = 1
426 AND civicrm_custom_group.extends IN ($in)
427 AND civicrm_custom_group.extends_entity_column_value IS NULL
433 // since we want a specific group id we add it to the where clause
434 $strWhere .= " AND civicrm_custom_group.id = %1";
435 $params[1] = array($groupID, 'Integer');
438 // since groupID is false we need to show all Inline groups
439 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
442 // ensure that the user has access to these custom groups
443 $strWhere .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
444 'civicrm_custom_group.'
448 ORDER BY civicrm_custom_group.weight,
449 civicrm_custom_group.title,
450 civicrm_custom_field.weight,
451 civicrm_custom_field.label
454 // final query string
455 $queryString = "$strSelect $strFrom $strWhere $orderBy";
457 // lets see if we can retrieve the groupTree from cache
458 $cacheString = $queryString;
459 if ( $groupID > 0 ) {
460 $cacheString .= "_{$groupID}";
462 $cacheString .= "_Inline";
465 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
467 $cache = CRM_Utils_Cache
::singleton();
470 $groupTree = $cache->get($cacheKey);
473 if (empty($groupTree)) {
474 $groupTree = array();
475 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
477 $customValueTables = array();
480 while ($crmDAO->fetch()) {
482 $groupID = $crmDAO->civicrm_custom_group_id
;
483 $fieldId = $crmDAO->civicrm_custom_field_id
;
485 // create an array for groups if it does not exist
486 if (!array_key_exists($groupID, $groupTree)) {
487 $groupTree[$groupID] = array();
488 $groupTree[$groupID]['id'] = $groupID;
490 // populate the group information
491 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
492 $fullFieldName = "civicrm_custom_group_$fieldName";
493 if ($fieldName == 'id' ||
494 is_null($crmDAO->$fullFieldName)
499 if ($fieldName == 'extends_entity_column_value' && $subType) {
500 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
502 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
504 $groupTree[$groupID]['fields'] = array();
506 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
509 // add the fields now (note - the query row will always contain a field)
510 // we only reset this once, since multiple values come is as multiple rows
511 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
512 $groupTree[$groupID]['fields'][$fieldId] = array();
515 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
516 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
517 // populate information for a custom field
518 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
519 $fullFieldName = "civicrm_custom_field_$fieldName";
520 if ($fieldName == 'id' ||
521 is_null($crmDAO->$fullFieldName)
525 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
529 if (!empty($customValueTables)) {
530 $groupTree['info'] = array('tables' => $customValueTables);
533 $cache->set($cacheKey, $groupTree);
536 // now that we have all the groups and fields, lets get the values
537 // since we need to know the table and field names
539 // add info to groupTree
540 if (isset($groupTree['info']) && !empty($groupTree['info'])) {
541 $select = $from = $where = array();
542 foreach ($groupTree['info']['tables'] as $table => $fields) {
544 $select[] = "{$table}.id as {$table}_id";
545 $select[] = "{$table}.entity_id as {$table}_entity_id";
547 foreach ($fields as $column => $dontCare) {
548 $select[] = "{$table}.{$column} as {$table}_{$column}";
552 $where[] = "{$table}.entity_id = $entityID";
556 $groupTree['info']['select'] = $select;
557 $groupTree['info']['from'] = $from;
558 $groupTree['info']['where'] = NULL;
561 $groupTree['info']['where'] = $where;
562 $select = implode(', ', $select);
564 // this is a hack to find a table that has some values for this
565 // entityID to make the below LEFT JOIN work (CRM-2518)
567 foreach ($from as $table) {
571 WHERE entity_id = $entityID
573 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
575 $firstTable = $table;
581 $fromSQL = $firstTable;
582 foreach ($from as $table) {
583 if ($table != $firstTable) {
584 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
591 WHERE {$firstTable}.entity_id = $entityID
594 $dao = CRM_Core_DAO
::executeQuery($query);
596 while ($dao->fetch()) {
597 foreach ($groupTree as $groupID => $group) {
598 if ($groupID === 'info') {
601 $table = $groupTree[$groupID]['table_name'];
602 foreach ($group['fields'] as $fieldID => $dontCare) {
603 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
604 $idName = "{$table}_id";
605 $fieldName = "{$table}_{$column}";
607 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
608 if ($dataType == 'File') {
609 if (isset($dao->$fieldName)) {
610 $config = CRM_Core_Config
::singleton();
611 $fileDAO = new CRM_Core_DAO_File();
612 $fileDAO->id
= $dao->$fieldName;
614 if ($fileDAO->find(TRUE)) {
615 $entityIDName = "{$table}_entity_id";
616 $customValue['id'] = $dao->$idName;
617 $customValue['data'] = $fileDAO->uri
;
618 $customValue['fid'] = $fileDAO->id
;
619 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
620 $customValue['displayURL'] = NULL;
621 $deleteExtra = ts('Are you sure you want to delete attached file.');
623 CRM_Core_Action
::DELETE
=>
625 'name' => ts('Delete Attached File'),
626 'url' => 'civicrm/file',
627 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
629 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
632 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
633 CRM_Core_Action
::DELETE
,
635 'id' => $fileDAO->id
,
636 'eid' => $dao->$entityIDName,
640 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
641 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
642 if ($fileDAO->mime_type
== "image/jpeg" ||
643 $fileDAO->mime_type
== "image/pjpeg" ||
644 $fileDAO->mime_type
== "image/gif" ||
645 $fileDAO->mime_type
== "image/x-png" ||
646 $fileDAO->mime_type
== "image/png"
648 $customValue['displayURL'] = $customValue['fileURL'];
649 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
654 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) . $fileDAO->uri
;
655 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId,
658 list($imageWidth, $imageHeight) = getimagesize($path);
659 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
660 $customValue['imageThumbWidth'] = $imageThumbWidth;
661 $customValue['imageThumbHeight'] = $imageThumbHeight;
666 $customValue = array(
667 'id' => $dao->$idName,
673 $customValue = array(
674 'id' => $dao->$idName,
675 'data' => $dao->$fieldName,
678 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
679 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
681 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
682 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
685 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
698 * Get the group title.
700 * @param int $id id of group.
702 * @return string title
708 public static function getTitle($id) {
709 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
713 * Get custom group details for a group.
715 * An array containing custom group details (including their custom field) is returned.
717 * @param int $groupId - group id whose details are needed
718 * @param boolean $searchable - is this field searchable
719 * @param array $extends - which table does it extend if any
721 * @return array $groupTree - array consisting of all group and field details
728 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL) {
730 $groupTree = array();
731 $select = $from = $where = $orderBy = '';
733 $tableData = array();
735 // using tableData to build the queryString
737 'civicrm_custom_field' =>
761 'civicrm_custom_group' =>
769 'collapse_adv_display',
771 'extends_entity_column_value',
779 foreach ($tableData as $tableName => $tableColumn) {
780 foreach ($tableColumn as $columnName) {
781 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
784 $select = 'SELECT ' . implode(', ', $s);
786 // from, where, order by
787 $from = " FROM civicrm_custom_field, civicrm_custom_group";
788 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
789 AND civicrm_custom_group.is_active = 1
790 AND civicrm_custom_field.is_active = 1 ";
792 $params[1] = array($groupId, 'Integer');
793 $where .= " AND civicrm_custom_group.id = %1";
797 $where .= " AND civicrm_custom_field.is_searchable = 1";
802 foreach ($extends as $e) {
803 $clause[] = "civicrm_custom_group.extends = '$e'";
805 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
807 //include case activities customdata if case is enabled
808 if (in_array('Activity', $extends)) {
809 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
810 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
811 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
815 // ensure that the user has access to these custom groups
816 $where .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
817 'civicrm_custom_group.'
820 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
822 // final query string
823 $queryString = $select . $from . $where . $orderBy;
826 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
829 while ($crmDAO->fetch()) {
830 $groupId = $crmDAO->civicrm_custom_group_id
;
831 $fieldId = $crmDAO->civicrm_custom_field_id
;
833 // create an array for groups if it does not exist
834 if (!array_key_exists($groupId, $groupTree)) {
835 $groupTree[$groupId] = array();
836 $groupTree[$groupId]['id'] = $groupId;
838 foreach ($tableData['civicrm_custom_group'] as $v) {
839 $fullField = "civicrm_custom_group_" . $v;
841 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
845 $groupTree[$groupId][$v] = $crmDAO->$fullField;
848 $groupTree[$groupId]['fields'] = array();
851 // add the fields now (note - the query row will always contain a field)
852 $groupTree[$groupId]['fields'][$fieldId] = array();
853 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
855 foreach ($tableData['civicrm_custom_field'] as $v) {
856 $fullField = "civicrm_custom_field_" . $v;
857 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
860 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
867 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
869 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
871 // get only 'Tab' groups
872 $customGroupDAO->whereAdd("style = 'Tab'");
873 $customGroupDAO->whereAdd("is_active = 1");
875 // add whereAdd for entity type
876 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
880 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
881 $customGroupDAO->whereAdd($permissionClause);
884 $customGroupDAO->orderBy('weight');
885 $customGroupDAO->find();
887 // process each group with menu tab
888 while ($customGroupDAO->fetch()) {
890 $group['id'] = $customGroupDAO->id
;
891 $group['path'] = $path;
892 $group['title'] = "$customGroupDAO->title";
893 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
894 $group['extra'] = array('gid' => $customGroupDAO->id
);
895 $group['table_name'] = $customGroupDAO->table_name
;
903 * Get the table name for the entity type
904 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
905 * tableName is 'civicrm_contact'
907 * @param string $entityType what entity are we extending here ?
909 * @return string $tableName
915 private static function _getTableName($entityType) {
917 switch ($entityType) {
922 $tableName = 'civicrm_contact';
926 $tableName = 'civicrm_contribution';
930 $tableName = 'civicrm_group';
932 // DRAFTING: Verify if we cannot make it pluggable
935 $tableName = 'civicrm_activity';
939 $tableName = 'civicrm_relationship';
943 $tableName = 'civicrm_membership';
947 $tableName = 'civicrm_participant';
951 $tableName = 'civicrm_event';
955 $tableName = 'civicrm_grant';
957 // need to add cases for Location, Address
964 * Get a list of custom groups which extend a given entity type.
965 * If there are custom-groups which only apply to certain subtypes,
966 * those WILL be included.
968 * @param $entityType string
969 * @return CRM_Core_DAO_CustomGroup
971 static function getAllCustomGroupsByBaseEntity($entityType) {
972 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
973 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
974 return $customGroupDAO;
978 * Add the whereAdd clause for the DAO depending on the type of entity
979 * the custom group is extending.
981 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
982 * @param string $entityType - what entity are we extending here ?
990 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
991 $addSubtypeClause = FALSE;
993 switch ($entityType) {
995 // if contact, get all related to contact
996 $extendList = "'Contact','Individual','Household','Organization'";
997 $customGroupDAO->whereAdd("extends IN ( $extendList )");
999 $addSubtypeClause = TRUE;
1005 case 'Organization':
1006 // is I/H/O then get I/H/O and contact
1007 $extendList = "'Contact','$entityType'";
1008 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1009 if (!$allSubtypes) {
1010 $addSubtypeClause = TRUE;
1017 case 'Contribution':
1020 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1024 if ($addSubtypeClause) {
1025 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1027 if (!empty($csType)) {
1028 $subtypeClause = array();
1029 foreach ($csType as $subtype) {
1030 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
1031 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1033 $subtypeClause[] = "extends_entity_column_value IS NULL";
1034 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) . " )");
1037 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1043 * Delete the Custom Group.
1045 * @param $group object the DAO custom group object
1046 * @param $force boolean whether to force the deletion, even if there are custom fields
1048 * @return boolean false if field exists for this group, true if group gets deleted.
1054 public static function deleteGroup($group, $force = FALSE) {
1056 //check wheter this contain any custom fields
1057 $customField = new CRM_Core_DAO_CustomField();
1058 $customField->custom_group_id
= $group->id
;
1059 $customField->find();
1061 // return early if there are custom fields and we're not
1062 // forcing the delete, otherwise delete the fields one by one
1063 while ($customField->fetch()) {
1067 CRM_Core_BAO_CustomField
::deleteField($customField);
1070 // drop the table associated with this custom group
1071 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1073 //delete custom group
1076 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1081 static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1082 foreach ($groupTree as $id => $group) {
1083 if (!isset($group['fields'])) {
1086 $groupId = CRM_Utils_Array
::value('id', $group);
1087 foreach ($group['fields'] as $field) {
1088 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1089 $value = $field['element_value'];
1091 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1092 ($action != CRM_Core_Action
::UPDATE ||
1094 !array_key_exists('element_value', $field)
1097 $value = $viewMode ?
NULL : $field['default_value'];
1103 $fieldId = $field['id'];
1104 $elementName = $field['element_name'];
1105 switch ($field['html_type']) {
1106 case 'Multi-Select':
1107 case 'AdvMulti-Select':
1109 $defaults[$elementName] = array();
1110 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1112 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1113 if (isset($value)) {
1114 foreach ($customOption as $customValue => $customLabel) {
1115 if (in_array($customValue, $checkedData)) {
1116 if ($field['html_type'] == 'CheckBox') {
1117 $defaults[$elementName][$customValue] = 1;
1120 $defaults[$elementName][$customValue] = $customValue;
1124 $defaults[$elementName][$customValue] = 0;
1130 if (isset($field['customValue']['data'])) {
1131 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1132 foreach ($customOption as $val) {
1133 if (in_array($val['value'], $checkedData)) {
1134 if ($field['html_type'] == 'CheckBox') {
1135 $defaults[$elementName][$val['value']] = 1;
1138 $defaults[$elementName][$val['value']] = $val['value'];
1142 $defaults[$elementName][$val['value']] = 0;
1147 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1148 foreach ($customOption as $val) {
1149 if (in_array($val['value'], $checkedValue)) {
1150 if ($field['html_type'] == 'CheckBox') {
1151 $defaults[$elementName][$val['value']] = 1;
1154 $defaults[$elementName][$val['value']] = $val['value'];
1163 if (isset($value)) {
1164 if (empty($field['time_format'])) {
1165 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1166 $field['date_format']
1170 $timeElement = $elementName . '_time';
1171 if (substr($elementName, -1) == ']') {
1172 $timeElement = substr($elementName, 0, -1) . '_time]';
1174 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1179 case 'Multi-Select Country':
1180 case 'Multi-Select State/Province':
1181 if (isset($value)) {
1182 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1183 foreach ($checkedValue as $val) {
1185 $defaults[$elementName][$val] = $val;
1191 case 'Select Country':
1193 $defaults[$elementName] = $value;
1196 $config = CRM_Core_Config
::singleton();
1197 $defaults[$elementName] = $config->defaultContactCountry
;
1201 case 'Autocomplete-Select':
1202 $hiddenEleName = $elementName . '_id';
1203 if (substr($elementName, -1) == ']') {
1204 $hiddenEleName = substr($elementName, 0, -1) . '_id]';
1206 if ($field['data_type'] == "ContactReference") {
1207 if (is_numeric($value)) {
1208 $defaults[$hiddenEleName] = $value;
1209 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1213 $label = CRM_Core_BAO_CustomOption
::getOptionLabel($field['id'], $value);
1214 $defaults[$hiddenEleName] = $value;
1215 $defaults[$elementName] = $label;
1220 if ($field['data_type'] == "Float") {
1221 $defaults[$elementName] = (float)$value;
1223 elseif ($field['data_type'] == 'Money' &&
1224 $field['html_type'] == 'Text'
1226 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1229 $defaults[$elementName] = $value;
1236 static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1237 // Get the Custom form values and groupTree
1238 // first reset all checkbox and radio data
1239 foreach ($groupTree as $groupID => $group) {
1240 if ($groupID === 'info') {
1243 foreach ($group['fields'] as $field) {
1244 $fieldId = $field['id'];
1246 //added Multi-Select option in the below if-statement
1247 if ($field['html_type'] == 'CheckBox' ||
$field['html_type'] == 'Radio' ||
1248 $field['html_type'] == 'AdvMulti-Select' ||
$field['html_type'] == 'Multi-Select'
1250 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1254 foreach ($params as $key => $val) {
1255 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1256 $match[1] == $field['id']
1263 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1264 // field exists in db so populate value from "form".
1265 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1268 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1270 //added for CheckBox
1274 $customValue = array_keys($v);
1275 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1278 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1282 //added for Advanced Multi-Select
1284 case 'AdvMulti-Select':
1285 //added for Multi-Select
1286 case 'Multi-Select':
1288 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1291 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1296 $date = CRM_Utils_Date
::processDate($v);
1297 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1305 //store the file in d/b
1306 $entityId = explode('=', $groupTree['info']['where'][0]);
1307 $fileParams = array('upload_date' => date('Ymdhis'));
1309 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1310 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1313 $fileParams['uri'] = $v['name'];
1314 $fileParams['mime_type'] = $v['type'];
1315 CRM_Core_BAO_File
::filePostProcess($v['name'],
1316 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1317 $groupTree[$groupID]['table_name'],
1322 'custom_' . $fieldId,
1326 $defaults = array();
1327 $paramsFile = array(
1328 'entity_table' => $groupTree[$groupID]['table_name'],
1329 'entity_id' => $entityId[1],
1332 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1337 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1341 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1349 * generic function to build all the form elements for a specific group tree
1351 * @param CRM_Core_Form $form the form object
1352 * @param array $groupTree the group tree object
1353 * @param string $showName
1354 * @param string $hideName
1360 static function buildQuickForm(&$form,
1362 $inactiveNeeded = FALSE,
1367 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1371 // this is fix for date field
1372 $form->assign('currentYear', date('Y'));
1374 foreach ($groupTree as $id => $group) {
1376 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1378 $groupId = CRM_Utils_Array
::value('id', $group);
1379 foreach ($group['fields'] as $field) {
1380 $required = CRM_Utils_Array
::value('is_required', $field);
1382 if ($field['data_type'] == 'File') {
1383 if (isset($field['customValue']['data'])) {
1388 $fieldId = $field['id'];
1389 $elementName = $field['element_name'];
1390 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1396 * Function to extract the get params from the url, validate
1397 * and store it in session
1399 * @param CRM_Core_Form $form the form object
1400 * @param string $type the type of custom group we are using
1406 static function extractGetParams(&$form, $type) {
1407 // if not GET params return
1412 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1413 $customValue = array();
1414 $htmlType = array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Select', 'Radio');
1416 foreach ($groupTree as $group) {
1417 if (!isset($group['fields'])) {
1420 foreach ($group['fields'] as $key => $field) {
1421 $fieldName = 'custom_' . $key;
1422 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form);
1426 if (!in_array($field['html_type'], $htmlType) ||
1427 $field['data_type'] == 'Boolean'
1429 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1431 if ($field['html_type'] == 'CheckBox' ||
1432 $field['html_type'] == 'AdvMulti-Select' ||
1433 $field['html_type'] == 'Multi-Select'
1435 $value = str_replace("|", ",", $value);
1436 $mulValues = explode(',', $value);
1437 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1439 foreach ($mulValues as $v1) {
1440 foreach ($customOption as $coID => $coValue) {
1441 if (strtolower(trim($coValue['label'])) == strtolower(trim($v1))) {
1442 $val[$coValue['value']] = 1;
1454 elseif ($field['html_type'] == 'Select' ||
1455 ($field['html_type'] == 'Radio' &&
1456 $field['data_type'] != 'Boolean'
1459 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1460 foreach ($customOption as $customID => $coValue) {
1461 if (strtolower(trim($coValue['label'])) == strtolower(trim($value))) {
1462 $value = $coValue['value'];
1467 elseif ($field['data_type'] == 'Date') {
1468 if (!empty($value)) {
1470 if (CRM_Utils_Array
::value('time_format', $field)) {
1471 $time = CRM_Utils_Request
::retrieve($fieldName . '_time', 'String', $form);
1473 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value . ' ' . $time);
1474 if (CRM_Utils_Array
::value('time_format', $field)) {
1475 $customValue[$fieldName . '_time'] = $time;
1482 $customValue[$fieldName] = $value;
1488 return $customValue;
1492 * Function to check the type of custom field type (eg: Used for Individual, Contribution, etc)
1493 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1495 * @param int $customFieldId custom field id
1496 * @param array $removeCustomFieldTypes remove custom fields of a type eg: array("Individual") ;
1499 * @return boolean false if it matches else true
1503 static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1504 $query = "SELECT cg.extends as extends
1505 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1506 WHERE cg.id = cf.custom_group_id
1507 AND cf.id =" . CRM_Utils_Type
::escape($customFieldId, 'Integer');
1509 $extends = CRM_Core_DAO
::singleValueQuery($query);
1511 if (in_array($extends, $removeCustomFieldTypes)) {
1517 static function mapTableName($table) {
1522 case 'Organization':
1523 return 'civicrm_contact';
1526 return 'civicrm_activity';
1529 return 'civicrm_group';
1531 case 'Contribution':
1532 return 'civicrm_contribution';
1534 case 'Relationship':
1535 return 'civicrm_relationship';
1538 return 'civicrm_event';
1541 return 'civicrm_membership';
1544 case 'ParticipantRole':
1545 case 'ParticipantEventName':
1546 case 'ParticipantEventType':
1547 return 'civicrm_participant';
1550 return 'civicrm_grant';
1553 return 'civicrm_pledge';
1556 return 'civicrm_address';
1559 return 'civicrm_campaign';
1563 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1564 $qParams = array(1 => array($table, 'String'));
1565 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1568 return 'civicrm_contact';
1571 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1572 if (array_key_exists($table, $extendObjs)) {
1573 return $extendObjs[$table];
1575 CRM_Core_Error
::fatal();
1580 static function createTable($group) {
1582 'name' => $group->table_name
,
1583 'is_multiple' => $group->is_multiple ?
1 : 0,
1584 'extends_name' => self
::mapTableName($group->extends),
1587 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1589 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1593 * Function returns formatted groupTree, sothat form can be easily build in template
1595 * @param array $groupTree associated array
1596 * @param int $groupCount group count by default 1, but can varry for multiple value custom data
1597 * @param object form object
1599 * @return array $formattedGroupTree
1601 static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1602 $formattedGroupTree = array();
1603 $uploadNames = array();
1605 foreach ($groupTree as $key => $value) {
1606 if ($key === 'info') {
1610 // add group information
1611 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1612 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1613 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1614 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1615 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1616 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1618 // this params needed of bulding multiple values
1619 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1620 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1621 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1622 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1623 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1624 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1626 // add field information
1627 foreach ($value['fields'] as $k => $properties) {
1628 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1629 if (isset($properties['customValue']) && !CRM_Utils_system
::isNull($properties['customValue'])) {
1630 if (isset($properties['customValue'][$groupCount])) {
1631 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1632 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1633 if ($properties['data_type'] == 'File') {
1634 $properties['element_value'] = $properties['customValue'][$groupCount];
1635 $uploadNames[] = $properties['element_name'];
1638 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1642 unset($properties['customValue']);
1643 $formattedGroupTree[$key]['fields'][$k] = $properties;
1648 // hack for field type File
1649 $formUploadNames = $form->get('uploadNames');
1650 if (is_array($formUploadNames)) {
1651 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1654 $form->set('uploadNames', $uploadNames);
1657 return $formattedGroupTree;
1661 * Build custom data view
1662 * @param object $form page object
1663 * @param array $groupTree associated array
1664 * @param boolean $returnCount true if customValue count needs to be returned
1666 static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL) {
1667 foreach ($groupTree as $key => $group) {
1668 if ($key === 'info') {
1672 foreach ($group['fields'] as $k => $properties) {
1673 $groupID = $group['id'];
1674 if (!empty($properties['customValue'])) {
1675 foreach ($properties['customValue'] as $values) {
1676 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1677 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1678 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1679 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1680 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1681 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1682 $details[$groupID][$values['id']]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties),
1683 'field_type' => CRM_Utils_Array
::value('html_type',
1686 'field_data_type' => CRM_Utils_Array
::value('data_type',
1689 'field_value' => self
::formatCustomValues($values,
1692 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1696 // also return contact reference contact id if user has view all or edit all contacts perm
1697 if ((CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts'))
1698 && $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] == 'ContactReference'
1700 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1705 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1706 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1707 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1708 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1709 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1710 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1711 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1717 //return a single value count if group id is passed to function
1718 //else return a groupId and count mapped array
1720 return count($details[$gID]);
1723 foreach( $details as $key => $value ) {
1724 $countValue[$key] = count($details[$key]);
1730 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1736 * Format custom value according to data, view mode
1738 * @param array $values associated array of custom values
1739 * @param array $field associated array
1740 * @param boolean $dncOptionPerLine true if optionPerLine should not be consider
1743 static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1744 $value = $values['data'];
1746 //changed isset CRM-4601
1747 if (CRM_Utils_System
::isNull($value)) {
1751 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1752 $dataType = CRM_Utils_Array
::value('data_type', $field);
1753 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1754 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1755 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1758 $freezeStringChecked = "";
1760 switch ($dataType) {
1762 $customTimeFormat = '';
1763 $customFormat = NULL;
1765 switch ($timeFormat) {
1767 $customTimeFormat = '%l:%M %P';
1771 $customTimeFormat = '%H:%M';
1775 // if time is not selected remove time from value
1776 $value = substr($value, 0, 10);
1779 $supportableFormats = array(
1780 'mm/dd' => "%B %E%f $customTimeFormat",
1781 'dd-mm' => "%E%f %B $customTimeFormat",
1782 'yy' => "%Y $customTimeFormat",
1783 'M yy' => "%b %Y $customTimeFormat",
1784 'yy-mm' => "%Y-%m $customTimeFormat"
1787 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
1788 if (array_key_exists($format, $supportableFormats)) {
1789 $customFormat = $supportableFormats["$format"];
1793 $retValue = CRM_Utils_Date
::customFormat($value, $customFormat);
1797 if ($value == '1') {
1798 $retValue = $freezeStringChecked . ts('Yes') . "\n";
1801 $retValue = $freezeStringChecked . ts('No') . "\n";
1807 $retValue = CRM_Utils_System
::formatWikiURL($value);
1812 $retValue = $values;
1815 case 'ContactReference':
1816 if (CRM_Utils_Array
::value('data', $values)) {
1817 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
1826 if ($htmlType == 'Text') {
1827 $retValue = (float)$value;
1831 if ($htmlType == 'Text') {
1832 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1837 if (in_array($htmlType, array('Text', 'TextArea'))) {
1841 // note that if its not text / textarea, the code falls thru and executes
1842 // the below case also
1843 case 'StateProvince':
1848 //added check for Multi-Select in the below if-statement
1849 $customData[] = $value;
1851 //form custom data for multiple-valued custom data
1852 switch ($htmlType) {
1853 case 'Multi-Select Country':
1854 case 'Select Country':
1855 $customData = $value;
1856 if (!is_array($value)) {
1857 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1860 SELECT id as value, name as label
1861 FROM civicrm_country";
1862 $coDAO = CRM_Core_DAO
::executeQuery($query);
1865 case 'Select State/Province':
1866 case 'Multi-Select State/Province':
1867 $customData = $value;
1868 if (!is_array($value)) {
1869 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1873 SELECT id as value, name as label
1874 FROM civicrm_state_province";
1875 $coDAO = CRM_Core_DAO
::executeQuery($query);
1879 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1880 if ($option_group_id) {
1881 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
1886 case 'AdvMulti-Select':
1887 case 'Multi-Select':
1888 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1890 if ($option_group_id) {
1891 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
1895 if (is_object($coDAO)) {
1896 while ($coDAO->fetch()) {
1897 $options[$coDAO->value
] = $coDAO->label
;
1901 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
1904 foreach ($options as $optionValue => $optionLabel) {
1905 if ($dataType == 'Money') {
1906 foreach ($customData as $k => $v) {
1907 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
1911 //to show only values that are checked
1912 if (in_array((string) $optionValue, $customData)) {
1913 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
1914 if (!$optionPerLine ||
$dncOptionPerLine) {
1918 $retValue .= $checked . $optionLabel;
1921 $retValue[] = $checked . $optionLabel;
1928 //special case for option per line formatting
1929 if ($optionPerLine > 1 && is_array($retValue)) {
1932 $displayValues = array();
1933 $displayString = '';
1934 foreach ($retValue as $val) {
1935 if ($displayString) {
1936 $displayString .= ", ";
1939 $displayString .= $val;
1943 if (($rowCounter == $optionPerLine) ||
($fieldCounter == count($retValue))) {
1944 $displayValues[] = $displayString;
1945 $displayString = '';
1949 $retValue = $displayValues;
1952 $retValue = isset($retValue) ?
$retValue : NULL;
1957 * Get the custom group titles by custom field ids.
1959 * @param array $fieldIds - array of custom field ids.
1961 * @return array $groupLabels - array consisting of groups and fields labels with ids.
1964 public static function getGroupTitles($fieldIds) {
1965 if (!is_array($fieldIds) && empty($fieldIds)) {
1969 $groupLabels = array();
1970 $fIds = "(" . implode(',', $fieldIds) . ")";
1973 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
1974 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
1975 FROM civicrm_custom_group, civicrm_custom_field
1976 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
1977 AND civicrm_custom_field.id IN {$fIds}";
1979 $dao = CRM_Core_DAO
::executeQuery($query);
1980 while ($dao->fetch()) {
1981 $groupLabels[$dao->fieldID
] = array(
1982 'fieldID' => $dao->fieldID
,
1983 'fieldLabel' => $dao->fieldLabel
,
1984 'groupID' => $dao->groupID
,
1985 'groupTitle' => $dao->groupTitle
,
1989 return $groupLabels;
1992 static function dropAllTables() {
1993 $query = "SELECT table_name FROM civicrm_custom_group";
1994 $dao = CRM_Core_DAO
::executeQuery($query);
1996 while ($dao->fetch()) {
1997 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
1998 CRM_Core_DAO
::executeQuery($query);
2003 * Check whether custom group is empty or not.
2005 * @param int $gID - custom group id.
2007 * @return boolean true if empty otherwise false.
2010 static function isGroupEmpty($gID) {
2015 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2020 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2021 $value = CRM_Core_DAO
::singleValueQuery($query);
2023 if (empty($value)) {
2031 * Get the list of types for objects that a custom group extends to.
2033 * @param array $types - var which should have the list appended.
2035 * @return array of types.
2038 static function getExtendedObjectTypes(&$types = array( )) {
2039 static $flag = FALSE, $objTypes = array();
2042 $extendObjs = array();
2043 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2045 foreach ($extendObjs as $ovId => $ovValues) {
2046 if ($ovValues['description']) {
2047 // description is expected to be a callback func to subtypes
2048 list($callback, $args) = explode(';', trim($ovValues['description']));
2050 if (!empty($args)) {
2051 eval('$args = ' . $args . ';');
2057 if (!is_array($args)) {
2058 CRM_Core_Error
::fatal('Arg is not of type array');
2061 list($className) = explode('::', $callback);
2062 require_once (str_replace('_',DIRECTORY_SEPARATOR
, $className) . '.php');
2064 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2070 $types = array_merge($types, $objTypes);
2074 function hasReachedMaxLimit($customGroupId, $entityId) {
2075 //check whether the group is multiple
2076 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2077 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2078 $hasReachedMax = FALSE;
2080 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))) {
2081 if (!$maxMultiple) {
2082 $hasReachedMax = FALSE;
2084 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2085 //count the number of entries for a entity
2086 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2087 $params = array(1 => array($entityId, 'Integer'));
2088 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2090 if ($count >= $maxMultiple) {
2091 $hasReachedMax = TRUE;
2095 return $hasReachedMax;