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