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
59 public static function create(&$params) {
60 // create custom group dao, populate fields and then save.
61 $group = new CRM_Core_DAO_CustomGroup();
62 $group->title
= $params['title'];
64 if (in_array($params['extends'][0],
67 'ParticipantEventName',
68 'ParticipantEventType',
71 $group->extends = 'Participant';
74 $group->extends = $params['extends'][0];
77 $group->extends_entity_column_id
= 'null';
79 $params['extends'][0] == 'ParticipantRole' ||
80 $params['extends'][0] == 'ParticipantEventName' ||
81 $params['extends'][0] == 'ParticipantEventType'
83 $group->extends_entity_column_id
=
84 CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $params['extends'][0], 'value', 'name');
87 //this is format when form get submit.
88 $extendsChildType = CRM_Utils_Array
::value(1, $params['extends']);
89 //lets allow user to pass direct child type value, CRM-6893
90 if (!empty($params['extends_entity_column_value'])) {
91 $extendsChildType = $params['extends_entity_column_value'];
93 if (!CRM_Utils_System
::isNull($extendsChildType)) {
94 $extendsChildType = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendsChildType);
95 if (CRM_Utils_Array
::value(0, $params['extends']) == 'Relationship') {
96 $extendsChildType = str_replace(array('_a_b', '_b_a'), array(
99 ), $extendsChildType);
101 if (substr($extendsChildType, 0, 1) != CRM_Core_DAO
::VALUE_SEPARATOR
) {
102 $extendsChildType = CRM_Core_DAO
::VALUE_SEPARATOR
. $extendsChildType .
103 CRM_Core_DAO
::VALUE_SEPARATOR
;
107 $extendsChildType = 'null';
109 $group->extends_entity_column_value
= $extendsChildType;
111 if (isset($params['id'])) {
112 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $params['id'], 'weight', 'id');
117 $group->weight
= CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomGroup', $oldWeight, CRM_Utils_Array
::value('weight', $params, FALSE));
121 'collapse_adv_display',
127 foreach ($fields as $field) {
128 $group->$field = CRM_Utils_Array
::value($field, $params, FALSE);
130 $group->max_multiple
= isset($params['is_multiple']) ?
(isset($params['max_multiple']) &&
131 $params['max_multiple'] >= '0'
132 ) ?
$params['max_multiple'] : 'null' : 'null';
134 $tableName = $oldTableName = NULL;
135 if (isset($params['id'])) {
136 $group->id
= $params['id'];
137 //check whether custom group was changed from single-valued to multiple-valued
138 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
143 if ((!empty($params['is_multiple']) ||
$isMultiple) &&
144 ($params['is_multiple'] != $isMultiple)
146 $oldTableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
153 $group->created_id
= CRM_Utils_Array
::value('created_id', $params);
154 $group->created_date
= CRM_Utils_Array
::value('created_date', $params);
156 // we do this only once, so name never changes
157 if (isset($params['name'])) {
158 $group->name
= CRM_Utils_String
::munge($params['name'], '_', 64);
161 $group->name
= CRM_Utils_String
::munge($group->title
, '_', 64);
164 if (isset($params['table_name'])) {
165 $tableName = $params['table_name'];
167 if (CRM_Core_DAO_AllCoreTables
::isCoreTable($tableName)) {
168 // Bad idea. Prevent group creation because it might lead to a broken configuration.
169 CRM_Core_Error
::fatal(ts("Cannot create custom table because %1 is already a core table.", array('1' => $tableName)));
174 if (array_key_exists('is_reserved', $params)) {
175 $group->is_reserved
= $params['is_reserved'] ?
1 : 0;
177 $op = isset($params['id']) ?
'edit' : 'create';
178 CRM_Utils_Hook
::pre($op, 'CustomGroup', CRM_Utils_Array
::value('id', $params), $params);
180 // enclose the below in a transaction
181 $transaction = new CRM_Core_Transaction();
184 if (!isset($params['id'])) {
185 if (!isset($params['table_name'])) {
186 $munged_title = strtolower(CRM_Utils_String
::munge($group->title
, '_', 42));
187 $tableName = "civicrm_value_{$munged_title}_{$group->id}";
189 $group->table_name
= $tableName;
190 CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup',
196 // now create the table associated with this group
197 self
::createTable($group);
199 elseif ($oldTableName) {
200 CRM_Core_BAO_SchemaHandler
::changeUniqueToIndex($oldTableName, CRM_Utils_Array
::value('is_multiple', $params));
203 if (CRM_Utils_Array
::value('overrideFKConstraint', $params) == 1) {
204 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
208 CRM_Core_BAO_SchemaHandler
::changeFKConstraint($table, self
::mapTableName($params['extends'][0]));
210 $transaction->commit();
213 CRM_Utils_System
::flushCache();
216 CRM_Utils_Hook
::post('create', 'CustomGroup', $group->id
, $group);
219 CRM_Utils_Hook
::post('edit', 'CustomGroup', $group->id
, $group);
226 * Fetch object based on array of properties
228 * @param array $params
229 * (reference ) an assoc array of name/value pairs.
230 * @param array $defaults
231 * (reference ) an assoc array to hold the flattened values.
233 * @return CRM_Core_DAO_CustomGroup
235 public static function retrieve(&$params, &$defaults) {
236 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomGroup', $params, $defaults);
240 * Update the is_active flag in the db
243 * Id of the database record.
244 * @param bool $is_activeValue we want to set the is_active field.
245 * Value we want to set the is_active field.
248 * DAO object on sucess, null otherwise
250 public static function setIsActive($id, $is_active) {
252 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
255 CRM_Core_BAO_UFField
::setUFFieldStatus($id, $is_active);
258 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active);
262 * Determine if given entity (sub)type has any custom groups
264 * @param string $extends
265 * E.g. "Individual", "Activity".
266 * @param int $columnId
267 * E.g. custom-group matching mechanism (usu NULL for matching on sub type-id); see extends_entity_column_id.
268 * @param string $columnValue
269 * E.g. "Student" or "3" or "3\05"; see extends_entity_column_value.
273 public static function hasCustomGroup($extends, $columnId, $columnValue) {
274 $dao = new CRM_Core_DAO_CustomGroup();
275 $dao->extends = $extends;
276 $dao->extends_entity_column_id
= $columnId;
278 CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Core_DAO
::escapeString($columnValue) .
279 CRM_Core_DAO
::VALUE_SEPARATOR
;
280 $dao->whereAdd("extends_entity_column_value LIKE \"%$escapedValue%\"");
281 //$dao->extends_entity_column_value = $columnValue;
282 return $dao->find() ?
TRUE : FALSE;
286 * Determine if there are any CustomGroups for the given $activityTypeId.
287 * If none found, create one.
289 * @param int $activityTypeId
292 * TRUE if a group is found or created; FALSE on error
294 public static function autoCreateByActivityType($activityTypeId) {
295 if (self
::hasCustomGroup('Activity', NULL, $activityTypeId)) {
298 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE, FALSE); // everything
301 'extends' => 'Activity',
302 'extends_entity_column_id' => NULL,
303 'extends_entity_column_value' => CRM_Utils_Array
::implodePadded(array($activityTypeId)),
304 'title' => ts('%1 Questions', array(1 => $activityTypes[$activityTypeId])),
308 $result = civicrm_api('CustomGroup', 'create', $params);
309 return !$result['is_error'];
313 * Get custom groups/fields data for type of entity in a tree structure representing group->field hierarchy
314 * This may also include entity specific data values.
316 * An array containing all custom groups and their custom fields is returned.
318 * @param string $entityType
319 * Of the contact whose contact type is needed.
320 * @param CRM_Core_Form $form
321 * Not used but required.
322 * @param int $entityID
323 * @param int $groupID
324 * @param string $subType
325 * @param string $subName
326 * @param bool $fromCache
327 * @param bool $onlySubType
330 * 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
340 public static function &getTree(
351 $entityID = CRM_Utils_Type
::escape($entityID, 'Integer');
355 $strSelect = $strFrom = $strWhere = $orderBy = '';
356 $tableData = array();
358 // using tableData to build the queryString
360 'civicrm_custom_field' => array(
380 'civicrm_custom_group' => array(
390 'extends_entity_column_id',
391 'extends_entity_column_value',
398 foreach ($tableData as $tableName => $tableColumn) {
399 foreach ($tableColumn as $columnName) {
400 $alias = $tableName . "_" . $columnName;
401 $select[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
404 $strSelect = "SELECT " . implode(', ', $select);
406 // from, where, order by
408 FROM civicrm_custom_group
409 LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id)
412 // if entity is either individual, organization or household pls get custom groups for 'contact' too.
413 if ($entityType == "Individual" ||
$entityType == 'Organization' ||
414 $entityType == 'Household'
416 $in = "'$entityType', 'Contact'";
418 elseif (strpos($entityType, "'") !== FALSE) {
419 // this allows the calling function to send in multiple entity types
424 $in = "'$entityType'";
429 if (is_array($subType)) {
430 $subType = implode(',', $subType);
432 if (strpos($subType, ',')) {
433 $subTypeParts = explode(',', $subType);
434 $subTypeClauses = array();
435 foreach ($subTypeParts as $subTypePart) {
436 $subTypePart = CRM_Core_DAO
::VALUE_SEPARATOR
.
437 trim($subTypePart, CRM_Core_DAO
::VALUE_SEPARATOR
) .
438 CRM_Core_DAO
::VALUE_SEPARATOR
;
439 $subTypeClauses[] = "civicrm_custom_group.extends_entity_column_value LIKE '%$subTypePart%'";
443 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) . ')';
446 $subTypeClause = '(' . implode(' OR ', $subTypeClauses) .
447 " OR civicrm_custom_group.extends_entity_column_value IS NULL )";
451 $subType = CRM_Core_DAO
::VALUE_SEPARATOR
.
452 trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
) .
453 CRM_Core_DAO
::VALUE_SEPARATOR
;
456 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%' )";
459 $subTypeClause = "( civicrm_custom_group.extends_entity_column_value LIKE '%$subType%'
460 OR civicrm_custom_group.extends_entity_column_value IS NULL )";
465 WHERE civicrm_custom_group.is_active = 1
466 AND civicrm_custom_field.is_active = 1
467 AND civicrm_custom_group.extends IN ($in)
471 $strWhere .= " AND civicrm_custom_group.extends_entity_column_id = {$subName} ";
476 WHERE civicrm_custom_group.is_active = 1
477 AND civicrm_custom_field.is_active = 1
478 AND civicrm_custom_group.extends IN ($in)
479 AND civicrm_custom_group.extends_entity_column_value IS NULL
485 // since we want a specific group id we add it to the where clause
486 $strWhere .= " AND civicrm_custom_group.id = %1";
487 $params[1] = array($groupID, 'Integer');
490 // since groupID is false we need to show all Inline groups
491 $strWhere .= " AND civicrm_custom_group.style = 'Inline'";
494 // ensure that the user has access to these custom groups
495 $strWhere .= " AND " .
496 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
497 'civicrm_custom_group.'
501 ORDER BY civicrm_custom_group.weight,
502 civicrm_custom_group.title,
503 civicrm_custom_field.weight,
504 civicrm_custom_field.label
507 // final query string
508 $queryString = "$strSelect $strFrom $strWhere $orderBy";
510 // lets see if we can retrieve the groupTree from cache
511 $cacheString = $queryString;
513 $cacheString .= "_{$groupID}";
516 $cacheString .= "_Inline";
519 $cacheKey = "CRM_Core_DAO_CustomGroup_Query " . md5($cacheString);
520 $multipleFieldGroupCacheKey =
521 "CRM_Core_DAO_CustomGroup_QueryMultipleFields " . md5($cacheString);
522 $cache = CRM_Utils_Cache
::singleton();
523 $tablesWithEntityData = array();
525 $groupTree = $cache->get($cacheKey);
526 $multipleFieldGroups = $cache->get($multipleFieldGroupCacheKey);
529 if (empty($groupTree)) {
530 $groupTree = $multipleFieldGroups = array();
531 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
532 $customValueTables = array();
535 while ($crmDAO->fetch()) {
537 $groupID = $crmDAO->civicrm_custom_group_id
;
538 $fieldId = $crmDAO->civicrm_custom_field_id
;
539 if ($crmDAO->civicrm_custom_group_is_multiple
) {
540 $multipleFieldGroups[$groupID] = $crmDAO->civicrm_custom_group_table_name
;
542 // create an array for groups if it does not exist
543 if (!array_key_exists($groupID, $groupTree)) {
544 $groupTree[$groupID] = array();
545 $groupTree[$groupID]['id'] = $groupID;
547 // populate the group information
548 foreach ($tableData['civicrm_custom_group'] as $fieldName) {
549 $fullFieldName = "civicrm_custom_group_$fieldName";
550 if ($fieldName == 'id' ||
551 is_null($crmDAO->$fullFieldName)
556 if ($fieldName == 'extends_entity_column_value' && $subType) {
557 $groupTree[$groupID]['subtype'] = trim($subType, CRM_Core_DAO
::VALUE_SEPARATOR
);
559 $groupTree[$groupID][$fieldName] = $crmDAO->$fullFieldName;
561 $groupTree[$groupID]['fields'] = array();
563 $customValueTables[$crmDAO->civicrm_custom_group_table_name
] = array();
566 // add the fields now (note - the query row will always contain a field)
567 // we only reset this once, since multiple values come is as multiple rows
568 if (!array_key_exists($fieldId, $groupTree[$groupID]['fields'])) {
569 $groupTree[$groupID]['fields'][$fieldId] = array();
572 $customValueTables[$crmDAO->civicrm_custom_group_table_name
][$crmDAO->civicrm_custom_field_column_name
] = 1;
573 $groupTree[$groupID]['fields'][$fieldId]['id'] = $fieldId;
574 // populate information for a custom field
575 foreach ($tableData['civicrm_custom_field'] as $fieldName) {
576 $fullFieldName = "civicrm_custom_field_$fieldName";
577 if ($fieldName == 'id' ||
578 is_null($crmDAO->$fullFieldName)
582 $groupTree[$groupID]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName;
586 if (!empty($customValueTables)) {
587 $groupTree['info'] = array('tables' => $customValueTables);
590 $cache->set($cacheKey, $groupTree);
591 $cache->set($multipleFieldGroupCacheKey, $multipleFieldGroups);
593 //entitySelectClauses is an array of select clauses for custom value tables which are not multiple
594 // and have data for the given entities. $entityMultipleSelectClauses is the same for ones with multiple
595 $entitySingleSelectClauses = $entityMultipleSelectClauses = $groupTree['info']['select'] = array();
596 $singleFieldTables = array();
597 // now that we have all the groups and fields, lets get the values
598 // since we need to know the table and field names
599 // add info to groupTree
601 if (isset($groupTree['info']) && !empty($groupTree['info']) &&
602 !empty($groupTree['info']['tables'])
604 $select = $from = $where = array();
605 $groupTree['info']['where'] = NULL;
607 foreach ($groupTree['info']['tables'] as $table => $fields) {
608 $groupTree['info']['from'][] = $table;
610 "{$table}.id as {$table}_id",
611 "{$table}.entity_id as {$table}_entity_id",
613 foreach ($fields as $column => $dontCare) {
614 $select[] = "{$table}.{$column} as {$table}_{$column}";
616 $groupTree['info']['select'] = array_merge($groupTree['info']['select'], $select);
618 $groupTree['info']['where'][] = "{$table}.entity_id = $entityID";
619 if (in_array($table, $multipleFieldGroups) &&
620 self
::customGroupDataExistsForEntity($entityID, $table)
622 $entityMultipleSelectClauses[$table] = $select;
625 $singleFieldTables[] = $table;
626 $entitySingleSelectClauses = array_merge($entitySingleSelectClauses, $select);
631 if ($entityID && !empty($singleFieldTables)) {
632 self
::buildEntityTreeSingleFields($groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTables);
634 $multipleFieldTablesWithEntityData = array_keys($entityMultipleSelectClauses);
635 if (!empty($multipleFieldTablesWithEntityData)) {
636 self
::buildEntityTreeMultipleFields($groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData);
644 * Check whether the custom group has any data for the given entity.
647 * @param int $entityID
648 * Id of entity for whom we are checking data for.
649 * @param string $table
650 * Table that we are checking.
652 * @param bool $getCount
655 * does this entity have data in this custom table
657 static public function customGroupDataExistsForEntity($entityID, $table, $getCount = FALSE) {
661 WHERE entity_id = $entityID
663 $recordExists = CRM_Core_DAO
::singleValueQuery($query);
665 return $recordExists;
667 return $recordExists ?
TRUE : FALSE;
671 * Build the group tree for Custom fields which are not 'is_multiple'
673 * The combination of all these fields in one query with a 'using' join was not working for
674 * multiple fields. These now have a new behaviour (one at a time) but the single fields still use this
675 * mechanism as it seemed to be acceptable in this context
677 * @param array $groupTree
678 * (reference) group tree array which is being built.
679 * @param int $entityID
680 * Id of entity for whom the tree is being build up.
681 * @param array $entitySingleSelectClauses
682 * Array of select clauses relevant to the entity.
683 * @param array $singleFieldTablesWithEntityData
684 * Array of tables in which this entity has data.
686 static public function buildEntityTreeSingleFields(&$groupTree, $entityID, $entitySingleSelectClauses, $singleFieldTablesWithEntityData) {
687 $select = implode(', ', $entitySingleSelectClauses);
688 $fromSQL = " (SELECT $entityID as entity_id ) as first ";
689 foreach ($singleFieldTablesWithEntityData as $table) {
690 $fromSQL .= "\nLEFT JOIN $table USING (entity_id)";
696 WHERE first.entity_id = $entityID
698 self
::buildTreeEntityDataFromQuery($groupTree, $query, $singleFieldTablesWithEntityData);
702 * Build the group tree for Custom fields which are 'is_multiple'
704 * This is done one table at a time to avoid Cross-Joins resulting in too many rows being returned
706 * @param array $groupTree
707 * (reference) group tree array which is being built.
708 * @param int $entityID
709 * Id of entity for whom the tree is being build up.
710 * @param array $entityMultipleSelectClauses
711 * Array of select clauses relevant to the entity.
712 * @param array $multipleFieldTablesWithEntityData
713 * Array of tables in which this entity has data.
715 static public function buildEntityTreeMultipleFields(&$groupTree, $entityID, $entityMultipleSelectClauses, $multipleFieldTablesWithEntityData) {
716 foreach ($entityMultipleSelectClauses as $table => $selectClauses) {
717 $select = implode(',', $selectClauses);
721 WHERE entity_id = $entityID
723 self
::buildTreeEntityDataFromQuery($groupTree, $query, array($table));
728 * Build the tree entity data - starting from a query retrieving the custom fields build the group
729 * tree data for the relevant entity (entity is included in the query).
731 * This function represents shared code between the buildEntityTreeMultipleFields & the buildEntityTreeSingleFields function
733 * @param array $groupTree
734 * (reference) group tree array which is being built.
735 * @param string $query
736 * @param array $includedTables
737 * Tables to include - required because the function (for historical reasons).
738 * iterates through the group tree
740 static public function buildTreeEntityDataFromQuery(&$groupTree, $query, $includedTables) {
741 $dao = CRM_Core_DAO
::executeQuery($query);
742 while ($dao->fetch()) {
743 foreach ($groupTree as $groupID => $group) {
744 if ($groupID === 'info') {
747 $table = $groupTree[$groupID]['table_name'];
748 //working from the groupTree instead of the table list means we have to iterate & exclude.
749 // this could possibly be re-written as other parts of the function have been refactored
750 // for now we just check if the given table is to be included in this function
751 if (!in_array($table, $includedTables)) {
754 foreach ($group['fields'] as $fieldID => $dontCare) {
755 self
::buildCustomFieldData($dao, $groupTree, $table, $groupID, $fieldID);
762 * Build the entity-specific custom data into the group tree on a per-field basis
765 * Object representing the custom field to be populated into the groupTree.
766 * @param array $groupTree
767 * (reference) the group tree being build.
768 * @param string $table
770 * @param unknown_type $groupID
772 * @param unknown_type $fieldID
775 static public function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID) {
776 $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
777 $idName = "{$table}_id";
778 $fieldName = "{$table}_{$column}";
779 $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
780 if ($dataType == 'File') {
781 if (isset($dao->$fieldName)) {
782 $config = CRM_Core_Config
::singleton();
783 $fileDAO = new CRM_Core_DAO_File();
784 $fileDAO->id
= $dao->$fieldName;
786 if ($fileDAO->find(TRUE)) {
787 $entityIDName = "{$table}_entity_id";
788 $customValue['id'] = $dao->$idName;
789 $customValue['data'] = $fileDAO->uri
;
790 $customValue['fid'] = $fileDAO->id
;
791 $customValue['fileURL'] = CRM_Utils_System
::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->$entityIDName}");
792 $customValue['displayURL'] = NULL;
793 $deleteExtra = ts('Are you sure you want to delete attached file.');
795 CRM_Core_Action
::DELETE
=> array(
796 'name' => ts('Delete Attached File'),
797 'url' => 'civicrm/file',
798 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete',
799 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra .
800 '\' ) ) this.href+=\'&confirmed=1\'; else return false;"',
803 $customValue['deleteURL'] = CRM_Core_Action
::formLink($deleteURL,
804 CRM_Core_Action
::DELETE
,
806 'id' => $fileDAO->id
,
807 'eid' => $dao->$entityIDName,
812 'file.manage.delete',
816 $customValue['deleteURLArgs'] = CRM_Core_BAO_File
::deleteURLArgs($table, $dao->$entityIDName, $fileDAO->id
);
817 $customValue['fileName'] = CRM_Utils_File
::cleanFileName(basename($fileDAO->uri
));
818 if ($fileDAO->mime_type
== "image/jpeg" ||
819 $fileDAO->mime_type
== "image/pjpeg" ||
820 $fileDAO->mime_type
== "image/gif" ||
821 $fileDAO->mime_type
== "image/x-png" ||
822 $fileDAO->mime_type
== "image/png"
824 $customValue['displayURL'] = $customValue['fileURL'];
825 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
830 $customValue['imageURL'] =
831 str_replace('persist/contribute', 'custom', $config->imageUploadURL
) .
833 list($path) = CRM_Core_BAO_File
::path($fileDAO->id
, $entityId,
836 if ($path && file_exists($path)) {
837 list($imageWidth, $imageHeight) = getimagesize($path);
838 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
839 $customValue['imageThumbWidth'] = $imageThumbWidth;
840 $customValue['imageThumbHeight'] = $imageThumbHeight;
846 $customValue = array(
847 'id' => $dao->$idName,
853 $customValue = array(
854 'id' => $dao->$idName,
855 'data' => $dao->$fieldName,
859 if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
860 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
862 if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
863 $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
866 $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
871 * Get the group title.
880 public static function getTitle($id) {
881 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $id, 'title');
885 * Get custom group details for a group.
887 * An array containing custom group details (including their custom field) is returned.
889 * @param int $groupId
890 * Group id whose details are needed.
891 * @param bool $searchable
892 * Is this field searchable.
893 * @param array $extends
894 * Which table does it extend if any.
896 * @param null $inSelector
899 * array consisting of all group and field details
903 public static function &getGroupDetail($groupId = NULL, $searchable = NULL, &$extends = NULL, $inSelector = NULL) {
905 $groupTree = array();
906 $select = $from = $where = $orderBy = '';
908 $tableData = array();
910 // using tableData to build the queryString
912 'civicrm_custom_field' => array(
936 'civicrm_custom_group' => array(
943 'collapse_adv_display',
945 'extends_entity_column_value',
954 foreach ($tableData as $tableName => $tableColumn) {
955 foreach ($tableColumn as $columnName) {
956 $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}";
959 $select = 'SELECT ' . implode(', ', $s);
961 // from, where, order by
962 $from = " FROM civicrm_custom_field, civicrm_custom_group";
963 $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id
964 AND civicrm_custom_group.is_active = 1
965 AND civicrm_custom_field.is_active = 1 ";
967 $params[1] = array($groupId, 'Integer');
968 $where .= " AND civicrm_custom_group.id = %1";
972 $where .= " AND civicrm_custom_field.is_searchable = 1";
976 $where .= " AND civicrm_custom_field.in_selector = 1 AND civicrm_custom_group.is_multiple = 1 ";
981 foreach ($extends as $e) {
982 $clause[] = "civicrm_custom_group.extends = '$e'";
984 $where .= " AND ( " . implode(' OR ', $clause) . " ) ";
986 //include case activities customdata if case is enabled
987 if (in_array('Activity', $extends)) {
988 $extendValues = implode(',', array_keys(CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE)));
989 $where .= " AND ( civicrm_custom_group.extends_entity_column_value IS NULL OR REPLACE( civicrm_custom_group.extends_entity_column_value, %2, ' ') IN ($extendValues) ) ";
990 $params[2] = array(CRM_Core_DAO
::VALUE_SEPARATOR
, 'String');
994 // ensure that the user has access to these custom groups
996 CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
997 'civicrm_custom_group.'
1000 $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight";
1002 // final query string
1003 $queryString = $select . $from . $where . $orderBy;
1006 $crmDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1009 while ($crmDAO->fetch()) {
1010 $groupId = $crmDAO->civicrm_custom_group_id
;
1011 $fieldId = $crmDAO->civicrm_custom_field_id
;
1013 // create an array for groups if it does not exist
1014 if (!array_key_exists($groupId, $groupTree)) {
1015 $groupTree[$groupId] = array();
1016 $groupTree[$groupId]['id'] = $groupId;
1018 foreach ($tableData['civicrm_custom_group'] as $v) {
1019 $fullField = "civicrm_custom_group_" . $v;
1021 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1025 $groupTree[$groupId][$v] = $crmDAO->$fullField;
1028 $groupTree[$groupId]['fields'] = array();
1031 // add the fields now (note - the query row will always contain a field)
1032 $groupTree[$groupId]['fields'][$fieldId] = array();
1033 $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId;
1035 foreach ($tableData['civicrm_custom_field'] as $v) {
1036 $fullField = "civicrm_custom_field_" . $v;
1037 if ($v == 'id' ||
is_null($crmDAO->$fullField)) {
1040 $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField;
1048 * @param $entityType
1050 * @param string $cidToken
1054 public static function &getActiveGroups($entityType, $path, $cidToken = '%%cid%%') {
1056 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1058 // get 'Tab' and 'Tab with table' groups
1059 $customGroupDAO->whereAdd("style IN ('Tab', 'Tab with table')");
1060 $customGroupDAO->whereAdd("is_active = 1");
1062 // add whereAdd for entity type
1063 self
::_addWhereAdd($customGroupDAO, $entityType, $cidToken);
1067 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
, NULL, TRUE);
1068 $customGroupDAO->whereAdd($permissionClause);
1071 $customGroupDAO->orderBy('weight');
1072 $customGroupDAO->find();
1074 // process each group with menu tab
1075 while ($customGroupDAO->fetch()) {
1077 $group['id'] = $customGroupDAO->id
;
1078 $group['path'] = $path;
1079 $group['title'] = "$customGroupDAO->title";
1080 $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}";
1081 $group['extra'] = array('gid' => $customGroupDAO->id
);
1082 $group['table_name'] = $customGroupDAO->table_name
;
1083 $group['is_multiple'] = $customGroupDAO->is_multiple
;
1091 * Get the table name for the entity type
1092 * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization'
1093 * tableName is 'civicrm_contact'
1095 * @param string $entityType
1096 * What entity are we extending here ?.
1101 * @see _apachesolr_civiAttachments_dereference_file_parent
1103 public static function getTableNameByEntityName($entityType) {
1105 switch ($entityType) {
1109 case 'Organization':
1110 $tableName = 'civicrm_contact';
1113 case 'Contribution':
1114 $tableName = 'civicrm_contribution';
1118 $tableName = 'civicrm_group';
1121 // DRAFTING: Verify if we cannot make it pluggable
1124 $tableName = 'civicrm_activity';
1127 case 'Relationship':
1128 $tableName = 'civicrm_relationship';
1132 $tableName = 'civicrm_membership';
1136 $tableName = 'civicrm_participant';
1140 $tableName = 'civicrm_event';
1144 $tableName = 'civicrm_grant';
1147 // need to add cases for Location, Address
1154 * Get a list of custom groups which extend a given entity type.
1155 * If there are custom-groups which only apply to certain subtypes,
1156 * those WILL be included.
1158 * @param string $entityType
1160 * @return CRM_Core_DAO_CustomGroup
1162 public static function getAllCustomGroupsByBaseEntity($entityType) {
1163 $customGroupDAO = new CRM_Core_DAO_CustomGroup();
1164 self
::_addWhereAdd($customGroupDAO, $entityType, NULL, TRUE);
1165 return $customGroupDAO;
1169 * Add the whereAdd clause for the DAO depending on the type of entity
1170 * the custom group is extending.
1172 * @param $customGroupDAO
1173 * @param string $entityType
1174 * What entity are we extending here ?.
1176 * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO.
1177 * @param bool $allSubtypes
1182 private static function _addWhereAdd(&$customGroupDAO, $entityType, $entityID = NULL, $allSubtypes = FALSE) {
1183 $addSubtypeClause = FALSE;
1185 switch ($entityType) {
1187 // if contact, get all related to contact
1188 $extendList = "'Contact','Individual','Household','Organization'";
1189 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1190 if (!$allSubtypes) {
1191 $addSubtypeClause = TRUE;
1197 case 'Organization':
1198 // is I/H/O then get I/H/O and contact
1199 $extendList = "'Contact','$entityType'";
1200 $customGroupDAO->whereAdd("extends IN ( $extendList )");
1201 if (!$allSubtypes) {
1202 $addSubtypeClause = TRUE;
1210 case 'Contribution':
1213 $customGroupDAO->whereAdd("extends IN ('$entityType')");
1217 if ($addSubtypeClause) {
1218 $csType = is_numeric($entityID) ? CRM_Contact_BAO_Contact
::getContactSubType($entityID) : FALSE;
1220 if (!empty($csType)) {
1221 $subtypeClause = array();
1222 foreach ($csType as $subtype) {
1223 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype .
1224 CRM_Core_DAO
::VALUE_SEPARATOR
;
1225 $subtypeClause[] = "extends_entity_column_value LIKE '%{$subtype}%'";
1227 $subtypeClause[] = "extends_entity_column_value IS NULL";
1228 $customGroupDAO->whereAdd("( " . implode(' OR ', $subtypeClause) .
1232 $customGroupDAO->whereAdd("extends_entity_column_value IS NULL");
1238 * Delete the Custom Group.
1241 * Object the DAO custom group object.
1242 * @param bool $force
1243 * whether to force the deletion, even if there are custom fields.
1246 * false if field exists for this group, true if group gets deleted.
1249 public static function deleteGroup($group, $force = FALSE) {
1251 //check wheter 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 bool $viewMode
1280 * @param bool $inactiveNeeded
1281 * @param int $action
1283 public static function setDefaults(&$groupTree, &$defaults, $viewMode = FALSE, $inactiveNeeded = FALSE, $action = CRM_Core_Action
::NONE
) {
1284 foreach ($groupTree as $id => $group) {
1285 if (!isset($group['fields'])) {
1288 foreach ($group['fields'] as $field) {
1289 if (CRM_Utils_Array
::value('element_value', $field) !== NULL) {
1290 $value = $field['element_value'];
1292 elseif (CRM_Utils_Array
::value('default_value', $field) !== NULL &&
1293 ($action != CRM_Core_Action
::UPDATE ||
1295 !array_key_exists('element_value', $field)
1298 $value = $viewMode ?
NULL : $field['default_value'];
1304 if (!empty($field['element_name'])) {
1305 $elementName = $field['element_name'];
1307 switch ($field['html_type']) {
1308 case 'Multi-Select':
1309 case 'AdvMulti-Select':
1311 $defaults[$elementName] = array();
1312 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($field['id'], $inactiveNeeded);
1314 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1315 if (isset($value)) {
1316 foreach ($customOption as $customValue => $customLabel) {
1317 if (in_array($customValue, $checkedData)) {
1318 if ($field['html_type'] == 'CheckBox') {
1319 $defaults[$elementName][$customValue] = 1;
1322 $defaults[$elementName][$customValue] = $customValue;
1326 $defaults[$elementName][$customValue] = 0;
1332 if (isset($field['customValue']['data'])) {
1333 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($field['customValue']['data'], 1, -1));
1334 foreach ($customOption as $val) {
1335 if (in_array($val['value'], $checkedData)) {
1336 if ($field['html_type'] == 'CheckBox') {
1337 $defaults[$elementName][$val['value']] = 1;
1340 $defaults[$elementName][$val['value']] = $val['value'];
1344 $defaults[$elementName][$val['value']] = 0;
1349 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, substr($value, 1, -1));
1350 foreach ($customOption as $val) {
1351 if (in_array($val['value'], $checkedValue)) {
1352 if ($field['html_type'] == 'CheckBox') {
1353 $defaults[$elementName][$val['value']] = 1;
1356 $defaults[$elementName][$val['value']] = $val['value'];
1365 if (isset($value)) {
1366 if (empty($field['time_format'])) {
1367 list($defaults[$elementName]) = CRM_Utils_Date
::setDateDefaults($value, NULL,
1368 $field['date_format']
1372 $timeElement = $elementName . '_time';
1373 if (substr($elementName, -1) == ']') {
1374 $timeElement = substr($elementName, 0, -1) . '_time]';
1376 list($defaults[$elementName], $defaults[$timeElement]) = CRM_Utils_Date
::setDateDefaults($value, NULL, $field['date_format'], $field['time_format']);
1381 case 'Multi-Select Country':
1382 case 'Multi-Select State/Province':
1383 if (isset($value)) {
1384 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1385 foreach ($checkedValue as $val) {
1387 $defaults[$elementName][$val] = $val;
1393 case 'Select Country':
1395 $defaults[$elementName] = $value;
1398 $config = CRM_Core_Config
::singleton();
1399 $defaults[$elementName] = $config->defaultContactCountry
;
1404 if ($field['data_type'] == "Float") {
1405 $defaults[$elementName] = (float) $value;
1407 elseif ($field['data_type'] == 'Money' &&
1408 $field['html_type'] == 'Text'
1410 $defaults[$elementName] = CRM_Utils_Money
::format($value, NULL, '%a');
1413 $defaults[$elementName] = $value;
1422 * @param array $params
1423 * @param bool $skipFile
1425 public static function postProcess(&$groupTree, &$params, $skipFile = FALSE) {
1426 // Get the Custom form values and groupTree
1427 // first reset all checkbox and radio data
1428 foreach ($groupTree as $groupID => $group) {
1429 if ($groupID === 'info') {
1432 foreach ($group['fields'] as $field) {
1433 $fieldId = $field['id'];
1435 //added Multi-Select option in the below if-statement
1436 if ($field['html_type'] == 'CheckBox' ||
1437 $field['html_type'] == 'Radio' ||
1438 $field['html_type'] == 'AdvMulti-Select' ||
1439 $field['html_type'] == 'Multi-Select'
1441 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = 'NULL';
1445 foreach ($params as $key => $val) {
1446 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match) &&
1447 $match[1] == $field['id']
1453 if (!isset($groupTree[$groupID]['fields'][$fieldId]['customValue'])) {
1454 // field exists in db so populate value from "form".
1455 $groupTree[$groupID]['fields'][$fieldId]['customValue'] = array();
1458 switch ($groupTree[$groupID]['fields'][$fieldId]['html_type']) {
1460 //added for CheckBox
1464 $customValue = array_keys($v);
1465 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] =
1466 CRM_Core_DAO
::VALUE_SEPARATOR
.
1467 implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customValue) .
1468 CRM_Core_DAO
::VALUE_SEPARATOR
;
1471 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1475 //added for Advanced Multi-Select
1477 case 'AdvMulti-Select':
1478 //added for Multi-Select
1479 case 'Multi-Select':
1481 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] =
1482 CRM_Core_DAO
::VALUE_SEPARATOR
.
1483 implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $v) .
1484 CRM_Core_DAO
::VALUE_SEPARATOR
;
1487 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = NULL;
1492 $date = CRM_Utils_Date
::processDate($v);
1493 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $date;
1501 //store the file in d/b
1502 $entityId = explode('=', $groupTree['info']['where'][0]);
1503 $fileParams = array('upload_date' => date('Ymdhis'));
1505 if ($groupTree[$groupID]['fields'][$fieldId]['customValue']['fid']) {
1506 $fileParams['id'] = $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'];
1509 $fileParams['uri'] = $v['name'];
1510 $fileParams['mime_type'] = $v['type'];
1511 CRM_Core_BAO_File
::filePostProcess($v['name'],
1512 $groupTree[$groupID]['fields'][$fieldId]['customValue']['fid'],
1513 $groupTree[$groupID]['table_name'],
1518 'custom_' . $fieldId,
1522 $defaults = array();
1523 $paramsFile = array(
1524 'entity_table' => $groupTree[$groupID]['table_name'],
1525 'entity_id' => $entityId[1],
1528 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_EntityFile',
1533 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $defaults['file_id'];
1537 $groupTree[$groupID]['fields'][$fieldId]['customValue']['data'] = $v;
1545 * Generic function to build all the form elements for a specific group tree
1547 * @param CRM_Core_Form $form
1549 * @param array $groupTree
1550 * The group tree object.
1551 * @param bool $inactiveNeeded
1552 * Return inactive custom groups.
1553 * @param string $prefix
1554 * Prefix for custom grouptree assigned to template.
1558 public static function buildQuickForm(&$form, &$groupTree, $inactiveNeeded = FALSE, $prefix = '') {
1559 $form->assign_by_ref("{$prefix}groupTree", $groupTree);
1561 // this is fix for date field
1562 $form->assign('currentYear', date('Y'));
1564 foreach ($groupTree as $id => $group) {
1565 CRM_Core_ShowHideBlocks
::links($form, $group['title'], '', '');
1566 foreach ($group['fields'] as $field) {
1567 $required = CRM_Utils_Array
::value('is_required', $field);
1569 if ($field['data_type'] == 'File') {
1570 if (!empty($field['element_value']['data'])) {
1575 $fieldId = $field['id'];
1576 $elementName = $field['element_name'];
1577 CRM_Core_BAO_CustomField
::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required);
1583 * Extract the get params from the url, validate
1584 * and store it in session
1586 * @param CRM_Core_Form $form
1588 * @param string $type
1589 * The type of custom group we are using.
1593 public static function extractGetParams(&$form, $type) {
1598 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($type, $form);
1599 $customValue = array();
1608 foreach ($groupTree as $group) {
1609 if (!isset($group['fields'])) {
1612 foreach ($group['fields'] as $key => $field) {
1613 $fieldName = 'custom_' . $key;
1614 $value = CRM_Utils_Request
::retrieve($fieldName, 'String', $form, FALSE, NULL, 'GET');
1618 if (!in_array($field['html_type'], $htmlType) ||
1619 $field['data_type'] == 'Boolean'
1621 $valid = CRM_Core_BAO_CustomValue
::typecheck($field['data_type'], $value);
1623 if ($field['html_type'] == 'CheckBox' ||
1624 $field['html_type'] == 'AdvMulti-Select' ||
1625 $field['html_type'] == 'Multi-Select'
1627 $value = str_replace("|", ",", $value);
1628 $mulValues = explode(',', $value);
1629 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1631 foreach ($mulValues as $v1) {
1632 foreach ($customOption as $coID => $coValue) {
1633 if (strtolower(trim($coValue['label'])) ==
1634 strtolower(trim($v1))
1636 $val[$coValue['value']] = 1;
1648 elseif ($field['html_type'] == 'Select' ||
1649 ($field['html_type'] == 'Radio' &&
1650 $field['data_type'] != 'Boolean'
1653 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($key, TRUE);
1654 foreach ($customOption as $customID => $coValue) {
1655 if (strtolower(trim($coValue['label'])) ==
1656 strtolower(trim($value))
1658 $value = $coValue['value'];
1663 elseif ($field['data_type'] == 'Date') {
1664 if (!empty($value)) {
1666 if (!empty($field['time_format'])) {
1667 $time = CRM_Utils_Request
::retrieve($fieldName .
1668 '_time', 'String', $form, FALSE, NULL, 'GET');
1670 list($value, $time) = CRM_Utils_Date
::setDateDefaults($value .
1672 if (!empty($field['time_format'])) {
1673 $customValue[$fieldName . '_time'] = $time;
1680 $customValue[$fieldName] = $value;
1686 return $customValue;
1690 * Check the type of custom field type (eg: Used for Individual, Contribution, etc)
1691 * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc )
1693 * @param int $customFieldId
1695 * @param array $removeCustomFieldTypes
1696 * Remove custom fields of a type eg: array("Individual") ;.
1700 * false if it matches else true
1702 public static function checkCustomField($customFieldId, &$removeCustomFieldTypes) {
1703 $query = "SELECT cg.extends as extends
1704 FROM civicrm_custom_group as cg, civicrm_custom_field as cf
1705 WHERE cg.id = cf.custom_group_id
1707 CRM_Utils_Type
::escape($customFieldId, 'Integer');
1709 $extends = CRM_Core_DAO
::singleValueQuery($query);
1711 if (in_array($extends, $removeCustomFieldTypes)) {
1723 public static function mapTableName($table) {
1728 case 'Organization':
1729 return 'civicrm_contact';
1732 return 'civicrm_activity';
1735 return 'civicrm_group';
1737 case 'Contribution':
1738 return 'civicrm_contribution';
1740 case 'Relationship':
1741 return 'civicrm_relationship';
1744 return 'civicrm_event';
1747 return 'civicrm_membership';
1750 case 'ParticipantRole':
1751 case 'ParticipantEventName':
1752 case 'ParticipantEventType':
1753 return 'civicrm_participant';
1756 return 'civicrm_grant';
1759 return 'civicrm_pledge';
1762 return 'civicrm_address';
1765 return 'civicrm_campaign';
1769 SELECT IF( EXISTS(SELECT name FROM civicrm_contact_type WHERE name like %1), 1, 0 )";
1770 $qParams = array(1 => array($table, 'String'));
1771 $result = CRM_Core_DAO
::singleValueQuery($query, $qParams);
1774 return 'civicrm_contact';
1777 $extendObjs = CRM_Core_OptionGroup
::values('cg_extend_objects', FALSE, FALSE, FALSE, NULL, 'name');
1778 if (array_key_exists($table, $extendObjs)) {
1779 return $extendObjs[$table];
1781 CRM_Core_Error
::fatal();
1789 public static function createTable($group) {
1791 'name' => $group->table_name
,
1792 'is_multiple' => $group->is_multiple ?
1 : 0,
1793 'extends_name' => self
::mapTableName($group->extends),
1796 $tableParams = CRM_Core_BAO_CustomField
::defaultCustomTableSchema($params);
1798 CRM_Core_BAO_SchemaHandler
::createTable($tableParams);
1802 * Function returns formatted groupTree, sothat form can be easily build in template
1804 * @param array $groupTree
1805 * @param int $groupCount
1806 * Group count by default 1, but can varry for multiple value custom data.
1807 * @param object form object
1811 public static function formatGroupTree(&$groupTree, $groupCount = 1, &$form) {
1812 $formattedGroupTree = array();
1813 $uploadNames = array();
1815 foreach ($groupTree as $key => $value) {
1816 if ($key === 'info') {
1820 // add group information
1821 $formattedGroupTree[$key]['name'] = CRM_Utils_Array
::value('name', $value);
1822 $formattedGroupTree[$key]['title'] = CRM_Utils_Array
::value('title', $value);
1823 $formattedGroupTree[$key]['help_pre'] = CRM_Utils_Array
::value('help_pre', $value);
1824 $formattedGroupTree[$key]['help_post'] = CRM_Utils_Array
::value('help_post', $value);
1825 $formattedGroupTree[$key]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $value);
1826 $formattedGroupTree[$key]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $value);
1828 // this params needed of bulding multiple values
1829 $formattedGroupTree[$key]['is_multiple'] = CRM_Utils_Array
::value('is_multiple', $value);
1830 $formattedGroupTree[$key]['extends'] = CRM_Utils_Array
::value('extends', $value);
1831 $formattedGroupTree[$key]['extends_entity_column_id'] = CRM_Utils_Array
::value('extends_entity_column_id', $value);
1832 $formattedGroupTree[$key]['extends_entity_column_value'] = CRM_Utils_Array
::value('extends_entity_column_value', $value);
1833 $formattedGroupTree[$key]['subtype'] = CRM_Utils_Array
::value('subtype', $value);
1834 $formattedGroupTree[$key]['max_multiple'] = CRM_Utils_Array
::value('max_multiple', $value);
1836 // add field information
1837 foreach ($value['fields'] as $k => $properties) {
1838 $properties['element_name'] = "custom_{$k}_-{$groupCount}";
1839 if (isset($properties['customValue']) &&
1840 !CRM_Utils_System
::isNull($properties['customValue'])
1842 if (isset($properties['customValue'][$groupCount])) {
1843 $properties['element_name'] = "custom_{$k}_{$properties['customValue'][$groupCount]['id']}";
1844 $formattedGroupTree[$key]['table_id'] = $properties['customValue'][$groupCount]['id'];
1845 if ($properties['data_type'] == 'File') {
1846 $properties['element_value'] = $properties['customValue'][$groupCount];
1847 $uploadNames[] = $properties['element_name'];
1850 $properties['element_value'] = $properties['customValue'][$groupCount]['data'];
1854 unset($properties['customValue']);
1855 $formattedGroupTree[$key]['fields'][$k] = $properties;
1860 // hack for field type File
1861 $formUploadNames = $form->get('uploadNames');
1862 if (is_array($formUploadNames)) {
1863 $uploadNames = array_unique(array_merge($formUploadNames, $uploadNames));
1866 $form->set('uploadNames', $uploadNames);
1869 return $formattedGroupTree;
1873 * Build custom data view
1875 * @param CRM_Core_Form $form
1877 * @param array $groupTree
1878 * @param bool $returnCount
1879 * True if customValue count needs to be returned.
1881 * @param null $prefix
1882 * @param int $customValueId
1886 public static function buildCustomDataView(&$form, &$groupTree, $returnCount = FALSE, $gID = NULL, $prefix = NULL, $customValueId = NULL) {
1888 foreach ($groupTree as $key => $group) {
1889 if ($key === 'info') {
1893 foreach ($group['fields'] as $k => $properties) {
1894 $groupID = $group['id'];
1895 if (!empty($properties['customValue'])) {
1896 foreach ($properties['customValue'] as $values) {
1897 if (!empty($customValueId) && $customValueId != $values['id']) {
1900 $details[$groupID][$values['id']]['title'] = CRM_Utils_Array
::value('title', $group);
1901 $details[$groupID][$values['id']]['name'] = CRM_Utils_Array
::value('name', $group);
1902 $details[$groupID][$values['id']]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1903 $details[$groupID][$values['id']]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1904 $details[$groupID][$values['id']]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1905 $details[$groupID][$values['id']]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1906 $details[$groupID][$values['id']]['fields'][$k] = array(
1907 'field_title' => CRM_Utils_Array
::value('label', $properties),
1908 'field_type' => CRM_Utils_Array
::value('html_type',
1911 'field_data_type' => CRM_Utils_Array
::value('data_type',
1914 'field_value' => self
::formatCustomValues($values,
1917 'options_per_line' => CRM_Utils_Array
::value('options_per_line',
1921 // also return contact reference contact id if user has view all or edit all contacts perm
1922 if ((CRM_Core_Permission
::check('view all contacts') ||
1923 CRM_Core_Permission
::check('edit all contacts'))
1925 $details[$groupID][$values['id']]['fields'][$k]['field_data_type'] ==
1928 $details[$groupID][$values['id']]['fields'][$k]['contact_ref_id'] = CRM_Utils_Array
::value('data', $values);
1933 $details[$groupID][0]['title'] = CRM_Utils_Array
::value('title', $group);
1934 $details[$groupID][0]['name'] = CRM_Utils_Array
::value('name', $group);
1935 $details[$groupID][0]['help_pre'] = CRM_Utils_Array
::value('help_pre', $group);
1936 $details[$groupID][0]['help_post'] = CRM_Utils_Array
::value('help_post', $group);
1937 $details[$groupID][0]['collapse_display'] = CRM_Utils_Array
::value('collapse_display', $group);
1938 $details[$groupID][0]['collapse_adv_display'] = CRM_Utils_Array
::value('collapse_adv_display', $group);
1939 $details[$groupID][0]['fields'][$k] = array('field_title' => CRM_Utils_Array
::value('label', $properties));
1945 //return a single value count if group id is passed to function
1946 //else return a groupId and count mapped array
1948 return count($details[$gID]);
1951 $countValue = array();
1952 foreach ($details as $key => $value) {
1953 $countValue[$key] = count($details[$key]);
1959 $form->assign_by_ref("{$prefix}viewCustomData", $details);
1965 * Format custom value according to data, view mode
1967 * @param array $values
1968 * Associated array of custom values.
1969 * @param array $field
1970 * @param bool $dncOptionPerLine
1971 * True if optionPerLine should not be consider.
1973 * @return array|null|string
1975 public static function formatCustomValues(&$values, &$field, $dncOptionPerLine = FALSE) {
1976 $value = $values['data'];
1978 //changed isset CRM-4601
1979 if (CRM_Utils_System
::isNull($value)) {
1983 $htmlType = CRM_Utils_Array
::value('html_type', $field);
1984 $dataType = CRM_Utils_Array
::value('data_type', $field);
1985 $option_group_id = CRM_Utils_Array
::value('option_group_id', $field);
1986 $timeFormat = CRM_Utils_Array
::value('time_format', $field);
1987 $optionPerLine = CRM_Utils_Array
::value('options_per_line', $field);
1990 $freezeStringChecked = "";
1992 switch ($dataType) {
1994 $customTimeFormat = '';
1995 $customFormat = NULL;
1997 switch ($timeFormat) {
1999 $customTimeFormat = '%l:%M %P';
2003 $customTimeFormat = '%H:%M';
2007 // if time is not selected remove time from value
2008 $value = substr($value, 0, 10);
2011 $supportableFormats = array(
2012 'mm/dd' => "%B %E%f $customTimeFormat",
2013 'dd-mm' => "%E%f %B $customTimeFormat",
2014 'yy' => "%Y $customTimeFormat",
2015 'M yy' => "%b %Y $customTimeFormat",
2016 'yy-mm' => "%Y-%m $customTimeFormat",
2019 if ($format = CRM_Utils_Array
::value('date_format', $field)) {
2020 if (array_key_exists($format, $supportableFormats)) {
2021 $customFormat = $supportableFormats["$format"];
2025 $retValue = CRM_Utils_Date
::customFormat($value, $customFormat);
2029 if ($value == '1') {
2030 $retValue = $freezeStringChecked . ts('Yes') . "\n";
2033 $retValue = $freezeStringChecked . ts('No') . "\n";
2039 $retValue = CRM_Utils_System
::formatWikiURL($value);
2044 $retValue = $values;
2047 case 'ContactReference':
2048 if (!empty($values['data'])) {
2049 $retValue = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $values['data'], 'display_name');
2058 if ($htmlType == 'Text') {
2059 $retValue = (float) $value;
2063 if ($htmlType == 'Text') {
2064 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2069 if (in_array($htmlType, array('Text', 'TextArea'))) {
2073 // note that if its not text / textarea, the code falls thru and executes
2074 // the below case also
2075 case 'StateProvince':
2080 //added check for Multi-Select in the below if-statement
2081 $customData[] = $value;
2083 //form custom data for multiple-valued custom data
2084 switch ($htmlType) {
2085 case 'Multi-Select Country':
2086 case 'Select Country':
2087 $customData = $value;
2088 if (!is_array($value)) {
2089 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2092 SELECT id as value, name as label
2093 FROM civicrm_country";
2094 $coDAO = CRM_Core_DAO
::executeQuery($query);
2097 case 'Select State/Province':
2098 case 'Multi-Select State/Province':
2099 $customData = $value;
2100 if (!is_array($value)) {
2101 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2105 SELECT id as value, name as label
2106 FROM civicrm_state_province";
2107 $coDAO = CRM_Core_DAO
::executeQuery($query);
2111 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2112 if ($option_group_id) {
2113 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2118 case 'AdvMulti-Select':
2119 case 'Multi-Select':
2120 $customData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2122 if ($option_group_id) {
2123 $options = CRM_Core_BAO_OptionValue
::getOptionValuesAssocArray($option_group_id);
2127 if (is_object($coDAO)) {
2128 while ($coDAO->fetch()) {
2129 if ($dataType == 'Country') {
2130 // NB: using ts() on a variable here is OK, since the value is pre-determined, not variable
2131 // and already extracted to .pot files.
2132 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'country'));
2134 elseif ($dataType == 'StateProvince') {
2135 $options[$coDAO->value
] = ts($coDAO->label
, array('context' => 'province'));
2138 $options[$coDAO->value
] = $coDAO->label
;
2143 CRM_Utils_Hook
::customFieldOptions($field['id'], $options, FALSE);
2146 foreach ($options as $optionValue => $optionLabel) {
2147 if ($dataType == 'Money') {
2148 foreach ($customData as $k => $v) {
2149 $customData[] = CRM_Utils_Money
::format($v, NULL, '%a');
2153 //to show only values that are checked
2154 if (in_array((string) $optionValue, $customData)) {
2155 $checked = in_array($optionValue, $customData) ?
$freezeStringChecked : $freezeString;
2156 if (!$optionPerLine ||
$dncOptionPerLine) {
2160 $retValue .= $checked . $optionLabel;
2163 $retValue[] = $checked . $optionLabel;
2170 //special case for option per line formatting
2171 if ($optionPerLine > 1 && is_array($retValue)) {
2174 $displayValues = array();
2175 $displayString = '';
2176 foreach ($retValue as $val) {
2177 if ($displayString) {
2178 $displayString .= ", ";
2181 $displayString .= $val;
2185 if (($rowCounter == $optionPerLine) ||
2186 ($fieldCounter == count($retValue))
2188 $displayValues[] = $displayString;
2189 $displayString = '';
2193 $retValue = $displayValues;
2196 $retValue = isset($retValue) ?
$retValue : NULL;
2201 * Get the custom group titles by custom field ids.
2203 * @param array $fieldIds
2204 * Array of custom field ids.
2207 * array consisting of groups and fields labels with ids.
2209 public static function getGroupTitles($fieldIds) {
2210 if (!is_array($fieldIds) && empty($fieldIds)) {
2214 $groupLabels = array();
2215 $fIds = "(" . implode(',', $fieldIds) . ")";
2218 SELECT civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupTitle,
2219 civicrm_custom_field.label as fieldLabel, civicrm_custom_field.id as fieldID
2220 FROM civicrm_custom_group, civicrm_custom_field
2221 WHERE civicrm_custom_group.id = civicrm_custom_field.custom_group_id
2222 AND civicrm_custom_field.id IN {$fIds}";
2224 $dao = CRM_Core_DAO
::executeQuery($query);
2225 while ($dao->fetch()) {
2226 $groupLabels[$dao->fieldID
] = array(
2227 'fieldID' => $dao->fieldID
,
2228 'fieldLabel' => $dao->fieldLabel
,
2229 'groupID' => $dao->groupID
,
2230 'groupTitle' => $dao->groupTitle
,
2234 return $groupLabels;
2237 public static function dropAllTables() {
2238 $query = "SELECT table_name FROM civicrm_custom_group";
2239 $dao = CRM_Core_DAO
::executeQuery($query);
2241 while ($dao->fetch()) {
2242 $query = "DROP TABLE IF EXISTS {$dao->table_name}";
2243 CRM_Core_DAO
::executeQuery($query);
2248 * Check whether custom group is empty or not.
2254 * true if empty otherwise false.
2256 public static function isGroupEmpty($gID) {
2261 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
2266 $query = "SELECT count(id) FROM {$tableName} WHERE id IS NOT NULL LIMIT 1";
2267 $value = CRM_Core_DAO
::singleValueQuery($query);
2269 if (empty($value)) {
2277 * Get the list of types for objects that a custom group extends to.
2279 * @param array $types
2280 * Var which should have the list appended.
2285 public static function getExtendedObjectTypes(&$types = array()) {
2286 static $flag = FALSE, $objTypes = array();
2289 $extendObjs = array();
2290 CRM_Core_OptionValue
::getValues(array('name' => 'cg_extend_objects'), $extendObjs);
2292 foreach ($extendObjs as $ovId => $ovValues) {
2293 if ($ovValues['description']) {
2294 // description is expected to be a callback func to subtypes
2295 list($callback, $args) = explode(';', trim($ovValues['description']));
2301 if (!is_array($args)) {
2302 CRM_Core_Error
::fatal('Arg is not of type array');
2305 list($className) = explode('::', $callback);
2306 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) .
2309 $objTypes[$ovValues['value']] = call_user_func_array($callback, $args);
2315 $types = array_merge($types, $objTypes);
2320 * @param int $customGroupId
2321 * @param int $entityId
2325 public static function hasReachedMaxLimit($customGroupId, $entityId) {
2326 //check whether the group is multiple
2327 $isMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'is_multiple');
2328 $isMultiple = ($isMultiple) ?
TRUE : FALSE;
2329 $hasReachedMax = FALSE;
2331 ($maxMultiple = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'max_multiple'))
2333 if (!$maxMultiple) {
2334 $hasReachedMax = FALSE;
2337 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'table_name');
2338 //count the number of entries for a entity
2339 $sql = "SELECT COUNT(id) FROM {$tableName} WHERE entity_id = %1";
2340 $params = array(1 => array($entityId, 'Integer'));
2341 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
2343 if ($count >= $maxMultiple) {
2344 $hasReachedMax = TRUE;
2348 return $hasReachedMax;
2354 public static function getMultipleFieldGroup() {
2355 $multipleGroup = array();
2356 $dao = new CRM_Core_DAO_CustomGroup();
2357 $dao->is_multiple
= 1;
2359 while ($dao->fetch()) {
2360 $multipleGroup[$dao->id
] = $dao->title
;
2362 return $multipleGroup;