INFRA-132 - Fix spacing of @return tag in comments
[civicrm-core.git] / CRM / Campaign / Form / Task / Reserve.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 * This class provides the functionality to add contacts for
38 * voter reservation.
39 */
40 class CRM_Campaign_Form_Task_Reserve extends CRM_Campaign_Form_Task {
41
42 /**
43 * Survet id`
44 *
45 * @var int
46 */
47 protected $_surveyId;
48
49 /**
50 * Interviewer id
51 *
52 * @var int
53 */
54 protected $_interviewerId;
55
56 /**
57 * Survey details
58 *
59 * @var object
60 */
61 protected $_surveyDetails;
62
63 /**
64 * Number of voters
65 *
66 * @var int
67 */
68 protected $_numVoters;
69
70 /**
71 * Build all the data structures needed to build the form
72 *
73 * @return void
74 */
75 public function preProcess() {
76 parent::preProcess();
77
78 //get the survey id from user submitted values.
79 $this->_surveyId = $this->get('surveyId');
80 $this->_interviewerId = $this->get('interviewerId');
81 if (!$this->_surveyId) {
82 CRM_Core_Error::statusBounce(ts("Could not find Survey Id."));
83 }
84 if (!$this->_interviewerId) {
85 CRM_Core_Error::statusBounce(ts("Missing Interviewer contact."));
86 }
87 if (!is_array($this->_contactIds) || empty($this->_contactIds)) {
88 CRM_Core_Error::statusBounce(ts("Could not find contacts for reservation."));
89 }
90
91 $params = array('id' => $this->_surveyId);
92 CRM_Campaign_BAO_Survey::retrieve($params, $this->_surveyDetails);
93
94 //get the survey activities.
95 $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
96 $statusIds = array();
97 foreach (array(
98 'Scheduled') as $name) {
99 if ($statusId = array_search($name, $activityStatus)) {
100 $statusIds[] = $statusId;
101 }
102 }
103
104 // these are the activities count that are linked to the current
105 // interviewer and current survey and not the list of ALL survey activities
106 $this->_numVoters = CRM_Campaign_BAO_Survey::getSurveyActivities($this->_surveyId,
107 $this->_interviewerId,
108 $statusIds,
109 NULL,
110 TRUE
111 );
112 //validate the selected survey.
113 $this->validateSurvey();
114 $this->assign('surveyTitle', $this->_surveyDetails['title']);
115 $this->assign('activityType', $this->_surveyDetails['activity_type_id']);
116 $this->assign('surveyId', $this->_surveyId);
117
118 //append breadcrumb to survey dashboard.
119 if (CRM_Campaign_BAO_Campaign::accessCampaign()) {
120 $url = CRM_Utils_System::url('civicrm/campaign', 'reset=1&subPage=survey');
121 CRM_Utils_System::appendBreadCrumb(array(array('title' => ts('Survey(s)'), 'url' => $url)));
122 }
123
124 //set the title.
125 CRM_Utils_System::setTitle(ts('Reserve Respondents'));
126 }
127
128 public function validateSurvey() {
129 $errorMsg = NULL;
130 $maxVoters = CRM_Utils_Array::value('max_number_of_contacts', $this->_surveyDetails);
131 if ($maxVoters) {
132 if ($maxVoters <= $this->_numVoters) {
133 $errorMsg = ts('The maximum number of contacts is already reserved for this interviewer.');
134 }
135 elseif (count($this->_contactIds) > ($maxVoters - $this->_numVoters)) {
136 $errorMsg = ts('You can reserve a maximum of %1 contact(s) at a time for this survey.',
137 array(1 => $maxVoters - $this->_numVoters)
138 );
139 }
140 }
141
142 $defaultNum = CRM_Utils_Array::value('default_number_of_contacts', $this->_surveyDetails);
143 if (!$errorMsg && $defaultNum && (count($this->_contactIds) > $defaultNum)) {
144 $errorMsg = ts('You can reserve a maximum of %1 contact(s) at a time for this survey.',
145 array(1 => $defaultNum)
146 );
147 }
148
149 if ($errorMsg) {
150 CRM_Core_Error::statusBounce($errorMsg);
151 }
152 }
153
154 /**
155 * Build the form object
156 *
157 *
158 * @return void
159 */
160 public function buildQuickForm() {
161 // allow to add contact to either new or existing group.
162 $this->addElement('text', 'ActivityType', ts('Activity Type'));
163 $this->addElement('text', 'newGroupName', ts('Name for new group'));
164 $this->addElement('text', 'newGroupDesc', ts('Description of new group'));
165 $groups = CRM_Core_PseudoConstant::nestedGroup();
166 $hasExistingGroups = FALSE;
167 if (is_array($groups) && !empty($groups)) {
168 $hasExistingGroups = TRUE;
169 $this->addElement('select', 'groups', ts('Add respondent(s) to existing group(s)'),
170 $groups, array('multiple' => "multiple", 'class' => 'crm-select2')
171 );
172 }
173 $this->assign('hasExistingGroups', $hasExistingGroups);
174
175 $buttons = array(
176 array(
177 'type' => 'done',
178 'name' => ts('Reserve'),
179 'subName' => 'reserve',
180 'isDefault' => TRUE,
181 ));
182
183 if (CRM_Core_Permission::check('manage campaign') ||
184 CRM_Core_Permission::check('administer CiviCampaign') ||
185 CRM_Core_Permission::check('interview campaign contacts')
186 ) {
187 $buttons[] = array(
188 'type' => 'next',
189 'name' => ts('Reserve and Interview'),
190 'subName' => 'reserveToInterview',
191 );
192 }
193 $buttons[] = array(
194 'type' => 'back',
195 'name' => ts('Cancel'),
196 );
197
198 $this->addButtons($buttons);
199 $this->addFormRule(array('CRM_Campaign_Form_Task_Reserve', 'formRule'), $this);
200 }
201
202 /**
203 * Global validation rules for the form
204 *
205 * @param array $fields
206 * Posted values of the form.
207 *
208 * @param $files
209 * @param $self
210 *
211 * @return array
212 * list of errors to be posted back to the form
213 * @static
214 */
215 public static function formRule($fields, $files, $self) {
216 $errors = array();
217 $invalidGroupName = FALSE;
218 if (!empty($fields['newGroupName'])) {
219 $title = trim($fields['newGroupName']);
220 $name = CRM_Utils_String::titleToVar($title);
221 $query = 'select count(*) from civicrm_group where name like %1 OR title like %2';
222 $grpCnt = CRM_Core_DAO::singleValueQuery($query, array(
223 1 => array($name, 'String'),
224 2 => array($title, 'String'),
225 ));
226 if ($grpCnt) {
227 $invalidGroupName = TRUE;
228 $errors['newGroupName'] = ts('Group \'%1\' already exists.', array(1 => $fields['newGroupName']));
229 }
230 }
231 $self->assign('invalidGroupName', $invalidGroupName);
232
233 return empty($errors) ? TRUE : $errors;
234 }
235
236 /**
237 * Process the form after the input has been submitted and validated
238 *
239 *
240 * @return void
241 */
242 public function postProcess() {
243 //add reservation.
244 $countVoters = 0;
245 $maxVoters = CRM_Utils_Array::value('max_number_of_contacts', $this->_surveyDetails);
246 $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
247 $statusHeld = array_search('Scheduled', $activityStatus);
248
249 $reservedVoterIds = array();
250 foreach ($this->_contactIds as $cid) {
251 $subject = ts('%1', array(1 => $this->_surveyDetails['title'])) . ' - ' . ts('Respondent Reservation');
252 $session = CRM_Core_Session::singleton();
253 $activityParams = array(
254 'source_contact_id' => $session->get('userID'),
255 'assignee_contact_id' => array($this->_interviewerId),
256 'target_contact_id' => array($cid),
257 'source_record_id' => $this->_surveyId,
258 'activity_type_id' => $this->_surveyDetails['activity_type_id'],
259 'subject' => $subject,
260 'activity_date_time' => date('YmdHis'),
261 'status_id' => $statusHeld,
262 'skipRecentView' => 1,
263 'campaign_id' => CRM_Utils_Array::value('campaign_id', $this->_surveyDetails),
264 );
265 $activity = CRM_Activity_BAO_Activity::create($activityParams);
266 if ($activity->id) {
267 $countVoters++;
268 $reservedVoterIds[$cid] = $cid;
269 }
270 if ($maxVoters && ($maxVoters <= ($this->_numVoters + $countVoters))) {
271 break;
272 }
273 }
274
275 //add reserved voters to groups.
276 $groupAdditions = $this->_addRespondentToGroup($reservedVoterIds);
277
278 // Success message
279 if ($countVoters > 0) {
280 $status = '<p>' . ts("%1 Contact(s) have been reserved.", array(1 => $countVoters)) . '</p>';
281 if ($groupAdditions) {
282 $status .= '<p>' . ts('Respondent(s) has been added to %1 group(s).',
283 array(1 => implode(', ', $groupAdditions))
284 ) . '</p>';
285 }
286 CRM_Core_Session::setStatus($status, ts('Reservation Added'), 'success');
287 }
288 // Error message
289 if (count($this->_contactIds) > $countVoters) {
290 CRM_Core_Session::setStatus(ts('Reservation did not add for %1 contact(s).',
291 array(1 => (count($this->_contactIds) - $countVoters))
292 ), ts('Notice'));
293 }
294
295 //get ready to jump to voter interview form.
296 $buttonName = $this->controller->getButtonName();
297 if (!empty($reservedVoterIds) &&
298 $buttonName == '_qf_Reserve_next_reserveToInterview'
299 ) {
300 $this->controller->set('surveyId', $this->_surveyId);
301 $this->controller->set('contactIds', $reservedVoterIds);
302 $this->controller->set('interviewerId', $this->_interviewerId);
303 $this->controller->set('reserveToInterview', TRUE);
304 }
305 }
306
307 /**
308 * @param $contactIds
309 *
310 * @return array
311 */
312 private function _addRespondentToGroup($contactIds) {
313 $groupAdditions = array();
314 if (empty($contactIds)) {
315 return $groupAdditions;
316 }
317
318 $params = $this->controller->exportValues($this->_name);
319 $groups = CRM_Utils_Array::value('groups', $params, array());
320 $newGroupName = CRM_Utils_Array::value('newGroupName', $params);
321 $newGroupDesc = CRM_Utils_Array::value('newGroupDesc', $params);
322
323 $newGroupId = NULL;
324 //create new group.
325 if ($newGroupName) {
326 $grpParams = array(
327 'title' => $newGroupName,
328 'description' => $newGroupDesc,
329 'is_active' => TRUE,
330 );
331 $group = CRM_Contact_BAO_Group::create($grpParams);
332 $groups[] = $newGroupId = $group->id;
333 }
334
335 //add the respondents to groups.
336 if (is_array($groups)) {
337 $existingGroups = CRM_Core_PseudoConstant::group();
338 foreach ($groups as $groupId) {
339 $addCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
340 $totalCount = CRM_Utils_Array::value(1, $addCount);
341 if ($groupId == $newGroupId) {
342 $name = $newGroupName;
343 $new = TRUE;
344 }
345 else {
346 $name = $existingGroups[$groupId];
347 $new = FALSE;
348 }
349 if ($totalCount) {
350 $url = CRM_Utils_System::url('civicrm/group/search',
351 'reset=1&force=1&context=smog&gid=' . $groupId
352 );
353 $groupAdditions[] = '<a href="' . $url . '">' . $name . '</a>';
354 }
355 }
356 }
357
358 return $groupAdditions;
359 }
360 }