Merge pull request #18907 from alifrumin/2139
[civicrm-core.git] / CRM / Contact / Form / Task / SaveSearch.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class provides the functionality to save a search.
20 *
21 * Saved Searches are used for saving frequently used queries
22 */
23 class CRM_Contact_Form_Task_SaveSearch extends CRM_Contact_Form_Task {
24
25 /**
26 * Saved search id if any.
27 *
28 * @var int
29 */
30 protected $_id;
31
32 /**
33 * Build all the data structures needed to build the form.
34 */
35 public function preProcess() {
36 $this->_id = NULL;
37
38 // get the submitted values of the search form
39 // we'll need to get fv from either search or adv search in the future
40 if ($this->_action == CRM_Core_Action::ADVANCED) {
41 $values = $this->controller->exportValues('Advanced');
42 }
43 elseif ($this->_action == CRM_Core_Action::PROFILE) {
44 $values = $this->controller->exportValues('Builder');
45 }
46 elseif ($this->_action == CRM_Core_Action::COPY) {
47 $values = $this->controller->exportValues('Custom');
48 }
49 else {
50 $values = $this->controller->exportValues('Basic');
51 }
52
53 // Get Task name
54 $modeValue = CRM_Contact_Form_Search::getModeValue(CRM_Utils_Array::value('component_mode', $values, CRM_Contact_BAO_Query::MODE_CONTACTS));
55 $className = $modeValue['taskClassName'];
56 $this->_task = $values['task'] ?? NULL;
57 }
58
59 /**
60 * Build the form object.
61 *
62 * It consists of
63 * - displaying the QILL (query in local language)
64 * - displaying elements for saving the search
65 */
66 public function buildQuickForm() {
67 // @todo sync this more with CRM_Group_Form_Edit.
68 $query = new CRM_Contact_BAO_Query($this->get('queryParams'));
69 $this->assign('qill', $query->qill());
70
71 // Values from the search form
72 $formValues = $this->controller->exportValues();
73
74 // the name and description are actually stored with the group and not the saved search
75 $this->add('text', 'title', ts('Group Title'),
76 CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'title'), TRUE
77 );
78
79 $this->addElement('textarea', 'description', ts('Group Description'),
80 CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'description')
81 );
82
83 $groupTypes = CRM_Core_OptionGroup::values('group_type', TRUE);
84 unset($groupTypes['Access Control']);
85 if (!CRM_Core_Permission::access('CiviMail')) {
86 $isWorkFlowEnabled = CRM_Mailing_Info::workflowEnabled();
87 if ($isWorkFlowEnabled &&
88 !CRM_Core_Permission::check('create mailings') &&
89 !CRM_Core_Permission::check('schedule mailings') &&
90 !CRM_Core_Permission::check('approve mailings')
91 ) {
92 unset($groupTypes['Mailing List']);
93 }
94 }
95
96 if (!empty($groupTypes)) {
97 $this->addCheckBox('group_type',
98 ts('Group Type'),
99 $groupTypes,
100 NULL, NULL, NULL, NULL, '&nbsp;&nbsp;&nbsp;'
101 );
102 }
103
104 //CRM-14190
105 CRM_Group_Form_Edit::buildParentGroups($this);
106 CRM_Group_Form_Edit::buildGroupOrganizations($this);
107
108 // get the group id for the saved search
109 $groupID = NULL;
110 if (isset($this->_id)) {
111 $groupID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
112 $this->_id,
113 'id',
114 'saved_search_id'
115 );
116 $this->addDefaultButtons(ts('Update Smart Group'));
117 }
118 else {
119 $this->addDefaultButtons(ts('Save Smart Group'));
120 $this->assign('partiallySelected', $formValues['radio_ts'] != 'ts_all');
121 }
122 $this->addRule('title', ts('Group Title already exists in Database.'),
123 'objectExists', ['CRM_Contact_DAO_Group', $groupID, 'title']
124 );
125 }
126
127 /**
128 * Process the form after the input has been submitted and validated.
129 */
130 public function postProcess() {
131 // saved search form values
132 // get form values of all the forms in this controller
133 $formValues = $this->controller->exportValues();
134
135 $isAdvanced = $this->get('isAdvanced');
136 $isSearchBuilder = $this->get('isSearchBuilder');
137
138 // add mapping record only for search builder saved search
139 $mappingId = NULL;
140 if ($isAdvanced == '2' && $isSearchBuilder == '1') {
141 //save the mapping for search builder
142
143 if (!$this->_id) {
144 //save record in mapping table
145 $mappingParams = [
146 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
147 ];
148 $mapping = CRM_Core_BAO_Mapping::add($mappingParams);
149 $mappingId = $mapping->id;
150 }
151 else {
152 //get the mapping id from saved search
153
154 $savedSearch = new CRM_Contact_BAO_SavedSearch();
155 $savedSearch->id = $this->_id;
156 $savedSearch->find(TRUE);
157 $mappingId = $savedSearch->mapping_id;
158 }
159
160 //save mapping fields
161 CRM_Core_BAO_Mapping::saveMappingFields($formValues, $mappingId);
162 }
163
164 //save the search
165 $savedSearch = new CRM_Contact_BAO_SavedSearch();
166 $savedSearch->id = $this->_id;
167 $queryParams = $this->get('queryParams');
168
169 // Use the query parameters rather than the form values - these have already been assessed / converted
170 // with the extra knowledge that the form has.
171 // Note that we want to move towards a standardised way of saving the query that is not
172 // an exact match for the form requirements & task the form layer with converting backwards and forwards.
173 // Ideally per CRM-17075 we will use entity reference fields heavily in the form layer & convert to the
174 // sql operator syntax at the query layer.
175 if (!$isSearchBuilder) {
176 CRM_Contact_BAO_SavedSearch::saveSkippedElement($queryParams, $formValues);
177 $savedSearch->form_values = serialize($queryParams);
178 }
179 else {
180 // We want search builder to be able to convert back & forth at the form layer
181 // to a standardised style - but it can't yet!
182 $savedSearch->form_values = serialize($formValues);
183 }
184
185 $savedSearch->mapping_id = $mappingId;
186 $savedSearch->search_custom_id = $this->get('customSearchID');
187 $savedSearch->save();
188 $this->set('ssID', $savedSearch->id);
189 CRM_Core_Session::setStatus(ts("Your smart group has been saved as '%1'.", [1 => $formValues['title']]), ts('Group Saved'), 'success');
190
191 // also create a group that is associated with this saved search only if new saved search
192 $params = [];
193 $params['title'] = $formValues['title'];
194 $params['description'] = $formValues['description'];
195 if (isset($formValues['group_type']) && is_array($formValues['group_type']) && count($formValues['group_type'])) {
196 $params['group_type'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
197 array_keys($formValues['group_type'])) . CRM_Core_DAO::VALUE_SEPARATOR;
198 }
199 else {
200 $params['group_type'] = '';
201 }
202 $params['visibility'] = 'User and User Admin Only';
203 $params['saved_search_id'] = $savedSearch->id;
204 $params['is_active'] = 1;
205
206 //CRM-14190
207 $params['parents'] = $formValues['parents'];
208
209 if ($this->_id) {
210 $params['id'] = CRM_Contact_BAO_SavedSearch::getName($this->_id, 'id');
211 }
212
213 $group = CRM_Contact_BAO_Group::create($params);
214
215 // Update mapping with the name and description of the group.
216 if ($mappingId && $group) {
217 $mappingParams = [
218 'id' => $mappingId,
219 'name' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $group->id, 'name', 'id'),
220 'description' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $group->id, 'description', 'id'),
221 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
222 ];
223 CRM_Core_BAO_Mapping::add($mappingParams);
224 }
225
226 // CRM-9464
227 $this->_id = $savedSearch->id;
228
229 //CRM-14190
230 if (!empty($formValues['parents'])) {
231 CRM_Contact_BAO_GroupNestingCache::update();
232 }
233 }
234
235 /**
236 * Set form defaults.
237 *
238 * return array
239 */
240 public function setDefaultValues() {
241 $defaults = [];
242 if (empty($defaults['parents'])) {
243 $defaults['parents'] = CRM_Core_BAO_Domain::getGroupId();
244 }
245 return $defaults;
246 }
247
248 }