2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
22 class AdminModule
extends PLModule
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,edit_directory'),
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/geocoding' => $this->make_hook('geocoding', AUTH_MDP
, 'admin'),
51 'admin/accounts' => $this->make_hook('accounts', AUTH_MDP
, 'admin'),
52 'admin/account/watch' => $this->make_hook('account_watch', AUTH_MDP
, 'admin'),
53 'admin/account/types' => $this->make_hook('account_types', AUTH_MDP
, 'admin'),
54 'admin/jobs' => $this->make_hook('jobs', AUTH_MDP
, 'admin,edit_directory'),
55 'admin/profile' => $this->make_hook('profile', AUTH_MDP
, 'admin,edit_directory')
59 function handler_phpinfo($page)
65 function handler_get_rights($page)
68 $page->kill('Déjà en SUID');
70 S
::assert_xsrf_token();
71 $level = Post
::s('account_type');
72 if ($level != 'admin') {
73 $user = User
::getSilentWithUID(S
::user()->id());
74 $user->is_admin
= false
;
75 $types = DirEnum
::getOptions(DirEnum
::ACCOUNTTYPES
);
76 if (!empty($types[$level])) {
77 $user->setPerms($types[$level]);
79 S
::set('suid_startpage', $_SERVER['HTTP_REFERER']);
80 Platal
::session()->startSUID($user);
82 if (!empty($_SERVER['HTTP_REFERER'])) {
83 http_redirect($_SERVER['HTTP_REFERER']);
89 function handler_set_skin($page)
91 S
::assert_xsrf_token();
92 S
::set('skin', Post
::s('change_skin'));
93 if (!empty($_SERVER['HTTP_REFERER'])) {
94 http_redirect($_SERVER['HTTP_REFERER']);
100 function handler_default($page)
102 $page->changeTpl('admin/index.tpl');
103 $page->setTitle('Administration');
106 function handler_postfix_delayed($page)
108 $page->changeTpl('admin/postfix_delayed.tpl');
109 $page->setTitle('Administration - Postfix : Retardés');
111 if (Env
::has('del')) {
112 $crc = Env
::v('crc');
113 XDB
::execute("UPDATE postfix_mailseen SET release = 'del' WHERE crc = {?}", $crc);
114 $page->trigSuccess($crc . " verra tous ses emails supprimés !");
115 } elseif (Env
::has('ok')) {
116 $crc = Env
::v('crc');
117 XDB
::execute("UPDATE postfix_mailseen SET release = 'ok' WHERE crc = {?}", $crc);
118 $page->trigSuccess($crc . " a le droit de passer !");
121 $sql = XDB
::iterator(
122 "SELECT crc, nb, update_time, create_time,
123 FIND_IN_SET('del', p.release) AS del,
124 FIND_IN_SET('ok', p.release) AS ok
125 FROM postfix_mailseen AS p
127 ORDER BY p.release != ''");
129 $page->assign_by_ref('mails', $sql);
134 /** Retrieves the available days for a given year and month.
135 * Obtain a list of days of the given month in the given year
136 * that are within the range of dates that we have log entries for.
138 * @param integer year
139 * @param integer month
140 * @return array days in that month we have log entries covering.
143 function _getDays($year, $month)
145 // give a 'no filter' option
149 if ($year && $month) {
150 $day_max = Array(-1, 31, checkdate(2, 29, $year) ?
29 : 28 , 31,
151 30, 31, 30, 31, 31, 30, 31, 30, 31);
152 $res = XDB
::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
153 MONTH(MAX(start)), MONTH(MIN(start)),
154 DAYOFMONTH(MAX(start)),
155 DAYOFMONTH(MIN(start))
157 list($ymax, $ymin, $mmax, $mmin, $dmax, $dmin) = $res->fetchOneRow();
159 if (($year < $ymin) ||
($year == $ymin && $month < $mmin)) {
163 if (($year > $ymax) ||
($year == $ymax && $month > $mmax)) {
167 $min = ($year==$ymin && $month==$mmin) ?
intval($dmin) : 1;
168 $max = ($year==$ymax && $month==$mmax) ?
intval($dmax) : $day_max[$month];
170 for($i = $min; $i<=$max; $i++
) {
178 /** Retrieves the available months for a given year.
179 * Obtains a list of month numbers that are within the timeframe that
180 * we have log entries for.
182 * @param integer year
183 * @return array List of month numbers we have log info for.
186 function _getMonths($year)
188 // give a 'no filter' option
193 $res = XDB
::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
194 MONTH(MAX(start)), MONTH(MIN(start))
196 list($ymax, $ymin, $mmax, $mmin) = $res->fetchOneRow();
198 if (($year < $ymin) ||
($year > $ymax)) {
202 $min = $year == $ymin ?
intval($mmin) : 1;
203 $max = $year == $ymax ?
intval($mmax) : 12;
205 for($i = $min; $i<=$max; $i++
) {
213 /** Retrieves the available years.
214 * Obtains a list of years that we have log entries covering.
216 * @return array years we have log entries for.
221 // give a 'no filter' option
225 // retrieve available years
226 $res = XDB
::query("select YEAR(MAX(start)), YEAR(MIN(start)) FROM log_sessions");
227 list($max, $min) = $res->fetchOneRow();
229 for($i = intval($min); $i<=$max; $i++
) {
236 /** Make a where clause to get a user's sessions.
237 * Prepare the where clause request that will retrieve the sessions.
239 * @param $year INTEGER Only get log entries made during the given year.
240 * @param $month INTEGER Only get log entries made during the given month.
241 * @param $day INTEGER Only get log entries made during the given day.
242 * @param $uid INTEGER Only get log entries referring to the given user ID.
244 * @return STRING the WHERE clause of a query, including the 'WHERE' keyword
247 function _makeWhere($year, $month, $day, $uid)
249 // start constructing the "where" clause
253 array_push($where, "s.uid='$uid'");
255 // we were given at least a year
258 $dmin = mktime(0, 0, 0, $month, $day, $year);
259 $dmax = mktime(0, 0, 0, $month, $day+
1, $year);
261 $dmin = mktime(0, 0, 0, $month, 1, $year);
262 $dmax = mktime(0, 0, 0, $month+
1, 1, $year);
264 $dmin = mktime(0, 0, 0, 1, 1, $year);
265 $dmax = mktime(0, 0, 0, 1, 1, $year+
1);
267 $where[] = "start >= " . date("Ymd000000", $dmin);
268 $where[] = "start < " . date("Ymd000000", $dmax);
271 if (!empty($where)) {
272 return ' WHERE ' . implode($where, " AND ");
276 // WE know it's totally reversed, so better use array_reverse than a SORT BY start DESC
281 function handler_logger($page, $action = null
, $arg = null
) {
282 if ($action == 'session') {
284 // we are viewing a session
285 $res = XDB
::query("SELECT ls.*, a.hruid AS username, sa.hruid AS suer
286 FROM log_sessions AS ls
287 INNER JOIN accounts AS a ON (a.uid = ls.uid)
288 LEFT JOIN accounts AS sa ON (sa.uid = ls.suid)
289 WHERE ls.id = {?}", $arg);
291 $page->assign('session', $a = $res->fetchOneAssoc());
293 $res = XDB
::iterator('SELECT a.text, e.data, e.stamp
295 LEFT JOIN log_actions AS a ON e.action=a.id
296 WHERE e.session={?}', $arg);
297 while ($myarr = $res->next()) {
298 $page->append('events', $myarr);
302 $loguser = $action == 'user' ?
$arg : Env
::v('loguser');
305 $user = User
::get($loguser);
306 $loguid = $user->id();
312 $year = Env
::i('year');
313 $month = Env
::i('month');
314 $day = Env
::i('day');
316 $year = Env
::i('year', intval(date('Y')));
317 $month = Env
::i('month', intval(date('m')));
318 $day = Env
::i('day', intval(date('d')));
326 // smarty assignments
327 // retrieve available years
328 $page->assign('years', $this->_getYears());
329 $page->assign('year', $year);
331 // retrieve available months for the current year
332 $page->assign('months', $this->_getMonths($year));
333 $page->assign('month', $month);
335 // retrieve available days for the current year and month
336 $page->assign('days', $this->_getDays($year, $month));
337 $page->assign('day', $day);
339 $page->assign('loguser', $loguser);
340 // smarty assignments
342 if ($loguid ||
$year) {
344 // get the requested sessions
345 $where = $this->_makeWhere($year, $month, $day, $loguid);
346 $select = "SELECT s.id, s.start, s.uid,
348 FROM log_sessions AS s
349 INNER JOIN accounts AS a ON (a.uid = s.uid)
351 ORDER BY start DESC";
352 $res = XDB
::iterator($select);
355 while ($mysess = $res->next()) {
356 $mysess['events'] = array();
357 $sessions[$mysess['id']] = $mysess;
359 array_reverse($sessions);
362 $sql = "SELECT s.id, a.text
363 FROM log_sessions AS s
364 LEFT JOIN log_events AS e ON(e.session=s.id)
365 INNER JOIN log_actions AS a ON(a.id=e.action)
368 $res = XDB
::iterator($sql);
369 while ($event = $res->next()) {
370 array_push($sessions[$event['id']]['events'], $event['text']);
372 $page->assign_by_ref('sessions', $sessions);
374 $page->assign('msg_nofilters', "Sélectionner une année et/ou un utilisateur");
378 $page->changeTpl('admin/logger-view.tpl');
380 $page->setTitle('Administration - Logs des sessions');
383 function handler_user($page, $login = false
)
386 $page->changeTpl('admin/user.tpl');
387 $page->setTitle('Administration - Compte');
390 $page->kill("Déjà en SUID !!!");
393 // Loads the user identity using the environment.
395 $user = User
::get($login);
398 pl_redirect('admin/accounts');
401 $listClient = new MMList(S
::user());
402 $login = $user->login();
403 $registered = ($user->state
!= 'pending');
406 if (!empty($_POST)) {
407 S
::assert_xsrf_token();
408 if (Post
::has('uid') && Post
::i('uid') != $user->id()) {
409 $page->kill('Une erreur s\'est produite');
413 // Handles specific requests (AX sync, su, ...).
414 if(Post
::has('log_account')) {
415 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
418 if(Post
::has('su_account') && $registered) {
419 if (!Platal
::session()->startSUID($user)) {
420 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->login());
426 // Handles account deletion.
427 if (Post
::has('account_deletion_confirmation')) {
429 $name = $user->fullName();
430 $profile = $user->profile();
431 if ($profile && Post
::b('clear_profile')) {
432 $user->profile()->clear();
435 $page->trigSuccess("L'utilisateur $name ($uid) a bien été désinscrit.");
436 if (Post
::b('erase_account')) {
437 XDB
::execute('DELETE FROM accounts
440 $page->trigSuccess("L'utilisateur $name ($uid) a été supprimé de la base de données");
445 $to_update = array();
446 if (Post
::has('disable_weak_access')) {
447 $to_update['weak_password'] = null
;
448 } else if (Post
::has('update_account')) {
449 if (!$user->hasProfile()) {
450 if (Post
::s('full_name') != $user->fullName()) {
451 $to_update['full_name'] = Post
::s('full_name');
453 if (Post
::s('display_name') != $user->displayName()) {
454 $to_update['display_name'] = Post
::s('display_name');
456 if (Post
::s('directory_name') != $user->directoryName()) {
457 $to_update['directory_name'] = Post
::s('directory_name');
460 if (Post
::s('sex') != ($user->isFemale() ?
'female' : 'male')) {
461 $to_update['sex'] = Post
::s('sex');
462 if ($user->hasProfile()) {
463 XDB
::execute('UPDATE profiles
466 Post
::s('sex'), $user->profile()->id());
469 if (!Post
::blank('pwhash')) {
470 $to_update['password'] = Post
::s('pwhash');
471 require_once 'googleapps.inc.php';
472 $account = new GoogleAppsAccount($user);
473 if ($account->active() && $account->sync_password
) {
474 $account->set_password(Post
::s('pwhash'));
477 if (!Post
::blank('weak_password')) {
478 $to_update['weak_password'] = Post
::s('weak_password');
480 if (Post
::i('token_access', 0) != ($user->token_access ?
1 : 0)) {
481 $to_update['token'] = Post
::i('token_access') ?
rand_url_id(16) : null
;
483 if (Post
::i('skin') != $user->skin
) {
484 $to_update['skin'] = Post
::i('skin');
485 if ($to_update['skin'] == 0) {
486 $to_update['skin'] = null
;
489 if (Post
::s('state') != $user->state
) {
490 $to_update['state'] = Post
::s('state');
492 if (Post
::i('is_admin', 0) != ($user->is_admin ?
1 : 0)) {
493 $to_update['is_admin'] = Post
::b('is_admin');
495 if (Post
::s('type') != $user->type
) {
496 $to_update['type'] = Post
::s('type');
498 if (Post
::i('watch', 0) != ($user->watch ?
1 : 0)) {
499 $to_update['flags'] = new PlFlagset();
500 $to_update['flags']->addFlag('watch', Post
::i('watch'));
502 if (Post
::t('comment') != $user->comment
) {
503 $to_update['comment'] = Post
::blank('comment') ? null
: Post
::t('comment');
505 if (!$user->checkPerms(User
::PERM_MAIL
) && Post
::t('email') != $user->forlifeEmail()) {
506 $to_update['email'] = Post
::t('email');
507 $listClient->change_user_email($user->forlifeEmail(), Post
::t('email'));
510 if (!empty($to_update)) {
511 $res = XDB
::query('SELECT *
513 WHERE uid = {?}', $user->id());
514 $oldValues = $res->fetchAllAssoc();
515 $oldValues = $oldValues[0];
519 foreach ($to_update as $k => $value) {
520 $value = XDB
::format('{?}', $value);
521 $set[] = $k . ' = ' . $value;
522 $diff[$k] = array($oldValues[$k], trim($value, "'"));
523 unset($oldValues[$k]);
525 XDB
::rawExecute('UPDATE accounts
526 SET ' . implode(', ', $set) . '
527 WHERE uid = ' . XDB
::format('{?}', $user->id()));
528 $page->trigSuccess('Données du compte mise à jour avec succès');
529 $user = User
::getWithUID($user->id());
531 /* Formats the $diff and send it to the site administrators. The rules are the folowing:
532 * -formats: password, token, weak_password
534 foreach (array('password', 'token', 'weak_password') as $key) {
535 if (isset($diff[$key])) {
536 $diff[$key] = array('old value', 'new value');
538 $oldValues[$key] = 'old value';
542 $mail = new PlMailer('admin/useredit.mail.tpl');
543 $mail->assign('admin', S
::user()->hruid
);
544 $mail->assign('hruid', $user->hruid
);
545 $mail->assign('diff', $diff);
546 $mail->assign('oldValues', $oldValues);
552 if (Post
::has('add_profile') || Post
::has('del_profile') || Post
::has('owner')) {
553 if (Post
::i('del_profile', 0) != 0) {
554 XDB
::execute('DELETE FROM account_profiles
555 WHERE uid = {?} AND pid = {?}',
556 $user->id(), Post
::i('del_profile'));
557 } else if (!Post
::blank('new_profile')) {
558 $profile = Profile
::get(Post
::t('new_profile'));
560 $page->trigError('Le profil ' . Post
::t('new_profile') . ' n\'existe pas');
562 XDB
::execute('INSERT IGNORE INTO account_profiles (uid, pid)
564 $user->id(), $profile->id());
567 XDB
::execute('UPDATE account_profiles
568 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
570 Post
::i('owner'), $user->id());
574 // Email forwards form {{{
575 require_once("emails.inc.php");
576 $redirect = ($registered ?
new Redirect($user) : null
);
577 if (Post
::has('add_fwd')) {
578 $email = Post
::t('email');
579 if (!isvalid_email_redirection($email)) {
580 $page->trigError("Email non valide: $email");
582 $redirect->add_email($email);
583 $page->trigSuccess("Ajout de $email effectué");
585 } else if (!Post
::blank('del_fwd')) {
586 $redirect->delete_email(Post
::t('del_fwd'));
587 } else if (!Post
::blank('activate_fwd')) {
588 $redirect->modify_one_email(Post
::t('activate_fwd'), true
);
589 } else if (!Post
::blank('deactivate_fwd')) {
590 $redirect->modify_one_email(Post
::t('deactivate_fwd'), false
);
591 } else if (Post
::has('disable_fwd')) {
592 $redirect->disable();
593 } else if (Post
::has('enable_fwd')) {
595 } else if (!Post
::blank('clean_fwd')) {
596 $redirect->clean_errors(Post
::t('clean_fwd'));
600 // Email alias form {{{
601 if (Post
::has('add_alias')) {
602 // Splits new alias in user and fqdn.
603 $alias = Env
::t('email');
604 if (strpos($alias, '@') !== false
) {
605 list($alias, $domain) = explode('@', $alias);
607 $domain = $user->mainEmailDomain();
610 // Checks for alias' user validity.
611 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
612 $page->trigError("'$alias' n'est pas un alias valide");
615 // Eventually adds the alias to the right domain.
616 if ($domain == $globals->mail
->alias_dom ||
$domain == $globals->mail
->alias_dom2
) {
617 $req = new AliasReq($user, $alias, 'Admin request', false
);
618 if ($req->commit()) {
619 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué.");
621 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué.");
623 } elseif ($domain == $user->mainEmailDomain()) {
624 XDB
::execute('INSERT INTO email_source_account (email, uid, domain, type, flags)
625 SELECT {?}, {?}, id, \'alias\', \'\'
626 FROM email_virtual_domains
628 $alias, $user->id(), $domain);
629 $page->trigSuccess("Nouvel alias '$alias' ajouté");
631 $page->trigError("Le domaine '$domain' n'est pas valide pour cet utilisateur.");
633 } else if (!Post
::blank('del_alias')) {
634 $delete_alias = Post
::t('del_alias');
635 list($email, $domain) = explode('@', $delete_alias);
636 XDB
::execute('DELETE s
637 FROM email_source_account AS s
638 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
639 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
640 WHERE s.email = {?} AND s.uid = {?} AND d.name = {?} AND type != \'forlife\'',
641 $email, $user->id(), $domain);
642 XDB
::execute('UPDATE email_redirect_account AS r
643 INNER JOIN email_virtual_domains AS m ON (m.name = {?})
644 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
646 WHERE r.uid = {?} AND r.rewrite = CONCAT({?}, \'@\', d.name)',
647 $domain, $user->id(), $email);
648 fix_bestalias($user);
649 $page->trigSuccess("L'alias '$delete_alias' a été supprimé");
650 } else if (!Post
::blank('best')) {
651 $best_alias = Post
::t('best');
652 // First delete the bestalias flag from all this user's emails.
653 XDB
::execute("UPDATE email_source_account
654 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
655 WHERE uid = {?}", $user->id());
656 // Then gives the bestalias flag to the given email.
657 list($email, $domain) = explode('@', $best_alias);
658 XDB
::execute("UPDATE email_source_account AS s
659 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
660 SET s.flags = CONCAT_WS(',', IF(s.flags = '', NULL, s.flags), 'bestalias')
661 WHERE s.uid = {?} AND s.email = {?} AND d.name = {?}", $user->id(), $email, $domain);
663 // As having a non-null bestalias value is critical in
664 // plat/al's code, we do an a posteriori check on the
665 // validity of the bestalias.
666 fix_bestalias($user);
671 if (Post
::has('del_openid')) {
672 XDB
::execute('DELETE FROM account_auth_openid
673 WHERE id = {?}', Post
::i('del_openid'));
678 if (Post
::has('b_edit')) {
679 XDB
::execute("DELETE FROM forum_innd
680 WHERE uid = {?}", $user->id());
681 if (Env
::v('write_perm') != "" || Env
::v('read_perm') != "" || Env
::v('commentaire') != "" ) {
682 XDB
::execute("INSERT INTO forum_innd
683 SET ipmin = '0', ipmax = '4294967295',
684 write_perm = {?}, read_perm = {?},
685 comment = {?}, priority = '200', uid = {?}",
686 Env
::v('write_perm'), Env
::v('read_perm'), Env
::v('comment'), $user->id());
692 $page->addJsLink('jquery.ui.xorg.js');
694 // Displays last login and last host information.
695 $res = XDB
::query("SELECT start, host
697 WHERE uid = {?} AND suid = 0
699 LIMIT 1", $user->id());
700 list($lastlogin,$host) = $res->fetchOneRow();
701 $page->assign('lastlogin', $lastlogin);
702 $page->assign('host', $host);
704 // Display mailing lists
705 $page->assign('mlists', $listClient->get_all_user_lists($user->forlifeEmail()));
707 // Display active aliases.
708 $page->assign('virtuals', $user->emailGroupAliases());
709 $aliases = XDB
::iterator("SELECT CONCAT(s.email, '@', d.name) AS email, (s.type = 'forlife') AS forlife,
710 (s.email REGEXP '\\\\.[0-9]{2}$') AS hundred_year,
711 FIND_IN_SET('bestalias', s.flags) AS bestalias, s.expire,
712 (s.type = 'alias_aux') AS alias
713 FROM email_source_account AS s
714 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
716 ORDER BY !alias, s.email",
718 $page->assign('aliases', $aliases);
719 $page->assign('account_types', XDB
::iterator('SELECT * FROM account_types ORDER BY type'));
720 $page->assign('skins', XDB
::iterator('SELECT id, name FROM skins ORDER BY name'));
721 $page->assign('profiles', XDB
::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
722 FROM account_profiles AS ap
723 INNER JOIN profiles AS p ON (ap.pid = p.pid)
724 WHERE ap.uid = {?}', $user->id()));
725 $page->assign('openid', XDB
::iterator('SELECT id, url
726 FROM account_auth_openid
727 WHERE uid = {?}', $user->id()));
729 // Displays email redirection and the general profile.
730 if ($registered && $redirect) {
731 $page->assign('emails', $redirect->emails
);
734 $page->assign('user', $user);
735 $page->assign('hasProfile', $user->hasProfile());
737 // Displays forum bans.
738 $res = XDB
::query("SELECT write_perm, read_perm, comment
740 WHERE uid = {?}", $user->id());
741 $bans = $res->fetchOneAssoc();
742 $page->assign('bans', $bans);
745 private static function getHrid($firstname, $lastname, $promo)
747 if ($firstname != null
&& $lastname != null
&& $promo != null
) {
748 return User
::makeHrid($firstname, $lastname, $promo);
753 private static function formatNewUser($page, $infosLine, $separator, $promo, $size)
755 $infos = explode($separator, $infosLine);
756 if (sizeof($infos) > $size ||
sizeof($infos) < 2) {
757 $page->trigError("La ligne $infosLine n'a pas été ajoutée.");
761 $infos = array_map('trim', $infos);
762 $hrid = self
::getHrid($infos[1], $infos[0], $promo);
763 $res1 = XDB
::query('SELECT COUNT(*)
765 WHERE hruid = {?}', $hrid);
766 $res2 = XDB
::query('SELECT COUNT(*)
768 WHERE hrpid = {?}', $hrid);
769 if (is_null($hrid) ||
$res1->fetchOneCell() > 0 ||
$res2->fetchOneCell() > 0) {
770 $page->trigError("La ligne $infosLine n'a pas été ajoutée: une entrée similaire existe déjà");
773 $infos['hrid'] = $hrid;
777 private static function formatSex($page, $sex, $line)
785 $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
790 private static function formatBirthDate($birthDate)
792 // strtotime believes dd/mm/yyyy to be an US date (i.e mm/dd/yyyy), and
793 // dd-mm-yyyy to be a normal date (i.e dd-mm-yyyy)...
794 return date("Y-m-d", strtotime(str_replace('/', '-', $birthDate)));
797 function handler_add_accounts($page, $action = null
, $promo = null
)
799 $page->changeTpl('admin/add_accounts.tpl');
801 if (Env
::has('add_type') && Env
::has('people')) {
802 $lines = explode("\n", Env
::t('people'));
803 $separator = Env
::t('separator');
804 $promotion = Env
::i('promotion');
805 $nameTypes = DirEnum
::getOptions(DirEnum
::NAMETYPES
);
806 $nameTypes = array_flip($nameTypes);
808 if (Env
::t('add_type') == 'promo') {
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')) {
815 $degreeid = $eduDegrees[Profile
::DEGREE_X
];
816 $entry_year = $promotion;
817 $grad_year = $promotion +
3;
818 $promo = 'X' . $promotion;
819 $hrpromo = $promotion;
823 $degreeid = $eduDegrees[Profile
::DEGREE_M
];
824 $grad_year = $promotion;
825 $entry_year = $promotion - 2;
826 $promo = 'M' . $promotion;
831 $degreeid = $eduDegrees[Profile
::DEGREE_D
];
832 $grad_year = $promotion;
833 $entry_year = $promotion - 3;
834 $promo = 'D' . $promotion;
839 $page->killError("La formation n'est pas reconnue:" . Env
::t('edu_type') . '.');
842 XDB
::startTransaction();
843 foreach ($lines as $line) {
844 if ($infos = self
::formatNewUser($page, $line, $separator, $hrpromo, 6)) {
845 $sex = self
::formatSex($page, $infos[3], $line);
846 if (!is_null($sex)) {
847 $fullName = $infos[1] . ' ' . $infos[0];
848 $directoryName = $infos[0] . ' ' . $infos[1];
849 $birthDate = self
::formatBirthDate($infos[2]);
851 $xorgId = Profile
::getXorgId($infos[4]);
853 $xorgId = trim($infos[4]);
855 if (is_null($xorgId)) {
856 $page->trigError("La ligne $line n'a pas été ajoutée car le matricule École est mal renseigné.");
860 XDB
::execute('INSERT INTO profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex)
861 VALUES ({?}, {?}, {?}, {?}, {?})',
862 $infos['hrid'], $xorgId, $infos[5], $birthDate, $sex);
863 $pid = XDB
::insertId();
864 XDB
::execute('INSERT INTO profile_name (pid, name, typeid)
865 VALUES ({?}, {?}, {?}),
869 $pid, $infos[0], $nameTypes['name_ini'],
870 $pid, $infos[0], $nameTypes['lastname'],
871 $pid, $infos[1], $nameTypes['firstname_ini'],
872 $pid, $infos[1], $nameTypes['firstname']);
873 XDB
::execute('INSERT INTO profile_display (pid, yourself, public_name, private_name,
874 directory_name, short_name, sort_name, promo)
875 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
876 $pid, $infos[1], $fullName, $fullName, $directoryName, $fullName, $directoryName, $promo);
877 XDB
::execute('INSERT INTO profile_education (id, pid, eduid, degreeid, entry_year, grad_year, flags)
878 VALUES (100, {?}, {?}, {?}, {?}, {?}, \'primary\')',
879 $pid, $eduSchools[Profile
::EDU_X
], $degreeid, $entry_year, $grad_year);
880 XDB
::execute('INSERT INTO accounts (hruid, type, is_admin, state, full_name, directory_name, display_name, sex)
881 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
882 $infos['hrid'], $type, 0, 'pending', $fullName, $directoryName, $infos[1], $sex);
883 $uid = XDB
::insertId();
884 XDB
::execute('INSERT INTO account_profiles (uid, pid, perms)
885 VALUES ({?}, {?}, {?})',
886 $uid, $pid, 'owner');
887 Profile
::rebuildSearchTokens($pid, false
);
892 } else if (Env
::t('add_type') == 'account') {
893 $type = Env
::t('type');
894 $newAccounts = array();
895 foreach ($lines as $line) {
896 if ($infos = self
::formatNewUser($page, $line, $separator, $type, 4)) {
897 $sex = self
::formatSex($page, $infos[3], $line);
898 if (!is_null($sex)) {
899 $fullName = $infos[1] . ' ' . $infos[0];
900 $directoryName = $infos[0] . ' ' . $infos[1];
901 XDB
::execute('INSERT INTO accounts (hruid, type, is_admin, state,
902 email, full_name, directory_name,
904 VALUES ({?}, {?}, {?}, {?},
905 {?}, {?}, {?}, {?}, {?})',
906 $infos['hrid'], $type, 0, 'pending',
907 $infos[2], $fullName, $directoryName,
909 $newAccounts[$infos['hrid']] = $infos[1] . ' ' . $infos[0];
913 if (!empty($newAccounts)) {
914 $page->assign('newAccounts', $newAccounts);
916 } else if (Env
::t('add_type') == 'ax_id') {
918 foreach ($lines as $line) {
919 if ($infos = self
::formatNewUser($page, $line, $separator, $promotion, 3)) {
920 XDB
::execute('UPDATE profiles
923 $infos[2], $infos['hrid']);
928 $errors = $page->nb_errs();
930 $page->trigSuccess("L'opération a été effectuée avec succès.");
932 $page->trigSuccess('L\'opération a été effectuée avec succès, sauf pour '
933 . (($errors == 1) ?
'l\'erreur signalée' : "les $errors erreurs signalées") . ' ci-dessus.');
935 } else if (Env
::has('add_type')) {
936 $res = XDB
::query('SELECT type
937 FROM account_types');
938 $page->assign('account_types', $res->fetchColumn());
939 $page->assign('add_type', Env
::s('add_type'));
943 function handler_homonyms($page, $op = 'list', $target = null
)
945 $page->changeTpl('admin/homonymes.tpl');
946 $page->setTitle('Administration - Homonymes');
947 $this->load("homonyms.inc.php");
950 $user = User
::getSilentWithUID($target);
951 if (!$user ||
!($loginbis = select_if_homonym($user))) {
954 $page->assign('user', $user);
955 $page->assign('loginbis',$loginbis);
959 $page->assign('op', $op);
960 $page->assign('target', $target);
962 // When we have a valid target, prepare emails.
964 require_once 'emails.inc.php';
965 // Examine what operation needs to be performed.
968 S
::assert_xsrf_token();
970 send_warning_homonyme($user, $loginbis);
971 fix_bestalias($user);
973 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
977 S
::assert_xsrf_token();
979 XDB
::execute('DELETE FROM email_source_account
980 WHERE email = {?} AND type = \'alias\'',
982 XDB
::execute('INSERT INTO email_source_other (hrmid, email, domain, type, expire)
983 SELECT {?}, {?}, id, \'homonym\', NOW()
984 FROM email_virtual_domains
986 User
::makeHomonymHrmid($loginbis), $loginbis, $user->mainEmailDomain());
987 fix_bestalias($user);
988 send_robot_homonyme($user, $loginbis);
990 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
996 // Retrieves homonyms that are already been fixed.
997 $res = XDB
::iterator('SELECT o.email AS homonym, f.email AS forlife, o.expire, f.uid
998 FROM email_source_other AS o
999 INNER JOIN homonyms_list AS h ON (o.hrmid = h.hrmid)
1000 INNER JOIN email_source_account AS f ON (h.uid = f.uid AND f.type = \'forlife\')
1001 WHERE o.expire IS NOT NULL
1002 ORDER BY homonym, forlife');
1003 $homonyms = array();
1004 while ($item = $res->next()) {
1005 $homonyms[$item['homonym']][] = $item;
1007 $page->assign_by_ref('homonyms', $homonyms);
1009 // Retrieves homonyms that needs to be fixed.
1010 $res = XDB
::iterator('SELECT e.email AS homonym, f.email AS forlife, e.expire, e.uid, (e.expire < NOW()) AS urgent
1011 FROM email_source_account AS e
1012 INNER JOIN homonyms_list AS l ON (e.uid = l.uid)
1013 INNER JOIN homonyms_list AS h ON (l.hrmid = h.hrmid)
1014 INNER JOIN email_source_account AS f ON (h.uid = f.uid AND f.type = \'forlife\')
1015 WHERE e.expire IS NOT NULL
1016 ORDER BY homonym, forlife');
1017 $homonyms_to_fix = array();
1018 while ($item = $res->next()) {
1019 $homonyms_to_fix[$item['homonym']][] = $item;
1021 $page->assign_by_ref('homonyms_to_fix', $homonyms_to_fix);
1025 function handler_deaths($page, $promo = 0, $validate = false
)
1027 $page->changeTpl('admin/deces_promo.tpl');
1028 $page->setTitle('Administration - Deces');
1031 $promo = Env
::t('promo', 'X1923');
1033 $page->assign('promo', $promo);
1039 S
::assert_xsrf_token();
1041 $res = XDB
::iterRow('SELECT p.pid, pd.directory_name, p.deathdate
1043 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1044 WHERE pd.promo = {?}', $promo);
1045 while (list($pid, $name, $death) = $res->next()) {
1046 $val = Env
::v('death_' . $pid);
1047 if ($val == $death) {
1054 XDB
::execute('UPDATE profiles
1055 SET deathdate = {?}, deathdate_rec = NOW()
1056 WHERE pid = {?}', $val, $pid);
1058 $page->trigSuccess('Édition du décès de ' . $name . ' (' . ($val ?
$val : 'ressuscité') . ').');
1059 if ($val && ($death == '0000-00-00' ||
empty($death))) {
1060 $profile = Profile
::get($pid);
1062 $profile->owner()->clear(false
);
1067 $res = XDB
::iterator('SELECT p.pid, pd.directory_name, p.deathdate
1069 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1070 WHERE pd.promo = {?}
1071 ORDER BY pd.sort_name', $promo);
1072 $page->assign('profileList', $res);
1075 function handler_dead_but_active($page)
1077 $page->changeTpl('admin/dead_but_active.tpl');
1078 $page->setTitle('Administration - Décédés');
1080 $res = XDB
::iterator(
1081 "SELECT a.hruid, pd.promo, p.ax_id, pd.directory_name, p.deathdate, DATE(MAX(s.start)) AS last
1083 INNER JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET('owner', ap.perms))
1084 INNER JOIN profiles AS p ON (p.pid = ap.pid)
1085 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
1086 LEFT JOIN log_sessions AS s ON (s.uid = a.uid AND suid = 0)
1087 WHERE a.state = 'active' AND p.deathdate IS NOT NULL
1089 ORDER BY pd.promo, pd.sort_name");
1090 $page->assign('dead', $res);
1093 function handler_validate($page, $action = 'list', $id = null
)
1095 $page->changeTpl('admin/validation.tpl');
1096 $page->setTitle('Administration - Valider une demande');
1097 $page->addCssLink('nl.Polytechnique.org.css');
1099 if ($action == 'edit' && !is_null($id)) {
1100 $page->assign('preview_id', $id);
1102 $page->assign('preview_id', null
);
1105 if(Env
::has('uid') && Env
::has('type') && Env
::has('stamp')) {
1106 S
::assert_xsrf_token();
1108 $req = Validate
::get_typed_request(Env
::v('uid'), Env
::v('type'), Env
::v('stamp'));
1110 $req->handle_formu();
1112 $page->trigWarning('La validation a déjà été effectuée.');
1116 $r = XDB
::iterator('SHOW COLUMNS FROM requests_answers');
1117 while (($a = $r->next()) && $a['Field'] != 'category');
1118 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
1121 $res = XDB
::query('SELECT hidden_requests
1122 FROM requests_hidden
1123 WHERE uid = {?}', S
::v('uid'));
1124 $hide_requests = $res->fetchOneCell();
1125 if (Post
::has('hide')) {
1127 foreach ($categories as $cat)
1128 if (!Post
::v($cat)) {
1132 $hide_requests = join(',', $hide);
1133 XDB
::query('INSERT INTO requests_hidden (uid, hidden_requests)
1135 ON DUPLICATE KEY UPDATE hidden_requests = VALUES(hidden_requests)',
1136 S
::v('uid'), $hide_requests);
1137 } elseif ($hide_requests) {
1138 foreach (explode(',', $hide_requests) as $hide_type)
1139 $hidden[$hide_type] = true
;
1141 $page->assign('hide_requests', $hidden);
1143 // Update the count of item to validate here... useful in development configuration
1144 // where several copies of the site use the same DB, but not the same "dynamic configuration"
1146 $globals->updateNbValid();
1147 $page->assign('vit', Validate
::iterate());
1148 $page->assign('isAdmin', S
::admin());
1151 function handler_validate_answers($page, $action = 'list', $id = null
)
1153 $page->setTitle('Administration - Réponses automatiques de validation');
1154 $page->assign('title', 'Gestion des réponses automatiques');
1155 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
1156 $table_editor->describe('category','catégorie',true
);
1157 $table_editor->describe('title','titre',true
);
1158 $table_editor->describe('answer','texte',false
);
1159 $table_editor->apply($page, $action, $id);
1162 function handler_skins($page, $action = 'list', $id = null
)
1164 $page->setTitle('Administration - Skins');
1165 $page->assign('title', 'Gestion des skins');
1166 $table_editor = new PLTableEditor('admin/skins','skins','id');
1167 $table_editor->describe('name','nom',true
);
1168 $table_editor->describe('skin_tpl','nom du template',true
);
1169 $table_editor->describe('auteur','auteur',false
);
1170 $table_editor->describe('comment','commentaire',true
);
1171 $table_editor->describe('date','date',false
);
1172 $table_editor->describe('ext','extension du screenshot',false
);
1173 $table_editor->apply($page, $action, $id);
1176 function handler_postfix_blacklist($page, $action = 'list', $id = null
)
1178 $page->setTitle('Administration - Postfix : Blacklist');
1179 $page->assign('title', 'Blacklist de postfix');
1180 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true
);
1181 $table_editor->describe('reject_text','Texte de rejet',true
);
1182 $table_editor->describe('email','email',true
);
1183 $table_editor->apply($page, $action, $id);
1186 function handler_postfix_whitelist($page, $action = 'list', $id = null
)
1188 $page->setTitle('Administration - Postfix : Whitelist');
1189 $page->assign('title', 'Whitelist de postfix');
1190 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true
);
1191 $table_editor->describe('email','email',true
);
1192 $table_editor->apply($page, $action, $id);
1195 function handler_mx_broken($page, $action = 'list', $id = null
)
1197 $page->setTitle('Administration - MX Défaillants');
1198 $page->assign('title', 'MX Défaillant');
1199 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true
);
1200 $table_editor->describe('host', 'Masque', true
);
1201 $table_editor->describe('state', 'Niveau', true
);
1202 $table_editor->describe('text', 'Description du problème', false
);
1203 $table_editor->apply($page, $action, $id);
1206 function handler_logger_actions($page, $action = 'list', $id = null
)
1208 $page->setTitle('Administration - Actions');
1209 $page->assign('title', 'Gestion des actions de logger');
1210 $table_editor = new PLTableEditor('admin/logger/actions','log_actions','id');
1211 $table_editor->describe('text','intitulé',true
);
1212 $table_editor->describe('description','description',true
);
1213 $table_editor->apply($page, $action, $id);
1216 function handler_downtime($page, $action = 'list', $id = null
)
1218 $page->setTitle('Administration - Coupures');
1219 $page->assign('title', 'Gestion des coupures');
1220 $table_editor = new PLTableEditor('admin/downtime','downtimes','id');
1221 $table_editor->describe('debut','date',true
);
1222 $table_editor->describe('duree','durée',false
);
1223 $table_editor->describe('resume','résumé',true
);
1224 $table_editor->describe('services','services affectés',true
);
1225 $table_editor->describe('description','description',false
);
1226 $table_editor->apply($page, $action, $id);
1229 private static function isCountryIncomplete(array &$item)
1232 foreach (array('worldRegion', 'country', 'capital', 'phonePrefix', 'licensePlate', 'countryPlain') as $field) {
1233 if ($item[$field] == '') {
1234 $item[$field . '_warning'] = true
;
1238 if (is_null($item['belongsTo'])) {
1239 foreach (array('nationality', 'nationalityEn') as $field) {
1240 if ($item[$field] == '') {
1241 $item[$field . '_warning'] = true
;
1249 private static function updateCountry(array $item)
1251 XDB
::execute('UPDATE geoloc_countries
1252 SET countryPlain = {?}
1253 WHERE iso_3166_1_a2 = {?}',
1254 mb_strtoupper(replace_accent($item['country'])), $item['iso_3166_1_a2']);
1257 private static function isLanguageIncomplete(array &$item)
1259 if ($item['language'] == '') {
1260 $item['language_warning'] = true
;
1266 private static function updateLanguage(array $item) {}
1268 function handler_geocoding(&$page, $category = null
, $action = null
, $id = null
)
1270 // Warning, this handler requires the following packages:
1274 static $properties = array(
1277 'isocode' => '3166',
1278 'table' => 'geoloc_countries',
1279 'id' => 'iso_3166_1_a2',
1280 'main_fields' => array('iso_3166_1_a3', 'iso_3166_1_num', 'countryEn'),
1281 'other_fields' => array('worldRegion', 'country', 'capital', 'nationality', 'nationalityEn',
1282 'phonePrefix', 'phoneFormat', 'licensePlate', 'belongsTo')
1284 'language' => array(
1285 'name' => 'langages',
1287 'table' => 'profile_langskill_enum',
1288 'id' => 'iso_639_2b',
1289 'main_fields' => array('iso_639_2t', 'iso_639_1', 'language_en'),
1290 'other_fields' => array('language')
1295 if (is_null($category) ||
!array_key_exists($category, $properties)) {
1296 pl_redirect('admin');
1299 $data = $properties[$category];
1301 if ($action == 'edit' ||
$action == 'add') {
1302 $main_fields = array_merge(array($data['id']), $data['main_fields']);
1303 $all_fields = array_merge($main_fields, $data['other_fields']);
1306 if (Post
::has('new_id')) {
1307 $id = Post
::v('new_id');
1309 pl_redirect('admin/geocoding/' . $category);
1314 exec('isoquery --iso=' . $data['isocode'] . ' ' . $id, $list);
1315 if (count($list) == 1) {
1316 $array = explode("\t", $list[0]);
1317 foreach ($main_fields as $i => $field) {
1318 $iso[$field] = $array[$i];
1324 if ($action == 'add') {
1325 if (Post
::has('new_id')) {
1326 S
::assert_xsrf_token();
1332 $item = array($data['id'] => $id);
1334 XDB
::execute('INSERT INTO ' . $data['table'] . '(' . implode(', ', array_keys($item)) . ')
1335 VALUES ' . XDB
::formatArray($item));
1336 $page->trigSuccess($id . ' a bien été ajouté à la base.');
1337 } elseif ($action == 'edit') {
1338 if (Post
::has('edit')) {
1339 S
::assert_xsrf_token();
1343 foreach ($all_fields as $field) {
1344 $item[$field] = Post
::t($field);
1345 $set[] = $field . XDB
::format(' = {?}', ($item[$field] ?
$item[$field] : null
));
1347 XDB
::execute('UPDATE ' . $data['table'] . '
1348 SET ' . implode(', ', $set) . '
1349 WHERE ' . $data['id'] . ' = {?}',
1351 call_user_func_array(array('self', 'update' . ucfirst($category)), array($item));
1352 $page->trigSuccess($id . ' a bien été mis à jour.');
1353 } elseif (Post
::has('del')) {
1354 S
::assert_xsrf_token();
1356 XDB
::execute('DELETE FROM ' . $data['table'] . '
1357 WHERE ' . $data['id'] . ' = {?}',
1359 $page->trigSuccessRedirect($id . ' a bien été supprimé.', 'admin/geocoding/' . $category);
1361 $item = XDB
::fetchOneAssoc('SELECT *
1362 FROM ' . $data['table'] . '
1363 WHERE ' . $data['id'] . ' = {?}',
1368 $page->changeTpl('admin/geocoding_edit.tpl');
1369 $page->setTitle('Administration - ' . ucfirst($data['name']));
1370 $page->assign('category', $category);
1371 $page->assign('name', $data['name']);
1372 $page->assign('all_fields', $all_fields);
1373 $page->assign('id', $id);
1374 $page->assign('iso', $iso);
1375 $page->assign('item', $item);
1379 $page->changeTpl('admin/geocoding.tpl');
1380 $page->setTitle('Administration - ' . ucfirst($data['name']));
1381 $page->assign('category', $category);
1382 $page->assign('name', $data['name']);
1383 $page->assign('id', $data['id']);
1384 $page->assign('main_fields', $data['main_fields']);
1385 $page->assign('all_fields', array_merge($data['main_fields'], $data['other_fields']));
1387 // First build the list provided by the iso codes.
1389 exec('isoquery --iso=' . $data['isocode'], $list);
1391 foreach ($list as $key => $item) {
1392 $array = explode("\t", $item);
1394 $list[$array[0]] = array();
1395 foreach ($data['main_fields'] as $i => $field) {
1396 $list[$array[0]][$field] = $array[$i +
1];
1401 // Retrieve all data from the database.
1402 $db_list = XDB
::rawFetchAllAssoc('SELECT *
1403 FROM ' . $data['table'] . '
1404 ORDER BY ' . $data['id'],
1407 // Sort both iso and database data into 5 categories:
1408 // $missing: data from the iso list not in the database,
1409 // $non_existing: data from the database not in the iso list,
1410 // $erroneous: data that differ on main fields,
1411 // $incomplete: data with empty fields in the data base,
1412 // $remaining: remaining correct and complete data from the database.
1414 $missing = $non_existing = $erroneous = $incomplete = $remaining = array();
1415 foreach (array_keys($list) as $id) {
1416 if (!array_key_exists($id, $db_list)) {
1417 $missing[$id] = $list[$id];
1421 foreach ($db_list as $id => $item) {
1422 if (!array_key_exists($id, $list)) {
1423 $non_existing[$id] = $item;
1426 foreach ($data['main_fields'] as $field) {
1427 if ($item[$field] != $list[$id][$field]) {
1428 $item[$field . '_error'] = true
;
1432 if ($error == true
) {
1433 $erroneous[$id] = $item;
1434 } elseif (call_user_func_array(array('self', 'is' . ucfirst($category) . 'Incomplete'), array(&$item))) {
1435 $incomplete[$id] = $item;
1437 $remaining[$id] = $item;
1442 $page->assign('lists', array(
1443 'manquant' => $missing,
1444 'disparu' => $non_existing,
1445 'erroné' => $erroneous,
1446 'incomplet' => $incomplete,
1447 'restant' => $remaining
1451 function handler_accounts(PlPage
$page)
1453 $page->changeTpl('admin/accounts.tpl');
1454 $page->setTitle('Administration - Comptes');
1456 if (Post
::has('create_account')) {
1457 S
::assert_xsrf_token();
1458 $firstname = Post
::t('firstname');
1459 $lastname = strtoupper(Post
::t('lastname'));
1460 $sex = Post
::s('sex');
1461 $email = Post
::t('email');
1462 $type = Post
::s('type');
1463 $login = PlUser
::makeHrid($firstname, $lastname, $type);
1464 if (!isvalid_email($email)) {
1465 $page->trigError("Invalid email address: $email");
1466 } else if (strlen(Post
::s('pwhash')) != 40) {
1467 $page->trigError("Invalid password hash");
1469 $full_name = $firstname . ' ' . $lastname;
1470 $directory_name = $lastname . ' ' . $firstname;
1471 XDB
::execute("INSERT INTO accounts (hruid, type, state, password,
1472 registration_date, email, full_name,
1473 display_name, sex, directory_name)
1474 VALUES ({?}, {?}, 'active', {?}, NOW(), {?}, {?}, {?}, {?}, {?})",
1475 $login, $type, Post
::s('pwhash'), $email, $full_name, $full_name, $sex,
1480 $uf = new UserFilter(new UFC_AccountType('ax', 'school', 'fx'));
1481 $page->assign('users', $uf->iterUsers());
1485 function handler_account_types($page, $action = 'list', $id = null
)
1487 $page->setTitle('Administration - Types de comptes');
1488 $page->assign('title', 'Gestion des types de comptes');
1489 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true
);
1490 $table_editor->describe('type', 'Catégorie', true
);
1491 $table_editor->describe('perms', 'Permissions associées', true
);
1492 $table_editor->apply($page, $action, $id);
1495 function handler_wiki($page, $action = 'list', $wikipage = null
, $wikipage2 = null
)
1497 if (S
::hasAuthToken()) {
1498 $page->setRssLink('Changement Récents',
1499 '/Site/AllRecentChanges?action=rss&user=' . S
::v('hruid') . '&hash=' . S
::user()->token
);
1502 // update wiki perms
1503 if ($action == 'update') {
1504 S
::assert_xsrf_token();
1506 $perms_read = Post
::v('read');
1507 $perms_edit = Post
::v('edit');
1508 if ($perms_read ||
$perms_edit) {
1509 foreach ($_POST as $wiki_page => $val) {
1511 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1512 if ($wp->setPerms($perms_read ?
$perms_read : $wp->readPerms(),
1513 $perms_edit ?
$perms_edit : $wp->writePerms())) {
1514 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1516 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1521 } else if ($action != 'list' && !empty($wikipage)) {
1522 $wp = new PlWikiPage($wikipage);
1523 S
::assert_xsrf_token();
1525 if ($action == 'delete') {
1526 if ($wp->delete()) {
1527 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1529 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1531 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1532 if ($changedLinks = $wp->rename($wikipage2)) {
1533 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1534 if (is_numeric($changedLinks)) {
1535 $s .= $changedLinks.' lien'.(($changedLinks>1)?
's ont été modifiés.':' a été modifié.');
1537 $page->trigSuccess($s);
1539 $page->trigError("Impossible de déplacer la page ".$wikipage);
1544 $perms = PlWikiPage
::permOptions();
1546 // list wiki pages and their perms
1547 $wiki_pages = PlWikiPage
::listPages();
1549 $wiki_tree = array();
1550 foreach ($wiki_pages as $file => $desc) {
1551 list($cat, $name) = explode('.', $file);
1552 if (!isset($wiki_tree[$cat])) {
1553 $wiki_tree[$cat] = array();
1555 $wiki_tree[$cat][$name] = $desc;
1558 $page->changeTpl('admin/wiki.tpl');
1559 $page->assign('wiki_pages', $wiki_tree);
1560 $page->assign('perms_opts', $perms);
1563 function handler_ipwatch($page, $action = 'list', $ip = null
)
1565 $page->changeTpl('admin/ipwatcher.tpl');
1567 $states = array('safe' => 'Ne pas surveiller',
1568 'unsafe' => 'Surveiller les inscriptions',
1569 'dangerous' => 'Surveiller tous les accès',
1570 'ban' => 'Bannir cette adresse');
1571 $page->assign('states', $states);
1573 switch (Post
::v('action')) {
1575 if (trim(Post
::v('ipN')) != '') {
1576 S
::assert_xsrf_token();
1577 Xdb
::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1578 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1579 ip_to_uint(trim(Post
::v('ipN'))), ip_to_uint(trim(Post
::v('maskN'))),
1580 Post
::v('stateN'), S
::i('uid'), Post
::v('descriptionN'));
1585 S
::assert_xsrf_token();
1586 Xdb
::execute('UPDATE ip_watch
1587 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1588 WHERE ip = {?}', Post
::v('stateN'), S
::i('uid'), Post
::v('descriptionN'),
1589 ip_to_uint(Post
::v('maskN')), ip_to_uint(Post
::v('ipN')));
1593 if ($action == 'delete' && !is_null($ip)) {
1594 S
::assert_xsrf_token();
1595 Xdb
::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1598 if ($action != 'create' && $action != 'edit') {
1601 $page->assign('action', $action);
1603 if ($action == 'list') {
1604 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1605 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1606 IF(w.ip = s.ip, s.host, s.forward_host)),
1607 w.mask, w.detection, w.state, a.hruid
1609 LEFT JOIN log_sessions AS s ON (s.ip = w.ip)
1610 LEFT JOIN log_sessions AS s2 ON (s2.forward_ip = w.ip)
1611 LEFT JOIN accounts AS a ON (a.uid = s.uid)
1612 GROUP BY w.ip, a.hruid
1613 ORDER BY w.state, w.ip, a.hruid";
1614 $it = Xdb
::iterRow($sql);
1618 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1619 $ip = uint_to_ip($ip);
1620 $mask = uint_to_ip($mask);
1621 if (count($props) == 0 ||
$props['ip'] != $ip) {
1622 if (count($props) > 0) {
1625 $props = array('ip' => $ip,
1628 'detection' => $date,
1630 'users' => array($hruid));
1632 $props['users'][] = $hruid;
1635 if (count($props) > 0) {
1638 $page->assign('table', $table);
1639 } elseif ($action == 'edit') {
1640 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1641 a1.hruid AS edit, a2.hruid AS hruid, s.host
1643 LEFT JOIN accounts AS a1 ON (a1.uid = w.uid)
1644 LEFT JOIN log_sessions AS s ON (w.ip = s.ip)
1645 LEFT JOIN accounts AS a2 ON (a2.uid = s.uid)
1649 $it = Xdb
::iterRow($sql, ip_to_uint($ip));
1652 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1653 if (count($props) == 0) {
1654 $props = array('ip' => $ip,
1655 'mask' => uint_to_ip($mask),
1657 'detection' => $detection,
1660 'description' => $description,
1662 'users' => array($hruid));
1664 $props['users'][] = $hruid;
1667 $page->assign('ip', $props);
1671 function handler_icons($page)
1673 $page->changeTpl('admin/icons.tpl');
1674 $dh = opendir('../htdocs/images/icons');
1676 $page->trigError('Dossier des icones introuvables.');
1679 while (($file = readdir($dh)) !== false
) {
1680 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1681 array_push($icons, substr($file, 0, -4));
1685 $page->assign('icons', $icons);
1688 function handler_account_watch($page)
1690 $page->changeTpl('admin/accounts.tpl');
1691 $page->assign('disabled', XDB
::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1692 a.state = \'disabled\' AS disabled, a.comment
1694 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1695 ORDER BY a.hruid'));
1696 $page->assign('admins', XDB
::iterator('SELECT a.hruid
1699 ORDER BY a.hruid'));
1702 function handler_jobs($page, $id = -1)
1704 $page->changeTpl('admin/jobs.tpl');
1706 if (Env
::has('search')) {
1707 $res = XDB
::query("SELECT id, name, acronym
1708 FROM profile_job_enum
1709 WHERE name LIKE CONCAT('%', {?}, '%') OR acronym LIKE CONCAT('%', {?}, '%')",
1710 Env
::t('job'), Env
::t('job'));
1712 if ($res->numRows() <= 20) {
1713 $page->assign('jobs', $res->fetchAllAssoc());
1715 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1718 $page->assign('askedJob', Env
::v('job'));
1722 if (Env
::has('edit')) {
1723 S
::assert_xsrf_token();
1724 $selectedJob = Env
::has('selectedJob');
1726 Phone
::deletePhones(0, Phone
::LINK_COMPANY
, $id);
1727 Address
::deleteAddresses(null
, Address
::LINK_COMPANY
, $id);
1728 if (Env
::has('change')) {
1729 if (Env
::has('newJobId') && Env
::i('newJobId') > 0) {
1730 XDB
::execute('UPDATE profile_job
1733 Env
::i('newJobId'), $id);
1734 XDB
::execute('DELETE FROM profile_job_enum
1738 $page->trigSuccess("L'entreprise a bien été remplacée.");
1740 $page->trigError("L'entreprise n'a pas été remplacée car l'identifiant fourni n'est pas valide.");
1743 XDB
::execute('UPDATE profile_job_enum
1744 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1745 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1747 Env
::t('name'), Env
::t('acronym'), Env
::t('url'), Env
::t('email'),
1748 (Env
::t('NAF_code') == 0 ? null
: Env
::t('NAF_code')),
1749 (Env
::i('AX_code') == 0 ? null
: Env
::t('AX_code')),
1750 (Env
::i('holdingId') == 0 ? null
: Env
::t('holdingId')), $id);
1752 $phone = new Phone(array('display' => Env
::v('tel'), 'link_id' => $id, 'id' => 0, 'type' => 'fixed',
1753 'link_type' => Phone
::LINK_COMPANY
, 'pub' => 'public'));
1754 $fax = new Phone(array('display' => Env
::v('fax'), 'link_id' => $id, 'id' => 1, 'type' => 'fax',
1755 'link_type' => Phone
::LINK_COMPANY
, 'pub' => 'public'));
1756 $address = new Address(array('jobid' => $id, 'type' => Address
::LINK_COMPANY
, 'text' => Env
::t('address')));
1761 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1765 if (!Env
::has('change') && $id != -1) {
1766 $res = XDB
::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1767 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1768 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1769 FROM profile_job_enum AS e
1770 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
1771 LEFT JOIN profile_phones AS t ON (t.pid = e.id AND t.link_type = 'hq' AND t.tel_id = 0)
1772 LEFT JOIN profile_phones AS f ON (f.pid = e.id AND f.link_type = 'hq' AND f.tel_id = 1)
1773 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1777 if ($res->numRows() == 0) {
1778 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1780 $page->assign('selectedJob', $res->fetchOneAssoc());
1785 function handler_profile($page)
1787 $page->changeTpl('admin/profile.tpl');
1789 if (Post
::has('checked')) {
1790 S
::assert_xsrf_token();
1791 $res = XDB
::iterator('SELECT DISTINCT(pm.pid), pd.public_name
1792 FROM profile_modifications AS pm
1793 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1794 WHERE pm.type = \'self\'');
1796 while ($profile = $res->next()) {
1797 if (Post
::has('checked_' . $profile['pid'])) {
1798 XDB
::execute('DELETE FROM profile_modifications
1799 WHERE type = \'self\' AND pid = {?}', $profile['pid']);
1801 $page->trigSuccess('Profil de ' . $profile['public_name'] . ' vérifié.');
1806 $res = XDB
::iterator('SELECT p.hrpid, pm.pid, pd.directory_name, GROUP_CONCAT(pm.field SEPARATOR \', \') AS field
1807 FROM profile_modifications AS pm
1808 INNER JOIN profiles AS p ON (pm.pid = p.pid)
1809 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1810 WHERE pm.type = \'self\'
1811 GROUP BY pd.directory_name
1812 ORDER BY pd.directory_name');
1813 $page->assign('updates', $res);
1817 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: