2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
22 class AdminModule
extends PLModule
27 'phpinfo' => $this->make_hook('phpinfo', AUTH_MDP
, 'admin'),
28 'get_rights' => $this->make_hook('get_rights', AUTH_COOKIE
, 'admin'),
29 'set_skin' => $this->make_hook('set_skin', AUTH_COOKIE
, 'admin'),
30 'admin' => $this->make_hook('default', AUTH_MDP
, 'admin'),
31 'admin/dead-but-active' => $this->make_hook('dead_but_active', AUTH_MDP
, 'admin'),
32 'admin/deaths' => $this->make_hook('deaths', AUTH_MDP
, 'admin'),
33 'admin/downtime' => $this->make_hook('downtime', AUTH_MDP
, 'admin'),
34 'admin/homonyms' => $this->make_hook('homonyms', AUTH_MDP
, 'admin'),
35 'admin/logger' => $this->make_hook('logger', AUTH_MDP
, 'admin'),
36 'admin/logger/actions' => $this->make_hook('logger_actions', AUTH_MDP
, 'admin'),
37 'admin/postfix/blacklist' => $this->make_hook('postfix_blacklist', AUTH_MDP
, 'admin'),
38 'admin/postfix/delayed' => $this->make_hook('postfix_delayed', AUTH_MDP
, 'admin'),
39 'admin/postfix/regexp_bounces' => $this->make_hook('postfix_regexpsbounces', AUTH_MDP
, 'admin'),
40 'admin/postfix/whitelist' => $this->make_hook('postfix_whitelist', AUTH_MDP
, 'admin'),
41 'admin/mx/broken' => $this->make_hook('mx_broken', AUTH_MDP
, 'admin'),
42 'admin/skins' => $this->make_hook('skins', AUTH_MDP
, 'admin'),
43 'admin/user' => $this->make_hook('user', AUTH_MDP
, 'admin'),
44 'admin/add_accounts' => $this->make_hook('add_accounts', AUTH_MDP
, 'admin'),
45 'admin/validate' => $this->make_hook('validate', AUTH_MDP
, 'admin,edit_directory'),
46 'admin/validate/answers' => $this->make_hook('validate_answers', AUTH_MDP
, 'admin'),
47 'admin/wiki' => $this->make_hook('wiki', AUTH_MDP
, 'admin'),
48 'admin/ipwatch' => $this->make_hook('ipwatch', AUTH_MDP
, 'admin'),
49 'admin/icons' => $this->make_hook('icons', AUTH_MDP
, 'admin'),
50 'admin/geocoding' => $this->make_hook('geocoding', AUTH_MDP
, 'admin'),
51 'admin/accounts' => $this->make_hook('accounts', AUTH_MDP
, 'admin'),
52 'admin/account/watch' => $this->make_hook('account_watch', AUTH_MDP
, 'admin'),
53 'admin/account/types' => $this->make_hook('account_types', AUTH_MDP
, 'admin'),
54 'admin/xnet_without_group' => $this->make_hook('xnet_without_group', AUTH_MDP
, 'admin'),
55 'admin/jobs' => $this->make_hook('jobs', AUTH_MDP
, 'admin,edit_directory'),
56 'admin/profile' => $this->make_hook('profile', AUTH_MDP
, 'admin,edit_directory'),
57 'admin/phd' => $this->make_hook('phd', AUTH_MDP
, 'admin')
61 function handler_phpinfo($page)
67 function handler_get_rights($page)
70 $page->kill('Déjà en SUID');
72 S
::assert_xsrf_token();
73 $level = Post
::s('account_type');
74 if ($level != 'admin') {
75 $user = User
::getSilentWithUID(S
::user()->id());
76 $user->is_admin
= false
;
77 $types = DirEnum
::getOptions(DirEnum
::ACCOUNTTYPES
);
78 if (!empty($types[$level])) {
79 $user->setPerms($types[$level]);
81 S
::set('suid_startpage', $_SERVER['HTTP_REFERER']);
82 Platal
::session()->startSUID($user);
84 if (!empty($_SERVER['HTTP_REFERER'])) {
85 http_redirect($_SERVER['HTTP_REFERER']);
91 function handler_set_skin($page)
93 S
::assert_xsrf_token();
94 S
::set('skin', Post
::s('change_skin'));
95 if (!empty($_SERVER['HTTP_REFERER'])) {
96 http_redirect($_SERVER['HTTP_REFERER']);
102 function handler_default($page)
104 $page->changeTpl('admin/index.tpl');
105 $page->setTitle('Administration');
108 function handler_postfix_delayed($page)
110 $page->changeTpl('admin/postfix_delayed.tpl');
111 $page->setTitle('Administration - Postfix : Retardés');
113 if (Env
::has('del')) {
114 $crc = Env
::v('crc');
115 XDB
::execute("UPDATE postfix_mailseen SET release = 'del' WHERE crc = {?}", $crc);
116 $page->trigSuccess($crc . " verra tous ses emails supprimés !");
117 } elseif (Env
::has('ok')) {
118 $crc = Env
::v('crc');
119 XDB
::execute("UPDATE postfix_mailseen SET release = 'ok' WHERE crc = {?}", $crc);
120 $page->trigSuccess($crc . " a le droit de passer !");
123 $sql = XDB
::iterator(
124 "SELECT crc, nb, update_time, create_time,
125 FIND_IN_SET('del', p.release) AS del,
126 FIND_IN_SET('ok', p.release) AS ok
127 FROM postfix_mailseen AS p
129 ORDER BY p.release != ''");
131 $page->assign_by_ref('mails', $sql);
136 /** Retrieves the available days for a given year and month.
137 * Obtain a list of days of the given month in the given year
138 * that are within the range of dates that we have log entries for.
140 * @param integer year
141 * @param integer month
142 * @return array days in that month we have log entries covering.
145 function _getDays($year, $month)
147 // give a 'no filter' option
151 if ($year && $month) {
152 $day_max = Array(-1, 31, checkdate(2, 29, $year) ?
29 : 28 , 31,
153 30, 31, 30, 31, 31, 30, 31, 30, 31);
154 $res = XDB
::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
155 MONTH(MAX(start)), MONTH(MIN(start)),
156 DAYOFMONTH(MAX(start)),
157 DAYOFMONTH(MIN(start))
159 list($ymax, $ymin, $mmax, $mmin, $dmax, $dmin) = $res->fetchOneRow();
161 if (($year < $ymin) ||
($year == $ymin && $month < $mmin)) {
165 if (($year > $ymax) ||
($year == $ymax && $month > $mmax)) {
169 $min = ($year==$ymin && $month==$mmin) ?
intval($dmin) : 1;
170 $max = ($year==$ymax && $month==$mmax) ?
intval($dmax) : $day_max[$month];
172 for($i = $min; $i<=$max; $i++
) {
180 /** Retrieves the available months for a given year.
181 * Obtains a list of month numbers that are within the timeframe that
182 * we have log entries for.
184 * @param integer year
185 * @return array List of month numbers we have log info for.
188 function _getMonths($year)
190 // give a 'no filter' option
195 $res = XDB
::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
196 MONTH(MAX(start)), MONTH(MIN(start))
198 list($ymax, $ymin, $mmax, $mmin) = $res->fetchOneRow();
200 if (($year < $ymin) ||
($year > $ymax)) {
204 $min = $year == $ymin ?
intval($mmin) : 1;
205 $max = $year == $ymax ?
intval($mmax) : 12;
207 for($i = $min; $i<=$max; $i++
) {
215 /** Retrieves the available years.
216 * Obtains a list of years that we have log entries covering.
218 * @return array years we have log entries for.
223 // give a 'no filter' option
227 // retrieve available years
228 $res = XDB
::query("select YEAR(MAX(start)), YEAR(MIN(start)) FROM log_sessions");
229 list($max, $min) = $res->fetchOneRow();
231 for($i = intval($min); $i<=$max; $i++
) {
238 /** Make a where clause to get a user's sessions.
239 * Prepare the where clause request that will retrieve the sessions.
241 * @param $year INTEGER Only get log entries made during the given year.
242 * @param $month INTEGER Only get log entries made during the given month.
243 * @param $day INTEGER Only get log entries made during the given day.
244 * @param $uid INTEGER Only get log entries referring to the given user ID.
246 * @return STRING the WHERE clause of a query, including the 'WHERE' keyword
249 function _makeWhere($year, $month, $day, $uid)
251 // start constructing the "where" clause
255 array_push($where, "s.uid='$uid'");
257 // we were given at least a year
260 $dmin = mktime(0, 0, 0, $month, $day, $year);
261 $dmax = mktime(0, 0, 0, $month, $day+
1, $year);
263 $dmin = mktime(0, 0, 0, $month, 1, $year);
264 $dmax = mktime(0, 0, 0, $month+
1, 1, $year);
266 $dmin = mktime(0, 0, 0, 1, 1, $year);
267 $dmax = mktime(0, 0, 0, 1, 1, $year+
1);
269 $where[] = "start >= " . date("Ymd000000", $dmin);
270 $where[] = "start < " . date("Ymd000000", $dmax);
273 if (!empty($where)) {
274 return ' WHERE ' . implode($where, " AND ");
278 // WE know it's totally reversed, so better use array_reverse than a SORT BY start DESC
283 function handler_logger($page, $action = null
, $arg = null
) {
284 if ($action == 'session') {
286 // we are viewing a session
287 $res = XDB
::query("SELECT ls.*, a.hruid AS username, sa.hruid AS suer
288 FROM log_sessions AS ls
289 INNER JOIN accounts AS a ON (a.uid = ls.uid)
290 LEFT JOIN accounts AS sa ON (sa.uid = ls.suid)
291 WHERE ls.id = {?}", $arg);
293 $page->assign('session', $a = $res->fetchOneAssoc());
295 $res = XDB
::iterator('SELECT a.text, e.data, e.stamp
297 LEFT JOIN log_actions AS a ON e.action=a.id
298 WHERE e.session={?}', $arg);
299 while ($myarr = $res->next()) {
300 $page->append('events', $myarr);
304 $loguser = $action == 'user' ?
$arg : Env
::v('loguser');
307 $user = User
::get($loguser);
308 $loguid = $user->id();
314 $year = Env
::i('year');
315 $month = Env
::i('month');
316 $day = Env
::i('day');
318 $year = Env
::i('year', intval(date('Y')));
319 $month = Env
::i('month', intval(date('m')));
320 $day = Env
::i('day', intval(date('d')));
328 // smarty assignments
329 // retrieve available years
330 $page->assign('years', $this->_getYears());
331 $page->assign('year', $year);
333 // retrieve available months for the current year
334 $page->assign('months', $this->_getMonths($year));
335 $page->assign('month', $month);
337 // retrieve available days for the current year and month
338 $page->assign('days', $this->_getDays($year, $month));
339 $page->assign('day', $day);
341 $page->assign('loguser', $loguser);
342 // smarty assignments
344 if ($loguid ||
$year) {
346 // get the requested sessions
347 $where = $this->_makeWhere($year, $month, $day, $loguid);
348 $select = "SELECT s.id, s.start, s.uid,
350 FROM log_sessions AS s
351 INNER JOIN accounts AS a ON (a.uid = s.uid)
353 ORDER BY start DESC";
354 $res = XDB
::iterator($select);
357 while ($mysess = $res->next()) {
358 $mysess['events'] = array();
359 $sessions[$mysess['id']] = $mysess;
361 array_reverse($sessions);
364 $sql = "SELECT s.id, a.text
365 FROM log_sessions AS s
366 LEFT JOIN log_events AS e ON(e.session=s.id)
367 INNER JOIN log_actions AS a ON(a.id=e.action)
370 $res = XDB
::iterator($sql);
371 while ($event = $res->next()) {
372 array_push($sessions[$event['id']]['events'], $event['text']);
374 $page->assign_by_ref('sessions', $sessions);
376 $page->assign('msg_nofilters', "Sélectionner une année et/ou un utilisateur");
380 $page->changeTpl('admin/logger-view.tpl');
382 $page->setTitle('Administration - Logs des sessions');
385 function handler_user($page, $login = false
)
388 $page->changeTpl('admin/user.tpl');
389 $page->setTitle('Administration - Compte');
392 $page->kill("Déjà en SUID !!!");
395 // Loads the user identity using the environment.
397 $user = User
::get($login);
400 pl_redirect('admin/accounts');
403 $listClient = new MMList(S
::user());
404 $login = $user->login();
405 $registered = ($user->state
!= 'pending');
408 if (!empty($_POST)) {
409 S
::assert_xsrf_token();
410 if (Post
::has('uid') && Post
::i('uid') != $user->id()) {
411 $page->kill('Une erreur s\'est produite');
415 // Handles specific requests (AX sync, su, ...).
416 if(Post
::has('log_account')) {
417 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
420 if(Post
::has('su_account') && $registered) {
421 if (!Platal
::session()->startSUID($user)) {
422 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->login());
428 // Handles account deletion.
429 if (Post
::has('account_deletion_confirmation')) {
431 $name = $user->fullName();
432 $profile = $user->profile();
433 if ($profile && Post
::b('clear_profile')) {
434 $user->profile()->clear();
437 $page->trigSuccess("L'utilisateur $name ($uid) a bien été désinscrit.");
438 if (Post
::b('erase_account')) {
439 XDB
::execute('DELETE FROM accounts
442 $page->trigSuccess("L'utilisateur $name ($uid) a été supprimé de la base de données");
447 require_once 'emails.inc.php';
448 $to_update = array();
449 if (Post
::has('disable_weak_access')) {
450 $to_update['weak_password'] = null
;
451 } else if (Post
::has('update_account')) {
452 if (!$user->hasProfile()) {
453 if (Post
::s('full_name') != $user->fullName()) {
454 $to_update['full_name'] = Post
::s('full_name');
456 if (Post
::s('display_name') != $user->displayName()) {
457 $to_update['display_name'] = Post
::s('display_name');
459 if (Post
::s('directory_name') != $user->directoryName()) {
460 $to_update['directory_name'] = Post
::s('directory_name');
463 if (Post
::s('sex') != ($user->isFemale() ?
'female' : 'male')) {
464 $to_update['sex'] = Post
::s('sex');
465 if ($user->hasProfile()) {
466 XDB
::execute('UPDATE profiles
469 Post
::s('sex'), $user->profile()->id());
472 if (!Post
::blank('pwhash')) {
473 $to_update['password'] = Post
::s('pwhash');
474 require_once 'googleapps.inc.php';
475 $account = new GoogleAppsAccount($user);
476 if ($account->active() && $account->sync_password
) {
477 $account->set_password(Post
::s('pwhash'));
480 if (!Post
::blank('weak_password')) {
481 $to_update['weak_password'] = Post
::s('weak_password');
483 if (Post
::i('token_access', 0) != ($user->token_access ?
1 : 0)) {
484 $to_update['token'] = Post
::i('token_access') ?
rand_url_id(16) : null
;
486 if (Post
::i('skin') != $user->skin
) {
487 $to_update['skin'] = Post
::i('skin');
488 if ($to_update['skin'] == 0) {
489 $to_update['skin'] = null
;
492 if (Post
::s('state') != $user->state
) {
493 $to_update['state'] = Post
::s('state');
495 if (Post
::i('is_admin', 0) != ($user->is_admin ?
1 : 0)) {
496 $to_update['is_admin'] = Post
::b('is_admin');
498 if (Post
::s('type') != $user->type
) {
499 $to_update['type'] = Post
::s('type');
501 if (Post
::i('watch', 0) != ($user->watch ?
1 : 0)) {
502 $to_update['flags'] = new PlFlagset();
503 $to_update['flags']->addFlag('watch', Post
::i('watch'));
505 if (Post
::t('comment') != $user->comment
) {
506 $to_update['comment'] = Post
::blank('comment') ? null
: Post
::t('comment');
508 if (require_email_update($user, Post
::t('email'))) {
509 $to_update['email'] = Post
::t('email');
510 $listClient->change_user_email($user->forlifeEmail(), Post
::t('email'));
511 update_alias_user($user->forlifeEmail(), Post
::t('email'));
514 if (!empty($to_update)) {
515 $res = XDB
::query('SELECT *
517 WHERE uid = {?}', $user->id());
518 $oldValues = $res->fetchAllAssoc();
519 $oldValues = $oldValues[0];
523 foreach ($to_update as $k => $value) {
524 $value = XDB
::format('{?}', $value);
525 $set[] = $k . ' = ' . $value;
526 $diff[$k] = array($oldValues[$k], trim($value, "'"));
527 unset($oldValues[$k]);
529 XDB
::rawExecute('UPDATE accounts
530 SET ' . implode(', ', $set) . '
531 WHERE uid = ' . XDB
::format('{?}', $user->id()));
532 $page->trigSuccess('Données du compte mise à jour avec succès');
533 $user = User
::getWithUID($user->id());
535 /* Formats the $diff and send it to the site administrators. The rules are the folowing:
536 * -formats: password, token, weak_password
538 foreach (array('password', 'token', 'weak_password') as $key) {
539 if (isset($diff[$key])) {
540 $diff[$key] = array('old value', 'new value');
542 $oldValues[$key] = 'old value';
546 $mail = new PlMailer('admin/useredit.mail.tpl');
547 $mail->assign('admin', S
::user()->hruid
);
548 $mail->assign('hruid', $user->hruid
);
549 $mail->assign('diff', $diff);
550 $mail->assign('oldValues', $oldValues);
556 if (Post
::has('add_profile') || Post
::has('del_profile') || Post
::has('owner')) {
557 if (Post
::i('del_profile', 0) != 0) {
558 XDB
::execute('DELETE FROM account_profiles
559 WHERE uid = {?} AND pid = {?}',
560 $user->id(), Post
::i('del_profile'));
561 } else if (!Post
::blank('new_profile')) {
562 $profile = Profile
::get(Post
::t('new_profile'));
564 $page->trigError('Le profil ' . Post
::t('new_profile') . ' n\'existe pas');
566 XDB
::execute('INSERT IGNORE INTO account_profiles (uid, pid)
568 $user->id(), $profile->id());
571 XDB
::execute('UPDATE account_profiles
572 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
574 Post
::i('owner'), $user->id());
578 // Email forwards form {{{
579 $redirect = ($registered ?
new Redirect($user) : null
);
580 if (Post
::has('add_fwd')) {
581 $email = Post
::t('email');
582 if (!isvalid_email_redirection($email)) {
583 $page->trigError("Email non valide: $email");
585 $redirect->add_email($email);
586 $page->trigSuccess("Ajout de $email effectué");
588 } else if (!Post
::blank('del_fwd')) {
589 $redirect->delete_email(Post
::t('del_fwd'));
590 } else if (!Post
::blank('activate_fwd')) {
591 $redirect->modify_one_email(Post
::t('activate_fwd'), true
);
592 } else if (!Post
::blank('deactivate_fwd')) {
593 $redirect->modify_one_email(Post
::t('deactivate_fwd'), false
);
594 } else if (Post
::has('disable_fwd')) {
595 $redirect->disable();
596 } else if (Post
::has('enable_fwd')) {
598 } else if (!Post
::blank('clean_fwd')) {
599 $redirect->clean_errors(Post
::t('clean_fwd'));
603 // Email alias form {{{
604 if (Post
::has('add_alias')) {
605 // Splits new alias in user and fqdn.
606 $alias = Env
::t('email');
607 if (strpos($alias, '@') !== false
) {
608 list($alias, $domain) = explode('@', $alias);
610 $domain = $user->mainEmailDomain();
613 // Checks for alias' user validity.
614 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
615 $page->trigError("'$alias' n'est pas un alias valide");
618 // Eventually adds the alias to the right domain.
619 if ($domain == $globals->mail
->alias_dom ||
$domain == $globals->mail
->alias_dom2
) {
620 $req = new AliasReq($user, $alias, 'Admin request', false
);
621 if ($req->commit()) {
622 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué.");
624 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué.");
626 } elseif ($domain == $user->mainEmailDomain()) {
627 XDB
::execute('INSERT INTO email_source_account (email, uid, domain, type, flags)
628 SELECT {?}, {?}, id, \'alias\', \'\'
629 FROM email_virtual_domains
631 $alias, $user->id(), $domain);
632 $page->trigSuccess("Nouvel alias '$alias' ajouté");
634 $page->trigError("Le domaine '$domain' n'est pas valide pour cet utilisateur.");
636 } else if (!Post
::blank('del_alias')) {
637 $delete_alias = Post
::t('del_alias');
638 list($email, $domain) = explode('@', $delete_alias);
639 XDB
::execute('DELETE s
640 FROM email_source_account AS s
641 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
642 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
643 WHERE s.email = {?} AND s.uid = {?} AND d.name = {?} AND type != \'forlife\'',
644 $email, $user->id(), $domain);
645 XDB
::execute('UPDATE email_redirect_account AS r
646 INNER JOIN email_virtual_domains AS m ON (m.name = {?})
647 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
649 WHERE r.uid = {?} AND r.rewrite = CONCAT({?}, \'@\', d.name)',
650 $domain, $user->id(), $email);
651 fix_bestalias($user);
652 $page->trigSuccess("L'alias '$delete_alias' a été supprimé");
653 } else if (!Post
::blank('best')) {
654 $best_alias = Post
::t('best');
655 // First delete the bestalias flag from all this user's emails.
656 XDB
::execute("UPDATE email_source_account
657 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
658 WHERE uid = {?}", $user->id());
659 // Then gives the bestalias flag to the given email.
660 list($email, $domain) = explode('@', $best_alias);
661 XDB
::execute("UPDATE email_source_account
662 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
663 WHERE uid = {?} AND email = {?}", $user->id(), $email);
665 // As having a non-null bestalias value is critical in
666 // plat/al's code, we do an a posteriori check on the
667 // validity of the bestalias.
668 fix_bestalias($user);
673 if (Post
::has('del_openid')) {
674 XDB
::execute('DELETE FROM account_auth_openid
675 WHERE id = {?}', Post
::i('del_openid'));
680 if (Post
::has('b_edit')) {
681 XDB
::execute("DELETE FROM forum_innd
682 WHERE uid = {?}", $user->id());
683 if (Env
::v('write_perm') != "" || Env
::v('read_perm') != "" || Env
::v('commentaire') != "" ) {
684 XDB
::execute("INSERT INTO forum_innd
685 SET ipmin = '0', ipmax = '4294967295',
686 write_perm = {?}, read_perm = {?},
687 comment = {?}, priority = '200', uid = {?}",
688 Env
::v('write_perm'), Env
::v('read_perm'), Env
::v('comment'), $user->id());
694 $page->addJsLink('jquery.ui.xorg.js');
696 // Displays last login and last host information.
697 $res = XDB
::query("SELECT start, host
699 WHERE uid = {?} AND suid = 0
701 LIMIT 1", $user->id());
702 list($lastlogin,$host) = $res->fetchOneRow();
703 $page->assign('lastlogin', $lastlogin);
704 $page->assign('host', $host);
706 // Display mailing lists
707 $page->assign('mlists', $listClient->get_all_user_lists($user->forlifeEmail()));
709 // Display active aliases.
710 $page->assign('virtuals', $user->emailGroupAliases());
711 $aliases = XDB
::iterator("SELECT CONCAT(s.email, '@', d.name) AS email, (s.type = 'forlife') AS forlife,
712 (s.email REGEXP '\\\\.[0-9]{2}$') AS hundred_year,
713 FIND_IN_SET('bestalias', s.flags) AS bestalias, s.expire,
714 (s.type = 'alias_aux') AS alias
715 FROM email_source_account AS s
716 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
718 ORDER BY !alias, s.email",
720 $page->assign('aliases', $aliases);
721 $page->assign('account_types', XDB
::iterator('SELECT * FROM account_types ORDER BY type'));
722 $page->assign('skins', XDB
::iterator('SELECT id, name FROM skins ORDER BY name'));
723 $page->assign('profiles', XDB
::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
724 FROM account_profiles AS ap
725 INNER JOIN profiles AS p ON (ap.pid = p.pid)
726 WHERE ap.uid = {?}', $user->id()));
727 $page->assign('openid', XDB
::iterator('SELECT id, url
728 FROM account_auth_openid
729 WHERE uid = {?}', $user->id()));
731 // Displays email redirection and the general profile.
732 if ($registered && $redirect) {
733 $page->assign('emails', $redirect->emails
);
736 $page->assign('user', $user);
737 $page->assign('hasProfile', $user->hasProfile());
739 // Displays forum bans.
740 $res = XDB
::query("SELECT write_perm, read_perm, comment
742 WHERE uid = {?}", $user->id());
743 $bans = $res->fetchOneAssoc();
744 $page->assign('bans', $bans);
747 private static function getHrid($firstname, $lastname, $promo)
749 if ($firstname != null
&& $lastname != null
&& $promo != null
) {
750 return User
::makeHrid($firstname, $lastname, $promo);
755 private static function formatNewUser($page, $infosLine, $separator, $promo, $size)
757 $infos = explode($separator, $infosLine);
758 if (sizeof($infos) > $size ||
sizeof($infos) < 2) {
759 $page->trigError("La ligne $infosLine n'a pas été ajoutée.");
763 $infos = array_map('trim', $infos);
764 $hrid = self
::getHrid($infos[1], $infos[0], $promo);
765 $res1 = XDB
::query('SELECT COUNT(*)
767 WHERE hruid = {?}', $hrid);
768 $res2 = XDB
::query('SELECT COUNT(*)
770 WHERE hrpid = {?}', $hrid);
771 if (is_null($hrid) ||
$res1->fetchOneCell() > 0 ||
$res2->fetchOneCell() > 0) {
772 $page->trigError("La ligne $infosLine n'a pas été ajoutée: une entrée similaire existe déjà");
775 $infos['hrid'] = $hrid;
779 private static function formatSex($page, $sex, $line)
787 $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
792 private static function formatBirthDate($birthDate)
794 // strtotime believes dd/mm/yyyy to be an US date (i.e mm/dd/yyyy), and
795 // dd-mm-yyyy to be a normal date (i.e dd-mm-yyyy)...
796 return date("Y-m-d", strtotime(str_replace('/', '-', $birthDate)));
799 function handler_add_accounts($page, $action = null
, $promo = null
)
801 $page->changeTpl('admin/add_accounts.tpl');
803 if (Env
::has('add_type') && Env
::has('people')) {
804 $lines = explode("\n", Env
::t('people'));
805 $separator = Env
::t('separator');
806 $promotion = Env
::i('promotion');
807 $nameTypes = DirEnum
::getOptions(DirEnum
::NAMETYPES
);
808 $nameTypes = array_flip($nameTypes);
810 if (Env
::t('add_type') == 'promo') {
811 $eduSchools = DirEnum
::getOptions(DirEnum
::EDUSCHOOLS
);
812 $eduSchools = array_flip($eduSchools);
813 $eduDegrees = DirEnum
::getOptions(DirEnum
::EDUDEGREES
);
814 $eduDegrees = array_flip($eduDegrees);
815 switch (Env
::t('edu_type')) {
817 $degreeid = $eduDegrees[Profile
::DEGREE_X
];
818 $entry_year = $promotion;
819 $grad_year = $promotion +
3;
820 $promo = 'X' . $promotion;
821 $hrpromo = $promotion;
825 $degreeid = $eduDegrees[Profile
::DEGREE_M
];
826 $grad_year = $promotion;
827 $entry_year = $promotion - 2;
828 $promo = 'M' . $promotion;
833 $degreeid = $eduDegrees[Profile
::DEGREE_D
];
834 $grad_year = $promotion;
835 $entry_year = $promotion - 3;
836 $promo = 'D (en cours)';
841 $page->killError("La formation n'est pas reconnue : " . Env
::t('edu_type') . '.');
844 XDB
::startTransaction();
845 foreach ($lines as $line) {
846 if ($infos = self
::formatNewUser($page, $line, $separator, $hrpromo, 6)) {
847 $sex = self
::formatSex($page, $infos[3], $line);
848 if (!is_null($sex)) {
849 $fullName = $infos[1] . ' ' . $infos[0];
850 $directoryName = $infos[0] . ' ' . $infos[1];
851 $birthDate = self
::formatBirthDate($infos[2]);
853 $xorgId = Profile
::getXorgId($infos[4]);
854 } elseif (isset($infos[4])) {
855 $xorgId = trim($infos[4]);
859 if (is_null($xorgId)) {
860 $page->trigError("La ligne $line n'a pas été ajoutée car le matricule École est mal renseigné.");
864 XDB
::execute('INSERT INTO profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex)
865 VALUES ({?}, {?}, {?}, {?}, {?})',
866 $infos['hrid'], $xorgId, (isset($infos[5]) ?
$infos[5] : null
), $birthDate, $sex);
867 $pid = XDB
::insertId();
868 XDB
::execute('INSERT INTO profile_name (pid, name, typeid)
869 VALUES ({?}, {?}, {?}),
873 $pid, $infos[0], $nameTypes['name_ini'],
874 $pid, $infos[0], $nameTypes['lastname'],
875 $pid, $infos[1], $nameTypes['firstname_ini'],
876 $pid, $infos[1], $nameTypes['firstname']);
877 XDB
::execute('INSERT INTO profile_display (pid, yourself, public_name, private_name,
878 directory_name, short_name, sort_name, promo)
879 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
880 $pid, $infos[1], $fullName, $fullName, $directoryName, $fullName, $directoryName, $promo);
881 XDB
::execute('INSERT INTO profile_education (id, pid, eduid, degreeid, entry_year, grad_year, flags)
882 VALUES (100, {?}, {?}, {?}, {?}, {?}, \'primary\')',
883 $pid, $eduSchools[Profile
::EDU_X
], $degreeid, $entry_year, $grad_year);
884 XDB
::execute('INSERT INTO accounts (hruid, type, is_admin, state, full_name, directory_name, display_name, sex)
885 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
886 $infos['hrid'], $type, 0, 'pending', $fullName, $directoryName, $infos[1], $sex);
887 $uid = XDB
::insertId();
888 XDB
::execute('INSERT INTO account_profiles (uid, pid, perms)
889 VALUES ({?}, {?}, {?})',
890 $uid, $pid, 'owner');
891 Profile
::rebuildSearchTokens($pid, false
);
896 } else if (Env
::t('add_type') == 'account') {
897 $type = Env
::t('type');
898 $newAccounts = array();
899 foreach ($lines as $line) {
900 if ($infos = self
::formatNewUser($page, $line, $separator, $type, 4)) {
901 $sex = self
::formatSex($page, $infos[3], $line);
902 if (!is_null($sex)) {
903 $fullName = $infos[1] . ' ' . $infos[0];
904 $directoryName = $infos[0] . ' ' . $infos[1];
905 XDB
::execute('INSERT INTO accounts (hruid, type, is_admin, state,
906 email, full_name, directory_name,
908 VALUES ({?}, {?}, {?}, {?},
909 {?}, {?}, {?}, {?}, {?})',
910 $infos['hrid'], $type, 0, 'pending',
911 $infos[2], $fullName, $directoryName,
913 $newAccounts[$infos['hrid']] = $infos[1] . ' ' . $infos[0];
917 if (!empty($newAccounts)) {
918 $page->assign('newAccounts', $newAccounts);
920 } else if (Env
::t('add_type') == 'ax_id') {
922 foreach ($lines as $line) {
923 if ($infos = self
::formatNewUser($page, $line, $separator, $promotion, 3)) {
924 XDB
::execute('UPDATE profiles
927 $infos[2], $infos['hrid']);
932 $errors = $page->nb_errs();
934 $page->trigSuccess("L'opération a été effectuée avec succès.");
936 $page->trigSuccess('L\'opération a été effectuée avec succès, sauf pour '
937 . (($errors == 1) ?
'l\'erreur signalée' : "les $errors erreurs signalées") . ' ci-dessus.');
939 } else if (Env
::has('add_type')) {
940 $res = XDB
::query('SELECT type
941 FROM account_types');
942 $page->assign('account_types', $res->fetchColumn());
943 $page->assign('add_type', Env
::s('add_type'));
947 function handler_homonyms($page, $op = 'list', $target = null
)
949 $page->changeTpl('admin/homonymes.tpl');
950 $page->setTitle('Administration - Homonymes');
951 $this->load("homonyms.inc.php");
954 $user = User
::getSilentWithUID($target);
955 if (!$user ||
!($loginbis = select_if_homonym($user))) {
958 $page->assign('user', $user);
959 $page->assign('loginbis',$loginbis);
963 $page->assign('op', $op);
964 $page->assign('target', $target);
966 // When we have a valid target, prepare emails.
968 require_once 'emails.inc.php';
969 // Examine what operation needs to be performed.
972 S
::assert_xsrf_token();
974 send_warning_homonyme($user, $loginbis);
975 fix_bestalias($user);
977 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
981 S
::assert_xsrf_token();
983 XDB
::execute('DELETE FROM email_source_account
984 WHERE email = {?} AND type = \'alias\'',
986 XDB
::execute('INSERT INTO email_source_other (hrmid, email, domain, type, expire)
987 SELECT {?}, {?}, id, \'homonym\', NOW()
988 FROM email_virtual_domains
990 User
::makeHomonymHrmid($loginbis), $loginbis, $user->mainEmailDomain());
991 fix_bestalias($user);
992 send_robot_homonyme($user, $loginbis);
994 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
1000 // Retrieves homonyms that are already been fixed.
1001 $res = XDB
::iterator('SELECT o.email AS homonym, f.email AS forlife, o.expire, f.uid
1002 FROM email_source_other AS o
1003 INNER JOIN homonyms_list AS h ON (o.hrmid = h.hrmid)
1004 INNER JOIN email_source_account AS f ON (h.uid = f.uid AND f.type = \'forlife\')
1005 WHERE o.expire IS NOT NULL
1006 ORDER BY homonym, forlife');
1007 $homonyms = array();
1008 while ($item = $res->next()) {
1009 $homonyms[$item['homonym']][] = $item;
1011 $page->assign_by_ref('homonyms', $homonyms);
1013 // Retrieves homonyms that needs to be fixed.
1014 $res = XDB
::iterator('SELECT e.email AS homonym, f.email AS forlife, e.expire, e.uid, (e.expire < NOW()) AS urgent
1015 FROM email_source_account AS e
1016 INNER JOIN homonyms_list AS l ON (e.uid = l.uid)
1017 INNER JOIN homonyms_list AS h ON (l.hrmid = h.hrmid)
1018 INNER JOIN email_source_account AS f ON (h.uid = f.uid AND f.type = \'forlife\')
1019 WHERE e.expire IS NOT NULL
1020 ORDER BY homonym, forlife');
1021 $homonyms_to_fix = array();
1022 while ($item = $res->next()) {
1023 $homonyms_to_fix[$item['homonym']][] = $item;
1025 $page->assign_by_ref('homonyms_to_fix', $homonyms_to_fix);
1029 function handler_deaths($page, $promo = 0, $validate = false
)
1031 $page->changeTpl('admin/deces_promo.tpl');
1032 $page->setTitle('Administration - Deces');
1035 $promo = Env
::t('promo', 'X1923');
1037 $page->assign('promo', $promo);
1043 S
::assert_xsrf_token();
1045 $res = XDB
::iterRow('SELECT p.pid, pd.directory_name, p.deathdate
1047 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1048 WHERE pd.promo = {?}', $promo);
1049 while (list($pid, $name, $death) = $res->next()) {
1050 $val = Env
::v('death_' . $pid);
1051 if ($val == $death) {
1058 XDB
::execute('UPDATE profiles
1059 SET deathdate = {?}, deathdate_rec = NOW()
1060 WHERE pid = {?}', $val, $pid);
1062 $page->trigSuccess('Édition du décès de ' . $name . ' (' . ($val ?
$val : 'ressuscité') . ').');
1063 if ($val && ($death == '0000-00-00' ||
empty($death))) {
1064 $profile = Profile
::get($pid);
1066 $profile->owner()->clear(false
);
1071 $res = XDB
::iterator('SELECT p.pid, pd.directory_name, p.deathdate
1073 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1074 WHERE pd.promo = {?}
1075 ORDER BY pd.sort_name', $promo);
1076 $page->assign('profileList', $res);
1079 function handler_dead_but_active($page)
1081 $page->changeTpl('admin/dead_but_active.tpl');
1082 $page->setTitle('Administration - Décédés');
1084 $res = XDB
::iterator(
1085 "SELECT a.hruid, pd.promo, p.ax_id, pd.directory_name, p.deathdate, DATE(MAX(s.start)) AS last
1087 INNER JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET('owner', ap.perms))
1088 INNER JOIN profiles AS p ON (p.pid = ap.pid)
1089 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
1090 LEFT JOIN log_sessions AS s ON (s.uid = a.uid AND suid = 0)
1091 WHERE a.state = 'active' AND p.deathdate IS NOT NULL
1093 ORDER BY pd.promo, pd.sort_name");
1094 $page->assign('dead', $res);
1097 function handler_validate($page, $action = 'list', $id = null
)
1099 $page->changeTpl('admin/validation.tpl');
1100 $page->setTitle('Administration - Valider une demande');
1101 $page->addCssLink('nl.Polytechnique.org.css');
1103 if ($action == 'edit' && !is_null($id)) {
1104 $page->assign('preview_id', $id);
1106 $page->assign('preview_id', null
);
1109 if(Env
::has('uid') && Env
::has('type') && Env
::has('stamp')) {
1110 S
::assert_xsrf_token();
1112 $req = Validate
::get_typed_request(Env
::v('uid'), Env
::v('type'), Env
::v('stamp'));
1114 $req->handle_formu();
1116 $page->trigWarning('La validation a déjà été effectuée.');
1120 $r = XDB
::iterator('SHOW COLUMNS FROM requests_answers');
1121 while (($a = $r->next()) && $a['Field'] != 'category');
1122 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
1125 $res = XDB
::query('SELECT hidden_requests
1126 FROM requests_hidden
1127 WHERE uid = {?}', S
::v('uid'));
1128 $hide_requests = $res->fetchOneCell();
1129 if (Post
::has('hide')) {
1131 foreach ($categories as $cat)
1132 if (!Post
::v($cat)) {
1136 $hide_requests = join(',', $hide);
1137 XDB
::query('INSERT INTO requests_hidden (uid, hidden_requests)
1139 ON DUPLICATE KEY UPDATE hidden_requests = VALUES(hidden_requests)',
1140 S
::v('uid'), $hide_requests);
1141 } elseif ($hide_requests) {
1142 foreach (explode(',', $hide_requests) as $hide_type)
1143 $hidden[$hide_type] = true
;
1145 $page->assign('hide_requests', $hidden);
1147 // Update the count of item to validate here... useful in development configuration
1148 // where several copies of the site use the same DB, but not the same "dynamic configuration"
1150 $globals->updateNbValid();
1151 $page->assign('vit', Validate
::iterate());
1152 $page->assign('isAdmin', S
::admin());
1155 function handler_validate_answers($page, $action = 'list', $id = null
)
1157 $page->setTitle('Administration - Réponses automatiques de validation');
1158 $page->assign('title', 'Gestion des réponses automatiques');
1159 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
1160 $table_editor->describe('category','catégorie',true
);
1161 $table_editor->describe('title','titre',true
);
1162 $table_editor->describe('answer','texte',false
);
1163 $table_editor->apply($page, $action, $id);
1166 function handler_skins($page, $action = 'list', $id = null
)
1168 $page->setTitle('Administration - Skins');
1169 $page->assign('title', 'Gestion des skins');
1170 $table_editor = new PLTableEditor('admin/skins','skins','id');
1171 $table_editor->describe('name','nom',true
);
1172 $table_editor->describe('skin_tpl','nom du template',true
);
1173 $table_editor->describe('auteur','auteur',false
);
1174 $table_editor->describe('comment','commentaire',true
);
1175 $table_editor->describe('date','date',false
);
1176 $table_editor->describe('ext','extension du screenshot',false
);
1177 $table_editor->apply($page, $action, $id);
1180 function handler_postfix_blacklist($page, $action = 'list', $id = null
)
1182 $page->setTitle('Administration - Postfix : Blacklist');
1183 $page->assign('title', 'Blacklist de postfix');
1184 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true
);
1185 $table_editor->describe('reject_text','Texte de rejet',true
);
1186 $table_editor->describe('email','email',true
);
1187 $table_editor->apply($page, $action, $id);
1190 function handler_postfix_whitelist($page, $action = 'list', $id = null
)
1192 $page->setTitle('Administration - Postfix : Whitelist');
1193 $page->assign('title', 'Whitelist de postfix');
1194 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true
);
1195 $table_editor->describe('email','email',true
);
1196 $table_editor->apply($page, $action, $id);
1199 function handler_mx_broken($page, $action = 'list', $id = null
)
1201 $page->setTitle('Administration - MX Défaillants');
1202 $page->assign('title', 'MX Défaillant');
1203 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true
);
1204 $table_editor->describe('host', 'Masque', true
);
1205 $table_editor->describe('state', 'Niveau', true
);
1206 $table_editor->describe('text', 'Description du problème', false
);
1207 $table_editor->apply($page, $action, $id);
1210 function handler_logger_actions($page, $action = 'list', $id = null
)
1212 $page->setTitle('Administration - Actions');
1213 $page->assign('title', 'Gestion des actions de logger');
1214 $table_editor = new PLTableEditor('admin/logger/actions','log_actions','id');
1215 $table_editor->describe('text','intitulé',true
);
1216 $table_editor->describe('description','description',true
);
1217 $table_editor->apply($page, $action, $id);
1220 function handler_downtime($page, $action = 'list', $id = null
)
1222 $page->setTitle('Administration - Coupures');
1223 $page->assign('title', 'Gestion des coupures');
1224 $table_editor = new PLTableEditor('admin/downtime','downtimes','id');
1225 $table_editor->describe('debut','date',true
);
1226 $table_editor->describe('duree','durée',false
);
1227 $table_editor->describe('resume','résumé',true
);
1228 $table_editor->describe('services','services affectés',true
);
1229 $table_editor->describe('description','description',false
);
1230 $table_editor->apply($page, $action, $id);
1233 private static function isCountryIncomplete(array &$item)
1236 foreach (array('worldRegion', 'country', 'capital', 'phonePrefix', 'licensePlate', 'countryPlain') as $field) {
1237 if ($item[$field] == '') {
1238 $item[$field . '_warning'] = true
;
1242 if (is_null($item['belongsTo'])) {
1243 foreach (array('nationality', 'nationalityEn') as $field) {
1244 if ($item[$field] == '') {
1245 $item[$field . '_warning'] = true
;
1253 private static function updateCountry(array $item)
1255 XDB
::execute('UPDATE geoloc_countries
1256 SET countryPlain = {?}
1257 WHERE iso_3166_1_a2 = {?}',
1258 mb_strtoupper(replace_accent($item['country'])), $item['iso_3166_1_a2']);
1261 private static function isLanguageIncomplete(array &$item)
1263 if ($item['language'] == '') {
1264 $item['language_warning'] = true
;
1270 private static function updateLanguage(array $item) {}
1272 function handler_geocoding($page, $category = null
, $action = null
, $id = null
)
1274 // Warning, this handler requires the following packages:
1278 static $properties = array(
1281 'isocode' => '3166',
1282 'table' => 'geoloc_countries',
1283 'id' => 'iso_3166_1_a2',
1284 'main_fields' => array('iso_3166_1_a3', 'iso_3166_1_num', 'countryEn'),
1285 'other_fields' => array('worldRegion', 'country', 'capital', 'nationality', 'nationalityEn',
1286 'phonePrefix', 'phoneFormat', 'licensePlate', 'belongsTo')
1288 'language' => array(
1289 'name' => 'langages',
1291 'table' => 'profile_langskill_enum',
1292 'id' => 'iso_639_2b',
1293 'main_fields' => array('iso_639_2t', 'iso_639_1', 'language_en'),
1294 'other_fields' => array('language')
1299 if (is_null($category) ||
!array_key_exists($category, $properties)) {
1300 pl_redirect('admin');
1303 $data = $properties[$category];
1305 if ($action == 'edit' ||
$action == 'add') {
1306 $main_fields = array_merge(array($data['id']), $data['main_fields']);
1307 $all_fields = array_merge($main_fields, $data['other_fields']);
1310 if (Post
::has('new_id')) {
1311 $id = Post
::v('new_id');
1313 pl_redirect('admin/geocoding/' . $category);
1318 exec('isoquery --iso=' . $data['isocode'] . ' ' . $id, $list);
1319 if (count($list) == 1) {
1320 $array = explode("\t", $list[0]);
1321 foreach ($main_fields as $i => $field) {
1322 $iso[$field] = $array[$i];
1328 if ($action == 'add') {
1329 if (Post
::has('new_id')) {
1330 S
::assert_xsrf_token();
1336 $item = array($data['id'] => $id);
1338 XDB
::execute('INSERT INTO ' . $data['table'] . '(' . implode(', ', array_keys($item)) . ')
1339 VALUES ' . XDB
::formatArray($item));
1340 $page->trigSuccess($id . ' a bien été ajouté à la base.');
1341 } elseif ($action == 'edit') {
1342 if (Post
::has('edit')) {
1343 S
::assert_xsrf_token();
1347 foreach ($all_fields as $field) {
1348 $item[$field] = Post
::t($field);
1349 $set[] = $field . XDB
::format(' = {?}', ($item[$field] ?
$item[$field] : null
));
1351 XDB
::execute('UPDATE ' . $data['table'] . '
1352 SET ' . implode(', ', $set) . '
1353 WHERE ' . $data['id'] . ' = {?}',
1355 call_user_func_array(array('self', 'update' . ucfirst($category)), array($item));
1356 $page->trigSuccess($id . ' a bien été mis à jour.');
1357 } elseif (Post
::has('del')) {
1358 S
::assert_xsrf_token();
1360 XDB
::execute('DELETE FROM ' . $data['table'] . '
1361 WHERE ' . $data['id'] . ' = {?}',
1363 $page->trigSuccessRedirect($id . ' a bien été supprimé.', 'admin/geocoding/' . $category);
1365 $item = XDB
::fetchOneAssoc('SELECT *
1366 FROM ' . $data['table'] . '
1367 WHERE ' . $data['id'] . ' = {?}',
1372 $page->changeTpl('admin/geocoding_edit.tpl');
1373 $page->setTitle('Administration - ' . ucfirst($data['name']));
1374 $page->assign('category', $category);
1375 $page->assign('name', $data['name']);
1376 $page->assign('all_fields', $all_fields);
1377 $page->assign('id', $id);
1378 $page->assign('iso', $iso);
1379 $page->assign('item', $item);
1383 $page->changeTpl('admin/geocoding.tpl');
1384 $page->setTitle('Administration - ' . ucfirst($data['name']));
1385 $page->assign('category', $category);
1386 $page->assign('name', $data['name']);
1387 $page->assign('id', $data['id']);
1388 $page->assign('main_fields', $data['main_fields']);
1389 $page->assign('all_fields', array_merge($data['main_fields'], $data['other_fields']));
1391 // First build the list provided by the iso codes.
1393 exec('isoquery --iso=' . $data['isocode'], $list);
1395 foreach ($list as $key => $item) {
1396 $array = explode("\t", $item);
1398 $list[$array[0]] = array();
1399 foreach ($data['main_fields'] as $i => $field) {
1400 $list[$array[0]][$field] = $array[$i +
1];
1405 // Retrieve all data from the database.
1406 $db_list = XDB
::rawFetchAllAssoc('SELECT *
1407 FROM ' . $data['table'] . '
1408 ORDER BY ' . $data['id'],
1411 // Sort both iso and database data into 5 categories:
1412 // $missing: data from the iso list not in the database,
1413 // $non_existing: data from the database not in the iso list,
1414 // $erroneous: data that differ on main fields,
1415 // $incomplete: data with empty fields in the data base,
1416 // $remaining: remaining correct and complete data from the database.
1418 $missing = $non_existing = $erroneous = $incomplete = $remaining = array();
1419 foreach (array_keys($list) as $id) {
1420 if (!array_key_exists($id, $db_list)) {
1421 $missing[$id] = $list[$id];
1425 foreach ($db_list as $id => $item) {
1426 if (!array_key_exists($id, $list)) {
1427 $non_existing[$id] = $item;
1430 foreach ($data['main_fields'] as $field) {
1431 if ($item[$field] != $list[$id][$field]) {
1432 $item[$field . '_error'] = true
;
1436 if ($error == true
) {
1437 $erroneous[$id] = $item;
1438 } elseif (call_user_func_array(array('self', 'is' . ucfirst($category) . 'Incomplete'), array(&$item))) {
1439 $incomplete[$id] = $item;
1441 $remaining[$id] = $item;
1446 $page->assign('lists', array(
1447 'manquant' => $missing,
1448 'disparu' => $non_existing,
1449 'erroné' => $erroneous,
1450 'incomplet' => $incomplete,
1451 'restant' => $remaining
1455 function handler_accounts(PlPage
$page)
1457 $page->changeTpl('admin/accounts.tpl');
1458 $page->setTitle('Administration - Comptes');
1460 if (Post
::has('create_account')) {
1461 S
::assert_xsrf_token();
1462 $firstname = Post
::t('firstname');
1463 $lastname = strtoupper(Post
::t('lastname'));
1464 $sex = Post
::s('sex');
1465 $email = Post
::t('email');
1466 $type = Post
::s('type');
1467 $login = PlUser
::makeHrid($firstname, $lastname, $type);
1468 if (!isvalid_email($email)) {
1469 $page->trigError("Invalid email address: $email");
1470 } else if (strlen(Post
::s('pwhash')) != 40) {
1471 $page->trigError("Invalid password hash");
1473 $full_name = $firstname . ' ' . $lastname;
1474 $directory_name = $lastname . ' ' . $firstname;
1475 XDB
::execute("INSERT INTO accounts (hruid, type, state, password,
1476 registration_date, email, full_name,
1477 display_name, sex, directory_name)
1478 VALUES ({?}, {?}, 'active', {?}, NOW(), {?}, {?}, {?}, {?}, {?})",
1479 $login, $type, Post
::s('pwhash'), $email, $full_name, $full_name, $sex,
1484 $uf = new UserFilter(new UFC_AccountType('ax', 'school', 'fx'));
1485 $page->assign('users', $uf->iterUsers());
1489 function handler_account_types($page, $action = 'list', $id = null
)
1491 $page->setTitle('Administration - Types de comptes');
1492 $page->assign('title', 'Gestion des types de comptes');
1493 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true
);
1494 $table_editor->describe('type', 'Catégorie', true
);
1495 $table_editor->describe('perms', 'Permissions associées', true
);
1496 $table_editor->apply($page, $action, $id);
1499 function handler_wiki($page, $action = 'list', $wikipage = null
, $wikipage2 = null
)
1501 if (S
::hasAuthToken()) {
1502 $page->setRssLink('Changement Récents',
1503 '/Site/AllRecentChanges?action=rss&user=' . S
::v('hruid') . '&hash=' . S
::user()->token
);
1506 // update wiki perms
1507 if ($action == 'update') {
1508 S
::assert_xsrf_token();
1510 $perms_read = Post
::v('read');
1511 $perms_edit = Post
::v('edit');
1512 if ($perms_read ||
$perms_edit) {
1513 foreach ($_POST as $wiki_page => $val) {
1515 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1516 if ($wp->setPerms($perms_read ?
$perms_read : $wp->readPerms(),
1517 $perms_edit ?
$perms_edit : $wp->writePerms())) {
1518 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1520 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1525 } else if ($action != 'list' && !empty($wikipage)) {
1526 $wp = new PlWikiPage($wikipage);
1527 S
::assert_xsrf_token();
1529 if ($action == 'delete') {
1530 if ($wp->delete()) {
1531 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1533 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1535 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1536 if ($changedLinks = $wp->rename($wikipage2)) {
1537 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1538 if (is_numeric($changedLinks)) {
1539 $s .= $changedLinks.' lien'.(($changedLinks>1)?
's ont été modifiés.':' a été modifié.');
1541 $page->trigSuccess($s);
1543 $page->trigError("Impossible de déplacer la page ".$wikipage);
1548 $perms = PlWikiPage
::permOptions();
1550 // list wiki pages and their perms
1551 $wiki_pages = PlWikiPage
::listPages();
1553 $wiki_tree = array();
1554 foreach ($wiki_pages as $file => $desc) {
1555 list($cat, $name) = explode('.', $file);
1556 if (!isset($wiki_tree[$cat])) {
1557 $wiki_tree[$cat] = array();
1559 $wiki_tree[$cat][$name] = $desc;
1562 $page->changeTpl('admin/wiki.tpl');
1563 $page->assign('wiki_pages', $wiki_tree);
1564 $page->assign('perms_opts', $perms);
1567 function handler_ipwatch($page, $action = 'list', $ip = null
)
1569 $page->changeTpl('admin/ipwatcher.tpl');
1571 $states = array('safe' => 'Ne pas surveiller',
1572 'unsafe' => 'Surveiller les inscriptions',
1573 'dangerous' => 'Surveiller tous les accès',
1574 'ban' => 'Bannir cette adresse');
1575 $page->assign('states', $states);
1577 switch (Post
::v('action')) {
1579 if (trim(Post
::v('ipN')) != '') {
1580 S
::assert_xsrf_token();
1581 Xdb
::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1582 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1583 ip_to_uint(trim(Post
::v('ipN'))), ip_to_uint(trim(Post
::v('maskN'))),
1584 Post
::v('stateN'), S
::i('uid'), Post
::v('descriptionN'));
1589 S
::assert_xsrf_token();
1590 Xdb
::execute('UPDATE ip_watch
1591 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1592 WHERE ip = {?}', Post
::v('stateN'), S
::i('uid'), Post
::v('descriptionN'),
1593 ip_to_uint(Post
::v('maskN')), ip_to_uint(Post
::v('ipN')));
1597 if ($action == 'delete' && !is_null($ip)) {
1598 S
::assert_xsrf_token();
1599 Xdb
::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1602 if ($action != 'create' && $action != 'edit') {
1605 $page->assign('action', $action);
1607 if ($action == 'list') {
1608 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1609 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1610 IF(w.ip = s.ip, s.host, s.forward_host)),
1611 w.mask, w.detection, w.state, a.hruid
1613 LEFT JOIN log_sessions AS s ON (s.ip = w.ip)
1614 LEFT JOIN log_sessions AS s2 ON (s2.forward_ip = w.ip)
1615 LEFT JOIN accounts AS a ON (a.uid = s.uid)
1616 GROUP BY w.ip, a.hruid
1617 ORDER BY w.state, w.ip, a.hruid";
1618 $it = Xdb
::iterRow($sql);
1622 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1623 $ip = uint_to_ip($ip);
1624 $mask = uint_to_ip($mask);
1625 if (count($props) == 0 ||
$props['ip'] != $ip) {
1626 if (count($props) > 0) {
1629 $props = array('ip' => $ip,
1632 'detection' => $date,
1634 'users' => array($hruid));
1636 $props['users'][] = $hruid;
1639 if (count($props) > 0) {
1642 $page->assign('table', $table);
1643 } elseif ($action == 'edit') {
1644 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1645 a1.hruid AS edit, a2.hruid AS hruid, s.host
1647 LEFT JOIN accounts AS a1 ON (a1.uid = w.uid)
1648 LEFT JOIN log_sessions AS s ON (w.ip = s.ip)
1649 LEFT JOIN accounts AS a2 ON (a2.uid = s.uid)
1653 $it = Xdb
::iterRow($sql, ip_to_uint($ip));
1656 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1657 if (count($props) == 0) {
1658 $props = array('ip' => $ip,
1659 'mask' => uint_to_ip($mask),
1661 'detection' => $detection,
1664 'description' => $description,
1666 'users' => array($hruid));
1668 $props['users'][] = $hruid;
1671 $page->assign('ip', $props);
1675 function handler_icons($page)
1677 $page->changeTpl('admin/icons.tpl');
1678 $dh = opendir('../htdocs/images/icons');
1680 $page->trigError('Dossier des icones introuvables.');
1683 while (($file = readdir($dh)) !== false
) {
1684 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1685 array_push($icons, substr($file, 0, -4));
1689 $page->assign('icons', $icons);
1692 function handler_account_watch($page)
1694 $page->changeTpl('admin/accounts.tpl');
1695 $page->assign('disabled', XDB
::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1696 a.state = \'disabled\' AS disabled, a.comment
1698 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1699 ORDER BY a.hruid'));
1700 $page->assign('admins', XDB
::iterator('SELECT a.hruid
1703 ORDER BY a.hruid'));
1706 function handler_xnet_without_group($page)
1708 $page->changeTpl('admin/xnet_without_group.tpl');
1709 $page->assign('accounts', XDB
::iterator('SELECT a.hruid, a.state
1711 LEFT JOIN group_members AS m ON (a.uid = m.uid)
1712 WHERE a.type = \'xnet\' AND m.uid IS NULL
1713 ORDER BY a.state, a.hruid'));
1716 function handler_jobs($page, $id = -1)
1718 $page->changeTpl('admin/jobs.tpl');
1720 if (Env
::has('search')) {
1721 $res = XDB
::query("SELECT id, name, acronym
1722 FROM profile_job_enum
1723 WHERE name LIKE CONCAT('%', {?}, '%') OR acronym LIKE CONCAT('%', {?}, '%')",
1724 Env
::t('job'), Env
::t('job'));
1726 if ($res->numRows() <= 20) {
1727 $page->assign('jobs', $res->fetchAllAssoc());
1729 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1732 $page->assign('askedJob', Env
::v('job'));
1736 if (Env
::has('edit')) {
1737 S
::assert_xsrf_token();
1738 $selectedJob = Env
::has('selectedJob');
1740 Phone
::deletePhones(0, Phone
::LINK_COMPANY
, $id);
1741 Address
::deleteAddresses(null
, Address
::LINK_COMPANY
, $id);
1742 if (Env
::has('change')) {
1743 if (Env
::has('newJobId') && Env
::i('newJobId') > 0) {
1744 XDB
::execute('UPDATE profile_job
1747 Env
::i('newJobId'), $id);
1748 XDB
::execute('DELETE FROM profile_job_enum
1752 $page->trigSuccess("L'entreprise a bien été remplacée.");
1754 $page->trigError("L'entreprise n'a pas été remplacée car l'identifiant fourni n'est pas valide.");
1757 XDB
::execute('UPDATE profile_job_enum
1758 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1759 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1761 Env
::t('name'), Env
::t('acronym'), Env
::t('url'), Env
::t('email'),
1762 (Env
::t('NAF_code') == 0 ? null
: Env
::t('NAF_code')),
1763 (Env
::i('AX_code') == 0 ? null
: Env
::t('AX_code')),
1764 (Env
::i('holdingId') == 0 ? null
: Env
::t('holdingId')), $id);
1766 $phone = new Phone(array('display' => Env
::v('tel'), 'link_id' => $id, 'id' => 0, 'type' => 'fixed',
1767 'link_type' => Phone
::LINK_COMPANY
, 'pub' => 'public'));
1768 $fax = new Phone(array('display' => Env
::v('fax'), 'link_id' => $id, 'id' => 1, 'type' => 'fax',
1769 'link_type' => Phone
::LINK_COMPANY
, 'pub' => 'public'));
1770 $address = new Address(array('jobid' => $id, 'type' => Address
::LINK_COMPANY
, 'text' => Env
::t('address')));
1775 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1779 if (!Env
::has('change') && $id != -1) {
1780 $res = XDB
::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1781 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1782 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1783 FROM profile_job_enum AS e
1784 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
1785 LEFT JOIN profile_phones AS t ON (t.pid = e.id AND t.link_type = 'hq' AND t.tel_id = 0)
1786 LEFT JOIN profile_phones AS f ON (f.pid = e.id AND f.link_type = 'hq' AND f.tel_id = 1)
1787 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1791 if ($res->numRows() == 0) {
1792 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1794 $page->assign('selectedJob', $res->fetchOneAssoc());
1799 function handler_profile($page)
1801 $page->changeTpl('admin/profile.tpl');
1803 if (Post
::has('checked')) {
1804 S
::assert_xsrf_token();
1805 $res = XDB
::iterator('SELECT DISTINCT(pm.pid), pd.public_name
1806 FROM profile_modifications AS pm
1807 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1808 WHERE pm.type = \'self\'');
1810 while ($profile = $res->next()) {
1811 if (Post
::has('checked_' . $profile['pid'])) {
1812 XDB
::execute('DELETE FROM profile_modifications
1813 WHERE type = \'self\' AND pid = {?}', $profile['pid']);
1815 $page->trigSuccess('Profil de ' . $profile['public_name'] . ' vérifié.');
1820 $res = XDB
::iterator('SELECT p.hrpid, pm.pid, pd.directory_name, GROUP_CONCAT(pm.field SEPARATOR \', \') AS field
1821 FROM profile_modifications AS pm
1822 INNER JOIN profiles AS p ON (pm.pid = p.pid)
1823 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1824 WHERE pm.type = \'self\'
1825 GROUP BY pd.directory_name
1826 ORDER BY pd.directory_name');
1827 $page->assign('updates', $res);
1830 function handler_phd($page, $promo = null
, $validate = false
)
1832 $page->changeTpl('admin/phd.tpl');
1833 $eduDegrees = DirEnum
::getOptions(DirEnum
::EDUDEGREES
);
1834 $eduDegrees = array_flip($eduDegrees);
1836 if (is_null($promo)) {
1837 $promo_list = XDB
::fetchColumn('SELECT DISTINCT(grad_year)
1838 FROM profile_education
1839 WHERE FIND_IN_SET(\'primary\', flags) AND NOT FIND_IN_SET(\'completed\', flags) AND degreeid = {?}
1840 ORDER BY grad_year',
1841 $eduDegrees[Profile
::DEGREE_D
]);
1842 $page->assign('promo_list', $promo_list);
1843 $page->assign('nothing', count($promo_list) == 0);
1848 S
::assert_xsrf_token();
1850 $list = XDB
::iterator('SELECT pe.pid, pd.directory_name
1851 FROM profile_education AS pe
1852 INNER JOIN profile_display AS pd ON (pe.pid = pd.pid)
1853 WHERE FIND_IN_SET(\'primary\', pe.flags) AND NOT FIND_IN_SET(\'completed\', pe.flags)
1854 AND pe.degreeid = {?} AND pe.grad_year = {?}',
1855 $eduDegrees[Profile
::DEGREE_D
], $promo);
1856 while ($res = $list->next()) {
1858 $name = $res['directory_name'];
1859 if (Post
::b('completed_' . $pid)) {
1860 $grad_year = Post
::t('grad_year_' . $pid);
1861 XDB
::execute('UPDATE profile_education
1862 SET flags = \'primary,completed\', grad_year = {?}
1863 WHERE FIND_IN_SET(\'primary\', flags) AND pid = {?}',
1865 XDB
::execute('UPDATE profile_display
1868 'D' . $grad_year, $pid);
1869 $page->trigSuccess("Promotion de $name validée.");
1874 $list = XDB
::iterator('SELECT pe.pid, pd.directory_name
1875 FROM profile_education AS pe
1876 INNER JOIN profile_display AS pd ON (pe.pid = pd.pid)
1877 WHERE FIND_IN_SET(\'primary\', pe.flags) AND NOT FIND_IN_SET(\'completed\', pe.flags)
1878 AND pe.degreeid = {?} AND pe.grad_year = {?}
1879 ORDER BY pd.directory_name',
1880 $eduDegrees[Profile
::DEGREE_D
], $promo);
1881 $page->assign('list', $list);
1882 $page->assign('promo', $promo);
1886 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: