Also displays errors and warning when adding a file to a ML.
[platal.git] / modules / admin.php
index 5eb630a..4fc5989 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2010 Polytechnique.org                              *
+ *  Copyright (C) 2003-2011 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
@@ -24,58 +24,90 @@ class AdminModule extends PLModule
     function handlers()
     {
         return array(
-            'phpinfo'                      => $this->make_hook('phpinfo',                AUTH_MDP, 'admin'),
-            'get_rights'                   => $this->make_hook('get_rights',             AUTH_MDP, 'admin'),
-            'admin'                        => $this->make_hook('default',                AUTH_MDP, 'admin'),
-            'admin/dead-but-active'        => $this->make_hook('dead_but_active',        AUTH_MDP, 'admin'),
-            'admin/deaths'                 => $this->make_hook('deaths',                 AUTH_MDP, 'admin'),
-            'admin/downtime'               => $this->make_hook('downtime',               AUTH_MDP, 'admin'),
-            'admin/homonyms'               => $this->make_hook('homonyms',               AUTH_MDP, 'admin'),
-            'admin/logger'                 => $this->make_hook('logger',                 AUTH_MDP, 'admin'),
-            'admin/logger/actions'         => $this->make_hook('logger_actions',         AUTH_MDP, 'admin'),
-            'admin/postfix/blacklist'      => $this->make_hook('postfix_blacklist',      AUTH_MDP, 'admin'),
-            'admin/postfix/delayed'        => $this->make_hook('postfix_delayed',        AUTH_MDP, 'admin'),
-            'admin/postfix/regexp_bounces' => $this->make_hook('postfix_regexpsbounces', AUTH_MDP, 'admin'),
-            'admin/postfix/whitelist'      => $this->make_hook('postfix_whitelist',      AUTH_MDP, 'admin'),
-            'admin/mx/broken'              => $this->make_hook('mx_broken',              AUTH_MDP, 'admin'),
-            'admin/skins'                  => $this->make_hook('skins',                  AUTH_MDP, 'admin'),
-            'admin/user'                   => $this->make_hook('user',                   AUTH_MDP, 'admin'),
-            'admin/add_accounts'           => $this->make_hook('add_accounts',           AUTH_MDP, 'admin'),
-            'admin/validate'               => $this->make_hook('validate',               AUTH_MDP, 'admin'),
-            'admin/validate/answers'       => $this->make_hook('validate_answers',       AUTH_MDP, 'admin'),
-            'admin/wiki'                   => $this->make_hook('wiki',                   AUTH_MDP, 'admin'),
-            'admin/ipwatch'                => $this->make_hook('ipwatch',                AUTH_MDP, 'admin'),
-            'admin/icons'                  => $this->make_hook('icons',                  AUTH_MDP, 'admin'),
-            'admin/accounts'               => $this->make_hook('accounts',               AUTH_MDP, 'admin'),
-            'admin/account/types'          => $this->make_hook('account_types',          AUTH_MDP, 'admin'),
-            'admin/jobs'                   => $this->make_hook('jobs',                   AUTH_MDP, 'admin'),
+            'phpinfo'                      => $this->make_hook('phpinfo',                AUTH_PASSWD, 'admin'),
+            'get_rights'                   => $this->make_hook('get_rights',             AUTH_COOKIE, 'admin'),
+            'set_skin'                     => $this->make_hook('set_skin',               AUTH_COOKIE, 'admin'),
+            'admin'                        => $this->make_hook('default',                AUTH_PASSWD, 'admin'),
+            'admin/dead-but-active'        => $this->make_hook('dead_but_active',        AUTH_PASSWD, 'admin'),
+            'admin/deaths'                 => $this->make_hook('deaths',                 AUTH_PASSWD, 'admin'),
+            'admin/downtime'               => $this->make_hook('downtime',               AUTH_PASSWD, 'admin'),
+            'admin/homonyms'               => $this->make_hook('homonyms',               AUTH_PASSWD, 'admin'),
+            'admin/logger'                 => $this->make_hook('logger',                 AUTH_PASSWD, 'admin'),
+            'admin/logger/actions'         => $this->make_hook('logger_actions',         AUTH_PASSWD, 'admin'),
+            'admin/postfix/blacklist'      => $this->make_hook('postfix_blacklist',      AUTH_PASSWD, 'admin'),
+            'admin/postfix/delayed'        => $this->make_hook('postfix_delayed',        AUTH_PASSWD, 'admin'),
+            'admin/postfix/regexp_bounces' => $this->make_hook('postfix_regexpsbounces', AUTH_PASSWD, 'admin'),
+            'admin/postfix/whitelist'      => $this->make_hook('postfix_whitelist',      AUTH_PASSWD, 'admin'),
+            'admin/mx/broken'              => $this->make_hook('mx_broken',              AUTH_PASSWD, 'admin'),
+            'admin/skins'                  => $this->make_hook('skins',                  AUTH_PASSWD, 'admin'),
+            'admin/user'                   => $this->make_hook('user',                   AUTH_PASSWD, 'admin'),
+            'admin/add_accounts'           => $this->make_hook('add_accounts',           AUTH_PASSWD, 'admin'),
+            'admin/validate'               => $this->make_hook('validate',               AUTH_PASSWD, 'admin,edit_directory'),
+            'admin/validate/answers'       => $this->make_hook('validate_answers',       AUTH_PASSWD, 'admin'),
+            'admin/wiki'                   => $this->make_hook('wiki',                   AUTH_PASSWD, 'admin'),
+            'admin/ipwatch'                => $this->make_hook('ipwatch',                AUTH_PASSWD, 'admin'),
+            'admin/icons'                  => $this->make_hook('icons',                  AUTH_PASSWD, 'admin'),
+            'admin/geocoding'              => $this->make_hook('geocoding',              AUTH_PASSWD, 'admin'),
+            'admin/accounts'               => $this->make_hook('accounts',               AUTH_PASSWD, 'admin'),
+            'admin/account/watch'          => $this->make_hook('account_watch',          AUTH_PASSWD, 'admin'),
+            'admin/account/types'          => $this->make_hook('account_types',          AUTH_PASSWD, 'admin'),
+            'admin/xnet_without_group'     => $this->make_hook('xnet_without_group',     AUTH_PASSWD, 'admin'),
+            'admin/jobs'                   => $this->make_hook('jobs',                   AUTH_PASSWD, 'admin,edit_directory'),
+            'admin/profile'                => $this->make_hook('profile',                AUTH_PASSWD, 'admin,edit_directory'),
+            'admin/phd'                    => $this->make_hook('phd',                    AUTH_PASSWD, 'admin'),
+            'admin/name'                   => $this->make_hook('admin_name',             AUTH_PASSWD, 'admin'),
+            'admin/add_secondary_edu'      => $this->make_hook('add_secondary_edu',      AUTH_PASSWD, 'admin')
         );
     }
 
-    function handler_phpinfo(&$page)
+    function handler_phpinfo($page)
     {
         phpinfo();
         exit;
     }
 
-    function handler_get_rights(&$page, $level)
+    function handler_get_rights($page)
     {
         if (S::suid()) {
             $page->kill('Déjà en SUID');
         }
-        $user =& S::user();
-        Platal::session()->startSUID($user, $level);
+        S::assert_xsrf_token();
+        $level = Post::s('account_type');
+        if ($level != 'admin') {
+            $user = User::getSilentWithUID(S::user()->id());
+            $user->is_admin = false;
+            $types = DirEnum::getOptions(DirEnum::ACCOUNTTYPES);
+            if (!empty($types[$level])) {
+                $user->setPerms($types[$level]);
+            }
+            S::set('suid_startpage', $_SERVER['HTTP_REFERER']);
+            Platal::session()->startSUID($user);
+        }
+        if (!empty($_SERVER['HTTP_REFERER'])) {
+            http_redirect($_SERVER['HTTP_REFERER']);
+        } else {
+            pl_redirect('/');
+        }
+    }
 
-        pl_redirect('/');
+    function handler_set_skin($page)
+    {
+        S::assert_xsrf_token();
+        S::set('skin', Post::s('change_skin'));
+        if (!empty($_SERVER['HTTP_REFERER'])) {
+            http_redirect($_SERVER['HTTP_REFERER']);
+        } else {
+            pl_redirect('/');
+        }
     }
 
-    function handler_default(&$page)
+    function handler_default($page)
     {
         $page->changeTpl('admin/index.tpl');
         $page->setTitle('Administration');
     }
 
-    function handler_postfix_delayed(&$page)
+    function handler_postfix_delayed($page)
     {
         $page->changeTpl('admin/postfix_delayed.tpl');
         $page->setTitle('Administration - Postfix : Retardés');
@@ -101,23 +133,6 @@ class AdminModule extends PLModule
         $page->assign_by_ref('mails', $sql);
     }
 
