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 // lets create the table associated with the group and save it
154 $tableName = $group->table_name
= "civicrm_value_" . strtolower($group->name
);
157 // enclose the below in a transaction
158 $transaction = new CRM_Core_Transaction();
162 // now append group id to table name, this prevent any name conflicts
164 $tableName .= "_{$group->id}";
165 $group->table_name
= $tableName;
166 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
172 // now create the table associated with this group
173 self
::createTable($group);
175 elseif ($oldTableName) {
176 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($oldTableName, CRM_Utils_Array
::value('is_multiple', $params));
179 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
180 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
184 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends'][0]));
186 $transaction->commit();
189 CRM_Utils_System
::flushCache();
192 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
195 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
202 * Takes a bunch of params that are needed to match certain criteria and
203 * retrieves the relevant objects. Typically the valid params are only
204 * contact_id. We'll tweak this function to be more full featured over a period
205 * of time. This is the inverse function of create. It also stores all the retrieved
206 * values in the default array
208 * @param array $params (reference ) an assoc array of name/value pairs
209 * @param array $defaults (reference ) an assoc array to hold the flattened values
211 * @return object CRM_Core_DAO_CustomGroup object
215 static function retrieve(&$params, &$defaults) {
216 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
220 * update the is_active flag in the db
222 * @param int $id id of the database record
223 * @param boolean $is_active value we want to set the is_active field
225 * @return Object DAO object on sucess, null otherwise
229 static function setIsActive($id, $is_active) {
231 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
234 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
237 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
241 * Determine if given entity (sub)type has any custom groups
243 * @param string $extends e.g. "Individual", "Activity"
244 * @param int $columnId e.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id
245 * @param string $columnValue e.g. "Student" or "3" or "3\05"; see extends_entity_column_value
247 public static function hasCustomGroup($extends, $columnId, $columnValue) {
248 $dao = new CRM_Core_DAO_CustomGroup();
249 $dao->extends = $extends;
250 $dao->extends_entity_column_id
= $columnId;
251 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
252 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
253 //$dao->extends_entity_column_value = $columnValue;
254 return $dao->find() ?
TRUE : FALSE;
258 * Determine if there are any CustomGroups for the given $activityTypeId.
259 * If none found, create one.
261 * @param int $activityTypeId
262 * @return bool TRUE if a group is found or created; FALSE on error
264 public static function autoCreateByActivityType($activityTypeId) {
265 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
268 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
271 'extends' => 'Activity',
272 'extends_entity_column_id' => NULL,
273 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
274 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
278 $result = civicrm_api('CustomGroup', 'create', $params);
279 return ! $result['is_error'];
283 * Get custom groups/fields for type of entity.
285 * An array containing all custom groups and their custom fields is returned.
287 * @param string $entityType - of the contact whose contact type is needed
288 * @param int $entityId - optional - id of entity if we need to populate the tree with custom values.
289 * @param int $groupId - optional group id (if we need it for a single group only)
290 * - if groupId is 0 it gets for inline groups only
291 * - if groupId is -1 we get for all groups
293 * @return array $groupTree - array consisting of all groups and fields and optionally populated with custom data values.
300 public static function &getTree($entityType,
309 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
313 $strSelect = $strFrom = $strWhere = $orderBy = '';
314 $tableData = array();
316 // using tableData to build the queryString
318 'civicrm_custom_field' =>
338 'civicrm_custom_group' =>
349 'extends_entity_column_id',
350 'extends_entity_column_value',
357 foreach ($tableData as $tableName => $tableColumn) {
358 foreach ($tableColumn as $columnName) {
359 $alias = $tableName . "_" . $columnName;
360 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
363 $strSelect = "SELECT " . implode(', ', $select);
365 // from, where, order by
367 FROM civicrm_custom_group
368 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
371 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
372 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
$entityType == 'Household') {
373 $in = "'$entityType', 'Contact'";
375 elseif (strpos($entityType, "'") !== FALSE) {
376 // this allows the calling function to send in multiple entity types
381 $in = "'$entityType'";
386 if (is_array($subType)) {
387 $subType = implode(',', $subType);
389 if (strpos($subType, ',')) {
390 $subTypeParts = explode(',', $subType);
391 $subTypeClauses = array();
392 foreach ($subTypeParts as $subTypePart) {
393 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
394 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
396 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
399 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
401 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
402 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
406 WHERE civicrm_custom_group.is_active = 1
407 AND civicrm_custom_field.is_active = 1
408 AND civicrm_custom_group.extends IN ($in)
412 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
417 WHERE civicrm_custom_group.is_active = 1
418 AND civicrm_custom_field.is_active = 1
419 AND civicrm_custom_group.extends IN ($in)
420 AND civicrm_custom_group.extends_entity_column_value IS NULL
426 // since we want a specific group id we add it to the where clause
427 $strWhere .= " AND civicrm_custom_group.id = %1";
428 $params[1] = array($groupID, 'Integer');
431 // since groupID is false we need to show all Inline groups
432 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
435 // ensure that the user has access to these custom groups
436 $strWhere .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
437 'civicrm_custom_group.'
441 ORDER BY civicrm_custom_group.weight,
442 civicrm_custom_group.title,
443 civicrm_custom_field.weight,
444 civicrm_custom_field.label
447 // final query string
448 $queryString = "$strSelect $strFrom $strWhere $orderBy";
450 // lets see if we can retrieve the groupTree from cache
451 $cacheString = $queryString;
452 if ( $groupID > 0 ) {
453 $cacheString .= "_{$groupID}";
455 $cacheString .= "_Inline";
458 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
460 $cache = CRM_Utils_Cache
::singleton();
463 $groupTree = $cache->get($cacheKey);
466 if (empty($groupTree)) {
467 $groupTree = array();
468 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
470 $customValueTables = array();
473 while ($crmDAO->fetch()) {
475 $groupID = $crmDAO->civicrm_custom_group_id
;
476 $fieldId = $crmDAO->civicrm_custom_field_id
;
478 // create an array for groups if it does not exist
479 if (!array_key_exists($groupID, $groupTree)) {
480 $groupTree[$groupID] = array();
481 $groupTree[$groupID]['id'] = $groupID;
483 // populate the group information
484 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
485 $fullFieldName = "civicrm_custom_group_$fieldName";
486 if ($fieldName == 'id' ||
487 is_null($crmDAO->$fullFieldName)
492 if ($fieldName == 'extends_entity_column_value' && $subType) {
493 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
495 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
497 $groupTree[$groupID]['fields'] = array();
499 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
502 // add the fields now (note - the query row will always contain a field)
503 // we only reset this once, since multiple values come is as multiple rows
504 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
505 $groupTree[$groupID]['fields'][$fieldId] = array();
508 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
509 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
510 // populate information for a custom field
511 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
512 $fullFieldName = "civicrm_custom_field_$fieldName";
513 if ($fieldName == 'id' ||
514 is_null($crmDAO->$fullFieldName)
518 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
522 if (!empty($customValueTables)) {
523 $groupTree['info'] = array('tables' => $customValueTables);
526 $cache->set($cacheKey, $groupTree);
529 // now that we have all the groups and fields, lets get the values
530 // since we need to know the table and field names
532 // add info to groupTree
533 if (isset($groupTree['info']) && !empty($groupTree['info'])) {
534 $select = $from = $where = array();
535 foreach ($groupTree['info']['tables'] as $table => $fields) {
537 $select[] = "{$table}.id as {$table}_id";
538 $select[] = "{$table}.entity_id as {$table}_entity_id";
540 foreach ($fields as $column => $dontCare) {
541 $select[] = "{$table}.{$column} as {$table}_{$column}";
545 $where[] = "{$table}.entity_id = $entityID";
549 $groupTree['info']['select'] = $select;
550 $groupTree['info']['from'] = $from;
551 $groupTree['info']['where'] = NULL;
554 $groupTree['info']['where'] = $where;
555 $select = implode(', ', $select);
557 // this is a hack to find a table that has some values for this
558 // entityID to make the below LEFT JOIN work (CRM-2518)
560 foreach ($from as $table) {
564 WHERE entity_id = $entityID
566 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
568 $firstTable = $table;
574 $fromSQL = $firstTable;
575 foreach ($from as $table) {
576 if ($table != $firstTable) {
577 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
584 WHERE {$firstTable}.entity_id = $entityID
587 $dao = CRM_Core_DAO
::executeQuery($query);
589 while ($dao->fetch()) {
590 foreach ($groupTree as $groupID => $group) {
591 if ($groupID === 'info') {
594 $table = $groupTree[$groupID]['table_name'];
595 foreach ($group['fields'] as $fieldID => $dontCare) {
596 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
597 $idName = "{$table}_id";
598 $fieldName = "{$table}_{$column}";
600 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
601 if ($dataType == 'File') {
602 if (isset($dao->$fieldName)) {
603 $config = CRM_Core_Config
::singleton();
604 $fileDAO = new CRM_Core_DAO_File();
605 $fileDAO->id
= $dao->$fieldName;
607 if ($fileDAO->find(TRUE)) {
608 $entityIDName = "{$table}_entity_id";
609 $customValue['id'] = $dao->$idName;
610 $customValue['data'] = $fileDAO->uri
;
611 $customValue['fid'] = $fileDAO->id
;
612 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
613 $customValue['displayURL'] = NULL;
614 $deleteExtra = ts('Are you sure you want to delete attached file.');
616 CRM_Core_Action
::DELETE
=>
618 'name' => ts('Delete Attached File'),
619 'url' => 'civicrm/file',
620 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
622 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
625 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
626 CRM_Core_Action
::DELETE
,
628 'id' => $fileDAO->id
,
629 'eid' => $dao->$entityIDName,
633 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
634 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
635 if ($fileDAO->mime_type
== "image/jpeg" ||
636 $fileDAO->mime_type
== "image/pjpeg" ||
637 $fileDAO->mime_type
== "image/gif" ||
638 $fileDAO->mime_type
== "image/x-png" ||
639 $fileDAO->mime_type
== "image/png"
641 $customValue['displayURL'] = $customValue['fileURL'];
642 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
647 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) . $fileDAO->uri
;
648 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId,
651 list($imageWidth, $imageHeight) = getimagesize($path);
652 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
653 $customValue['imageThumbWidth'] = $imageThumbWidth;
654 $customValue['imageThumbHeight'] = $imageThumbHeight;
659 $customValue = array(
660 'id' => $dao->$idName,
666 $customValue = array(
667 'id' => $dao->$idName,
668 'data' => $dao->$fieldName,
671 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
672 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
674 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
675 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
678 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
691 * Get the group title.
693 * @param int $id id of group.
695 * @return string title
701 public static function getTitle($id) {
702 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
706 * Get custom group details for a group.
708 * An array containing custom group details (including their custom field) is returned.
710 * @param int $groupId - group id whose details are needed
711 * @param boolean $searchable - is this field searchable
712 * @param array $extends - which table does it extend if any
714 * @return array $groupTree - array consisting of all group and field details
721 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL) {
723 $groupTree = array();
724 $select = $from = $where = $orderBy = '';
726 $tableData = array();
728 // using tableData to build the queryString
730 'civicrm_custom_field' =>
754 'civicrm_custom_group' =>
762 'collapse_adv_display',
764 'extends_entity_column_value',
772 foreach ($tableData as $tableName => $tableColumn) {
773 foreach ($tableColumn as $columnName) {
774 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
777 $select = 'SELECT ' . implode(', ', $s);
779 // from, where, order by
780 $from = " FROM civicrm_custom_field, civicrm_custom_group";
781 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
782 AND civicrm_custom_group.is_active = 1
783 AND civicrm_custom_field.is_active = 1 ";
785 $params[1] = array($groupId, 'Integer');
786 $where .= " AND civicrm_custom_group.id = %1";
790 $where .= " AND civicrm_custom_field.is_searchable = 1";
795 foreach ($extends as $e) {
796 $clause[] = "civicrm_custom_group.extends = '$e'";
798 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
800 //include case activities customdata if case is enabled
801 if (in_array('Activity', $extends)) {
802 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
803 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
804 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
808 // ensure that the user has access to these custom groups
809 $where .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
810 'civicrm_custom_group.'
813 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
815 // final query string
816 $queryString = $select . $from . $where . $orderBy;
819 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
822 while ($crmDAO->fetch()) {
823 $groupId = $crmDAO->civicrm_custom_group_id
;
824 $fieldId = $crmDAO->civicrm_custom_field_id
;
826 // create an array for groups if it does not exist
827 if (!array_key_exists($groupId, $groupTree)) {
828 $groupTree[$groupId] = array();
829 $groupTree[$groupId]['id'] = $groupId;
831 foreach ($tableData['civicrm_custom_group'] as $v) {
832 $fullField = "civicrm_custom_group_" . $v;
834 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
838 $groupTree[$groupId][$v] = $crmDAO->$fullField;
841 $groupTree[$groupId]['fields'] = array();
844 // add the fields now (note - the query row will always contain a field)
845 $groupTree[$groupId]['fields'][$fieldId] = array();
846 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
848 foreach ($tableData['civicrm_custom_field'] as $v) {
849 $fullField = "civicrm_custom_field_" . $v;
850 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
853 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
860 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
862 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
864 // get only 'Tab' groups
865 $customGroupDAO->whereAdd("style = 'Tab'");
866 $customGroupDAO->whereAdd("is_active = 1");
868 // add whereAdd for entity type
869 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
873 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
874 $customGroupDAO->whereAdd($permissionClause);
877 $customGroupDAO->orderBy('weight');
878 $customGroupDAO->find();
880 // process each group with menu tab
881 while ($customGroupDAO->fetch()) {
883 $group['id'] = $customGroupDAO->id
;
884 $group['path'] = $path;
885 $group['title'] = "$customGroupDAO->title";
886 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
887 $group['extra'] = array('gid' => $customGroupDAO->id
);
888 $group['table_name'] = $customGroupDAO->table_name
;
896 * Get the table name for the entity type
897 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
898 * tableName is 'civicrm_contact'
900 * @param string $entityType what entity are we extending here ?
902 * @return string $tableName
908 private static function _getTableName($entityType) {
910 switch ($entityType) {
915 $tableName = 'civicrm_contact';
919 $tableName = 'civicrm_contribution';
923 $tableName = 'civicrm_group';
925 // DRAFTING: Verify if we cannot make it pluggable
928 $tableName = 'civicrm_activity';
932 $tableName = 'civicrm_relationship';
936 $tableName = 'civicrm_membership';
940 $tableName = 'civicrm_participant';
944 $tableName = 'civicrm_event';
948 $tableName = 'civicrm_grant';
950 // need to add cases for Location, Address
957 * Get a list of custom groups which extend a given entity type.
958 * If there are custom-groups which only apply to certain subtypes,
959 * those WILL be included.
961 * @param $entityType string
962 * @return CRM_Core_DAO_CustomGroup
964 static function getAllCustomGroupsByBaseEntity($entityType) {
965 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
966 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
967 return $customGroupDAO;
971 * Add the whereAdd clause for the DAO depending on the type of entity
972 * the custom group is extending.
974 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
975 * @param string $entityType - what entity are we extending here ?
983 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
984 $addSubtypeClause = FALSE;
986 switch ($entityType) {
988 // if contact, get all related to contact
989 $extendList = "'Contact','Individual','Household','Organization'";
990 $customGroupDAO->whereAdd("extends IN ( $extendList )");
992 $addSubtypeClause = TRUE;
999 // is I/H/O then get I/H/O and contact
1000 $extendList = "'Contact','$entityType'";
1001 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1002 if (!$allSubtypes) {
1003 $addSubtypeClause = TRUE;
1010 case 'Contribution':
1013 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1017 if ($addSubtypeClause) {
1018 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1020 if (!empty($csType)) {
1021 $subtypeClause = array();
1022 foreach ($csType as $subtype) {
1023 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
1024 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1026 $subtypeClause[] = "extends_entity_column_value IS NULL";
1027 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) . " )");
1030 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1036 * Delete the Custom Group.
1038 * @param $group object the DAO custom group object
1039 * @param $force boolean whether to force the deletion, even if there are custom fields
1041 * @return boolean false if field exists for this group, true if group gets deleted.
1047 public static function deleteGroup($group, $force = FALSE) {
1049 //check wheter this contain any custom fields
1050 $customField = new CRM_Core_DAO_CustomField();
1051 $customField->custom_group_id
= $group->id
;
1052 $customField->find();
1054 // return early if there are custom fields and we're not
1055 // forcing the delete, otherwise delete the fields one by one
1056 while ($customField->fetch()) {
1060 CRM_Core_BAO_CustomField
::deleteField($customField);
1063 // drop the table associated with this custom group
1064 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1066 //delete custom group
1069 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1074 static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1075 foreach ($groupTree as $id => $group) {
1076 if (!isset($group['fields'])) {
1079 $groupId = CRM_Utils_Array
::value('id', $group);
1080 foreach ($group['fields'] as $field) {
1081 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1082 $value = $field['element_value'];
1084 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1085 ($action != CRM_Core_Action
::UPDATE ||
1087 !array_key_exists('element_value', $field)
1090 $value = $viewMode ?
NULL : $field['default_value'];
1096 $fieldId = $field['id'];
1097 $elementName = $field['element_name'];
1098 switch ($field['html_type']) {
1099 case 'Multi-Select':
1100 case 'AdvMulti-Select':
1102 $defaults[$elementName] = array();
1103 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1105 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1106 if (isset($value)) {
1107 foreach ($customOption as $customValue => $customLabel) {
1108 if (in_array($customValue, $checkedData)) {
1109 if ($field['html_type'] == 'CheckBox') {
1110 $defaults[$elementName][$customValue] = 1;
1113 $defaults[$elementName][$customValue] = $customValue;
1117 $defaults[$elementName][$customValue] = 0;
1123 if (isset($field['customValue']['data'])) {
1124 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1125 foreach ($customOption as $val) {
1126 if (in_array($val['value'], $checkedData)) {
1127 if ($field['html_type'] == 'CheckBox') {
1128 $defaults[$elementName][$val['value']] = 1;
1131 $defaults[$elementName][$val['value']] = $val['value'];
1135 $defaults[$elementName][$val['value']] = 0;
1140 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1141 foreach ($customOption as $val) {
1142 if (in_array($val['value'], $checkedValue)) {
1143 if ($field['html_type'] == 'CheckBox') {
1144 $defaults[$elementName][$val['value']] = 1;
1147 $defaults[$elementName][$val['value']] = $val['value'];
1156 if (isset($value)) {
1157 if (empty($field['time_format'])) {
1158 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1159 $field['date_format']
1163 $timeElement = $elementName . '_time';
1164 if (substr($elementName, -1) == ']') {
1165 $timeElement = substr($elementName, 0, -1) . '_time]';
1167 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1172 case 'Multi-Select Country':
1173 case 'Multi-Select State/Province':
1174 if (isset($value)) {
1175 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1176 foreach ($checkedValue as $val) {
1178 $defaults[$elementName][$val] = $val;
1184 case 'Select Country':
1186 $defaults[$elementName] = $value;
1189 $config = CRM_Core_Config
::singleton();
1190 $defaults[$elementName] = $config->defaultContactCountry
;
1194 case 'Autocomplete-Select':
1195 $hiddenEleName = $elementName . '_id';
1196 if (substr($elementName, -1) == ']') {
1197 $hiddenEleName = substr($elementName, 0, -1) . '_id]';
1199 if ($field['data_type'] == "ContactReference") {
1200 if (is_numeric($value)) {
1201 $defaults[$hiddenEleName] = $value;
1202 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1206 $label = CRM_Core_BAO_CustomOption
::getOptionLabel($field['id'], $value);
1207 $defaults[$hiddenEleName] = $value;
1208 $defaults[$elementName] = $label;
1213 if ($field['data_type'] == "Float") {
1214 $defaults[$elementName] = (float)$value;
1216 elseif ($field['data_type'] == 'Money' &&
1217 $field['html_type'] == 'Text'
1219 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1222 $defaults[$elementName] = $value;
1229 static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1230 // Get the Custom form values and groupTree
1231 // first reset all checkbox and radio data
1232 foreach ($groupTree as $groupID => $group) {
1233 if ($groupID === 'info') {
1236 foreach ($group['fields'] as $field) {
1237 $fieldId = $field['id'];
1239 //added Multi-Select option in the below if-statement
1240 if ($field['html_type'] == 'CheckBox' ||
$field['html_type'] == 'Radio' ||
1241 $field['html_type'] == 'AdvMulti-Select' ||
$field['html_type'] == 'Multi-Select'
1243 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1247 foreach ($params as $key => $val) {
1248 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1249 $match[1] == $field['id']
1256 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1257 // field exists in db so populate value from "form".
1258 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1261 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1263 //added for CheckBox
1267 $customValue = array_keys($v);
1268 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1271 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1275 //added for Advanced Multi-Select
1277 case 'AdvMulti-Select':
1278 //added for Multi-Select
1279 case 'Multi-Select':
1281 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1284 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1289 $date = CRM_Utils_Date
::processDate($v);
1290 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1298 //store the file in d/b
1299 $entityId = explode('=', $groupTree['info']['where'][0]);
1300 $fileParams = array('upload_date' => date('Ymdhis'));
1302 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1303 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1306 $fileParams['uri'] = $v['name'];
1307 $fileParams['mime_type'] = $v['type'];
1308 CRM_Core_BAO_File
::filePostProcess($v['name'],
1309 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1310 $groupTree[$groupID]['table_name'],
1315 'custom_' . $fieldId,
1319 $defaults = array();
1320 $paramsFile = array(
1321 'entity_table' => $groupTree[$groupID]['table_name'],
1322 'entity_id' => $entityId[1],
1325 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1330 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1334 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1342 * generic function to build all the form elements for a specific group tree
1344 * @param CRM_Core_Form $form the form object
1345 * @param array $groupTree the group tree object
1346 * @param string $showName
1347 * @param string $hideName
1353 static function buildQuickForm(&$form,
1355 $inactiveNeeded = FALSE,
1360 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1364 // this is fix for date field
1365 $form->assign('currentYear', date('Y'));
1367 foreach ($groupTree as $id => $group) {
1369 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1371 $groupId = CRM_Utils_Array
::value('id', $group);
1372 foreach ($group['fields'] as $field) {
1373 $required = CRM_Utils_Array
::value('is_required', $field);
1375 if ($field['data_type'] == 'File') {
1376 if (isset($field['customValue']['data'])) {
1381 $fieldId = $field['id'];
1382 $elementName = $field['element_name'];
1383 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1389 * Function to extract the get params from the url, validate
1390 * and store it in session
1392 * @param CRM_Core_Form $form the form object
1393 * @param string $type the type of custom group we are using
1399 static function extractGetParams(&$form, $type) {
1400 // if not GET params return
1405 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1406 $customValue = array();
1407 $htmlType = array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Select', 'Radio');
1409 foreach ($groupTree as $group) {
1410 if (!isset($group['fields'])) {
1413 foreach ($group['fields'] as $key => $field) {
1414 $fieldName = 'custom_' . $key;
1415 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1419 if (!in_array($field['html_type'], $htmlType) ||
1420 $field['data_type'] == 'Boolean'
1422 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1424 if ($field['html_type'] == 'CheckBox' ||
1425 $field['html_type'] == 'AdvMulti-Select' ||
1426 $field['html_type'] == 'Multi-Select'
1428 $value = str_replace("|", ",", $value);
1429 $mulValues = explode(',', $value);
1430 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1432 foreach ($mulValues as $v1) {
1433 foreach ($customOption as $coID => $coValue) {
1434 if (strtolower(trim($coValue['label'])) == strtolower(trim($v1))) {
1435 $val[$coValue['value']] = 1;
1447 elseif ($field['html_type'] == 'Select' ||
1448 ($field['html_type'] == 'Radio' &&
1449 $field['data_type'] != 'Boolean'
1452 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1453 foreach ($customOption as $customID => $coValue) {
1454 if (strtolower(trim($coValue['label'])) == strtolower(trim($value))) {
1455 $value = $coValue['value'];
1460 elseif ($field['data_type'] == 'Date') {
1461 if (!empty($value)) {
1463 if (CRM_Utils_Array
::value('time_format', $field)) {
1464 $time = CRM_Utils_Request
::retrieve($fieldName . '_time', 'String', $form, FALSE, NULL, 'GET');
1466 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value . ' ' . $time);
1467 if (CRM_Utils_Array
::value('time_format', $field)) {
1468 $customValue[$fieldName . '_time'] = $time;
1475 $customValue[$fieldName] = $value;
1481 return $customValue;
1485 * Function to check the type of custom field type (eg: Used for Individual, Contribution, etc)
1486 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1488 * @param int $customFieldId custom field id
1489 * @param array $removeCustomFieldTypes remove custom fields of a type eg: array("Individual") ;
1492 * @return boolean false if it matches else true
1496 static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1497 $query = "SELECT cg.extends as extends
1498 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1499 WHERE cg.id = cf.custom_group_id
1500 AND cf.id =" . CRM_Utils_Type
::escape($customFieldId, 'Integer');
1502 $extends = CRM_Core_DAO
::singleValueQuery($query);
1504 if (in_array($extends, $removeCustomFieldTypes)) {
1510 static function mapTableName($table) {
1515 case 'Organization':
1516 return 'civicrm_contact';
1519 return 'civicrm_activity';
1522 return 'civicrm_group';
1524 case 'Contribution':
1525 return 'civicrm_contribution';
1527 case 'Relationship':
1528 return 'civicrm_relationship';
1531 return 'civicrm_event';
1534 return 'civicrm_membership';
1537 case 'ParticipantRole':
1538 case 'ParticipantEventName':
1539 case 'ParticipantEventType':
1540 return 'civicrm_participant';
1543 return 'civicrm_grant';
1546 return 'civicrm_pledge';
1549 return 'civicrm_address';
1552 return 'civicrm_campaign';
1556 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1557 $qParams = array(1 => array($table, 'String'));
1558 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1561 return 'civicrm_contact';
1564 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1565 if (array_key_exists($table, $extendObjs)) {
1566 return $extendObjs[$table];
1568 CRM_Core_Error
::fatal();
1573 static function createTable($group) {
1575 'name' => $group->table_name
,
1576 'is_multiple' => $group->is_multiple ?
1 : 0,
1577 'extends_name' => self
::mapTableName($group->extends),
1580 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1582 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1586 * Function returns formatted groupTree, sothat form can be easily build in template
1588 * @param array $groupTree associated array
1589 * @param int $groupCount group count by default 1, but can varry for multiple value custom data
1590 * @param object form object
1592 * @return array $formattedGroupTree
1594 static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1595 $formattedGroupTree = array();
1596 $uploadNames = array();
1598 foreach ($groupTree as $key => $value) {
1599 if ($key === 'info') {
1603 // add group information
1604 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1605 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1606 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1607 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1608 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1609 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1611 // this params needed of bulding multiple values
1612 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1613 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1614 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1615 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1616 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1617 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1619 // add field information
1620 foreach ($value['fields'] as $k => $properties) {
1621 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1622 if (isset($properties['customValue']) && !CRM_Utils_system
::isNull($properties['customValue'])) {
1623 if (isset($properties['customValue'][$groupCount])) {
1624 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1625 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1626 if ($properties['data_type'] == 'File') {
1627 $properties['element_value'] = $properties['customValue'][$groupCount];
1628 $uploadNames[] = $properties['element_name'];
1631 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1635 unset($properties['customValue']);
1636 $formattedGroupTree[$key]['fields'][$k] = $properties;
1641 // hack for field type File
1642 $formUploadNames = $form->get('uploadNames');
1643 if (is_array($formUploadNames)) {
1644 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1647 $form->set('uploadNames', $uploadNames);
1650 return $formattedGroupTree;
1654 * Build custom data view
1655 * @param object $form page object
1656 * @param array $groupTree associated array
1657 * @param boolean $returnCount true if customValue count needs to be returned
1659 static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL) {
1660 foreach ($groupTree as $key => $group) {
1661 if ($key === 'info') {
1665 foreach ($group['fields'] as $k => $properties) {
1666 $groupID = $group['id'];
1667 if (!empty($properties['customValue'])) {
1668 foreach ($properties['customValue'] as $values) {
1669 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1670 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1671 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1672 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1673 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1674 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1675 $details[$groupID][$values['id']]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties),
1676 'field_type' => CRM_Utils_Array
::value('html_type',
1679 'field_data_type' => CRM_Utils_Array
::value('data_type',
1682 'field_value' => self
::formatCustomValues($values,
1685 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1689 // also return contact reference contact id if user has view all or edit all contacts perm
1690 if ((CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts'))
1691 && $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] == 'ContactReference'
1693 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1698 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1699 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1700 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1701 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1702 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1703 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1704 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1710 //return a single value count if group id is passed to function
1711 //else return a groupId and count mapped array
1713 return count($details[$gID]);
1716 foreach( $details as $key => $value ) {
1717 $countValue[$key] = count($details[$key]);
1723 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1729 * Format custom value according to data, view mode
1731 * @param array $values associated array of custom values
1732 * @param array $field associated array
1733 * @param boolean $dncOptionPerLine true if optionPerLine should not be consider
1736 static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1737 $value = $values['data'];
1739 //changed isset CRM-4601
1740 if (CRM_Utils_System
::isNull($value)) {
1744 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1745 $dataType = CRM_Utils_Array
::value('data_type', $field);
1746 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1747 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1748 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1751 $freezeStringChecked = "";
1753 switch ($dataType) {
1755 $customTimeFormat = '';
1756 $customFormat = NULL;
1758 switch ($timeFormat) {
1760 $customTimeFormat = '%l:%M %P';
1764 $customTimeFormat = '%H:%M';
1768 // if time is not selected remove time from value
1769 $value = substr($value, 0, 10);
1772 $supportableFormats = array(
1773 'mm/dd' => "%B %E%f $customTimeFormat",
1774 'dd-mm' => "%E%f %B $customTimeFormat",
1775 'yy' => "%Y $customTimeFormat",
1776 'M yy' => "%b %Y $customTimeFormat",
1777 'yy-mm' => "%Y-%m $customTimeFormat"
1780 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
1781 if (array_key_exists($format, $supportableFormats)) {
1782 $customFormat = $supportableFormats["$format"];
1786 $retValue = CRM_Utils_Date
::customFormat($value, $customFormat);
1790 if ($value == '1') {
1791 $retValue = $freezeStringChecked . ts('Yes') . "\n";
1794 $retValue = $freezeStringChecked . ts('No') . "\n";
1800 $retValue = CRM_Utils_System
::formatWikiURL($value);
1805 $retValue = $values;
1808 case 'ContactReference':
1809 if (CRM_Utils_Array
::value('data', $values)) {
1810 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
1819 if ($htmlType == 'Text') {
1820 $retValue = (float)$value;
1824 if ($htmlType == 'Text') {
1825 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1830 if (in_array($htmlType, array('Text', 'TextArea'))) {
1834 // note that if its not text / textarea, the code falls thru and executes
1835 // the below case also
1836 case 'StateProvince':
1841 //added check for Multi-Select in the below if-statement
1842 $customData[] = $value;
1844 //form custom data for multiple-valued custom data
1845 switch ($htmlType) {
1846 case 'Multi-Select Country':
1847 case 'Select Country':
1848 $customData = $value;
1849 if (!is_array($value)) {
1850 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1853 SELECT id as value, name as label
1854 FROM civicrm_country";
1855 $coDAO = CRM_Core_DAO
::executeQuery($query);
1858 case 'Select State/Province':
1859 case 'Multi-Select State/Province':
1860 $customData = $value;
1861 if (!is_array($value)) {
1862 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1866 SELECT id as value, name as label
1867 FROM civicrm_state_province";
1868 $coDAO = CRM_Core_DAO
::executeQuery($query);
1872 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1873 if ($option_group_id) {
1874 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
1879 case 'AdvMulti-Select':
1880 case 'Multi-Select':
1881 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1883 if ($option_group_id) {
1884 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
1888 if (is_object($coDAO)) {
1889 while ($coDAO->fetch()) {
1890 if ($dataType == 'Country') {
1891 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
1892 // and already extracted to .pot files.
1893 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
1895 elseif ($dataType == 'StateProvince') {
1896 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
1899 $options[$coDAO->value
] = $coDAO->label
;
1904 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
1907 foreach ($options as $optionValue => $optionLabel) {
1908 if ($dataType == 'Money') {
1909 foreach ($customData as $k => $v) {
1910 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
1914 //to show only values that are checked
1915 if (in_array((string) $optionValue, $customData)) {
1916 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
1917 if (!$optionPerLine ||
$dncOptionPerLine) {
1921 $retValue .= $checked . $optionLabel;
1924 $retValue[] = $checked . $optionLabel;
1931 //special case for option per line formatting
1932 if ($optionPerLine > 1 && is_array($retValue)) {
1935 $displayValues = array();
1936 $displayString = '';
1937 foreach ($retValue as $val) {
1938 if ($displayString) {
1939 $displayString .= ", ";
1942 $displayString .= $val;
1946 if (($rowCounter == $optionPerLine) ||
($fieldCounter == count($retValue))) {
1947 $displayValues[] = $displayString;
1948 $displayString = '';
1952 $retValue = $displayValues;
1955 $retValue = isset($retValue) ?
$retValue : NULL;
1960 * Get the custom group titles by custom field ids.
1962 * @param array $fieldIds - array of custom field ids.
1964 * @return array $groupLabels - array consisting of groups and fields labels with ids.
1967 public static function getGroupTitles($fieldIds) {
1968 if (!is_array($fieldIds) && empty($fieldIds)) {
1972 $groupLabels = array();
1973 $fIds = "(" . implode(',', $fieldIds) . ")";
1976 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
1977 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
1978 FROM civicrm_custom_group, civicrm_custom_field
1979 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
1980 AND civicrm_custom_field.id IN {$fIds}";
1982 $dao = CRM_Core_DAO
::executeQuery($query);
1983 while ($dao->fetch()) {
1984 $groupLabels[$dao->fieldID
] = array(
1985 'fieldID' => $dao->fieldID
,
1986 'fieldLabel' => $dao->fieldLabel
,
1987 'groupID' => $dao->groupID
,
1988 'groupTitle' => $dao->groupTitle
,
1992 return $groupLabels;
1995 static function dropAllTables() {
1996 $query = "SELECT table_name FROM civicrm_custom_group";
1997 $dao = CRM_Core_DAO
::executeQuery($query);
1999 while ($dao->fetch()) {
2000 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2001 CRM_Core_DAO
::executeQuery($query);
2006 * Check whether custom group is empty or not.
2008 * @param int $gID - custom group id.
2010 * @return boolean true if empty otherwise false.
2013 static function isGroupEmpty($gID) {
2018 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2023 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2024 $value = CRM_Core_DAO
::singleValueQuery($query);
2026 if (empty($value)) {
2034 * Get the list of types for objects that a custom group extends to.
2036 * @param array $types - var which should have the list appended.
2038 * @return array of types.
2041 static function getExtendedObjectTypes(&$types = array( )) {
2042 static $flag = FALSE, $objTypes = array();
2045 $extendObjs = array();
2046 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2048 foreach ($extendObjs as $ovId => $ovValues) {
2049 if ($ovValues['description']) {
2050 // description is expected to be a callback func to subtypes
2051 list($callback, $args) = explode(';', trim($ovValues['description']));
2053 if (!empty($args)) {
2054 eval('$args = ' . $args . ';');
2060 if (!is_array($args)) {
2061 CRM_Core_Error
::fatal('Arg is not of type array');
2064 list($className) = explode('::', $callback);
2065 require_once (str_replace('_',DIRECTORY_SEPARATOR
, $className) . '.php');
2067 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2073 $types = array_merge($types, $objTypes);
2077 static function hasReachedMaxLimit($customGroupId, $entityId) {
2078 //check whether the group is multiple
2079 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2080 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2081 $hasReachedMax = FALSE;
2083 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))) {
2084 if (!$maxMultiple) {
2085 $hasReachedMax = FALSE;
2087 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2088 //count the number of entries for a entity
2089 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2090 $params = array(1 => array($entityId, 'Integer'));
2091 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2093 if ($count >= $maxMultiple) {
2094 $hasReachedMax = TRUE;
2098 return $hasReachedMax;