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