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