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