ea22e89e47246a2e0897ca792d89af7da9caa150
[civicrm-core.git] / CRM / Campaign / Form / Search.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * Files required
38 */
39 class CRM_Campaign_Form_Search extends CRM_Core_Form_Search {
40
41 /**
42 * The params that are sent to the query
43 *
44 * @var array
45 */
46 protected $_queryParams;
47
48 /**
49 * Are we restricting ourselves to a single contact
50 *
51 * @var boolean
52 */
53 protected $_single = FALSE;
54
55 /**
56 * Are we restricting ourselves to a single contact
57 *
58 * @var boolean
59 */
60 protected $_limit = NULL;
61
62 protected $_defaults;
63
64 /**
65 * Prefix for the controller
66 *
67 */
68 protected $_prefix = "survey_";
69
70
71 private $_operation = 'reserve';
72
73 /**
74 * Processing needed for buildForm and later
75 *
76 * @return void
77 */
78 function preProcess() {
79 $this->_done = FALSE;
80 $this->_defaults = array();
81
82 //set the button name.
83 $this->_searchButtonName = $this->getButtonName('refresh');
84 $this->_printButtonName = $this->getButtonName('next', 'print');
85 $this->_actionButtonName = $this->getButtonName('next', 'action');
86
87 //we allow the controller to set force/reset externally,
88 //useful when we are being driven by the wizard framework
89 $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
90 $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
91 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
92 $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean', CRM_Core_DAO::$_nullObject);
93
94 //operation for state machine.
95 $this->_operation = CRM_Utils_Request::retrieve('op', 'String', $this, FALSE, 'reserve');
96 //validate operation.
97 if (!in_array($this->_operation, array(
98 'reserve', 'release', 'interview'))) {
99 $this->_operation = 'reserve';
100 $this->set('op', $this->_operation);
101 }
102 $this->set('searchVoterFor', $this->_operation);
103 $this->assign('searchVoterFor', $this->_operation);
104 $this->assign('isFormSubmitted', $this->isSubmitted());
105
106 //do check permissions.
107 if (!CRM_Core_Permission::check('administer CiviCampaign') &&
108 !CRM_Core_Permission::check('manage campaign') &&
109 !CRM_Core_Permission::check("{$this->_operation} campaign contacts")
110 ) {
111 CRM_Utils_System::permissionDenied();
112 CRM_Utils_System::civiExit();
113 }
114
115 $this->assign("context", $this->_context);
116
117 // get user submitted values
118 // get it from controller only if form has been submitted, else preProcess has set this
119
120 if (empty($_POST)) {
121 $this->_formValues = $this->get('formValues');
122 }
123 else {
124 $this->_formValues = $this->controller->exportValues($this->_name);
125 }
126
127 if ($this->_force) {
128 $this->postProcess();
129 $this->set('force', 0);
130 }
131
132 $sortID = NULL;
133 if ($this->get(CRM_Utils_Sort::SORT_ID)) {
134 $sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
135 $this->get(CRM_Utils_Sort::SORT_DIRECTION)
136 );
137 }
138
139 //get the voter clause.
140 $voterClause = $this->voterClause();
141
142 $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
143
144 $selector = new CRM_Campaign_Selector_Search($this->_queryParams,
145 $this->_action,
146 $voterClause,
147 $this->_single,
148 $this->_limit,
149 $this->_context
150 );
151 $prefix = NULL;
152 if ($this->_context == 'user') {
153 $prefix = $this->_prefix;
154 }
155
156 $this->assign("{$prefix}limit", $this->_limit);
157 $this->assign("{$prefix}single", $this->_single);
158
159 $controller = new CRM_Core_Selector_Controller($selector,
160 $this->get(CRM_Utils_Pager::PAGE_ID),
161 $sortID,
162 CRM_Core_Action::VIEW,
163 $this,
164 CRM_Core_Selector_Controller::TRANSFER,
165 $prefix
166 );
167
168 $controller->setEmbedded(TRUE);
169 $controller->moveFromSessionToTemplate();
170
171 //append breadcrumb to survey dashboard.
172 if (CRM_Campaign_BAO_Campaign::accessCampaign()) {
173 $url = CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=survey');
174 CRM_Utils_System::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
175 }
176
177 //set the form title.
178 CRM_Utils_System::setTitle(ts('Find Respondents To %1', array(1 => ucfirst($this->_operation))));
179 }
180
181 public function setDefaultValues() {
182 //load the default survey for all actions.
183 if (empty($this->_defaults)) {
184 $defaultSurveyId = key(CRM_Campaign_BAO_Survey::getSurveys(TRUE, TRUE));
185 if ($defaultSurveyId) {
186 $this->_defaults['campaign_survey_id'] = $defaultSurveyId;
187 }
188 }
189
190 return $this->_defaults;
191 }
192
193 /**
194 * Build the form object
195 *
196 *
197 * @return void
198 */
199 public function buildQuickForm() {
200 parent::buildQuickForm();
201 //build the search form.
202 CRM_Campaign_BAO_Query::buildSearchForm($this);
203
204 $rows = $this->get('rows');
205 if (is_array($rows)) {
206 if (!$this->_single) {
207 $this->addRowSelectors($rows);
208 }
209
210 $permission = CRM_Core_Permission::getPermission();
211 $allTasks = CRM_Campaign_Task::permissionedTaskTitles($permission);
212
213 //hack to serve right page to state machine.
214 $taskMapping = array(
215 'interview' => 1,
216 'reserve' => 2,
217 'release' => 3,
218 );
219
220 $currentTaskValue = CRM_Utils_Array::value($this->_operation, $taskMapping);
221 $taskValue = array($currentTaskValue => $allTasks[$currentTaskValue]);
222 if ($this->_operation == 'interview' && !empty($this->_formValues['campaign_survey_id'])) {
223 $activityTypes = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE);
224
225 $surveyTypeId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey',
226 $this->_formValues['campaign_survey_id'],
227 'activity_type_id'
228 );
229 $taskValue = array(
230 $currentTaskValue => ts('Record %1 Responses',
231 array(1 => $activityTypes[$surveyTypeId])
232 ));
233 }
234
235 $this->addTaskMenu($taskValue);
236 }
237
238 }
239
240 /**
241 * The post processing of the form gets done here.
242 *
243 * Key things done during post processing are
244 * - check for reset or next request. if present, skip post procesing.
245 * - now check if user requested running a saved search, if so, then
246 * the form values associated with the saved search are used for searching.
247 * - if user has done a submit with new values the regular post submissing is
248 * done.
249 * The processing consists of using a Selector / Controller framework for getting the
250 * search results.
251 *
252 * @param
253 *
254 * @return void
255 */
256 public function postProcess() {
257 if ($this->_done) {
258 return;
259 }
260
261 $this->_done = TRUE;
262
263 if (!empty($_POST)) {
264 $this->_formValues = $this->controller->exportValues($this->_name);
265 }
266
267 $this->fixFormValues();
268
269 //format params as per task.
270 $this->formatParams();
271
272 $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
273
274 $this->set('formValues', $this->_formValues);
275 $this->set('queryParams', $this->_queryParams);
276
277 $buttonName = $this->controller->getButtonName();
278 if ($buttonName == $this->_actionButtonName) {
279 // check actionName and if next, then do not repeat a search, since we are going to the next page
280
281 // hack, make sure we reset the task values
282 $stateMachine = $this->controller->getStateMachine();
283 $formName = $stateMachine->getTaskFormName();
284
285 $this->controller->resetPage($formName);
286 return;
287 }
288
289 $sortID = NULL;
290 if ($this->get(CRM_Utils_Sort::SORT_ID)) {
291 $sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
292 $this->get(CRM_Utils_Sort::SORT_DIRECTION)
293 );
294 }
295
296 //get the voter clause.
297 $voterClause = $this->voterClause();
298
299 $selector = new CRM_Campaign_Selector_Search($this->_queryParams,
300 $this->_action,
301 $voterClause,
302 $this->_single,
303 $this->_limit,
304 $this->_context
305 );
306 $selector->setKey($this->controller->_key);
307
308 $prefix = NULL;
309 if ($this->_context == 'basic' ||
310 $this->_context == 'user'
311 ) {
312 $prefix = $this->_prefix;
313 }
314
315 $controller = new CRM_Core_Selector_Controller($selector,
316 $this->get(CRM_Utils_Pager::PAGE_ID),
317 $sortID,
318 CRM_Core_Action::VIEW,
319 $this,
320 CRM_Core_Selector_Controller::SESSION,
321 $prefix
322 );
323 $controller->setEmbedded(TRUE);
324 $query = $selector->getQuery();
325 if ($this->_context == 'user') {
326 $query->setSkipPermission(TRUE);
327 }
328 $controller->run();
329 }
330
331 public function formatParams() {
332 $interviewerId = CRM_Utils_Array::value('survey_interviewer_id', $this->_formValues);
333 if ($interviewerId) {
334 $this->set('interviewerId', $interviewerId);
335 }
336
337 //format multi-select group and contact types.
338 foreach (array('group', 'contact_type') as $param) {
339 if ($this->_force) {
340 continue;
341 }
342 $paramValue = CRM_Utils_Array::value($param, $this->_formValues);
343 if ($paramValue && is_array($paramValue)) {
344 unset($this->_formValues[$param]);
345 foreach ($paramValue as $key => $value) {
346 $this->_formValues[$param][$value] = 1;
347 }
348 }
349 }
350
351 //apply filter of survey contact type for search.
352 $contactType = CRM_Campaign_BAO_Survey::getSurveyContactType(CRM_Utils_Array::value('campaign_survey_id', $this->_formValues));
353 if ($contactType && in_array($this->_operation, array(
354 'reserve', 'interview'))) {
355 $this->_formValues['contact_type'][$contactType] = 1;
356 }
357
358 if ($this->_operation == 'reserve') {
359 if (!empty($this->_formValues['campaign_survey_id'])) {
360 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey',
361 $this->_formValues['campaign_survey_id'],
362 'campaign_id'
363 );
364
365 //allow voter search in sub-part of given constituents,
366 //but make sure in case user does not select any group.
367 //get all associated campaign groups in where filter, CRM-7406
368 $groups = CRM_Utils_Array::value('group', $this->_formValues);
369 if ($campaignId && CRM_Utils_System::isNull($groups)) {
370 $campGroups = CRM_Campaign_BAO_Campaign::getCampaignGroups($campaignId);
371 foreach ($campGroups as $id => $title) $this->_formValues['group'][$id] = 1;
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', CRM_Core_DAO::$_nullObject);
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', CRM_Core_DAO::$_nullObject);
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 }