Merge pull request #1305 from davecivicrm/CRM-13090
[civicrm-core.git] / CRM / Campaign / Form / Search.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35
36 /**
37 * Files required
38 */
39 class CRM_Campaign_Form_Search extends CRM_Core_Form {
40
41 /**
42 * Are we forced to run a search
43 *
44 * @var int
45 * @access protected
46 */
47 protected $_force;
48
49 /**
50 * name of search button
51 *
52 * @var string
53 * @access protected
54 */
55 protected $_searchButtonName;
56
57 /**
58 * name of print button
59 *
60 * @var string
61 * @access protected
62 */
63 protected $_printButtonName;
64
65 /**
66 * name of action button
67 *
68 * @var string
69 * @access protected
70 */
71 protected $_actionButtonName;
72
73 /**
74 * form values that we will be using
75 *
76 * @var array
77 * @access protected
78 */
79 protected $_formValues;
80
81 /**
82 * the params that are sent to the query
83 *
84 * @var array
85 * @access protected
86 */
87 protected $_queryParams;
88
89 /**
90 * have we already done this search
91 *
92 * @access protected
93 * @var boolean
94 */
95 protected $_done;
96
97 /**
98 * are we restricting ourselves to a single contact
99 *
100 * @access protected
101 * @var boolean
102 */
103 protected $_single = FALSE;
104
105 /**
106 * are we restricting ourselves to a single contact
107 *
108 * @access protected
109 * @var boolean
110 */
111 protected $_limit = NULL;
112
113 /**
114 * what context are we being invoked from
115 *
116 * @access protected
117 * @var string
118 */
119 protected $_context = NULL;
120
121 protected $_defaults;
122
123 /**
124 * prefix for the controller
125 *
126 */
127 protected $_prefix = "survey_";
128
129
130 private $_operation = 'reserve';
131
132 /**
133 * processing needed for buildForm and later
134 *
135 * @return void
136 * @access public
137 */ function preProcess() {
138 $this->_done = FALSE;
139 $this->_defaults = array();
140
141 //set the button name.
142 $this->_searchButtonName = $this->getButtonName('refresh');
143 $this->_printButtonName = $this->getButtonName('next', 'print');
144 $this->_actionButtonName = $this->getButtonName('next', 'action');
145
146 //we allow the controller to set force/reset externally,
147 //useful when we are being driven by the wizard framework
148 $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
149 $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
150 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
151 $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean', CRM_Core_DAO::$_nullObject);
152
153 //operation for state machine.
154 $this->_operation = CRM_Utils_Request::retrieve('op', 'String', $this, FALSE, 'reserve');
155 //validate operation.
156 if (!in_array($this->_operation, array(
157 'reserve', 'release', 'interview'))) {
158 $this->_operation = 'reserve';
159 $this->set('op', $this->_operation);
160 }
161 $this->set('searchVoterFor', $this->_operation);
162 $this->assign('searchVoterFor', $this->_operation);
163 $this->assign('isFormSubmitted', $this->isSubmitted());
164
165 //do check permissions.
166 if (!CRM_Core_Permission::check('administer CiviCampaign') &&
167 !CRM_Core_Permission::check('manage campaign') &&
168 !CRM_Core_Permission::check("{$this->_operation} campaign contacts")
169 ) {
170 CRM_Utils_System::permissionDenied();
171 CRM_Utils_System::civiExit();
172 }
173
174 $this->assign("context", $this->_context);
175
176 // get user submitted values
177 // get it from controller only if form has been submitted, else preProcess has set this
178
179 if (empty($_POST)) {
180 $this->_formValues = $this->get('formValues');
181 }
182 else {
183 $this->_formValues = $this->controller->exportValues($this->_name);
184 }
185
186 if ($this->_force) {
187 $this->postProcess();
188 $this->set('force', 0);
189 }
190
191 $sortID = NULL;
192 if ($this->get(CRM_Utils_Sort::SORT_ID)) {
193 $sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
194 $this->get(CRM_Utils_Sort::SORT_DIRECTION)
195 );
196 }
197
198 //get the voter clause.
199 $voterClause = $this->voterClause();
200
201 $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
202
203 $selector = new CRM_Campaign_Selector_Search($this->_queryParams,
204 $this->_action,
205 $voterClause,
206 $this->_single,
207 $this->_limit,
208 $this->_context
209 );
210 $prefix = NULL;
211 if ($this->_context == 'user') {
212 $prefix = $this->_prefix;
213 }
214
215 $this->assign("{$prefix}limit", $this->_limit);
216 $this->assign("{$prefix}single", $this->_single);
217
218 $controller = new CRM_Core_Selector_Controller($selector,
219 $this->get(CRM_Utils_Pager::PAGE_ID),
220 $sortID,
221 CRM_Core_Action::VIEW,
222 $this,
223 CRM_Core_Selector_Controller::TRANSFER,
224 $prefix
225 );
226
227 $controller->setEmbedded(TRUE);
228 $controller->moveFromSessionToTemplate();
229
230 //append breadcrumb to survey dashboard.
231 if (CRM_Campaign_BAO_Campaign::accessCampaign()) {
232 $url = CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=survey');
233 CRM_Utils_System::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
234 }
235
236 //set the form title.
237 CRM_Utils_System::setTitle(ts('Find Respondents To %1', array(1 => ucfirst($this->_operation))));
238 }
239
240 function setDefaultValues() {
241 //load the default survey for all actions.
242 if (empty($this->_defaults)) {
243 $defaultSurveyId = key(CRM_Campaign_BAO_Survey::getSurveys(TRUE, TRUE));
244 if ($defaultSurveyId) {
245 $this->_defaults['campaign_survey_id'] = $defaultSurveyId;
246 }
247 }
248
249 return $this->_defaults;
250 }
251
252 /**
253 * Build the form
254 *
255 * @access public
256 *
257 * @return void
258 */
259 function buildQuickForm() {
260 //build the search form.
261 CRM_Campaign_BAO_Query::buildSearchForm($this);
262
263 /*
264 * add form checkboxes for each row. This is needed out here to conform to QF protocol
265 * of all elements being declared in builQuickForm
266 */
267
268
269 $rows = $this->get('rows');
270 if (is_array($rows)) {
271 if (!$this->_single) {
272 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, array('onclick' => "toggleTaskAction( true ); return toggleCheckboxVals('mark_x_',this);"));
273 foreach ($rows as $row) {
274 $this->addElement('checkbox', $row['checkbox'],
275 NULL, NULL,
276 array('onclick' => "toggleTaskAction( true ); return checkSelectedBox('" . $row['checkbox'] . "');")
277 );
278 }
279 }
280
281 $total = $cancel = 0;
282
283 $permission = CRM_Core_Permission::getPermission();
284 $allTasks = CRM_Campaign_Task::permissionedTaskTitles($permission);
285
286 //hack to serve right page to state machine.
287 $taskMapping = array(
288 'interview' => 1,
289 'reserve' => 2,
290 'release' => 3,
291 );
292
293 $currentTaskValue = CRM_Utils_Array::value($this->_operation, $taskMapping);
294 $taskValue = array($currentTaskValue => $allTasks[$currentTaskValue]);
295 if ($this->_operation == 'interview' &&
296 CRM_Utils_Array::value('campaign_survey_id', $this->_formValues)
297 ) {
298 $activityTypes = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
299
300 $surveyTypeId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey',
301 $this->_formValues['campaign_survey_id'],
302 'activity_type_id'
303 );
304 $taskValue = array(
305 $currentTaskValue => ts('Record %1 Responses',
306 array(1 => $activityTypes[$surveyTypeId])
307 ));
308 }
309
310 $this->add('select', 'task', ts('Actions:') . ' ', $taskValue);
311 $this->setDefaults(array('task' => $currentTaskValue));
312
313 $this->add('submit', $this->_actionButtonName, ts('Go'),
314 array(
315 'class' => 'form-submit',
316 'id' => 'Go',
317 )
318 );
319
320 $this->add('submit', $this->_printButtonName, ts('Print'),
321 array(
322 'class' => 'form-submit',
323 'onclick' => "return checkPerformAction('mark_x', '" . $this->getName() . "', 1);",
324 )
325 );
326
327 // need to perform tasks on all or selected items ? using radio_ts(task selection) for it
328 $this->addElement('radio', 'radio_ts', NULL, '', 'ts_sel', array('checked' => 'checked'));
329 $this->addElement('radio', 'radio_ts', NULL, '', 'ts_all', array('onclick' => $this->getName() . ".toggleSelect.checked = false; toggleCheckboxVals('mark_x_',this); toggleTaskAction( true );"));
330 }
331
332 // add buttons
333 $this->addButtons(array(
334 array(
335 'type' => 'refresh',
336 'name' => ts('Search'),
337 'isDefault' => TRUE,
338 ),
339 )
340 );
341 }
342
343 /**
344 * The post processing of the form gets done here.
345 *
346 * Key things done during post processing are
347 * - check for reset or next request. if present, skip post procesing.
348 * - now check if user requested running a saved search, if so, then
349 * the form values associated with the saved search are used for searching.
350 * - if user has done a submit with new values the regular post submissing is
351 * done.
352 * The processing consists of using a Selector / Controller framework for getting the
353 * search results.
354 *
355 * @param
356 *
357 * @return void
358 * @access public
359 */
360 function postProcess() {
361 if ($this->_done) {
362 return;
363 }
364
365 $this->_done = TRUE;
366
367 if (!empty($_POST)) {
368 $this->_formValues = $this->controller->exportValues($this->_name);
369 }
370
371 $this->fixFormValues();
372
373 //format params as per task.
374 $this->formatParams();
375
376 $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
377
378 $this->set('formValues', $this->_formValues);
379 $this->set('queryParams', $this->_queryParams);
380
381 $buttonName = $this->controller->getButtonName();
382 if ($buttonName == $this->_actionButtonName || $buttonName == $this->_printButtonName) {
383 // check actionName and if next, then do not repeat a search, since we are going to the next page
384
385 // hack, make sure we reset the task values
386 $stateMachine = $this->controller->getStateMachine();
387 $formName = $stateMachine->getTaskFormName();
388
389 $this->controller->resetPage($formName);
390 return;
391 }
392
393 $sortID = NULL;
394 if ($this->get(CRM_Utils_Sort::SORT_ID)) {
395 $sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
396 $this->get(CRM_Utils_Sort::SORT_DIRECTION)
397 );
398 }
399
400 //get the voter clause.
401 $voterClause = $this->voterClause();
402
403 $selector = new CRM_Campaign_Selector_Search($this->_queryParams,
404 $this->_action,
405 $voterClause,
406 $this->_single,
407 $this->_limit,
408 $this->_context
409 );
410 $selector->setKey($this->controller->_key);
411
412 $prefix = NULL;
413 if ($this->_context == 'basic' ||
414 $this->_context == 'user'
415 ) {
416 $prefix = $this->_prefix;
417 }
418
419 $controller = new CRM_Core_Selector_Controller($selector,
420 $this->get(CRM_Utils_Pager::PAGE_ID),
421 $sortID,
422 CRM_Core_Action::VIEW,
423 $this,
424 CRM_Core_Selector_Controller::SESSION,
425 $prefix
426 );
427 $controller->setEmbedded(TRUE);
428 $query = $selector->getQuery();
429 if ($this->_context == 'user') {
430 $query->setSkipPermission(TRUE);
431 }
432 $controller->run();
433 }
434
435 function formatParams() {
436 $interviewerId = CRM_Utils_Array::value('survey_interviewer_id', $this->_formValues);
437 if (!$interviewerId) {
438 $session = CRM_Core_Session::singleton();
439 $this->_formValues['survey_interviewer_id'] = $interviewerId = $session->get('userID');
440 }
441 $this->set('interviewerId', $interviewerId);
442 if (!CRM_Utils_Array::value('survey_interviewer_name', $this->_formValues)) {
443 $this->_formValues['survey_interviewer_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
444 $interviewerId,
445 'sort_name',
446 'id'
447 );
448 }
449
450 //format multi-select group and contact types.
451 foreach (array(
452 'group', 'contact_type') as $param) {
453 if ($this->_force) {
454 continue;
455 }
456 $paramValue = CRM_Utils_Array::value($param, $this->_formValues);
457 if ($paramValue && is_array($paramValue)) {
458 unset($this->_formValues[$param]);
459 foreach ($paramValue as $key => $value) {
460 $this->_formValues[$param][$value] = 1;
461 }
462 }
463 }
464
465 //apply filter of survey contact type for search.
466 $contactType = CRM_Campaign_BAO_Survey::getSurveyContactType(CRM_Utils_Array::value('campaign_survey_id', $this->_formValues));
467 if ($contactType && in_array($this->_operation, array(
468 'reserve', 'interview'))) {
469 $this->_formValues['contact_type'][$contactType] = 1;
470 }
471
472 if ($this->_operation == 'reserve') {
473 if (CRM_Utils_Array::value('campaign_survey_id', $this->_formValues)) {
474 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey',
475 $this->_formValues['campaign_survey_id'],
476 'campaign_id'
477 );
478
479 //allow voter search in sub-part of given constituents,
480 //but make sure in case user does not select any group.
481 //get all associated campaign groups in where filter, CRM-7406
482 $groups = CRM_Utils_Array::value('group', $this->_formValues);
483 if ($campaignId && CRM_Utils_System::isNull($groups)) {
484 $campGroups = CRM_Campaign_BAO_Campaign::getCampaignGroups($campaignId);
485 foreach ($campGroups as $id => $title) $this->_formValues['group'][$id] = 1;
486 }
487
488 //carry servey id w/ this.
489 $this->set('surveyId', $this->_formValues['campaign_survey_id']);
490 unset($this->_formValues['campaign_survey_id']);
491 }
492 unset($this->_formValues['survey_interviewer_id']);
493 }
494 elseif ($this->_operation == 'interview' ||
495 $this->_operation == 'release'
496 ) {
497 //to conduct interview / release activity status should be scheduled.
498 $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
499 if ($scheduledStatusId = array_search('Scheduled', $activityStatus)) {
500 $this->_formValues['survey_status_id'] = $scheduledStatusId;
501 }
502 }
503
504 //pass voter search operation.
505 $this->_formValues['campaign_search_voter_for'] = $this->_operation;
506 }
507
508 function fixFormValues() {
509 // if this search has been forced
510 // then see if there are any get values, and if so over-ride the post values
511 // note that this means that GET over-rides POST :)
512
513 //since we have qfKey, no need to manipulate set defaults.
514 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', CRM_Core_DAO::$_nullObject);
515
516 if (!$this->_force || CRM_Utils_Rule::qfKey($qfKey)) {
517 return;
518 }
519
520 // get survey id
521 $surveyId = CRM_Utils_Request::retrieve('sid', 'Positive', CRM_Core_DAO::$_nullObject);
522
523 if ($surveyId) {
524 $surveyId = CRM_Utils_Type::escape($surveyId, 'Integer');
525 }
526 else {
527 // use default survey id
528 $surveyId = key(CRM_Campaign_BAO_Survey::getSurveys(TRUE, TRUE));
529 }
530 if (!$surveyId) {
531 CRM_Core_Error::fatal('Could not find valid Survey Id.');
532 }
533 $this->_formValues['campaign_survey_id'] = $this->_formValues['campaign_survey_id'] = $surveyId;
534
535 $session = CRM_Core_Session::singleton();
536 $userId = $session->get('userID');
537
538 // get interviewer id
539 $cid = CRM_Utils_Request::retrieve('cid', 'Positive',
540 CRM_Core_DAO::$_nullObject, FALSE, $userId
541 );
542 //to force other contact as interviewer, user should be admin.
543 if ($cid != $userId &&
544 !CRM_Core_Permission::check('administer CiviCampaign')
545 ) {
546 CRM_Utils_System::permissionDenied();
547 CRM_Utils_System::civiExit();
548 }
549 $this->_formValues['survey_interviewer_id'] = $cid;
550 $this->_formValues['survey_interviewer_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
551 $cid,
552 'sort_name',
553 'id'
554 );
555 //get all in defaults.
556 $this->_defaults = $this->_formValues;
557 $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
558 }
559
560 function voterClause() {
561 $params = array('campaign_search_voter_for' => $this->_operation);
562
563 $clauseFields = array(
564 'surveyId' => 'campaign_survey_id',
565 'interviewerId' => 'survey_interviewer_id',
566 );
567
568 foreach ($clauseFields as $param => $key) {
569 $params[$key] = CRM_Utils_Array::value($key, $this->_formValues);
570 if (!$params[$key]) {
571 $params[$key] = $this->get($param);
572 }
573 }
574
575 //build the clause.
576 $voterClause = CRM_Campaign_BAO_Query::voterClause($params);
577
578 return $voterClause;
579 }
580
581 /**
582 * Return a descriptive name for the page, used in wizard header
583 *
584 * @return string
585 * @access public
586 */
587 public function getTitle() {
588 return ts('Find Respondents');
589 }
590 }
591