-    function handler_postfix_regexpsbounces(&$page, $new = null) {
-        $page->changeTpl('admin/emails_bounces_re.tpl');
-        $page->setTitle('Administration - Postfix : Regexps Bounces');
-        $page->assign('new', $new);
-
-        if (Post::has('submit')) {
-            foreach (Env::v('lvl') as $id=>$val) {
-                XDB::query(
-                        "REPLACE INTO emails_bounces_re (id,pos,lvl,re,text) VALUES ({?}, {?}, {?}, {?}, {?})",
-                        $id, $_POST['pos'][$id], $_POST['lvl'][$id], $_POST['re'][$id], $_POST['text'][$id]
-                );
-            }
-        }
-
-        $page->assign('bre', XDB::iterator("SELECT * FROM emails_bounces_re ORDER BY pos"));
-    }
-
     // {{{ logger view
 
     /** Retrieves the available days for a given year and month.
@@ -132,7 +147,8 @@ class AdminModule extends PLModule
     function _getDays($year, $month)
     {
         // give a 'no filter' option
-        $months[0] = "----";
+        $days = array();
+        $days[0] = "----";
 
         if ($year && $month) {
             $day_max = Array(-1, 31, checkdate(2, 29, $year) ? 29 : 28 , 31,
@@ -174,6 +190,7 @@ class AdminModule extends PLModule
     function _getMonths($year)
     {
         // give a 'no filter' option
+        $months = array();
         $months[0] = "----";
 
         if ($year) {
@@ -206,6 +223,7 @@ class AdminModule extends PLModule
     function _getYears()
     {
         // give a 'no filter' option
+        $years = array();
         $years[0] = "----";
 
         // retrieve available years
@@ -236,7 +254,7 @@ class AdminModule extends PLModule
         $where = array();
 
         if ($uid)
-            array_push($where, "uid='$uid'");
+            array_push($where, "s.uid='$uid'");
 
         // we were given at least a year
         if ($year) {
@@ -264,14 +282,14 @@ class AdminModule extends PLModule
 
     // }}}
 
-    function handler_logger(&$page, $action = null, $arg = null) {
+    function handler_logger($page, $action = null, $arg = null) {
         if ($action == 'session') {
 
             // we are viewing a session
-            $res = XDB::query("SELECT  ls.*, a.alias AS username, sa.alias AS suer
+            $res = XDB::query("SELECT  ls.*, a.hruid AS username, sa.hruid AS suer
                                  FROM  log_sessions AS ls
-                            LEFT JOIN  aliases   AS a  ON (a.uid = ls.uid AND a.type='a_vie')
-                            LEFT JOIN  aliases   AS sa ON (sa.uid = ls.suid AND sa.type='a_vie')
+                           INNER JOIN  accounts   AS a  ON (a.uid = ls.uid)
+                            LEFT JOIN  accounts   AS sa ON (sa.uid = ls.suid)
                                 WHERE  ls.id = {?}", $arg);
 
             $page->assign('session', $a = $res->fetchOneAssoc());
@@ -287,9 +305,12 @@ class AdminModule extends PLModule
         } else {
             $loguser = $action == 'user' ? $arg : Env::v('loguser');
 
-            $res = XDB::query('SELECT uid FROM aliases WHERE alias={?}',
-                              $loguser);
-            $loguid  = $res->fetchOneCell();
+            if ($loguser) {
+                $user = User::get($loguser);
+                $loguid = $user->id();
+            } else {
+                $loguid = null;
+            }
 
             if ($loguid) {
                 $year  = Env::i('year');
@@ -327,9 +348,9 @@ class AdminModule extends PLModule
                 // get the requested sessions
                 $where  = $this->_makeWhere($year, $month, $day, $loguid);
                 $select = "SELECT  s.id, s.start, s.uid,
-                                   a.alias as username
+                                   a.hruid as username
                              FROM  log_sessions AS s
-                        LEFT JOIN  aliases   AS a  ON (a.uid = s.uid AND a.type='a_vie')
+                       INNER JOIN  accounts   AS a  ON (a.uid = s.uid)
                     $where
                     ORDER BY start DESC";
                 $res = XDB::iterator($select);
@@ -354,7 +375,7 @@ class AdminModule extends PLModule
                 }
                 $page->assign_by_ref('sessions', $sessions);
             } else {
-                $page->assign('msg_nofilters', "Sélectionner une annuée et/ou un utilisateur");
+                $page->assign('msg_nofilters', "Sélectionner une année et/ou un utilisateur");
             }
         }
 
@@ -363,7 +384,7 @@ class AdminModule extends PLModule
         $page->setTitle('Administration - Logs des sessions');
     }
 
-    function handler_user(&$page, $login = false)
+    function handler_user($page, $login = false)
     {
         global $globals;
         $page->changeTpl('admin/user.tpl');
@@ -374,11 +395,14 @@ class AdminModule extends PLModule
         }
 
         // Loads the user identity using the environment.
-        $user = User::get($login);
-        if (!$user) {
-            return;
+        if ($login) {
+            $user = User::get($login);
+        }
+        if (empty($user)) {
+            pl_redirect('admin/accounts');
         }
 
+        $listClient = new MMList(S::user());
         $login = $user->login();
         $registered = ($user->state != 'pending');
 
@@ -391,11 +415,11 @@ class AdminModule extends PLModule
         }
 
         // Handles specific requests (AX sync, su, ...).
-        if(Post::has('logs_account')) {
+        if(Post::has('log_account')) {
             pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
         }
 
-        if(Post::has('su_button') && $registered) {
+        if(Post::has('su_account') && $registered) {
             if (!Platal::session()->startSUID($user)) {
                 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->login());
             } else {
@@ -403,29 +427,71 @@ class AdminModule extends PLModule
             }
         }
 
+        // Handles account deletion.
+        if (Post::has('account_deletion_confirmation')) {
+            $uid = $user->id();
+            $name = $user->fullName();
+            $profile = $user->profile();
+            if ($profile && Post::b('clear_profile')) {
+                $user->profile()->clear();
+            }
+            $user->clear(true);
+            $page->trigSuccess("L'utilisateur $name ($uid) a bien été désinscrit.");
+            if (Post::b('erase_account')) {
+                XDB::execute('DELETE FROM  accounts
+                                    WHERE  uid = {?}',
+                             $uid);
+                $page->trigSuccess("L'utilisateur $name ($uid) a été supprimé de la base de données");
+            }
+        }
+
         // Account Form {{{
+        require_once 'emails.inc.php';
         $to_update = array();
         if (Post::has('disable_weak_access')) {
             $to_update['weak_password'] = null;
         } else if (Post::has('update_account')) {
-            if (Post::s('full_name') != $user->fullName()) {
-                // XXX: Update profile if a profile is associated
-                $to_update['full_name'] = Post::s('full_name');
-            }
-            if (Post::s('display_name') != $user->displayName()) {
-                // XXX: Update profile if a profile is associated
-                $to_update['display_name'] = Post::s('display_name');
+            if (!$user->hasProfile()) {
+                require_once 'name.func.inc.php';
+                $name_update = false;
+                $lastname = capitalize_name(Post::t('lastname'));
+                $firstname = capitalize_name(Post::t('firstname'));
+                if ($lastname != $user->lastname) {
+                    $to_update['lastname'] = $lastname;
+                    $name_update = true;
+                }
+                if (Post::s('type') != 'virtual' && $firstname != $user->firstname) {
+                    $to_update['firstname'] = $firstname;
+                    $name_update = true;
+                }
+                if ($name_update) {
+                    if (Post::s('type') == 'virtual') {
+                        $firstname = '';
+                    }
+                    $to_update['full_name'] = build_full_name($firstname, $lastname);
+                    $to_update['directory_name'] = build_directory_name($firstname, $lastname);
+                    $to_update['sort_name'] = build_sort_name($firstname, $lastname);
+                }
+                if (Post::s('display_name') != $user->displayName()) {
+                    $to_update['display_name'] = Post::s('display_name');
+                }
             }
             if (Post::s('sex') != ($user->isFemale() ? 'female' : 'male')) {
                 $to_update['sex'] = Post::s('sex');
+                if ($user->hasProfile()) {
+                    XDB::execute('UPDATE  profiles
+                                     SET  sex = {?}
+                                   WHERE  pid = {?}',
+                                 Post::s('sex'), $user->profile()->id());
+                }
             }
-            if (!Post::blank('hashpass')) {
-                $to_update['password'] = Post::s('hashpass');
-                // TODO: Propagate the password update to GoogleApps, when required. Eg:
-                // $account = new GoogleAppsAccount($user);
-                // if ($account->active() && $account->sync_password) {
-                //     $account->set_password($pass_encrypted);
-                // }
+            if (!Post::blank('pwhash')) {
+                $to_update['password'] = Post::s('pwhash');
+                require_once 'googleapps.inc.php';
+                $account = new GoogleAppsAccount($user);
+                if ($account->active() && $account->sync_password) {
+                    $account->set_password(Post::s('pwhash'));
+                }
             }
             if (!Post::blank('weak_password')) {
                 $to_update['weak_password'] = Post::s('weak_password');
@@ -433,8 +499,8 @@ class AdminModule extends PLModule
             if (Post::i('token_access', 0) != ($user->token_access ? 1 : 0)) {
                 $to_update['token'] = Post::i('token_access') ? rand_url_id(16) : null;
             }
-            if (Post::i('skin', 0) != $user->skin) {
-                $to_update['skin'] = Post::i('skin', 0);
+            if (Post::i('skin') != $user->skin) {
+                $to_update['skin'] = Post::i('skin');
                 if ($to_update['skin'] == 0) {
                     $to_update['skin'] = null;
                 }
@@ -455,19 +521,51 @@ class AdminModule extends PLModule
             if (Post::t('comment') != $user->comment) {
                 $to_update['comment'] = Post::blank('comment') ? null : Post::t('comment');
             }
+            $new_email = strtolower(Post::t('email'));
+            if (require_email_update($user, $new_email)) {
+                $to_update['email'] = $new_email;
+                $listClient->change_user_email($user->forlifeEmail(), $new_email);
+                update_alias_user($user->forlifeEmail(), $new_email);
+            }
         }
         if (!empty($to_update)) {
-            // TODO: fetch the initial values of the fields, and eventually send
-            // a summary of the changes to an admin.
+            $res = XDB::query('SELECT  *
+                                 FROM  accounts
+                                WHERE  uid = {?}', $user->id());
+            $oldValues = $res->fetchAllAssoc();
+            $oldValues = $oldValues[0];
+
             $set = array();
+            $diff = array();
             foreach ($to_update as $k => $value) {
-                $set[] = XDB::format($k . ' = {?}', $value);
+                $value = XDB::format('{?}', $value);
+                $set[] = $k . ' = ' . $value;
+                $diff[$k] = array($oldValues[$k], trim($value, "'"));
+                unset($oldValues[$k]);
             }
-            XDB::execute('UPDATE  accounts
-                             SET  ' . implode(', ', $set) . ' 
-                           WHERE  uid = ' . XDB::format('{?}', $user->id()));
+            XDB::rawExecute('UPDATE  accounts
+                                SET  ' . implode(', ', $set) . '
+                              WHERE  uid = ' . XDB::format('{?}', $user->id()));
             $page->trigSuccess('Données du compte mise à jour avec succès');
             $user = User::getWithUID($user->id());
+
+            /* Formats the $diff and send it to the site administrators. The rules are the folowing:
+             *  -formats: password, token, weak_password
+             */
+            foreach (array('password', 'token', 'weak_password') as $key) {
+                if (isset($diff[$key])) {
+                    $diff[$key] = array('old value', 'new value');
+                } else {
+                    $oldValues[$key] = 'old value';
+                }
+            }
+
+            $mail = new PlMailer('admin/useredit.mail.tpl');
+            $mail->assign('admin', S::user()->hruid);
+            $mail->assign('hruid', $user->hruid);
+            $mail->assign('diff', $diff);
+            $mail->assign('oldValues', $oldValues);
+            $mail->send();
         }
         // }}}
 
@@ -495,11 +593,10 @@ class AdminModule extends PLModule
         // }}}
 
         // Email forwards form {{{
