Fix Bug #830: Negative assurance points
[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 // Build the left navigation
27 $actions = array();
28 $actions['assurance'] = I18n::_('Automated Assurance');
29 $actions['admin-increase'] = I18n::_('Administrative Increase');
30 $actions['assurer-challenge'] = I18n::_('Assurer Challenge');
31 $actions['flags'] = I18n::_('Set Flags');
32 $url = array('controller' => 'manage-account');
33 foreach ($actions as $action => $label) {
34 $url['action'] = $action;
35 $link = '<a href="'.$this->view->url($url, 'default', true).'">'.
36 $label . '</a>';
37 $this->view->leftNav($link);
38 }
39
40 }
41
42 public function indexAction()
43 {
44 // Just render the view
45 return;
46 }
47
48 public function assuranceAction()
49 {
50 // Validate form
51 $form = $this->getAssuranceForm();
52 if (!$this->getRequest()->isPost() || !$form->isValid($_POST)) {
53 $this->view->assurance_form = $form;
54 return $this->render('assuranceform');
55 }
56
57 // Form is valid -> get values for processing
58 $values = $form->getValues();
59
60 // Get user data
61 $user['id'] = $this->getUserId();
62 $user['points'] = $this->getPoints($user['id']);
63
64
65 // Do the actual assurances
66 $assurance = array(); // Make sure the array is empty
67 $assurance['to'] = $user['id'];
68 $assurance['location'] = $values['location'];
69 $assurance['date'] = $values['date'];
70 $assurance['when'] = new Zend_Db_Expr('now()');
71 $this->view->assurancesDone = array();
72
73 $quantity = $values['quantity'];
74 do {
75 // split up into multiple assurances
76 if ($quantity > self::MAX_POINTS_PER_ASSURANCE) {
77 $assurance['awarded'] = self::MAX_POINTS_PER_ASSURANCE;
78 $quantity -= self::MAX_POINTS_PER_ASSURANCE;
79 } else {
80 $assurance['awarded'] = $quantity;
81 $quantity = 0;
82 }
83
84 // Get the assurer for this assurance
85 $assurance['from'] = $this->getNewAssurer($user['id']);
86
87 // only assign points whithin the limit
88 if ($user['points'] + $assurance['awarded'] > self::MAX_ASSURANCE_POINTS){
89 $assurance['points'] = self::MAX_ASSURANCE_POINTS - $user['points'];
90 } else {
91 $assurance['points'] = $assurance['awarded'];
92 }
93
94 // Only assign positive amounts
95 if ($assurance['points'] < 0){
96 $assurance['points'] = 0;
97 }
98
99 $this->db->insert('notary', $assurance);
100
101 $user['points'] += $assurance['points'];
102 $this->view->assurancesDone[] = $assurance['points'];
103 } while ($quantity > 0);
104
105
106 // Maybe user is now assurer
107 $this->fixAssurerFlag($user['id']);
108
109 return;
110 }
111
112 public function adminIncreaseAction()
113 {
114 // Validate form
115 $form = $this->getAdminIncreaseForm();
116 if (!$this->getRequest()->isPost() || !$form->isValid($_POST)) {
117 $this->view->admin_increase_form = $form;
118 return $this->render('admin-increase-form');
119 }
120
121 // Form is valid -> get values for processing
122 $values = $form->getValues();
123
124 // Get user data
125 $user['id'] = $this->getUserId();
126 $user['points'] = $this->getPoints($user['id']);
127
128
129 // Do the actual increase
130 $increase = array(); // Make sure the array is empty
131 $increase['from'] = $user['id'];
132 $increase['to'] = $user['id'];
133 $increase['location'] = $values['location'];
134 $increase['date'] = $values['date'];
135 $increase['method'] = self::ADMIN_INCREASE_METHOD;
136 $increase['when'] = new Zend_Db_Expr('now()');
137 $this->view->adminIncreasesDone = array();
138
139 $quantity = $values['quantity'];
140 do {
141 // Split up into multiple increases if fragment flag is set
142 if ($values['fragment'] == '1' &&
143 $quantity > self::ADMIN_INCREASE_FRAGMENT_SIZE) {
144 $increase['awarded'] = self::ADMIN_INCREASE_FRAGMENT_SIZE;
145 $quantity -= self::ADMIN_INCREASE_FRAGMENT_SIZE;
146 } else {
147 $increase['awarded'] = $quantity;
148 $quantity = 0;
149 }
150
151 // Only assign points within the limit if unlimited flag is not set
152 if ($values['unlimited'] != '1') {
153 if ($user['points'] >= self::MAX_POINTS_TOTAL) {
154 // No more administrative increases should be done
155 break;
156 } elseif ($user['points'] + $increase['awarded'] > self::MAX_POINTS_TOTAL) {
157 $increase['awarded'] = self::MAX_POINTS_TOTAL - $user['points'];
158 }
159 }
160
161 // Admin increases always have `points` == `awarded`
162 $increase['points'] = $increase['awarded'];
163
164 $this->db->insert('notary', $increase);
165
166 $user['points'] += $increase['points'];
167 $this->view->adminIncreasesDone[] = $increase['points'];
168 } while ($quantity > 0);
169
170 // Maybe user is now assurer
171 $this->fixAssurerFlag($user['id']);
172
173 return;
174 }
175
176
177 public function assurerChallengeAction()
178 {
179 // Validate form
180 $form = $this->getAssurerChallengeForm();
181 if (!$this->getRequest()->isPost() || !$form->isValid($_POST)) {
182 $this->view->assurer_challenge_form = $form;
183 return $this->render('assurer-challenge-form');
184 }
185
186 // Form is valid -> get values for processing
187 $values = $form->getValues();
188
189 // Get user data
190 $user['id'] = $this->getUserId();
191
192 // Assign the assurer challenge
193 $challenge = array(); // Make sure the array is empty
194 $challenge['user_id'] = $user['id'];
195 $challenge['variant_id'] = $values['variant'];
196 $challenge['pass_date'] = date('Y-m-d H:i:s');
197 $this->db->insert('cats_passed', $challenge);
198
199 // Maybe user is now assurer
200 $this->fixAssurerFlag($user['id']);
201
202 return;
203 }
204
205 public function flagsAction()
206 {
207 // Get user data
208 $user['id'] = $this->getUserId();
209
210 // Validate form
211 $form = $this->getFlagsForm($user['id']);
212 $this->view->flags_form = $form;
213 if (!$this->getRequest()->isPost() || !$form->isValid($_POST)) {
214 return;
215 }
216
217 $flags = array('admin', 'codesign', 'orgadmin', 'ttpadmin', 'board',
218 'locadmin', 'locked', 'assurer_blocked');
219 $update = array(); // Make sure array is empty
220 foreach ($flags as $flag) {
221 if ($form->getElement($flag)->isChecked()) {
222 $update[$flag] = 1;
223 } else {
224 $update[$flag] = 0;
225 }
226 }
227 $this->db->update('users', $update, '`id` = '.$user['id']);
228
229 return;
230 }
231
232 /**
233 * Get and check the user ID of the current user
234 *
235 * @return int The ID of the current user
236 */
237 protected function getUserId()
238 {
239 $session = Zend_Registry::get('session');
240 if ($session->authdata['authed'] !== true) {
241 throw new Exception(__METHOD__ . ': you need to log in to use this feature');
242 }
243
244 // Check if the ID is present on the test server
245 $query = 'select `id` from `users` where `id` = :user';
246 $query_params['user'] = $session->authdata['authed_id'];
247 $result = $this->db->query($query, $query_params);
248 if ($result->rowCount() !== 1) {
249 throw new Exception(__METHOD__ . ': user ID not found in the data base');
250 }
251 $row = $result->fetch();
252
253 return $row['id'];
254 }
255
256 /**
257 * Get current points of the user
258 *
259 * @param int $user_id ID of the user
260 * @return int the amount of points the user currently has
261 */
262 protected function getPoints($user_id)
263 {
264 $query = 'select sum(`points`) as `total` from `notary` where `to` = :user';
265 $query_params['user'] = $user_id;
266 $row = $this->db->query($query, $query_params)->fetch();
267 if ($row['total'] === NULL) $row['total'] = 0;
268
269 return $row['total'];
270 }
271
272 /**
273 * Get the first assurer who didn't already assure the user
274 *
275 * @param int $user_id The ID of the user who should get assured
276 * @return int The ID of the selected assurer
277 */
278 protected function getNewAssurer($user_id)
279 {
280 $query = 'select min(`id`) as `assurer` from `users` ' .
281 'where `email` like \'john.doe-___@example.com\' and ' .
282 '`id` not in (select `from` from `notary` where `to` = :user)';
283 $query_params['user'] = $user_id;
284 $row = $this->db->query($query, $query_params)->fetch();
285
286 if ($row['assurer'] === NULL) {
287 throw new Exception(__METHOD__ . ': no more assurers that haven\'t '.
288 'already assured this account');
289 }
290
291 return $row['assurer'];
292 }
293
294 /**
295 * Fix the assurer flag for the given user
296 *
297 * @param $user_id ID of the user
298 */
299 protected function fixAssurerFlag($user_id)
300 {
301 // TODO: unset flag if requirements are not met
302
303 $query = 'UPDATE `users` SET `assurer` = 1 WHERE `users`.`id` = :user AND '.
304
305 'EXISTS(SELECT * FROM `cats_passed` AS `cp`, `cats_variant` AS `cv` '.
306 'WHERE `cp`.`variant_id` = `cv`.`id` AND `cv`.`type_id` = 1 AND '.
307 '`cp`.`user_id` = :user) AND '.
308
309 '(SELECT SUM(`points`) FROM `notary` WHERE `to` = :user AND '.
310 '`expire` < now()) >= 100';
311 $query_params['user'] = $user_id;
312 $this->db->query($query, $query_params);
313 }
314
315 protected function getAssuranceForm()
316 {
317 $form = new Zend_Form();
318 $form->setAction('/manage-account/assurance')->setMethod('post');
319
320 $quantity = new Zend_Form_Element_Text('quantity');
321 $quantity->setRequired(true)
322 ->setLabel(I18n::_('Number of Points'))
323 ->addFilter(new Zend_Filter_Int())
324 ->addValidator(new Zend_Validate_Between(0, 100));
325 $form->addElement($quantity);
326
327 $location = new Zend_Form_Element_Text('location');
328 $location->setRequired(true)
329 ->setLabel(I18n::_('Location'))
330 ->setValue(I18n::_('CAcert Test Manager'))
331 ->addValidator(new Zend_Validate_StringLength(1,255));
332 $form->addElement($location);
333
334 $date = new Zend_Form_Element_Text('date');
335 $date->setRequired(true)
336 ->setLabel(I18n::_('Date of Assurance'))
337 ->setValue(date('Y-m-d H:i:s'))
338 ->addValidator(new Zend_Validate_StringLength(1,255));
339 $form->addElement($date);
340
341 $submit = new Zend_Form_Element_Submit('submit');
342 $submit->setLabel(I18n::_('Assure Me'));
343 $form->addElement($submit);
344
345 return $form;
346 }
347
348 protected function getAdminIncreaseForm()
349 {
350 $form = new Zend_Form();
351 $form->setAction('/manage-account/admin-increase')->setMethod('post');
352
353 $quantity = new Zend_Form_Element_Text('quantity');
354 $quantity->setRequired(true)
355 ->setLabel(I18n::_('Number of Points'))
356 ->addFilter(new Zend_Filter_Int())
357 ->addValidator(new Zend_Validate_GreaterThan(0));
358 $form->addElement($quantity);
359
360 $fragment = new Zend_Form_Element_Checkbox('fragment');
361 $fragment->setLabel(I18n::_('Split into 2-Point Fragments'))
362 ->setChecked(true);
363 $form->addElement($fragment);
364
365 $unlimited = new Zend_Form_Element_Checkbox('unlimited');
366 $unlimited->setLabel(I18n::_('Assign Points even if the Limit of 150 '.
367 'is exceeded'))
368 ->setChecked(false);
369 $form->addElement($unlimited);
370
371 $location = new Zend_Form_Element_Text('location');
372 $location->setRequired(true)
373 ->setLabel(I18n::_('Location'))
374 ->setValue(I18n::_('CAcert Test Manager'))
375 ->addValidator(new Zend_Validate_StringLength(1,255));
376 $form->addElement($location);
377
378 $date = new Zend_Form_Element_Text('date');
379 $date->setRequired(true)
380 ->setLabel(I18n::_('Date of Increase'))
381 ->setValue(date('Y-m-d H:i:s'))
382 ->addValidator(new Zend_Validate_StringLength(1,255));
383 $form->addElement($date);
384
385 $submit = new Zend_Form_Element_Submit('submit');
386 $submit->setLabel(I18n::_('Give Me Points'));
387 $form->addElement($submit);
388
389 return $form;
390 }
391
392 protected function getAssurerChallengeForm()
393 {
394 $form = new Zend_Form();
395 $form->setAction('/manage-account/assurer-challenge')
396 ->setMethod('post');
397
398 $variant = new Zend_Form_Element_Select('variant');
399 $variant->setLabel(I18n::_('Variant'));
400 // Get the available variants from the database
401 $query = 'select `id`, `test_text` from `cats_variant`
402 where `type_id` = 1';
403 $options = $this->db->fetchPairs($query);
404 $variant->setMultiOptions($options)
405 ->setRequired(true);
406 $form->addElement($variant);
407
408 $submit = new Zend_Form_Element_Submit('submit');
409 $submit->setLabel(I18n::_('Challenge Me'));
410 $form->addElement($submit);
411
412 return $form;
413 }
414
415 protected function getFlagsForm($user_id)
416 {
417 $form = new Zend_Form();
418 $form->setAction('/manage-account/flags')
419 ->setMethod('post');
420
421 // Get the current setting of the flags
422 $query = 'select `admin`, `codesign`, `orgadmin`, `ttpadmin`, `board`,
423 `tverify`, `locadmin`, `locked`, `assurer_blocked` from `users`
424 where `id` = :user';
425 $query_params['user'] = $user_id;
426 $result = $this->db->query($query, $query_params);
427 if ($result->rowCount() !== 1) {
428 throw new Exception(__METHOD__ . ': user ID not found in the data base');
429 }
430 $row = $result->fetch();
431
432 // Add a checkbox for each flag
433 $labels = array();
434 $labels['admin'] = I18n::_('Support Engineer');
435 $labels['codesign'] = I18n::_('Code Signing');
436 $labels['orgadmin'] = I18n::_('Organisation Admin');
437 $labels['ttpadmin'] = I18n::_('TTP Admin');
438 $labels['board'] = I18n::_('Board Member');
439 $labels['locadmin'] = I18n::_('Location Admin');
440 $labels['locked'] = I18n::_('Lock Account');
441 $labels['assurer_blocked'] = I18n::_('Block Assurer');
442
443 foreach ($labels as $flag => $label) {
444 $checkbox = new Zend_Form_Element_Checkbox($flag);
445 $checkbox->setLabel($label)
446 ->setChecked($row[$flag] === 1);
447 $form->addElement($checkbox);
448 }
449
450 $submit = new Zend_Form_Element_Submit('submit');
451 $submit->setLabel(I18n::_('Save Flags'));
452 $form->addElement($submit);
453
454 return $form;
455 }
456 }