New assurer challenge feature
[cacert-mgr.git] / manager / application / controllers / ManageAccountController.php
1 <?php
2 /**
3 * @author Michael Tänzer
4 */
5
6 class ManageAccountController extends Zend_Controller_Action
7 {
8 const MAX_POINTS_PER_ASSURANCE = 35;
9 const MAX_ASSURANCE_POINTS = 100;
10 const MAX_POINTS_TOTAL = 150;
11 const ADMIN_INCREASE_FRAGMENT_SIZE = 2;
12
13 // Value used in the database to identify a admin increase
14 const ADMIN_INCREASE_METHOD = 'Administrative Increase';
15
16 protected $db;
17
18 public function init()
19 {
20 $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini',
21 APPLICATION_ENV);
22
23 $this->db = Zend_Db::factory($config->ca_mgr->db->auth->pdo,
24 $config->ca_mgr->db->auth);
25 }
26
27 public function indexAction()
28 {
29 // Just render the view
30 return;
31 }
32
33 public function assuranceAction()
34 {
35 // Validate form
36 $form = $this->getAssuranceForm();
37 if (!$this->getRequest()->isPost() || !$form->isValid($_POST)) {
38 $this->view->assurance_form = $form;
39 return $this->render('assuranceform');
40 }
41
42 // Form is valid -> get values for processing
43 $values = $form->getValues();
44
45 // Get user data
46 $user['id'] = $this->getUserId();
47 $user['points'] = $this->getPoints($user['id']);
48
49
50 // Do the actual assurances
51 $assurance = array(); // Make sure the array is empty
52 $assurance['to'] = $user['id'];
53 $assurance['location'] = $values['location'];
54 $assurance['date'] = $values['date'];
55 $assurance['when'] = new Zend_Db_Expr('now()');
56 $this->view->assurancesDone = array();
57
58 $quantity = $values['quantity'];
59 do {
60 // split up into multiple assurances
61 if ($quantity > self::MAX_POINTS_PER_ASSURANCE) {
62 $assurance['awarded'] = self::MAX_POINTS_PER_ASSURANCE;
63 $quantity -= self::MAX_POINTS_PER_ASSURANCE;
64 } else {
65 $assurance['awarded'] = $quantity;
66 $quantity = 0;
67 }
68
69 // Get the assurer for this assurance
70 $assurance['from'] = $this->getNewAssurer($user['id']);
71
72 // only assign points whithin the limit
73 if ($user['points'] + $assurance['awarded'] > self::MAX_ASSURANCE_POINTS){
74 $assurance['points'] = self::MAX_ASSURANCE_POINTS - $user['points'];
75 } else {
76 $assurance['points'] = $assurance['awarded'];
77 }
78
79 $this->db->insert('notary', $assurance);
80
81 $user['points'] += $assurance['points'];
82 $this->view->assurancesDone[] = $assurance['points'];
83 } while ($quantity > 0);
84
85
86 // Maybe user is now assurer
87 $this->fixAssurerFlag($user['id']);
88
89 return;
90 }
91
92 public function adminIncreaseAction()
93 {
94 // Validate form
95 $form = $this->getAdminIncreaseForm();
96 if (!$this->getRequest()->isPost() || !$form->isValid($_POST)) {
97 $this->view->admin_increase_form = $form;
98 return $this->render('admin-increase-form');
99 }
100
101 // Form is valid -> get values for processing
102 $values = $form->getValues();
103
104 // Get user data
105 $user['id'] = $this->getUserId();
106 $user['points'] = $this->getPoints($user['id']);
107
108
109 // Do the actual increase
110 $increase = array(); // Make sure the array is empty
111 $increase['from'] = $user['id'];
112 $increase['to'] = $user['id'];
113 $increase['location'] = $values['location'];
114 $increase['date'] = $values['date'];
115 $increase['method'] = self::ADMIN_INCREASE_METHOD;
116 $increase['when'] = new Zend_Db_Expr('now()');
117 $this->view->adminIncreasesDone = array();
118
119 $quantity = $values['quantity'];
120 do {
121 // Split up into multiple increases if fragment flag is set
122 if ($values['fragment'] == '1' &&
123 $quantity > self::ADMIN_INCREASE_FRAGMENT_SIZE) {
124 $increase['awarded'] = self::ADMIN_INCREASE_FRAGMENT_SIZE;
125 $quantity -= self::ADMIN_INCREASE_FRAGMENT_SIZE;
126 } else {
127 $increase['awarded'] = $quantity;
128 $quantity = 0;
129 }
130
131 // Only assign points within the limit if unlimited flag is not set
132 if ($values['unlimited'] != '1') {
133 if ($user['points'] >= self::MAX_POINTS_TOTAL) {
134 // No more administrative increases should be done
135 break;
136 } elseif ($user['points'] + $increase['awarded'] > self::MAX_POINTS_TOTAL) {
137 $increase['awarded'] = self::MAX_POINTS_TOTAL - $user['points'];
138 }
139 }
140
141 // Admin increases always have `points` == `awarded`
142 $increase['points'] = $increase['awarded'];
143
144 $this->db->insert('notary', $increase);
145
146 $user['points'] += $increase['points'];
147 $this->view->adminIncreasesDone[] = $increase['points'];
148 } while ($quantity > 0);
149
150 // Maybe user is now assurer
151 $this->fixAssurerFlag($user['id']);
152
153 return;
154 }
155
156
157 public function assurerChallengeAction()
158 {
159 // Validate form
160 $form = $this->getAssurerChallengeForm();
161 if (!$this->getRequest()->isPost() || !$form->isValid($_POST)) {
162 $this->view->assurer_challenge_form = $form;
163 return $this->render('assurer-challenge-form');
164 }
165
166 // Form is valid -> get values for processing
167 $values = $form->getValues();
168
169 // Get user data
170 $user['id'] = $this->getUserId();
171
172 // Assign the assurer challenge
173 $challenge = array(); // Make sure the array is empty
174 $challenge['user_id'] = $user['id'];
175 $challenge['variant_id'] = $values['variant'];
176 $challenge['pass_date'] = date('Y-m-d H:i:s');
177 $this->db->insert('cats_passed', $challenge);
178
179 // Maybe user is now assurer
180 $this->fixAssurerFlag($user['id']);
181
182 return;
183 }
184
185 /**
186 * Get and check the user ID of the current user
187 *
188 * @return int The ID of the current user
189 */
190 protected function getUserId()
191 {
192 $session = Zend_Registry::get('session');
193 if ($session->authdata['authed'] !== true) {
194 throw new Exception(__METHOD__ . ': you need to log in to use this feature');
195 }
196
197 // Check if the ID is present on the test server
198 $query = 'select `id` from `users` where `id` = :user';
199 $query_params['user'] = $session->authdata['authed_id'];
200 $result = $this->db->query($query, $query_params);
201 if ($result->rowCount() !== 1) {
202 throw new Exception(__METHOD__ . ': user ID not found in the data base');
203 }
204 $row = $result->fetch();
205
206 return $row['id'];
207 }
208
209 /**
210 * Get current points of the user
211 *
212 * @param int $user_id ID of the user
213 * @return int the amount of points the user currently has
214 */
215 protected function getPoints($user_id)
216 {
217 $query = 'select sum(`points`) as `total` from `notary` where `to` = :user';
218 $query_params['user'] = $user_id;
219 $row = $this->db->query($query, $query_params)->fetch();
220 if ($row['total'] === NULL) $row['total'] = 0;
221
222 return $row['total'];
223 }
224
225 /**
226 * Get the first assurer who didn't already assure the user
227 *
228 * @param int $user_id The ID of the user who should get assured
229 * @return int The ID of the selected assurer
230 */
231 protected function getNewAssurer($user_id)
232 {
233 $query = 'select min(`id`) as `assurer` from `users` ' .
234 'where `email` like \'john.doe-___@example.com\' and ' .
235 '`id` not in (select `from` from `notary` where `to` = :user)';
236 $query_params['user'] = $user_id;
237 $row = $this->db->query($query, $query_params)->fetch();
238
239 if ($row['assurer'] === NULL) {
240 throw new Exception(__METHOD__ . ': no more assurers that haven\'t '.
241 'already assured this account');
242 }
243
244 return $row['assurer'];
245 }
246
247 /**
248 * Fix the assurer flag for the given user
249 *
250 * @param $user_id ID of the user
251 */
252 protected function fixAssurerFlag($user_id)
253 {
254 // TODO: unset flag if requirements are not met
255
256 $query = 'UPDATE `users` SET `assurer` = 1 WHERE `users`.`id` = :user AND '.
257
258 'EXISTS(SELECT * FROM `cats_passed` AS `cp`, `cats_variant` AS `cv` '.
259 'WHERE `cp`.`variant_id` = `cv`.`id` AND `cv`.`type_id` = 1 AND '.
260 '`cp`.`user_id` = :user) AND '.
261
262 '(SELECT SUM(`points`) FROM `notary` WHERE `to` = :user AND '.
263 '`expire` < now()) >= 100';
264 $query_params['user'] = $user_id;
265 $this->db->query($query, $query_params);
266 }
267
268 protected function getAssuranceForm()
269 {
270 $form = new Zend_Form();
271 $form->setAction('/manage-account/assurance')->setMethod('post');
272
273 $quantity = new Zend_Form_Element_Text('quantity');
274 $quantity->setRequired(true)
275 ->setLabel(I18n::_('Number of Points'))
276 ->addFilter(new Zend_Filter_Int())
277 ->addValidator(new Zend_Validate_Between(0, 100));
278 $form->addElement($quantity);
279
280 $location = new Zend_Form_Element_Text('location');
281 $location->setRequired(true)
282 ->setLabel(I18n::_('Location'))
283 ->setValue(I18n::_('CAcert Test Manager'))
284 ->addValidator(new Zend_Validate_StringLength(1,255));
285 $form->addElement($location);
286
287 $date = new Zend_Form_Element_Text('date');
288 $date->setRequired(true)
289 ->setLabel(I18n::_('Date of Assurance'))
290 ->setValue(date('Y-m-d H:i:s'))
291 ->addValidator(new Zend_Validate_StringLength(1,255));
292 $form->addElement($date);
293
294 $submit = new Zend_Form_Element_Submit('submit');
295 $submit->setLabel(I18n::_('Assure Me'));
296 $form->addElement($submit);
297
298 return $form;
299 }
300
301 protected function getAdminIncreaseForm()
302 {
303 $form = new Zend_Form();
304 $form->setAction('/manage-account/admin-increase')->setMethod('post');
305
306 $quantity = new Zend_Form_Element_Text('quantity');
307 $quantity->setRequired(true)
308 ->setLabel(I18n::_('Number of Points'))
309 ->addFilter(new Zend_Filter_Int())
310 ->addValidator(new Zend_Validate_GreaterThan(0));
311 $form->addElement($quantity);
312
313 $fragment = new Zend_Form_Element_Checkbox('fragment');
314 $fragment->setLabel(I18n::_('Split into 2-Point Fragments'))
315 ->setChecked(true);
316 $form->addElement($fragment);
317
318 $unlimited = new Zend_Form_Element_Checkbox('unlimited');
319 $unlimited->setLabel(I18n::_('Assign Points even if the Limit of 150 '.
320 'is exceeded'))
321 ->setChecked(false);
322 $form->addElement($unlimited);
323
324 $location = new Zend_Form_Element_Text('location');
325 $location->setRequired(true)
326 ->setLabel(I18n::_('Location'))
327 ->setValue(I18n::_('CAcert Test Manager'))
328 ->addValidator(new Zend_Validate_StringLength(1,255));
329 $form->addElement($location);
330
331 $date = new Zend_Form_Element_Text('date');
332 $date->setRequired(true)
333 ->setLabel(I18n::_('Date of Increase'))
334 ->setValue(date('Y-m-d H:i:s'))
335 ->addValidator(new Zend_Validate_StringLength(1,255));
336 $form->addElement($date);
337
338 $submit = new Zend_Form_Element_Submit('submit');
339 $submit->setLabel(I18n::_('Give Me Points'));
340 $form->addElement($submit);
341
342 return $form;
343 }
344
345 protected function getAssurerChallengeForm()
346 {
347 $form = new Zend_Form();
348 $form->setAction('/manage-account/assurer-challenge')
349 ->setMethod('post');
350
351 $variant = new Zend_Form_Element_Select('variant');
352 $variant->setLabel(I18n::_('Variant'));
353 // Get the available variants from the database
354 $query = 'select `id`, `test_text` from `cats_variant`
355 where `type_id` = 1';
356 $options = $this->db->fetchPairs($query);
357 $variant->setOptions($options)
358 ->setRequired(true);
359 $form->addElement($variant);
360
361 $submit = new Zend_Form_Element_Submit('submit');
362 $submit->setLabel(I18n::_('Challenge Me'));
363 $form->addElement($submit);
364
365 return $form;
366 }
367 }