Merge pull request #12337 from lcdservices/dev-core-190
[civicrm-core.git] / CRM / Campaign / Form / Search.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * Files required.
36 */
37 class CRM_Campaign_Form_Search extends CRM_Core_Form_Search {
38
39 /**
40 * The params that are sent to the query.
41 *
42 * @var array
43 */
44 protected $_queryParams;
45
46 /**
47 * Are we restricting ourselves to a single contact.
48 *
49 * @var boolean
50 */
51 protected $_single = FALSE;
52
53 /**
54 * Are we restricting ourselves to a single contact.
55 *
56 * @var boolean
57 */
58 protected $_limit = NULL;
59
60 /**
61 * Prefix for the controller.
62 */
63 protected $_prefix = "survey_";
64
65
66 private $_operation = 'reserve';
67
68 /**
69 * Processing needed for buildForm and later.
70 */
71 public function preProcess() {
72 $this->_done = FALSE;
73 $this->_defaults = array();
74
75 //set the button name.
76 $this->_searchButtonName = $this->getButtonName('refresh');
77 $this->_printButtonName = $this->getButtonName('next', 'print');
78 $this->_actionButtonName = $this->getButtonName('next', 'action');
79
80 $this->loadStandardSearchOptionsFromUrl();
81
82 //operation for state machine.
83 $this->_operation = CRM_Utils_Request::retrieve('op', 'String', $this, FALSE, 'reserve');
84 //validate operation.
85 if (!in_array($this->_operation, array(
86 'reserve',
87 'release',
88 'interview',
89 ))
90 ) {
91 $this->_operation = 'reserve';
92 $this->set('op', $this->_operation);
93 }
94 $this->set('searchVoterFor', $this->_operation);
95 $this->assign('searchVoterFor', $this->_operation);
96 $this->assign('isFormSubmitted', $this->isSubmitted());
97
98 //do check permissions.
99 if (!CRM_Core_Permission::check('administer CiviCampaign') &&
100 !CRM_Core_Permission::check('manage campaign') &&
101 !CRM_Core_Permission::check("{$this->_operation} campaign contacts")
102 ) {
103 CRM_Utils_System::permissionDenied();
104 CRM_Utils_System::civiExit();
105 }
106
107 $this->assign("context", $this->_context);
108
109 // get user submitted values
110 // get it from controller only if form has been submitted, else preProcess has set this
111
112 if (empty($_POST)) {
113 $this->_formValues = $this->get('formValues');
114 }
115 else {
116 $this->_formValues = $this->controller->exportValues($this->_name);
117 }
118
119 if ($this->_force) {
120 $this->postProcess();
121 $this->set('force', 0);
122 }
123
124 $sortID = NULL;
125 if ($this->get(CRM_Utils_Sort::SORT_ID)) {
126 $sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
127 $this->get(CRM_Utils_Sort::SORT_DIRECTION)
128 );
129 }
130
131 //get the voter clause.
132 $voterClause = $this->voterClause();
133
134 $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
135
136 $selector = new CRM_Campaign_Selector_Search($this->_queryParams,
137 $this->_action,
138 $voterClause,
139 $this->_single,
140 $this->_limit,
141 $this->_context
142 );
143 $prefix = NULL;
144 if ($this->_context == 'user') {
145 $prefix = $this->_prefix;
146 }
147
148 $this->assign("{$prefix}limit", $this->_limit);
149 $this->assign("{$prefix}single", $this->_single);
150
151 $controller = new CRM_Core_Selector_Controller($selector,
152 $this->get(CRM_Utils_Pager::PAGE_ID),
153 $sortID,
154 CRM_Core_Action::VIEW,
155 $this,
156 CRM_Core_Selector_Controller::TRANSFER,
157 $prefix
158 );
159
160 $controller->setEmbedded(TRUE);
161 $controller->moveFromSessionToTemplate();
162
163 //append breadcrumb to survey dashboard.
164 if (CRM_Campaign_BAO_Campaign::accessCampaign()) {
165 $url = CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=survey');
166 CRM_Utils_System::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
167 }
168
169 //set the form title.
170 CRM_Utils_System::setTitle(ts('Find Respondents To %1', array(1 => ucfirst($this->_operation))));
171 }
172
173 /**
174 * Load the default survey for all actions.
175 *
176 * @return array
177 */
178 public function setDefaultValues() {
179 if (empty($this->_defaults)) {
180 $defaultSurveyId = key(CRM_Campaign_BAO_Survey::getSurveys(TRUE, TRUE));
181 if ($defaultSurveyId) {
182 $this->_defaults['campaign_survey_id'] = $defaultSurveyId;
183 }
184 }
185
186 return $this->_defaults;
187 }
188
189 /**
190 * Build the form object.
191 */
192 public function buildQuickForm() {
193 parent::buildQuickForm();
194 //build the search form.
195 CRM_Campaign_BAO_Query::buildSearchForm($this);
196
197 $rows = $this->get('rows');
198 if (is_array($rows)) {
199 if (!$this->_single) {
200 $this->addRowSelectors($rows);
201 }
202
203 $allTasks = CRM_Campaign_Task::permissionedTaskTitles(CRM_Core_Permission::getPermission());
204
205 //hack to serve right page to state machine.
206 $taskMapping = array(
207 'interview' => CRM_Campaign_Task::INTERVIEW,
208 'reserve' => CRM_Campaign_Task::RESERVE,
209 'release' => CRM_Campaign_Task::RELEASE,
210 );
211
212 $currentTaskValue = CRM_Utils_Array::value($this->_operation, $taskMapping);
213 $taskValue = array($currentTaskValue => $allTasks[$currentTaskValue]);
214 if ($this->_operation == 'interview' && !empty($this->_formValues['campaign_survey_id'])) {
215 $activityTypes = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
216
217 $surveyTypeId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey',
218 $this->_formValues['campaign_survey_id'],
219 'activity_type_id'
220 );
221 $taskValue = array(
222 $currentTaskValue => ts('Record %1 Responses',
223 array(1 => $activityTypes[$surveyTypeId])
224 ),
225 );
226 }
227
228 $this->addTaskMenu($taskValue);
229 }
230
231 }
232
233 /**
234 * The post processing of the form gets done here.
235 *
236 * Key things done during post processing are
237 * - check for reset or next request. if present, skip post procesing.
238 * - now check if user requested running a saved search, if so, then
239 * the form values associated with the saved search are used for searching.
240 * - if user has done a submit with new values the regular post submissing is
241 * done.
242 * The processing consists of using a Selector / Controller framework for getting the
243 * search results.
244 */
245 public function postProcess() {
246 if ($this->_done) {
247 return;
248 }
249
250 $this->_done = TRUE;
251
252 if (!empty($_POST)) {
253 $this->_formValues = $this->controller->exportValues($this->_name);
254 }
255
256 $this->fixFormValues();
257
258 //format params as per task.
259 $this->formatParams();
260
261 $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
262
263 $this->set('formValues', $this->_formValues);
264 $this->set('queryParams', $this->_queryParams);
265
266 $buttonName = $this->controller->getButtonName();
267 if ($buttonName == $this->_actionButtonName) {
268 // check actionName and if next, then do not repeat a search, since we are going to the next page
269
270 // hack, make sure we reset the task values
271 $stateMachine = $this->controller->getStateMachine();
272 $formName = $stateMachine->getTaskFormName();
273
274 $this->controller->resetPage($formName);
275 return;
276 }
277
278 $sortID = NULL;
279 if ($this->get(CRM_Utils_Sort::SORT_ID)) {
280 $sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
281 $this->get(CRM_Utils_Sort::SORT_DIRECTION)
282 );
283 }
284
285 //get the voter clause.
286 $voterClause = $this->voterClause();
287
288 $selector = new CRM_Campaign_Selector_Search($this->_queryParams,
289 $this->_action,
290 $voterClause,
291 $this->_single,
292 $this->_limit,
293 $this->_context
294 );
295 $selector->setKey($this->controller->_key);
296
297 $prefix = NULL;
298 if ($this->_context == 'basic' ||
299 $this->_context == 'user'
300 ) {
301 $prefix = $this->_prefix;
302 }
303
304 $controller = new CRM_Core_Selector_Controller($selector,
305 $this->get(CRM_Utils_Pager::PAGE_ID),
306 $sortID,
307 CRM_Core_Action::VIEW,
308 $this,
309 CRM_Core_Selector_Controller::SESSION,
310 $prefix
311 );
312 $controller->setEmbedded(TRUE);
313 $query = $selector->getQuery();
314 if ($this->_context == 'user') {
315 $query->setSkipPermission(TRUE);
316 }
317 $controller->run();
318 }
319
320 public function formatParams() {
321 $interviewerId = CRM_Utils_Array::value('survey_interviewer_id', $this->_formValues);
322 if ($interviewerId) {
323 $this->set('interviewerId', $interviewerId);
324 }
325
326 //format multi-select group and contact types.
327 foreach (array('group', 'contact_type') as $param) {
328 if ($this->_force) {
329 continue;
330 }
331 $paramValue = CRM_Utils_Array::value($param, $this->_formValues);
332 if ($paramValue && is_array($paramValue)) {
333 unset($this->_formValues[$param]);
334 foreach ($paramValue as $key => $value) {
335 $this->_formValues[$param][$value] = 1;
336 }
337 }
338 }
339
340 //apply filter of survey contact type for search.
341 $contactType = CRM_Campaign_BAO_Survey::getSurveyContactType(CRM_Utils_Array::value('campaign_survey_id', $this->_formValues));
342 if ($contactType && in_array($this->_operation, array(
343 'reserve',
344 'interview',
345 ))
346 ) {
347 $this->_formValues['contact_type'][$contactType] = 1;
348 }
349
350 if ($this->_operation == 'reserve') {
351 if (!empty($this->_formValues['campaign_survey_id'])) {
352 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey',
353 $this->_formValues['campaign_survey_id'],
354 'campaign_id'
355 );
356
357 //allow voter search in sub-part of given constituents,
358 //but make sure in case user does not select any group.
359 //get all associated campaign groups in where filter, CRM-7406
360 $groups = CRM_Utils_Array::value('group', $this->_formValues);
361 if ($campaignId && CRM_Utils_System::isNull($groups)) {
362 $campGroups = CRM_Campaign_BAO_Campaign::getCampaignGroups($campaignId);
363 foreach ($campGroups as $id => $title) {
364 $this->_formValues['group'][$id] = 1;
365 }
366 }
367
368 //carry servey id w/ this.
369 $this->set('surveyId', $this->_formValues['campaign_survey_id']);
370 unset($this->_formValues['campaign_survey_id']);
371 }
372 unset($this->_formValues['survey_interviewer_id']);
373 }
374 elseif ($this->_operation == 'interview' ||
375 $this->_operation == 'release'
376 ) {
377 //to conduct interview / release activity status should be scheduled.
378 $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
379 if ($scheduledStatusId = array_search('Scheduled', $activityStatus)) {
380 $this->_formValues['survey_status_id'] = $scheduledStatusId;
381 }
382 }
383
384 //pass voter search operation.
385 $this->_formValues['campaign_search_voter_for'] = $this->_operation;
386 }
387
388 public function fixFormValues() {
389 // if this search has been forced
390 // then see if there are any get values, and if so over-ride the post values
391 // note that this means that GET over-rides POST :)
392
393 //since we have qfKey, no need to manipulate set defaults.
394 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String');
395
396 if (!$this->_force || CRM_Utils_Rule::qfKey($qfKey)) {
397 return;
398 }
399
400 // get survey id
401 $surveyId = CRM_Utils_Request::retrieve('sid', 'Positive');
402
403 if ($surveyId) {
404 $surveyId = CRM_Utils_Type::escape($surveyId, 'Integer');
405 }
406 else {
407 // use default survey id
408 $surveyId = key(CRM_Campaign_BAO_Survey::getSurveys(TRUE, TRUE));
409 }
410 if (!$surveyId) {
411 CRM_Core_Error::fatal('Could not find valid Survey Id.');
412 }
413 $this->_formValues['campaign_survey_id'] = $this->_formValues['campaign_survey_id'] = $surveyId;
414
415 $session = CRM_Core_Session::singleton();
416 $userId = $session->get('userID');
417
418 // get interviewer id
419 $cid = CRM_Utils_Request::retrieve('cid', 'Positive',
420 CRM_Core_DAO::$_nullObject, FALSE, $userId
421 );
422 //to force other contact as interviewer, user should be admin.
423 if ($cid != $userId &&
424 !CRM_Core_Permission::check('administer CiviCampaign')
425 ) {
426 CRM_Utils_System::permissionDenied();
427 CRM_Utils_System::civiExit();
428 }
429 $this->_formValues['survey_interviewer_id'] = $cid;
430 //get all in defaults.
431 $this->_defaults = $this->_formValues;
432 $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
433 }
434
435 /**
436 * @return array
437 */
438 public function voterClause() {
439 $params = array('campaign_search_voter_for' => $this->_operation);
440
441 $clauseFields = array(
442 'surveyId' => 'campaign_survey_id',
443 'interviewerId' => 'survey_interviewer_id',
444 );
445
446 foreach ($clauseFields as $param => $key) {
447 $params[$key] = CRM_Utils_Array::value($key, $this->_formValues);
448 if (!$params[$key]) {
449 $params[$key] = $this->get($param);
450 }
451 }
452
453 //build the clause.
454 $voterClause = CRM_Campaign_BAO_Query::voterClause($params);
455
456 return $voterClause;
457 }
458
459 /**
460 * Return a descriptive name for the page, used in wizard header
461 *
462 * @return string
463 */
464 public function getTitle() {
465 return ts('Find Respondents');
466 }
467
468 }