3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
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 if (isset($params['title'])) {
60 $group->title
= $params['title'];
63 if (in_array($params['extends'][0],
66 'ParticipantEventName',
67 'ParticipantEventType',
70 $group->extends = 'Participant';
73 $group->extends = $params['extends'][0];
76 $group->extends_entity_column_id
= 'null';
78 $params['extends'][0] == 'ParticipantRole' ||
79 $params['extends'][0] == 'ParticipantEventName' ||
80 $params['extends'][0] == 'ParticipantEventType'
82 $group->extends_entity_column_id
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $params['extends'][0], 'value', 'name');
85 //this is format when form get submit.
86 $extendsChildType = CRM_Utils_Array
::value(1, $params['extends']);
87 //lets allow user to pass direct child type value, CRM-6893
88 if (!empty($params['extends_entity_column_value'])) {
89 $extendsChildType = $params['extends_entity_column_value'];
91 if (!CRM_Utils_System
::isNull($extendsChildType)) {
92 $extendsChildType = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendsChildType);
93 if (CRM_Utils_Array
::value(0, $params['extends']) == 'Relationship') {
94 $extendsChildType = str_replace(array('_a_b', '_b_a'), array(
97 ), $extendsChildType);
99 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
100 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType .
101 CRM_Core_DAO
::VALUE_SEPARATOR
;
105 $extendsChildType = 'null';
107 $group->extends_entity_column_value
= $extendsChildType;
109 if (isset($params['id'])) {
110 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
115 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
119 'collapse_adv_display',
125 foreach ($fields as $field) {
126 if (isset($params[$field]) ||
$field == 'is_multiple') {
127 $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(
147 'CRM_Core_DAO_CustomGroup',
154 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
155 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
157 // we do this only once, so name never changes
158 if (isset($params['name'])) {
159 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
162 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
165 if (isset($params['table_name'])) {
166 $tableName = $params['table_name'];
168 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
169 // Bad idea. Prevent group creation because it might lead to a broken configuration.
170 CRM_Core_Error
::fatal(ts("Cannot create custom table because %1 is already a core table.", array('1' => $tableName)));
175 if (array_key_exists('is_reserved', $params)) {
176 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
178 $op = isset($params['id']) ?
'edit' : 'create';
179 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
181 // enclose the below in a transaction
182 $transaction = new CRM_Core_Transaction();
185 if (!isset($params['id'])) {
186 if (!isset($params['table_name'])) {
187 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 42));
188 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
190 $group->table_name
= $tableName;
191 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
197 // now create the table associated with this group
198 self
::createTable($group);
200 elseif ($oldTableName) {
201 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($oldTableName, CRM_Utils_Array
::value('is_multiple', $params));
204 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
205 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
209 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends'][0]));
211 $transaction->commit();
214 CRM_Utils_System
::flushCache();
217 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
220 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
227 * Fetch object based on array of properties.
229 * @param array $params
230 * (reference ) an assoc array of name/value pairs.
231 * @param array $defaults
232 * (reference ) an assoc array to hold the flattened values.
234 * @return CRM_Core_DAO_CustomGroup
236 public static function retrieve(&$params, &$defaults) {
237 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
241 * Update the is_active flag in the db.
244 * Id of the database record.
245 * @param bool $is_active
246 * Value we want to set the is_active field.
249 * DAO object on success, null otherwise
251 public static function setIsActive($id, $is_active) {
253 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
256 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
259 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
263 * Determine if given entity (sub)type has any custom groups
265 * @param string $extends
266 * E.g. "Individual", "Activity".
267 * @param int $columnId
268 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
269 * @param string $columnValue
270 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
274 public static function hasCustomGroup($extends, $columnId, $columnValue) {
275 $dao = new CRM_Core_DAO_CustomGroup();
276 $dao->extends = $extends;
277 $dao->extends_entity_column_id
= $columnId;
278 $escapedValue = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) . CRM_Core_DAO
::VALUE_SEPARATOR
;
279 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
280 //$dao->extends_entity_column_value = $columnValue;
281 return $dao->find() ?
TRUE : FALSE;
285 * Determine if there are any CustomGroups for the given $activityTypeId.
286 * If none found, create one.
288 * @param int $activityTypeId
291 * TRUE if a group is found or created; FALSE on error
293 public static function autoCreateByActivityType($activityTypeId) {
294 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
297 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
300 'extends' => 'Activity',
301 'extends_entity_column_id' => NULL,
302 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
303 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
307 $result = civicrm_api('CustomGroup', 'create', $params);
308 return !$result['is_error'];
312 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
313 * This may also include entity specific data values.
315 * An array containing all custom groups and their custom fields is returned.
317 * @param string $entityType
318 * Of the contact whose contact type is needed.
319 * @param CRM_Core_Form $form
321 * @param int $entityID
322 * @param int $groupID
323 * @param string $subType
324 * @param string $subName
325 * @param bool $fromCache
326 * @param bool $onlySubType
327 * Only return specified subtype or return specified subtype + unrestricted fields.
328 * @param bool $returnAll
329 * Do not restrict by subtype at all. (The parameter feels a bit cludgey but is only used from the
330 * api - through which it is properly tested - so can be refactored with some comfort.)
332 * @param bool $checkPermission
335 * Custom field 'tree'.
337 * The returned array is keyed by group id and has the custom group table fields
338 * and a subkey 'fields' holding the specific custom fields.
339 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
340 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
342 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
343 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
344 * With caching the performance impact would be small & the function would be cleaner
346 public static function &getTree(
356 $checkPermission = TRUE
359 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
363 $strSelect = $strFrom = $strWhere = $orderBy = '';
364 $tableData = array();
366 // using tableData to build the queryString
368 'civicrm_custom_field' => array(
388 'civicrm_custom_group' => array(
398 'extends_entity_column_id',
399 'extends_entity_column_value',
406 foreach ($tableData as $tableName => $tableColumn) {
407 foreach ($tableColumn as $columnName) {
408 $alias = $tableName . "_" . $columnName;
409 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
412 $strSelect = "SELECT " . implode(', ', $select);
414 // from, where, order by
416 FROM civicrm_custom_group
417 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
420 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
421 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
422 $entityType == 'Household'
424 $in = "'$entityType', 'Contact'";
426 elseif (strpos($entityType, "'") !== FALSE) {
427 // this allows the calling function to send in multiple entity types
432 $in = "'$entityType'";
437 if (is_array($subType)) {
438 $subType = implode(',', $subType);
440 if (strpos($subType, ',')) {
441 $subTypeParts = explode(',', $subType);
442 $subTypeClauses = array();
443 foreach ($subTypeParts as $subTypePart) {
444 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
.
445 trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) .
446 CRM_Core_DAO
::VALUE_SEPARATOR
;
447 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
451 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
454 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) .
455 " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
459 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
.
460 trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) .
461 CRM_Core_DAO
::VALUE_SEPARATOR
;
464 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
467 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
468 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
473 WHERE civicrm_custom_group.is_active = 1
474 AND civicrm_custom_field.is_active = 1
475 AND civicrm_custom_group.extends IN ($in)
479 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
484 WHERE civicrm_custom_group.is_active = 1
485 AND civicrm_custom_field.is_active = 1
486 AND civicrm_custom_group.extends IN ($in)
489 $strWhere .= "AND civicrm_custom_group.extends_entity_column_value IS NULL";
495 // since we want a specific group id we add it to the where clause
496 $strWhere .= " AND civicrm_custom_group.id = %1";
497 $params[1] = array($groupID, 'Integer');
500 // since groupID is false we need to show all Inline groups
501 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
503 if ($checkPermission) {
504 // ensure that the user has access to these custom groups
505 $strWhere .= " AND " .
506 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
507 'civicrm_custom_group.'
512 ORDER BY civicrm_custom_group.weight,
513 civicrm_custom_group.title,
514 civicrm_custom_field.weight,
515 civicrm_custom_field.label
518 // final query string
519 $queryString = "$strSelect $strFrom $strWhere $orderBy";
521 // lets see if we can retrieve the groupTree from cache
522 $cacheString = $queryString;
524 $cacheString .= "_{$groupID}";
527 $cacheString .= "_Inline";
530 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
531 $multipleFieldGroupCacheKey = "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
532 $cache = CRM_Utils_Cache
::singleton();
533 $tablesWithEntityData = array();
535 $groupTree = $cache->get($cacheKey);
536 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
539 if (empty($groupTree)) {
540 $groupTree = $multipleFieldGroups = array();
541 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
542 $customValueTables = array();
545 while ($crmDAO->fetch()) {
547 $groupID = $crmDAO->civicrm_custom_group_id
;
548 $fieldId = $crmDAO->civicrm_custom_field_id
;
549 if ($crmDAO->civicrm_custom_group_is_multiple
) {
550 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
552 // create an array for groups if it does not exist
553 if (!array_key_exists($groupID, $groupTree)) {
554 $groupTree[$groupID] = array();
555 $groupTree[$groupID]['id'] = $groupID;
557 // populate the group information
558 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
559 $fullFieldName = "civicrm_custom_group_$fieldName";
560 if ($fieldName == 'id' ||
561 is_null($crmDAO->$fullFieldName)
566 if ($fieldName == 'extends_entity_column_value' && $subType) {
567 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
569 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
571 $groupTree[$groupID]['fields'] = array();
573 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
576 // add the fields now (note - the query row will always contain a field)
577 // we only reset this once, since multiple values come is as multiple rows
578 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
579 $groupTree[$groupID]['fields'][$fieldId] = array();
582 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
583 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
584 // populate information for a custom field
585 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
586 $fullFieldName = "civicrm_custom_field_$fieldName";
587 if ($fieldName == 'id' ||
588 is_null($crmDAO->$fullFieldName)
592 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
596 if (!empty($customValueTables)) {
597 $groupTree['info'] = array('tables' => $customValueTables);
600 $cache->set($cacheKey, $groupTree);
601 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
603 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
604 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
605 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
606 $singleFieldTables = array();
607 // now that we have all the groups and fields, lets get the values
608 // since we need to know the table and field names
609 // add info to groupTree
611 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
612 !empty($groupTree['info']['tables'])
614 $select = $from = $where = array();
615 $groupTree['info']['where'] = NULL;
617 foreach ($groupTree['info']['tables'] as $table => $fields) {
618 $groupTree['info']['from'][] = $table;
620 "{$table}.id as {$table}_id",
621 "{$table}.entity_id as {$table}_entity_id",
623 foreach ($fields as $column => $dontCare) {
624 $select[] = "{$table}.{$column} as {$table}_{$column}";
626 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
628 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
629 if (in_array($table, $multipleFieldGroups) &&
630 self
::customGroupDataExistsForEntity($entityID, $table)
632 $entityMultipleSelectClauses[$table] = $select;
635 $singleFieldTables[] = $table;
636 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
641 if ($entityID && !empty($singleFieldTables)) {
642 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
644 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
645 if (!empty($multipleFieldTablesWithEntityData)) {
646 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
654 * Check whether the custom group has any data for the given entity.
657 * @param int $entityID
658 * Id of entity for whom we are checking data for.
659 * @param string $table
660 * Table that we are checking.
662 * @param bool $getCount
665 * does this entity have data in this custom table
667 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
671 WHERE entity_id = $entityID
673 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
675 return $recordExists;
677 return $recordExists ?
TRUE : FALSE;
681 * Build the group tree for Custom fields which are not 'is_multiple'
683 * The combination of all these fields in one query with a 'using' join was not working for
684 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
685 * mechanism as it seemed to be acceptable in this context
687 * @param array $groupTree
688 * (reference) group tree array which is being built.
689 * @param int $entityID
690 * Id of entity for whom the tree is being build up.
691 * @param array $entitySingleSelectClauses
692 * Array of select clauses relevant to the entity.
693 * @param array $singleFieldTablesWithEntityData
694 * Array of tables in which this entity has data.
696 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
697 $select = implode(', ', $entitySingleSelectClauses);
698 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
699 foreach ($singleFieldTablesWithEntityData as $table) {
700 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
706 WHERE first.entity_id = $entityID
708 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
712 * Build the group tree for Custom fields which are 'is_multiple'
714 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
716 * @param array $groupTree
717 * (reference) group tree array which is being built.
718 * @param int $entityID
719 * Id of entity for whom the tree is being build up.
720 * @param array $entityMultipleSelectClauses
721 * Array of select clauses relevant to the entity.
722 * @param array $multipleFieldTablesWithEntityData
723 * Array of tables in which this entity has data.
725 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData) {
726 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
727 $select = implode(',', $selectClauses);
731 WHERE entity_id = $entityID
733 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
738 * Build the tree entity data - starting from a query retrieving the custom fields build the group
739 * tree data for the relevant entity (entity is included in the query).
741 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
743 * @param array $groupTree
744 * (reference) group tree array which is being built.
745 * @param string $query
746 * @param array $includedTables
747 * Tables to include - required because the function (for historical reasons).
748 * iterates through the group tree
750 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables) {
751 $dao = CRM_Core_DAO
::executeQuery($query);
752 while ($dao->fetch()) {
753 foreach ($groupTree as $groupID => $group) {
754 if ($groupID === 'info') {
757 $table = $groupTree[$groupID]['table_name'];
758 //working from the groupTree instead of the table list means we have to iterate & exclude.
759 // this could possibly be re-written as other parts of the function have been refactored
760 // for now we just check if the given table is to be included in this function
761 if (!in_array($table, $includedTables)) {
764 foreach ($group['fields'] as $fieldID => $dontCare) {
765 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
772 * Build the entity-specific custom data into the group tree on a per-field basis
775 * Object representing the custom field to be populated into the groupTree.
776 * @param array $groupTree
777 * (reference) the group tree being build.
778 * @param string $table
780 * @param int $groupID
782 * @param int $fieldID
785 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID) {
786 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
787 $idName = "{$table}_id";
788 $fieldName = "{$table}_{$column}";
789 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
790 if ($dataType == 'File') {
791 if (isset($dao->$fieldName)) {
792 $config = CRM_Core_Config
::singleton();
793 $fileDAO = new CRM_Core_DAO_File();
794 $fileDAO->id
= $dao->$fieldName;
796 if ($fileDAO->find(TRUE)) {
797 $entityIDName = "{$table}_entity_id";
798 $customValue['id'] = $dao->$idName;
799 $customValue['data'] = $fileDAO->uri
;
800 $customValue['fid'] = $fileDAO->id
;
801 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
802 $customValue['displayURL'] = NULL;
803 $deleteExtra = ts('Are you sure you want to delete attached file.');
805 CRM_Core_Action
::DELETE
=> array(
806 'name' => ts('Delete Attached File'),
807 'url' => 'civicrm/file',
808 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
809 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra
810 . '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
813 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
814 CRM_Core_Action
::DELETE
,
816 'id' => $fileDAO->id
,
817 'eid' => $dao->$entityIDName,
822 'file.manage.delete',
826 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
827 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
828 if ($fileDAO->mime_type
== "image/jpeg" ||
829 $fileDAO->mime_type
== "image/pjpeg" ||
830 $fileDAO->mime_type
== "image/gif" ||
831 $fileDAO->mime_type
== "image/x-png" ||
832 $fileDAO->mime_type
== "image/png"
834 $customValue['displayURL'] = $customValue['fileURL'];
835 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
840 $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
842 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId, NULL, NULL);
843 if ($path && file_exists($path)) {
844 list($imageWidth, $imageHeight) = getimagesize($path);
845 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
846 $customValue['imageThumbWidth'] = $imageThumbWidth;
847 $customValue['imageThumbHeight'] = $imageThumbHeight;
853 $customValue = array(
854 'id' => $dao->$idName,
860 $customValue = array(
861 'id' => $dao->$idName,
862 'data' => $dao->$fieldName,
866 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
867 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
869 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
870 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
873 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
878 * Get the group title.
886 public static function getTitle($id) {
887 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
891 * Get custom group details for a group.
893 * An array containing custom group details (including their custom field) is returned.
895 * @param int $groupId
896 * Group id whose details are needed.
897 * @param bool $searchable
898 * Is this field searchable.
899 * @param array $extends
900 * Which table does it extend if any.
902 * @param null $inSelector
905 * array consisting of all group and field details
907 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
909 $groupTree = array();
910 $select = $from = $where = $orderBy = '';
912 $tableData = array();
914 // using tableData to build the queryString
916 'civicrm_custom_field' => array(
940 'civicrm_custom_group' => array(
947 'collapse_adv_display',
949 'extends_entity_column_value',
958 foreach ($tableData as $tableName => $tableColumn) {
959 foreach ($tableColumn as $columnName) {
960 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
963 $select = 'SELECT ' . implode(', ', $s);
965 // from, where, order by
966 $from = " FROM civicrm_custom_field, civicrm_custom_group";
967 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
968 AND civicrm_custom_group.is_active = 1
969 AND civicrm_custom_field.is_active = 1 ";
971 $params[1] = array($groupId, 'Integer');
972 $where .= " AND civicrm_custom_group.id = %1";
976 $where .= " AND civicrm_custom_field.is_searchable = 1";
980 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
985 foreach ($extends as $e) {
986 $clause[] = "civicrm_custom_group.extends = '$e'";
988 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
990 //include case activities customdata if case is enabled
991 if (in_array('Activity', $extends)) {
992 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
993 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
994 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
998 // ensure that the user has access to these custom groups
1000 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
1001 'civicrm_custom_group.'
1004 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1006 // final query string
1007 $queryString = $select . $from . $where . $orderBy;
1010 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1013 while ($crmDAO->fetch()) {
1014 $groupId = $crmDAO->civicrm_custom_group_id
;
1015 $fieldId = $crmDAO->civicrm_custom_field_id
;
1017 // create an array for groups if it does not exist
1018 if (!array_key_exists($groupId, $groupTree)) {
1019 $groupTree[$groupId] = array();
1020 $groupTree[$groupId]['id'] = $groupId;
1022 foreach ($tableData['civicrm_custom_group'] as $v) {
1023 $fullField = "civicrm_custom_group_" . $v;
1025 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1029 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1032 $groupTree[$groupId]['fields'] = array();
1035 // add the fields now (note - the query row will always contain a field)
1036 $groupTree[$groupId]['fields'][$fieldId] = array();
1037 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1039 foreach ($tableData['civicrm_custom_field'] as $v) {
1040 $fullField = "civicrm_custom_field_" . $v;
1041 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1044 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1052 * @param $entityType
1054 * @param string $cidToken
1058 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1060 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1062 // get 'Tab' and 'Tab with table' groups
1063 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1064 $customGroupDAO->whereAdd("is_active = 1");
1066 // add whereAdd for entity type
1067 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1071 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1072 $customGroupDAO->whereAdd($permissionClause);
1075 $customGroupDAO->orderBy('weight');
1076 $customGroupDAO->find();
1078 // process each group with menu tab
1079 while ($customGroupDAO->fetch()) {
1081 $group['id'] = $customGroupDAO->id
;
1082 $group['path'] = $path;
1083 $group['title'] = "$customGroupDAO->title";
1084 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1085 $group['extra'] = array('gid' => $customGroupDAO->id
);
1086 $group['table_name'] = $customGroupDAO->table_name
;
1087 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1095 * Get the table name for the entity type
1096 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1097 * tableName is 'civicrm_contact'
1099 * @param string $entityType
1100 * What entity are we extending here ?.
1105 * @see _apachesolr_civiAttachments_dereference_file_parent
1107 public static function getTableNameByEntityName($entityType) {
1109 switch ($entityType) {
1113 case 'Organization':
1114 $tableName = 'civicrm_contact';
1117 case 'Contribution':
1118 $tableName = 'civicrm_contribution';
1122 $tableName = 'civicrm_group';
1125 // DRAFTING: Verify if we cannot make it pluggable
1128 $tableName = 'civicrm_activity';
1131 case 'Relationship':
1132 $tableName = 'civicrm_relationship';
1136 $tableName = 'civicrm_membership';
1140 $tableName = 'civicrm_participant';
1144 $tableName = 'civicrm_event';
1148 $tableName = 'civicrm_grant';
1151 // need to add cases for Location, Address
1158 * Get a list of custom groups which extend a given entity type.
1159 * If there are custom-groups which only apply to certain subtypes,
1160 * those WILL be included.
1162 * @param string $entityType
1164 * @return CRM_Core_DAO_CustomGroup
1166 public static function getAllCustomGroupsByBaseEntity($entityType) {
1167 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1168 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1169 return $customGroupDAO;
1173 * Add the whereAdd clause for the DAO depending on the type of entity
1174 * the custom group is extending.
1176 * @param object $customGroupDAO
1177 * @param string $entityType
1178 * What entity are we extending here ?.
1180 * @param int $entityID
1181 * @param bool $allSubtypes
1183 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1184 $addSubtypeClause = FALSE;
1186 switch ($entityType) {
1188 // if contact, get all related to contact
1189 $extendList = "'Contact','Individual','Household','Organization'";
1190 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1191 if (!$allSubtypes) {
1192 $addSubtypeClause = TRUE;
1198 case 'Organization':
1199 // is I/H/O then get I/H/O and contact
1200 $extendList = "'Contact','$entityType'";
1201 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1202 if (!$allSubtypes) {
1203 $addSubtypeClause = TRUE;
1211 case 'Contribution':
1214 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1218 if ($addSubtypeClause) {
1219 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1221 if (!empty($csType)) {
1222 $subtypeClause = array();
1223 foreach ($csType as $subtype) {
1224 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1225 CRM_Core_DAO
::VALUE_SEPARATOR
;
1226 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1228 $subtypeClause[] = "extends_entity_column_value IS NULL";
1229 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1233 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1239 * Delete the Custom Group.
1241 * @param CRM_Core_BAO_CustomGroup $group
1242 * Custom group object.
1243 * @param bool $force
1244 * whether to force the deletion, even if there are custom fields.
1247 * False if field exists for this group, true if group gets deleted.
1249 public static function deleteGroup($group, $force = FALSE) {
1251 //check whether this contain any custom fields
1252 $customField = new CRM_Core_DAO_CustomField();
1253 $customField->custom_group_id
= $group->id
;
1254 $customField->find();
1256 // return early if there are custom fields and we're not
1257 // forcing the delete, otherwise delete the fields one by one
1258 while ($customField->fetch()) {
1262 CRM_Core_BAO_CustomField
::deleteField($customField);
1265 // drop the table associated with this custom group
1266 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1268 //delete custom group
1271 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1279 * @param array $groupTree
1280 * @param array $defaults
1281 * @param bool $viewMode
1282 * @param bool $inactiveNeeded
1283 * @param int $action
1285 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1286 foreach ($groupTree as $id => $group) {
1287 if (!isset($group['fields'])) {
1290 foreach ($group['fields'] as $field) {
1291 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1292 $value = $field['element_value'];
1294 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1295 ($action != CRM_Core_Action
::UPDATE ||
1297 !array_key_exists('element_value', $field)
1300 $value = $viewMode ?
NULL : $field['default_value'];
1306 if (empty($field['element_name'])) {
1310 $elementName = $field['element_name'];
1312 switch ($field['html_type']) {
1313 case 'Multi-Select':
1314 case 'AdvMulti-Select':
1316 $defaults[$elementName] = array();
1317 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1319 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1320 if (isset($value)) {
1321 foreach ($customOption as $customValue => $customLabel) {
1322 if (in_array($customValue, $checkedData)) {
1323 if ($field['html_type'] == 'CheckBox') {
1324 $defaults[$elementName][$customValue] = 1;
1327 $defaults[$elementName][$customValue] = $customValue;
1331 $defaults[$elementName][$customValue] = 0;
1337 if (isset($field['customValue']['data'])) {
1338 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1339 foreach ($customOption as $val) {
1340 if (in_array($val['value'], $checkedData)) {
1341 if ($field['html_type'] == 'CheckBox') {
1342 $defaults[$elementName][$val['value']] = 1;
1345 $defaults[$elementName][$val['value']] = $val['value'];
1349 $defaults[$elementName][$val['value']] = 0;
1354 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1355 foreach ($customOption as $val) {
1356 if (in_array($val['value'], $checkedValue)) {
1357 if ($field['html_type'] == 'CheckBox') {
1358 $defaults[$elementName][$val['value']] = 1;
1361 $defaults[$elementName][$val['value']] = $val['value'];
1370 if (isset($value)) {
1371 if (empty($field['time_format'])) {
1372 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1373 $field['date_format']
1377 $timeElement = $elementName . '_time';
1378 if (substr($elementName, -1) == ']') {
1379 $timeElement = substr($elementName, 0, -1) . '_time]';
1381 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1386 case 'Multi-Select Country':
1387 case 'Multi-Select State/Province':
1388 if (isset($value)) {
1389 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1390 foreach ($checkedValue as $val) {
1392 $defaults[$elementName][$val] = $val;
1398 case 'Select Country':
1400 $defaults[$elementName] = $value;
1403 $config = CRM_Core_Config
::singleton();
1404 $defaults[$elementName] = $config->defaultContactCountry
;
1409 if ($field['data_type'] == "Float") {
1410 $defaults[$elementName] = (float) $value;
1412 elseif ($field['data_type'] == 'Money' &&
1413 $field['html_type'] == 'Text'
1415 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1418 $defaults[$elementName] = $value;
1426 * PostProcess function.
1428 * @param array $groupTree
1429 * @param array $params
1430 * @param bool $skipFile
1432 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1433 // Get the Custom form values and groupTree
1434 // first reset all checkbox and radio data
1435 foreach ($groupTree as $groupID => $group) {
1436 if ($groupID === 'info') {
1439 foreach ($group['fields'] as $field) {
1440 $fieldId = $field['id'];
1442 //added Multi-Select option in the below if-statement
1443 if ($field['html_type'] == 'CheckBox' ||
1444 $field['html_type'] == 'Radio' ||
1445 $field['html_type'] == 'AdvMulti-Select' ||
1446 $field['html_type'] == 'Multi-Select'
1448 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1452 foreach ($params as $key => $val) {
1453 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1454 $match[1] == $field['id']
1460 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1461 // field exists in db so populate value from "form".
1462 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1465 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1467 //added for CheckBox
1471 $customValue = array_keys($v);
1472 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1473 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue)
1474 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1477 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1481 //added for Advanced Multi-Select
1483 case 'AdvMulti-Select':
1484 //added for Multi-Select
1485 case 'Multi-Select':
1487 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = CRM_Core_DAO
::VALUE_SEPARATOR
1488 . implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v)
1489 . CRM_Core_DAO
::VALUE_SEPARATOR
;
1492 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1497 $date = CRM_Utils_Date
::processDate($v);
1498 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1506 //store the file in d/b
1507 $entityId = explode('=', $groupTree['info']['where'][0]);
1508 $fileParams = array('upload_date' => date('Ymdhis'));
1510 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1511 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1514 $fileParams['uri'] = $v['name'];
1515 $fileParams['mime_type'] = $v['type'];
1516 CRM_Core_BAO_File
::filePostProcess($v['name'],
1517 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1518 $groupTree[$groupID]['table_name'],
1523 'custom_' . $fieldId,
1527 $defaults = array();
1528 $paramsFile = array(
1529 'entity_table' => $groupTree[$groupID]['table_name'],
1530 'entity_id' => $entityId[1],
1533 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1538 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1542 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1550 * Generic function to build all the form elements for a specific group tree.
1552 * @param CRM_Core_Form $form
1554 * @param array $groupTree
1555 * The group tree object.
1556 * @param bool $inactiveNeeded
1557 * Return inactive custom groups.
1558 * @param string $prefix
1559 * Prefix for custom grouptree assigned to template.
1561 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1562 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1564 // this is fix for date field
1565 $form->assign('currentYear', date('Y'));
1567 foreach ($groupTree as $id => $group) {
1568 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1569 foreach ($group['fields'] as $field) {
1570 $required = CRM_Utils_Array
::value('is_required', $field);
1572 if ($field['data_type'] == 'File') {
1573 if (!empty($field['element_value']['data'])) {
1578 $fieldId = $field['id'];
1579 $elementName = $field['element_name'];
1580 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1586 * Extract the get params from the url, validate and store it in session.
1588 * @param CRM_Core_Form $form
1590 * @param string $type
1591 * The type of custom group we are using.
1595 public static function extractGetParams(&$form, $type) {
1600 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1601 $customValue = array();
1610 foreach ($groupTree as $group) {
1611 if (!isset($group['fields'])) {
1614 foreach ($group['fields'] as $key => $field) {
1615 $fieldName = 'custom_' . $key;
1616 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1620 if (!in_array($field['html_type'], $htmlType) ||
1621 $field['data_type'] == 'Boolean'
1623 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1625 if ($field['html_type'] == 'CheckBox' ||
1626 $field['html_type'] == 'AdvMulti-Select' ||
1627 $field['html_type'] == 'Multi-Select'
1629 $value = str_replace("|", ",", $value);
1630 $mulValues = explode(',', $value);
1631 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1633 foreach ($mulValues as $v1) {
1634 foreach ($customOption as $coID => $coValue) {
1635 if (strtolower(trim($coValue['label'])) ==
1636 strtolower(trim($v1))
1638 $val[$coValue['value']] = 1;
1650 elseif ($field['html_type'] == 'Select' ||
1651 ($field['html_type'] == 'Radio' &&
1652 $field['data_type'] != 'Boolean'
1655 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1656 foreach ($customOption as $customID => $coValue) {
1657 if (strtolower(trim($coValue['label'])) ==
1658 strtolower(trim($value))
1660 $value = $coValue['value'];
1665 elseif ($field['data_type'] == 'Date') {
1666 if (!empty($value)) {
1668 if (!empty($field['time_format'])) {
1669 $time = CRM_Utils_Request
::retrieve($fieldName .
1670 '_time', 'String', $form, FALSE, NULL, 'GET');
1672 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value .
1674 if (!empty($field['time_format'])) {
1675 $customValue[$fieldName . '_time'] = $time;
1682 $customValue[$fieldName] = $value;
1688 return $customValue;
1692 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1693 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1695 * @param int $customFieldId
1697 * @param array $removeCustomFieldTypes
1698 * Remove custom fields of a type eg: array("Individual") ;.
1701 * false if it matches else true
1703 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1704 $query = "SELECT cg.extends as extends
1705 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1706 WHERE cg.id = cf.custom_group_id
1708 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1710 $extends = CRM_Core_DAO
::singleValueQuery($query);
1712 if (in_array($extends, $removeCustomFieldTypes)) {
1724 public static function mapTableName($table) {
1729 case 'Organization':
1730 return 'civicrm_contact';
1733 return 'civicrm_activity';
1736 return 'civicrm_group';
1738 case 'Contribution':
1739 return 'civicrm_contribution';
1741 case 'ContributionRecur':
1742 return 'civicrm_contribution_recur';
1744 case 'Relationship':
1745 return 'civicrm_relationship';
1748 return 'civicrm_event';
1751 return 'civicrm_membership';
1754 case 'ParticipantRole':
1755 case 'ParticipantEventName':
1756 case 'ParticipantEventType':
1757 return 'civicrm_participant';
1760 return 'civicrm_grant';
1763 return 'civicrm_pledge';
1766 return 'civicrm_address';
1769 return 'civicrm_campaign';
1773 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1774 $qParams = array(1 => array($table, 'String'));
1775 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1778 return 'civicrm_contact';
1781 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1782 if (array_key_exists($table, $extendObjs)) {
1783 return $extendObjs[$table];
1785 CRM_Core_Error
::fatal();
1793 public static function createTable($group) {
1795 'name' => $group->table_name
,
1796 'is_multiple' => $group->is_multiple ?
1 : 0,
1797 'extends_name' => self
::mapTableName($group->extends),
1800 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1802 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1806 * Function returns formatted groupTree, sothat form can be easily build in template
1808 * @param array $groupTree
1809 * @param int $groupCount
1810 * Group count by default 1, but can varry for multiple value custom data.
1811 * @param object $form
1815 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1816 $formattedGroupTree = array();
1817 $uploadNames = array();
1819 foreach ($groupTree as $key => $value) {
1820 if ($key === 'info') {
1824 // add group information
1825 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1826 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1827 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1828 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1829 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1830 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1832 // this params needed of bulding multiple values
1833 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1834 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1835 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1836 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1837 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1838 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1840 // add field information
1841 foreach ($value['fields'] as $k => $properties) {
1842 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1843 if (isset($properties['customValue']) &&
1844 !CRM_Utils_System
::isNull($properties['customValue'])
1846 if (isset($properties['customValue'][$groupCount])) {
1847 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1848 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1849 if ($properties['data_type'] == 'File') {
1850 $properties['element_value'] = $properties['customValue'][$groupCount];
1851 $uploadNames[] = $properties['element_name'];
1854 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1858 unset($properties['customValue']);
1859 $formattedGroupTree[$key]['fields'][$k] = $properties;
1864 // hack for field type File
1865 $formUploadNames = $form->get('uploadNames');
1866 if (is_array($formUploadNames)) {
1867 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1870 $form->set('uploadNames', $uploadNames);
1873 return $formattedGroupTree;
1877 * Build custom data view.
1879 * @param CRM_Core_Form $form
1881 * @param array $groupTree
1882 * @param bool $returnCount
1883 * True if customValue count needs to be returned.
1885 * @param null $prefix
1886 * @param int $customValueId
1890 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1892 foreach ($groupTree as $key => $group) {
1893 if ($key === 'info') {
1897 foreach ($group['fields'] as $k => $properties) {
1898 $groupID = $group['id'];
1899 if (!empty($properties['customValue'])) {
1900 foreach ($properties['customValue'] as $values) {
1901 if (!empty($customValueId) && $customValueId != $values['id']) {
1904 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1905 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1906 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1907 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1908 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1909 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1910 $details[$groupID][$values['id']]['fields'][$k] = array(
1911 'field_title' => CRM_Utils_Array
::value('label', $properties),
1912 'field_type' => CRM_Utils_Array
::value('html_type',
1915 'field_data_type' => CRM_Utils_Array
::value('data_type',
1918 'field_value' => self
::formatCustomValues($values,
1921 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1925 // also return contact reference contact id if user has view all or edit all contacts perm
1926 if ((CRM_Core_Permission
::check('view all contacts') ||
1927 CRM_Core_Permission
::check('edit all contacts'))
1929 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1932 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1937 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1938 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1939 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1940 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1941 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1942 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1943 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1949 //return a single value count if group id is passed to function
1950 //else return a groupId and count mapped array
1952 return count($details[$gID]);
1955 $countValue = array();
1956 foreach ($details as $key => $value) {
1957 $countValue[$key] = count($details[$key]);
1963 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1969 * Format custom value according to data, view mode
1971 * @param array $values
1972 * Associated array of custom values.
1973 * @param array $field
1974 * @param bool $dncOptionPerLine
1975 * True if optionPerLine should not be consider.
1977 * @return array|null|string
1979 public static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1980 $value = $values['data'];
1982 //changed isset CRM-4601
1983 if (CRM_Utils_System
::isNull($value)) {
1987 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1988 $dataType = CRM_Utils_Array
::value('data_type', $field);
1989 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1990 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1991 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1994 $freezeStringChecked = "";
1996 switch ($dataType) {
1998 $customFormat = NULL;
2000 $actualPHPFormats = CRM_Core_SelectValues
::datePluginToPHPFormats();
2002 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
2003 if (array_key_exists($format, $actualPHPFormats)) {
2004 $customTimeFormat = (array) CRM_Utils_Array
::value($format, $actualPHPFormats);
2005 switch ($timeFormat) {
2007 $customTimeFormat[] = 'g:iA';
2011 $customTimeFormat[] = 'G:i';
2015 // if time is not selected remove time from value
2016 $value = substr($value, 0, 10);
2018 $customFormat = implode(" ", $customTimeFormat);
2021 $retValue = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
2025 if ($value == '1') {
2026 $retValue = $freezeStringChecked . ts('Yes') . "\n";
2029 $retValue = $freezeStringChecked . ts('No') . "\n";
2035 $retValue = CRM_Utils_System
::formatWikiURL($value);
2040 $retValue = $values;
2043 case 'ContactReference':
2044 if (!empty($values['data'])) {
2045 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
2054 if ($htmlType == 'Text') {
2055 $retValue = (float) $value;
2059 if ($htmlType == 'Text') {
2060 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2065 if (in_array($htmlType, array('Text', 'TextArea'))) {
2069 // note that if its not text / textarea, the code falls thru and executes
2070 // the below case also
2071 case 'StateProvince':
2076 //added check for Multi-Select in the below if-statement
2077 $customData[] = $value;
2079 //form custom data for multiple-valued custom data
2080 switch ($htmlType) {
2081 case 'Multi-Select Country':
2082 case 'Select Country':
2083 $customData = $value;
2084 if (!is_array($value)) {
2085 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2088 SELECT id as value, name as label
2089 FROM civicrm_country";
2090 $coDAO = CRM_Core_DAO
::executeQuery($query);
2093 case 'Select State/Province':
2094 case 'Multi-Select State/Province':
2095 $customData = $value;
2096 if (!is_array($value)) {
2097 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2101 SELECT id as value, name as label
2102 FROM civicrm_state_province";
2103 $coDAO = CRM_Core_DAO
::executeQuery($query);
2107 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2108 if ($option_group_id) {
2109 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2114 case 'AdvMulti-Select':
2115 case 'Multi-Select':
2116 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2118 if ($option_group_id) {
2119 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2123 if (is_object($coDAO)) {
2124 while ($coDAO->fetch()) {
2125 if ($dataType == 'Country') {
2126 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2127 // and already extracted to .pot files.
2128 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
2130 elseif ($dataType == 'StateProvince') {
2131 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
2134 $options[$coDAO->value
] = $coDAO->label
;
2139 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
2142 foreach ($options as $optionValue => $optionLabel) {
2143 if ($dataType == 'Money') {
2144 foreach ($customData as $k => $v) {
2145 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
2149 //to show only values that are checked
2150 if (in_array((string) $optionValue, $customData)) {
2151 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
2152 if (!$optionPerLine ||
$dncOptionPerLine) {
2156 $retValue .= $checked . $optionLabel;
2159 $retValue[] = $checked . $optionLabel;
2166 //special case for option per line formatting
2167 if ($optionPerLine > 1 && is_array($retValue)) {
2170 $displayValues = array();
2171 $displayString = '';
2172 foreach ($retValue as $val) {
2173 if ($displayString) {
2174 $displayString .= ", ";
2177 $displayString .= $val;
2181 if (($rowCounter == $optionPerLine) ||
2182 ($fieldCounter == count($retValue))
2184 $displayValues[] = $displayString;
2185 $displayString = '';
2189 $retValue = $displayValues;
2192 $retValue = isset($retValue) ?
$retValue : NULL;
2197 * Get the custom group titles by custom field ids.
2199 * @param array $fieldIds
2200 * Array of custom field ids.
2202 * @return array|NULL
2203 * array consisting of groups and fields labels with ids.
2205 public static function getGroupTitles($fieldIds) {
2206 if (!is_array($fieldIds) && empty($fieldIds)) {
2210 $groupLabels = array();
2211 $fIds = "(" . implode(',', $fieldIds) . ")";
2214 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2215 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2216 FROM civicrm_custom_group, civicrm_custom_field
2217 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2218 AND civicrm_custom_field.id IN {$fIds}";
2220 $dao = CRM_Core_DAO
::executeQuery($query);
2221 while ($dao->fetch()) {
2222 $groupLabels[$dao->fieldID
] = array(
2223 'fieldID' => $dao->fieldID
,
2224 'fieldLabel' => $dao->fieldLabel
,
2225 'groupID' => $dao->groupID
,
2226 'groupTitle' => $dao->groupTitle
,
2230 return $groupLabels;
2233 public static function dropAllTables() {
2234 $query = "SELECT table_name FROM civicrm_custom_group";
2235 $dao = CRM_Core_DAO
::executeQuery($query);
2237 while ($dao->fetch()) {
2238 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2239 CRM_Core_DAO
::executeQuery($query);
2244 * Check whether custom group is empty or not.
2250 * true if empty otherwise false.
2252 public static function isGroupEmpty($gID) {
2257 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2262 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2263 $value = CRM_Core_DAO
::singleValueQuery($query);
2265 if (empty($value)) {
2273 * Get the list of types for objects that a custom group extends to.
2275 * @param array $types
2276 * Var which should have the list appended.
2281 public static function getExtendedObjectTypes(&$types = array()) {
2282 static $flag = FALSE, $objTypes = array();
2285 $extendObjs = array();
2286 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2288 foreach ($extendObjs as $ovId => $ovValues) {
2289 if ($ovValues['description']) {
2290 // description is expected to be a callback func to subtypes
2291 list($callback, $args) = explode(';', trim($ovValues['description']));
2297 if (!is_array($args)) {
2298 CRM_Core_Error
::fatal('Arg is not of type array');
2301 list($className) = explode('::', $callback);
2302 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2305 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2311 $types = array_merge($types, $objTypes);
2316 * @param int $customGroupId
2317 * @param int $entityId
2321 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2322 //check whether the group is multiple
2323 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2324 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2325 $hasReachedMax = FALSE;
2327 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2329 if (!$maxMultiple) {
2330 $hasReachedMax = FALSE;
2333 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2334 //count the number of entries for a entity
2335 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2336 $params = array(1 => array($entityId, 'Integer'));
2337 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2339 if ($count >= $maxMultiple) {
2340 $hasReachedMax = TRUE;
2344 return $hasReachedMax;
2350 public static function getMultipleFieldGroup() {
2351 $multipleGroup = array();
2352 $dao = new CRM_Core_DAO_CustomGroup();
2353 $dao->is_multiple
= 1;
2355 while ($dao->fetch()) {
2356 $multipleGroup[$dao->id
] = $dao->title
;
2358 return $multipleGroup;