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
55 * (reference) an assoc array of name/value pairs.
57 * @return CRM_Core_DAO_CustomGroup object
60 public static function create(&$params) {
61 // create custom group dao, populate fields and then save.
62 $group = new CRM_Core_DAO_CustomGroup();
63 $group->title
= $params['title'];
65 if (in_array($params['extends'][0],
68 'ParticipantEventName',
69 'ParticipantEventType',
72 $group->extends = 'Participant';
75 $group->extends = $params['extends'][0];
78 $group->extends_entity_column_id
= 'null';
80 $params['extends'][0] == 'ParticipantRole' ||
81 $params['extends'][0] == 'ParticipantEventName' ||
82 $params['extends'][0] == 'ParticipantEventType'
84 $group->extends_entity_column_id
=
85 CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $params['extends'][0], 'value', 'name');
88 //this is format when form get submit.
89 $extendsChildType = CRM_Utils_Array
::value(1, $params['extends']);
90 //lets allow user to pass direct child type value, CRM-6893
91 if (!empty($params['extends_entity_column_value'])) {
92 $extendsChildType = $params['extends_entity_column_value'];
94 if (!CRM_Utils_System
::isNull($extendsChildType)) {
95 $extendsChildType = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendsChildType);
96 if (CRM_Utils_Array
::value(0, $params['extends']) == 'Relationship') {
97 $extendsChildType = str_replace(array('_a_b', '_b_a'), array(
100 ), $extendsChildType);
102 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
103 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType .
104 CRM_Core_DAO
::VALUE_SEPARATOR
;
108 $extendsChildType = 'null';
110 $group->extends_entity_column_value
= $extendsChildType;
112 if (isset($params['id'])) {
113 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
118 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
122 'collapse_adv_display',
128 foreach ($fields as $field) {
129 $group->$field = CRM_Utils_Array
::value($field, $params, FALSE);
131 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
132 $params['max_multiple'] >= '0'
133 ) ?
$params['max_multiple'] : 'null' : 'null';
135 $tableName = $oldTableName = NULL;
136 if (isset($params['id'])) {
137 $group->id
= $params['id'];
138 //check whether custom group was changed from single-valued to multiple-valued
139 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
144 if ((!empty($params['is_multiple']) ||
$isMultiple) &&
145 ($params['is_multiple'] != $isMultiple)
147 $oldTableName = CRM_Core_DAO
::getFieldValue('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 object
237 public static function retrieve(&$params, &$defaults) {
238 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
242 * Update the is_active flag in the db
245 * Id of the database record.
246 * @param bool $is_activeValue we want to set the is_active field.
247 * Value we want to set the is_active field.
249 * @return Object DAO object on sucess, null otherwise
252 public static function setIsActive($id, $is_active) {
254 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
257 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
260 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
264 * Determine if given entity (sub)type has any custom groups
266 * @param string $extends
267 * E.g. "Individual", "Activity".
268 * @param int $columnId
269 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
270 * @param string $columnValue
271 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
275 public static function hasCustomGroup($extends, $columnId, $columnValue) {
276 $dao = new CRM_Core_DAO_CustomGroup();
277 $dao->extends = $extends;
278 $dao->extends_entity_column_id
= $columnId;
280 CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) .
281 CRM_Core_DAO
::VALUE_SEPARATOR
;
282 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
283 //$dao->extends_entity_column_value = $columnValue;
284 return $dao->find() ?
TRUE : FALSE;
288 * Determine if there are any CustomGroups for the given $activityTypeId.
289 * If none found, create one.
291 * @param int $activityTypeId
293 * @return bool TRUE if a group is found or created; FALSE on error
295 public static function autoCreateByActivityType($activityTypeId) {
296 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
299 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
302 'extends' => 'Activity',
303 'extends_entity_column_id' => NULL,
304 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
305 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
309 $result = civicrm_api('CustomGroup', 'create', $params);
310 return !$result['is_error'];
314 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
315 * This may also include entity specific data values.
317 * An array containing all custom groups and their custom fields is returned.
319 * @param string $entityType
320 * Of the contact whose contact type is needed.
321 * @param CRM_Core_Form $form
322 * Not used but required.
323 * @param int $entityID
324 * @param int $groupID
325 * @param string $subType
326 * @param string $subName
327 * @param bool $fromCache
328 * @param bool $onlySubType
330 * @return array $groupTree - array The returned array is keyed by group id and has the custom group table fields
331 * and a subkey 'fields' holding the specific custom fields.
332 * If entityId is passed in the fields keys have a subkey 'customValue' which holds custom data
333 * if set for the given entity. This is structured as an array of values with each one having the keys 'id', 'data'
335 * @todo - review this - It also returns an array called 'info' with tables, select, from, where keys
336 * The reason for the info array in unclear and it could be determined from parsing the group tree after creation
337 * With caching the performance impact would be small & the function would be cleaner
342 public static function &getTree(
353 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
357 $strSelect = $strFrom = $strWhere = $orderBy = '';
358 $tableData = array();
360 // using tableData to build the queryString
362 'civicrm_custom_field' => array(
382 'civicrm_custom_group' => array(
392 'extends_entity_column_id',
393 'extends_entity_column_value',
400 foreach ($tableData as $tableName => $tableColumn) {
401 foreach ($tableColumn as $columnName) {
402 $alias = $tableName . "_" . $columnName;
403 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
406 $strSelect = "SELECT " . implode(', ', $select);
408 // from, where, order by
410 FROM civicrm_custom_group
411 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
414 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
415 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
416 $entityType == 'Household'
418 $in = "'$entityType', 'Contact'";
420 elseif (strpos($entityType, "'") !== FALSE) {
421 // this allows the calling function to send in multiple entity types
426 $in = "'$entityType'";
431 if (is_array($subType)) {
432 $subType = implode(',', $subType);
434 if (strpos($subType, ',')) {
435 $subTypeParts = explode(',', $subType);
436 $subTypeClauses = array();
437 foreach ($subTypeParts as $subTypePart) {
438 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
.
439 trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) .
440 CRM_Core_DAO
::VALUE_SEPARATOR
;
441 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
445 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
448 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) .
449 " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
453 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
.
454 trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) .
455 CRM_Core_DAO
::VALUE_SEPARATOR
;
458 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
461 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
462 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
467 WHERE civicrm_custom_group.is_active = 1
468 AND civicrm_custom_field.is_active = 1
469 AND civicrm_custom_group.extends IN ($in)
473 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
478 WHERE civicrm_custom_group.is_active = 1
479 AND civicrm_custom_field.is_active = 1
480 AND civicrm_custom_group.extends IN ($in)
481 AND civicrm_custom_group.extends_entity_column_value IS NULL
487 // since we want a specific group id we add it to the where clause
488 $strWhere .= " AND civicrm_custom_group.id = %1";
489 $params[1] = array($groupID, 'Integer');
492 // since groupID is false we need to show all Inline groups
493 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
496 // ensure that the user has access to these custom groups
497 $strWhere .= " AND " .
498 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
499 'civicrm_custom_group.'
503 ORDER BY civicrm_custom_group.weight,
504 civicrm_custom_group.title,
505 civicrm_custom_field.weight,
506 civicrm_custom_field.label
509 // final query string
510 $queryString = "$strSelect $strFrom $strWhere $orderBy";
512 // lets see if we can retrieve the groupTree from cache
513 $cacheString = $queryString;
515 $cacheString .= "_{$groupID}";
518 $cacheString .= "_Inline";
521 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
522 $multipleFieldGroupCacheKey =
523 "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
524 $cache = CRM_Utils_Cache
::singleton();
525 $tablesWithEntityData = array();
527 $groupTree = $cache->get($cacheKey);
528 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
531 if (empty($groupTree)) {
532 $groupTree = $multipleFieldGroups = array();
533 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
534 $customValueTables = array();
537 while ($crmDAO->fetch()) {
539 $groupID = $crmDAO->civicrm_custom_group_id
;
540 $fieldId = $crmDAO->civicrm_custom_field_id
;
541 if ($crmDAO->civicrm_custom_group_is_multiple
) {
542 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
544 // create an array for groups if it does not exist
545 if (!array_key_exists($groupID, $groupTree)) {
546 $groupTree[$groupID] = array();
547 $groupTree[$groupID]['id'] = $groupID;
549 // populate the group information
550 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
551 $fullFieldName = "civicrm_custom_group_$fieldName";
552 if ($fieldName == 'id' ||
553 is_null($crmDAO->$fullFieldName)
558 if ($fieldName == 'extends_entity_column_value' && $subType) {
559 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
561 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
563 $groupTree[$groupID]['fields'] = array();
565 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
568 // add the fields now (note - the query row will always contain a field)
569 // we only reset this once, since multiple values come is as multiple rows
570 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
571 $groupTree[$groupID]['fields'][$fieldId] = array();
574 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
575 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
576 // populate information for a custom field
577 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
578 $fullFieldName = "civicrm_custom_field_$fieldName";
579 if ($fieldName == 'id' ||
580 is_null($crmDAO->$fullFieldName)
584 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
588 if (!empty($customValueTables)) {
589 $groupTree['info'] = array('tables' => $customValueTables);
592 $cache->set($cacheKey, $groupTree);
593 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
595 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
596 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
597 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
598 $singleFieldTables = array();
599 // now that we have all the groups and fields, lets get the values
600 // since we need to know the table and field names
601 // add info to groupTree
603 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
604 !empty($groupTree['info']['tables'])
606 $select = $from = $where = array();
607 $groupTree['info']['where'] = NULL;
609 foreach ($groupTree['info']['tables'] as $table => $fields) {
610 $groupTree['info']['from'][] = $table;
612 "{$table}.id as {$table}_id",
613 "{$table}.entity_id as {$table}_entity_id",
615 foreach ($fields as $column => $dontCare) {
616 $select[] = "{$table}.{$column} as {$table}_{$column}";
618 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
620 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
621 if (in_array($table, $multipleFieldGroups) &&
622 self
::customGroupDataExistsForEntity($entityID, $table)
624 $entityMultipleSelectClauses[$table] = $select;
627 $singleFieldTables[] = $table;
628 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
633 if ($entityID && !empty($singleFieldTables)) {
634 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
636 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
637 if (!empty($multipleFieldTablesWithEntityData)) {
638 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
646 * Check whether the custom group has any data for the given entity.
649 * @param int $entityID
650 * Id of entity for whom we are checking data for.
651 * @param string $table
652 * Table that we are checking.
654 * @param bool $getCount
656 * @return boolean does this entity have data in this custom table
658 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
662 WHERE entity_id = $entityID
664 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
666 return $recordExists;
668 return $recordExists ?
TRUE : FALSE;
672 * Build the group tree for Custom fields which are not 'is_multiple'
674 * The combination of all these fields in one query with a 'using' join was not working for
675 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
676 * mechanism as it seemed to be acceptable in this context
678 * @param array $groupTree
679 * (reference) group tree array which is being built.
680 * @param int $entityID
681 * Id of entity for whom the tree is being build up.
682 * @param array $entitySingleSelectClauses
683 * Array of select clauses relevant to the entity.
684 * @param array $singleFieldTablesWithEntityData
685 * Array of tables in which this entity has data.
687 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
688 $select = implode(', ', $entitySingleSelectClauses);
689 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
690 foreach ($singleFieldTablesWithEntityData as $table) {
691 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
697 WHERE first.entity_id = $entityID
699 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
703 * Build the group tree for Custom fields which are 'is_multiple'
705 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
707 * @param array $groupTree
708 * (reference) group tree array which is being built.
709 * @param int $entityID
710 * Id of entity for whom the tree is being build up.
711 * @param array $entityMultipleSelectClauses
712 * Array of select clauses relevant to the entity.
713 * @param array $multipleFieldTablesWithEntityData
714 * Array of tables in which this entity has data.
716 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData) {
717 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
718 $select = implode(',', $selectClauses);
722 WHERE entity_id = $entityID
724 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
729 * Build the tree entity data - starting from a query retrieving the custom fields build the group
730 * tree data for the relevant entity (entity is included in the query).
732 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
734 * @param array $groupTree
735 * (reference) group tree array which is being built.
736 * @param string $query
737 * @param array $includedTables
738 * Tables to include - required because the function (for historical reasons).
739 * iterates through the group tree
741 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables) {
742 $dao = CRM_Core_DAO
::executeQuery($query);
743 while ($dao->fetch()) {
744 foreach ($groupTree as $groupID => $group) {
745 if ($groupID === 'info') {
748 $table = $groupTree[$groupID]['table_name'];
749 //working from the groupTree instead of the table list means we have to iterate & exclude.
750 // this could possibly be re-written as other parts of the function have been refactored
751 // for now we just check if the given table is to be included in this function
752 if (!in_array($table, $includedTables)) {
755 foreach ($group['fields'] as $fieldID => $dontCare) {
756 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
763 * Build the entity-specific custom data into the group tree on a per-field basis
766 * Object representing the custom field to be populated into the groupTree.
767 * @param array $groupTree
768 * (reference) the group tree being build.
769 * @param string $table
771 * @param unknown_type $groupID
773 * @param unknown_type $fieldID
776 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID) {
777 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
778 $idName = "{$table}_id";
779 $fieldName = "{$table}_{$column}";
780 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
781 if ($dataType == 'File') {
782 if (isset($dao->$fieldName)) {
783 $config = CRM_Core_Config
::singleton();
784 $fileDAO = new CRM_Core_DAO_File();
785 $fileDAO->id
= $dao->$fieldName;
787 if ($fileDAO->find(TRUE)) {
788 $entityIDName = "{$table}_entity_id";
789 $customValue['id'] = $dao->$idName;
790 $customValue['data'] = $fileDAO->uri
;
791 $customValue['fid'] = $fileDAO->id
;
792 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
793 $customValue['displayURL'] = NULL;
794 $deleteExtra = ts('Are you sure you want to delete attached file.');
796 CRM_Core_Action
::DELETE
=> array(
797 'name' => ts('Delete Attached File'),
798 'url' => 'civicrm/file',
799 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
800 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra .
801 '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
804 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
805 CRM_Core_Action
::DELETE
,
807 'id' => $fileDAO->id
,
808 'eid' => $dao->$entityIDName,
813 'file.manage.delete',
817 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
818 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
819 if ($fileDAO->mime_type
== "image/jpeg" ||
820 $fileDAO->mime_type
== "image/pjpeg" ||
821 $fileDAO->mime_type
== "image/gif" ||
822 $fileDAO->mime_type
== "image/x-png" ||
823 $fileDAO->mime_type
== "image/png"
825 $customValue['displayURL'] = $customValue['fileURL'];
826 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
831 $customValue['imageURL'] =
832 str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
834 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId,
837 if ($path && file_exists($path)) {
838 list($imageWidth, $imageHeight) = getimagesize($path);
839 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
840 $customValue['imageThumbWidth'] = $imageThumbWidth;
841 $customValue['imageThumbHeight'] = $imageThumbHeight;
847 $customValue = array(
848 'id' => $dao->$idName,
854 $customValue = array(
855 'id' => $dao->$idName,
856 'data' => $dao->$fieldName,
860 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
861 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
863 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
864 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
867 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
872 * Get the group title.
877 * @return string title
882 public static function getTitle($id) {
883 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
887 * Get custom group details for a group.
889 * An array containing custom group details (including their custom field) is returned.
891 * @param int $groupId
892 * Group id whose details are needed.
893 * @param bool $searchable
894 * Is this field searchable.
895 * @param array $extends
896 * Which table does it extend if any.
898 * @param null $inSelector
900 * @return array $groupTree - array consisting of all group and field details
905 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
907 $groupTree = array();
908 $select = $from = $where = $orderBy = '';
910 $tableData = array();
912 // using tableData to build the queryString
914 'civicrm_custom_field' => array(
938 'civicrm_custom_group' => array(
945 'collapse_adv_display',
947 'extends_entity_column_value',
956 foreach ($tableData as $tableName => $tableColumn) {
957 foreach ($tableColumn as $columnName) {
958 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
961 $select = 'SELECT ' . implode(', ', $s);
963 // from, where, order by
964 $from = " FROM civicrm_custom_field, civicrm_custom_group";
965 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
966 AND civicrm_custom_group.is_active = 1
967 AND civicrm_custom_field.is_active = 1 ";
969 $params[1] = array($groupId, 'Integer');
970 $where .= " AND civicrm_custom_group.id = %1";
974 $where .= " AND civicrm_custom_field.is_searchable = 1";
978 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
983 foreach ($extends as $e) {
984 $clause[] = "civicrm_custom_group.extends = '$e'";
986 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
988 //include case activities customdata if case is enabled
989 if (in_array('Activity', $extends)) {
990 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
991 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
992 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
996 // ensure that the user has access to these custom groups
998 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
999 'civicrm_custom_group.'
1002 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1004 // final query string
1005 $queryString = $select . $from . $where . $orderBy;
1008 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1011 while ($crmDAO->fetch()) {
1012 $groupId = $crmDAO->civicrm_custom_group_id
;
1013 $fieldId = $crmDAO->civicrm_custom_field_id
;
1015 // create an array for groups if it does not exist
1016 if (!array_key_exists($groupId, $groupTree)) {
1017 $groupTree[$groupId] = array();
1018 $groupTree[$groupId]['id'] = $groupId;
1020 foreach ($tableData['civicrm_custom_group'] as $v) {
1021 $fullField = "civicrm_custom_group_" . $v;
1023 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1027 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1030 $groupTree[$groupId]['fields'] = array();
1033 // add the fields now (note - the query row will always contain a field)
1034 $groupTree[$groupId]['fields'][$fieldId] = array();
1035 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1037 foreach ($tableData['civicrm_custom_field'] as $v) {
1038 $fullField = "civicrm_custom_field_" . $v;
1039 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1042 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1050 * @param $entityType
1052 * @param string $cidToken
1056 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1058 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1060 // get 'Tab' and 'Tab with table' groups
1061 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1062 $customGroupDAO->whereAdd("is_active = 1");
1064 // add whereAdd for entity type
1065 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1069 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1070 $customGroupDAO->whereAdd($permissionClause);
1073 $customGroupDAO->orderBy('weight');
1074 $customGroupDAO->find();
1076 // process each group with menu tab
1077 while ($customGroupDAO->fetch()) {
1079 $group['id'] = $customGroupDAO->id
;
1080 $group['path'] = $path;
1081 $group['title'] = "$customGroupDAO->title";
1082 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1083 $group['extra'] = array('gid' => $customGroupDAO->id
);
1084 $group['table_name'] = $customGroupDAO->table_name
;
1085 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1093 * Get the table name for the entity type
1094 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1095 * tableName is 'civicrm_contact'
1097 * @param string $entityType
1098 * What entity are we extending here ?.
1100 * @return string $tableName
1104 * @see _apachesolr_civiAttachments_dereference_file_parent
1106 public static function getTableNameByEntityName($entityType) {
1108 switch ($entityType) {
1112 case 'Organization':
1113 $tableName = 'civicrm_contact';
1116 case 'Contribution':
1117 $tableName = 'civicrm_contribution';
1121 $tableName = 'civicrm_group';
1124 // DRAFTING: Verify if we cannot make it pluggable
1127 $tableName = 'civicrm_activity';
1130 case 'Relationship':
1131 $tableName = 'civicrm_relationship';
1135 $tableName = 'civicrm_membership';
1139 $tableName = 'civicrm_participant';
1143 $tableName = 'civicrm_event';
1147 $tableName = 'civicrm_grant';
1150 // need to add cases for Location, Address
1157 * Get a list of custom groups which extend a given entity type.
1158 * If there are custom-groups which only apply to certain subtypes,
1159 * those WILL be included.
1161 * @param string $entityType
1163 * @return CRM_Core_DAO_CustomGroup
1165 public static function getAllCustomGroupsByBaseEntity($entityType) {
1166 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1167 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1168 return $customGroupDAO;
1172 * Add the whereAdd clause for the DAO depending on the type of entity
1173 * the custom group is extending.
1175 * @param $customGroupDAO
1176 * @param string $entityType
1177 * What entity are we extending here ?.
1179 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
1180 * @param bool $allSubtypes
1186 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1187 $addSubtypeClause = FALSE;
1189 switch ($entityType) {
1191 // if contact, get all related to contact
1192 $extendList = "'Contact','Individual','Household','Organization'";
1193 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1194 if (!$allSubtypes) {
1195 $addSubtypeClause = TRUE;
1201 case 'Organization':
1202 // is I/H/O then get I/H/O and contact
1203 $extendList = "'Contact','$entityType'";
1204 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1205 if (!$allSubtypes) {
1206 $addSubtypeClause = TRUE;
1214 case 'Contribution':
1217 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1221 if ($addSubtypeClause) {
1222 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1224 if (!empty($csType)) {
1225 $subtypeClause = array();
1226 foreach ($csType as $subtype) {
1227 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1228 CRM_Core_DAO
::VALUE_SEPARATOR
;
1229 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1231 $subtypeClause[] = "extends_entity_column_value IS NULL";
1232 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1236 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1242 * Delete the Custom Group.
1245 * Object the DAO custom group object.
1246 * @param bool $force
1247 * whether to force the deletion, even if there are custom fields.
1249 * @return boolean false if field exists for this group, true if group gets deleted.
1254 public static function deleteGroup($group, $force = FALSE) {
1256 //check wheter this contain any custom fields
1257 $customField = new CRM_Core_DAO_CustomField();
1258 $customField->custom_group_id
= $group->id
;
1259 $customField->find();
1261 // return early if there are custom fields and we're not
1262 // forcing the delete, otherwise delete the fields one by one
1263 while ($customField->fetch()) {
1267 CRM_Core_BAO_CustomField
::deleteField($customField);
1270 // drop the table associated with this custom group
1271 CRM_Core_BAO_SchemaHandler
::dropTable($group->table_name
);
1273 //delete custom group
1276 CRM_Utils_Hook
::post('delete', 'CustomGroup', $group->id
, $group);
1284 * @param bool $viewMode
1285 * @param bool $inactiveNeeded
1286 * @param int $action
1288 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1289 foreach ($groupTree as $id => $group) {
1290 if (!isset($group['fields'])) {
1293 foreach ($group['fields'] as $field) {
1294 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1295 $value = $field['element_value'];
1297 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1298 ($action != CRM_Core_Action
::UPDATE ||
1300 !array_key_exists('element_value', $field)
1303 $value = $viewMode ?
NULL : $field['default_value'];
1309 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;
1427 * @param array $params
1428 * @param bool $skipFile
1430 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1431 // Get the Custom form values and groupTree
1432 // first reset all checkbox and radio data
1433 foreach ($groupTree as $groupID => $group) {
1434 if ($groupID === 'info') {
1437 foreach ($group['fields'] as $field) {
1438 $fieldId = $field['id'];
1440 //added Multi-Select option in the below if-statement
1441 if ($field['html_type'] == 'CheckBox' ||
1442 $field['html_type'] == 'Radio' ||
1443 $field['html_type'] == 'AdvMulti-Select' ||
1444 $field['html_type'] == 'Multi-Select'
1446 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1450 foreach ($params as $key => $val) {
1451 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1452 $match[1] == $field['id']
1458 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1459 // field exists in db so populate value from "form".
1460 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1463 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1465 //added for CheckBox
1469 $customValue = array_keys($v);
1470 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] =
1471 CRM_Core_DAO
::VALUE_SEPARATOR
.
1472 implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue) .
1473 CRM_Core_DAO
::VALUE_SEPARATOR
;
1476 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1480 //added for Advanced Multi-Select
1482 case 'AdvMulti-Select':
1483 //added for Multi-Select
1484 case 'Multi-Select':
1486 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] =
1487 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.
1564 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1565 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1567 // this is fix for date field
1568 $form->assign('currentYear', date('Y'));
1570 foreach ($groupTree as $id => $group) {
1571 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1572 foreach ($group['fields'] as $field) {
1573 $required = CRM_Utils_Array
::value('is_required', $field);
1575 if ($field['data_type'] == 'File') {
1576 if (!empty($field['element_value']['data'])) {
1581 $fieldId = $field['id'];
1582 $elementName = $field['element_name'];
1583 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1589 * Extract the get params from the url, validate
1590 * and store it in session
1592 * @param CRM_Core_Form $form
1594 * @param string $type
1595 * The type of custom group we are using.
1600 public static function extractGetParams(&$form, $type) {
1605 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1606 $customValue = array();
1615 foreach ($groupTree as $group) {
1616 if (!isset($group['fields'])) {
1619 foreach ($group['fields'] as $key => $field) {
1620 $fieldName = 'custom_' . $key;
1621 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1625 if (!in_array($field['html_type'], $htmlType) ||
1626 $field['data_type'] == 'Boolean'
1628 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1630 if ($field['html_type'] == 'CheckBox' ||
1631 $field['html_type'] == 'AdvMulti-Select' ||
1632 $field['html_type'] == 'Multi-Select'
1634 $value = str_replace("|", ",", $value);
1635 $mulValues = explode(',', $value);
1636 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1638 foreach ($mulValues as $v1) {
1639 foreach ($customOption as $coID => $coValue) {
1640 if (strtolower(trim($coValue['label'])) ==
1641 strtolower(trim($v1))
1643 $val[$coValue['value']] = 1;
1655 elseif ($field['html_type'] == 'Select' ||
1656 ($field['html_type'] == 'Radio' &&
1657 $field['data_type'] != 'Boolean'
1660 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1661 foreach ($customOption as $customID => $coValue) {
1662 if (strtolower(trim($coValue['label'])) ==
1663 strtolower(trim($value))
1665 $value = $coValue['value'];
1670 elseif ($field['data_type'] == 'Date') {
1671 if (!empty($value)) {
1673 if (!empty($field['time_format'])) {
1674 $time = CRM_Utils_Request
::retrieve($fieldName .
1675 '_time', 'String', $form, FALSE, NULL, 'GET');
1677 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value .
1679 if (!empty($field['time_format'])) {
1680 $customValue[$fieldName . '_time'] = $time;
1687 $customValue[$fieldName] = $value;
1693 return $customValue;
1697 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1698 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1700 * @param int $customFieldId
1702 * @param array $removeCustomFieldTypes
1703 * Remove custom fields of a type eg: array("Individual") ;.
1706 * @return boolean false if it matches else true
1709 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1710 $query = "SELECT cg.extends as extends
1711 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1712 WHERE cg.id = cf.custom_group_id
1714 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1716 $extends = CRM_Core_DAO
::singleValueQuery($query);
1718 if (in_array($extends, $removeCustomFieldTypes)) {
1730 public static function mapTableName($table) {
1735 case 'Organization':
1736 return 'civicrm_contact';
1739 return 'civicrm_activity';
1742 return 'civicrm_group';
1744 case 'Contribution':
1745 return 'civicrm_contribution';
1747 case 'Relationship':
1748 return 'civicrm_relationship';
1751 return 'civicrm_event';
1754 return 'civicrm_membership';
1757 case 'ParticipantRole':
1758 case 'ParticipantEventName':
1759 case 'ParticipantEventType':
1760 return 'civicrm_participant';
1763 return 'civicrm_grant';
1766 return 'civicrm_pledge';
1769 return 'civicrm_address';
1772 return 'civicrm_campaign';
1776 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1777 $qParams = array(1 => array($table, 'String'));
1778 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1781 return 'civicrm_contact';
1784 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1785 if (array_key_exists($table, $extendObjs)) {
1786 return $extendObjs[$table];
1788 CRM_Core_Error
::fatal();
1796 public static function createTable($group) {
1798 'name' => $group->table_name
,
1799 'is_multiple' => $group->is_multiple ?
1 : 0,
1800 'extends_name' => self
::mapTableName($group->extends),
1803 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1805 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1809 * Function returns formatted groupTree, sothat form can be easily build in template
1811 * @param array $groupTree
1813 * @param int $groupCount
1814 * Group count by default 1, but can varry for multiple value custom data.
1815 * @param object form object
1817 * @return array $formattedGroupTree
1819 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1820 $formattedGroupTree = array();
1821 $uploadNames = array();
1823 foreach ($groupTree as $key => $value) {
1824 if ($key === 'info') {
1828 // add group information
1829 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1830 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1831 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1832 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1833 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1834 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1836 // this params needed of bulding multiple values
1837 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1838 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1839 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1840 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1841 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1842 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1844 // add field information
1845 foreach ($value['fields'] as $k => $properties) {
1846 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1847 if (isset($properties['customValue']) &&
1848 !CRM_Utils_System
::isNull($properties['customValue'])
1850 if (isset($properties['customValue'][$groupCount])) {
1851 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1852 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1853 if ($properties['data_type'] == 'File') {
1854 $properties['element_value'] = $properties['customValue'][$groupCount];
1855 $uploadNames[] = $properties['element_name'];
1858 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1862 unset($properties['customValue']);
1863 $formattedGroupTree[$key]['fields'][$k] = $properties;
1868 // hack for field type File
1869 $formUploadNames = $form->get('uploadNames');
1870 if (is_array($formUploadNames)) {
1871 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1874 $form->set('uploadNames', $uploadNames);
1877 return $formattedGroupTree;
1881 * Build custom data view
1883 * @param CRM_Core_Form $form
1885 * @param array $groupTree
1887 * @param bool $returnCount
1888 * True if customValue count needs to be returned.
1890 * @param null $prefix
1891 * @param int $customValueId
1895 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1897 foreach ($groupTree as $key => $group) {
1898 if ($key === 'info') {
1902 foreach ($group['fields'] as $k => $properties) {
1903 $groupID = $group['id'];
1904 if (!empty($properties['customValue'])) {
1905 foreach ($properties['customValue'] as $values) {
1906 if (!empty($customValueId) && $customValueId != $values['id']) {
1909 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1910 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1911 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1912 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1913 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1914 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1915 $details[$groupID][$values['id']]['fields'][$k] = array(
1916 'field_title' => CRM_Utils_Array
::value('label', $properties),
1917 'field_type' => CRM_Utils_Array
::value('html_type',
1920 'field_data_type' => CRM_Utils_Array
::value('data_type',
1923 'field_value' => self
::formatCustomValues($values,
1926 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1930 // also return contact reference contact id if user has view all or edit all contacts perm
1931 if ((CRM_Core_Permission
::check('view all contacts') ||
1932 CRM_Core_Permission
::check('edit all contacts'))
1934 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1937 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1942 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1943 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1944 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1945 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1946 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1947 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1948 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1954 //return a single value count if group id is passed to function
1955 //else return a groupId and count mapped array
1957 return count($details[$gID]);
1960 $countValue = array();
1961 foreach ($details as $key => $value) {
1962 $countValue[$key] = count($details[$key]);
1968 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1974 * Format custom value according to data, view mode
1976 * @param array $values
1977 * Associated array of custom values.
1978 * @param array $field
1980 * @param bool $dncOptionPerLine
1981 * True if optionPerLine should not be consider.
1983 * @return array|null|string
1985 public static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1986 $value = $values['data'];
1988 //changed isset CRM-4601
1989 if (CRM_Utils_System
::isNull($value)) {
1993 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1994 $dataType = CRM_Utils_Array
::value('data_type', $field);
1995 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1996 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1997 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
2000 $freezeStringChecked = "";
2002 switch ($dataType) {
2004 $customTimeFormat = '';
2005 $customFormat = NULL;
2007 switch ($timeFormat) {
2009 $customTimeFormat = '%l:%M %P';
2013 $customTimeFormat = '%H:%M';
2017 // if time is not selected remove time from value
2018 $value = substr($value, 0, 10);
2021 $supportableFormats = array(
2022 'mm/dd' => "%B %E%f $customTimeFormat",
2023 'dd-mm' => "%E%f %B $customTimeFormat",
2024 'yy' => "%Y $customTimeFormat",
2025 'M yy' => "%b %Y $customTimeFormat",
2026 'yy-mm' => "%Y-%m $customTimeFormat",
2029 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
2030 if (array_key_exists($format, $supportableFormats)) {
2031 $customFormat = $supportableFormats["$format"];
2035 $retValue = CRM_Utils_Date
::customFormat($value, $customFormat);
2039 if ($value == '1') {
2040 $retValue = $freezeStringChecked . ts('Yes') . "\n";
2043 $retValue = $freezeStringChecked . ts('No') . "\n";
2049 $retValue = CRM_Utils_System
::formatWikiURL($value);
2054 $retValue = $values;
2057 case 'ContactReference':
2058 if (!empty($values['data'])) {
2059 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
2068 if ($htmlType == 'Text') {
2069 $retValue = (float) $value;
2073 if ($htmlType == 'Text') {
2074 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2079 if (in_array($htmlType, array('Text', 'TextArea'))) {
2083 // note that if its not text / textarea, the code falls thru and executes
2084 // the below case also
2085 case 'StateProvince':
2090 //added check for Multi-Select in the below if-statement
2091 $customData[] = $value;
2093 //form custom data for multiple-valued custom data
2094 switch ($htmlType) {
2095 case 'Multi-Select Country':
2096 case 'Select Country':
2097 $customData = $value;
2098 if (!is_array($value)) {
2099 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2102 SELECT id as value, name as label
2103 FROM civicrm_country";
2104 $coDAO = CRM_Core_DAO
::executeQuery($query);
2107 case 'Select State/Province':
2108 case 'Multi-Select State/Province':
2109 $customData = $value;
2110 if (!is_array($value)) {
2111 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2115 SELECT id as value, name as label
2116 FROM civicrm_state_province";
2117 $coDAO = CRM_Core_DAO
::executeQuery($query);
2121 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2122 if ($option_group_id) {
2123 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2128 case 'AdvMulti-Select':
2129 case 'Multi-Select':
2130 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2132 if ($option_group_id) {
2133 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2137 if (is_object($coDAO)) {
2138 while ($coDAO->fetch()) {
2139 if ($dataType == 'Country') {
2140 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2141 // and already extracted to .pot files.
2142 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
2144 elseif ($dataType == 'StateProvince') {
2145 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
2148 $options[$coDAO->value
] = $coDAO->label
;
2153 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
2156 foreach ($options as $optionValue => $optionLabel) {
2157 if ($dataType == 'Money') {
2158 foreach ($customData as $k => $v) {
2159 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
2163 //to show only values that are checked
2164 if (in_array((string) $optionValue, $customData)) {
2165 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
2166 if (!$optionPerLine ||
$dncOptionPerLine) {
2170 $retValue .= $checked . $optionLabel;
2173 $retValue[] = $checked . $optionLabel;
2180 //special case for option per line formatting
2181 if ($optionPerLine > 1 && is_array($retValue)) {
2184 $displayValues = array();
2185 $displayString = '';
2186 foreach ($retValue as $val) {
2187 if ($displayString) {
2188 $displayString .= ", ";
2191 $displayString .= $val;
2195 if (($rowCounter == $optionPerLine) ||
2196 ($fieldCounter == count($retValue))
2198 $displayValues[] = $displayString;
2199 $displayString = '';
2203 $retValue = $displayValues;
2206 $retValue = isset($retValue) ?
$retValue : NULL;
2211 * Get the custom group titles by custom field ids.
2213 * @param array $fieldIds
2214 * Array of custom field ids.
2216 * @return array $groupLabels - array consisting of groups and fields labels with ids.
2218 public static function getGroupTitles($fieldIds) {
2219 if (!is_array($fieldIds) && empty($fieldIds)) {
2223 $groupLabels = array();
2224 $fIds = "(" . implode(',', $fieldIds) . ")";
2227 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2228 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2229 FROM civicrm_custom_group, civicrm_custom_field
2230 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2231 AND civicrm_custom_field.id IN {$fIds}";
2233 $dao = CRM_Core_DAO
::executeQuery($query);
2234 while ($dao->fetch()) {
2235 $groupLabels[$dao->fieldID
] = array(
2236 'fieldID' => $dao->fieldID
,
2237 'fieldLabel' => $dao->fieldLabel
,
2238 'groupID' => $dao->groupID
,
2239 'groupTitle' => $dao->groupTitle
,
2243 return $groupLabels;
2246 public static function dropAllTables() {
2247 $query = "SELECT table_name FROM civicrm_custom_group";
2248 $dao = CRM_Core_DAO
::executeQuery($query);
2250 while ($dao->fetch()) {
2251 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2252 CRM_Core_DAO
::executeQuery($query);
2257 * Check whether custom group is empty or not.
2262 * @return boolean true if empty otherwise false.
2264 public static function isGroupEmpty($gID) {
2269 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2274 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2275 $value = CRM_Core_DAO
::singleValueQuery($query);
2277 if (empty($value)) {
2285 * Get the list of types for objects that a custom group extends to.
2287 * @param array $types
2288 * Var which should have the list appended.
2290 * @return array of types.
2292 public static function getExtendedObjectTypes(&$types = array()) {
2293 static $flag = FALSE, $objTypes = array();
2296 $extendObjs = array();
2297 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2299 foreach ($extendObjs as $ovId => $ovValues) {
2300 if ($ovValues['description']) {
2301 // description is expected to be a callback func to subtypes
2302 list($callback, $args) = explode(';', trim($ovValues['description']));
2308 if (!is_array($args)) {
2309 CRM_Core_Error
::fatal('Arg is not of type array');
2312 list($className) = explode('::', $callback);
2313 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2316 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2322 $types = array_merge($types, $objTypes);
2327 * @param int $customGroupId
2328 * @param int $entityId
2332 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2333 //check whether the group is multiple
2334 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2335 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2336 $hasReachedMax = FALSE;
2338 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2340 if (!$maxMultiple) {
2341 $hasReachedMax = FALSE;
2344 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2345 //count the number of entries for a entity
2346 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2347 $params = array(1 => array($entityId, 'Integer'));
2348 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2350 if ($count >= $maxMultiple) {
2351 $hasReachedMax = TRUE;
2355 return $hasReachedMax;
2361 public static function getMultipleFieldGroup() {
2362 $multipleGroup = array();
2363 $dao = new CRM_Core_DAO_CustomGroup();
2364 $dao->is_multiple
= 1;
2366 while ($dao->fetch()) {
2367 $multipleGroup[$dao->id
] = $dao->title
;
2369 return $multipleGroup;