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['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
634 if ($fileDAO->mime_type
== "image/jpeg" ||
635 $fileDAO->mime_type
== "image/pjpeg" ||
636 $fileDAO->mime_type
== "image/gif" ||
637 $fileDAO->mime_type
== "image/x-png" ||
638 $fileDAO->mime_type
== "image/png"
640 $customValue['displayURL'] = $customValue['fileURL'];
641 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
646 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) . $fileDAO->uri
;
647 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId,
650 list($imageWidth, $imageHeight) = getimagesize($path);
651 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
652 $customValue['imageThumbWidth'] = $imageThumbWidth;
653 $customValue['imageThumbHeight'] = $imageThumbHeight;
658 $customValue = array(
659 'id' => $dao->$idName,
665 $customValue = array(
666 'id' => $dao->$idName,
667 'data' => $dao->$fieldName,
670 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
671 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
673 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
674 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
677 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
690 * Get the group title.
692 * @param int $id id of group.
694 * @return string title
700 public static function getTitle($id) {
701 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
705 * Get custom group details for a group.
707 * An array containing custom group details (including their custom field) is returned.
709 * @param int $groupId - group id whose details are needed
710 * @param boolean $searchable - is this field searchable
711 * @param array $extends - which table does it extend if any
713 * @return array $groupTree - array consisting of all group and field details
720 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL) {
722 $groupTree = array();
723 $select = $from = $where = $orderBy = '';
725 $tableData = array();
727 // using tableData to build the queryString
729 'civicrm_custom_field' =>
753 'civicrm_custom_group' =>
761 'collapse_adv_display',
763 'extends_entity_column_value',
771 foreach ($tableData as $tableName => $tableColumn) {
772 foreach ($tableColumn as $columnName) {
773 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
776 $select = 'SELECT ' . implode(', ', $s);
778 // from, where, order by
779 $from = " FROM civicrm_custom_field, civicrm_custom_group";
780 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
781 AND civicrm_custom_group.is_active = 1
782 AND civicrm_custom_field.is_active = 1 ";
784 $params[1] = array($groupId, 'Integer');
785 $where .= " AND civicrm_custom_group.id = %1";
789 $where .= " AND civicrm_custom_field.is_searchable = 1";
794 foreach ($extends as $e) {
795 $clause[] = "civicrm_custom_group.extends = '$e'";
797 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
799 //include case activities customdata if case is enabled
800 if (in_array('Activity', $extends)) {
801 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
802 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
803 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
807 // ensure that the user has access to these custom groups
808 $where .= " AND " . CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
809 'civicrm_custom_group.'
812 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
814 // final query string
815 $queryString = $select . $from . $where . $orderBy;
818 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
821 while ($crmDAO->fetch()) {
822 $groupId = $crmDAO->civicrm_custom_group_id
;
823 $fieldId = $crmDAO->civicrm_custom_field_id
;
825 // create an array for groups if it does not exist
826 if (!array_key_exists($groupId, $groupTree)) {
827 $groupTree[$groupId] = array();
828 $groupTree[$groupId]['id'] = $groupId;
830 foreach ($tableData['civicrm_custom_group'] as $v) {
831 $fullField = "civicrm_custom_group_" . $v;
833 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
837 $groupTree[$groupId][$v] = $crmDAO->$fullField;
840 $groupTree[$groupId]['fields'] = array();
843 // add the fields now (note - the query row will always contain a field)
844 $groupTree[$groupId]['fields'][$fieldId] = array();
845 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
847 foreach ($tableData['civicrm_custom_field'] as $v) {
848 $fullField = "civicrm_custom_field_" . $v;
849 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
852 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
859 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
861 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
863 // get only 'Tab' groups
864 $customGroupDAO->whereAdd("style = 'Tab'");
865 $customGroupDAO->whereAdd("is_active = 1");
867 // add whereAdd for entity type
868 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
872 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
873 $customGroupDAO->whereAdd($permissionClause);
876 $customGroupDAO->orderBy('weight');
877 $customGroupDAO->find();
879 // process each group with menu tab
880 while ($customGroupDAO->fetch()) {
882 $group['id'] = $customGroupDAO->id
;
883 $group['path'] = $path;
884 $group['title'] = "$customGroupDAO->title";
885 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
886 $group['extra'] = array('gid' => $customGroupDAO->id
);
887 $group['table_name'] = $customGroupDAO->table_name
;
895 * Get the table name for the entity type
896 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
897 * tableName is 'civicrm_contact'
899 * @param string $entityType what entity are we extending here ?
901 * @return string $tableName
907 private static function _getTableName($entityType) {
909 switch ($entityType) {
914 $tableName = 'civicrm_contact';
918 $tableName = 'civicrm_contribution';
922 $tableName = 'civicrm_group';
924 // DRAFTING: Verify if we cannot make it pluggable
927 $tableName = 'civicrm_activity';
931 $tableName = 'civicrm_relationship';
935 $tableName = 'civicrm_membership';
939 $tableName = 'civicrm_participant';
943 $tableName = 'civicrm_event';
947 $tableName = 'civicrm_grant';
949 // need to add cases for Location, Address
956 * Get a list of custom groups which extend a given entity type.
957 * If there are custom-groups which only apply to certain subtypes,
958 * those WILL be included.
960 * @param $entityType string
961 * @return CRM_Core_DAO_CustomGroup
963 static function getAllCustomGroupsByBaseEntity($entityType) {
964 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
965 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
966 return $customGroupDAO;
970 * Add the whereAdd clause for the DAO depending on the type of entity
971 * the custom group is extending.
973 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
974 * @param string $entityType - what entity are we extending here ?
982 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
983 $addSubtypeClause = FALSE;
985 switch ($entityType) {
987 // if contact, get all related to contact
988 $extendList = "'Contact','Individual','Household','Organization'";
989 $customGroupDAO->whereAdd("extends IN ( $extendList )");
991 $addSubtypeClause = TRUE;
998 // is I/H/O then get I/H/O and contact
999 $extendList = "'Contact','$entityType'";
1000 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1001 if (!$allSubtypes) {
1002 $addSubtypeClause = TRUE;
1009 case 'Contribution':
1012 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1016 if ($addSubtypeClause) {
1017 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1019 if (!empty($csType)) {
1020 $subtypeClause = array();
1021 foreach ($csType as $subtype) {
1022 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
1023 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1025 $subtypeClause[] = "extends_entity_column_value IS NULL";
1026 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) . " )");
1029 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1035 * Delete the Custom Group.
1037 * @param $group object the DAO custom group object
1038 * @param $force boolean whether to force the deletion, even if there are custom fields
1040 * @return boolean false if field exists for this group, true if group gets deleted.
1046 public static function deleteGroup($group, $force = FALSE) {
1048 //check wheter this contain any custom fields
1049 $customField = new CRM_Core_DAO_CustomField();
1050 $customField->custom_group_id
= $group->id
;
1051 $customField->find();
1053 // return early if there are custom fields and we're not
1054 // forcing the delete, otherwise delete the fields one by one
1055 while ($customField->fetch()) {
1059 CRM_Core_BAO_CustomField
::deleteField($customField);
1062 // drop the table associated with this custom group
1063 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1065 //delete custom group
1068 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1073 static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1074 foreach ($groupTree as $id => $group) {
1075 if (!isset($group['fields'])) {
1078 $groupId = CRM_Utils_Array
::value('id', $group);
1079 foreach ($group['fields'] as $field) {
1080 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1081 $value = $field['element_value'];
1083 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1084 ($action != CRM_Core_Action
::UPDATE ||
1086 !array_key_exists('element_value', $field)
1089 $value = $viewMode ?
NULL : $field['default_value'];
1095 $fieldId = $field['id'];
1096 $elementName = $field['element_name'];
1097 switch ($field['html_type']) {
1098 case 'Multi-Select':
1099 case 'AdvMulti-Select':
1101 $defaults[$elementName] = array();
1102 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1104 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1105 if (isset($value)) {
1106 foreach ($customOption as $customValue => $customLabel) {
1107 if (in_array($customValue, $checkedData)) {
1108 if ($field['html_type'] == 'CheckBox') {
1109 $defaults[$elementName][$customValue] = 1;
1112 $defaults[$elementName][$customValue] = $customValue;
1116 $defaults[$elementName][$customValue] = 0;
1122 if (isset($field['customValue']['data'])) {
1123 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1124 foreach ($customOption as $val) {
1125 if (in_array($val['value'], $checkedData)) {
1126 if ($field['html_type'] == 'CheckBox') {
1127 $defaults[$elementName][$val['value']] = 1;
1130 $defaults[$elementName][$val['value']] = $val['value'];
1134 $defaults[$elementName][$val['value']] = 0;
1139 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1140 foreach ($customOption as $val) {
1141 if (in_array($val['value'], $checkedValue)) {
1142 if ($field['html_type'] == 'CheckBox') {
1143 $defaults[$elementName][$val['value']] = 1;
1146 $defaults[$elementName][$val['value']] = $val['value'];
1155 if (isset($value)) {
1156 if (empty($field['time_format'])) {
1157 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1158 $field['date_format']
1162 $timeElement = $elementName . '_time';
1163 if (substr($elementName, -1) == ']') {
1164 $timeElement = substr($elementName, 0, -1) . '_time]';
1166 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1171 case 'Multi-Select Country':
1172 case 'Multi-Select State/Province':
1173 if (isset($value)) {
1174 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1175 foreach ($checkedValue as $val) {
1177 $defaults[$elementName][$val] = $val;
1183 case 'Select Country':
1185 $defaults[$elementName] = $value;
1188 $config = CRM_Core_Config
::singleton();
1189 $defaults[$elementName] = $config->defaultContactCountry
;
1193 case 'Autocomplete-Select':
1194 $hiddenEleName = $elementName . '_id';
1195 if (substr($elementName, -1) == ']') {
1196 $hiddenEleName = substr($elementName, 0, -1) . '_id]';
1198 if ($field['data_type'] == "ContactReference") {
1199 if (is_numeric($value)) {
1200 $defaults[$hiddenEleName] = $value;
1201 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1205 $label = CRM_Core_BAO_CustomOption
::getOptionLabel($field['id'], $value);
1206 $defaults[$hiddenEleName] = $value;
1207 $defaults[$elementName] = $label;
1212 if ($field['data_type'] == "Float") {
1213 $defaults[$elementName] = (float)$value;
1215 elseif ($field['data_type'] == 'Money' &&
1216 $field['html_type'] == 'Text'
1218 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1221 $defaults[$elementName] = $value;
1228 static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1229 // Get the Custom form values and groupTree
1230 // first reset all checkbox and radio data
1231 foreach ($groupTree as $groupID => $group) {
1232 if ($groupID === 'info') {
1235 foreach ($group['fields'] as $field) {
1236 $fieldId = $field['id'];
1238 //added Multi-Select option in the below if-statement
1239 if ($field['html_type'] == 'CheckBox' ||
$field['html_type'] == 'Radio' ||
1240 $field['html_type'] == 'AdvMulti-Select' ||
$field['html_type'] == 'Multi-Select'
1242 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1246 foreach ($params as $key => $val) {
1247 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1248 $match[1] == $field['id']
1255 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1256 // field exists in db so populate value from "form".
1257 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1260 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1262 //added for CheckBox
1266 $customValue = array_keys($v);
1267 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1270 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1274 //added for Advanced Multi-Select
1276 case 'AdvMulti-Select':
1277 //added for Multi-Select
1278 case 'Multi-Select':
1280 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1283 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1288 $date = CRM_Utils_Date
::processDate($v);
1289 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1297 //store the file in d/b
1298 $entityId = explode('=', $groupTree['info']['where'][0]);
1299 $fileParams = array('upload_date' => date('Ymdhis'));
1301 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1302 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1305 $fileParams['uri'] = $v['name'];
1306 $fileParams['mime_type'] = $v['type'];
1307 CRM_Core_BAO_File
::filePostProcess($v['name'],
1308 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1309 $groupTree[$groupID]['table_name'],
1314 'custom_' . $fieldId,
1318 $defaults = array();
1319 $paramsFile = array(
1320 'entity_table' => $groupTree[$groupID]['table_name'],
1321 'entity_id' => $entityId[1],
1324 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1329 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1333 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1341 * generic function to build all the form elements for a specific group tree
1343 * @param CRM_Core_Form $form the form object
1344 * @param array $groupTree the group tree object
1345 * @param string $showName
1346 * @param string $hideName
1352 static function buildQuickForm(&$form,
1354 $inactiveNeeded = FALSE,
1359 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1363 // this is fix for date field
1364 $form->assign('currentYear', date('Y'));
1366 foreach ($groupTree as $id => $group) {
1368 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1370 $groupId = CRM_Utils_Array
::value('id', $group);
1371 foreach ($group['fields'] as $field) {
1372 $required = CRM_Utils_Array
::value('is_required', $field);
1374 if ($field['data_type'] == 'File') {
1375 if (isset($field['customValue']['data'])) {
1380 $fieldId = $field['id'];
1381 $elementName = $field['element_name'];
1382 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1388 * Function to extract the get params from the url, validate
1389 * and store it in session
1391 * @param CRM_Core_Form $form the form object
1392 * @param string $type the type of custom group we are using
1398 static function extractGetParams(&$form, $type) {
1399 // if not GET params return
1404 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1405 $customValue = array();
1406 $htmlType = array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Select', 'Radio');
1408 foreach ($groupTree as $group) {
1409 if (!isset($group['fields'])) {
1412 foreach ($group['fields'] as $key => $field) {
1413 $fieldName = 'custom_' . $key;
1414 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form);
1418 if (!in_array($field['html_type'], $htmlType) ||
1419 $field['data_type'] == 'Boolean'
1421 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1423 if ($field['html_type'] == 'CheckBox' ||
1424 $field['html_type'] == 'AdvMulti-Select' ||
1425 $field['html_type'] == 'Multi-Select'
1427 $value = str_replace("|", ",", $value);
1428 $mulValues = explode(',', $value);
1429 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1431 foreach ($mulValues as $v1) {
1432 foreach ($customOption as $coID => $coValue) {
1433 if (strtolower(trim($coValue['label'])) == strtolower(trim($v1))) {
1434 $val[$coValue['value']] = 1;
1446 elseif ($field['html_type'] == 'Select' ||
1447 ($field['html_type'] == 'Radio' &&
1448 $field['data_type'] != 'Boolean'
1451 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1452 foreach ($customOption as $customID => $coValue) {
1453 if (strtolower(trim($coValue['label'])) == strtolower(trim($value))) {
1454 $value = $coValue['value'];
1459 elseif ($field['data_type'] == 'Date') {
1460 if (!empty($value)) {
1462 if (CRM_Utils_Array
::value('time_format', $field)) {
1463 $time = CRM_Utils_Request
::retrieve($fieldName . '_time', 'String', $form);
1465 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value . ' ' . $time);
1466 if (CRM_Utils_Array
::value('time_format', $field)) {
1467 $customValue[$fieldName . '_time'] = $time;
1474 $customValue[$fieldName] = $value;
1480 return $customValue;
1484 * Function to check the type of custom field type (eg: Used for Individual, Contribution, etc)
1485 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1487 * @param int $customFieldId custom field id
1488 * @param array $removeCustomFieldTypes remove custom fields of a type eg: array("Individual") ;
1491 * @return boolean false if it matches else true
1495 static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1496 $query = "SELECT cg.extends as extends
1497 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1498 WHERE cg.id = cf.custom_group_id
1499 AND cf.id =" . CRM_Utils_Type
::escape($customFieldId, 'Integer');
1501 $extends = CRM_Core_DAO
::singleValueQuery($query);
1503 if (in_array($extends, $removeCustomFieldTypes)) {
1509 static function mapTableName($table) {
1514 case 'Organization':
1515 return 'civicrm_contact';
1518 return 'civicrm_activity';
1521 return 'civicrm_group';
1523 case 'Contribution':
1524 return 'civicrm_contribution';
1526 case 'Relationship':
1527 return 'civicrm_relationship';
1530 return 'civicrm_event';
1533 return 'civicrm_membership';
1536 case 'ParticipantRole':
1537 case 'ParticipantEventName':
1538 case 'ParticipantEventType':
1539 return 'civicrm_participant';
1542 return 'civicrm_grant';
1545 return 'civicrm_pledge';
1548 return 'civicrm_address';
1551 return 'civicrm_campaign';
1555 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1556 $qParams = array(1 => array($table, 'String'));
1557 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1560 return 'civicrm_contact';
1563 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1564 if (array_key_exists($table, $extendObjs)) {
1565 return $extendObjs[$table];
1567 CRM_Core_Error
::fatal();
1572 static function createTable($group) {
1574 'name' => $group->table_name
,
1575 'is_multiple' => $group->is_multiple ?
1 : 0,
1576 'extends_name' => self
::mapTableName($group->extends),
1579 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1581 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1585 * Function returns formatted groupTree, sothat form can be easily build in template
1587 * @param array $groupTree associated array
1588 * @param int $groupCount group count by default 1, but can varry for multiple value custom data
1589 * @param object form object
1591 * @return array $formattedGroupTree
1593 static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1594 $formattedGroupTree = array();
1595 $uploadNames = array();
1597 foreach ($groupTree as $key => $value) {
1598 if ($key === 'info') {
1602 // add group information
1603 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1604 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1605 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1606 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1607 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1608 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1610 // this params needed of bulding multiple values
1611 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1612 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1613 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1614 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1615 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1616 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1618 // add field information
1619 foreach ($value['fields'] as $k => $properties) {
1620 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1621 if (isset($properties['customValue']) && !CRM_Utils_system
::isNull($properties['customValue'])) {
1622 if (isset($properties['customValue'][$groupCount])) {
1623 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1624 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1625 if ($properties['data_type'] == 'File') {
1626 $properties['element_value'] = $properties['customValue'][$groupCount];
1627 $uploadNames[] = $properties['element_name'];
1630 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1634 unset($properties['customValue']);
1635 $formattedGroupTree[$key]['fields'][$k] = $properties;
1640 // hack for field type File
1641 $formUploadNames = $form->get('uploadNames');
1642 if (is_array($formUploadNames)) {
1643 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1646 $form->set('uploadNames', $uploadNames);
1649 return $formattedGroupTree;
1653 * Build custom data view
1654 * @param object $form page object
1655 * @param array $groupTree associated array
1656 * @param boolean $returnCount true if customValue count needs to be returned
1658 static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL) {
1659 foreach ($groupTree as $key => $group) {
1660 if ($key === 'info') {
1664 foreach ($group['fields'] as $k => $properties) {
1665 $groupID = $group['id'];
1666 if (!empty($properties['customValue'])) {
1667 foreach ($properties['customValue'] as $values) {
1668 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1669 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1670 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1671 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1672 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1673 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1674 $details[$groupID][$values['id']]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties),
1675 'field_type' => CRM_Utils_Array
::value('html_type',
1678 'field_data_type' => CRM_Utils_Array
::value('data_type',
1681 'field_value' => self
::formatCustomValues($values,
1684 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1688 // also return contact reference contact id if user has view all or edit all contacts perm
1689 if ((CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts'))
1690 && $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] == 'ContactReference'
1692 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1697 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1698 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1699 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1700 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1701 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1702 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1703 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1709 //return a single value count if group id is passed to function
1710 //else return a groupId and count mapped array
1712 return count($details[$gID]);
1715 foreach( $details as $key => $value ) {
1716 $countValue[$key] = count($details[$key]);
1722 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1728 * Format custom value according to data, view mode
1730 * @param array $values associated array of custom values
1731 * @param array $field associated array
1732 * @param boolean $dncOptionPerLine true if optionPerLine should not be consider
1735 static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1736 $value = $values['data'];
1738 //changed isset CRM-4601
1739 if (CRM_Utils_System
::isNull($value)) {
1743 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1744 $dataType = CRM_Utils_Array
::value('data_type', $field);
1745 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1746 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1747 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1750 $freezeStringChecked = "";
1752 switch ($dataType) {
1754 $customTimeFormat = '';
1755 $customFormat = NULL;
1757 switch ($timeFormat) {
1759 $customTimeFormat = '%l:%M %P';
1763 $customTimeFormat = '%H:%M';
1767 // if time is not selected remove time from value
1768 $value = substr($value, 0, 10);
1771 $supportableFormats = array(
1772 'mm/dd' => "%B %E%f $customTimeFormat",
1773 'dd-mm' => "%E%f %B $customTimeFormat",
1774 'yy' => "%Y $customTimeFormat",
1775 'M yy' => "%b %Y $customTimeFormat",
1776 'yy-mm' => "%Y-%m $customTimeFormat"
1779 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
1780 if (array_key_exists($format, $supportableFormats)) {
1781 $customFormat = $supportableFormats["$format"];
1785 $retValue = CRM_Utils_Date
::customFormat($value, $customFormat);
1789 if ($value == '1') {
1790 $retValue = $freezeStringChecked . ts('Yes') . "\n";
1793 $retValue = $freezeStringChecked . ts('No') . "\n";
1799 $retValue = CRM_Utils_System
::formatWikiURL($value);
1804 $retValue = $values;
1807 case 'ContactReference':
1808 if (CRM_Utils_Array
::value('data', $values)) {
1809 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
1818 if ($htmlType == 'Text') {
1819 $retValue = (float)$value;
1823 if ($htmlType == 'Text') {
1824 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1829 if (in_array($htmlType, array('Text', 'TextArea'))) {
1833 // note that if its not text / textarea, the code falls thru and executes
1834 // the below case also
1835 case 'StateProvince':
1840 //added check for Multi-Select in the below if-statement
1841 $customData[] = $value;
1843 //form custom data for multiple-valued custom data
1844 switch ($htmlType) {
1845 case 'Multi-Select Country':
1846 case 'Select Country':
1847 $customData = $value;
1848 if (!is_array($value)) {
1849 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1852 SELECT id as value, name as label
1853 FROM civicrm_country";
1854 $coDAO = CRM_Core_DAO
::executeQuery($query);
1857 case 'Select State/Province':
1858 case 'Multi-Select State/Province':
1859 $customData = $value;
1860 if (!is_array($value)) {
1861 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1865 SELECT id as value, name as label
1866 FROM civicrm_state_province";
1867 $coDAO = CRM_Core_DAO
::executeQuery($query);
1871 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1872 if ($option_group_id) {
1873 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
1878 case 'AdvMulti-Select':
1879 case 'Multi-Select':
1880 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1882 if ($option_group_id) {
1883 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
1887 if (is_object($coDAO)) {
1888 while ($coDAO->fetch()) {
1889 $options[$coDAO->value
] = $coDAO->label
;
1893 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
1896 foreach ($options as $optionValue => $optionLabel) {
1897 if ($dataType == 'Money') {
1898 foreach ($customData as $k => $v) {
1899 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
1903 //to show only values that are checked
1904 if (in_array((string) $optionValue, $customData)) {
1905 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
1906 if (!$optionPerLine ||
$dncOptionPerLine) {
1910 $retValue .= $checked . $optionLabel;
1913 $retValue[] = $checked . $optionLabel;
1920 //special case for option per line formatting
1921 if ($optionPerLine > 1 && is_array($retValue)) {
1924 $displayValues = array();
1925 $displayString = '';
1926 foreach ($retValue as $val) {
1927 if ($displayString) {
1928 $displayString .= ", ";
1931 $displayString .= $val;
1935 if (($rowCounter == $optionPerLine) ||
($fieldCounter == count($retValue))) {
1936 $displayValues[] = $displayString;
1937 $displayString = '';
1941 $retValue = $displayValues;
1944 $retValue = isset($retValue) ?
$retValue : NULL;
1949 * Get the custom group titles by custom field ids.
1951 * @param array $fieldIds - array of custom field ids.
1953 * @return array $groupLabels - array consisting of groups and fields labels with ids.
1956 public static function getGroupTitles($fieldIds) {
1957 if (!is_array($fieldIds) && empty($fieldIds)) {
1961 $groupLabels = array();
1962 $fIds = "(" . implode(',', $fieldIds) . ")";
1965 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
1966 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
1967 FROM civicrm_custom_group, civicrm_custom_field
1968 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
1969 AND civicrm_custom_field.id IN {$fIds}";
1971 $dao = CRM_Core_DAO
::executeQuery($query);
1972 while ($dao->fetch()) {
1973 $groupLabels[$dao->fieldID
] = array(
1974 'fieldID' => $dao->fieldID
,
1975 'fieldLabel' => $dao->fieldLabel
,
1976 'groupID' => $dao->groupID
,
1977 'groupTitle' => $dao->groupTitle
,
1981 return $groupLabels;
1984 static function dropAllTables() {
1985 $query = "SELECT table_name FROM civicrm_custom_group";
1986 $dao = CRM_Core_DAO
::executeQuery($query);
1988 while ($dao->fetch()) {
1989 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
1990 CRM_Core_DAO
::executeQuery($query);
1995 * Check whether custom group is empty or not.
1997 * @param int $gID - custom group id.
1999 * @return boolean true if empty otherwise false.
2002 static function isGroupEmpty($gID) {
2007 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2012 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2013 $value = CRM_Core_DAO
::singleValueQuery($query);
2015 if (empty($value)) {
2023 * Get the list of types for objects that a custom group extends to.
2025 * @param array $types - var which should have the list appended.
2027 * @return array of types.
2030 static function getExtendedObjectTypes(&$types = array( )) {
2031 static $flag = FALSE, $objTypes = array();
2034 $extendObjs = array();
2035 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2037 foreach ($extendObjs as $ovId => $ovValues) {
2038 if ($ovValues['description']) {
2039 // description is expected to be a callback func to subtypes
2040 list($callback, $args) = explode(';', trim($ovValues['description']));
2042 if (!empty($args)) {
2043 eval('$args = ' . $args . ';');
2049 if (!is_array($args)) {
2050 CRM_Core_Error
::fatal('Arg is not of type array');
2053 list($className) = explode('::', $callback);
2054 require_once (str_replace('_',DIRECTORY_SEPARATOR
, $className) . '.php');
2056 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2062 $types = array_merge($types, $objTypes);
2066 function hasReachedMaxLimit($customGroupId, $entityId) {
2067 //check whether the group is multiple
2068 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2069 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2070 $hasReachedMax = FALSE;
2072 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))) {
2073 if (!$maxMultiple) {
2074 $hasReachedMax = FALSE;
2076 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2077 //count the number of entries for a entity
2078 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2079 $params = array(1 => array($entityId, 'Integer'));
2080 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2082 if ($count >= $maxMultiple) {
2083 $hasReachedMax = TRUE;
2087 return $hasReachedMax;