2 /***************************************************************************
3 * Copyright (C) 2003-2010 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'),
46 'admin/validate/answers' => $this->make_hook('validate_answers', AUTH_MDP
, 'admin'),
47 'admin/wiki' => $this->make_hook('wiki', AUTH_MDP
, 'admin'),
48 'admin/ipwatch' => $this->make_hook('ipwatch', AUTH_MDP
, 'admin'),
49 'admin/icons' => $this->make_hook('icons', AUTH_MDP
, 'admin'),
50 'admin/accounts' => $this->make_hook('accounts', AUTH_MDP
, 'admin'),
51 'admin/account/watch' => $this->make_hook('account_watch', AUTH_MDP
, 'admin'),
52 'admin/account/types' => $this->make_hook('account_types', AUTH_MDP
, 'admin'),
53 'admin/jobs' => $this->make_hook('jobs', AUTH_MDP
, 'admin'),
57 function handler_phpinfo(&$page)
63 function handler_get_rights(&$page)
66 $page->kill('Déjà en SUID');
68 S
::assert_xsrf_token();
69 $level = Post
::s('account_type');
70 if ($level != 'admin') {
71 $user = User
::getSilentWithUID(S
::user()->id());
72 $user->is_admin
= false
;
73 $types = DirEnum
::getOptions(DirEnum
::ACCOUNTTYPES
);
74 if (!empty($types[$level])) {
75 $user->setPerms($types[$level]);
77 S
::set('suid_startpage', $_SERVER['HTTP_REFERER']);
78 Platal
::session()->startSUID($user);
80 if (!empty($_SERVER['HTTP_REFERER'])) {
81 http_redirect($_SERVER['HTTP_REFERER']);
87 function handler_set_skin(&$page)
89 S
::assert_xsrf_token();
90 S
::set('skin', Post
::s('change_skin'));
91 if (!empty($_SERVER['HTTP_REFERER'])) {
92 http_redirect($_SERVER['HTTP_REFERER']);
98 function handler_default(&$page)
100 $page->changeTpl('admin/index.tpl');
101 $page->setTitle('Administration');
104 function handler_postfix_delayed(&$page)
106 $page->changeTpl('admin/postfix_delayed.tpl');
107 $page->setTitle('Administration - Postfix : Retardés');
109 if (Env
::has('del')) {
110 $crc = Env
::v('crc');
111 XDB
::execute("UPDATE postfix_mailseen SET release = 'del' WHERE crc = {?}", $crc);
112 $page->trigSuccess($crc . " verra tous ses emails supprimés !");
113 } elseif (Env
::has('ok')) {
114 $crc = Env
::v('crc');
115 XDB
::execute("UPDATE postfix_mailseen SET release = 'ok' WHERE crc = {?}", $crc);
116 $page->trigSuccess($crc . " a le droit de passer !");
119 $sql = XDB
::iterator(
120 "SELECT crc, nb, update_time, create_time,
121 FIND_IN_SET('del', p.release) AS del,
122 FIND_IN_SET('ok', p.release) AS ok
123 FROM postfix_mailseen AS p
125 ORDER BY p.release != ''");
127 $page->assign_by_ref('mails', $sql);
130 function handler_postfix_regexpsbounces(&$page, $new = null
) {
131 $page->changeTpl('admin/emails_bounces_re.tpl');
132 $page->setTitle('Administration - Postfix : Regexps Bounces');
133 $page->assign('new', $new);
135 if (Post
::has('submit')) {
136 foreach (Env
::v('lvl') as $id=>$val) {
138 "REPLACE INTO emails_bounces_re (id,pos,lvl,re,text) VALUES ({?}, {?}, {?}, {?}, {?})",
139 $id, $_POST['pos'][$id], $_POST['lvl'][$id], $_POST['re'][$id], $_POST['text'][$id]
144 $page->assign('bre', XDB
::iterator("SELECT * FROM emails_bounces_re ORDER BY pos"));
149 /** Retrieves the available days for a given year and month.
150 * Obtain a list of days of the given month in the given year
151 * that are within the range of dates that we have log entries for.
153 * @param integer year
154 * @param integer month
155 * @return array days in that month we have log entries covering.
158 function _getDays($year, $month)
160 // give a 'no filter' option
164 if ($year && $month) {
165 $day_max = Array(-1, 31, checkdate(2, 29, $year) ?
29 : 28 , 31,
166 30, 31, 30, 31, 31, 30, 31, 30, 31);
167 $res = XDB
::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
168 MONTH(MAX(start)), MONTH(MIN(start)),
169 DAYOFMONTH(MAX(start)),
170 DAYOFMONTH(MIN(start))
172 list($ymax, $ymin, $mmax, $mmin, $dmax, $dmin) = $res->fetchOneRow();
174 if (($year < $ymin) ||
($year == $ymin && $month < $mmin)) {
178 if (($year > $ymax) ||
($year == $ymax && $month > $mmax)) {
182 $min = ($year==$ymin && $month==$mmin) ?
intval($dmin) : 1;
183 $max = ($year==$ymax && $month==$mmax) ?
intval($dmax) : $day_max[$month];
185 for($i = $min; $i<=$max; $i++
) {
193 /** Retrieves the available months for a given year.
194 * Obtains a list of month numbers that are within the timeframe that
195 * we have log entries for.
197 * @param integer year
198 * @return array List of month numbers we have log info for.
201 function _getMonths($year)
203 // give a 'no filter' option
208 $res = XDB
::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
209 MONTH(MAX(start)), MONTH(MIN(start))
211 list($ymax, $ymin, $mmax, $mmin) = $res->fetchOneRow();
213 if (($year < $ymin) ||
($year > $ymax)) {
217 $min = $year == $ymin ?
intval($mmin) : 1;
218 $max = $year == $ymax ?
intval($mmax) : 12;
220 for($i = $min; $i<=$max; $i++
) {
228 /** Retrieves the available years.
229 * Obtains a list of years that we have log entries covering.
231 * @return array years we have log entries for.
236 // give a 'no filter' option
240 // retrieve available years
241 $res = XDB
::query("select YEAR(MAX(start)), YEAR(MIN(start)) FROM log_sessions");
242 list($max, $min) = $res->fetchOneRow();
244 for($i = intval($min); $i<=$max; $i++
) {
251 /** Make a where clause to get a user's sessions.
252 * Prepare the where clause request that will retrieve the sessions.
254 * @param $year INTEGER Only get log entries made during the given year.
255 * @param $month INTEGER Only get log entries made during the given month.
256 * @param $day INTEGER Only get log entries made during the given day.
257 * @param $uid INTEGER Only get log entries referring to the given user ID.
259 * @return STRING the WHERE clause of a query, including the 'WHERE' keyword
262 function _makeWhere($year, $month, $day, $uid)
264 // start constructing the "where" clause
268 array_push($where, "s.uid='$uid'");
270 // we were given at least a year
273 $dmin = mktime(0, 0, 0, $month, $day, $year);
274 $dmax = mktime(0, 0, 0, $month, $day+
1, $year);
276 $dmin = mktime(0, 0, 0, $month, 1, $year);
277 $dmax = mktime(0, 0, 0, $month+
1, 1, $year);
279 $dmin = mktime(0, 0, 0, 1, 1, $year);
280 $dmax = mktime(0, 0, 0, 1, 1, $year+
1);
282 $where[] = "start >= " . date("Ymd000000", $dmin);
283 $where[] = "start < " . date("Ymd000000", $dmax);
286 if (!empty($where)) {
287 return ' WHERE ' . implode($where, " AND ");
291 // WE know it's totally reversed, so better use array_reverse than a SORT BY start DESC
296 function handler_logger(&$page, $action = null
, $arg = null
) {
297 if ($action == 'session') {
299 // we are viewing a session
300 $res = XDB
::query("SELECT ls.*, a.hruid AS username, sa.hruid AS suer
301 FROM log_sessions AS ls
302 INNER JOIN accounts AS a ON (a.uid = ls.uid)
303 LEFT JOIN accounts AS sa ON (sa.uid = ls.suid)
304 WHERE ls.id = {?}", $arg);
306 $page->assign('session', $a = $res->fetchOneAssoc());
308 $res = XDB
::iterator('SELECT a.text, e.data, e.stamp
310 LEFT JOIN log_actions AS a ON e.action=a.id
311 WHERE e.session={?}', $arg);
312 while ($myarr = $res->next()) {
313 $page->append('events', $myarr);
317 $loguser = $action == 'user' ?
$arg : Env
::v('loguser');
320 $user = User
::get($loguser);
321 $loguid = $user->id();
327 $year = Env
::i('year');
328 $month = Env
::i('month');
329 $day = Env
::i('day');
331 $year = Env
::i('year', intval(date('Y')));
332 $month = Env
::i('month', intval(date('m')));
333 $day = Env
::i('day', intval(date('d')));
341 // smarty assignments
342 // retrieve available years
343 $page->assign('years', $this->_getYears());
344 $page->assign('year', $year);
346 // retrieve available months for the current year
347 $page->assign('months', $this->_getMonths($year));
348 $page->assign('month', $month);
350 // retrieve available days for the current year and month
351 $page->assign('days', $this->_getDays($year, $month));
352 $page->assign('day', $day);
354 $page->assign('loguser', $loguser);
355 // smarty assignments
357 if ($loguid ||
$year) {
359 // get the requested sessions
360 $where = $this->_makeWhere($year, $month, $day, $loguid);
361 $select = "SELECT s.id, s.start, s.uid,
363 FROM log_sessions AS s
364 INNER JOIN accounts AS a ON (a.uid = s.uid)
366 ORDER BY start DESC";
367 $res = XDB
::iterator($select);
370 while ($mysess = $res->next()) {
371 $mysess['events'] = array();
372 $sessions[$mysess['id']] = $mysess;
374 array_reverse($sessions);
377 $sql = "SELECT s.id, a.text
378 FROM log_sessions AS s
379 LEFT JOIN log_events AS e ON(e.session=s.id)
380 INNER JOIN log_actions AS a ON(a.id=e.action)
383 $res = XDB
::iterator($sql);
384 while ($event = $res->next()) {
385 array_push($sessions[$event['id']]['events'], $event['text']);
387 $page->assign_by_ref('sessions', $sessions);
389 $page->assign('msg_nofilters', "Sélectionner une année et/ou un utilisateur");
393 $page->changeTpl('admin/logger-view.tpl');
395 $page->setTitle('Administration - Logs des sessions');
398 function handler_user(&$page, $login = false
)
401 $page->changeTpl('admin/user.tpl');
402 $page->setTitle('Administration - Compte');
405 $page->kill("Déjà en SUID !!!");
408 // Loads the user identity using the environment.
410 $user = User
::get($login);
413 pl_redirect('admin/accounts');
416 $listClient = new MMList(S
::user());
417 $login = $user->login();
418 $registered = ($user->state
!= 'pending');
421 if (!empty($_POST)) {
422 S
::assert_xsrf_token();
423 if (Post
::has('uid') && Post
::i('uid') != $user->id()) {
424 $page->kill('Une erreur s\'est produite');
428 // Handles specific requests (AX sync, su, ...).
429 if(Post
::has('log_account')) {
430 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
433 if(Post
::has('su_account') && $registered) {
434 if (!Platal
::session()->startSUID($user)) {
435 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->login());
441 // Handles account deletion.
442 if (Post
::has('account_deletion_confirmation')) {
444 $name = $user->fullName();
445 $profile = $user->profile();
446 if ($profile && Post
::b('clear_profile')) {
447 $user->profile()->clear();
450 $page->trigSuccess("L'utilisateur $name ($uid) a bien été désinscrit.");
451 if (Post
::b('erase_account')) {
452 XDB
::execute('DELETE FROM accounts
455 $page->trigSuccess("L'utilisateur $name ($uid) a été supprimé de la base de données");
460 $to_update = array();
461 if (Post
::has('disable_weak_access')) {
462 $to_update['weak_password'] = null
;
463 } else if (Post
::has('update_account')) {
464 if (!$user->hasProfile()) {
465 if (Post
::s('full_name') != $user->fullName()) {
466 $to_update['full_name'] = Post
::s('full_name');
468 if (Post
::s('display_name') != $user->displayName()) {
469 $to_update['display_name'] = Post
::s('display_name');
471 if (Post
::s('directory_name') != $user->directoryName()) {
472 $to_update['directory_name'] = Post
::s('directory_name');
475 if (Post
::s('sex') != ($user->isFemale() ?
'female' : 'male')) {
476 $to_update['sex'] = Post
::s('sex');
477 if ($user->hasProfile()) {
478 XDB
::execute('UPDATE profiles
481 Post
::s('sex'), $user->profile()->id());
484 if (!Post
::blank('pwhash')) {
485 $to_update['password'] = Post
::s('pwhash');
486 require_once 'googleapps.inc.php';
487 $account = new GoogleAppsAccount($user);
488 if ($account->active() && $account->sync_password
) {
489 $account->set_password(Post
::s('pwhash'));
492 if (!Post
::blank('weak_password')) {
493 $to_update['weak_password'] = Post
::s('weak_password');
495 if (Post
::i('token_access', 0) != ($user->token_access ?
1 : 0)) {
496 $to_update['token'] = Post
::i('token_access') ?
rand_url_id(16) : null
;
498 if (Post
::i('skin') != $user->skin
) {
499 $to_update['skin'] = Post
::i('skin');
500 if ($to_update['skin'] == 0) {
501 $to_update['skin'] = null
;
504 if (Post
::s('state') != $user->state
) {
505 $to_update['state'] = Post
::s('state');
507 if (Post
::i('is_admin', 0) != ($user->is_admin ?
1 : 0)) {
508 $to_update['is_admin'] = Post
::b('is_admin');
510 if (Post
::s('type') != $user->type
) {
511 $to_update['type'] = Post
::s('type');
513 if (Post
::i('watch', 0) != ($user->watch ?
1 : 0)) {
514 $to_update['flags'] = new PlFlagset();
515 $to_update['flags']->addFlag('watch', Post
::i('watch'));
517 if (Post
::t('comment') != $user->comment
) {
518 $to_update['comment'] = Post
::blank('comment') ? null
: Post
::t('comment');
520 if (!$user->checkPerms(User
::PERM_MAIL
) && Post
::t('email') != $user->forlifeEmail()) {
521 $to_update['email'] = Post
::t('email');
522 $listClient->change_user_email($user->forlifeEmail(), Post
::t('email'));
525 if (!empty($to_update)) {
526 $res = XDB
::query('SELECT *
528 WHERE uid = {?}', $user->id());
529 $oldValues = $res->fetchAllAssoc();
530 $oldValues = $oldValues[0];
534 foreach ($to_update as $k => $value) {
535 $value = XDB
::format('{?}', $value);
536 $set[] = $k . ' = ' . $value;
537 $diff[$k] = array($oldValues[$k], trim($value, "'"));
538 unset($oldValues[$k]);
540 XDB
::rawExecute('UPDATE accounts
541 SET ' . implode(', ', $set) . '
542 WHERE uid = ' . XDB
::format('{?}', $user->id()));
543 $page->trigSuccess('Données du compte mise à jour avec succès');
544 $user = User
::getWithUID($user->id());
546 /* Formats the $diff and send it to the site administrators. The rules are the folowing:
547 * -formats: password, token, weak_password
549 foreach (array('password', 'token', 'weak_password') as $key) {
550 if (isset($diff[$key])) {
551 $diff[$key] = array('old value', 'new value');
553 $oldValues[$key] = 'old value';
557 $mail = new PlMailer('admin/useredit.mail.tpl');
558 $mail->assign('admin', S
::user()->hruid
);
559 $mail->assign('hruid', $user->hruid
);
560 $mail->assign('diff', $diff);
561 $mail->assign('oldValues', $oldValues);
567 if (Post
::has('add_profile') || Post
::has('del_profile') || Post
::has('owner')) {
568 if (Post
::i('del_profile', 0) != 0) {
569 XDB
::execute('DELETE FROM account_profiles
570 WHERE uid = {?} AND pid = {?}',
571 $user->id(), Post
::i('del_profile'));
572 } else if (!Post
::blank('new_profile')) {
573 $profile = Profile
::get(Post
::t('new_profile'));
575 $page->trigError('Le profil ' . Post
::t('new_profile') . ' n\'existe pas');
577 XDB
::execute('INSERT IGNORE INTO account_profiles (uid, pid)
579 $user->id(), $profile->id());
582 XDB
::execute('UPDATE account_profiles
583 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
585 Post
::i('owner'), $user->id());
589 // Email forwards form {{{
590 require_once("emails.inc.php");
591 $redirect = ($registered ?
new Redirect($user) : null
);
592 if (Post
::has('add_fwd')) {
593 $email = Post
::t('email');
594 if (!isvalid_email_redirection($email)) {
595 $page->trigError("Email non valide: $email");
597 $redirect->add_email($email);
598 $page->trigSuccess("Ajout de $email effectué");
600 } else if (!Post
::blank('del_fwd')) {
601 $redirect->delete_email(Post
::t('del_fwd'));
602 } else if (!Post
::blank('activate_fwd')) {
603 $redirect->modify_one_email(Post
::t('activate_fwd', true
));
604 } else if (!Post
::blank('deactivate_fwd')) {
605 $redirect->modify_one_email(Post
::t('deactivate_fwd', false
));
606 } else if (Post
::has('disable_fwd')) {
607 $redirect->disable();
608 } else if (Post
::has('enable_fwd')) {
610 } else if (!Post
::blank('clean_fwd')) {
611 $redirect->clean_errors(Post
::t('clean_fwd'));
615 // Email alias form {{{
616 if (Post
::has('add_alias')) {
617 // Splits new alias in user and fqdn.
618 $alias = Env
::t('email');
619 if (strpos($alias, '@') !== false
) {
620 list($alias, $domain) = explode('@', $alias);
622 $domain = $globals->mail
->domain
;
625 // Checks for alias' user validity.
626 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
627 $page->trigError("'$alias' n'est pas un alias valide");
630 // Eventually adds the alias to the right domain.
631 if ($domain == $globals->mail
->alias_dom ||
$domain == $globals->mail
->alias_dom2
) {
632 $req = new AliasReq($user, $alias, 'Admin request', false
);
633 if ($req->commit()) {
634 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué");
636 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué");
638 } elseif ($domain == $globals->mail
->domain ||
$domain == $globals->mail
->domain2
) {
639 $res = XDB
::execute("INSERT INTO aliases (uid, alias, type)
640 VALUES ({?}, {?}, 'alias')",
641 $user->id(), $alias);
642 $page->trigSuccess("Nouvel alias '$alias' ajouté");
644 $page->trigError("Le domaine '$domain' n'est pas valide");
646 } else if (!Post
::blank('del_alias')) {
647 XDB
::execute("DELETE FROM aliases
648 WHERE uid = {?} AND alias = {?} AND
649 type NOT IN ('a_vie', 'homonyme')",
651 XDB
::execute("UPDATE emails
653 WHERE uid = {?} AND rewrite LIKE CONCAT({?}, '@%')",
655 fix_bestalias($user);
656 $page->trigSuccess("L'alias '$val' a été supprimé");
657 } else if (!Post
::blank('best')) {
658 XDB
::execute("UPDATE aliases
659 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
660 WHERE uid = {?}", $user->id());
661 XDB
::execute("UPDATE aliases
662 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
663 WHERE uid = {?} AND alias = {?}", $user->id(), $val);
664 // As having a non-null bestalias value is critical in
665 // plat/al's code, we do an a posteriori check on the
666 // validity of the bestalias.
667 fix_bestalias($user);
672 if (Post
::has('del_openid')) {
673 XDB
::execute('DELETE FROM account_auth_openid
674 WHERE id = {?}', Post
::i('del_openid'));
679 if (Post
::has('b_edit')) {
680 XDB
::execute("DELETE FROM forum_innd
681 WHERE uid = {?}", $user->id());
682 if (Env
::v('write_perm') != "" || Env
::v('read_perm') != "" || Env
::v('commentaire') != "" ) {
683 XDB
::execute("INSERT INTO forum_innd
684 SET ipmin = '0', ipmax = '4294967295',
685 write_perm = {?}, read_perm = {?},
686 comment = {?}, priority = '200', uid = {?}",
687 Env
::v('write_perm'), Env
::v('read_perm'), Env
::v('comment'), $user->id());
693 $page->addJsLink('jquery.ui.core.js');
694 $page->addJsLink('jquery.ui.widget.js');
695 $page->addJsLink('jquery.ui.tabs.js');
696 $page->addJsLink('password.js');
698 // Displays last login and last host information.
699 $res = XDB
::query("SELECT start, host
701 WHERE uid = {?} AND suid = 0
703 LIMIT 1", $user->id());
704 list($lastlogin,$host) = $res->fetchOneRow();
705 $page->assign('lastlogin', $lastlogin);
706 $page->assign('host', $host);
708 // Display mailing lists
709 $page->assign('mlists', $listClient->get_all_user_lists($user->forlifeEmail()));
711 // Display active aliases.
712 $page->assign('virtuals', $user->emailAliases());
713 $page->assign('aliases', XDB
::iterator("SELECT alias, type='a_vie' AS for_life,
714 FIND_IN_SET('bestalias',flags) AS best, expire
716 WHERE uid = {?} AND type != 'homonyme'
717 ORDER BY type != 'a_vie'", $user->id()));
718 $page->assign('account_types', XDB
::iterator('SELECT * FROM account_types ORDER BY type'));
719 $page->assign('skins', XDB
::iterator('SELECT id, name FROM skins ORDER BY name'));
720 $page->assign('profiles', XDB
::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
721 FROM account_profiles AS ap
722 INNER JOIN profiles AS p ON (ap.pid = p.pid)
723 WHERE ap.uid = {?}', $user->id()));
724 $page->assign('openid', XDB
::iterator('SELECT id, url
725 FROM account_auth_openid
726 WHERE uid = {?}', $user->id()));
728 // Displays email redirection and the general profile.
729 if ($registered && $redirect) {
730 $page->assign('emails', $redirect->emails
);
733 $page->assign('user', $user);
734 $page->assign('hasProfile', $user->hasProfile());
736 // Displays forum bans.
737 $res = XDB
::query("SELECT write_perm, read_perm, comment
739 WHERE uid = {?}", $user->id());
740 $bans = $res->fetchOneAssoc();
741 $page->assign('bans', $bans);
744 private static function getHrid($firstname, $lastname, $promo)
746 if ($firstname != null
&& $lastname != null
&& $promo != null
) {
747 return User
::makeHrid($firstname, $lastname, $promo);
752 private static function formatNewUser(&$page, $infosLine, $separator, $promo, $size)
754 $infos = explode($separator, $infosLine);
755 if (sizeof($infos) > $size ||
sizeof($infos) < 2) {
756 $page->trigError("La ligne $infosLine n'a pas été ajoutée.");
760 $infos = array_map('trim', $infos);
761 $hrid = self
::getHrid($infos[1], $infos[0], $promo);
762 $res1 = XDB
::query('SELECT COUNT(*)
764 WHERE hruid = {?}', $hrid);
765 $res2 = XDB
::query('SELECT COUNT(*)
767 WHERE hrpid = {?}', $hrid);
768 if (is_null($hrid) ||
$res1->fetchOneCell() > 0 ||
$res2->fetchOneCell() > 0) {
769 $page->trigError("La ligne $infosLine n'a pas été ajoutée: une entrée similaire existe déjà");
772 $infos['hrid'] = $hrid;
776 private static function formatSex(&$page, $sex, $line)
780 return PlUser
::GENDER_FEMALE
;
782 return PlUser
::GENDER_MALE
;
784 $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
789 private static function formatBirthDate($birthDate)
791 // strtotime believes dd/mm/yyyy to be an US date (i.e mm/dd/yyyy), and
792 // dd-mm-yyyy to be a normal date (i.e dd-mm-yyyy)...
793 return date("Y-m-d", strtotime(str_replace('/', '-', $birthDate)));
796 function handler_add_accounts(&$page, $action = null
, $promo = null
)
798 $page->changeTpl('admin/add_accounts.tpl');
800 if (Env
::has('add_type') && Env
::has('people')) {
801 $lines = explode("\n", Env
::t('people'));
802 $separator = Env
::t('separator');
803 $promotion = Env
::i('promotion');
804 $nameTypes = DirEnum
::getOptions(DirEnum
::NAMETYPES
);
805 $nameTypes = array_flip($nameTypes);
807 if (Env
::t('add_type') == 'promo') {
809 $eduSchools = DirEnum
::getOptions(DirEnum
::EDUSCHOOLS
);
810 $eduSchools = array_flip($eduSchools);
811 $eduDegrees = DirEnum
::getOptions(DirEnum
::EDUDEGREES
);
812 $eduDegrees = array_flip($eduDegrees);
813 switch (Env
::t('edu_type')) {
815 $degreeid = $eduDegrees[Profile
::DEGREE_X
];
816 $entry_year = $promotion;
817 $grad_year = $promotion +
3;
818 $promo = 'X' . $promotion;
819 $hrpromo = $promotion;
822 $degreeid = $eduDegrees[Profile
::DEGREE_M
];
823 $grad_year = $promotion;
824 $entry_year = $promotion - 2;
825 $promo = 'M' . $promotion;
830 $degreeid = $eduDegrees[Profile
::DEGREE_D
];
831 $grad_year = $promotion;
832 $entry_year = $promotion - 3;
833 $promo = 'D' . $promotion;
838 $page->killError("La formation n'est pas reconnue:" . Env
::t('edu_type') . '.');
841 XDB
::startTransaction();
842 foreach ($lines as $line) {
843 if ($infos = self
::formatNewUser($page, $line, $separator, $hrpromo, 6)) {
844 $sex = self
::formatSex($page, $infos[3], $line);
845 if (!is_null($sex)) {
846 $fullName = $infos[1] . ' ' . $infos[0];
847 $directoryName = $infos[0] . ' ' . $infos[1];
848 $birthDate = self
::formatBirthDate($infos[2]);
849 $xorgId = Profile
::getXorgId($infos[4]);
850 if (is_null($xorgId)) {
851 $page->trigError("La ligne $line n'a pas été ajoutée car le matricule École est mal renseigné.");
855 XDB
::execute('INSERT INTO profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex)
856 VALUES ({?}, {?}, {?}, {?}, {?})',
857 $infos['hrid'], $xorgId, $infos[5], $birthDate, $sex);
858 $pid = XDB
::insertId();
859 XDB
::execute('INSERT INTO profile_name (pid, name, typeid)
860 VALUES ({?}, {?}, {?}),
864 $pid, $infos[0], $nameTypes['name_ini'],
865 $pid, $infos[0], $nameTypes['lastname'],
866 $pid, $infos[1], $nameTypes['firstname_ini'],
867 $pid, $infos[1], $nameTypes['firstname']);
868 XDB
::execute('INSERT INTO profile_display (pid, yourself, public_name, private_name,
869 directory_name, short_name, sort_name, promo)
870 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
871 $pid, $infos[1], $fullName, $fullName, $directoryName, $fullName, $directoryName, $promo);
872 XDB
::execute('INSERT INTO profile_education (pid, eduid, degreeid, entry_year, grad_year, flags)
873 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
874 $pid, $eduSchools[Profile
::EDU_X
], $degreeid, $entry_year, $grad_year, 'primary');
875 XDB
::execute('INSERT INTO accounts (hruid, type, is_admin, state, full_name, directory_name, display_name, sex)
876 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
877 $infos['hrid'], $type, 0, 'pending', $fullName, $directoryName, $infos[1], $sex);
878 $uid = XDB
::insertId();
879 XDB
::execute('INSERT INTO account_profiles (uid, pid, perms)
880 VALUES ({?}, {?}, {?})',
881 $uid, $pid, 'owner');
882 Profile
::rebuildSearchTokens($pid, false
);
887 } else if (Env
::t('add_type') == 'account') {
888 $type = Env
::t('type');
889 $newAccounts = array();
890 foreach ($lines as $line) {
891 if ($infos = self
::formatNewUser($page, $line, $separator, $type, 4)) {
892 $sex = self
::formatSex($page, $infos[3], $line);
893 if (!is_null($sex)) {
894 $fullName = $infos[1] . ' ' . $infos[0];
895 $directoryName = $infos[0] . ' ' . $infos[1];
896 XDB
::execute('INSERT INTO accounts (hruid, type, is_admin, state,
897 email, full_name, directory_name,
899 VALUES ({?}, {?}, {?}, {?},
900 {?}, {?}, {?}, {?}, {?})',
901 $infos['hrid'], $type, 0, 'pending',
902 $infos[2], $fullName, $directoryName,
904 $newAccounts[$infos['hrid']] = $infos[1] . ' ' . $infos[0];
908 if (!empty($newAccounts)) {
909 $page->assign('newAccounts', $newAccounts);
911 } else if (Env
::t('add_type') == 'ax_id') {
913 foreach ($lines as $line) {
914 if ($infos = self
::formatNewUser($page, $line, $separator, $promotion, 3)) {
915 XDB
::execute('UPDATE profiles
918 $infos[2], $infos['hrid']);
923 $errors = $page->nb_errs();
925 $page->trigSuccess("L'opération a été effectuée avec succès.");
927 $page->trigSuccess('L\'opération a été effectuée avec succès, sauf pour '
928 . (($errors == 1) ?
'l\'erreur signalée' : "les $errors erreurs signalées") . ' ci-dessus.');
930 } else if (Env
::has('add_type')) {
931 $res = XDB
::query('SELECT type
932 FROM account_types');
933 $page->assign('account_types', $res->fetchColumn());
934 $page->assign('add_type', Env
::s('add_type'));
938 function handler_homonyms(&$page, $op = 'list', $target = null
)
940 $page->changeTpl('admin/homonymes.tpl');
941 $page->setTitle('Administration - Homonymes');
942 $this->load("homonyms.inc.php");
945 $user = User
::getSilent($target);
946 if (!$user ||
!($loginbis = select_if_homonyme($user))) {
949 $page->assign('user', $user);
950 $page->assign('loginbis',$loginbis);
954 $page->assign('op', $op);
955 $page->assign('target', $target);
957 // on a un $target valide, on prepare les mails
959 // on examine l'op a effectuer
962 S
::assert_xsrf_token();
964 send_warning_homonyme($user, $loginbis);
965 switch_bestalias($user, $loginbis);
967 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
971 S
::assert_xsrf_token();
973 switch_bestalias($user, $loginbis);
974 XDB
::execute("UPDATE aliases
975 SET type = 'homonyme', expire=NOW()
976 WHERE alias = {?}", $loginbis);
977 XDB
::execute("REPLACE INTO homonyms (homonyme_id, uid)
978 VALUES ({?}, {?})", $target, $target);
979 send_robot_homonyme($user, $loginbis);
981 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
987 $res = XDB
::iterator(
988 "SELECT a.alias AS homonyme, s.alias AS forlife,
989 IF(h.homonyme_id = s.uid, a.expire, NULL) AS expire,
990 IF(h.homonyme_id = s.uid, a.type, NULL) AS type, ac.uid
992 LEFT JOIN homonyms AS h ON (h.homonyme_id = a.uid)
993 INNER JOIN aliases AS s ON (s.uid = h.uid AND s.type = 'a_vie')
994 INNER JOIN accounts AS ac ON (ac.uid = a.uid)
995 WHERE a.type = 'homonyme' OR a.expire != ''
996 ORDER BY a.alias, forlife");
998 while ($tab = $res->next()) {
999 $hnymes[$tab['homonyme']][] = $tab;
1001 $page->assign_by_ref('hnymes', $hnymes);
1005 function handler_deaths(&$page, $promo = 0, $validate = false
)
1007 $page->changeTpl('admin/deces_promo.tpl');
1008 $page->setTitle('Administration - Deces');
1011 $promo = Env
::t('promo', 'X1923');
1013 $page->assign('promo', $promo);
1019 S
::assert_xsrf_token();
1021 $res = XDB
::iterRow('SELECT p.pid, pd.directory_name, p.deathdate
1023 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1024 WHERE pd.promo = {?}', $promo);
1025 while (list($pid, $name, $death) = $res->next()) {
1026 $val = Env
::v('death_' . $pid);
1027 if ($val == $death) {
1034 XDB
::execute('UPDATE profiles
1035 SET deathdate = {?}, deathdate_rec = NOW()
1036 WHERE pid = {?}', $val, $pid);
1038 $page->trigSuccess('Édition du décès de ' . $name . ' (' . ($val ?
$val : 'ressuscité') . ').');
1039 if ($val && ($death == '0000-00-00' ||
empty($death))) {
1040 $profile = Profile
::get($pid);
1042 $profile->owner()->clear(false
);
1047 $res = XDB
::iterator('SELECT p.pid, pd.directory_name, p.deathdate
1049 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1050 WHERE pd.promo = {?}
1051 ORDER BY pd.sort_name', $promo);
1052 $page->assign('profileList', $res);
1055 function handler_dead_but_active(&$page)
1057 $page->changeTpl('admin/dead_but_active.tpl');
1058 $page->setTitle('Administration - Décédés');
1060 $res = XDB
::iterator(
1061 "SELECT a.hruid, pd.promo, p.ax_id, pd.directory_name, p.deathdate, DATE(MAX(s.start)) AS last
1063 INNER JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET('owner', ap.perms))
1064 INNER JOIN profiles AS p ON (p.pid = ap.pid)
1065 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
1066 LEFT JOIN log_sessions AS s ON (s.uid = a.uid AND suid = 0)
1067 WHERE a.state = 'active' AND p.deathdate IS NOT NULL
1069 ORDER BY pd.promo, pd.sort_name");
1070 $page->assign('dead', $res);
1073 function handler_validate(&$page, $action = 'list', $id = null
)
1075 $page->changeTpl('admin/validation.tpl');
1076 $page->setTitle('Administration - Valider une demande');
1077 $page->addCssLink('nl.css');
1079 if ($action == 'edit' && !is_null($id)) {
1080 $page->assign('preview_id', $id);
1082 $page->assign('preview_id', null
);
1085 if(Env
::has('uid') && Env
::has('type') && Env
::has('stamp')) {
1086 S
::assert_xsrf_token();
1088 $req = Validate
::get_typed_request(Env
::v('uid'), Env
::v('type'), Env
::v('stamp'));
1090 $req->handle_formu();
1092 $page->trigWarning('La validation a déjà été effectuée.');
1096 $r = XDB
::iterator('SHOW COLUMNS FROM requests_answers');
1097 while (($a = $r->next()) && $a['Field'] != 'category');
1098 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
1101 $res = XDB
::query('SELECT hidden_requests
1102 FROM requests_hidden
1103 WHERE uid = {?}', S
::v('uid'));
1104 $hide_requests = $res->fetchOneCell();
1105 if (Post
::has('hide')) {
1107 foreach ($categories as $cat)
1108 if (!Post
::v($cat)) {
1112 $hide_requests = join(',', $hide);
1113 XDB
::query('REPLACE INTO requests_hidden (uid, hidden_requests)
1115 S
::v('uid'), $hide_requests);
1116 } elseif ($hide_requests) {
1117 foreach (explode(',', $hide_requests) as $hide_type)
1118 $hidden[$hide_type] = true
;
1120 $page->assign('hide_requests', $hidden);
1122 // Update the count of item to validate here... useful in development configuration
1123 // where several copies of the site use the same DB, but not the same "dynamic configuration"
1125 $globals->updateNbValid();
1126 $page->assign('vit', Validate
::iterate());
1129 function handler_validate_answers(&$page, $action = 'list', $id = null
)
1131 $page->setTitle('Administration - Réponses automatiques de validation');
1132 $page->assign('title', 'Gestion des réponses automatiques');
1133 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
1134 $table_editor->describe('category','catégorie',true
);
1135 $table_editor->describe('title','titre',true
);
1136 $table_editor->describe('answer','texte',false
);
1137 $table_editor->apply($page, $action, $id);
1140 function handler_skins(&$page, $action = 'list', $id = null
)
1142 $page->setTitle('Administration - Skins');
1143 $page->assign('title', 'Gestion des skins');
1144 $table_editor = new PLTableEditor('admin/skins','skins','id');
1145 $table_editor->describe('name','nom',true
);
1146 $table_editor->describe('skin_tpl','nom du template',true
);
1147 $table_editor->describe('auteur','auteur',false
);
1148 $table_editor->describe('comment','commentaire',true
);
1149 $table_editor->describe('date','date',false
);
1150 $table_editor->describe('ext','extension du screenshot',false
);
1151 $table_editor->apply($page, $action, $id);
1154 function handler_postfix_blacklist(&$page, $action = 'list', $id = null
)
1156 $page->setTitle('Administration - Postfix : Blacklist');
1157 $page->assign('title', 'Blacklist de postfix');
1158 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true
);
1159 $table_editor->describe('reject_text','Texte de rejet',true
);
1160 $table_editor->describe('email','email',true
);
1161 $table_editor->apply($page, $action, $id);
1164 function handler_postfix_whitelist(&$page, $action = 'list', $id = null
)
1166 $page->setTitle('Administration - Postfix : Whitelist');
1167 $page->assign('title', 'Whitelist de postfix');
1168 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true
);
1169 $table_editor->describe('email','email',true
);
1170 $table_editor->apply($page, $action, $id);
1173 function handler_mx_broken(&$page, $action = 'list', $id = null
)
1175 $page->setTitle('Administration - MX Défaillants');
1176 $page->assign('title', 'MX Défaillant');
1177 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true
);
1178 $table_editor->describe('host', 'Masque', true
);
1179 $table_editor->describe('state', 'Niveau', true
);
1180 $table_editor->describe('text', 'Description du problème', false
);
1181 $table_editor->apply($page, $action, $id);
1184 function handler_logger_actions(&$page, $action = 'list', $id = null
)
1186 $page->setTitle('Administration - Actions');
1187 $page->assign('title', 'Gestion des actions de logger');
1188 $table_editor = new PLTableEditor('admin/logger/actions','log_actions','id');
1189 $table_editor->describe('text','intitulé',true
);
1190 $table_editor->describe('description','description',true
);
1191 $table_editor->apply($page, $action, $id);
1194 function handler_downtime(&$page, $action = 'list', $id = null
)
1196 $page->setTitle('Administration - Coupures');
1197 $page->assign('title', 'Gestion des coupures');
1198 $table_editor = new PLTableEditor('admin/downtime','downtimes','id');
1199 $table_editor->describe('debut','date',true
);
1200 $table_editor->describe('duree','durée',false
);
1201 $table_editor->describe('resume','résumé',true
);
1202 $table_editor->describe('services','services affectés',true
);
1203 $table_editor->describe('description','description',false
);
1204 $table_editor->apply($page, $action, $id);
1207 function handler_accounts(PlPage
$page)
1209 $page->changeTpl('admin/accounts.tpl');
1210 $page->setTitle('Administration - Comptes');
1211 $page->addJsLink('password.js');
1213 if (Post
::has('create_account')) {
1214 S
::assert_xsrf_token();
1215 $firstname = Post
::t('firstname');
1216 $lastname = strtoupper(Post
::t('lastname'));
1217 $sex = Post
::s('sex');
1218 $email = Post
::t('email');
1219 $type = Post
::s('type');
1220 $login = PlUser
::makeHrid($firstname, $lastname, $type);
1221 if (!isvalid_email($email)) {
1222 $page->trigError("Invalid email address: $email");
1223 } else if (strlen(Post
::s('pwhash')) != 40) {
1224 $page->trigError("Invalid password hash");
1226 $full_name = $firstname . ' ' . $lastname;
1227 $directory_name = $lastname . ' ' . $firstname;
1228 XDB
::execute("INSERT INTO accounts (hruid, type, state, password,
1229 registration_date, email, full_name,
1230 display_name, sex, directory_name)
1231 VALUES ({?}, {?}, 'active', {?}, NOW(), {?}, {?}, {?}, {?}, {?})",
1232 $login, $type, Post
::s('pwhash'), $email, $full_name, $full_name, $sex,
1237 $uf = new UserFilter(new UFC_AccountType('ax', 'school', 'fx'));
1238 $page->assign('users', $uf->iterUsers());
1242 function handler_account_types(&$page, $action = 'list', $id = null
)
1244 $page->setTitle('Administration - Types de comptes');
1245 $page->assign('title', 'Gestion des types de comptes');
1246 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true
);
1247 $table_editor->describe('type', 'Catégorie', true
);
1248 $table_editor->describe('perms', 'Permissions associées', true
);
1249 $table_editor->apply($page, $action, $id);
1252 function handler_wiki(&$page, $action = 'list', $wikipage = null
, $wikipage2 = null
)
1254 if (S
::hasAuthToken()) {
1255 $page->setRssLink('Changement Récents',
1256 '/Site/AllRecentChanges?action=rss&user=' . S
::v('hruid') . '&hash=' . S
::user()->token
);
1259 // update wiki perms
1260 if ($action == 'update') {
1261 S
::assert_xsrf_token();
1263 $perms_read = Post
::v('read');
1264 $perms_edit = Post
::v('edit');
1265 if ($perms_read ||
$perms_edit) {
1266 foreach ($_POST as $wiki_page => $val) {
1268 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1269 if ($wp->setPerms($perms_read ?
$perms_read : $wp->readPerms(),
1270 $perms_edit ?
$perms_edit : $wp->writePerms())) {
1271 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1273 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1278 } else if ($action != 'list' && !empty($wikipage)) {
1279 $wp = new PlWikiPage($wikipage);
1280 S
::assert_xsrf_token();
1282 if ($action == 'delete') {
1283 if ($wp->delete()) {
1284 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1286 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1288 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1289 if ($changedLinks = $wp->rename($wikipage2)) {
1290 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1291 if (is_numeric($changedLinks)) {
1292 $s .= $changedLinks.' lien'.(($changedLinks>1)?
's ont été modifiés.':' a été modifié.');
1294 $page->trigSuccess($s);
1296 $page->trigError("Impossible de déplacer la page ".$wikipage);
1301 $perms = PlWikiPage
::permOptions();
1303 // list wiki pages and their perms
1304 $wiki_pages = PlWikiPage
::listPages();
1306 $wiki_tree = array();
1307 foreach ($wiki_pages as $file => $desc) {
1308 list($cat, $name) = explode('.', $file);
1309 if (!isset($wiki_tree[$cat])) {
1310 $wiki_tree[$cat] = array();
1312 $wiki_tree[$cat][$name] = $desc;
1315 $page->changeTpl('admin/wiki.tpl');
1316 $page->assign('wiki_pages', $wiki_tree);
1317 $page->assign('perms_opts', $perms);
1320 function handler_ipwatch(&$page, $action = 'list', $ip = null
)
1322 $page->changeTpl('admin/ipwatcher.tpl');
1324 $states = array('safe' => 'Ne pas surveiller',
1325 'unsafe' => 'Surveiller les inscriptions',
1326 'dangerous' => 'Surveiller tous les accès',
1327 'ban' => 'Bannir cette adresse');
1328 $page->assign('states', $states);
1330 switch (Post
::v('action')) {
1332 if (trim(Post
::v('ipN')) != '') {
1333 S
::assert_xsrf_token();
1334 Xdb
::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1335 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1336 ip_to_uint(trim(Post
::v('ipN'))), ip_to_uint(trim(Post
::v('maskN'))),
1337 Post
::v('stateN'), S
::i('uid'), Post
::v('descriptionN'));
1342 S
::assert_xsrf_token();
1343 Xdb
::execute('UPDATE ip_watch
1344 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1345 WHERE ip = {?}', Post
::v('stateN'), S
::i('uid'), Post
::v('descriptionN'),
1346 ip_to_uint(Post
::v('maskN')), ip_to_uint(Post
::v('ipN')));
1350 if ($action == 'delete' && !is_null($ip)) {
1351 S
::assert_xsrf_token();
1352 Xdb
::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1355 if ($action != 'create' && $action != 'edit') {
1358 $page->assign('action', $action);
1360 if ($action == 'list') {
1361 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1362 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1363 IF(w.ip = s.ip, s.host, s.forward_host)),
1364 w.mask, w.detection, w.state, a.hruid
1366 LEFT JOIN log_sessions AS s ON (s.ip = w.ip)
1367 LEFT JOIN log_sessions AS s2 ON (s2.forward_ip = w.ip)
1368 LEFT JOIN accounts AS a ON (a.uid = s.uid)
1369 GROUP BY w.ip, a.hruid
1370 ORDER BY w.state, w.ip, a.hruid";
1371 $it = Xdb
::iterRow($sql);
1375 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1376 $ip = uint_to_ip($ip);
1377 $mask = uint_to_ip($mask);
1378 if (count($props) == 0 ||
$props['ip'] != $ip) {
1379 if (count($props) > 0) {
1382 $props = array('ip' => $ip,
1385 'detection' => $date,
1387 'users' => array($hruid));
1389 $props['users'][] = $hruid;
1392 if (count($props) > 0) {
1395 $page->assign('table', $table);
1396 } elseif ($action == 'edit') {
1397 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1398 a1.hruid AS edit, a2.hruid AS hruid, s.host
1400 LEFT JOIN accounts AS a1 ON (a1.uid = w.uid)
1401 LEFT JOIN log_sessions AS s ON (w.ip = s.ip)
1402 LEFT JOIN accounts AS a2 ON (a2.uid = s.uid)
1406 $it = Xdb
::iterRow($sql, ip_to_uint($ip));
1409 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1410 if (count($props) == 0) {
1411 $props = array('ip' => $ip,
1412 'mask' => uint_to_ip($mask),
1414 'detection' => $detection,
1417 'description' => $description,
1419 'users' => array($hruid));
1421 $props['users'][] = $hruid;
1424 $page->assign('ip', $props);
1428 function handler_icons(&$page)
1430 $page->changeTpl('admin/icons.tpl');
1431 $dh = opendir('../htdocs/images/icons');
1433 $page->trigError('Dossier des icones introuvables.');
1436 while (($file = readdir($dh)) !== false
) {
1437 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1438 array_push($icons, substr($file, 0, -4));
1442 $page->assign('icons', $icons);
1445 function handler_account_watch(&$page)
1447 $page->changeTpl('admin/accounts.tpl');
1448 $page->assign('disabled', XDB
::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1449 a.state = \'disabled\' AS disabled, a.comment
1451 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1452 ORDER BY a.hruid'));
1453 $page->assign('admins', XDB
::iterator('SELECT a.hruid
1456 ORDER BY a.hruid'));
1459 function handler_jobs(&$page, $id = -1)
1461 $page->changeTpl('admin/jobs.tpl');
1463 if (Env
::has('search')) {
1464 $res = XDB
::query("SELECT id, name, acronym
1465 FROM profile_job_enum
1466 WHERE name LIKE CONCAT('%', {?}, '%') OR acronym LIKE CONCAT('%', {?}, '%')",
1467 Env
::t('job'), Env
::t('job'));
1469 if ($res->numRows() <= 20) {
1470 $page->assign('jobs', $res->fetchAllAssoc());
1472 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1475 $page->assign('askedJob', Env
::v('job'));
1479 if (Env
::has('edit')) {
1480 S
::assert_xsrf_token();
1481 $selectedJob = Env
::has('selectedJob');
1483 Phone
::deletePhones(0, Phone
::LINK_COMPANY
, $id);
1484 Address
::deleteAddresses(null
, Address
::LINK_COMPANY
, $id);
1485 if (Env
::has('change')) {
1486 XDB
::execute('UPDATE profile_job
1489 Env
::i('newJobId'), $id);
1490 XDB
::execute('DELETE FROM profile_job_enum
1494 $page->trigSuccess("L'entreprise a bien été remplacée.");
1496 XDB
::execute('UPDATE profile_job_enum
1497 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1498 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1500 Env
::t('name'), Env
::t('acronym'), Env
::t('url'), Env
::t('email'),
1501 Env
::t('NAF_code'), Env
::i('AX_code'), Env
::i('holdingId'), $id);
1503 $phone = new Phone(array('display' => Env
::v('tel'), 'link_id' => $id, 'id' => 0, 'type' => 'fixed',
1504 'link_type' => Phone
::LINK_COMPANY
, 'pub' => 'public'));
1505 $fax = new Phone(array('display' => Env
::v('fax'), 'link_id' => $id, 'id' => 1, 'type' => 'fax',
1506 'link_type' => Phone
::LINK_COMPANY
, 'pub' => 'public'));
1507 $address = new Address(array('jobid' => $jobid, 'type' => Address
::LINK_COMPANY
, 'text' => Env
::t('address')));
1512 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1516 if (!Env
::has('change') && $id != -1) {
1517 $res = XDB
::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1518 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1519 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1520 FROM profile_job_enum AS e
1521 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
1522 LEFT JOIN profile_phones AS t ON (t.pid = e.id AND t.link_type = 'hq' AND t.tel_id = 0)
1523 LEFT JOIN profile_phones AS f ON (f.pid = e.id AND f.link_type = 'hq' AND f.tel_id = 1)
1524 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1528 if ($res->numRows() == 0) {
1529 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1531 $page->assign('selectedJob', $res->fetchOneAssoc());
1537 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: