3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * Business object for managing custom data groups
40 class CRM_Core_BAO_CustomGroup
extends CRM_Core_DAO_CustomGroup
{
45 public function __construct() {
46 parent
::__construct();
50 * Takes an associative array and creates a custom group object
52 * This function is invoked from within the web form layer and also from the api layer
54 * @param array $params (reference) an assoc array of name/value pairs
56 * @return CRM_Core_DAO_CustomGroup object
59 public static function create(&$params) {
60 // create custom group dao, populate fields and then save.
61 $group = new CRM_Core_DAO_CustomGroup();
62 $group->title
= $params['title'];
64 if (in_array($params['extends'][0],
67 'ParticipantEventName',
68 'ParticipantEventType',
71 $group->extends = 'Participant';
74 $group->extends = $params['extends'][0];
77 $group->extends_entity_column_id
= 'null';
79 $params['extends'][0] == 'ParticipantRole' ||
80 $params['extends'][0] == 'ParticipantEventName' ||
81 $params['extends'][0] == 'ParticipantEventType'
83 $group->extends_entity_column_id
=
84 CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $params['extends'][0], 'value', 'name');
87 //this is format when form get submit.
88 $extendsChildType = CRM_Utils_Array
::value(1, $params['extends']);
89 //lets allow user to pass direct child type value, CRM-6893
90 if (!empty($params['extends_entity_column_value'])) {
91 $extendsChildType = $params['extends_entity_column_value'];
93 if (!CRM_Utils_System
::isNull($extendsChildType)) {
94 $extendsChildType = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendsChildType);
95 if (CRM_Utils_Array
::value(0, $params['extends']) == 'Relationship') {
96 $extendsChildType = str_replace(array('_a_b', '_b_a'), array(
99 ), $extendsChildType);
101 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
102 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType .
103 CRM_Core_DAO
::VALUE_SEPARATOR
;
107 $extendsChildType = 'null';
109 $group->extends_entity_column_value
= $extendsChildType;
111 if (isset($params['id'])) {
112 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
117 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
121 'collapse_adv_display',
127 foreach ($fields as $field) {
128 $group->$field = CRM_Utils_Array
::value($field, $params, FALSE);
130 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
131 $params['max_multiple'] >= '0'
132 ) ?
$params['max_multiple'] : 'null' : 'null';
134 $tableName = $oldTableName = NULL;
135 if (isset($params['id'])) {
136 $group->id
= $params['id'];
137 //check whether custom group was changed from single-valued to multiple-valued
138 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
143 if ((!empty($params['is_multiple']) ||
$isMultiple) &&
144 ($params['is_multiple'] != $isMultiple)
146 $oldTableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
153 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
154 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
156 // we do this only once, so name never changes
157 if (isset($params['name'])) {
158 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
161 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
164 if (isset($params['table_name'])) {
165 $tableName = $params['table_name'];
167 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
168 // Bad idea. Prevent group creation because it might lead to a broken configuration.
169 CRM_Core_Error
::fatal(ts("Cannot create custom table because %1 is already a core table.", array('1' => $tableName)));
174 if (array_key_exists('is_reserved', $params)) {
175 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
177 $op = isset($params['id']) ?
'edit' : 'create';
178 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
180 // enclose the below in a transaction
181 $transaction = new CRM_Core_Transaction();
184 if (!isset($params['id'])) {
185 if (!isset($params['table_name'])) {
186 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 42));
187 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
189 $group->table_name
= $tableName;
190 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
196 // now create the table associated with this group
197 self
::createTable($group);
199 elseif ($oldTableName) {
200 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($oldTableName, CRM_Utils_Array
::value('is_multiple', $params));
203 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
204 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
208 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends'][0]));
210 $transaction->commit();
213 CRM_Utils_System
::flushCache();
216 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
219 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
226 * Fetch object based on array of properties
228 * @param array $params (reference ) an assoc array of name/value pairs
229 * @param array $defaults (reference ) an assoc array to hold the flattened values
231 * @return CRM_Core_DAO_CustomGroup object
234 public static function retrieve(&$params, &$defaults) {
235 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
239 * Update the is_active flag in the db
241 * @param int $id id of the database record
242 * @param boolean $is_active value we want to set the is_active field
244 * @return Object 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 e.g. "Individual", "Activity"
262 * @param int $columnId e.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id
263 * @param string $columnValue e.g. "Student" or "3" or "3\05"; see extends_entity_column_value
267 public static function hasCustomGroup($extends, $columnId, $columnValue) {
268 $dao = new CRM_Core_DAO_CustomGroup();
269 $dao->extends = $extends;
270 $dao->extends_entity_column_id
= $columnId;
272 CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) .
273 CRM_Core_DAO
::VALUE_SEPARATOR
;
274 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
275 //$dao->extends_entity_column_value = $columnValue;
276 return $dao->find() ?
TRUE : FALSE;
280 * Determine if there are any CustomGroups for the given $activityTypeId.
281 * If none found, create one.
283 * @param int $activityTypeId
285 * @return bool TRUE if a group is found or created; FALSE on error
287 public static function autoCreateByActivityType($activityTypeId) {
288 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
291 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
294 'extends' => 'Activity',
295 'extends_entity_column_id' => NULL,
296 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
297 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
301 $result = civicrm_api('CustomGroup', 'create', $params);
302 return !$result['is_error'];
306 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
307 * This may also include entity specific data values.
309 * An array containing all custom groups and their custom fields is returned.
311 * @param string $entityType - of the contact whose contact type is needed
312 * @param CRM_Core_Form $form - not used but required
313 * @param int $entityID
314 * @param int $groupID
315 * @param string $subType
316 * @param string $subName
317 * @param bool $fromCache
318 * @param bool $onlySubType
320 * @return array $groupTree - array The returned array is keyed by group id and has the custom group table fields
321 * and a subkey 'fields' holding the specific custom fields.
322 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
323 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
325 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
326 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
327 * With caching the performance impact would be small & the function would be cleaner
332 public static function &getTree(
343 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
347 $strSelect = $strFrom = $strWhere = $orderBy = '';
348 $tableData = array();
350 // using tableData to build the queryString
352 'civicrm_custom_field' => array(
372 'civicrm_custom_group' => array(
382 'extends_entity_column_id',
383 'extends_entity_column_value',
390 foreach ($tableData as $tableName => $tableColumn) {
391 foreach ($tableColumn as $columnName) {
392 $alias = $tableName . "_" . $columnName;
393 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
396 $strSelect = "SELECT " . implode(', ', $select);
398 // from, where, order by
400 FROM civicrm_custom_group
401 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
404 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
405 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
406 $entityType == 'Household'
408 $in = "'$entityType', 'Contact'";
410 elseif (strpos($entityType, "'") !== FALSE) {
411 // this allows the calling function to send in multiple entity types
416 $in = "'$entityType'";
421 if (is_array($subType)) {
422 $subType = implode(',', $subType);
424 if (strpos($subType, ',')) {
425 $subTypeParts = explode(',', $subType);
426 $subTypeClauses = array();
427 foreach ($subTypeParts as $subTypePart) {
428 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
.
429 trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) .
430 CRM_Core_DAO
::VALUE_SEPARATOR
;
431 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
435 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
438 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) .
439 " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
443 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
.
444 trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) .
445 CRM_Core_DAO
::VALUE_SEPARATOR
;
448 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
451 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
452 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
457 WHERE civicrm_custom_group.is_active = 1
458 AND civicrm_custom_field.is_active = 1
459 AND civicrm_custom_group.extends IN ($in)
463 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
468 WHERE civicrm_custom_group.is_active = 1
469 AND civicrm_custom_field.is_active = 1
470 AND civicrm_custom_group.extends IN ($in)
471 AND civicrm_custom_group.extends_entity_column_value IS NULL
477 // since we want a specific group id we add it to the where clause
478 $strWhere .= " AND civicrm_custom_group.id = %1";
479 $params[1] = array($groupID, 'Integer');
482 // since groupID is false we need to show all Inline groups
483 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
486 // ensure that the user has access to these custom groups
487 $strWhere .= " AND " .
488 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
489 'civicrm_custom_group.'
493 ORDER BY civicrm_custom_group.weight,
494 civicrm_custom_group.title,
495 civicrm_custom_field.weight,
496 civicrm_custom_field.label
499 // final query string
500 $queryString = "$strSelect $strFrom $strWhere $orderBy";
502 // lets see if we can retrieve the groupTree from cache
503 $cacheString = $queryString;
505 $cacheString .= "_{$groupID}";
508 $cacheString .= "_Inline";
511 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
512 $multipleFieldGroupCacheKey =
513 "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
514 $cache = CRM_Utils_Cache
::singleton();
515 $tablesWithEntityData = array();
517 $groupTree = $cache->get($cacheKey);
518 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
521 if (empty($groupTree)) {
522 $groupTree = $multipleFieldGroups = array();
523 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
524 $customValueTables = array();
527 while ($crmDAO->fetch()) {
529 $groupID = $crmDAO->civicrm_custom_group_id
;
530 $fieldId = $crmDAO->civicrm_custom_field_id
;
531 if ($crmDAO->civicrm_custom_group_is_multiple
) {
532 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
534 // create an array for groups if it does not exist
535 if (!array_key_exists($groupID, $groupTree)) {
536 $groupTree[$groupID] = array();
537 $groupTree[$groupID]['id'] = $groupID;
539 // populate the group information
540 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
541 $fullFieldName = "civicrm_custom_group_$fieldName";
542 if ($fieldName == 'id' ||
543 is_null($crmDAO->$fullFieldName)
548 if ($fieldName == 'extends_entity_column_value' && $subType) {
549 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
551 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
553 $groupTree[$groupID]['fields'] = array();
555 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
558 // add the fields now (note - the query row will always contain a field)
559 // we only reset this once, since multiple values come is as multiple rows
560 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
561 $groupTree[$groupID]['fields'][$fieldId] = array();
564 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
565 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
566 // populate information for a custom field
567 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
568 $fullFieldName = "civicrm_custom_field_$fieldName";
569 if ($fieldName == 'id' ||
570 is_null($crmDAO->$fullFieldName)
574 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
578 if (!empty($customValueTables)) {
579 $groupTree['info'] = array('tables' => $customValueTables);
582 $cache->set($cacheKey, $groupTree);
583 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
585 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
586 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
587 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
588 $singleFieldTables = array();
589 // now that we have all the groups and fields, lets get the values
590 // since we need to know the table and field names
591 // add info to groupTree
593 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
594 !empty($groupTree['info']['tables'])
596 $select = $from = $where = array();
597 $groupTree['info']['where'] = NULL;
599 foreach ($groupTree['info']['tables'] as $table => $fields) {
600 $groupTree['info']['from'][] = $table;
602 "{$table}.id as {$table}_id",
603 "{$table}.entity_id as {$table}_entity_id"
605 foreach ($fields as $column => $dontCare) {
606 $select[] = "{$table}.{$column} as {$table}_{$column}";
608 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
610 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
611 if (in_array($table, $multipleFieldGroups) &&
612 self
::customGroupDataExistsForEntity($entityID, $table)
614 $entityMultipleSelectClauses[$table] = $select;
617 $singleFieldTables[] = $table;
618 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
623 if ($entityID && !empty($singleFieldTables)) {
624 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
626 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
627 if (!empty($multipleFieldTablesWithEntityData)) {
628 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
636 * Check whether the custom group has any data for the given entity.
639 * @param integer $entityID id of entity for whom we are checking data for
640 * @param string $table table that we are checking
642 * @param bool $getCount
644 * @return boolean does this entity have data in this custom table
646 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
650 WHERE entity_id = $entityID
652 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
654 return $recordExists;
656 return $recordExists ?
TRUE : FALSE;
660 * Build the group tree for Custom fields which are not 'is_multiple'
662 * The combination of all these fields in one query with a 'using' join was not working for
663 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
664 * mechanism as it seemed to be acceptable in this context
666 * @param array $groupTree (reference) group tree array which is being built
667 * @param integer $entityID id of entity for whom the tree is being build up.
668 * @param array $entitySingleSelectClauses array of select clauses relevant to the entity
669 * @param array $singleFieldTablesWithEntityData array of tables in which this entity has data
671 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
672 $select = implode(', ', $entitySingleSelectClauses);
673 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
674 foreach ($singleFieldTablesWithEntityData as $table) {
675 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
681 WHERE first.entity_id = $entityID
683 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
687 * Build the group tree for Custom fields which are 'is_multiple'
689 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
691 * @param array $groupTree (reference) group tree array which is being built
692 * @param integer $entityID id of entity for whom the tree is being build up.
693 * @param array $entityMultipleSelectClauses array of select clauses relevant to the entity
694 * @param array $multipleFieldTablesWithEntityData array of tables in which this entity has data
696 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData) {
697 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
698 $select = implode(',', $selectClauses);
702 WHERE entity_id = $entityID
704 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
709 * Build the tree entity data - starting from a query retrieving the custom fields build the group
710 * tree data for the relevant entity (entity is included in the query).
712 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
714 * @param array $groupTree (reference) group tree array which is being built
715 * @param string $query
716 * @param array $includedTables tables to include - required because the function (for historical reasons)
717 * iterates through the group tree
719 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables) {
720 $dao = CRM_Core_DAO
::executeQuery($query);
721 while ($dao->fetch()) {
722 foreach ($groupTree as $groupID => $group) {
723 if ($groupID === 'info') {
726 $table = $groupTree[$groupID]['table_name'];
727 //working from the groupTree instead of the table list means we have to iterate & exclude.
728 // this could possibly be re-written as other parts of the function have been refactored
729 // for now we just check if the given table is to be included in this function
730 if (!in_array($table, $includedTables)) {
733 foreach ($group['fields'] as $fieldID => $dontCare) {
734 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
741 * Build the entity-specific custom data into the group tree on a per-field basis
743 * @param object $dao object representing the custom field to be populated into the groupTree
744 * @param array $groupTree (reference) the group tree being build
745 * @param string $table table name
746 * @param unknown_type $groupID custom group ID
747 * @param unknown_type $fieldID custom field ID
749 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID) {
750 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
751 $idName = "{$table}_id";
752 $fieldName = "{$table}_{$column}";
753 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
754 if ($dataType == 'File') {
755 if (isset($dao->$fieldName)) {
756 $config = CRM_Core_Config
::singleton();
757 $fileDAO = new CRM_Core_DAO_File();
758 $fileDAO->id
= $dao->$fieldName;
760 if ($fileDAO->find(TRUE)) {
761 $entityIDName = "{$table}_entity_id";
762 $customValue['id'] = $dao->$idName;
763 $customValue['data'] = $fileDAO->uri
;
764 $customValue['fid'] = $fileDAO->id
;
765 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
766 $customValue['displayURL'] = NULL;
767 $deleteExtra = ts('Are you sure you want to delete attached file.');
769 CRM_Core_Action
::DELETE
=> array(
770 'name' => ts('Delete Attached File'),
771 'url' => 'civicrm/file',
772 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
773 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra .
774 '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
777 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
778 CRM_Core_Action
::DELETE
,
780 'id' => $fileDAO->id
,
781 'eid' => $dao->$entityIDName,
786 'file.manage.delete',
790 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
791 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
792 if ($fileDAO->mime_type
== "image/jpeg" ||
793 $fileDAO->mime_type
== "image/pjpeg" ||
794 $fileDAO->mime_type
== "image/gif" ||
795 $fileDAO->mime_type
== "image/x-png" ||
796 $fileDAO->mime_type
== "image/png"
798 $customValue['displayURL'] = $customValue['fileURL'];
799 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
804 $customValue['imageURL'] =
805 str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
807 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId,
810 if ($path && file_exists($path)) {
811 list($imageWidth, $imageHeight) = getimagesize($path);
812 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
813 $customValue['imageThumbWidth'] = $imageThumbWidth;
814 $customValue['imageThumbHeight'] = $imageThumbHeight;
820 $customValue = array(
821 'id' => $dao->$idName,
827 $customValue = array(
828 'id' => $dao->$idName,
829 'data' => $dao->$fieldName,
833 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
834 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
836 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
837 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
840 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
845 * Get the group title.
847 * @param int $id id of group.
849 * @return string title
854 public static function getTitle($id) {
855 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
859 * Get custom group details for a group.
861 * An array containing custom group details (including their custom field) is returned.
863 * @param int $groupId - group id whose details are needed
864 * @param boolean $searchable - is this field searchable
865 * @param array $extends - which table does it extend if any
867 * @param null $inSelector
869 * @return array $groupTree - array consisting of all group and field details
874 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
876 $groupTree = array();
877 $select = $from = $where = $orderBy = '';
879 $tableData = array();
881 // using tableData to build the queryString
883 'civicrm_custom_field' => array(
907 'civicrm_custom_group' => array(
914 'collapse_adv_display',
916 'extends_entity_column_value',
925 foreach ($tableData as $tableName => $tableColumn) {
926 foreach ($tableColumn as $columnName) {
927 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
930 $select = 'SELECT ' . implode(', ', $s);
932 // from, where, order by
933 $from = " FROM civicrm_custom_field, civicrm_custom_group";
934 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
935 AND civicrm_custom_group.is_active = 1
936 AND civicrm_custom_field.is_active = 1 ";
938 $params[1] = array($groupId, 'Integer');
939 $where .= " AND civicrm_custom_group.id = %1";
943 $where .= " AND civicrm_custom_field.is_searchable = 1";
947 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
952 foreach ($extends as $e) {
953 $clause[] = "civicrm_custom_group.extends = '$e'";
955 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
957 //include case activities customdata if case is enabled
958 if (in_array('Activity', $extends)) {
959 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
960 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
961 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
965 // ensure that the user has access to these custom groups
967 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
968 'civicrm_custom_group.'
971 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
973 // final query string
974 $queryString = $select . $from . $where . $orderBy;
977 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
980 while ($crmDAO->fetch()) {
981 $groupId = $crmDAO->civicrm_custom_group_id
;
982 $fieldId = $crmDAO->civicrm_custom_field_id
;
984 // create an array for groups if it does not exist
985 if (!array_key_exists($groupId, $groupTree)) {
986 $groupTree[$groupId] = array();
987 $groupTree[$groupId]['id'] = $groupId;
989 foreach ($tableData['civicrm_custom_group'] as $v) {
990 $fullField = "civicrm_custom_group_" . $v;
992 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
996 $groupTree[$groupId][$v] = $crmDAO->$fullField;
999 $groupTree[$groupId]['fields'] = array();
1002 // add the fields now (note - the query row will always contain a field)
1003 $groupTree[$groupId]['fields'][$fieldId] = array();
1004 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1006 foreach ($tableData['civicrm_custom_field'] as $v) {
1007 $fullField = "civicrm_custom_field_" . $v;
1008 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1011 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1019 * @param $entityType
1021 * @param string $cidToken
1025 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1027 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1029 // get 'Tab' and 'Tab with table' groups
1030 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1031 $customGroupDAO->whereAdd("is_active = 1");
1033 // add whereAdd for entity type
1034 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1038 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1039 $customGroupDAO->whereAdd($permissionClause);
1042 $customGroupDAO->orderBy('weight');
1043 $customGroupDAO->find();
1045 // process each group with menu tab
1046 while ($customGroupDAO->fetch()) {
1048 $group['id'] = $customGroupDAO->id
;
1049 $group['path'] = $path;
1050 $group['title'] = "$customGroupDAO->title";
1051 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1052 $group['extra'] = array('gid' => $customGroupDAO->id
);
1053 $group['table_name'] = $customGroupDAO->table_name
;
1054 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1062 * Get the table name for the entity type
1063 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1064 * tableName is 'civicrm_contact'
1066 * @param string $entityType what entity are we extending here ?
1068 * @return string $tableName
1072 * @see _apachesolr_civiAttachments_dereference_file_parent
1074 public static function getTableNameByEntityName($entityType) {
1076 switch ($entityType) {
1080 case 'Organization':
1081 $tableName = 'civicrm_contact';
1084 case 'Contribution':
1085 $tableName = 'civicrm_contribution';
1089 $tableName = 'civicrm_group';
1091 // DRAFTING: Verify if we cannot make it pluggable
1094 $tableName = 'civicrm_activity';
1097 case 'Relationship':
1098 $tableName = 'civicrm_relationship';
1102 $tableName = 'civicrm_membership';
1106 $tableName = 'civicrm_participant';
1110 $tableName = 'civicrm_event';
1114 $tableName = 'civicrm_grant';
1116 // need to add cases for Location, Address
1123 * Get a list of custom groups which extend a given entity type.
1124 * If there are custom-groups which only apply to certain subtypes,
1125 * those WILL be included.
1127 * @param $entityType string
1129 * @return CRM_Core_DAO_CustomGroup
1131 public static function getAllCustomGroupsByBaseEntity($entityType) {
1132 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1133 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1134 return $customGroupDAO;
1138 * Add the whereAdd clause for the DAO depending on the type of entity
1139 * the custom group is extending.
1141 * @param $customGroupDAO
1142 * @param string $entityType - what entity are we extending here ?
1144 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
1145 * @param bool $allSubtypes
1151 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1152 $addSubtypeClause = FALSE;
1154 switch ($entityType) {
1156 // if contact, get all related to contact
1157 $extendList = "'Contact','Individual','Household','Organization'";
1158 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1159 if (!$allSubtypes) {
1160 $addSubtypeClause = TRUE;
1166 case 'Organization':
1167 // is I/H/O then get I/H/O and contact
1168 $extendList = "'Contact','$entityType'";
1169 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1170 if (!$allSubtypes) {
1171 $addSubtypeClause = TRUE;
1179 case 'Contribution':
1182 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1186 if ($addSubtypeClause) {
1187 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1189 if (!empty($csType)) {
1190 $subtypeClause = array();
1191 foreach ($csType as $subtype) {
1192 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1193 CRM_Core_DAO
::VALUE_SEPARATOR
;
1194 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1196 $subtypeClause[] = "extends_entity_column_value IS NULL";
1197 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1201 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1207 * Delete the Custom Group.
1209 * @param $group object the DAO custom group object
1210 * @param $force boolean whether to force the deletion, even if there are custom fields
1212 * @return boolean false if field exists for this group, true if group gets deleted.
1217 public static function deleteGroup($group, $force = FALSE) {
1219 //check wheter this contain any custom fields
1220 $customField = new CRM_Core_DAO_CustomField();
1221 $customField->custom_group_id
= $group->id
;
1222 $customField->find();
1224 // return early if there are custom fields and we're not
1225 // forcing the delete, otherwise delete the fields one by one
1226 while ($customField->fetch()) {
1230 CRM_Core_BAO_CustomField
::deleteField($customField);
1233 // drop the table associated with this custom group
1234 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1236 //delete custom group
1239 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1247 * @param bool $viewMode
1248 * @param bool $inactiveNeeded
1249 * @param int $action
1251 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1252 foreach ($groupTree as $id => $group) {
1253 if (!isset($group['fields'])) {
1256 foreach ($group['fields'] as $field) {
1257 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1258 $value = $field['element_value'];
1260 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1261 ($action != CRM_Core_Action
::UPDATE ||
1263 !array_key_exists('element_value', $field)
1266 $value = $viewMode ?
NULL : $field['default_value'];
1272 if (!empty($field['element_name'])) {
1273 $elementName = $field['element_name'];
1275 switch ($field['html_type']) {
1276 case 'Multi-Select':
1277 case 'AdvMulti-Select':
1279 $defaults[$elementName] = array();
1280 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1282 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1283 if (isset($value)) {
1284 foreach ($customOption as $customValue => $customLabel) {
1285 if (in_array($customValue, $checkedData)) {
1286 if ($field['html_type'] == 'CheckBox') {
1287 $defaults[$elementName][$customValue] = 1;
1290 $defaults[$elementName][$customValue] = $customValue;
1294 $defaults[$elementName][$customValue] = 0;
1300 if (isset($field['customValue']['data'])) {
1301 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1302 foreach ($customOption as $val) {
1303 if (in_array($val['value'], $checkedData)) {
1304 if ($field['html_type'] == 'CheckBox') {
1305 $defaults[$elementName][$val['value']] = 1;
1308 $defaults[$elementName][$val['value']] = $val['value'];
1312 $defaults[$elementName][$val['value']] = 0;
1317 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1318 foreach ($customOption as $val) {
1319 if (in_array($val['value'], $checkedValue)) {
1320 if ($field['html_type'] == 'CheckBox') {
1321 $defaults[$elementName][$val['value']] = 1;
1324 $defaults[$elementName][$val['value']] = $val['value'];
1333 if (isset($value)) {
1334 if (empty($field['time_format'])) {
1335 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1336 $field['date_format']
1340 $timeElement = $elementName . '_time';
1341 if (substr($elementName, -1) == ']') {
1342 $timeElement = substr($elementName, 0, -1) . '_time]';
1344 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1349 case 'Multi-Select Country':
1350 case 'Multi-Select State/Province':
1351 if (isset($value)) {
1352 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1353 foreach ($checkedValue as $val) {
1355 $defaults[$elementName][$val] = $val;
1361 case 'Select Country':
1363 $defaults[$elementName] = $value;
1366 $config = CRM_Core_Config
::singleton();
1367 $defaults[$elementName] = $config->defaultContactCountry
;
1372 if ($field['data_type'] == "Float") {
1373 $defaults[$elementName] = (float) $value;
1375 elseif ($field['data_type'] == 'Money' &&
1376 $field['html_type'] == 'Text'
1378 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1381 $defaults[$elementName] = $value;
1390 * @param array $params
1391 * @param bool $skipFile
1393 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1394 // Get the Custom form values and groupTree
1395 // first reset all checkbox and radio data
1396 foreach ($groupTree as $groupID => $group) {
1397 if ($groupID === 'info') {
1400 foreach ($group['fields'] as $field) {
1401 $fieldId = $field['id'];
1403 //added Multi-Select option in the below if-statement
1404 if ($field['html_type'] == 'CheckBox' ||
1405 $field['html_type'] == 'Radio' ||
1406 $field['html_type'] == 'AdvMulti-Select' ||
1407 $field['html_type'] == 'Multi-Select'
1409 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1413 foreach ($params as $key => $val) {
1414 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1415 $match[1] == $field['id']
1422 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1423 // field exists in db so populate value from "form".
1424 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1427 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1429 //added for CheckBox
1433 $customValue = array_keys($v);
1434 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] =
1435 CRM_Core_DAO
::VALUE_SEPARATOR
.
1436 implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue) .
1437 CRM_Core_DAO
::VALUE_SEPARATOR
;
1440 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1444 //added for Advanced Multi-Select
1446 case 'AdvMulti-Select':
1447 //added for Multi-Select
1448 case 'Multi-Select':
1450 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] =
1451 CRM_Core_DAO
::VALUE_SEPARATOR
.
1452 implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v) .
1453 CRM_Core_DAO
::VALUE_SEPARATOR
;
1456 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1461 $date = CRM_Utils_Date
::processDate($v);
1462 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1470 //store the file in d/b
1471 $entityId = explode('=', $groupTree['info']['where'][0]);
1472 $fileParams = array('upload_date' => date('Ymdhis'));
1474 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1475 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1478 $fileParams['uri'] = $v['name'];
1479 $fileParams['mime_type'] = $v['type'];
1480 CRM_Core_BAO_File
::filePostProcess($v['name'],
1481 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1482 $groupTree[$groupID]['table_name'],
1487 'custom_' . $fieldId,
1491 $defaults = array();
1492 $paramsFile = array(
1493 'entity_table' => $groupTree[$groupID]['table_name'],
1494 'entity_id' => $entityId[1],
1497 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1502 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1506 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1514 * Generic function to build all the form elements for a specific group tree
1516 * @param CRM_Core_Form $form the form object
1517 * @param array $groupTree the group tree object
1518 * @param boolean $inactiveNeeded return inactive custom groups
1519 * @param string $prefix prefix for custom grouptree assigned to template
1524 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1525 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1527 // this is fix for date field
1528 $form->assign('currentYear', date('Y'));
1530 foreach ($groupTree as $id => $group) {
1531 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1532 foreach ($group['fields'] as $field) {
1533 $required = CRM_Utils_Array
::value('is_required', $field);
1535 if ($field['data_type'] == 'File') {
1536 if (!empty($field['element_value']['data'])) {
1541 $fieldId = $field['id'];
1542 $elementName = $field['element_name'];
1543 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1549 * Extract the get params from the url, validate
1550 * and store it in session
1552 * @param CRM_Core_Form $form the form object
1553 * @param string $type the type of custom group we are using
1558 public static function extractGetParams(&$form, $type) {
1563 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1564 $customValue = array();
1573 foreach ($groupTree as $group) {
1574 if (!isset($group['fields'])) {
1577 foreach ($group['fields'] as $key => $field) {
1578 $fieldName = 'custom_' . $key;
1579 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1583 if (!in_array($field['html_type'], $htmlType) ||
1584 $field['data_type'] == 'Boolean'
1586 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1588 if ($field['html_type'] == 'CheckBox' ||
1589 $field['html_type'] == 'AdvMulti-Select' ||
1590 $field['html_type'] == 'Multi-Select'
1592 $value = str_replace("|", ",", $value);
1593 $mulValues = explode(',', $value);
1594 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1596 foreach ($mulValues as $v1) {
1597 foreach ($customOption as $coID => $coValue) {
1598 if (strtolower(trim($coValue['label'])) ==
1599 strtolower(trim($v1))
1601 $val[$coValue['value']] = 1;
1613 elseif ($field['html_type'] == 'Select' ||
1614 ($field['html_type'] == 'Radio' &&
1615 $field['data_type'] != 'Boolean'
1618 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1619 foreach ($customOption as $customID => $coValue) {
1620 if (strtolower(trim($coValue['label'])) ==
1621 strtolower(trim($value))
1623 $value = $coValue['value'];
1628 elseif ($field['data_type'] == 'Date') {
1629 if (!empty($value)) {
1631 if (!empty($field['time_format'])) {
1632 $time = CRM_Utils_Request
::retrieve($fieldName .
1633 '_time', 'String', $form, FALSE, NULL, 'GET');
1635 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value .
1637 if (!empty($field['time_format'])) {
1638 $customValue[$fieldName . '_time'] = $time;
1645 $customValue[$fieldName] = $value;
1651 return $customValue;
1655 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1656 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1658 * @param int $customFieldId custom field id
1659 * @param array $removeCustomFieldTypes remove custom fields of a type eg: array("Individual") ;
1662 * @return boolean false if it matches else true
1665 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1666 $query = "SELECT cg.extends as extends
1667 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1668 WHERE cg.id = cf.custom_group_id
1670 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1672 $extends = CRM_Core_DAO
::singleValueQuery($query);
1674 if (in_array($extends, $removeCustomFieldTypes)) {
1686 public static function mapTableName($table) {
1691 case 'Organization':
1692 return 'civicrm_contact';
1695 return 'civicrm_activity';
1698 return 'civicrm_group';
1700 case 'Contribution':
1701 return 'civicrm_contribution';
1703 case 'Relationship':
1704 return 'civicrm_relationship';
1707 return 'civicrm_event';
1710 return 'civicrm_membership';
1713 case 'ParticipantRole':
1714 case 'ParticipantEventName':
1715 case 'ParticipantEventType':
1716 return 'civicrm_participant';
1719 return 'civicrm_grant';
1722 return 'civicrm_pledge';
1725 return 'civicrm_address';
1728 return 'civicrm_campaign';
1732 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1733 $qParams = array(1 => array($table, 'String'));
1734 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1737 return 'civicrm_contact';
1740 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1741 if (array_key_exists($table, $extendObjs)) {
1742 return $extendObjs[$table];
1744 CRM_Core_Error
::fatal();
1752 public static function createTable($group) {
1754 'name' => $group->table_name
,
1755 'is_multiple' => $group->is_multiple ?
1 : 0,
1756 'extends_name' => self
::mapTableName($group->extends),
1759 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1761 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1765 * Function returns formatted groupTree, sothat form can be easily build in template
1767 * @param array $groupTree associated array
1768 * @param int $groupCount group count by default 1, but can varry for multiple value custom data
1769 * @param object form object
1771 * @return array $formattedGroupTree
1773 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1774 $formattedGroupTree = array();
1775 $uploadNames = array();
1777 foreach ($groupTree as $key => $value) {
1778 if ($key === 'info') {
1782 // add group information
1783 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1784 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1785 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1786 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1787 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1788 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1790 // this params needed of bulding multiple values
1791 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1792 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1793 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1794 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1795 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1796 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1798 // add field information
1799 foreach ($value['fields'] as $k => $properties) {
1800 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1801 if (isset($properties['customValue']) &&
1802 !CRM_Utils_System
::isNull($properties['customValue'])
1804 if (isset($properties['customValue'][$groupCount])) {
1805 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1806 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1807 if ($properties['data_type'] == 'File') {
1808 $properties['element_value'] = $properties['customValue'][$groupCount];
1809 $uploadNames[] = $properties['element_name'];
1812 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1816 unset($properties['customValue']);
1817 $formattedGroupTree[$key]['fields'][$k] = $properties;
1822 // hack for field type File
1823 $formUploadNames = $form->get('uploadNames');
1824 if (is_array($formUploadNames)) {
1825 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1828 $form->set('uploadNames', $uploadNames);
1831 return $formattedGroupTree;
1835 * Build custom data view
1837 * @param CRM_Core_Form $form page object
1838 * @param array $groupTree associated array
1839 * @param boolean $returnCount true if customValue count needs to be returned
1841 * @param null $prefix
1842 * @param int $customValueId
1846 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1848 foreach ($groupTree as $key => $group) {
1849 if ($key === 'info') {
1853 foreach ($group['fields'] as $k => $properties) {
1854 $groupID = $group['id'];
1855 if (!empty($properties['customValue'])) {
1856 foreach ($properties['customValue'] as $values) {
1857 if (!empty($customValueId) && $customValueId != $values['id']) {
1860 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1861 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1862 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1863 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1864 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1865 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1866 $details[$groupID][$values['id']]['fields'][$k] = array(
1867 'field_title' => CRM_Utils_Array
::value('label', $properties),
1868 'field_type' => CRM_Utils_Array
::value('html_type',
1871 'field_data_type' => CRM_Utils_Array
::value('data_type',
1874 'field_value' => self
::formatCustomValues($values,
1877 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1881 // also return contact reference contact id if user has view all or edit all contacts perm
1882 if ((CRM_Core_Permission
::check('view all contacts') ||
1883 CRM_Core_Permission
::check('edit all contacts'))
1885 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1888 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1893 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1894 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1895 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1896 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1897 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1898 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1899 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1905 //return a single value count if group id is passed to function
1906 //else return a groupId and count mapped array
1908 return count($details[$gID]);
1911 $countValue = array();
1912 foreach ($details as $key => $value) {
1913 $countValue[$key] = count($details[$key]);
1919 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1925 * Format custom value according to data, view mode
1927 * @param array $values associated array of custom values
1928 * @param array $field associated array
1929 * @param boolean $dncOptionPerLine true if optionPerLine should not be consider
1931 * @return array|null|string
1933 public static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1934 $value = $values['data'];
1936 //changed isset CRM-4601
1937 if (CRM_Utils_System
::isNull($value)) {
1941 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1942 $dataType = CRM_Utils_Array
::value('data_type', $field);
1943 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1944 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1945 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1948 $freezeStringChecked = "";
1950 switch ($dataType) {
1952 $customTimeFormat = '';
1953 $customFormat = NULL;
1955 switch ($timeFormat) {
1957 $customTimeFormat = '%l:%M %P';
1961 $customTimeFormat = '%H:%M';
1965 // if time is not selected remove time from value
1966 $value = substr($value, 0, 10);
1969 $supportableFormats = array(
1970 'mm/dd' => "%B %E%f $customTimeFormat",
1971 'dd-mm' => "%E%f %B $customTimeFormat",
1972 'yy' => "%Y $customTimeFormat",
1973 'M yy' => "%b %Y $customTimeFormat",
1974 'yy-mm' => "%Y-%m $customTimeFormat"
1977 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
1978 if (array_key_exists($format, $supportableFormats)) {
1979 $customFormat = $supportableFormats["$format"];
1983 $retValue = CRM_Utils_Date
::customFormat($value, $customFormat);
1987 if ($value == '1') {
1988 $retValue = $freezeStringChecked . ts('Yes') . "\n";
1991 $retValue = $freezeStringChecked . ts('No') . "\n";
1997 $retValue = CRM_Utils_System
::formatWikiURL($value);
2002 $retValue = $values;
2005 case 'ContactReference':
2006 if (!empty($values['data'])) {
2007 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
2016 if ($htmlType == 'Text') {
2017 $retValue = (float) $value;
2021 if ($htmlType == 'Text') {
2022 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2027 if (in_array($htmlType, array('Text', 'TextArea'))) {
2031 // note that if its not text / textarea, the code falls thru and executes
2032 // the below case also
2033 case 'StateProvince':
2038 //added check for Multi-Select in the below if-statement
2039 $customData[] = $value;
2041 //form custom data for multiple-valued custom data
2042 switch ($htmlType) {
2043 case 'Multi-Select Country':
2044 case 'Select Country':
2045 $customData = $value;
2046 if (!is_array($value)) {
2047 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2050 SELECT id as value, name as label
2051 FROM civicrm_country";
2052 $coDAO = CRM_Core_DAO
::executeQuery($query);
2055 case 'Select State/Province':
2056 case 'Multi-Select State/Province':
2057 $customData = $value;
2058 if (!is_array($value)) {
2059 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2063 SELECT id as value, name as label
2064 FROM civicrm_state_province";
2065 $coDAO = CRM_Core_DAO
::executeQuery($query);
2069 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2070 if ($option_group_id) {
2071 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2076 case 'AdvMulti-Select':
2077 case 'Multi-Select':
2078 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2080 if ($option_group_id) {
2081 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2085 if (is_object($coDAO)) {
2086 while ($coDAO->fetch()) {
2087 if ($dataType == 'Country') {
2088 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2089 // and already extracted to .pot files.
2090 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
2092 elseif ($dataType == 'StateProvince') {
2093 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
2096 $options[$coDAO->value
] = $coDAO->label
;
2101 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
2104 foreach ($options as $optionValue => $optionLabel) {
2105 if ($dataType == 'Money') {
2106 foreach ($customData as $k => $v) {
2107 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
2111 //to show only values that are checked
2112 if (in_array((string) $optionValue, $customData)) {
2113 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
2114 if (!$optionPerLine ||
$dncOptionPerLine) {
2118 $retValue .= $checked . $optionLabel;
2121 $retValue[] = $checked . $optionLabel;
2128 //special case for option per line formatting
2129 if ($optionPerLine > 1 && is_array($retValue)) {
2132 $displayValues = array();
2133 $displayString = '';
2134 foreach ($retValue as $val) {
2135 if ($displayString) {
2136 $displayString .= ", ";
2139 $displayString .= $val;
2143 if (($rowCounter == $optionPerLine) ||
2144 ($fieldCounter == count($retValue))
2146 $displayValues[] = $displayString;
2147 $displayString = '';
2151 $retValue = $displayValues;
2154 $retValue = isset($retValue) ?
$retValue : NULL;
2159 * Get the custom group titles by custom field ids.
2161 * @param array $fieldIds - array of custom field ids.
2163 * @return array $groupLabels - array consisting of groups and fields labels with ids.
2165 public static function getGroupTitles($fieldIds) {
2166 if (!is_array($fieldIds) && empty($fieldIds)) {
2170 $groupLabels = array();
2171 $fIds = "(" . implode(',', $fieldIds) . ")";
2174 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2175 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2176 FROM civicrm_custom_group, civicrm_custom_field
2177 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2178 AND civicrm_custom_field.id IN {$fIds}";
2180 $dao = CRM_Core_DAO
::executeQuery($query);
2181 while ($dao->fetch()) {
2182 $groupLabels[$dao->fieldID
] = array(
2183 'fieldID' => $dao->fieldID
,
2184 'fieldLabel' => $dao->fieldLabel
,
2185 'groupID' => $dao->groupID
,
2186 'groupTitle' => $dao->groupTitle
,
2190 return $groupLabels;
2193 public static function dropAllTables() {
2194 $query = "SELECT table_name FROM civicrm_custom_group";
2195 $dao = CRM_Core_DAO
::executeQuery($query);
2197 while ($dao->fetch()) {
2198 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2199 CRM_Core_DAO
::executeQuery($query);
2204 * Check whether custom group is empty or not.
2206 * @param int $gID - custom group id.
2208 * @return boolean true if empty otherwise false.
2210 public static function isGroupEmpty($gID) {
2215 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2220 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2221 $value = CRM_Core_DAO
::singleValueQuery($query);
2223 if (empty($value)) {
2231 * Get the list of types for objects that a custom group extends to.
2233 * @param array $types - var which should have the list appended.
2235 * @return array of types.
2237 public static function getExtendedObjectTypes(&$types = array()) {
2238 static $flag = FALSE, $objTypes = array();
2241 $extendObjs = array();
2242 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2244 foreach ($extendObjs as $ovId => $ovValues) {
2245 if ($ovValues['description']) {
2246 // description is expected to be a callback func to subtypes
2247 list($callback, $args) = explode(';', trim($ovValues['description']));
2253 if (!is_array($args)) {
2254 CRM_Core_Error
::fatal('Arg is not of type array');
2257 list($className) = explode('::', $callback);
2258 require_once(str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2261 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2267 $types = array_merge($types, $objTypes);
2272 * @param int $customGroupId
2273 * @param int $entityId
2277 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2278 //check whether the group is multiple
2279 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2280 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2281 $hasReachedMax = FALSE;
2283 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2285 if (!$maxMultiple) {
2286 $hasReachedMax = FALSE;
2289 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2290 //count the number of entries for a entity
2291 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2292 $params = array(1 => array($entityId, 'Integer'));
2293 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2295 if ($count >= $maxMultiple) {
2296 $hasReachedMax = TRUE;
2300 return $hasReachedMax;
2306 public static function getMultipleFieldGroup() {
2307 $multipleGroup = array();
2308 $dao = new CRM_Core_DAO_CustomGroup();
2309 $dao->is_multiple
= 1;
2311 while ($dao->fetch()) {
2312 $multipleGroup[$dao->id
] = $dao->title
;
2314 return $multipleGroup;