3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
35 * Business object for managing custom data groups.
37 class CRM_Core_BAO_CustomGroup
extends CRM_Core_DAO_CustomGroup
{
42 public function __construct() {
43 parent
::__construct();
47 * Takes an associative array and creates a custom group object.
49 * This function is invoked from within the web form layer and also from the api layer
51 * @param array $params
52 * (reference) an assoc array of name/value pairs.
54 * @return CRM_Core_DAO_CustomGroup
56 public static function create(&$params) {
57 // create custom group dao, populate fields and then save.
58 $group = new CRM_Core_DAO_CustomGroup();
59 $group->title
= $params['title'];
61 if (in_array($params['extends'][0],
64 'ParticipantEventName',
65 'ParticipantEventType',
68 $group->extends = 'Participant';
71 $group->extends = $params['extends'][0];
74 $group->extends_entity_column_id
= 'null';
76 $params['extends'][0] == 'ParticipantRole' ||
77 $params['extends'][0] == 'ParticipantEventName' ||
78 $params['extends'][0] == 'ParticipantEventType'
80 $group->extends_entity_column_id
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $params['extends'][0], 'value', 'name');
83 //this is format when form get submit.
84 $extendsChildType = CRM_Utils_Array
::value(1, $params['extends']);
85 //lets allow user to pass direct child type value, CRM-6893
86 if (!empty($params['extends_entity_column_value'])) {
87 $extendsChildType = $params['extends_entity_column_value'];
89 if (!CRM_Utils_System
::isNull($extendsChildType)) {
90 $extendsChildType = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendsChildType);
91 if (CRM_Utils_Array
::value(0, $params['extends']) == 'Relationship') {
92 $extendsChildType = str_replace(array('_a_b', '_b_a'), array(
95 ), $extendsChildType);
97 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
98 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType .
99 CRM_Core_DAO
::VALUE_SEPARATOR
;
103 $extendsChildType = 'null';
105 $group->extends_entity_column_value
= $extendsChildType;
107 if (isset($params['id'])) {
108 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
113 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
117 'collapse_adv_display',
123 foreach ($fields as $field) {
124 $group->$field = CRM_Utils_Array
::value($field, $params, FALSE);
126 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
127 $params['max_multiple'] >= '0'
128 ) ?
$params['max_multiple'] : 'null' : 'null';
130 $tableName = $oldTableName = NULL;
131 if (isset($params['id'])) {
132 $group->id
= $params['id'];
133 //check whether custom group was changed from single-valued to multiple-valued
134 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
139 if ((!empty($params['is_multiple']) ||
$isMultiple) &&
140 ($params['is_multiple'] != $isMultiple)
142 $oldTableName = CRM_Core_DAO
::getFieldValue(
143 'CRM_Core_DAO_CustomGroup',
150 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
151 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
153 // we do this only once, so name never changes
154 if (isset($params['name'])) {
155 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
158 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
161 if (isset($params['table_name'])) {
162 $tableName = $params['table_name'];
164 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
165 // Bad idea. Prevent group creation because it might lead to a broken configuration.
166 CRM_Core_Error
::fatal(ts("Cannot create custom table because %1 is already a core table.", array('1' => $tableName)));
171 if (array_key_exists('is_reserved', $params)) {
172 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
174 $op = isset($params['id']) ?
'edit' : 'create';
175 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
177 // enclose the below in a transaction
178 $transaction = new CRM_Core_Transaction();
181 if (!isset($params['id'])) {
182 if (!isset($params['table_name'])) {
183 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 42));
184 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
186 $group->table_name
= $tableName;
187 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
193 // now create the table associated with this group
194 self
::createTable($group);
196 elseif ($oldTableName) {
197 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($oldTableName, CRM_Utils_Array
::value('is_multiple', $params));
200 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
201 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
205 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends'][0]));
207 $transaction->commit();
210 CRM_Utils_System
::flushCache();
213 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
216 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
223 * Fetch object based on array of properties.
225 * @param array $params
226 * (reference ) an assoc array of name/value pairs.
227 * @param array $defaults
228 * (reference ) an assoc array to hold the flattened values.
230 * @return CRM_Core_DAO_CustomGroup
232 public static function retrieve(&$params, &$defaults) {
233 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
237 * Update the is_active flag in the db.
240 * Id of the database record.
241 * @param bool $is_active
242 * Value we want to set the is_active field.
245 * DAO object on sucess, null otherwise
247 public static function setIsActive($id, $is_active) {
249 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
252 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
255 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
259 * Determine if given entity (sub)type has any custom groups
261 * @param string $extends
262 * E.g. "Individual", "Activity".
263 * @param int $columnId
264 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
265 * @param string $columnValue
266 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
270 public static function hasCustomGroup($extends, $columnId, $columnValue) {
271 $dao = new CRM_Core_DAO_CustomGroup();
272 $dao->extends = $extends;
273 $dao->extends_entity_column_id
= $columnId;
274 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
275 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
276 //$dao->extends_entity_column_value = $columnValue;
277 return $dao->find() ?
TRUE : FALSE;
281 * Determine if there are any CustomGroups for the given $activityTypeId.
282 * If none found, create one.
284 * @param int $activityTypeId
287 * TRUE if a group is found or created; FALSE on error
289 public static function autoCreateByActivityType($activityTypeId) {
290 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
293 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
296 'extends' => 'Activity',
297 'extends_entity_column_id' => NULL,
298 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
299 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
303 $result = civicrm_api('CustomGroup', 'create', $params);
304 return !$result['is_error'];
308 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
309 * This may also include entity specific data values.
311 * An array containing all custom groups and their custom fields is returned.
313 * @param string $entityType
314 * Of the contact whose contact type is needed.
315 * @param CRM_Core_Form $form
316 * Not used but required.
317 * @param int $entityID
318 * @param int $groupID
319 * @param string $subType
320 * @param string $subName
321 * @param bool $fromCache
322 * @param bool $onlySubType
325 * The returned array is keyed by group id and has the custom group table fields
326 * and a subkey 'fields' holding the specific custom fields.
327 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
328 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
330 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
331 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
332 * With caching the performance impact would be small & the function would be cleaner
335 public static function &getTree(
346 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
350 $strSelect = $strFrom = $strWhere = $orderBy = '';
351 $tableData = array();
353 // using tableData to build the queryString
355 'civicrm_custom_field' => array(
375 'civicrm_custom_group' => array(
385 'extends_entity_column_id',
386 'extends_entity_column_value',
393 foreach ($tableData as $tableName => $tableColumn) {
394 foreach ($tableColumn as $columnName) {
395 $alias = $tableName . "_" . $columnName;
396 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
399 $strSelect = "SELECT " . implode(', ', $select);
401 // from, where, order by
403 FROM civicrm_custom_group
404 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
407 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
408 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
409 $entityType == 'Household'
411 $in = "'$entityType', 'Contact'";
413 elseif (strpos($entityType, "'") !== FALSE) {
414 // this allows the calling function to send in multiple entity types
419 $in = "'$entityType'";
424 if (is_array($subType)) {
425 $subType = implode(',', $subType);
427 if (strpos($subType, ',')) {
428 $subTypeParts = explode(',', $subType);
429 $subTypeClauses = array();
430 foreach ($subTypeParts as $subTypePart) {
431 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
.
432 trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) .
433 CRM_Core_DAO
::VALUE_SEPARATOR
;
434 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
438 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
441 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) .
442 " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
446 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
.
447 trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) .
448 CRM_Core_DAO
::VALUE_SEPARATOR
;
451 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
454 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
455 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
460 WHERE civicrm_custom_group.is_active = 1
461 AND civicrm_custom_field.is_active = 1
462 AND civicrm_custom_group.extends IN ($in)
466 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
471 WHERE civicrm_custom_group.is_active = 1
472 AND civicrm_custom_field.is_active = 1
473 AND civicrm_custom_group.extends IN ($in)
474 AND civicrm_custom_group.extends_entity_column_value IS NULL
480 // since we want a specific group id we add it to the where clause
481 $strWhere .= " AND civicrm_custom_group.id = %1";
482 $params[1] = array($groupID, 'Integer');
485 // since groupID is false we need to show all Inline groups
486 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
489 // ensure that the user has access to these custom groups
490 $strWhere .= " AND " .
491 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
492 'civicrm_custom_group.'
496 ORDER BY civicrm_custom_group.weight,
497 civicrm_custom_group.title,
498 civicrm_custom_field.weight,
499 civicrm_custom_field.label
502 // final query string
503 $queryString = "$strSelect $strFrom $strWhere $orderBy";
505 // lets see if we can retrieve the groupTree from cache
506 $cacheString = $queryString;
508 $cacheString .= "_{$groupID}";
511 $cacheString .= "_Inline";
514 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
515 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
516 $cache = CRM_Utils_Cache
::singleton();
517 $tablesWithEntityData = array();
519 $groupTree = $cache->get($cacheKey);
520 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
523 if (empty($groupTree)) {
524 $groupTree = $multipleFieldGroups = array();
525 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
526 $customValueTables = array();
529 while ($crmDAO->fetch()) {
531 $groupID = $crmDAO->civicrm_custom_group_id
;
532 $fieldId = $crmDAO->civicrm_custom_field_id
;
533 if ($crmDAO->civicrm_custom_group_is_multiple
) {
534 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
536 // create an array for groups if it does not exist
537 if (!array_key_exists($groupID, $groupTree)) {
538 $groupTree[$groupID] = array();
539 $groupTree[$groupID]['id'] = $groupID;
541 // populate the group information
542 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
543 $fullFieldName = "civicrm_custom_group_$fieldName";
544 if ($fieldName == 'id' ||
545 is_null($crmDAO->$fullFieldName)
550 if ($fieldName == 'extends_entity_column_value' && $subType) {
551 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
553 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
555 $groupTree[$groupID]['fields'] = array();
557 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
560 // add the fields now (note - the query row will always contain a field)
561 // we only reset this once, since multiple values come is as multiple rows
562 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
563 $groupTree[$groupID]['fields'][$fieldId] = array();
566 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
567 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
568 // populate information for a custom field
569 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
570 $fullFieldName = "civicrm_custom_field_$fieldName";
571 if ($fieldName == 'id' ||
572 is_null($crmDAO->$fullFieldName)
576 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
580 if (!empty($customValueTables)) {
581 $groupTree['info'] = array('tables' => $customValueTables);
584 $cache->set($cacheKey, $groupTree);
585 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
587 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
588 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
589 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
590 $singleFieldTables = array();
591 // now that we have all the groups and fields, lets get the values
592 // since we need to know the table and field names
593 // add info to groupTree
595 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
596 !empty($groupTree['info']['tables'])
598 $select = $from = $where = array();
599 $groupTree['info']['where'] = NULL;
601 foreach ($groupTree['info']['tables'] as $table => $fields) {
602 $groupTree['info']['from'][] = $table;
604 "{$table}.id as {$table}_id",
605 "{$table}.entity_id as {$table}_entity_id",
607 foreach ($fields as $column => $dontCare) {
608 $select[] = "{$table}.{$column} as {$table}_{$column}";
610 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
612 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
613 if (in_array($table, $multipleFieldGroups) &&
614 self
::customGroupDataExistsForEntity($entityID, $table)
616 $entityMultipleSelectClauses[$table] = $select;
619 $singleFieldTables[] = $table;
620 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
625 if ($entityID && !empty($singleFieldTables)) {
626 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
628 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
629 if (!empty($multipleFieldTablesWithEntityData)) {
630 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
638 * Check whether the custom group has any data for the given entity.
641 * @param int $entityID
642 * Id of entity for whom we are checking data for.
643 * @param string $table
644 * Table that we are checking.
646 * @param bool $getCount
649 * does this entity have data in this custom table
651 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
655 WHERE entity_id = $entityID
657 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
659 return $recordExists;
661 return $recordExists ?
TRUE : FALSE;
665 * Build the group tree for Custom fields which are not 'is_multiple'
667 * The combination of all these fields in one query with a 'using' join was not working for
668 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
669 * mechanism as it seemed to be acceptable in this context
671 * @param array $groupTree
672 * (reference) group tree array which is being built.
673 * @param int $entityID
674 * Id of entity for whom the tree is being build up.
675 * @param array $entitySingleSelectClauses
676 * Array of select clauses relevant to the entity.
677 * @param array $singleFieldTablesWithEntityData
678 * Array of tables in which this entity has data.
680 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
681 $select = implode(', ', $entitySingleSelectClauses);
682 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
683 foreach ($singleFieldTablesWithEntityData as $table) {
684 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
690 WHERE first.entity_id = $entityID
692 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
696 * Build the group tree for Custom fields which are 'is_multiple'
698 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
700 * @param array $groupTree
701 * (reference) group tree array which is being built.
702 * @param int $entityID
703 * Id of entity for whom the tree is being build up.
704 * @param array $entityMultipleSelectClauses
705 * Array of select clauses relevant to the entity.
706 * @param array $multipleFieldTablesWithEntityData
707 * Array of tables in which this entity has data.
709 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData) {
710 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
711 $select = implode(',', $selectClauses);
715 WHERE entity_id = $entityID
717 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
722 * Build the tree entity data - starting from a query retrieving the custom fields build the group
723 * tree data for the relevant entity (entity is included in the query).
725 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
727 * @param array $groupTree
728 * (reference) group tree array which is being built.
729 * @param string $query
730 * @param array $includedTables
731 * Tables to include - required because the function (for historical reasons).
732 * iterates through the group tree
734 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables) {
735 $dao = CRM_Core_DAO
::executeQuery($query);
736 while ($dao->fetch()) {
737 foreach ($groupTree as $groupID => $group) {
738 if ($groupID === 'info') {
741 $table = $groupTree[$groupID]['table_name'];
742 //working from the groupTree instead of the table list means we have to iterate & exclude.
743 // this could possibly be re-written as other parts of the function have been refactored
744 // for now we just check if the given table is to be included in this function
745 if (!in_array($table, $includedTables)) {
748 foreach ($group['fields'] as $fieldID => $dontCare) {
749 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
756 * Build the entity-specific custom data into the group tree on a per-field basis
759 * Object representing the custom field to be populated into the groupTree.
760 * @param array $groupTree
761 * (reference) the group tree being build.
762 * @param string $table
764 * @param int $groupID
766 * @param int $fieldID
769 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID) {
770 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
771 $idName = "{$table}_id";
772 $fieldName = "{$table}_{$column}";
773 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
774 if ($dataType == 'File') {
775 if (isset($dao->$fieldName)) {
776 $config = CRM_Core_Config
::singleton();
777 $fileDAO = new CRM_Core_DAO_File();
778 $fileDAO->id
= $dao->$fieldName;
780 if ($fileDAO->find(TRUE)) {
781 $entityIDName = "{$table}_entity_id";
782 $customValue['id'] = $dao->$idName;
783 $customValue['data'] = $fileDAO->uri
;
784 $customValue['fid'] = $fileDAO->id
;
785 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
786 $customValue['displayURL'] = NULL;
787 $deleteExtra = ts('Are you sure you want to delete attached file.');
789 CRM_Core_Action
::DELETE
=> array(
790 'name' => ts('Delete Attached File'),
791 'url' => 'civicrm/file',
792 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
793 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
794 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
797 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
798 CRM_Core_Action
::DELETE
,
800 'id' => $fileDAO->id
,
801 'eid' => $dao->$entityIDName,
806 'file.manage.delete',
810 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
811 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
812 if ($fileDAO->mime_type
== "image/jpeg" ||
813 $fileDAO->mime_type
== "image/pjpeg" ||
814 $fileDAO->mime_type
== "image/gif" ||
815 $fileDAO->mime_type
== "image/x-png" ||
816 $fileDAO->mime_type
== "image/png"
818 $customValue['displayURL'] = $customValue['fileURL'];
819 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
824 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
826 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId, NULL, NULL);
827 if ($path && file_exists($path)) {
828 list($imageWidth, $imageHeight) = getimagesize($path);
829 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
830 $customValue['imageThumbWidth'] = $imageThumbWidth;
831 $customValue['imageThumbHeight'] = $imageThumbHeight;
837 $customValue = array(
838 'id' => $dao->$idName,
844 $customValue = array(
845 'id' => $dao->$idName,
846 'data' => $dao->$fieldName,
850 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
851 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
853 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
854 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
857 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
862 * Get the group title.
870 public static function getTitle($id) {
871 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
875 * Get custom group details for a group.
877 * An array containing custom group details (including their custom field) is returned.
879 * @param int $groupId
880 * Group id whose details are needed.
881 * @param bool $searchable
882 * Is this field searchable.
883 * @param array $extends
884 * Which table does it extend if any.
886 * @param null $inSelector
889 * array consisting of all group and field details
891 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
893 $groupTree = array();
894 $select = $from = $where = $orderBy = '';
896 $tableData = array();
898 // using tableData to build the queryString
900 'civicrm_custom_field' => array(
924 'civicrm_custom_group' => array(
931 'collapse_adv_display',
933 'extends_entity_column_value',
942 foreach ($tableData as $tableName => $tableColumn) {
943 foreach ($tableColumn as $columnName) {
944 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
947 $select = 'SELECT ' . implode(', ', $s);
949 // from, where, order by
950 $from = " FROM civicrm_custom_field, civicrm_custom_group";
951 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
952 AND civicrm_custom_group.is_active = 1
953 AND civicrm_custom_field.is_active = 1 ";
955 $params[1] = array($groupId, 'Integer');
956 $where .= " AND civicrm_custom_group.id = %1";
960 $where .= " AND civicrm_custom_field.is_searchable = 1";
964 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
969 foreach ($extends as $e) {
970 $clause[] = "civicrm_custom_group.extends = '$e'";
972 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
974 //include case activities customdata if case is enabled
975 if (in_array('Activity', $extends)) {
976 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
977 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
978 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
982 // ensure that the user has access to these custom groups
984 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
985 'civicrm_custom_group.'
988 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
990 // final query string
991 $queryString = $select . $from . $where . $orderBy;
994 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
997 while ($crmDAO->fetch()) {
998 $groupId = $crmDAO->civicrm_custom_group_id
;
999 $fieldId = $crmDAO->civicrm_custom_field_id
;
1001 // create an array for groups if it does not exist
1002 if (!array_key_exists($groupId, $groupTree)) {
1003 $groupTree[$groupId] = array();
1004 $groupTree[$groupId]['id'] = $groupId;
1006 foreach ($tableData['civicrm_custom_group'] as $v) {
1007 $fullField = "civicrm_custom_group_" . $v;
1009 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1013 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1016 $groupTree[$groupId]['fields'] = array();
1019 // add the fields now (note - the query row will always contain a field)
1020 $groupTree[$groupId]['fields'][$fieldId] = array();
1021 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1023 foreach ($tableData['civicrm_custom_field'] as $v) {
1024 $fullField = "civicrm_custom_field_" . $v;
1025 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1028 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1036 * @param $entityType
1038 * @param string $cidToken
1042 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1044 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1046 // get 'Tab' and 'Tab with table' groups
1047 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1048 $customGroupDAO->whereAdd("is_active = 1");
1050 // add whereAdd for entity type
1051 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1055 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1056 $customGroupDAO->whereAdd($permissionClause);
1059 $customGroupDAO->orderBy('weight');
1060 $customGroupDAO->find();
1062 // process each group with menu tab
1063 while ($customGroupDAO->fetch()) {
1065 $group['id'] = $customGroupDAO->id
;
1066 $group['path'] = $path;
1067 $group['title'] = "$customGroupDAO->title";
1068 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1069 $group['extra'] = array('gid' => $customGroupDAO->id
);
1070 $group['table_name'] = $customGroupDAO->table_name
;
1071 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1079 * Get the table name for the entity type
1080 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1081 * tableName is 'civicrm_contact'
1083 * @param string $entityType
1084 * What entity are we extending here ?.
1089 * @see _apachesolr_civiAttachments_dereference_file_parent
1091 public static function getTableNameByEntityName($entityType) {
1093 switch ($entityType) {
1097 case 'Organization':
1098 $tableName = 'civicrm_contact';
1101 case 'Contribution':
1102 $tableName = 'civicrm_contribution';
1106 $tableName = 'civicrm_group';
1109 // DRAFTING: Verify if we cannot make it pluggable
1112 $tableName = 'civicrm_activity';
1115 case 'Relationship':
1116 $tableName = 'civicrm_relationship';
1120 $tableName = 'civicrm_membership';
1124 $tableName = 'civicrm_participant';
1128 $tableName = 'civicrm_event';
1132 $tableName = 'civicrm_grant';
1135 // need to add cases for Location, Address
1142 * Get a list of custom groups which extend a given entity type.
1143 * If there are custom-groups which only apply to certain subtypes,
1144 * those WILL be included.
1146 * @param string $entityType
1148 * @return CRM_Core_DAO_CustomGroup
1150 public static function getAllCustomGroupsByBaseEntity($entityType) {
1151 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1152 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1153 return $customGroupDAO;
1157 * Add the whereAdd clause for the DAO depending on the type of entity
1158 * the custom group is extending.
1160 * @param object $customGroupDAO
1161 * @param string $entityType
1162 * What entity are we extending here ?.
1164 * @param int $entityID
1165 * @param bool $allSubtypes
1167 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1168 $addSubtypeClause = FALSE;
1170 switch ($entityType) {
1172 // if contact, get all related to contact
1173 $extendList = "'Contact','Individual','Household','Organization'";
1174 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1175 if (!$allSubtypes) {
1176 $addSubtypeClause = TRUE;
1182 case 'Organization':
1183 // is I/H/O then get I/H/O and contact
1184 $extendList = "'Contact','$entityType'";
1185 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1186 if (!$allSubtypes) {
1187 $addSubtypeClause = TRUE;
1195 case 'Contribution':
1198 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1202 if ($addSubtypeClause) {
1203 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1205 if (!empty($csType)) {
1206 $subtypeClause = array();
1207 foreach ($csType as $subtype) {
1208 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1209 CRM_Core_DAO
::VALUE_SEPARATOR
;
1210 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1212 $subtypeClause[] = "extends_entity_column_value IS NULL";
1213 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1217 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1223 * Delete the Custom Group.
1225 * @param CRM_Core_BAO_CustomGroup $group
1226 * Custom group object.
1227 * @param bool $force
1228 * whether to force the deletion, even if there are custom fields.
1231 * False if field exists for this group, true if group gets deleted.
1233 public static function deleteGroup($group, $force = FALSE) {
1235 //check whether this contain any custom fields
1236 $customField = new CRM_Core_DAO_CustomField();
1237 $customField->custom_group_id
= $group->id
;
1238 $customField->find();
1240 // return early if there are custom fields and we're not
1241 // forcing the delete, otherwise delete the fields one by one
1242 while ($customField->fetch()) {
1246 CRM_Core_BAO_CustomField
::deleteField($customField);
1249 // drop the table associated with this custom group
1250 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1252 //delete custom group
1255 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1263 * @param array $groupTree
1264 * @param array $defaults
1265 * @param bool $viewMode
1266 * @param bool $inactiveNeeded
1267 * @param int $action
1269 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1270 foreach ($groupTree as $id => $group) {
1271 if (!isset($group['fields'])) {
1274 foreach ($group['fields'] as $field) {
1275 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1276 $value = $field['element_value'];
1278 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1279 ($action != CRM_Core_Action
::UPDATE ||
1281 !array_key_exists('element_value', $field)
1284 $value = $viewMode ?
NULL : $field['default_value'];
1290 if (!empty($field['element_name'])) {
1291 $elementName = $field['element_name'];
1293 switch ($field['html_type']) {
1294 case 'Multi-Select':
1295 case 'AdvMulti-Select':
1297 $defaults[$elementName] = array();
1298 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1300 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1301 if (isset($value)) {
1302 foreach ($customOption as $customValue => $customLabel) {
1303 if (in_array($customValue, $checkedData)) {
1304 if ($field['html_type'] == 'CheckBox') {
1305 $defaults[$elementName][$customValue] = 1;
1308 $defaults[$elementName][$customValue] = $customValue;
1312 $defaults[$elementName][$customValue] = 0;
1318 if (isset($field['customValue']['data'])) {
1319 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1320 foreach ($customOption as $val) {
1321 if (in_array($val['value'], $checkedData)) {
1322 if ($field['html_type'] == 'CheckBox') {
1323 $defaults[$elementName][$val['value']] = 1;
1326 $defaults[$elementName][$val['value']] = $val['value'];
1330 $defaults[$elementName][$val['value']] = 0;
1335 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1336 foreach ($customOption as $val) {
1337 if (in_array($val['value'], $checkedValue)) {
1338 if ($field['html_type'] == 'CheckBox') {
1339 $defaults[$elementName][$val['value']] = 1;
1342 $defaults[$elementName][$val['value']] = $val['value'];
1351 if (isset($value)) {
1352 if (empty($field['time_format'])) {
1353 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1354 $field['date_format']
1358 $timeElement = $elementName . '_time';
1359 if (substr($elementName, -1) == ']') {
1360 $timeElement = substr($elementName, 0, -1) . '_time]';
1362 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1367 case 'Multi-Select Country':
1368 case 'Multi-Select State/Province':
1369 if (isset($value)) {
1370 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1371 foreach ($checkedValue as $val) {
1373 $defaults[$elementName][$val] = $val;
1379 case 'Select Country':
1381 $defaults[$elementName] = $value;
1384 $config = CRM_Core_Config
::singleton();
1385 $defaults[$elementName] = $config->defaultContactCountry
;
1390 if ($field['data_type'] == "Float") {
1391 $defaults[$elementName] = (float) $value;
1393 elseif ($field['data_type'] == 'Money' &&
1394 $field['html_type'] == 'Text'
1396 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1399 $defaults[$elementName] = $value;
1407 * PostProcess function.
1409 * @param array $groupTree
1410 * @param array $params
1411 * @param bool $skipFile
1413 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1414 // Get the Custom form values and groupTree
1415 // first reset all checkbox and radio data
1416 foreach ($groupTree as $groupID => $group) {
1417 if ($groupID === 'info') {
1420 foreach ($group['fields'] as $field) {
1421 $fieldId = $field['id'];
1423 //added Multi-Select option in the below if-statement
1424 if ($field['html_type'] == 'CheckBox' ||
1425 $field['html_type'] == 'Radio' ||
1426 $field['html_type'] == 'AdvMulti-Select' ||
1427 $field['html_type'] == 'Multi-Select'
1429 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1433 foreach ($params as $key => $val) {
1434 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1435 $match[1] == $field['id']
1441 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1442 // field exists in db so populate value from "form".
1443 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1446 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1448 //added for CheckBox
1452 $customValue = array_keys($v);
1453 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1454 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1455 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1458 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1462 //added for Advanced Multi-Select
1464 case 'AdvMulti-Select':
1465 //added for Multi-Select
1466 case 'Multi-Select':
1468 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1469 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1470 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1473 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1478 $date = CRM_Utils_Date
::processDate($v);
1479 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1487 //store the file in d/b
1488 $entityId = explode('=', $groupTree['info']['where'][0]);
1489 $fileParams = array('upload_date' => date('Ymdhis'));
1491 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1492 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1495 $fileParams['uri'] = $v['name'];
1496 $fileParams['mime_type'] = $v['type'];
1497 CRM_Core_BAO_File
::filePostProcess($v['name'],
1498 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1499 $groupTree[$groupID]['table_name'],
1504 'custom_' . $fieldId,
1508 $defaults = array();
1509 $paramsFile = array(
1510 'entity_table' => $groupTree[$groupID]['table_name'],
1511 'entity_id' => $entityId[1],
1514 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1519 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1523 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1531 * Generic function to build all the form elements for a specific group tree.
1533 * @param CRM_Core_Form $form
1535 * @param array $groupTree
1536 * The group tree object.
1537 * @param bool $inactiveNeeded
1538 * Return inactive custom groups.
1539 * @param string $prefix
1540 * Prefix for custom grouptree assigned to template.
1542 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1543 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1545 // this is fix for date field
1546 $form->assign('currentYear', date('Y'));
1548 foreach ($groupTree as $id => $group) {
1549 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1550 foreach ($group['fields'] as $field) {
1551 $required = CRM_Utils_Array
::value('is_required', $field);
1553 if ($field['data_type'] == 'File') {
1554 if (!empty($field['element_value']['data'])) {
1559 $fieldId = $field['id'];
1560 $elementName = $field['element_name'];
1561 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1567 * Extract the get params from the url, validate and store it in session.
1569 * @param CRM_Core_Form $form
1571 * @param string $type
1572 * The type of custom group we are using.
1576 public static function extractGetParams(&$form, $type) {
1581 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1582 $customValue = array();
1591 foreach ($groupTree as $group) {
1592 if (!isset($group['fields'])) {
1595 foreach ($group['fields'] as $key => $field) {
1596 $fieldName = 'custom_' . $key;
1597 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1601 if (!in_array($field['html_type'], $htmlType) ||
1602 $field['data_type'] == 'Boolean'
1604 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1606 if ($field['html_type'] == 'CheckBox' ||
1607 $field['html_type'] == 'AdvMulti-Select' ||
1608 $field['html_type'] == 'Multi-Select'
1610 $value = str_replace("|", ",", $value);
1611 $mulValues = explode(',', $value);
1612 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1614 foreach ($mulValues as $v1) {
1615 foreach ($customOption as $coID => $coValue) {
1616 if (strtolower(trim($coValue['label'])) ==
1617 strtolower(trim($v1))
1619 $val[$coValue['value']] = 1;
1631 elseif ($field['html_type'] == 'Select' ||
1632 ($field['html_type'] == 'Radio' &&
1633 $field['data_type'] != 'Boolean'
1636 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1637 foreach ($customOption as $customID => $coValue) {
1638 if (strtolower(trim($coValue['label'])) ==
1639 strtolower(trim($value))
1641 $value = $coValue['value'];
1646 elseif ($field['data_type'] == 'Date') {
1647 if (!empty($value)) {
1649 if (!empty($field['time_format'])) {
1650 $time = CRM_Utils_Request
::retrieve($fieldName .
1651 '_time', 'String', $form, FALSE, NULL, 'GET');
1653 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value .
1655 if (!empty($field['time_format'])) {
1656 $customValue[$fieldName . '_time'] = $time;
1663 $customValue[$fieldName] = $value;
1669 return $customValue;
1673 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1674 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1676 * @param int $customFieldId
1678 * @param array $removeCustomFieldTypes
1679 * Remove custom fields of a type eg: array("Individual") ;.
1682 * false if it matches else true
1684 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1685 $query = "SELECT cg.extends as extends
1686 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1687 WHERE cg.id = cf.custom_group_id
1689 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1691 $extends = CRM_Core_DAO
::singleValueQuery($query);
1693 if (in_array($extends, $removeCustomFieldTypes)) {
1705 public static function mapTableName($table) {
1710 case 'Organization':
1711 return 'civicrm_contact';
1714 return 'civicrm_activity';
1717 return 'civicrm_group';
1719 case 'Contribution':
1720 return 'civicrm_contribution';
1722 case 'Relationship':
1723 return 'civicrm_relationship';
1726 return 'civicrm_event';
1729 return 'civicrm_membership';
1732 case 'ParticipantRole':
1733 case 'ParticipantEventName':
1734 case 'ParticipantEventType':
1735 return 'civicrm_participant';
1738 return 'civicrm_grant';
1741 return 'civicrm_pledge';
1744 return 'civicrm_address';
1747 return 'civicrm_campaign';
1751 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1752 $qParams = array(1 => array($table, 'String'));
1753 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1756 return 'civicrm_contact';
1759 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1760 if (array_key_exists($table, $extendObjs)) {
1761 return $extendObjs[$table];
1763 CRM_Core_Error
::fatal();
1771 public static function createTable($group) {
1773 'name' => $group->table_name
,
1774 'is_multiple' => $group->is_multiple ?
1 : 0,
1775 'extends_name' => self
::mapTableName($group->extends),
1778 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1780 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1784 * Function returns formatted groupTree, sothat form can be easily build in template
1786 * @param array $groupTree
1787 * @param int $groupCount
1788 * Group count by default 1, but can varry for multiple value custom data.
1789 * @param object $form
1793 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1794 $formattedGroupTree = array();
1795 $uploadNames = array();
1797 foreach ($groupTree as $key => $value) {
1798 if ($key === 'info') {
1802 // add group information
1803 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1804 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1805 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1806 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1807 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1808 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1810 // this params needed of bulding multiple values
1811 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1812 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1813 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1814 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1815 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1816 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1818 // add field information
1819 foreach ($value['fields'] as $k => $properties) {
1820 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1821 if (isset($properties['customValue']) &&
1822 !CRM_Utils_System
::isNull($properties['customValue'])
1824 if (isset($properties['customValue'][$groupCount])) {
1825 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1826 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1827 if ($properties['data_type'] == 'File') {
1828 $properties['element_value'] = $properties['customValue'][$groupCount];
1829 $uploadNames[] = $properties['element_name'];
1832 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1836 unset($properties['customValue']);
1837 $formattedGroupTree[$key]['fields'][$k] = $properties;
1842 // hack for field type File
1843 $formUploadNames = $form->get('uploadNames');
1844 if (is_array($formUploadNames)) {
1845 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1848 $form->set('uploadNames', $uploadNames);
1851 return $formattedGroupTree;
1855 * Build custom data view.
1857 * @param CRM_Core_Form $form
1859 * @param array $groupTree
1860 * @param bool $returnCount
1861 * True if customValue count needs to be returned.
1863 * @param null $prefix
1864 * @param int $customValueId
1868 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1870 foreach ($groupTree as $key => $group) {
1871 if ($key === 'info') {
1875 foreach ($group['fields'] as $k => $properties) {
1876 $groupID = $group['id'];
1877 if (!empty($properties['customValue'])) {
1878 foreach ($properties['customValue'] as $values) {
1879 if (!empty($customValueId) && $customValueId != $values['id']) {
1882 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1883 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1884 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1885 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1886 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1887 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1888 $details[$groupID][$values['id']]['fields'][$k] = array(
1889 'field_title' => CRM_Utils_Array
::value('label', $properties),
1890 'field_type' => CRM_Utils_Array
::value('html_type',
1893 'field_data_type' => CRM_Utils_Array
::value('data_type',
1896 'field_value' => self
::formatCustomValues($values,
1899 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1903 // also return contact reference contact id if user has view all or edit all contacts perm
1904 if ((CRM_Core_Permission
::check('view all contacts') ||
1905 CRM_Core_Permission
::check('edit all contacts'))
1907 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1910 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1915 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1916 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1917 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1918 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1919 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1920 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1921 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1927 //return a single value count if group id is passed to function
1928 //else return a groupId and count mapped array
1930 return count($details[$gID]);
1933 $countValue = array();
1934 foreach ($details as $key => $value) {
1935 $countValue[$key] = count($details[$key]);
1941 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1947 * Format custom value according to data, view mode
1949 * @param array $values
1950 * Associated array of custom values.
1951 * @param array $field
1952 * @param bool $dncOptionPerLine
1953 * True if optionPerLine should not be consider.
1955 * @return array|null|string
1957 public static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1958 $value = $values['data'];
1960 //changed isset CRM-4601
1961 if (CRM_Utils_System
::isNull($value)) {
1965 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1966 $dataType = CRM_Utils_Array
::value('data_type', $field);
1967 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1968 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1969 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1972 $freezeStringChecked = "";
1974 switch ($dataType) {
1976 $customFormat = NULL;
1978 $actualPHPFormats = CRM_Core_SelectValues
::datePluginToPHPFormats();
1980 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
1981 if (array_key_exists($format, $actualPHPFormats)) {
1982 $customTimeFormat = (array) CRM_Utils_Array
::value($format, $actualPHPFormats);
1983 switch ($timeFormat) {
1985 $customTimeFormat[] = 'g:iA';
1989 $customTimeFormat[] = 'G:i';
1993 // if time is not selected remove time from value
1994 $value = substr($value, 0, 10);
1996 $customFormat = implode(" ", $customTimeFormat);
1999 $retValue = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
2003 if ($value == '1') {
2004 $retValue = $freezeStringChecked . ts('Yes') . "\n";
2007 $retValue = $freezeStringChecked . ts('No') . "\n";
2013 $retValue = CRM_Utils_System
::formatWikiURL($value);
2018 $retValue = $values;
2021 case 'ContactReference':
2022 if (!empty($values['data'])) {
2023 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
2032 if ($htmlType == 'Text') {
2033 $retValue = (float) $value;
2037 if ($htmlType == 'Text') {
2038 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2043 if (in_array($htmlType, array('Text', 'TextArea'))) {
2047 // note that if its not text / textarea, the code falls thru and executes
2048 // the below case also
2049 case 'StateProvince':
2054 //added check for Multi-Select in the below if-statement
2055 $customData[] = $value;
2057 //form custom data for multiple-valued custom data
2058 switch ($htmlType) {
2059 case 'Multi-Select Country':
2060 case 'Select Country':
2061 $customData = $value;
2062 if (!is_array($value)) {
2063 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2066 SELECT id as value, name as label
2067 FROM civicrm_country";
2068 $coDAO = CRM_Core_DAO
::executeQuery($query);
2071 case 'Select State/Province':
2072 case 'Multi-Select State/Province':
2073 $customData = $value;
2074 if (!is_array($value)) {
2075 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2079 SELECT id as value, name as label
2080 FROM civicrm_state_province";
2081 $coDAO = CRM_Core_DAO
::executeQuery($query);
2085 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2086 if ($option_group_id) {
2087 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2092 case 'AdvMulti-Select':
2093 case 'Multi-Select':
2094 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2096 if ($option_group_id) {
2097 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2101 if (is_object($coDAO)) {
2102 while ($coDAO->fetch()) {
2103 if ($dataType == 'Country') {
2104 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2105 // and already extracted to .pot files.
2106 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
2108 elseif ($dataType == 'StateProvince') {
2109 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
2112 $options[$coDAO->value
] = $coDAO->label
;
2117 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
2120 foreach ($options as $optionValue => $optionLabel) {
2121 if ($dataType == 'Money') {
2122 foreach ($customData as $k => $v) {
2123 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
2127 //to show only values that are checked
2128 if (in_array((string) $optionValue, $customData)) {
2129 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
2130 if (!$optionPerLine ||
$dncOptionPerLine) {
2134 $retValue .= $checked . $optionLabel;
2137 $retValue[] = $checked . $optionLabel;
2144 //special case for option per line formatting
2145 if ($optionPerLine > 1 && is_array($retValue)) {
2148 $displayValues = array();
2149 $displayString = '';
2150 foreach ($retValue as $val) {
2151 if ($displayString) {
2152 $displayString .= ", ";
2155 $displayString .= $val;
2159 if (($rowCounter == $optionPerLine) ||
2160 ($fieldCounter == count($retValue))
2162 $displayValues[] = $displayString;
2163 $displayString = '';
2167 $retValue = $displayValues;
2170 $retValue = isset($retValue) ?
$retValue : NULL;
2175 * Get the custom group titles by custom field ids.
2177 * @param array $fieldIds
2178 * Array of custom field ids.
2180 * @return array|NULL
2181 * array consisting of groups and fields labels with ids.
2183 public static function getGroupTitles($fieldIds) {
2184 if (!is_array($fieldIds) && empty($fieldIds)) {
2188 $groupLabels = array();
2189 $fIds = "(" . implode(',', $fieldIds) . ")";
2192 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2193 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2194 FROM civicrm_custom_group, civicrm_custom_field
2195 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2196 AND civicrm_custom_field.id IN {$fIds}";
2198 $dao = CRM_Core_DAO
::executeQuery($query);
2199 while ($dao->fetch()) {
2200 $groupLabels[$dao->fieldID
] = array(
2201 'fieldID' => $dao->fieldID
,
2202 'fieldLabel' => $dao->fieldLabel
,
2203 'groupID' => $dao->groupID
,
2204 'groupTitle' => $dao->groupTitle
,
2208 return $groupLabels;
2211 public static function dropAllTables() {
2212 $query = "SELECT table_name FROM civicrm_custom_group";
2213 $dao = CRM_Core_DAO
::executeQuery($query);
2215 while ($dao->fetch()) {
2216 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2217 CRM_Core_DAO
::executeQuery($query);
2222 * Check whether custom group is empty or not.
2228 * true if empty otherwise false.
2230 public static function isGroupEmpty($gID) {
2235 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2240 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2241 $value = CRM_Core_DAO
::singleValueQuery($query);
2243 if (empty($value)) {
2251 * Get the list of types for objects that a custom group extends to.
2253 * @param array $types
2254 * Var which should have the list appended.
2259 public static function getExtendedObjectTypes(&$types = array()) {
2260 static $flag = FALSE, $objTypes = array();
2263 $extendObjs = array();
2264 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2266 foreach ($extendObjs as $ovId => $ovValues) {
2267 if ($ovValues['description']) {
2268 // description is expected to be a callback func to subtypes
2269 list($callback, $args) = explode(';', trim($ovValues['description']));
2275 if (!is_array($args)) {
2276 CRM_Core_Error
::fatal('Arg is not of type array');
2279 list($className) = explode('::', $callback);
2280 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2283 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2289 $types = array_merge($types, $objTypes);
2294 * @param int $customGroupId
2295 * @param int $entityId
2299 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2300 //check whether the group is multiple
2301 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2302 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2303 $hasReachedMax = FALSE;
2305 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2307 if (!$maxMultiple) {
2308 $hasReachedMax = FALSE;
2311 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2312 //count the number of entries for a entity
2313 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2314 $params = array(1 => array($entityId, 'Integer'));
2315 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2317 if ($count >= $maxMultiple) {
2318 $hasReachedMax = TRUE;
2322 return $hasReachedMax;
2328 public static function getMultipleFieldGroup() {
2329 $multipleGroup = array();
2330 $dao = new CRM_Core_DAO_CustomGroup();
2331 $dao->is_multiple
= 1;
2333 while ($dao->fetch()) {
2334 $multipleGroup[$dao->id
] = $dao->title
;
2336 return $multipleGroup;