Merge remote branch 'origin/xorg/1.0.2/master' into xorg/master
[platal.git] / modules / admin.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 class AdminModule extends PLModule
23 {
24 function handlers()
25 {
26 return array(
27 'phpinfo' => $this->make_hook('phpinfo', AUTH_MDP, 'admin'),
28 'get_rights' => $this->make_hook('get_rights', AUTH_COOKIE, 'admin'),
29 'set_skin' => $this->make_hook('set_skin', AUTH_COOKIE, 'admin'),
30 'admin' => $this->make_hook('default', AUTH_MDP, 'admin'),
31 'admin/dead-but-active' => $this->make_hook('dead_but_active', AUTH_MDP, 'admin'),
32 'admin/deaths' => $this->make_hook('deaths', AUTH_MDP, 'admin'),
33 'admin/downtime' => $this->make_hook('downtime', AUTH_MDP, 'admin'),
34 'admin/homonyms' => $this->make_hook('homonyms', AUTH_MDP, 'admin'),
35 'admin/logger' => $this->make_hook('logger', AUTH_MDP, 'admin'),
36 'admin/logger/actions' => $this->make_hook('logger_actions', AUTH_MDP, 'admin'),
37 'admin/postfix/blacklist' => $this->make_hook('postfix_blacklist', AUTH_MDP, 'admin'),
38 'admin/postfix/delayed' => $this->make_hook('postfix_delayed', AUTH_MDP, 'admin'),
39 'admin/postfix/regexp_bounces' => $this->make_hook('postfix_regexpsbounces', AUTH_MDP, 'admin'),
40 'admin/postfix/whitelist' => $this->make_hook('postfix_whitelist', AUTH_MDP, 'admin'),
41 'admin/mx/broken' => $this->make_hook('mx_broken', AUTH_MDP, 'admin'),
42 'admin/skins' => $this->make_hook('skins', AUTH_MDP, 'admin'),
43 'admin/user' => $this->make_hook('user', AUTH_MDP, 'admin'),
44 'admin/add_accounts' => $this->make_hook('add_accounts', AUTH_MDP, 'admin'),
45 'admin/validate' => $this->make_hook('validate', AUTH_MDP, 'admin'),
46 'admin/validate/answers' => $this->make_hook('validate_answers', AUTH_MDP, 'admin'),
47 'admin/wiki' => $this->make_hook('wiki', AUTH_MDP, 'admin'),
48 'admin/ipwatch' => $this->make_hook('ipwatch', AUTH_MDP, 'admin'),
49 'admin/icons' => $this->make_hook('icons', AUTH_MDP, 'admin'),
50 'admin/accounts' => $this->make_hook('accounts', AUTH_MDP, 'admin'),
51 'admin/account/watch' => $this->make_hook('account_watch', AUTH_MDP, 'admin'),
52 'admin/account/types' => $this->make_hook('account_types', AUTH_MDP, 'admin'),
53 'admin/jobs' => $this->make_hook('jobs', AUTH_MDP, 'admin'),
54 );
55 }
56
57 function handler_phpinfo(&$page)
58 {
59 phpinfo();
60 exit;
61 }
62
63 function handler_get_rights(&$page)
64 {
65 if (S::suid()) {
66 $page->kill('Déjà en SUID');
67 }
68 S::assert_xsrf_token();
69 $level = Post::s('account_type');
70 if ($level != 'admin') {
71 $user = User::getSilentWithUID(S::user()->id());
72 $user->is_admin = false;
73 $types = DirEnum::getOptions(DirEnum::ACCOUNTTYPES);
74 if (!empty($types[$level])) {
75 $user->setPerms($types[$level]);
76 }
77 S::set('suid_startpage', $_SERVER['HTTP_REFERER']);
78 Platal::session()->startSUID($user);
79 }
80 if (!empty($_SERVER['HTTP_REFERER'])) {
81 http_redirect($_SERVER['HTTP_REFERER']);
82 } else {
83 pl_redirect('/');
84 }
85 }
86
87 function handler_set_skin(&$page)
88 {
89 S::assert_xsrf_token();
90 S::set('skin', Post::s('change_skin'));
91 if (!empty($_SERVER['HTTP_REFERER'])) {
92 http_redirect($_SERVER['HTTP_REFERER']);
93 } else {
94 pl_redirect('/');
95 }
96 }
97
98 function handler_default(&$page)
99 {
100 $page->changeTpl('admin/index.tpl');
101 $page->setTitle('Administration');
102 }
103
104 function handler_postfix_delayed(&$page)
105 {
106 $page->changeTpl('admin/postfix_delayed.tpl');
107 $page->setTitle('Administration - Postfix : Retardés');
108
109 if (Env::has('del')) {
110 $crc = Env::v('crc');
111 XDB::execute("UPDATE postfix_mailseen SET release = 'del' WHERE crc = {?}", $crc);
112 $page->trigSuccess($crc . " verra tous ses emails supprimés&nbsp;!");
113 } elseif (Env::has('ok')) {
114 $crc = Env::v('crc');
115 XDB::execute("UPDATE postfix_mailseen SET release = 'ok' WHERE crc = {?}", $crc);
116 $page->trigSuccess($crc . " a le droit de passer&nbsp;!");
117 }
118
119 $sql = XDB::iterator(
120 "SELECT crc, nb, update_time, create_time,
121 FIND_IN_SET('del', p.release) AS del,
122 FIND_IN_SET('ok', p.release) AS ok
123 FROM postfix_mailseen AS p
124 WHERE nb >= 30
125 ORDER BY p.release != ''");
126
127 $page->assign_by_ref('mails', $sql);
128 }
129
130 // {{{ logger view
131
132 /** Retrieves the available days for a given year and month.
133 * Obtain a list of days of the given month in the given year
134 * that are within the range of dates that we have log entries for.
135 *
136 * @param integer year
137 * @param integer month
138 * @return array days in that month we have log entries covering.
139 * @private
140 */
141 function _getDays($year, $month)
142 {
143 // give a 'no filter' option
144 $days = array();
145 $days[0] = "----";
146
147 if ($year && $month) {
148 $day_max = Array(-1, 31, checkdate(2, 29, $year) ? 29 : 28 , 31,
149 30, 31, 30, 31, 31, 30, 31, 30, 31);
150 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
151 MONTH(MAX(start)), MONTH(MIN(start)),
152 DAYOFMONTH(MAX(start)),
153 DAYOFMONTH(MIN(start))
154 FROM log_sessions");
155 list($ymax, $ymin, $mmax, $mmin, $dmax, $dmin) = $res->fetchOneRow();
156
157 if (($year < $ymin) || ($year == $ymin && $month < $mmin)) {
158 return array();
159 }
160
161 if (($year > $ymax) || ($year == $ymax && $month > $mmax)) {
162 return array();
163 }
164
165 $min = ($year==$ymin && $month==$mmin) ? intval($dmin) : 1;
166 $max = ($year==$ymax && $month==$mmax) ? intval($dmax) : $day_max[$month];
167
168 for($i = $min; $i<=$max; $i++) {
169 $days[$i] = $i;
170 }
171 }
172 return $days;
173 }
174
175
176 /** Retrieves the available months for a given year.
177 * Obtains a list of month numbers that are within the timeframe that
178 * we have log entries for.
179 *
180 * @param integer year
181 * @return array List of month numbers we have log info for.
182 * @private
183 */
184 function _getMonths($year)
185 {
186 // give a 'no filter' option
187 $months = array();
188 $months[0] = "----";
189
190 if ($year) {
191 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
192 MONTH(MAX(start)), MONTH(MIN(start))
193 FROM log_sessions");
194 list($ymax, $ymin, $mmax, $mmin) = $res->fetchOneRow();
195
196 if (($year < $ymin) || ($year > $ymax)) {
197 return array();
198 }
199
200 $min = $year == $ymin ? intval($mmin) : 1;
201 $max = $year == $ymax ? intval($mmax) : 12;
202
203 for($i = $min; $i<=$max; $i++) {
204 $months[$i] = $i;
205 }
206 }
207 return $months;
208 }
209
210
211 /** Retrieves the available years.
212 * Obtains a list of years that we have log entries covering.
213 *
214 * @return array years we have log entries for.
215 * @private
216 */
217 function _getYears()
218 {
219 // give a 'no filter' option
220 $years = array();
221 $years[0] = "----";
222
223 // retrieve available years
224 $res = XDB::query("select YEAR(MAX(start)), YEAR(MIN(start)) FROM log_sessions");
225 list($max, $min) = $res->fetchOneRow();
226
227 for($i = intval($min); $i<=$max; $i++) {
228 $years[$i] = $i;
229 }
230 return $years;
231 }
232
233
234 /** Make a where clause to get a user's sessions.
235 * Prepare the where clause request that will retrieve the sessions.
236 *
237 * @param $year INTEGER Only get log entries made during the given year.
238 * @param $month INTEGER Only get log entries made during the given month.
239 * @param $day INTEGER Only get log entries made during the given day.
240 * @param $uid INTEGER Only get log entries referring to the given user ID.
241 *
242 * @return STRING the WHERE clause of a query, including the 'WHERE' keyword
243 * @private
244 */
245 function _makeWhere($year, $month, $day, $uid)
246 {
247 // start constructing the "where" clause
248 $where = array();
249
250 if ($uid)
251 array_push($where, "s.uid='$uid'");
252
253 // we were given at least a year
254 if ($year) {
255 if ($day) {
256 $dmin = mktime(0, 0, 0, $month, $day, $year);
257 $dmax = mktime(0, 0, 0, $month, $day+1, $year);
258 } elseif ($month) {
259 $dmin = mktime(0, 0, 0, $month, 1, $year);
260 $dmax = mktime(0, 0, 0, $month+1, 1, $year);
261 } else {
262 $dmin = mktime(0, 0, 0, 1, 1, $year);
263 $dmax = mktime(0, 0, 0, 1, 1, $year+1);
264 }
265 $where[] = "start >= " . date("Ymd000000", $dmin);
266 $where[] = "start < " . date("Ymd000000", $dmax);
267 }
268
269 if (!empty($where)) {
270 return ' WHERE ' . implode($where, " AND ");
271 } else {
272 return '';
273 }
274 // WE know it's totally reversed, so better use array_reverse than a SORT BY start DESC
275 }
276
277 // }}}
278
279 function handler_logger(&$page, $action = null, $arg = null) {
280 if ($action == 'session') {
281
282 // we are viewing a session
283 $res = XDB::query("SELECT ls.*, a.hruid AS username, sa.hruid AS suer
284 FROM log_sessions AS ls
285 INNER JOIN accounts AS a ON (a.uid = ls.uid)
286 LEFT JOIN accounts AS sa ON (sa.uid = ls.suid)
287 WHERE ls.id = {?}", $arg);
288
289 $page->assign('session', $a = $res->fetchOneAssoc());
290
291 $res = XDB::iterator('SELECT a.text, e.data, e.stamp
292 FROM log_events AS e
293 LEFT JOIN log_actions AS a ON e.action=a.id
294 WHERE e.session={?}', $arg);
295 while ($myarr = $res->next()) {
296 $page->append('events', $myarr);
297 }
298
299 } else {
300 $loguser = $action == 'user' ? $arg : Env::v('loguser');
301
302 if ($loguser) {
303 $user = User::get($loguser);
304 $loguid = $user->id();
305 } else {
306 $loguid = null;
307 }
308
309 if ($loguid) {
310 $year = Env::i('year');
311 $month = Env::i('month');
312 $day = Env::i('day');
313 } else {
314 $year = Env::i('year', intval(date('Y')));
315 $month = Env::i('month', intval(date('m')));
316 $day = Env::i('day', intval(date('d')));
317 }
318
319 if (!$year)
320 $month = 0;
321 if (!$month)
322 $day = 0;
323
324 // smarty assignments
325 // retrieve available years
326 $page->assign('years', $this->_getYears());
327 $page->assign('year', $year);
328
329 // retrieve available months for the current year
330 $page->assign('months', $this->_getMonths($year));
331 $page->assign('month', $month);
332
333 // retrieve available days for the current year and month
334 $page->assign('days', $this->_getDays($year, $month));
335 $page->assign('day', $day);
336
337 $page->assign('loguser', $loguser);
338 // smarty assignments
339
340 if ($loguid || $year) {
341
342 // get the requested sessions
343 $where = $this->_makeWhere($year, $month, $day, $loguid);
344 $select = "SELECT s.id, s.start, s.uid,
345 a.hruid as username
346 FROM log_sessions AS s
347 INNER JOIN accounts AS a ON (a.uid = s.uid)
348 $where
349 ORDER BY start DESC";
350 $res = XDB::iterator($select);
351
352 $sessions = array();
353 while ($mysess = $res->next()) {
354 $mysess['events'] = array();
355 $sessions[$mysess['id']] = $mysess;
356 }
357 array_reverse($sessions);
358
359 // attach events
360 $sql = "SELECT s.id, a.text
361 FROM log_sessions AS s
362 LEFT JOIN log_events AS e ON(e.session=s.id)
363 INNER JOIN log_actions AS a ON(a.id=e.action)
364 $where";
365
366 $res = XDB::iterator($sql);
367 while ($event = $res->next()) {
368 array_push($sessions[$event['id']]['events'], $event['text']);
369 }
370 $page->assign_by_ref('sessions', $sessions);
371 } else {
372 $page->assign('msg_nofilters', "Sélectionner une année et/ou un utilisateur");
373 }
374 }
375
376 $page->changeTpl('admin/logger-view.tpl');
377
378 $page->setTitle('Administration - Logs des sessions');
379 }
380
381 function handler_user(&$page, $login = false)
382 {
383 global $globals;
384 $page->changeTpl('admin/user.tpl');
385 $page->setTitle('Administration - Compte');
386
387 if (S::suid()) {
388 $page->kill("Déjà en SUID&nbsp;!!!");
389 }
390
391 // Loads the user identity using the environment.
392 if ($login) {
393 $user = User::get($login);
394 }
395 if (empty($user)) {
396 pl_redirect('admin/accounts');
397 }
398
399 $listClient = new MMList(S::user());
400 $login = $user->login();
401 $registered = ($user->state != 'pending');
402
403 // Form processing
404 if (!empty($_POST)) {
405 S::assert_xsrf_token();
406 if (Post::has('uid') && Post::i('uid') != $user->id()) {
407 $page->kill('Une erreur s\'est produite');
408 }
409 }
410
411 // Handles specific requests (AX sync, su, ...).
412 if(Post::has('log_account')) {
413 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
414 }
415
416 if(Post::has('su_account') && $registered) {
417 if (!Platal::session()->startSUID($user)) {
418 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->login());
419 } else {
420 pl_redirect("");
421 }
422 }
423
424 // Handles account deletion.
425 if (Post::has('account_deletion_confirmation')) {
426 $uid = $user->id();
427 $name = $user->fullName();
428 $profile = $user->profile();
429 if ($profile && Post::b('clear_profile')) {
430 $user->profile()->clear();
431 }
432 $user->clear(true);
433 $page->trigSuccess("L'utilisateur $name ($uid) a bien été désinscrit.");
434 if (Post::b('erase_account')) {
435 XDB::execute('DELETE FROM accounts
436 WHERE uid = {?}',
437 $uid);
438 $page->trigSuccess("L'utilisateur $name ($uid) a été supprimé de la base de données");
439 }
440 }
441
442 // Account Form {{{
443 $to_update = array();
444 if (Post::has('disable_weak_access')) {
445 $to_update['weak_password'] = null;
446 } else if (Post::has('update_account')) {
447 if (!$user->hasProfile()) {
448 if (Post::s('full_name') != $user->fullName()) {
449 $to_update['full_name'] = Post::s('full_name');
450 }
451 if (Post::s('display_name') != $user->displayName()) {
452 $to_update['display_name'] = Post::s('display_name');
453 }
454 if (Post::s('directory_name') != $user->directoryName()) {
455 $to_update['directory_name'] = Post::s('directory_name');
456 }
457 }
458 if (Post::s('sex') != ($user->isFemale() ? 'female' : 'male')) {
459 $to_update['sex'] = Post::s('sex');
460 if ($user->hasProfile()) {
461 XDB::execute('UPDATE profiles
462 SET sex = {?}
463 WHERE pid = {?}',
464 Post::s('sex'), $user->profile()->id());
465 }
466 }
467 if (!Post::blank('pwhash')) {
468 $to_update['password'] = Post::s('pwhash');
469 require_once 'googleapps.inc.php';
470 $account = new GoogleAppsAccount($user);
471 if ($account->active() && $account->sync_password) {
472 $account->set_password(Post::s('pwhash'));
473 }
474 }
475 if (!Post::blank('weak_password')) {
476 $to_update['weak_password'] = Post::s('weak_password');
477 }
478 if (Post::i('token_access', 0) != ($user->token_access ? 1 : 0)) {
479 $to_update['token'] = Post::i('token_access') ? rand_url_id(16) : null;
480 }
481 if (Post::i('skin') != $user->skin) {
482 $to_update['skin'] = Post::i('skin');
483 if ($to_update['skin'] == 0) {
484 $to_update['skin'] = null;
485 }
486 }
487 if (Post::s('state') != $user->state) {
488 $to_update['state'] = Post::s('state');
489 }
490 if (Post::i('is_admin', 0) != ($user->is_admin ? 1 : 0)) {
491 $to_update['is_admin'] = Post::b('is_admin');
492 }
493 if (Post::s('type') != $user->type) {
494 $to_update['type'] = Post::s('type');
495 }
496 if (Post::i('watch', 0) != ($user->watch ? 1 : 0)) {
497 $to_update['flags'] = new PlFlagset();
498 $to_update['flags']->addFlag('watch', Post::i('watch'));
499 }
500 if (Post::t('comment') != $user->comment) {
501 $to_update['comment'] = Post::blank('comment') ? null : Post::t('comment');
502 }
503 if (!$user->checkPerms(User::PERM_MAIL) && Post::t('email') != $user->forlifeEmail()) {
504 $to_update['email'] = Post::t('email');
505 $listClient->change_user_email($user->forlifeEmail(), Post::t('email'));
506 }
507 }
508 if (!empty($to_update)) {
509 $res = XDB::query('SELECT *
510 FROM accounts
511 WHERE uid = {?}', $user->id());
512 $oldValues = $res->fetchAllAssoc();
513 $oldValues = $oldValues[0];
514
515 $set = array();
516 $diff = array();
517 foreach ($to_update as $k => $value) {
518 $value = XDB::format('{?}', $value);
519 $set[] = $k . ' = ' . $value;
520 $diff[$k] = array($oldValues[$k], trim($value, "'"));
521 unset($oldValues[$k]);
522 }
523 XDB::rawExecute('UPDATE accounts
524 SET ' . implode(', ', $set) . '
525 WHERE uid = ' . XDB::format('{?}', $user->id()));
526 $page->trigSuccess('Données du compte mise à jour avec succès');
527 $user = User::getWithUID($user->id());
528
529 /* Formats the $diff and send it to the site administrators. The rules are the folowing:
530 * -formats: password, token, weak_password
531 */
532 foreach (array('password', 'token', 'weak_password') as $key) {
533 if (isset($diff[$key])) {
534 $diff[$key] = array('old value', 'new value');
535 } else {
536 $oldValues[$key] = 'old value';
537 }
538 }
539
540 $mail = new PlMailer('admin/useredit.mail.tpl');
541 $mail->assign('admin', S::user()->hruid);
542 $mail->assign('hruid', $user->hruid);
543 $mail->assign('diff', $diff);
544 $mail->assign('oldValues', $oldValues);
545 $mail->send();
546 }
547 // }}}
548
549 // Profile form {{{
550 if (Post::has('add_profile') || Post::has('del_profile') || Post::has('owner')) {
551 if (Post::i('del_profile', 0) != 0) {
552 XDB::execute('DELETE FROM account_profiles
553 WHERE uid = {?} AND pid = {?}',
554 $user->id(), Post::i('del_profile'));
555 } else if (!Post::blank('new_profile')) {
556 $profile = Profile::get(Post::t('new_profile'));
557 if (!$profile) {
558 $page->trigError('Le profil ' . Post::t('new_profile') . ' n\'existe pas');
559 } else {
560 XDB::execute('INSERT IGNORE INTO account_profiles (uid, pid)
561 VALUES ({?}, {?})',
562 $user->id(), $profile->id());
563 }
564 }
565 XDB::execute('UPDATE account_profiles
566 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
567 WHERE uid = {?}',
568 Post::i('owner'), $user->id());
569 }
570 // }}}
571
572 // Email forwards form {{{
573 require_once("emails.inc.php");
574 $redirect = ($registered ? new Redirect($user) : null);
575 if (Post::has('add_fwd')) {
576 $email = Post::t('email');
577 if (!isvalid_email_redirection($email)) {
578 $page->trigError("Email non valide: $email");
579 } else {
580 $redirect->add_email($email);
581 $page->trigSuccess("Ajout de $email effectué");
582 }
583 } else if (!Post::blank('del_fwd')) {
584 $redirect->delete_email(Post::t('del_fwd'));
585 } else if (!Post::blank('activate_fwd')) {
586 $redirect->modify_one_email(Post::t('activate_fwd', true));
587 } else if (!Post::blank('deactivate_fwd')) {
588 $redirect->modify_one_email(Post::t('deactivate_fwd', false));
589 } else if (Post::has('disable_fwd')) {
590 $redirect->disable();
591 } else if (Post::has('enable_fwd')) {
592 $redirect->enable();
593 } else if (!Post::blank('clean_fwd')) {
594 $redirect->clean_errors(Post::t('clean_fwd'));
595 }
596 // }}}
597
598 // Email alias form {{{
599 if (Post::has('add_alias')) {
600 // Splits new alias in user and fqdn.
601 $alias = Env::t('email');
602 if (strpos($alias, '@') !== false) {
603 list($alias, $domain) = explode('@', $alias);
604 } else {
605 $domain = $globals->mail->domain;
606 }
607
608 // Checks for alias' user validity.
609 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
610 $page->trigError("'$alias' n'est pas un alias valide");
611 }
612
613 // Eventually adds the alias to the right domain.
614 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
615 $req = new AliasReq($user, $alias, 'Admin request', false);
616 if ($req->commit()) {
617 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué");
618 } else {
619 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué");
620 }
621 } elseif ($domain == $globals->mail->domain || $domain == $globals->mail->domain2) {
622 $res = XDB::execute("INSERT INTO aliases (uid, alias, type)
623 VALUES ({?}, {?}, 'alias')",
624 $user->id(), $alias);
625 $page->trigSuccess("Nouvel alias '$alias' ajouté");
626 } else {
627 $page->trigError("Le domaine '$domain' n'est pas valide");
628 }
629 } else if (!Post::blank('del_alias')) {
630 XDB::execute("DELETE FROM aliases
631 WHERE uid = {?} AND alias = {?} AND
632 type NOT IN ('a_vie', 'homonyme')",
633 $user->id(), $val);
634 XDB::execute("UPDATE emails
635 SET rewrite = ''
636 WHERE uid = {?} AND rewrite LIKE CONCAT({?}, '@%')",
637 $user->id(), $val);
638 fix_bestalias($user);
639 $page->trigSuccess("L'alias '$val' a été supprimé");
640 } else if (!Post::blank('best')) {
641 XDB::execute("UPDATE aliases
642 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
643 WHERE uid = {?}", $user->id());
644 XDB::execute("UPDATE aliases
645 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
646 WHERE uid = {?} AND alias = {?}", $user->id(), $val);
647 // As having a non-null bestalias value is critical in
648 // plat/al's code, we do an a posteriori check on the
649 // validity of the bestalias.
650 fix_bestalias($user);
651 }
652 // }}}
653
654 // OpenId form {{{
655 if (Post::has('del_openid')) {
656 XDB::execute('DELETE FROM account_auth_openid
657 WHERE id = {?}', Post::i('del_openid'));
658 }
659 // }}}
660
661 // Forum form {{{
662 if (Post::has('b_edit')) {
663 XDB::execute("DELETE FROM forum_innd
664 WHERE uid = {?}", $user->id());
665 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
666 XDB::execute("INSERT INTO forum_innd
667 SET ipmin = '0', ipmax = '4294967295',
668 write_perm = {?}, read_perm = {?},
669 comment = {?}, priority = '200', uid = {?}",
670 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
671 }
672 }
673 // }}}
674
675
676 $page->addJsLink('jquery.ui.core.js');
677 $page->addJsLink('jquery.ui.widget.js');
678 $page->addJsLink('jquery.ui.tabs.js');
679 $page->addJsLink('password.js');
680
681 // Displays last login and last host information.
682 $res = XDB::query("SELECT start, host
683 FROM log_sessions
684 WHERE uid = {?} AND suid = 0
685 ORDER BY start DESC
686 LIMIT 1", $user->id());
687 list($lastlogin,$host) = $res->fetchOneRow();
688 $page->assign('lastlogin', $lastlogin);
689 $page->assign('host', $host);
690
691 // Display mailing lists
692 $page->assign('mlists', $listClient->get_all_user_lists($user->forlifeEmail()));
693
694 // Display active aliases.
695 $page->assign('virtuals', $user->emailAliases());
696 $page->assign('aliases', XDB::iterator("SELECT alias, type='a_vie' AS for_life,
697 FIND_IN_SET('bestalias',flags) AS best, expire
698 FROM aliases
699 WHERE uid = {?} AND type != 'homonyme'
700 ORDER BY type != 'a_vie'", $user->id()));
701 $page->assign('account_types', XDB::iterator('SELECT * FROM account_types ORDER BY type'));
702 $page->assign('skins', XDB::iterator('SELECT id, name FROM skins ORDER BY name'));
703 $page->assign('profiles', XDB::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
704 FROM account_profiles AS ap
705 INNER JOIN profiles AS p ON (ap.pid = p.pid)
706 WHERE ap.uid = {?}', $user->id()));
707 $page->assign('openid', XDB::iterator('SELECT id, url
708 FROM account_auth_openid
709 WHERE uid = {?}', $user->id()));
710
711 // Displays email redirection and the general profile.
712 if ($registered && $redirect) {
713 $page->assign('emails', $redirect->emails);
714 }
715
716 $page->assign('user', $user);
717 $page->assign('hasProfile', $user->hasProfile());
718
719 // Displays forum bans.
720 $res = XDB::query("SELECT write_perm, read_perm, comment
721 FROM forum_innd
722 WHERE uid = {?}", $user->id());
723 $bans = $res->fetchOneAssoc();
724 $page->assign('bans', $bans);
725 }
726
727 private static function getHrid($firstname, $lastname, $promo)
728 {
729 if ($firstname != null && $lastname != null && $promo != null) {
730 return User::makeHrid($firstname, $lastname, $promo);
731 }
732 return null;
733 }
734
735 private static function formatNewUser(&$page, $infosLine, $separator, $promo, $size)
736 {
737 $infos = explode($separator, $infosLine);
738 if (sizeof($infos) > $size || sizeof($infos) < 2) {
739 $page->trigError("La ligne $infosLine n'a pas été ajoutée.");
740 return false;
741 }
742
743 $infos = array_map('trim', $infos);
744 $hrid = self::getHrid($infos[1], $infos[0], $promo);
745 $res1 = XDB::query('SELECT COUNT(*)
746 FROM accounts
747 WHERE hruid = {?}', $hrid);
748 $res2 = XDB::query('SELECT COUNT(*)
749 FROM profiles
750 WHERE hrpid = {?}', $hrid);
751 if (is_null($hrid) || $res1->fetchOneCell() > 0 || $res2->fetchOneCell() > 0) {
752 $page->trigError("La ligne $infosLine n'a pas été ajoutée: une entrée similaire existe déjà");
753 return false;
754 }
755 $infos['hrid'] = $hrid;
756 return $infos;
757 }
758
759 private static function formatSex(&$page, $sex, $line)
760 {
761 switch ($sex) {
762 case 'F':
763 return PlUser::GENDER_FEMALE;
764 case 'M':
765 return PlUser::GENDER_MALE;
766 default:
767 $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
768 return null;
769 }
770 }
771
772 private static function formatBirthDate($birthDate)
773 {
774 // strtotime believes dd/mm/yyyy to be an US date (i.e mm/dd/yyyy), and
775 // dd-mm-yyyy to be a normal date (i.e dd-mm-yyyy)...
776 return date("Y-m-d", strtotime(str_replace('/', '-', $birthDate)));
777 }
778
779 function handler_add_accounts(&$page, $action = null, $promo = null)
780 {
781 $page->changeTpl('admin/add_accounts.tpl');
782
783 if (Env::has('add_type') && Env::has('people')) {
784 $lines = explode("\n", Env::t('people'));
785 $separator = Env::t('separator');
786 $promotion = Env::i('promotion');
787 $nameTypes = DirEnum::getOptions(DirEnum::NAMETYPES);
788 $nameTypes = array_flip($nameTypes);
789
790 if (Env::t('add_type') == 'promo') {
791 $type = 'x';
792 $eduSchools = DirEnum::getOptions(DirEnum::EDUSCHOOLS);
793 $eduSchools = array_flip($eduSchools);
794 $eduDegrees = DirEnum::getOptions(DirEnum::EDUDEGREES);
795 $eduDegrees = array_flip($eduDegrees);
796 switch (Env::t('edu_type')) {
797 case 'X':
798 $degreeid = $eduDegrees[Profile::DEGREE_X];
799 $entry_year = $promotion;
800 $grad_year = $promotion + 3;
801 $promo = 'X' . $promotion;
802 $hrpromo = $promotion;
803 break;
804 case 'M':
805 $degreeid = $eduDegrees[Profile::DEGREE_M];
806 $grad_year = $promotion;
807 $entry_year = $promotion - 2;
808 $promo = 'M' . $promotion;
809 $hrpromo = $promo;
810 $type = 'master';
811 break;
812 case 'D':
813 $degreeid = $eduDegrees[Profile::DEGREE_D];
814 $grad_year = $promotion;
815 $entry_year = $promotion - 3;
816 $promo = 'D' . $promotion;
817 $hrpromo = $promo;
818 $type = 'phd';
819 break;
820 default:
821 $page->killError("La formation n'est pas reconnue:" . Env::t('edu_type') . '.');
822 }
823
824 XDB::startTransaction();
825 foreach ($lines as $line) {
826 if ($infos = self::formatNewUser($page, $line, $separator, $hrpromo, 6)) {
827 $sex = self::formatSex($page, $infos[3], $line);
828 if (!is_null($sex)) {
829 $fullName = $infos[1] . ' ' . $infos[0];
830 $directoryName = $infos[0] . ' ' . $infos[1];
831 $birthDate = self::formatBirthDate($infos[2]);
832 $xorgId = Profile::getXorgId($infos[4]);
833 if (is_null($xorgId)) {
834 $page->trigError("La ligne $line n'a pas été ajoutée car le matricule École est mal renseigné.");
835 continue;
836 }
837
838 XDB::execute('INSERT INTO profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex)
839 VALUES ({?}, {?}, {?}, {?}, {?})',
840 $infos['hrid'], $xorgId, $infos[5], $birthDate, $sex);
841 $pid = XDB::insertId();
842 XDB::execute('INSERT INTO profile_name (pid, name, typeid)
843 VALUES ({?}, {?}, {?}),
844 ({?}, {?}, {?}),
845 ({?}, {?}, {?}),
846 ({?}, {?}, {?})',
847 $pid, $infos[0], $nameTypes['name_ini'],
848 $pid, $infos[0], $nameTypes['lastname'],
849 $pid, $infos[1], $nameTypes['firstname_ini'],
850 $pid, $infos[1], $nameTypes['firstname']);
851 XDB::execute('INSERT INTO profile_display (pid, yourself, public_name, private_name,
852 directory_name, short_name, sort_name, promo)
853 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
854 $pid, $infos[1], $fullName, $fullName, $directoryName, $fullName, $directoryName, $promo);
855 XDB::execute('INSERT INTO profile_education (pid, eduid, degreeid, entry_year, grad_year, flags)
856 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
857 $pid, $eduSchools[Profile::EDU_X], $degreeid, $entry_year, $grad_year, 'primary');
858 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, full_name, directory_name, display_name, sex)
859 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
860 $infos['hrid'], $type, 0, 'pending', $fullName, $directoryName, $infos[1], $sex);
861 $uid = XDB::insertId();
862 XDB::execute('INSERT INTO account_profiles (uid, pid, perms)
863 VALUES ({?}, {?}, {?})',
864 $uid, $pid, 'owner');
865 Profile::rebuildSearchTokens($pid, false);
866 }
867 }
868 }
869 XDB::commit();
870 } else if (Env::t('add_type') == 'account') {
871 $type = Env::t('type');
872 $newAccounts = array();
873 foreach ($lines as $line) {
874 if ($infos = self::formatNewUser($page, $line, $separator, $type, 4)) {
875 $sex = self::formatSex($page, $infos[3], $line);
876 if (!is_null($sex)) {
877 $fullName = $infos[1] . ' ' . $infos[0];
878 $directoryName = $infos[0] . ' ' . $infos[1];
879 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state,
880 email, full_name, directory_name,
881 display_name, sex)
882 VALUES ({?}, {?}, {?}, {?},
883 {?}, {?}, {?}, {?}, {?})',
884 $infos['hrid'], $type, 0, 'pending',
885 $infos[2], $fullName, $directoryName,
886 $infos[1], $sex);
887 $newAccounts[$infos['hrid']] = $infos[1] . ' ' . $infos[0];
888 }
889 }
890 }
891 if (!empty($newAccounts)) {
892 $page->assign('newAccounts', $newAccounts);
893 }
894 } else if (Env::t('add_type') == 'ax_id') {
895 $type = 'x';
896 foreach ($lines as $line) {
897 if ($infos = self::formatNewUser($page, $line, $separator, $promotion, 3)) {
898 XDB::execute('UPDATE profiles
899 SET ax_id = {?}
900 WHERE hrpid = {?}',
901 $infos[2], $infos['hrid']);
902 }
903 }
904 }
905
906 $errors = $page->nb_errs();
907 if ($errors == 0) {
908 $page->trigSuccess("L'opération a été effectuée avec succès.");
909 } else {
910 $page->trigSuccess('L\'opération a été effectuée avec succès, sauf pour '
911 . (($errors == 1) ? 'l\'erreur signalée' : "les $errors erreurs signalées") . ' ci-dessus.');
912 }
913 } else if (Env::has('add_type')) {
914 $res = XDB::query('SELECT type
915 FROM account_types');
916 $page->assign('account_types', $res->fetchColumn());
917 $page->assign('add_type', Env::s('add_type'));
918 }
919 }
920
921 function handler_homonyms(&$page, $op = 'list', $target = null)
922 {
923 $page->changeTpl('admin/homonymes.tpl');
924 $page->setTitle('Administration - Homonymes');
925 $this->load("homonyms.inc.php");
926
927 if ($target) {
928 $user = User::getSilent($target);
929 if (!$user || !($loginbis = select_if_homonyme($user))) {
930 $target = 0;
931 } else {
932 $page->assign('user', $user);
933 $page->assign('loginbis',$loginbis);
934 }
935 }
936
937 $page->assign('op', $op);
938 $page->assign('target', $target);
939
940 // on a un $target valide, on prepare les mails
941 if ($target) {
942 // on examine l'op a effectuer
943 switch ($op) {
944 case 'mail':
945 S::assert_xsrf_token();
946
947 send_warning_homonyme($user, $loginbis);
948 switch_bestalias($user, $loginbis);
949 $op = 'list';
950 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
951 break;
952
953 case 'correct':
954 S::assert_xsrf_token();
955
956 switch_bestalias($user, $loginbis);
957 XDB::execute("UPDATE aliases
958 SET type = 'homonyme', expire=NOW()
959 WHERE alias = {?}", $loginbis);
960 XDB::execute('INSERT IGNORE INTO homonyms (homonyme_id, uid)
961 VALUES ({?}, {?})', $target, $target);
962 send_robot_homonyme($user, $loginbis);
963 $op = 'list';
964 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
965 break;
966 }
967 }
968
969 if ($op == 'list') {
970 $res = XDB::iterator(
971 "SELECT a.alias AS homonyme, s.alias AS forlife,
972 IF(h.homonyme_id = s.uid, a.expire, NULL) AS expire,
973 IF(h.homonyme_id = s.uid, a.type, NULL) AS type, ac.uid
974 FROM aliases AS a
975 LEFT JOIN homonyms AS h ON (h.homonyme_id = a.uid)
976 INNER JOIN aliases AS s ON (s.uid = h.uid AND s.type = 'a_vie')
977 INNER JOIN accounts AS ac ON (ac.uid = a.uid)
978 WHERE a.type = 'homonyme' OR a.expire != ''
979 ORDER BY a.alias, forlife");
980 $hnymes = Array();
981 while ($tab = $res->next()) {
982 $hnymes[$tab['homonyme']][] = $tab;
983 }
984 $page->assign_by_ref('hnymes', $hnymes);
985 }
986 }
987
988 function handler_deaths(&$page, $promo = 0, $validate = false)
989 {
990 $page->changeTpl('admin/deces_promo.tpl');
991 $page->setTitle('Administration - Deces');
992
993 if (!$promo) {
994 $promo = Env::t('promo', 'X1923');
995 }
996 $page->assign('promo', $promo);
997 if (!$promo) {
998 return;
999 }
1000
1001 if ($validate) {
1002 S::assert_xsrf_token();
1003
1004 $res = XDB::iterRow('SELECT p.pid, pd.directory_name, p.deathdate
1005 FROM profiles AS p
1006 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1007 WHERE pd.promo = {?}', $promo);
1008 while (list($pid, $name, $death) = $res->next()) {
1009 $val = Env::v('death_' . $pid);
1010 if ($val == $death) {
1011 continue;
1012 }
1013
1014 if (empty($val)) {
1015 $val = null;
1016 }
1017 XDB::execute('UPDATE profiles
1018 SET deathdate = {?}, deathdate_rec = NOW()
1019 WHERE pid = {?}', $val, $pid);
1020
1021 $page->trigSuccess('Édition du décès de ' . $name . ' (' . ($val ? $val : 'ressuscité') . ').');
1022 if ($val && ($death == '0000-00-00' || empty($death))) {
1023 $profile = Profile::get($pid);
1024 $profile->clear();
1025 $profile->owner()->clear(false);
1026 }
1027 }
1028 }
1029
1030 $res = XDB::iterator('SELECT p.pid, pd.directory_name, p.deathdate
1031 FROM profiles AS p
1032 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1033 WHERE pd.promo = {?}
1034 ORDER BY pd.sort_name', $promo);
1035 $page->assign('profileList', $res);
1036 }
1037
1038 function handler_dead_but_active(&$page)
1039 {
1040 $page->changeTpl('admin/dead_but_active.tpl');
1041 $page->setTitle('Administration - Décédés');
1042
1043 $res = XDB::iterator(
1044 "SELECT a.hruid, pd.promo, p.ax_id, pd.directory_name, p.deathdate, DATE(MAX(s.start)) AS last
1045 FROM accounts AS a
1046 INNER JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET('owner', ap.perms))
1047 INNER JOIN profiles AS p ON (p.pid = ap.pid)
1048 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
1049 LEFT JOIN log_sessions AS s ON (s.uid = a.uid AND suid = 0)
1050 WHERE a.state = 'active' AND p.deathdate IS NOT NULL
1051 GROUP BY a.uid
1052 ORDER BY pd.promo, pd.sort_name");
1053 $page->assign('dead', $res);
1054 }
1055
1056 function handler_validate(&$page, $action = 'list', $id = null)
1057 {
1058 $page->changeTpl('admin/validation.tpl');
1059 $page->setTitle('Administration - Valider une demande');
1060 $page->addCssLink('nl.css');
1061
1062 if ($action == 'edit' && !is_null($id)) {
1063 $page->assign('preview_id', $id);
1064 } else {
1065 $page->assign('preview_id', null);
1066 }
1067
1068 if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
1069 S::assert_xsrf_token();
1070
1071 $req = Validate::get_typed_request(Env::v('uid'), Env::v('type'), Env::v('stamp'));
1072 if ($req) {
1073 $req->handle_formu();
1074 } else {
1075 $page->trigWarning('La validation a déjà été effectuée.');
1076 }
1077 }
1078
1079 $r = XDB::iterator('SHOW COLUMNS FROM requests_answers');
1080 while (($a = $r->next()) && $a['Field'] != 'category');
1081 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
1082
1083 $hidden = array();
1084 $res = XDB::query('SELECT hidden_requests
1085 FROM requests_hidden
1086 WHERE uid = {?}', S::v('uid'));
1087 $hide_requests = $res->fetchOneCell();
1088 if (Post::has('hide')) {
1089 $hide = array();
1090 foreach ($categories as $cat)
1091 if (!Post::v($cat)) {
1092 $hidden[$cat] = 1;
1093 $hide[] = $cat;
1094 }
1095 $hide_requests = join(',', $hide);
1096 XDB::query('INSERT INTO requests_hidden (uid, hidden_requests)
1097 VALUES ({?}, {?})
1098 ON DUPLICATE KEY UPDATE hidden_requests = VALUES(hidden_requests)',
1099 S::v('uid'), $hide_requests);
1100 } elseif ($hide_requests) {
1101 foreach (explode(',', $hide_requests) as $hide_type)
1102 $hidden[$hide_type] = true;
1103 }
1104 $page->assign('hide_requests', $hidden);
1105
1106 // Update the count of item to validate here... useful in development configuration
1107 // where several copies of the site use the same DB, but not the same "dynamic configuration"
1108 global $globals;
1109 $globals->updateNbValid();
1110 $page->assign('vit', Validate::iterate());
1111 }
1112
1113 function handler_validate_answers(&$page, $action = 'list', $id = null)
1114 {
1115 $page->setTitle('Administration - Réponses automatiques de validation');
1116 $page->assign('title', 'Gestion des réponses automatiques');
1117 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
1118 $table_editor->describe('category','catégorie',true);
1119 $table_editor->describe('title','titre',true);
1120 $table_editor->describe('answer','texte',false);
1121 $table_editor->apply($page, $action, $id);
1122 }
1123
1124 function handler_skins(&$page, $action = 'list', $id = null)
1125 {
1126 $page->setTitle('Administration - Skins');
1127 $page->assign('title', 'Gestion des skins');
1128 $table_editor = new PLTableEditor('admin/skins','skins','id');
1129 $table_editor->describe('name','nom',true);
1130 $table_editor->describe('skin_tpl','nom du template',true);
1131 $table_editor->describe('auteur','auteur',false);
1132 $table_editor->describe('comment','commentaire',true);
1133 $table_editor->describe('date','date',false);
1134 $table_editor->describe('ext','extension du screenshot',false);
1135 $table_editor->apply($page, $action, $id);
1136 }
1137
1138 function handler_postfix_blacklist(&$page, $action = 'list', $id = null)
1139 {
1140 $page->setTitle('Administration - Postfix : Blacklist');
1141 $page->assign('title', 'Blacklist de postfix');
1142 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true);
1143 $table_editor->describe('reject_text','Texte de rejet',true);
1144 $table_editor->describe('email','email',true);
1145 $table_editor->apply($page, $action, $id);
1146 }
1147
1148 function handler_postfix_whitelist(&$page, $action = 'list', $id = null)
1149 {
1150 $page->setTitle('Administration - Postfix : Whitelist');
1151 $page->assign('title', 'Whitelist de postfix');
1152 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true);
1153 $table_editor->describe('email','email',true);
1154 $table_editor->apply($page, $action, $id);
1155 }
1156
1157 function handler_mx_broken(&$page, $action = 'list', $id = null)
1158 {
1159 $page->setTitle('Administration - MX Défaillants');
1160 $page->assign('title', 'MX Défaillant');
1161 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true);
1162 $table_editor->describe('host', 'Masque', true);
1163 $table_editor->describe('state', 'Niveau', true);
1164 $table_editor->describe('text', 'Description du problème', false);
1165 $table_editor->apply($page, $action, $id);
1166 }
1167
1168 function handler_logger_actions(&$page, $action = 'list', $id = null)
1169 {
1170 $page->setTitle('Administration - Actions');
1171 $page->assign('title', 'Gestion des actions de logger');
1172 $table_editor = new PLTableEditor('admin/logger/actions','log_actions','id');
1173 $table_editor->describe('text','intitulé',true);
1174 $table_editor->describe('description','description',true);
1175 $table_editor->apply($page, $action, $id);
1176 }
1177
1178 function handler_downtime(&$page, $action = 'list', $id = null)
1179 {
1180 $page->setTitle('Administration - Coupures');
1181 $page->assign('title', 'Gestion des coupures');
1182 $table_editor = new PLTableEditor('admin/downtime','downtimes','id');
1183 $table_editor->describe('debut','date',true);
1184 $table_editor->describe('duree','durée',false);
1185 $table_editor->describe('resume','résumé',true);
1186 $table_editor->describe('services','services affectés',true);
1187 $table_editor->describe('description','description',false);
1188 $table_editor->apply($page, $action, $id);
1189 }
1190
1191 function handler_accounts(PlPage $page)
1192 {
1193 $page->changeTpl('admin/accounts.tpl');
1194 $page->setTitle('Administration - Comptes');
1195 $page->addJsLink('password.js');
1196
1197 if (Post::has('create_account')) {
1198 S::assert_xsrf_token();
1199 $firstname = Post::t('firstname');
1200 $lastname = strtoupper(Post::t('lastname'));
1201 $sex = Post::s('sex');
1202 $email = Post::t('email');
1203 $type = Post::s('type');
1204 $login = PlUser::makeHrid($firstname, $lastname, $type);
1205 if (!isvalid_email($email)) {
1206 $page->trigError("Invalid email address: $email");
1207 } else if (strlen(Post::s('pwhash')) != 40) {
1208 $page->trigError("Invalid password hash");
1209 } else {
1210 $full_name = $firstname . ' ' . $lastname;
1211 $directory_name = $lastname . ' ' . $firstname;
1212 XDB::execute("INSERT INTO accounts (hruid, type, state, password,
1213 registration_date, email, full_name,
1214 display_name, sex, directory_name)
1215 VALUES ({?}, {?}, 'active', {?}, NOW(), {?}, {?}, {?}, {?}, {?})",
1216 $login, $type, Post::s('pwhash'), $email, $full_name, $full_name, $sex,
1217 $directory_name);
1218 }
1219 }
1220
1221 $uf = new UserFilter(new UFC_AccountType('ax', 'school', 'fx'));
1222 $page->assign('users', $uf->iterUsers());
1223
1224 }
1225
1226 function handler_account_types(&$page, $action = 'list', $id = null)
1227 {
1228 $page->setTitle('Administration - Types de comptes');
1229 $page->assign('title', 'Gestion des types de comptes');
1230 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true);
1231 $table_editor->describe('type', 'Catégorie', true);
1232 $table_editor->describe('perms', 'Permissions associées', true);
1233 $table_editor->apply($page, $action, $id);
1234 }
1235
1236 function handler_wiki(&$page, $action = 'list', $wikipage = null, $wikipage2 = null)
1237 {
1238 if (S::hasAuthToken()) {
1239 $page->setRssLink('Changement Récents',
1240 '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::user()->token);
1241 }
1242
1243 // update wiki perms
1244 if ($action == 'update') {
1245 S::assert_xsrf_token();
1246
1247 $perms_read = Post::v('read');
1248 $perms_edit = Post::v('edit');
1249 if ($perms_read || $perms_edit) {
1250 foreach ($_POST as $wiki_page => $val) {
1251 if ($val == 'on') {
1252 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1253 if ($wp->setPerms($perms_read ? $perms_read : $wp->readPerms(),
1254 $perms_edit ? $perms_edit : $wp->writePerms())) {
1255 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1256 } else {
1257 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1258 }
1259 }
1260 }
1261 }
1262 } else if ($action != 'list' && !empty($wikipage)) {
1263 $wp = new PlWikiPage($wikipage);
1264 S::assert_xsrf_token();
1265
1266 if ($action == 'delete') {
1267 if ($wp->delete()) {
1268 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1269 } else {
1270 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1271 }
1272 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1273 if ($changedLinks = $wp->rename($wikipage2)) {
1274 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1275 if (is_numeric($changedLinks)) {
1276 $s .= $changedLinks.' lien'.(($changedLinks>1)?'s ont été modifiés.':' a été modifié.');
1277 }
1278 $page->trigSuccess($s);
1279 } else {
1280 $page->trigError("Impossible de déplacer la page ".$wikipage);
1281 }
1282 }
1283 }
1284
1285 $perms = PlWikiPage::permOptions();
1286
1287 // list wiki pages and their perms
1288 $wiki_pages = PlWikiPage::listPages();
1289 ksort($wiki_pages);
1290 $wiki_tree = array();
1291 foreach ($wiki_pages as $file => $desc) {
1292 list($cat, $name) = explode('.', $file);
1293 if (!isset($wiki_tree[$cat])) {
1294 $wiki_tree[$cat] = array();
1295 }
1296 $wiki_tree[$cat][$name] = $desc;
1297 }
1298
1299 $page->changeTpl('admin/wiki.tpl');
1300 $page->assign('wiki_pages', $wiki_tree);
1301 $page->assign('perms_opts', $perms);
1302 }
1303
1304 function handler_ipwatch(&$page, $action = 'list', $ip = null)
1305 {
1306 $page->changeTpl('admin/ipwatcher.tpl');
1307
1308 $states = array('safe' => 'Ne pas surveiller',
1309 'unsafe' => 'Surveiller les inscriptions',
1310 'dangerous' => 'Surveiller tous les accès',
1311 'ban' => 'Bannir cette adresse');
1312 $page->assign('states', $states);
1313
1314 switch (Post::v('action')) {
1315 case 'create':
1316 if (trim(Post::v('ipN')) != '') {
1317 S::assert_xsrf_token();
1318 Xdb::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1319 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1320 ip_to_uint(trim(Post::v('ipN'))), ip_to_uint(trim(Post::v('maskN'))),
1321 Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
1322 };
1323 break;
1324
1325 case 'edit':
1326 S::assert_xsrf_token();
1327 Xdb::execute('UPDATE ip_watch
1328 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1329 WHERE ip = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'),
1330 ip_to_uint(Post::v('maskN')), ip_to_uint(Post::v('ipN')));
1331 break;
1332
1333 default:
1334 if ($action == 'delete' && !is_null($ip)) {
1335 S::assert_xsrf_token();
1336 Xdb::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1337 }
1338 }
1339 if ($action != 'create' && $action != 'edit') {
1340 $action = 'list';
1341 }
1342 $page->assign('action', $action);
1343
1344 if ($action == 'list') {
1345 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1346 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1347 IF(w.ip = s.ip, s.host, s.forward_host)),
1348 w.mask, w.detection, w.state, a.hruid
1349 FROM ip_watch AS w
1350 LEFT JOIN log_sessions AS s ON (s.ip = w.ip)
1351 LEFT JOIN log_sessions AS s2 ON (s2.forward_ip = w.ip)
1352 LEFT JOIN accounts AS a ON (a.uid = s.uid)
1353 GROUP BY w.ip, a.hruid
1354 ORDER BY w.state, w.ip, a.hruid";
1355 $it = Xdb::iterRow($sql);
1356
1357 $table = array();
1358 $props = array();
1359 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1360 $ip = uint_to_ip($ip);
1361 $mask = uint_to_ip($mask);
1362 if (count($props) == 0 || $props['ip'] != $ip) {
1363 if (count($props) > 0) {
1364 $table[] = $props;
1365 }
1366 $props = array('ip' => $ip,
1367 'mask' => $mask,
1368 'host' => $host,
1369 'detection' => $date,
1370 'state' => $state,
1371 'users' => array($hruid));
1372 } else {
1373 $props['users'][] = $hruid;
1374 }
1375 }
1376 if (count($props) > 0) {
1377 $table[] = $props;
1378 }
1379 $page->assign('table', $table);
1380 } elseif ($action == 'edit') {
1381 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1382 a1.hruid AS edit, a2.hruid AS hruid, s.host
1383 FROM ip_watch AS w
1384 LEFT JOIN accounts AS a1 ON (a1.uid = w.uid)
1385 LEFT JOIN log_sessions AS s ON (w.ip = s.ip)
1386 LEFT JOIN accounts AS a2 ON (a2.uid = s.uid)
1387 WHERE w.ip = {?}
1388 GROUP BY a2.hruid
1389 ORDER BY a2.hruid";
1390 $it = Xdb::iterRow($sql, ip_to_uint($ip));
1391
1392 $props = array();
1393 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1394 if (count($props) == 0) {
1395 $props = array('ip' => $ip,
1396 'mask' => uint_to_ip($mask),
1397 'host' => $host,
1398 'detection' => $detection,
1399 'state' => $state,
1400 'last' => $last,
1401 'description' => $description,
1402 'edit' => $edit,
1403 'users' => array($hruid));
1404 } else {
1405 $props['users'][] = $hruid;
1406 }
1407 }
1408 $page->assign('ip', $props);
1409 }
1410 }
1411
1412 function handler_icons(&$page)
1413 {
1414 $page->changeTpl('admin/icons.tpl');
1415 $dh = opendir('../htdocs/images/icons');
1416 if (!$dh) {
1417 $page->trigError('Dossier des icones introuvables.');
1418 }
1419 $icons = array();
1420 while (($file = readdir($dh)) !== false) {
1421 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1422 array_push($icons, substr($file, 0, -4));
1423 }
1424 }
1425 sort($icons);
1426 $page->assign('icons', $icons);
1427 }
1428
1429 function handler_account_watch(&$page)
1430 {
1431 $page->changeTpl('admin/accounts.tpl');
1432 $page->assign('disabled', XDB::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1433 a.state = \'disabled\' AS disabled, a.comment
1434 FROM accounts AS a
1435 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1436 ORDER BY a.hruid'));
1437 $page->assign('admins', XDB::iterator('SELECT a.hruid
1438 FROM accounts AS a
1439 WHERE a.is_admin
1440 ORDER BY a.hruid'));
1441 }
1442
1443 function handler_jobs(&$page, $id = -1)
1444 {
1445 $page->changeTpl('admin/jobs.tpl');
1446
1447 if (Env::has('search')) {
1448 $res = XDB::query("SELECT id, name, acronym
1449 FROM profile_job_enum
1450 WHERE name LIKE CONCAT('%', {?}, '%') OR acronym LIKE CONCAT('%', {?}, '%')",
1451 Env::t('job'), Env::t('job'));
1452
1453 if ($res->numRows() <= 20) {
1454 $page->assign('jobs', $res->fetchAllAssoc());
1455 } else {
1456 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1457 }
1458
1459 $page->assign('askedJob', Env::v('job'));
1460 return;
1461 }
1462
1463 if (Env::has('edit')) {
1464 S::assert_xsrf_token();
1465 $selectedJob = Env::has('selectedJob');
1466
1467 Phone::deletePhones(0, Phone::LINK_COMPANY, $id);
1468 Address::deleteAddresses(null, Address::LINK_COMPANY, $id);
1469 if (Env::has('change')) {
1470 XDB::execute('UPDATE profile_job
1471 SET jobid = {?}
1472 WHERE jobid = {?}',
1473 Env::i('newJobId'), $id);
1474 XDB::execute('DELETE FROM profile_job_enum
1475 WHERE id = {?}',
1476 $id);
1477
1478 $page->trigSuccess("L'entreprise a bien été remplacée.");
1479 } else {
1480 XDB::execute('UPDATE profile_job_enum
1481 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1482 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1483 WHERE id = {?}',
1484 Env::t('name'), Env::t('acronym'), Env::t('url'), Env::t('email'),
1485 (Env::t('NAF_code') == 0 ? null : Env::t('NAF_code')),
1486 (Env::i('AX_code') == 0 ? null : Env::t('AX_code')),
1487 (Env::i('holdingId') == 0 ? null : Env::t('holdingId')), $id);
1488
1489 $phone = new Phone(array('display' => Env::v('tel'), 'link_id' => $id, 'id' => 0, 'type' => 'fixed',
1490 'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
1491 $fax = new Phone(array('display' => Env::v('fax'), 'link_id' => $id, 'id' => 1, 'type' => 'fax',
1492 'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
1493 $address = new Address(array('jobid' => $jobid, 'type' => Address::LINK_COMPANY, 'text' => Env::t('address')));
1494 $phone->save();
1495 $fax->save();
1496 $address->save();
1497
1498 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1499 }
1500 }
1501
1502 if (!Env::has('change') && $id != -1) {
1503 $res = XDB::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1504 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1505 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1506 FROM profile_job_enum AS e
1507 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
1508 LEFT JOIN profile_phones AS t ON (t.pid = e.id AND t.link_type = 'hq' AND t.tel_id = 0)
1509 LEFT JOIN profile_phones AS f ON (f.pid = e.id AND f.link_type = 'hq' AND f.tel_id = 1)
1510 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1511 WHERE e.id = {?}",
1512 $id);
1513
1514 if ($res->numRows() == 0) {
1515 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1516 } else {
1517 $page->assign('selectedJob', $res->fetchOneAssoc());
1518 }
1519 }
1520 }
1521 }
1522
1523 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1524 ?>