-        require_once("emails.inc.php");
         $redirect = ($registered ? new Redirect($user) : null);
         if (Post::has('add_fwd')) {
             $email = Post::t('email');
-            if (!isvalid_email_redirection($email)) {
+            if (!isvalid_email_redirection($email, $user)) {
                 $page->trigError("Email non valide: $email");
             } else {
                 $redirect->add_email($email);
@@ -508,9 +605,9 @@ class AdminModule extends PLModule
         } else if (!Post::blank('del_fwd')) {
             $redirect->delete_email(Post::t('del_fwd'));
         } else if (!Post::blank('activate_fwd')) {
-            $redirect->modify_one_email(Post::t('activate_fwd', true));
+            $redirect->modify_one_email(Post::t('activate_fwd'), true);
         } else if (!Post::blank('deactivate_fwd')) {
-            $redirect->modify_one_email(Post::t('deactivate_fwd', false));
+            $redirect->modify_one_email(Post::t('deactivate_fwd'), false);
         } else if (Post::has('disable_fwd')) {
             $redirect->disable();
         } else if (Post::has('enable_fwd')) {
@@ -527,7 +624,7 @@ class AdminModule extends PLModule
             if (strpos($alias, '@') !== false) {
                 list($alias, $domain) = explode('@', $alias);
             } else {
-                $domain = $globals->mail->domain;
+                $domain = $user->mainEmailDomain();
             }
 
             // Checks for alias' user validity.
@@ -539,36 +636,49 @@ class AdminModule extends PLModule
             if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
                 $req = new AliasReq($user, $alias, 'Admin request', false);
                 if ($req->commit()) {
-                    $page->trigSuccess("Nouvel alias '$alias@$domain' attribué");
+                    $page->trigSuccess("Nouvel alias '$alias@$domain' attribué.");
                 } else {
-                    $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué");
+                    $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué.");
                 }
-            } elseif ($domain == $globals->mail->domain || $domain == $globals->mail->domain2) {
-                $res = XDB::execute("INSERT INTO  aliases (uid, alias, type)
-                                          VALUES  ({?}, {?}, 'alias')",
-                                    $user->id(), $alias);
+            } elseif ($domain == $user->mainEmailDomain()) {
+                XDB::execute('INSERT INTO  email_source_account (email, uid, domain, type, flags)
+                                   SELECT  {?}, {?}, id, \'alias\', \'\'
+                                     FROM  email_virtual_domains
+                                    WHERE  name = {?}',
+                              $alias, $user->id(), $domain);
                 $page->trigSuccess("Nouvel alias '$alias' ajouté");
             } else {
-                $page->trigError("Le domaine '$domain' n'est pas valide");
+                $page->trigError("Le domaine '$domain' n'est pas valide pour cet utilisateur.");
             }
         } else if (!Post::blank('del_alias')) {
-            XDB::execute("DELETE FROM  aliases
-                                WHERE  uid = {?} AND alias = {?} AND
-                                       type NOT IN ('a_vie', 'homonyme')",
-                         $user->id(), $val);
-            XDB::execute("UPDATE  emails
-                             SET  rewrite = ''
-                           WHERE  uid = {?} AND rewrite LIKE CONCAT({?}, '@%')",
-                         $user->id(), $val);
+            $delete_alias = Post::t('del_alias');
+            list($email, $domain) = explode('@', $delete_alias);
+            XDB::execute('DELETE  s
+                            FROM  email_source_account  AS s
+                      INNER JOIN  email_virtual_domains AS m ON (s.domain = m.id)
+                      INNER JOIN  email_virtual_domains AS d ON (d.aliasing = m.id)
+                           WHERE  s.email = {?} AND s.uid = {?} AND d.name = {?} AND type != \'forlife\'',
+                          $email, $user->id(), $domain);
+            XDB::execute('UPDATE  email_redirect_account AS r
+                      INNER JOIN  email_virtual_domains  AS m ON (m.name = {?})
+                      INNER JOIN  email_virtual_domains  AS d ON (d.aliasing = m.id)
+                             SET  r.rewrite = \'\'
+                           WHERE  r.uid = {?} AND r.rewrite = CONCAT({?}, \'@\', d.name)',
+                         $domain, $user->id(), $email);
             fix_bestalias($user);
-            $page->trigSuccess("L'alias '$val' a été supprimé");
+            $page->trigSuccess("L'alias '$delete_alias' a été supprimé");
         } else if (!Post::blank('best')) {
-            XDB::execute("UPDATE  aliases
+            $best_alias = Post::t('best');
+            // First delete the bestalias flag from all this user's emails.
+            XDB::execute("UPDATE  email_source_account
                              SET  flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
                            WHERE  uid = {?}", $user->id());
-            XDB::execute("UPDATE  aliases
+            // Then gives the bestalias flag to the given email.
+            list($email, $domain) = explode('@', $best_alias);
+            XDB::execute("UPDATE  email_source_account
                              SET  flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
-                           WHERE  uid = {?} AND alias = {?}", $user->id(), $val);
+                           WHERE  uid = {?} AND email = {?}", $user->id(), $email);
+
             // As having a non-null bestalias value is critical in
             // plat/al's code, we do an a posteriori check on the
             // validity of the bestalias.
@@ -598,8 +708,7 @@ class AdminModule extends PLModule
         // }}}
 
 
-        $page->addJsLink('ui.core.js');
-        $page->addJsLink('ui.tabs.js');
+        $page->addJsLink('jquery.ui.xorg.js');
 
         // Displays last login and last host information.
         $res = XDB::query("SELECT  start, host
@@ -611,16 +720,24 @@ class AdminModule extends PLModule
         $page->assign('lastlogin', $lastlogin);
         $page->assign('host', $host);
 
+        // Display mailing lists
+        $page->assign('mlists', $listClient->get_all_user_lists($user->forlifeEmail()));
+
         // Display active aliases.
-        $page->assign('virtuals', $user->emailAliases());
-        $page->assign('aliases', XDB::iterator("SELECT  alias, type='a_vie' AS for_life,
-                                                        FIND_IN_SET('bestalias',flags) AS best, expire
-                                                  FROM  aliases
-                                                 WHERE  uid = {?} AND type != 'homonyme'
-                                              ORDER BY  type != 'a_vie'", $user->id()));
+        $page->assign('virtuals', $user->emailGroupAliases());
+        $aliases = XDB::iterator("SELECT  CONCAT(s.email, '@', d.name) AS email, (s.type = 'forlife') AS forlife,
+                                          (s.email REGEXP '\\\\.[0-9]{2}$') AS hundred_year,
+                                          FIND_IN_SET('bestalias', s.flags) AS bestalias, s.expire,
+                                          (s.type = 'alias_aux') AS alias
+                                    FROM  email_source_account  AS s
+                              INNER JOIN  email_virtual_domains AS d ON (s.domain = d.id)
+                                   WHERE  s.uid = {?}
+                                ORDER BY  !alias, s.email",
+                                 $user->id());
+        $page->assign('aliases', $aliases);
         $page->assign('account_types', XDB::iterator('SELECT * FROM account_types ORDER BY type'));
         $page->assign('skins', XDB::iterator('SELECT id, name FROM skins ORDER BY name'));
-        $page->assign('profiles', XDB::iterator('SELECT  p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
+        $page->assign('profiles', XDB::iterator('SELECT  p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner, p.ax_id
                                                    FROM  account_profiles AS ap
                                              INNER JOIN  profiles AS p ON (ap.pid = p.pid)
                                                   WHERE  ap.uid = {?}', $user->id()));
@@ -634,6 +751,7 @@ class AdminModule extends PLModule
         }
 
         $page->assign('user', $user);
+        $page->assign('hasProfile', $user->hasProfile());
 
         // Displays forum bans.
         $res = XDB::query("SELECT  write_perm, read_perm, comment
@@ -651,14 +769,15 @@ class AdminModule extends PLModule
         return null;
     }
 
-    private static function formatNewUser($infosLine, $separator, $promo, $size)
+    private static function formatNewUser($page, $infosLine, $separator, $promo, $size)
     {
         $infos = explode($separator, $infosLine);
-        if (sizeof($infos) != $size) {
+        if (sizeof($infos) > $size || sizeof($infos) < 2) {
+            $page->trigError("La ligne $infosLine n'a pas été ajoutée.");
             return false;
         }
 
-        array_map('trim', $infos);
+        $infos = array_map('trim', $infos);
         $hrid = self::getHrid($infos[1], $infos[0], $promo);
         $res1 = XDB::query('SELECT  COUNT(*)
                               FROM  accounts
@@ -667,20 +786,20 @@ class AdminModule extends PLModule
                               FROM  profiles
                              WHERE  hrpid = {?}', $hrid);
         if (is_null($hrid) || $res1->fetchOneCell() > 0 || $res2->fetchOneCell() > 0) {
-            $page->trigError("La ligne $line n'a pas été ajoutée.");
+            $page->trigError("La ligne $infosLine n'a pas été ajoutée: une entrée similaire existe déjà");
             return false;
         }
         $infos['hrid'] = $hrid;
         return $infos;
     }
 
-    private static function formatSex(&$page, $sex, $line)
+    private static function formatSex($page, $sex, $line)
     {
         switch ($sex) {
           case 'F':
-            return PlUser::GENDER_FEMALE;
+            return 'female';
           case 'M':
-            return PlUser::GENDER_MALE;
+            return 'male';
           default:
             $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
             return null;
@@ -689,98 +808,140 @@ class AdminModule extends PLModule
 
     private static function formatBirthDate($birthDate)
     {
-        return date("Y-m-d", strtotime($birthDate));
+        // strtotime believes dd/mm/yyyy to be an US date (i.e mm/dd/yyyy), and
+        // dd-mm-yyyy to be a normal date (i.e dd-mm-yyyy)...
+        return date("Y-m-d", strtotime(str_replace('/', '-', $birthDate)));
     }
 
-    function handler_add_accounts(&$page, $action = null, $promo = null)
+    function handler_add_accounts($page, $action = null, $promo = null)
     {
+        require_once 'name.func.inc.php';
         $page->changeTpl('admin/add_accounts.tpl');
 
         if (Env::has('add_type') && Env::has('people')) {
-            require_once 'directory.enums.inc.php';
+            static $titles = array('male' => 'M', 'female' => 'MLLE');
             $lines = explode("\n", Env::t('people'));
             $separator = Env::t('separator');
             $promotion = Env::i('promotion');
-            $nameTypes = DirEnum::getOptions(DirEnum::NAMETYPES);
-            $nameTypes = array_flip($nameTypes);
 
             if (Env::t('add_type') == 'promo') {
-                $type = 'x';
                 $eduSchools = DirEnum::getOptions(DirEnum::EDUSCHOOLS);
                 $eduSchools = array_flip($eduSchools);
                 $eduDegrees = DirEnum::getOptions(DirEnum::EDUDEGREES);
                 $eduDegrees = array_flip($eduDegrees);
-                var_dump($eduDegrees);
                 switch (Env::t('edu_type')) {
                   case 'X':
                     $degreeid = $eduDegrees[Profile::DEGREE_X];
                     $entry_year = $promotion;
                     $grad_year = $promotion + 3;
                     $promo = 'X' . $promotion;
+                    $hrpromo = $promotion;
+                    $type = 'x';
                     break;
                   case 'M':
                     $degreeid = $eduDegrees[Profile::DEGREE_M];
                     $grad_year = $promotion;
                     $entry_year = $promotion - 2;
                     $promo = 'M' . $promotion;
+                    $hrpromo = $promo;
+                    $type = 'master';
                     break;
                   case 'D':
                     $degreeid = $eduDegrees[Profile::DEGREE_D];
                     $grad_year = $promotion;
                     $entry_year = $promotion - 3;
-                    $promo = 'D' . $promotion;
+                    $promo = 'D (en cours)';
+                    $hrpromo = 'D' . $promotion;
+                    $type = 'phd';
                     break;
                   default:
-                    $page->killError("La formation n'est pas reconnue:" . Env::t('edu_type') . '.');
+                    $page->killError("La formation n'est pas reconnue : " . Env::t('edu_type') . '.');
                 }
+                $best_domain = XDB::fetchOneCell('SELECT  id
+                                                    FROM  email_virtual_domains
+                                                   WHERE  name = {?}',
+                                                 User::$sub_mail_domains[$type] . Platal::globals()->mail->domain);
 
+                XDB::startTransaction();
                 foreach ($lines as $line) {
-                    if (($infos = self::formatNewUser($line, $separator, $promotion, 6))
-                        && ($sex = self::formatSex($page, $infos[3], $line))) {
-                        $name = $infos[1] . ' ' . $infos[0];
-                        $birthDate = self::formatBirthDate($infos[2]);
-                        $xorgId = Profile::getXorgId($infos[4]);
-
-                        XDB::execute('INSERT INTO  profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex)
-                                           VALUES  ({?}, {?}, {?}, {?})',
-                                     $infos['hrid'], $xorgId, $infos[5], $birthDate, $sex);
-                        $pid = XDB::insertId();
-                        XDB::execute('INSERT INTO  profile_name (pid, name, typeid)
-                                           VALUES  ({?}, {?}, {?})',
-                                     $pid, $infos[0], $nameTypes['name_ini']);
-                        XDB::execute('INSERT INTO  profile_name (pid, name, typeid)
-                                           VALUES  ({?}, {?}, {?})',
-                                     $pid, $infos[1], $nameTypes['firstname_ini']);
-                        XDB::execute('INSERT INTO  profile_display (pid, yourself, public_name, private_name,
-                                                                    directory_name, short_name, sort_name, promo)
-                                           VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
-                                     $pid, $infos[1], $name, $name, $name, $name, $infos[0] . ' ' . $infos[1], $promo);
-                        XDB::execute('INSERT INTO  profile_education (pid, eduid, degreeid, entry_year, grad_year, flags)
-                                           VALUES  ({?}, {?}, {?}, {?}, {?}, {?})',
-                                     $pid, $eduSchools[Profile::EDU_X], $degreeid, $entry_year, $grad_year, 'primary');
-                        XDB::execute('INSERT INTO  accounts (hruid, type, is_admin, state, full_name, display_name, sex)
-                                           VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
-                                     $infos['hrid'], $type, 0, 'active', $name, $infos[1], $sex);
-                        $uid = XDB::insertId();
-                        XDB::execute('INSERT INTO  account_profiles (uid, pid, perms)
-                                           VALUES  ({?}, {?}, {?})',
-                                     $uid, $pid, 'owner');
+                    if ($infos = self::formatNewUser($page, $line, $separator, $hrpromo, 6)) {
+                        $sex = self::formatSex($page, $infos[3], $line);
+                        $lastname = capitalize_name($infos[0]);
+                        $firstname = capitalize_name($infos[1]);
+                        if (!is_null($sex)) {
+                            $fullName = build_full_name($firstname, $lastname);
+                            $directoryName = build_directory_name($firstname, $lastname);
+                            $sortName = build_sort_name($firstname, $lastname);
+                            $birthDate = self::formatBirthDate($infos[2]);
+                            if ($type == 'x') {
+                                $xorgId = Profile::getXorgId($infos[4]);
+                            } elseif (isset($infos[4])) {
+                                $xorgId = trim($infos[4]);
+                            } else {
+                                $xorgId = 0;
+                            }
+                            if (is_null($xorgId)) {
+                                $page->trigError("La ligne $line n'a pas été ajoutée car le matricule École est mal renseigné.");
+                                continue;
+                            }
+
+                            XDB::execute('INSERT INTO  profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex, title)
+                                               VALUES  ({?}, {?}, {?}, {?}, {?}, {?})',
+                                         $infos['hrid'], $xorgId, (isset($infos[5]) ? $infos[5] : null),
+                                         $birthDate, $sex, $titles[$sex]);
+                            $pid = XDB::insertId();
+                            XDB::execute('INSERT INTO  profile_public_names (pid, lastname_initial, lastname_main, firstname_initial, firstname_main)
+                                               VALUES  ({?}, {?}, {?}, {?}, {?})',
+                                         $pid, $lastname, $lastname, $firstname, $firstname);
+                            XDB::execute('INSERT INTO  profile_display (pid, yourself, public_name, private_name,
+                                                                        directory_name, short_name, sort_name, promo)
+                                               VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
+                                         $pid, $firstname, $fullName, $fullName, $directoryName, $fullName, $sortName, $promo);
+                            XDB::execute('INSERT INTO  profile_education (id, pid, eduid, degreeid, entry_year, grad_year, promo_year, flags)
+                                               VALUES  (100, {?}, {?}, {?}, {?}, {?}, {?}, \'primary\')',
+                                         $pid, $eduSchools[Profile::EDU_X], $degreeid, $entry_year, $grad_year, $promotion);
+                            XDB::execute('INSERT INTO  accounts (hruid, type, is_admin, state, full_name, directory_name,
+                                                                 display_name, sort_name, lastname, firstname, sex, best_domain)
+                                               VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
+                                         $infos['hrid'], $type, 0, 'pending', $fullName, $directoryName, $sortName,
+                                         $firstname, $lastname, $firstname, $sex, $best_domain);
+                            $uid = XDB::insertId();
+                            XDB::execute('INSERT INTO  account_profiles (uid, pid, perms)
+                                               VALUES  ({?}, {?}, {?})',
+                                         $uid, $pid, 'owner');
+                            Profile::rebuildSearchTokens($pid, false);
+                        }
                     }
                 }
+                XDB::commit();
             } else if (Env::t('add_type') == 'account') {
                 $type = Env::t('type');
+                $newAccounts = array();
                 foreach ($lines as $line) {
-                    if (($infos = self::formatNewUser($line, $separator, $type, 4))
-                        && ($sex = self::formatSex(&$page, $infos[3], $line))) {
-                        XDB::execute('INSERT INTO  accounts (hruid, type, is_admin, state, email, full_name, display_name, sex)
-                                           VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
-                                     $infos['hrid'], $type, 0, 'active', $infos[2], $infos[1] . ' ' . $infos[0], $infos[1], $sex);
+                    if ($infos = self::formatNewUser($page, $line, $separator, $type, 4)) {
+                        $sex = self::formatSex($page, $infos[3], $line);
+                        if (!is_null($sex)) {
+                            $lastname = capitalize_name($infos[0]);
+                            $firstname = capitalize_name($infos[1]);
+                            $fullName = build_full_name($firstname, $lastname);
+                            $directoryName = build_directory_name($firstname, $lastname);
+                            $sortName = build_sort_name($firstname, $lastname);
+                            XDB::execute('INSERT INTO  accounts (hruid, type, is_admin, state, email, full_name, directory_name,
+                                                                 sort_name, display_name, lastname, firstname, sex)
+                                               VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
+                                         $infos['hrid'], $type, 0, 'pending', $infos[2], $fullName, $directoryName,
+                                         $sortName ,$firstname, $lastname, $firstname, $sex);
+                            $newAccounts[$infos['hrid']] = $fullName;
+                        }
                     }
                 }
+                if (!empty($newAccounts)) {
+                    $page->assign('newAccounts', $newAccounts);
+                }
             } else if (Env::t('add_type') == 'ax_id') {
                 $type = 'x';
                 foreach ($lines as $line) {
-                    if ($infos = self::formatNewUser($line, $separator, $promotion, 3)) {
+                    if ($infos = self::formatNewUser($page, $line, $separator, $promotion, 3)) {
                         XDB::execute('UPDATE  profiles
                                          SET  ax_id = {?}
                                        WHERE  hrpid = {?}',
@@ -789,11 +950,12 @@ class AdminModule extends PLModule
                 }
             }
 
-            if ($page->nb_errs == 0) {
+            $errors = $page->nb_errs();
+            if ($errors == 0) {
                 $page->trigSuccess("L'opération a été effectuée avec succès.");
             } else {
-                $page->trigSuccess("L'opération a été effectuée avec succès, sauf pour les "
-                                   . $page->nb_errs . 'erreurs signalées ci-dessus.');
+                $page->trigSuccess('L\'opération a été effectuée avec succès, sauf pour '
+                                   . (($errors == 1) ? 'l\'erreur signalée' : "les $errors erreurs signalées") . ' ci-dessus.');
             }
         } else if (Env::has('add_type')) {
             $res = XDB::query('SELECT  type
@@ -803,15 +965,15 @@ class AdminModule extends PLModule
         }
     }
 
-    function handler_homonyms(&$page, $op = 'list', $target = null)
+    function handler_homonyms($page, $op = 'list', $target = null)
     {
         $page->changeTpl('admin/homonymes.tpl');
         $page->setTitle('Administration - Homonymes');
         $this->load("homonyms.inc.php");
 
         if ($target) {
-            $user = User::getSilent($target);
-            if (!$user || !($loginbis = select_if_homonyme($user))) {
+            $user = User::getSilentWithUID($target);
+            if (!$user || !($loginbis = select_if_homonym($user))) {
                 $target = 0;
             } else {
                 $page->assign('user', $user);
@@ -822,15 +984,14 @@ class AdminModule extends PLModule
         $page->assign('op', $op);
         $page->assign('target', $target);
 
-        // on a un $target valide, on prepare les mails
+        // When we have a valid target, prepare emails.
         if ($target) {
-            // on examine l'op a effectuer
+            // Examine what operation needs to be performed.
             switch ($op) {
                 case 'mail':
                     S::assert_xsrf_token();
 
-                    send_warning_homonyme($user, $loginbis);
-                    switch_bestalias($user, $loginbis);
+                    send_warning_homonym($user, $loginbis);
                     $op = 'list';
                     $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
                     break;
@@ -838,13 +999,8 @@ class AdminModule extends PLModule
                 case 'correct':
                     S::assert_xsrf_token();
 
-                    switch_bestalias($user, $loginbis);
-                    XDB::execute("UPDATE  aliases
-                                     SET  type = 'homonyme', expire=NOW()
-                                   WHERE  alias = {?}", $loginbis);
-                    XDB::execute("REPLACE INTO  homonyms (homonyme_id, uid)
-                                        VALUES  ({?}, {?})", $target, $target);
-                    send_robot_homonyme($user, $loginbis);
+                    fix_homonym($user, $loginbis);
+                    send_robot_homonym($user, $loginbis);
                     $op = 'list';
                     $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
                     break;
@@ -852,25 +1008,44 @@ class AdminModule extends PLModule
         }
 
         if ($op == 'list') {
-            $res = XDB::iterator(
-                    "SELECT  a.alias AS homonyme, s.alias AS forlife,
-                             IF(h.homonyme_id = s.id, a.expire, NULL) AS expire,
-                             IF(h.homonyme_id = s.id, a.type, NULL) AS type, ac.uid
-                       FROM  aliases       AS a
-                  LEFT JOIN  homonyms      AS h  ON (h.homonyme_id = a.uid)
-                 INNER JOIN  aliases       AS s  ON (s.uid = h.uid AND s.type = 'a_vie')
-                 INNER JOIN  accounts      AS ac ON (ac.uid = a.uid)
-                      WHERE  a.type = 'homonyme' OR a.expire != ''
-                   ORDER BY  a.alias, forlife");
-            $hnymes = Array();
-            while ($tab = $res->next()) {
-                $hnymes[$tab['homonyme']][] = $tab;
-            }
-            $page->assign_by_ref('hnymes', $hnymes);
+            // Retrieves homonyms that are already been fixed.
+            $res = XDB::iterator('SELECT  o.email AS homonym, f.email AS forlife, o.expire, f.uid
+                                    FROM  email_source_other    AS o
+                              INNER JOIN  homonyms_list         AS h ON (o.hrmid = h.hrmid)
+                              INNER JOIN  email_source_account  AS f ON (h.uid = f.uid AND f.type = \'forlife\')
+                                   WHERE  o.expire IS NOT NULL
+                                ORDER BY  homonym, forlife');
+            $homonyms = array();
+            while ($item = $res->next()) {
+                $homonyms[$item['homonym']][] = $item;
+            }
+            $page->assign_by_ref('homonyms', $homonyms);
+
+            // Retrieves homonyms that needs to be fixed.
+            $res = XDB::iterator('SELECT  e.email AS homonym, f.email AS forlife, e.expire, e.uid, (e.expire < NOW()) AS urgent
+                                    FROM  email_source_account  AS e
+                              INNER JOIN  homonyms_list         AS l ON (e.uid = l.uid)
+                              INNER JOIN  homonyms_list         AS h ON (l.hrmid = h.hrmid)
+                              INNER JOIN  email_source_account  AS f ON (h.uid = f.uid AND f.type = \'forlife\')
+                                   WHERE  e.expire IS NOT NULL
+                                ORDER BY  homonym, forlife');
+            $homonyms_to_fix = array();
+            while ($item = $res->next()) {
+                $homonyms_to_fix[$item['homonym']][] = $item;
+            }
+            $page->assign_by_ref('homonyms_to_fix', $homonyms_to_fix);
+        }
+
+        if ($op == 'correct-conf') {
+            $page->assign('robot_mail_text', get_robot_mail_text($user, $loginbis));
+        }
+
+        if ($op == 'mail-conf') {
+            $page->assign('warning_mail_text', get_warning_mail_text($user, $loginbis));
         }
     }
 
-    function handler_deaths(&$page, $promo = 0, $validate = false)
+    function handler_deaths($page, $promo = 0, $validate = false)
     {
         $page->changeTpl('admin/deces_promo.tpl');
         $page->setTitle('Administration - Deces');
@@ -886,37 +1061,41 @@ class AdminModule extends PLModule
         if ($validate) {
             S::assert_xsrf_token();
 
-            $res = XDB::iterRow('SELECT  p.hrpid, pd.directory_name, p.deathdate
+            $res = XDB::iterRow('SELECT  p.pid, pd.directory_name, p.deathdate
                                    FROM  profiles AS p
                              INNER JOIN  profile_display AS pd ON (p.pid = pd.pid)
                                   WHERE  pd.promo = {?}', $promo);
             while (list($pid, $name, $death) = $res->next()) {
-                $val = Env::v($pid);
-                if($val == $deces || empty($val)) {
+                $val = Env::v('death_' . $pid);
+                if ($val == $death) {
                     continue;
                 }
 
+                if (empty($val)) {
+                    $val = null;
+                }
                 XDB::execute('UPDATE  profiles
                                  SET  deathdate = {?}, deathdate_rec = NOW()
-                               WHERE  hrpid = {?}', $val, $pid);
-                $page->trigSuccess('Ajout du décès de ' . $name . ' le ' . $val . '.');
-                if($death == '0000-00-00' || empty($death)) {
-                    // TODO: FIX THIS DEPRECATED CALL
-                    require_once('user.func.inc.php');
-                    user_clear_all_subs($uid, false);   // by default, dead ppl do not loose their email
+                               WHERE  pid = {?}', $val, $pid);
+
+                $page->trigSuccess('Édition du décès de ' . $name . ' (' . ($val ? $val : 'ressuscité') . ').');
+                if ($val && ($death == '0000-00-00' || empty($death))) {
+                    $profile = Profile::get($pid);
+                    $profile->clear();
+                    $profile->owner()->clear(false);
                 }
             }
         }
 
-        $res = XDB::iterator('SELECT  p.hrpid, pd.directory_name, p.deathdate
+        $res = XDB::iterator('SELECT  p.pid, pd.directory_name, p.deathdate
                                 FROM  profiles AS p
                           INNER JOIN  profile_display AS pd ON (p.pid = pd.pid)
                                WHERE  pd.promo = {?}
                             ORDER BY  pd.sort_name', $promo);
-        $page->assign('decedes', $res);
+        $page->assign('profileList', $res);
     }
 
-    function handler_dead_but_active(&$page)
+    function handler_dead_but_active($page)
     {
         $page->changeTpl('admin/dead_but_active.tpl');
         $page->setTitle('Administration - Décédés');
@@ -934,17 +1113,16 @@ class AdminModule extends PLModule
         $page->assign('dead', $res);
     }
 
-    function handler_validate(&$page, $action = 'list', $id = null)
+    function handler_validate($page, $action = 'list', $id = null)
     {
-        $page->changeTpl('admin/valider.tpl');
+        $page->changeTpl('admin/validation.tpl');
         $page->setTitle('Administration - Valider une demande');
-                $page->addCssLink('nl.css');
-        $page->addJsLink('ajax.js');
-        require_once("validations.inc.php");
-
+        $page->addCssLink('nl.Polytechnique.org.css');
 
-        if ($action == 'edit' and !is_null($id)) {
+        if ($action == 'edit' && !is_null($id)) {
             $page->assign('preview_id', $id);
+        } else {
+            $page->assign('preview_id', null);
         }
 
         if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
@@ -975,8 +1153,9 @@ class AdminModule extends PLModule
                     $hide[] = $cat;
                 }
             $hide_requests = join(',', $hide);
-            XDB::query('REPLACE INTO  requests_hidden (uid, hidden_requests)
-                              VALUES  ({?}, {?})',
+            XDB::query('INSERT INTO  requests_hidden (uid, hidden_requests)
+                             VALUES  ({?}, {?})
+            ON DUPLICATE KEY UPDATE  hidden_requests = VALUES(hidden_requests)',
                        S::v('uid'), $hide_requests);
         } elseif ($hide_requests)  {
             foreach (explode(',', $hide_requests) as $hide_type)
@@ -988,35 +1167,36 @@ class AdminModule extends PLModule
         // where several copies of the site use the same DB, but not the same "dynamic configuration"
         global $globals;
         $globals->updateNbValid();
-        $page->assign('vit', new ValidateIterator());
+        $page->assign('vit', Validate::iterate());
+        $page->assign('isAdmin', S::admin());
     }
 
-    function handler_validate_answers(&$page, $action = 'list', $id = null)
+    function handler_validate_answers($page, $action = 'list', $id = null)
     {
         $page->setTitle('Administration - Réponses automatiques de validation');
         $page->assign('title', 'Gestion des réponses automatiques');
         $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
         $table_editor->describe('category','catégorie',true);
         $table_editor->describe('title','titre',true);
-        $table_editor->describe('answer','texte',false);
+        $table_editor->describe('answer','texte',false, true);
         $table_editor->apply($page, $action, $id);
     }
 
-    function handler_skins(&$page, $action = 'list', $id = null)
+    function handler_skins($page, $action = 'list', $id = null)
     {
         $page->setTitle('Administration - Skins');
         $page->assign('title', 'Gestion des skins');
         $table_editor = new PLTableEditor('admin/skins','skins','id');
         $table_editor->describe('name','nom',true);
         $table_editor->describe('skin_tpl','nom du template',true);
-        $table_editor->describe('auteur','auteur',false);
+        $table_editor->describe('auteur','auteur',false, true);
         $table_editor->describe('comment','commentaire',true);
-        $table_editor->describe('date','date',false);
-        $table_editor->describe('ext','extension du screenshot',false);
+        $table_editor->describe('date','date',false, true);
+        $table_editor->describe('ext','extension du screenshot',false, true);
         $table_editor->apply($page, $action, $id);
     }
 
-    function handler_postfix_blacklist(&$page, $action = 'list', $id = null)
+    function handler_postfix_blacklist($page, $action = 'list', $id = null)
     {
         $page->setTitle('Administration - Postfix : Blacklist');
         $page->assign('title', 'Blacklist de postfix');
@@ -1026,7 +1206,7 @@ class AdminModule extends PLModule
         $table_editor->apply($page, $action, $id);
     }
 
-    function handler_postfix_whitelist(&$page, $action = 'list', $id = null)
+    function handler_postfix_whitelist($page, $action = 'list', $id = null)
     {
         $page->setTitle('Administration - Postfix : Whitelist');
         $page->assign('title', 'Whitelist de postfix');
@@ -1035,18 +1215,18 @@ class AdminModule extends PLModule
         $table_editor->apply($page, $action, $id);
     }
 
-    function handler_mx_broken(&$page, $action = 'list', $id = null)
+    function handler_mx_broken($page, $action = 'list', $id = null)
     {
         $page->setTitle('Administration - MX Défaillants');
         $page->assign('title', 'MX Défaillant');
         $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true);
         $table_editor->describe('host', 'Masque', true);
         $table_editor->describe('state', 'Niveau', true);
-        $table_editor->describe('text', 'Description du problème', false);
+        $table_editor->describe('text', 'Description du problème', false, true);
         $table_editor->apply($page, $action, $id);
     }
 
-    function handler_logger_actions(&$page, $action = 'list', $id = null)
+    function handler_logger_actions($page, $action = 'list', $id = null)
     {
         $page->setTitle('Administration - Actions');
         $page->assign('title', 'Gestion des actions de logger');
@@ -1056,20 +1236,277 @@ class AdminModule extends PLModule
         $table_editor->apply($page, $action, $id);
     }
 
-    function handler_downtime(&$page, $action = 'list', $id = null)
+    function handler_downtime($page, $action = 'list', $id = null)
     {
         $page->setTitle('Administration - Coupures');
         $page->assign('title', 'Gestion des coupures');
         $table_editor = new PLTableEditor('admin/downtime','downtimes','id');
         $table_editor->describe('debut','date',true);
-        $table_editor->describe('duree','durée',false);
+        $table_editor->describe('duree','durée',false, true);
         $table_editor->describe('resume','résumé',true);
         $table_editor->describe('services','services affectés',true);
-        $table_editor->describe('description','description',false);
+        $table_editor->describe('description','description',false, true);
         $table_editor->apply($page, $action, $id);
     }
 
-    function handler_account_types(&$page, $action = 'list', $id = null) 
+    private static function isCountryIncomplete(array &$item)
+    {
+        $warning = false;
+        foreach (array('worldRegion', 'country', 'capital', 'phonePrefix', 'licensePlate', 'countryPlain') as $field) {
+            if ($item[$field] == '') {
+                $item[$field . '_warning'] = true;
+                $warning = true;
+            }
+        }
+        if (is_null($item['belongsTo'])) {
+            foreach (array('nationality', 'nationalityEn') as $field) {
+                if ($item[$field] == '') {
+                    $item[$field . '_warning'] = true;
+                    $warning = true;
+                }
+            }
+        }
+        return $warning;
+    }
+
+    private static function updateCountry(array $item)
+    {
+        XDB::execute('UPDATE  geoloc_countries
+                         SET  countryPlain = {?}
+                       WHERE  iso_3166_1_a2 = {?}',
+                     mb_strtoupper(replace_accent($item['country'])), $item['iso_3166_1_a2']);
+    }
+
+    private static function isLanguageIncomplete(array &$item)
+    {
+        if ($item['language'] == '') {
+            $item['language_warning'] = true;
+            return true;
+        }
+        return false;
+    }
+
+    private static function updateLanguage(array $item) {}
+
+    function handler_geocoding($page, $category = null, $action = null, $id = null)
+    {
+        // Warning, this handler requires the following packages:
+        //  * pkg-isocodes
+        //  * isoquery
+
+        static $properties = array(
+            'country'  => array(
+                'name'         => 'pays',
+                'isocode'      => '3166',
+                'table'        => 'geoloc_countries',
+                'id'           => 'iso_3166_1_a2',
+                'main_fields'  => array('iso_3166_1_a3', 'iso_3166_1_num', 'countryEn'),
+                'other_fields' => array('worldRegion', 'country', 'capital', 'nationality', 'nationalityEn',
+                                        'phonePrefix', 'phoneFormat', 'licensePlate', 'belongsTo')
+            ),
+            'language' => array(
+                'name'         => 'langages',
+                'isocode'      => '639',
+                'table'        => 'profile_langskill_enum',
+                'id'           => 'iso_639_2b',
+                'main_fields'  => array('iso_639_2t', 'iso_639_1', 'language_en'),
+                'other_fields' => array('language')
+
+            )
+        );
+
+        if (is_null($category) || !array_key_exists($category, $properties)) {
+            pl_redirect('admin');
+        }
+
+        $data = $properties[$category];
+
+        if ($action == 'edit' || $action == 'add') {
+            $main_fields = array_merge(array($data['id']), $data['main_fields']);
+            $all_fields = array_merge($main_fields, $data['other_fields']);
+
+            if (is_null($id)) {
+                if (Post::has('new_id')) {
+                    $id = Post::v('new_id');
+                } else {
+                    pl_redirect('admin/geocoding/' . $category);
+                }
+            }
+
+            $list = array();
+            exec('isoquery --iso=' . $data['isocode'] . ' ' . $id, $list);
+            if (count($list) == 1) {
+                $array = explode("\t", $list[0]);
+                foreach ($main_fields as $i => $field) {
+                    $iso[$field] = $array[$i];
+                }
+            } else {
+                $iso = array();
+            }
+
+            if ($action == 'add') {
+                if (Post::has('new_id')) {
+                    S::assert_xsrf_token();
+                }
+
+                if (count($iso)) {
+                    $item = $iso;
+                } else {
+                    $item = array($data['id'] => $id);
+                }
+                XDB::execute('INSERT INTO  ' . $data['table'] . '(' . implode(', ', array_keys($item)) . ')
+                                   VALUES  ' . XDB::formatArray($item));
+                $page->trigSuccess($id . ' a bien été ajouté à la base.');
+            } elseif ($action == 'edit') {
+                if (Post::has('edit')) {
+                    S::assert_xsrf_token();
+
+                    $item = array();
+                    $set  = array();
+                    foreach ($all_fields as $field) {
+                        $item[$field] = Post::t($field);
+                        $set[] = $field . XDB::format(' = {?}', ($item[$field] ? $item[$field] : null));
+                    }
+                    XDB::execute('UPDATE  ' . $data['table'] . '
+                                     SET  ' . implode(', ', $set) . '
+                                   WHERE  ' . $data['id'] . ' = {?}',
+                                 $id);
+                    call_user_func_array(array('self', 'update' . ucfirst($category)), array($item));
+                    $page->trigSuccess($id . ' a bien été mis à jour.');
+                } elseif (Post::has('del')) {
+                    S::assert_xsrf_token();
+
+                    XDB::execute('DELETE FROM  ' . $data['table'] . '
+                                        WHERE  ' . $data['id'] . ' = {?}',
+                                 $id);
+                    $page->trigSuccessRedirect($id . ' a bien été supprimé.', 'admin/geocoding/' . $category);
+                } else {
+                    $item = XDB::fetchOneAssoc('SELECT  *
+                                                  FROM  ' . $data['table'] . '
+                                                 WHERE  ' . $data['id'] . ' = {?}',
+                                               $id);
+                }
+            }
+
+            $page->changeTpl('admin/geocoding_edit.tpl');
+            $page->setTitle('Administration - ' . ucfirst($data['name']));
+            $page->assign('category', $category);
+            $page->assign('name', $data['name']);
+            $page->assign('all_fields', $all_fields);
+            $page->assign('id', $id);
+            $page->assign('iso', $iso);
+            $page->assign('item', $item);
+            return;
+        }
+
+        $page->changeTpl('admin/geocoding.tpl');
+        $page->setTitle('Administration - ' . ucfirst($data['name']));
+        $page->assign('category', $category);
+        $page->assign('name', $data['name']);
+        $page->assign('id', $data['id']);
+        $page->assign('main_fields', $data['main_fields']);
+        $page->assign('all_fields', array_merge($data['main_fields'], $data['other_fields']));
+
+        // First build the list provided by the iso codes.
+        $list = array();
+        exec('isoquery --iso=' . $data['isocode'], $list);
+
+        foreach ($list as $key => $item) {
+            $array = explode("\t", $item);
+            unset($list[$key]);
+            $list[$array[0]] = array();
+            foreach ($data['main_fields'] as $i => $field) {
+                $list[$array[0]][$field] = $array[$i + 1];
+            }
+        }
+        ksort($list);
+
+        // Retrieve all data from the database.
+        $db_list = XDB::rawFetchAllAssoc('SELECT  *
+                                            FROM  ' . $data['table'] . '
+                                        ORDER BY  ' . $data['id'],
+                                         $data['id']);
+
+        // Sort both iso and database data into 5 categories:
+        //  $missing: data from the iso list not in the database,
+        //  $non_existing: data from the database not in the iso list,
+        //  $erroneous: data that differ on main fields,
+        //  $incomplete: data with empty fields in the data base,
+        //  $remaining: remaining correct and complete data from the database.
+
+        $missing = $non_existing = $erroneous = $incomplete = $remaining = array();
+        foreach (array_keys($list) as $id) {
+            if (!array_key_exists($id, $db_list)) {
+                $missing[$id] = $list[$id];
+            }
+        }
+
+        foreach ($db_list as $id => $item) {
+            if (!array_key_exists($id, $list)) {
+                $non_existing[$id] = $item;
+            } else {
+                $error = false;
+                foreach ($data['main_fields'] as $field) {
+                    if ($item[$field] != $list[$id][$field]) {
+                        $item[$field . '_error'] = true;
+                        $error = true;
+                    }
+                }
+                if ($error == true) {
+                    $erroneous[$id] = $item;
+                } elseif (call_user_func_array(array('self', 'is' . ucfirst($category) . 'Incomplete'), array(&$item))) {
+                    $incomplete[$id] = $item;
+                } else {
+                    $remaining[$id] = $item;
+                }
+            }
+        }
+
+        $page->assign('lists', array(
+                'manquant'  => $missing,
+                'disparu'   => $non_existing,
+                'erroné'    => $erroneous,
+                'incomplet' => $incomplete,
+                'restant'   => $remaining
+        ));
+    }
+
+    function handler_accounts(PlPage $page)
+    {
+        $page->changeTpl('admin/accounts.tpl');
+        $page->setTitle('Administration - Comptes');
+
+        if (Post::has('create_account')) {
+            S::assert_xsrf_token();
+            $firstname = Post::t('firstname');
+            $lastname = mb_strtoupper(Post::t('lastname'));
+            $sex = Post::s('sex');
+            $email = Post::t('email');
+            $type = Post::s('type');
+            $login = PlUser::makeHrid($firstname, $lastname, $type);
+            if (!isvalid_email($email)) {
+                $page->trigError("Invalid email address: $email");
+            } else if (strlen(Post::s('pwhash')) != 40) {
+                $page->trigError("Invalid password hash");
+            } else {
+                $full_name = $firstname . ' ' . $lastname;
+                $directory_name = $lastname . ' ' . $firstname;
+                XDB::execute("INSERT INTO  accounts (hruid, type, state, password,
+                                                     registration_date, email, full_name,
+                                                     display_name, sex, directory_name,
+                                                     lastname, firstname)
+                                   VALUES  ({?}, {?}, 'active', {?}, NOW(), {?}, {?}, {?}, {?}, {?}, {?}, {?})",
+                             $login, $type, Post::s('pwhash'), $email, $full_name, $full_name, $sex,
+                             $directory_name, $lastname, $firstname);
+            }
+        }
+
+        $uf = new UserFilter(new UFC_AccountType('ax', 'school', 'fx'));
+        $page->assign('users', $uf->iterUsers());
+
+    }
+
+    function handler_account_types($page, $action = 'list', $id = null)
     {
         $page->setTitle('Administration - Types de comptes');
         $page->assign('title', 'Gestion des types de comptes');
@@ -1079,11 +1516,11 @@ class AdminModule extends PLModule
         $table_editor->apply($page, $action, $id);
     }
 
-    function handler_wiki(&$page, $action = 'list', $wikipage = null, $wikipage2 = null)
+    function handler_wiki($page, $action = 'list', $wikipage = null, $wikipage2 = null)
     {
         if (S::hasAuthToken()) {
            $page->setRssLink('Changement Récents',
-                             '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::v('token'));
+                             '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::user()->token);
         }
 
         // update wiki perms
@@ -1147,7 +1584,7 @@ class AdminModule extends PLModule
         $page->assign('perms_opts', $perms);
     }
 
-    function handler_ipwatch(&$page, $action = 'list', $ip = null)
+    function handler_ipwatch($page, $action = 'list', $ip = null)
     {
         $page->changeTpl('admin/ipwatcher.tpl');
 
@@ -1255,7 +1692,7 @@ class AdminModule extends PLModule
         }
     }
 
-    function handler_icons(&$page)
+    function handler_icons($page)
     {
         $page->changeTpl('admin/icons.tpl');
         $dh = opendir('../htdocs/images/icons');
@@ -1272,7 +1709,7 @@ class AdminModule extends PLModule
         $page->assign('icons', $icons);
     }
 
-    function handler_accounts(&$page)
+    function handler_account_watch($page)
     {
         $page->changeTpl('admin/accounts.tpl');
         $page->assign('disabled', XDB::iterator('SELECT  a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
@@ -1286,14 +1723,24 @@ class AdminModule extends PLModule
                                              ORDER BY  a.hruid'));
     }
 
-    function handler_jobs(&$page, $id = -1)
+    function handler_xnet_without_group($page)
+    {
+        $page->changeTpl('admin/xnet_without_group.tpl');
+        $page->assign('accounts', XDB::iterator('SELECT  a.hruid, a.state
+                                                   FROM  accounts      AS a
+                                              LEFT JOIN  group_members AS m ON (a.uid = m.uid)
+                                                  WHERE  a.type = \'xnet\' AND m.uid IS NULL
+                                               ORDER BY  a.state, a.hruid'));
+    }
+
+    function handler_jobs($page, $id = -1)
     {
         $page->changeTpl('admin/jobs.tpl');
 
         if (Env::has('search')) {
-            $res = XDB::query("SELECT  e.id, e.name, e.acronym
-                                 FROM  profile_job_enum AS e
-                                WHERE  e.name LIKE CONCAT('% ', {?}, '%') OR e.acronym LIKE CONCAT('% ', {?}, '%')",
+            $res = XDB::query("SELECT  id, name, acronym
+                                 FROM  profile_job_enum
+                                WHERE  name LIKE CONCAT('%', {?}, '%') OR acronym LIKE CONCAT('%', {?}, '%')",
                               Env::t('job'), Env::t('job'));
 
             if ($res->numRows() <= 20) {
@@ -1307,68 +1754,43 @@ class AdminModule extends PLModule
         }
 
         if (Env::has('edit')) {
-            // TODO: use address and phone classes to update profile_job_enum and profile_phones once they are done.
-
             S::assert_xsrf_token();
             $selectedJob = Env::has('selectedJob');
 
-            XDB::execute("DELETE FROM  profile_phones
-                                WHERE  pid = {?} AND link_type = 'hq'",
-                         $id);
-            XDB::execute("DELETE FROM  profile_addresses
-                                WHERE  jobid = {?} AND type = 'hq'",
-                         $id);
-            XDB::execute('DELETE FROM  profile_job_enum
-                                WHERE  id = {?}',
-                         $id);
-
+            Phone::deletePhones(0, Phone::LINK_COMPANY, $id);
+            Address::deleteAddresses(null, Address::LINK_COMPANY, $id);
             if (Env::has('change')) {
-                XDB::execute('UPDATE  profile_job
-                                 SET  jobid = {?}
-                               WHERE  jobid = {?}',
-                             Env::i('newJobId'), $id);
-
-                $page->trigSuccess("L'entreprise a bien été remplacée.");
+                if (Env::has('newJobId') && Env::i('newJobId') > 0) {
+                    XDB::execute('UPDATE  profile_job
+                                     SET  jobid = {?}
+                                   WHERE  jobid = {?}',
+                                 Env::i('newJobId'), $id);
+                    XDB::execute('DELETE FROM  profile_job_enum
+                                        WHERE  id = {?}',
+                                 $id);
+
+                    $page->trigSuccess("L'entreprise a bien été remplacée.");
+                } else {
+                    $page->trigError("L'entreprise n'a pas été remplacée car l'identifiant fourni n'est pas valide.");
+                }
             } else {
-                require_once 'profil.func.inc.php';
-                require_once 'geocoding.inc.php';
-
-                $display_tel = format_display_number(Env::v('tel'), $error_tel);
-                $display_fax = format_display_number(Env::v('fax'), $error_fax);
-                $gmapsGeocoder = new GMapsGeocoder();
-                $address = array('text' => Env::t('address'));
-                $address = $gmapsGeocoder->getGeocodedAddress($address);
-                Geocoder::getAreaId($address, 'administrativeArea');
-                Geocoder::getAreaId($address, 'subAdministrativeArea');
-                Geocoder::getAreaId($address, 'locality');
-
                 XDB::execute('UPDATE  profile_job_enum
                                  SET  name = {?}, acronym = {?}, url = {?}, email = {?},
                                       NAF_code = {?}, AX_code = {?}, holdingid = {?}
                                WHERE  id = {?}',
                              Env::t('name'), Env::t('acronym'), Env::t('url'), Env::t('email'),
-                             Env::t('NAF_code'), Env::i('AX_code'), Env::i('holdingId'), $id);
-
-                XDB::execute("INSERT INTO  profile_phones (pid, link_type, link_id, tel_id, tel_type,
-                                           search_tel, display_tel, pub)
-                                   VALUES  ({?}, 'hq', 0, 0, 'fixed', {?}, {?}, 'public'),
-                                           ({?}, 'hq', 0, 1, 'fax', {?}, {?}, 'public')",
-                             $id, format_phone_number(Env::v('tel')), $display_tel,
-                             $id, format_phone_number(Env::v('fax')), $display_fax);
-
-                XDB::execute("INSERT INTO  profile_addresses (jobid, type, id, accuracy,
-                                                              text, postalText, postalCode, localityId,
-                                                              subAdministrativeAreaId, administrativeAreaId,
-                                                              countryId, latitude, longitude, updateTime,
-                                                              north, south, east, west)
-                                   VALUES  ({?}, 'hq', 0, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
-                                            {?}, {?}, FROM_UNIXTIME({?}), {?}, {?}, {?}, {?})",
-                             $id, $address['accuracy'], $address['text'], $address['postalText'],
-                             $address['postalCode'], $address['localityId'],
-                             $address['subAdministrativeAreaId'], $address['administrativeAreaId'],
-                             $address['countryId'], $address['latitude'], $address['longitude'],
-                             $address['updateTime'], $address['north'], $address['south'],
-                             $address['east'], $address['west']);
+                             (Env::t('NAF_code') == 0 ? null : Env::t('NAF_code')),
+                             (Env::i('AX_code') == 0 ? null : Env::t('AX_code')),
+                             (Env::i('holdingId') == 0 ? null : Env::t('holdingId')), $id);
+
+                $phone = new Phone(array('display' => Env::v('tel'), 'link_id' => $id, 'id' => 0, 'type' => 'fixed',
+                                         'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
+                $fax = new Phone(array('display' => Env::v('fax'), 'link_id' => $id, 'id' => 1, 'type' => 'fax',
+                                         'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
+                $address = new Address(array('jobid' => $id, 'type' => Address::LINK_COMPANY, 'text' => Env::t('address')));
+                $phone->save();
+                $fax->save();
+                $address->save();
 
                 $page->trigSuccess("L'entreprise a bien été mise à jour.");
             }
@@ -1380,8 +1802,8 @@ class AdminModule extends PLModule
                                        t.display_tel AS tel, f.display_tel AS fax, a.text AS address
                                  FROM  profile_job_enum  AS e
                             LEFT JOIN  profile_job_enum  AS h ON (e.holdingid = h.id)
-                            LEFT JOIN  profile_phones    AS t ON (t.pid = e.id AND link_type = 'hq' AND tel_id = 0)
-                            LEFT JOIN  profile_phones    AS f ON (f.pid = e.id AND link_type = 'hq' AND tel_id = 1)
+                            LEFT JOIN  profile_phones    AS t ON (t.pid = e.id AND t.link_type = 'hq' AND t.tel_id = 0)
+                            LEFT JOIN  profile_phones    AS f ON (f.pid = e.id AND f.link_type = 'hq' AND f.tel_id = 1)
                             LEFT JOIN  profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
                                 WHERE  e.id = {?}",
                               $id);
@@ -1393,6 +1815,305 @@ class AdminModule extends PLModule
             }
         }
     }
+
+    function handler_profile($page)
+    {
+        $page->changeTpl('admin/profile.tpl');
+
+        if (Post::has('checked')) {
+            S::assert_xsrf_token();
+            $res = XDB::iterator('SELECT  DISTINCT(pm.pid), pd.public_name
+                                    FROM  profile_modifications AS pm
+                              INNER JOIN  profile_display       AS pd ON (pm.pid = pd.pid)
+                                   WHERE  pm.type = \'self\'');
+
+            while ($profile = $res->next()) {
+                if (Post::has('checked_' . $profile['pid'])) {
+                    XDB::execute('DELETE FROM  profile_modifications
+                                        WHERE  type = \'self\' AND pid = {?}', $profile['pid']);
+
+                    $page->trigSuccess('Profil de ' . $profile['public_name'] . ' vérifié.');
+                }
+            }
+        }
+
+        $res = XDB::iterator('SELECT  p.hrpid, pm.pid, pd.directory_name, GROUP_CONCAT(pm.field SEPARATOR \', \') AS field
+                                FROM  profile_modifications AS pm
+                          INNER JOIN  profiles              AS p  ON (pm.pid = p.pid)
+                          INNER JOIN  profile_display       AS pd ON (pm.pid = pd.pid)
+                               WHERE  pm.type = \'self\'
+                            GROUP BY  pd.directory_name
+                            ORDER BY  pd.directory_name');
+        $page->assign('updates', $res);
+    }
+
+    function handler_phd($page, $promo = null, $validate = false)
+    {
+        $page->changeTpl('admin/phd.tpl');
+        $eduDegrees = DirEnum::getOptions(DirEnum::EDUDEGREES);
+        $eduDegrees = array_flip($eduDegrees);
+
+        if (is_null($promo)) {
+            $promo_list = XDB::fetchColumn('SELECT  DISTINCT(grad_year)
+                                              FROM  profile_education
+                                             WHERE  FIND_IN_SET(\'primary\', flags) AND NOT FIND_IN_SET(\'completed\', flags) AND degreeid = {?}
+                                          ORDER BY  grad_year',
+                                           $eduDegrees[Profile::DEGREE_D]);
+            $page->assign('promo_list', $promo_list);
+            $page->assign('nothing', count($promo_list) == 0);
+            return;
+        }
+
+        if ($validate) {
+            S::assert_xsrf_token();
+
+            $list = XDB::iterator('SELECT  pe.pid, pd.directory_name
+                                     FROM  profile_education AS pe
+                               INNER JOIN  profile_display   AS pd ON (pe.pid = pd.pid)
+                                    WHERE  FIND_IN_SET(\'primary\', pe.flags) AND NOT FIND_IN_SET(\'completed\', pe.flags)
+                                           AND pe.degreeid = {?} AND pe.grad_year = {?}',
+                                  $eduDegrees[Profile::DEGREE_D], $promo);
+            while ($res = $list->next()) {
+                $pid = $res['pid'];
+                $name = $res['directory_name'];
+                if (Post::b('completed_' . $pid)) {
+                    $grad_year = Post::t('grad_year_' . $pid);
+                    XDB::execute('UPDATE  profile_education
+                                     SET  flags = \'primary,completed\', grad_year = {?}
+                                   WHERE  FIND_IN_SET(\'primary\', flags) AND pid = {?}',
+                                 $grad_year, $pid);
+                    XDB::execute('UPDATE  profile_display
+                                     SET  promo = {?}
+                                   WHERE  pid = {?}',
+                                 'D' . $grad_year, $pid);
+                    $page->trigSuccess("Promotion de $name validée.");
+                }
+            }
+        }
+
+        $list = XDB::iterator('SELECT  pe.pid, pd.directory_name
+                                 FROM  profile_education AS pe
+                           INNER JOIN  profile_display   AS pd ON (pe.pid = pd.pid)
+                                WHERE  FIND_IN_SET(\'primary\', pe.flags) AND NOT FIND_IN_SET(\'completed\', pe.flags)
+                                       AND pe.degreeid = {?} AND pe.grad_year = {?}
+                             ORDER BY  pd.directory_name',
+                              $eduDegrees[Profile::DEGREE_D], $promo);
+        $page->assign('list', $list);
+        $page->assign('promo', $promo);
+    }
+
+    function handler_add_secondary_edu($page)
+    {
+        $page->changeTpl('admin/add_secondary_edu.tpl');
+
+        if (!(Post::has('verify') || Post::has('add'))) {
+            return;
+        } elseif (!Post::has('people')) {
+            $page->trigWarning("Aucune information n'a été fournie.");
+            return;
+        }
+
+        require_once 'name.func.inc.php';
+        $lines = explode("\n", Post::t('people'));
+        $separator = Post::t('separator');
+        $degree = Post::v('degree');
+        $promotion = Post::i('promotion');
+        $schoolsList = array_flip(DirEnum::getOptions(DirEnum::EDUSCHOOLS));
+        $degreesList = array_flip(DirEnum::getOptions(DirEnum::EDUDEGREES));
+        $edu_id = $schoolsList[Profile::EDU_X];
+        $degree_id = $degreesList[$degree];
+
+        $res = array(
+            'incomplete' => array(),
+            'empty'      => array(),
+            'multiple'   => array(),
+            'already'    => array(),
+            'new'        => array()
+        );
+        $old_pids = array();
+        $new_pids = array();
+        foreach ($lines as $line) {
+            $line = trim($line);
+            $line_array = explode($separator, $line);
+            array_walk($line_array, 'trim');
+            if (count($line_array) != 3) {
+                $page->trigError("La ligne « $line » est incomplète.");
+                $res['incomplete'][] = $line;
+                continue;
+            }
+            $cond = new PFC_And(new UFC_NameTokens(split_name_for_search($line_array[0]), array(), false, false, Profile::LASTNAME));
+            $cond->addChild(new UFC_NameTokens(split_name_for_search($line_array[1]), array(), false, false, Profile::FIRSTNAME));
+            $cond->addChild(new UFC_Promo('=', UserFilter::DISPLAY, $line_array[2]));
+            $uf = new UserFilter($cond);
+            $pid = $uf->getPIDs();
+            $count = count($pid);
+            if ($count == 0) {
+                $page->trigError("La ligne « $line » ne correspond à aucun profil existant.");
+                $res['empty'][] = $line;
+                continue;
+            } elseif ($count > 1) {
+                $page->trigError("La ligne « $line » correspond à plusieurs profils existant.");
+                $res['multiple'][] = $line;
+                continue;
+            } else {
+                $count = XDB::fetchOneCell('SELECT  COUNT(*) AS count
+                                              FROM  profile_education
+                                             WHERE  pid = {?} AND eduid = {?} AND degreeid = {?}',
+                                      $pid, $edu_id, $degree_id);
+                if ($count == 1) {
+                    $res['already'][] = $line;
+                    $old_pids[] = $pid[0];
+                } else {
+                    $res['new'][] = $line;
+                    $new_pids[] = $pid[0];
+                }
+            }
+        }
+
+        $display = array();
+        foreach ($res as $type => $res_type) {
+            if (count($res_type) > 0) {
+                $display = array_merge($display, array('--------------------' . $type . ':'), $res_type);
+            }
+        }
+        $page->assign('people', implode("\n", $display));
+        $page->assign('promotion', $promotion);
+        $page->assign('degree', $degree);
+
+        if (Post::has('add')) {
+            $entry_year = $promotion - Profile::educationDuration($degree);
+
+            if (Post::b('force_addition')) {
+                $pids = array_unique(array_merge($old_pids, $new_pids));
+            } else {
+                $pids = array_unique($new_pids);
+
+                // Updates years.
+                if (count($old_pids)) {
+                    XDB::execute('UPDATE  profile_education
+                                     SET  entry_year = {?}, grad_year = {?}, promo_year = {?}
+                                   WHERE  pid IN {?} AND eduid = {?} AND degreeid = {?}',
+                                 $entry_year, $promotion, $promotion, $old_pids, $edu_id, $degree_id);
+                }
+            }
+
+            // Precomputes values common to all users.
+            $select = XDB::format('MAX(id) + 1, pid, {?}, {?}, {?}, {?}, {?}, \'secondary\'',
+                                  $edu_id, $degree_id, $entry_year, $promotion, $promotion );
+            XDB::startTransaction();
+            foreach ($pids as $pid) {
+                XDB::execute('INSERT INTO  profile_education (id, pid, eduid, degreeid, entry_year, grad_year, promo_year, flags)
+                                   SELECT  ' . $select . '
+                                     FROM  profile_education
+                                    WHERE  pid = {?}
+                                 GROUP BY  pid',
+                             $pid);
+            }
+            XDB::commit();
+        }
+
+    }
+
+    function handler_admin_name($page, $hruid = null)
+    {
+        $page->changeTpl('admin/admin_name.tpl');
+
+        if (Post::has('id')) {
+            $user = User::get(Post::t('id'));
+            if (is_null($user)) {
+                $page->trigError("L'identifiant donné ne correspond à personne ou est ambigu.");
+                exit();
+            }
+            pl_redirect('admin/name/' . $user->hruid);
+        }
+
+        $user = User::getSilent($hruid);
+        if (!is_null($user)) {
+            require_once 'name.func.inc.php';
+
+            if ($user->hasProfile()) {
+                $name_types = array(
+                    'lastname_main'      => 'Nom patronymique',
+                    'lastname_marital'   => 'Nom marital',
+                    'lastname_ordinary'  => 'Nom usuel',
+                    'firstname_main'     => 'Prénom',
+                    'firstname_ordinary' => 'Prénom usuel',
+                    'pseudonym'          => 'Pseudonyme'
+                );
+                $names = XDB::fetchOneAssoc('SELECT  lastname_main, lastname_marital, lastname_ordinary,
+                                                     firstname_main, firstname_ordinary, pseudonym
+                                               FROM  profile_public_names
+                                              WHERE  pid = {?}',
+                                            $user->profile()->id());
+            } else {
+                $name_types = array(
+                    'lastname'  => 'Nom',
+                    'firstname' => 'Prénom'
+                );
+                $names = XDB::fetchOneAssoc('SELECT  lastname, firstname
+                                               FROM  accounts
+                                              WHERE  uid = {?}',
+                                            $user->id());
+            }
+
+            if (Post::has('correct')) {
+                $new_names = array();
+                $update = true;
+                foreach ($name_types as $key => $fullname) {
+                    $new_names[$key] = Post::t($key);
+                    if (mb_strtolower($new_names[$key]) != mb_strtolower($names[$key])) {
+                        $update = false;
+                    }
+                }
+
+                if ($update) {
+                    if ($user->hasProfile()) {
+                        update_public_names($user->profile()->id(), $new_names);
+                        update_display_names($user->profile(), $new_names);
+                    } else {
+                        $new_names['full_name'] = build_full_name($new_names['firstname'], $new_names['lastname']);
+                        $new_names['directory_name'] = build_directory_name($new_names['firstname'], $new_names['lastname']);
+                        $new_names['sort_name'] = build_sort_name($new_names['firstname'], $new_names['lastname']);
+                        XDB::execute('UPDATE  accounts
+                                         SET  lastname = {?}, firstname = {?}, full_name = {?},
+                                              directory_name = {?}, sort_name = {?}
+                                       WHERE  uid = {?}',
+                                     $new_names['lastname'], $new_names['firstname'], $new_names['full_name'],
+                                     $new_names['directory_name'], $new_names['sort_name'], $user->id());
+                    }
+                    $page->trigSuccess('Mise à jour réussie.');
+                } else {
+                    $page->trigError('Seuls des changements de casse sont autorisés ici.');
+                }
+            }
+
+            if ($user->hasProfile()) {
+                $names = XDB::fetchOneAssoc('SELECT  lastname_main, lastname_marital, lastname_ordinary,
+                                                     firstname_main, firstname_ordinary, pseudonym
+                                               FROM  profile_public_names
+                                              WHERE  pid = {?}',
+                                            $user->profile()->id());
+            } else {
+                $names = XDB::fetchOneAssoc('SELECT  lastname, firstname
+                                               FROM  accounts
+                                              WHERE  uid = {?}',
+                                            $user->id());
+            }
+
+            foreach ($names as $key => $name) {
+                $names[$key] = array(
+                    'value'    => $name,
+                    'standard' => capitalize_name($name)
+                );
+                $names[$key]['different'] = ($names[$key]['value'] != $names[$key]['standard']);
+            }
+
+            $page->assign('uid', $user->id());
+            $page->assign('hruid', $user->hruid);
+            $page->assign('names', $names);
+            $page->assign('name_types', $name_types);
+        }
+    }
 }
 
 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: