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,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/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,edit_directory'),
54 'admin/profile' => $this->make_hook('profile', AUTH_MDP
, 'admin,edit_directory')
58 function handler_phpinfo(&$page)
64 function handler_get_rights(&$page)
67 $page->kill('Déjà en SUID');
69 S
::assert_xsrf_token();
70 $level = Post
::s('account_type');
71 if ($level != 'admin') {
72 $user = User
::getSilentWithUID(S
::user()->id());
73 $user->is_admin
= false
;
74 $types = DirEnum
::getOptions(DirEnum
::ACCOUNTTYPES
);
75 if (!empty($types[$level])) {
76 $user->setPerms($types[$level]);
78 S
::set('suid_startpage', $_SERVER['HTTP_REFERER']);
79 Platal
::session()->startSUID($user);
81 if (!empty($_SERVER['HTTP_REFERER'])) {
82 http_redirect($_SERVER['HTTP_REFERER']);
88 function handler_set_skin(&$page)
90 S
::assert_xsrf_token();
91 S
::set('skin', Post
::s('change_skin'));
92 if (!empty($_SERVER['HTTP_REFERER'])) {
93 http_redirect($_SERVER['HTTP_REFERER']);
99 function handler_default(&$page)
101 $page->changeTpl('admin/index.tpl');
102 $page->setTitle('Administration');
105 function handler_postfix_delayed(&$page)
107 $page->changeTpl('admin/postfix_delayed.tpl');
108 $page->setTitle('Administration - Postfix : Retardés');
110 if (Env
::has('del')) {
111 $crc = Env
::v('crc');
112 XDB
::execute("UPDATE postfix_mailseen SET release = 'del' WHERE crc = {?}", $crc);
113 $page->trigSuccess($crc . " verra tous ses emails supprimés !");
114 } elseif (Env
::has('ok')) {
115 $crc = Env
::v('crc');
116 XDB
::execute("UPDATE postfix_mailseen SET release = 'ok' WHERE crc = {?}", $crc);
117 $page->trigSuccess($crc . " a le droit de passer !");
120 $sql = XDB
::iterator(
121 "SELECT crc, nb, update_time, create_time,
122 FIND_IN_SET('del', p.release) AS del,
123 FIND_IN_SET('ok', p.release) AS ok
124 FROM postfix_mailseen AS p
126 ORDER BY p.release != ''");
128 $page->assign_by_ref('mails', $sql);
131 function handler_postfix_regexpsbounces(&$page, $new = null
) {
132 $page->changeTpl('admin/emails_bounces_re.tpl');
133 $page->setTitle('Administration - Postfix : Regexps Bounces');
134 $page->assign('new', $new);
136 if (Post
::has('submit')) {
137 foreach (Env
::v('lvl') as $id=>$val) {
139 "REPLACE INTO emails_bounces_re (id,pos,lvl,re,text) VALUES ({?}, {?}, {?}, {?}, {?})",
140 $id, $_POST['pos'][$id], $_POST['lvl'][$id], $_POST['re'][$id], $_POST['text'][$id]
145 $page->assign('bre', XDB
::iterator("SELECT * FROM emails_bounces_re ORDER BY pos"));
150 /** Retrieves the available days for a given year and month.
151 * Obtain a list of days of the given month in the given year
152 * that are within the range of dates that we have log entries for.
154 * @param integer year
155 * @param integer month
156 * @return array days in that month we have log entries covering.
159 function _getDays($year, $month)
161 // give a 'no filter' option
165 if ($year && $month) {
166 $day_max = Array(-1, 31, checkdate(2, 29, $year) ?
29 : 28 , 31,
167 30, 31, 30, 31, 31, 30, 31, 30, 31);
168 $res = XDB
::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
169 MONTH(MAX(start)), MONTH(MIN(start)),
170 DAYOFMONTH(MAX(start)),
171 DAYOFMONTH(MIN(start))
173 list($ymax, $ymin, $mmax, $mmin, $dmax, $dmin) = $res->fetchOneRow();
175 if (($year < $ymin) ||
($year == $ymin && $month < $mmin)) {
179 if (($year > $ymax) ||
($year == $ymax && $month > $mmax)) {
183 $min = ($year==$ymin && $month==$mmin) ?
intval($dmin) : 1;
184 $max = ($year==$ymax && $month==$mmax) ?
intval($dmax) : $day_max[$month];
186 for($i = $min; $i<=$max; $i++
) {
194 /** Retrieves the available months for a given year.
195 * Obtains a list of month numbers that are within the timeframe that
196 * we have log entries for.
198 * @param integer year
199 * @return array List of month numbers we have log info for.
202 function _getMonths($year)
204 // give a 'no filter' option
209 $res = XDB
::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
210 MONTH(MAX(start)), MONTH(MIN(start))
212 list($ymax, $ymin, $mmax, $mmin) = $res->fetchOneRow();
214 if (($year < $ymin) ||
($year > $ymax)) {
218 $min = $year == $ymin ?
intval($mmin) : 1;
219 $max = $year == $ymax ?
intval($mmax) : 12;
221 for($i = $min; $i<=$max; $i++
) {
229 /** Retrieves the available years.
230 * Obtains a list of years that we have log entries covering.
232 * @return array years we have log entries for.
237 // give a 'no filter' option
241 // retrieve available years
242 $res = XDB
::query("select YEAR(MAX(start)), YEAR(MIN(start)) FROM log_sessions");
243 list($max, $min) = $res->fetchOneRow();
245 for($i = intval($min); $i<=$max; $i++
) {
252 /** Make a where clause to get a user's sessions.
253 * Prepare the where clause request that will retrieve the sessions.
255 * @param $year INTEGER Only get log entries made during the given year.
256 * @param $month INTEGER Only get log entries made during the given month.
257 * @param $day INTEGER Only get log entries made during the given day.
258 * @param $uid INTEGER Only get log entries referring to the given user ID.
260 * @return STRING the WHERE clause of a query, including the 'WHERE' keyword
263 function _makeWhere($year, $month, $day, $uid)
265 // start constructing the "where" clause
269 array_push($where, "s.uid='$uid'");
271 // we were given at least a year
274 $dmin = mktime(0, 0, 0, $month, $day, $year);
275 $dmax = mktime(0, 0, 0, $month, $day+
1, $year);
277 $dmin = mktime(0, 0, 0, $month, 1, $year);
278 $dmax = mktime(0, 0, 0, $month+
1, 1, $year);
280 $dmin = mktime(0, 0, 0, 1, 1, $year);
281 $dmax = mktime(0, 0, 0, 1, 1, $year+
1);
283 $where[] = "start >= " . date("Ymd000000", $dmin);
284 $where[] = "start < " . date("Ymd000000", $dmax);
287 if (!empty($where)) {
288 return ' WHERE ' . implode($where, " AND ");
292 // WE know it's totally reversed, so better use array_reverse than a SORT BY start DESC
297 function handler_logger(&$page, $action = null
, $arg = null
) {
298 if ($action == 'session') {
300 // we are viewing a session
301 $res = XDB
::query("SELECT ls.*, a.hruid AS username, sa.hruid AS suer
302 FROM log_sessions AS ls
303 INNER JOIN accounts AS a ON (a.uid = ls.uid)
304 LEFT JOIN accounts AS sa ON (sa.uid = ls.suid)
305 WHERE ls.id = {?}", $arg);
307 $page->assign('session', $a = $res->fetchOneAssoc());
309 $res = XDB
::iterator('SELECT a.text, e.data, e.stamp
311 LEFT JOIN log_actions AS a ON e.action=a.id
312 WHERE e.session={?}', $arg);
313 while ($myarr = $res->next()) {
314 $page->append('events', $myarr);
318 $loguser = $action == 'user' ?
$arg : Env
::v('loguser');
321 $user = User
::get($loguser);
322 $loguid = $user->id();
328 $year = Env
::i('year');
329 $month = Env
::i('month');
330 $day = Env
::i('day');
332 $year = Env
::i('year', intval(date('Y')));
333 $month = Env
::i('month', intval(date('m')));
334 $day = Env
::i('day', intval(date('d')));
342 // smarty assignments
343 // retrieve available years
344 $page->assign('years', $this->_getYears());
345 $page->assign('year', $year);
347 // retrieve available months for the current year
348 $page->assign('months', $this->_getMonths($year));
349 $page->assign('month', $month);
351 // retrieve available days for the current year and month
352 $page->assign('days', $this->_getDays($year, $month));
353 $page->assign('day', $day);
355 $page->assign('loguser', $loguser);
356 // smarty assignments
358 if ($loguid ||
$year) {
360 // get the requested sessions
361 $where = $this->_makeWhere($year, $month, $day, $loguid);
362 $select = "SELECT s.id, s.start, s.uid,
364 FROM log_sessions AS s
365 INNER JOIN accounts AS a ON (a.uid = s.uid)
367 ORDER BY start DESC";
368 $res = XDB
::iterator($select);
371 while ($mysess = $res->next()) {
372 $mysess['events'] = array();
373 $sessions[$mysess['id']] = $mysess;
375 array_reverse($sessions);
378 $sql = "SELECT s.id, a.text
379 FROM log_sessions AS s
380 LEFT JOIN log_events AS e ON(e.session=s.id)
381 INNER JOIN log_actions AS a ON(a.id=e.action)
384 $res = XDB
::iterator($sql);
385 while ($event = $res->next()) {
386 array_push($sessions[$event['id']]['events'], $event['text']);
388 $page->assign_by_ref('sessions', $sessions);
390 $page->assign('msg_nofilters', "Sélectionner une année et/ou un utilisateur");
394 $page->changeTpl('admin/logger-view.tpl');
396 $page->setTitle('Administration - Logs des sessions');
399 function handler_user(&$page, $login = false
)
402 $page->changeTpl('admin/user.tpl');
403 $page->setTitle('Administration - Compte');
406 $page->kill("Déjà en SUID !!!");
409 // Loads the user identity using the environment.
411 $user = User
::get($login);
414 pl_redirect('admin/accounts');
417 $listClient = new MMList(S
::user());
418 $login = $user->login();
419 $registered = ($user->state
!= 'pending');
422 if (!empty($_POST)) {
423 S
::assert_xsrf_token();
424 if (Post
::has('uid') && Post
::i('uid') != $user->id()) {
425 $page->kill('Une erreur s\'est produite');
429 // Handles specific requests (AX sync, su, ...).
430 if(Post
::has('log_account')) {
431 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
434 if(Post
::has('su_account') && $registered) {
435 if (!Platal
::session()->startSUID($user)) {
436 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->login());
442 // Handles account deletion.
443 if (Post
::has('account_deletion_confirmation')) {
445 $name = $user->fullName();
446 $profile = $user->profile();
447 if ($profile && Post
::b('clear_profile')) {
448 $user->profile()->clear();
451 $page->trigSuccess("L'utilisateur $name ($uid) a bien été désinscrit.");
452 if (Post
::b('erase_account')) {
453 XDB
::execute('DELETE FROM accounts
456 $page->trigSuccess("L'utilisateur $name ($uid) a été supprimé de la base de données");
461 $to_update = array();
462 if (Post
::has('disable_weak_access')) {
463 $to_update['weak_password'] = null
;
464 } else if (Post
::has('update_account')) {
465 if (!$user->hasProfile()) {
466 if (Post
::s('full_name') != $user->fullName()) {
467 $to_update['full_name'] = Post
::s('full_name');
469 if (Post
::s('display_name') != $user->displayName()) {
470 $to_update['display_name'] = Post
::s('display_name');
472 if (Post
::s('directory_name') != $user->directoryName()) {
473 $to_update['directory_name'] = Post
::s('directory_name');
476 if (Post
::s('sex') != ($user->isFemale() ?
'female' : 'male')) {
477 $to_update['sex'] = Post
::s('sex');
478 if ($user->hasProfile()) {
479 XDB
::execute('UPDATE profiles
482 Post
::s('sex'), $user->profile()->id());
485 if (!Post
::blank('pwhash')) {
486 $to_update['password'] = Post
::s('pwhash');
487 require_once 'googleapps.inc.php';
488 $account = new GoogleAppsAccount($user);
489 if ($account->active() && $account->sync_password
) {
490 $account->set_password(Post
::s('pwhash'));
493 if (!Post
::blank('weak_password')) {
494 $to_update['weak_password'] = Post
::s('weak_password');
496 if (Post
::i('token_access', 0) != ($user->token_access ?
1 : 0)) {
497 $to_update['token'] = Post
::i('token_access') ?
rand_url_id(16) : null
;
499 if (Post
::i('skin') != $user->skin
) {
500 $to_update['skin'] = Post
::i('skin');
501 if ($to_update['skin'] == 0) {
502 $to_update['skin'] = null
;
505 if (Post
::s('state') != $user->state
) {
506 $to_update['state'] = Post
::s('state');
508 if (Post
::i('is_admin', 0) != ($user->is_admin ?
1 : 0)) {
509 $to_update['is_admin'] = Post
::b('is_admin');
511 if (Post
::s('type') != $user->type
) {
512 $to_update['type'] = Post
::s('type');
514 if (Post
::i('watch', 0) != ($user->watch ?
1 : 0)) {
515 $to_update['flags'] = new PlFlagset();
516 $to_update['flags']->addFlag('watch', Post
::i('watch'));
518 if (Post
::t('comment') != $user->comment
) {
519 $to_update['comment'] = Post
::blank('comment') ? null
: Post
::t('comment');
521 if (!$user->checkPerms(User
::PERM_MAIL
) && Post
::t('email') != $user->forlifeEmail()) {
522 $to_update['email'] = Post
::t('email');
523 $listClient->change_user_email($user->forlifeEmail(), Post
::t('email'));
526 if (!empty($to_update)) {
527 $res = XDB
::query('SELECT *
529 WHERE uid = {?}', $user->id());
530 $oldValues = $res->fetchAllAssoc();
531 $oldValues = $oldValues[0];
535 foreach ($to_update as $k => $value) {
536 $value = XDB
::format('{?}', $value);
537 $set[] = $k . ' = ' . $value;
538 $diff[$k] = array($oldValues[$k], trim($value, "'"));
539 unset($oldValues[$k]);
541 XDB
::rawExecute('UPDATE accounts
542 SET ' . implode(', ', $set) . '
543 WHERE uid = ' . XDB
::format('{?}', $user->id()));
544 $page->trigSuccess('Données du compte mise à jour avec succès');
545 $user = User
::getWithUID($user->id());
547 /* Formats the $diff and send it to the site administrators. The rules are the folowing:
548 * -formats: password, token, weak_password
550 foreach (array('password', 'token', 'weak_password') as $key) {
551 if (isset($diff[$key])) {
552 $diff[$key] = array('old value', 'new value');
554 $oldValues[$key] = 'old value';
558 $mail = new PlMailer('admin/useredit.mail.tpl');
559 $mail->assign('admin', S
::user()->hruid
);
560 $mail->assign('hruid', $user->hruid
);
561 $mail->assign('diff', $diff);
562 $mail->assign('oldValues', $oldValues);
568 if (Post
::has('add_profile') || Post
::has('del_profile') || Post
::has('owner')) {
569 if (Post
::i('del_profile', 0) != 0) {
570 XDB
::execute('DELETE FROM account_profiles
571 WHERE uid = {?} AND pid = {?}',
572 $user->id(), Post
::i('del_profile'));
573 } else if (!Post
::blank('new_profile')) {
574 $profile = Profile
::get(Post
::t('new_profile'));
576 $page->trigError('Le profil ' . Post
::t('new_profile') . ' n\'existe pas');
578 XDB
::execute('INSERT IGNORE INTO account_profiles (uid, pid)
580 $user->id(), $profile->id());
583 XDB
::execute('UPDATE account_profiles
584 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
586 Post
::i('owner'), $user->id());
590 // Email forwards form {{{
591 require_once("emails.inc.php");
592 $redirect = ($registered ?
new Redirect($user) : null
);
593 if (Post
::has('add_fwd')) {
594 $email = Post
::t('email');
595 if (!isvalid_email_redirection($email)) {
596 $page->trigError("Email non valide: $email");
598 $redirect->add_email($email);
599 $page->trigSuccess("Ajout de $email effectué");
601 } else if (!Post
::blank('del_fwd')) {
602 $redirect->delete_email(Post
::t('del_fwd'));
603 } else if (!Post
::blank('activate_fwd')) {
604 $redirect->modify_one_email(Post
::t('activate_fwd', true
));
605 } else if (!Post
::blank('deactivate_fwd')) {
606 $redirect->modify_one_email(Post
::t('deactivate_fwd', false
));
607 } else if (Post
::has('disable_fwd')) {
608 $redirect->disable();
609 } else if (Post
::has('enable_fwd')) {
611 } else if (!Post
::blank('clean_fwd')) {
612 $redirect->clean_errors(Post
::t('clean_fwd'));
616 // Email alias form {{{
617 if (Post
::has('add_alias')) {
618 // Splits new alias in user and fqdn.
619 $alias = Env
::t('email');
620 if (strpos($alias, '@') !== false
) {
621 list($alias, $domain) = explode('@', $alias);
623 $domain = $globals->mail
->domain
;
626 // Checks for alias' user validity.
627 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
628 $page->trigError("'$alias' n'est pas un alias valide");
631 // Eventually adds the alias to the right domain.
632 if ($domain == $globals->mail
->alias_dom ||
$domain == $globals->mail
->alias_dom2
) {
633 $req = new AliasReq($user, $alias, 'Admin request', false
);
634 if ($req->commit()) {
635 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué");
637 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué");
639 } elseif ($domain == $globals->mail
->domain ||
$domain == $globals->mail
->domain2
) {
640 $res = XDB
::execute("INSERT INTO aliases (uid, alias, type)
641 VALUES ({?}, {?}, 'alias')",
642 $user->id(), $alias);
643 $page->trigSuccess("Nouvel alias '$alias' ajouté");
645 $page->trigError("Le domaine '$domain' n'est pas valide");
647 } else if (!Post
::blank('del_alias')) {
648 XDB
::execute("DELETE FROM aliases
649 WHERE uid = {?} AND alias = {?} AND
650 type NOT IN ('a_vie', 'homonyme')",
652 XDB
::execute("UPDATE emails
654 WHERE uid = {?} AND rewrite LIKE CONCAT({?}, '@%')",
656 fix_bestalias($user);
657 $page->trigSuccess("L'alias '$val' a été supprimé");
658 } else if (!Post
::blank('best')) {
659 XDB
::execute("UPDATE aliases
660 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
661 WHERE uid = {?}", $user->id());
662 XDB
::execute("UPDATE aliases
663 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
664 WHERE uid = {?} AND alias = {?}", $user->id(), $val);
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.core.js');
695 $page->addJsLink('jquery.ui.widget.js');
696 $page->addJsLink('jquery.ui.tabs.js');
697 $page->addJsLink('password.js');
699 // Displays last login and last host information.
700 $res = XDB
::query("SELECT start, host
702 WHERE uid = {?} AND suid = 0
704 LIMIT 1", $user->id());
705 list($lastlogin,$host) = $res->fetchOneRow();
706 $page->assign('lastlogin', $lastlogin);
707 $page->assign('host', $host);
709 // Display mailing lists
710 $page->assign('mlists', $listClient->get_all_user_lists($user->forlifeEmail()));
712 // Display active aliases.
713 $page->assign('virtuals', $user->emailAliases());
714 $page->assign('aliases', XDB
::iterator("SELECT alias, type='a_vie' AS for_life,
715 FIND_IN_SET('bestalias',flags) AS best, expire
717 WHERE uid = {?} AND type != 'homonyme'
718 ORDER BY type != 'a_vie'", $user->id()));
719 $page->assign('account_types', XDB
::iterator('SELECT * FROM account_types ORDER BY type'));
720 $page->assign('skins', XDB
::iterator('SELECT id, name FROM skins ORDER BY name'));
721 $page->assign('profiles', XDB
::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
722 FROM account_profiles AS ap
723 INNER JOIN profiles AS p ON (ap.pid = p.pid)
724 WHERE ap.uid = {?}', $user->id()));
725 $page->assign('openid', XDB
::iterator('SELECT id, url
726 FROM account_auth_openid
727 WHERE uid = {?}', $user->id()));
729 // Displays email redirection and the general profile.
730 if ($registered && $redirect) {
731 $page->assign('emails', $redirect->emails
);
734 $page->assign('user', $user);
735 $page->assign('hasProfile', $user->hasProfile());
737 // Displays forum bans.
738 $res = XDB
::query("SELECT write_perm, read_perm, comment
740 WHERE uid = {?}", $user->id());
741 $bans = $res->fetchOneAssoc();
742 $page->assign('bans', $bans);
745 private static function getHrid($firstname, $lastname, $promo)
747 if ($firstname != null
&& $lastname != null
&& $promo != null
) {
748 return User
::makeHrid($firstname, $lastname, $promo);
753 private static function formatNewUser(&$page, $infosLine, $separator, $promo, $size)
755 $infos = explode($separator, $infosLine);
756 if (sizeof($infos) > $size ||
sizeof($infos) < 2) {
757 $page->trigError("La ligne $infosLine n'a pas été ajoutée.");
761 $infos = array_map('trim', $infos);
762 $hrid = self
::getHrid($infos[1], $infos[0], $promo);
763 $res1 = XDB
::query('SELECT COUNT(*)
765 WHERE hruid = {?}', $hrid);
766 $res2 = XDB
::query('SELECT COUNT(*)
768 WHERE hrpid = {?}', $hrid);
769 if (is_null($hrid) ||
$res1->fetchOneCell() > 0 ||
$res2->fetchOneCell() > 0) {
770 $page->trigError("La ligne $infosLine n'a pas été ajoutée: une entrée similaire existe déjà");
773 $infos['hrid'] = $hrid;
777 private static function formatSex(&$page, $sex, $line)
781 return PlUser
::GENDER_FEMALE
;
783 return PlUser
::GENDER_MALE
;
785 $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
790 private static function formatBirthDate($birthDate)
792 // strtotime believes dd/mm/yyyy to be an US date (i.e mm/dd/yyyy), and
793 // dd-mm-yyyy to be a normal date (i.e dd-mm-yyyy)...
794 return date("Y-m-d", strtotime(str_replace('/', '-', $birthDate)));
797 function handler_add_accounts(&$page, $action = null
, $promo = null
)
799 $page->changeTpl('admin/add_accounts.tpl');
801 if (Env
::has('add_type') && Env
::has('people')) {
802 $lines = explode("\n", Env
::t('people'));
803 $separator = Env
::t('separator');
804 $promotion = Env
::i('promotion');
805 $nameTypes = DirEnum
::getOptions(DirEnum
::NAMETYPES
);
806 $nameTypes = array_flip($nameTypes);
808 if (Env
::t('add_type') == 'promo') {
810 $eduSchools = DirEnum
::getOptions(DirEnum
::EDUSCHOOLS
);
811 $eduSchools = array_flip($eduSchools);
812 $eduDegrees = DirEnum
::getOptions(DirEnum
::EDUDEGREES
);
813 $eduDegrees = array_flip($eduDegrees);
814 switch (Env
::t('edu_type')) {
816 $degreeid = $eduDegrees[Profile
::DEGREE_X
];
817 $entry_year = $promotion;
818 $grad_year = $promotion +
3;
819 $promo = 'X' . $promotion;
820 $hrpromo = $promotion;
823 $degreeid = $eduDegrees[Profile
::DEGREE_M
];
824 $grad_year = $promotion;
825 $entry_year = $promotion - 2;
826 $promo = 'M' . $promotion;
831 $degreeid = $eduDegrees[Profile
::DEGREE_D
];
832 $grad_year = $promotion;
833 $entry_year = $promotion - 3;
834 $promo = 'D' . $promotion;
839 $page->killError("La formation n'est pas reconnue:" . Env
::t('edu_type') . '.');
842 XDB
::startTransaction();
843 foreach ($lines as $line) {
844 if ($infos = self
::formatNewUser($page, $line, $separator, $hrpromo, 6)) {
845 $sex = self
::formatSex($page, $infos[3], $line);
846 if (!is_null($sex)) {
847 $fullName = $infos[1] . ' ' . $infos[0];
848 $directoryName = $infos[0] . ' ' . $infos[1];
849 $birthDate = self
::formatBirthDate($infos[2]);
850 $xorgId = Profile
::getXorgId($infos[4]);
851 if (is_null($xorgId)) {
852 $page->trigError("La ligne $line n'a pas été ajoutée car le matricule École est mal renseigné.");
856 XDB
::execute('INSERT INTO profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex)
857 VALUES ({?}, {?}, {?}, {?}, {?})',
858 $infos['hrid'], $xorgId, $infos[5], $birthDate, $sex);
859 $pid = XDB
::insertId();
860 XDB
::execute('INSERT INTO profile_name (pid, name, typeid)
861 VALUES ({?}, {?}, {?}),
865 $pid, $infos[0], $nameTypes['name_ini'],
866 $pid, $infos[0], $nameTypes['lastname'],
867 $pid, $infos[1], $nameTypes['firstname_ini'],
868 $pid, $infos[1], $nameTypes['firstname']);
869 XDB
::execute('INSERT INTO profile_display (pid, yourself, public_name, private_name,
870 directory_name, short_name, sort_name, promo)
871 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
872 $pid, $infos[1], $fullName, $fullName, $directoryName, $fullName, $directoryName, $promo);
873 XDB
::execute('INSERT INTO profile_education (pid, eduid, degreeid, entry_year, grad_year, flags)
874 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
875 $pid, $eduSchools[Profile
::EDU_X
], $degreeid, $entry_year, $grad_year, 'primary');
876 XDB
::execute('INSERT INTO accounts (hruid, type, is_admin, state, full_name, directory_name, display_name, sex)
877 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
878 $infos['hrid'], $type, 0, 'pending', $fullName, $directoryName, $infos[1], $sex);
879 $uid = XDB
::insertId();
880 XDB
::execute('INSERT INTO account_profiles (uid, pid, perms)
881 VALUES ({?}, {?}, {?})',
882 $uid, $pid, 'owner');
883 Profile
::rebuildSearchTokens($pid, false
);
888 } else if (Env
::t('add_type') == 'account') {
889 $type = Env
::t('type');
890 $newAccounts = array();
891 foreach ($lines as $line) {
892 if ($infos = self
::formatNewUser($page, $line, $separator, $type, 4)) {
893 $sex = self
::formatSex($page, $infos[3], $line);
894 if (!is_null($sex)) {
895 $fullName = $infos[1] . ' ' . $infos[0];
896 $directoryName = $infos[0] . ' ' . $infos[1];
897 XDB
::execute('INSERT INTO accounts (hruid, type, is_admin, state,
898 email, full_name, directory_name,
900 VALUES ({?}, {?}, {?}, {?},
901 {?}, {?}, {?}, {?}, {?})',
902 $infos['hrid'], $type, 0, 'pending',
903 $infos[2], $fullName, $directoryName,
905 $newAccounts[$infos['hrid']] = $infos[1] . ' ' . $infos[0];
909 if (!empty($newAccounts)) {
910 $page->assign('newAccounts', $newAccounts);
912 } else if (Env
::t('add_type') == 'ax_id') {
914 foreach ($lines as $line) {
915 if ($infos = self
::formatNewUser($page, $line, $separator, $promotion, 3)) {
916 XDB
::execute('UPDATE profiles
919 $infos[2], $infos['hrid']);
924 $errors = $page->nb_errs();
926 $page->trigSuccess("L'opération a été effectuée avec succès.");
928 $page->trigSuccess('L\'opération a été effectuée avec succès, sauf pour '
929 . (($errors == 1) ?
'l\'erreur signalée' : "les $errors erreurs signalées") . ' ci-dessus.');
931 } else if (Env
::has('add_type')) {
932 $res = XDB
::query('SELECT type
933 FROM account_types');
934 $page->assign('account_types', $res->fetchColumn());
935 $page->assign('add_type', Env
::s('add_type'));
939 function handler_homonyms(&$page, $op = 'list', $target = null
)
941 $page->changeTpl('admin/homonymes.tpl');
942 $page->setTitle('Administration - Homonymes');
943 $this->load("homonyms.inc.php");
946 $user = User
::getSilent($target);
947 if (!$user ||
!($loginbis = select_if_homonyme($user))) {
950 $page->assign('user', $user);
951 $page->assign('loginbis',$loginbis);
955 $page->assign('op', $op);
956 $page->assign('target', $target);
958 // on a un $target valide, on prepare les mails
960 // on examine l'op a effectuer
963 S
::assert_xsrf_token();
965 send_warning_homonyme($user, $loginbis);
966 switch_bestalias($user, $loginbis);
968 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
972 S
::assert_xsrf_token();
974 switch_bestalias($user, $loginbis);
975 XDB
::execute("UPDATE aliases
976 SET type = 'homonyme', expire=NOW()
977 WHERE alias = {?}", $loginbis);
978 XDB
::execute('INSERT IGNORE INTO homonyms (homonyme_id, uid)
979 VALUES ({?}, {?})', $target, $target);
980 send_robot_homonyme($user, $loginbis);
982 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
988 $res = XDB
::iterator(
989 "SELECT a.alias AS homonyme, s.alias AS forlife,
990 IF(h.homonyme_id = s.uid, a.expire, NULL) AS expire,
991 IF(h.homonyme_id = s.uid, a.type, NULL) AS type, ac.uid
993 LEFT JOIN homonyms AS h ON (h.homonyme_id = a.uid)
994 INNER JOIN aliases AS s ON (s.uid = h.uid AND s.type = 'a_vie')
995 INNER JOIN accounts AS ac ON (ac.uid = a.uid)
996 WHERE a.type = 'homonyme' OR a.expire != ''
997 ORDER BY a.alias, forlife");
999 while ($tab = $res->next()) {
1000 $hnymes[$tab['homonyme']][] = $tab;
1002 $page->assign_by_ref('hnymes', $hnymes);
1006 function handler_deaths(&$page, $promo = 0, $validate = false
)
1008 $page->changeTpl('admin/deces_promo.tpl');
1009 $page->setTitle('Administration - Deces');
1012 $promo = Env
::t('promo', 'X1923');
1014 $page->assign('promo', $promo);
1020 S
::assert_xsrf_token();
1022 $res = XDB
::iterRow('SELECT p.pid, pd.directory_name, p.deathdate
1024 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1025 WHERE pd.promo = {?}', $promo);
1026 while (list($pid, $name, $death) = $res->next()) {
1027 $val = Env
::v('death_' . $pid);
1028 if ($val == $death) {
1035 XDB
::execute('UPDATE profiles
1036 SET deathdate = {?}, deathdate_rec = NOW()
1037 WHERE pid = {?}', $val, $pid);
1039 $page->trigSuccess('Édition du décès de ' . $name . ' (' . ($val ?
$val : 'ressuscité') . ').');
1040 if ($val && ($death == '0000-00-00' ||
empty($death))) {
1041 $profile = Profile
::get($pid);
1043 $profile->owner()->clear(false
);
1048 $res = XDB
::iterator('SELECT p.pid, pd.directory_name, p.deathdate
1050 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1051 WHERE pd.promo = {?}
1052 ORDER BY pd.sort_name', $promo);
1053 $page->assign('profileList', $res);
1056 function handler_dead_but_active(&$page)
1058 $page->changeTpl('admin/dead_but_active.tpl');
1059 $page->setTitle('Administration - Décédés');
1061 $res = XDB
::iterator(
1062 "SELECT a.hruid, pd.promo, p.ax_id, pd.directory_name, p.deathdate, DATE(MAX(s.start)) AS last
1064 INNER JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET('owner', ap.perms))
1065 INNER JOIN profiles AS p ON (p.pid = ap.pid)
1066 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
1067 LEFT JOIN log_sessions AS s ON (s.uid = a.uid AND suid = 0)
1068 WHERE a.state = 'active' AND p.deathdate IS NOT NULL
1070 ORDER BY pd.promo, pd.sort_name");
1071 $page->assign('dead', $res);
1074 function handler_validate(&$page, $action = 'list', $id = null
)
1076 $page->changeTpl('admin/validation.tpl');
1077 $page->setTitle('Administration - Valider une demande');
1078 $page->addCssLink('nl.css');
1080 if ($action == 'edit' && !is_null($id)) {
1081 $page->assign('preview_id', $id);
1083 $page->assign('preview_id', null
);
1086 if(Env
::has('uid') && Env
::has('type') && Env
::has('stamp')) {
1087 S
::assert_xsrf_token();
1089 $req = Validate
::get_typed_request(Env
::v('uid'), Env
::v('type'), Env
::v('stamp'));
1091 $req->handle_formu();
1093 $page->trigWarning('La validation a déjà été effectuée.');
1097 $r = XDB
::iterator('SHOW COLUMNS FROM requests_answers');
1098 while (($a = $r->next()) && $a['Field'] != 'category');
1099 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
1102 $res = XDB
::query('SELECT hidden_requests
1103 FROM requests_hidden
1104 WHERE uid = {?}', S
::v('uid'));
1105 $hide_requests = $res->fetchOneCell();
1106 if (Post
::has('hide')) {
1108 foreach ($categories as $cat)
1109 if (!Post
::v($cat)) {
1113 $hide_requests = join(',', $hide);
1114 XDB
::query('INSERT INTO requests_hidden (uid, hidden_requests)
1116 ON DUPLICATE KEY UPDATE hidden_requests = VALUES(hidden_requests)',
1117 S
::v('uid'), $hide_requests);
1118 } elseif ($hide_requests) {
1119 foreach (explode(',', $hide_requests) as $hide_type)
1120 $hidden[$hide_type] = true
;
1122 $page->assign('hide_requests', $hidden);
1124 // Update the count of item to validate here... useful in development configuration
1125 // where several copies of the site use the same DB, but not the same "dynamic configuration"
1127 $globals->updateNbValid();
1128 $page->assign('vit', Validate
::iterate());
1129 $page->assign('isAdmin', S
::admin());
1132 function handler_validate_answers(&$page, $action = 'list', $id = null
)
1134 $page->setTitle('Administration - Réponses automatiques de validation');
1135 $page->assign('title', 'Gestion des réponses automatiques');
1136 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
1137 $table_editor->describe('category','catégorie',true
);
1138 $table_editor->describe('title','titre',true
);
1139 $table_editor->describe('answer','texte',false
);
1140 $table_editor->apply($page, $action, $id);
1143 function handler_skins(&$page, $action = 'list', $id = null
)
1145 $page->setTitle('Administration - Skins');
1146 $page->assign('title', 'Gestion des skins');
1147 $table_editor = new PLTableEditor('admin/skins','skins','id');
1148 $table_editor->describe('name','nom',true
);
1149 $table_editor->describe('skin_tpl','nom du template',true
);
1150 $table_editor->describe('auteur','auteur',false
);
1151 $table_editor->describe('comment','commentaire',true
);
1152 $table_editor->describe('date','date',false
);
1153 $table_editor->describe('ext','extension du screenshot',false
);
1154 $table_editor->apply($page, $action, $id);
1157 function handler_postfix_blacklist(&$page, $action = 'list', $id = null
)
1159 $page->setTitle('Administration - Postfix : Blacklist');
1160 $page->assign('title', 'Blacklist de postfix');
1161 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true
);
1162 $table_editor->describe('reject_text','Texte de rejet',true
);
1163 $table_editor->describe('email','email',true
);
1164 $table_editor->apply($page, $action, $id);
1167 function handler_postfix_whitelist(&$page, $action = 'list', $id = null
)
1169 $page->setTitle('Administration - Postfix : Whitelist');
1170 $page->assign('title', 'Whitelist de postfix');
1171 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true
);
1172 $table_editor->describe('email','email',true
);
1173 $table_editor->apply($page, $action, $id);
1176 function handler_mx_broken(&$page, $action = 'list', $id = null
)
1178 $page->setTitle('Administration - MX Défaillants');
1179 $page->assign('title', 'MX Défaillant');
1180 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true
);
1181 $table_editor->describe('host', 'Masque', true
);
1182 $table_editor->describe('state', 'Niveau', true
);
1183 $table_editor->describe('text', 'Description du problème', false
);
1184 $table_editor->apply($page, $action, $id);
1187 function handler_logger_actions(&$page, $action = 'list', $id = null
)
1189 $page->setTitle('Administration - Actions');
1190 $page->assign('title', 'Gestion des actions de logger');
1191 $table_editor = new PLTableEditor('admin/logger/actions','log_actions','id');
1192 $table_editor->describe('text','intitulé',true
);
1193 $table_editor->describe('description','description',true
);
1194 $table_editor->apply($page, $action, $id);
1197 function handler_downtime(&$page, $action = 'list', $id = null
)
1199 $page->setTitle('Administration - Coupures');
1200 $page->assign('title', 'Gestion des coupures');
1201 $table_editor = new PLTableEditor('admin/downtime','downtimes','id');
1202 $table_editor->describe('debut','date',true
);
1203 $table_editor->describe('duree','durée',false
);
1204 $table_editor->describe('resume','résumé',true
);
1205 $table_editor->describe('services','services affectés',true
);
1206 $table_editor->describe('description','description',false
);
1207 $table_editor->apply($page, $action, $id);
1210 function handler_accounts(PlPage
$page)
1212 $page->changeTpl('admin/accounts.tpl');
1213 $page->setTitle('Administration - Comptes');
1214 $page->addJsLink('password.js');
1216 if (Post
::has('create_account')) {
1217 S
::assert_xsrf_token();
1218 $firstname = Post
::t('firstname');
1219 $lastname = strtoupper(Post
::t('lastname'));
1220 $sex = Post
::s('sex');
1221 $email = Post
::t('email');
1222 $type = Post
::s('type');
1223 $login = PlUser
::makeHrid($firstname, $lastname, $type);
1224 if (!isvalid_email($email)) {
1225 $page->trigError("Invalid email address: $email");
1226 } else if (strlen(Post
::s('pwhash')) != 40) {
1227 $page->trigError("Invalid password hash");
1229 $full_name = $firstname . ' ' . $lastname;
1230 $directory_name = $lastname . ' ' . $firstname;
1231 XDB
::execute("INSERT INTO accounts (hruid, type, state, password,
1232 registration_date, email, full_name,
1233 display_name, sex, directory_name)
1234 VALUES ({?}, {?}, 'active', {?}, NOW(), {?}, {?}, {?}, {?}, {?})",
1235 $login, $type, Post
::s('pwhash'), $email, $full_name, $full_name, $sex,
1240 $uf = new UserFilter(new UFC_AccountType('ax', 'school', 'fx'));
1241 $page->assign('users', $uf->iterUsers());
1245 function handler_account_types(&$page, $action = 'list', $id = null
)
1247 $page->setTitle('Administration - Types de comptes');
1248 $page->assign('title', 'Gestion des types de comptes');
1249 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true
);
1250 $table_editor->describe('type', 'Catégorie', true
);
1251 $table_editor->describe('perms', 'Permissions associées', true
);
1252 $table_editor->apply($page, $action, $id);
1255 function handler_wiki(&$page, $action = 'list', $wikipage = null
, $wikipage2 = null
)
1257 if (S
::hasAuthToken()) {
1258 $page->setRssLink('Changement Récents',
1259 '/Site/AllRecentChanges?action=rss&user=' . S
::v('hruid') . '&hash=' . S
::user()->token
);
1262 // update wiki perms
1263 if ($action == 'update') {
1264 S
::assert_xsrf_token();
1266 $perms_read = Post
::v('read');
1267 $perms_edit = Post
::v('edit');
1268 if ($perms_read ||
$perms_edit) {
1269 foreach ($_POST as $wiki_page => $val) {
1271 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1272 if ($wp->setPerms($perms_read ?
$perms_read : $wp->readPerms(),
1273 $perms_edit ?
$perms_edit : $wp->writePerms())) {
1274 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1276 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1281 } else if ($action != 'list' && !empty($wikipage)) {
1282 $wp = new PlWikiPage($wikipage);
1283 S
::assert_xsrf_token();
1285 if ($action == 'delete') {
1286 if ($wp->delete()) {
1287 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1289 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1291 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1292 if ($changedLinks = $wp->rename($wikipage2)) {
1293 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1294 if (is_numeric($changedLinks)) {
1295 $s .= $changedLinks.' lien'.(($changedLinks>1)?
's ont été modifiés.':' a été modifié.');
1297 $page->trigSuccess($s);
1299 $page->trigError("Impossible de déplacer la page ".$wikipage);
1304 $perms = PlWikiPage
::permOptions();
1306 // list wiki pages and their perms
1307 $wiki_pages = PlWikiPage
::listPages();
1309 $wiki_tree = array();
1310 foreach ($wiki_pages as $file => $desc) {
1311 list($cat, $name) = explode('.', $file);
1312 if (!isset($wiki_tree[$cat])) {
1313 $wiki_tree[$cat] = array();
1315 $wiki_tree[$cat][$name] = $desc;
1318 $page->changeTpl('admin/wiki.tpl');
1319 $page->assign('wiki_pages', $wiki_tree);
1320 $page->assign('perms_opts', $perms);
1323 function handler_ipwatch(&$page, $action = 'list', $ip = null
)
1325 $page->changeTpl('admin/ipwatcher.tpl');
1327 $states = array('safe' => 'Ne pas surveiller',
1328 'unsafe' => 'Surveiller les inscriptions',
1329 'dangerous' => 'Surveiller tous les accès',
1330 'ban' => 'Bannir cette adresse');
1331 $page->assign('states', $states);
1333 switch (Post
::v('action')) {
1335 if (trim(Post
::v('ipN')) != '') {
1336 S
::assert_xsrf_token();
1337 Xdb
::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1338 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1339 ip_to_uint(trim(Post
::v('ipN'))), ip_to_uint(trim(Post
::v('maskN'))),
1340 Post
::v('stateN'), S
::i('uid'), Post
::v('descriptionN'));
1345 S
::assert_xsrf_token();
1346 Xdb
::execute('UPDATE ip_watch
1347 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1348 WHERE ip = {?}', Post
::v('stateN'), S
::i('uid'), Post
::v('descriptionN'),
1349 ip_to_uint(Post
::v('maskN')), ip_to_uint(Post
::v('ipN')));
1353 if ($action == 'delete' && !is_null($ip)) {
1354 S
::assert_xsrf_token();
1355 Xdb
::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1358 if ($action != 'create' && $action != 'edit') {
1361 $page->assign('action', $action);
1363 if ($action == 'list') {
1364 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1365 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1366 IF(w.ip = s.ip, s.host, s.forward_host)),
1367 w.mask, w.detection, w.state, a.hruid
1369 LEFT JOIN log_sessions AS s ON (s.ip = w.ip)
1370 LEFT JOIN log_sessions AS s2 ON (s2.forward_ip = w.ip)
1371 LEFT JOIN accounts AS a ON (a.uid = s.uid)
1372 GROUP BY w.ip, a.hruid
1373 ORDER BY w.state, w.ip, a.hruid";
1374 $it = Xdb
::iterRow($sql);
1378 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1379 $ip = uint_to_ip($ip);
1380 $mask = uint_to_ip($mask);
1381 if (count($props) == 0 ||
$props['ip'] != $ip) {
1382 if (count($props) > 0) {
1385 $props = array('ip' => $ip,
1388 'detection' => $date,
1390 'users' => array($hruid));
1392 $props['users'][] = $hruid;
1395 if (count($props) > 0) {
1398 $page->assign('table', $table);
1399 } elseif ($action == 'edit') {
1400 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1401 a1.hruid AS edit, a2.hruid AS hruid, s.host
1403 LEFT JOIN accounts AS a1 ON (a1.uid = w.uid)
1404 LEFT JOIN log_sessions AS s ON (w.ip = s.ip)
1405 LEFT JOIN accounts AS a2 ON (a2.uid = s.uid)
1409 $it = Xdb
::iterRow($sql, ip_to_uint($ip));
1412 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1413 if (count($props) == 0) {
1414 $props = array('ip' => $ip,
1415 'mask' => uint_to_ip($mask),
1417 'detection' => $detection,
1420 'description' => $description,
1422 'users' => array($hruid));
1424 $props['users'][] = $hruid;
1427 $page->assign('ip', $props);
1431 function handler_icons(&$page)
1433 $page->changeTpl('admin/icons.tpl');
1434 $dh = opendir('../htdocs/images/icons');
1436 $page->trigError('Dossier des icones introuvables.');
1439 while (($file = readdir($dh)) !== false
) {
1440 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1441 array_push($icons, substr($file, 0, -4));
1445 $page->assign('icons', $icons);
1448 function handler_account_watch(&$page)
1450 $page->changeTpl('admin/accounts.tpl');
1451 $page->assign('disabled', XDB
::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1452 a.state = \'disabled\' AS disabled, a.comment
1454 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1455 ORDER BY a.hruid'));
1456 $page->assign('admins', XDB
::iterator('SELECT a.hruid
1459 ORDER BY a.hruid'));
1462 function handler_jobs(&$page, $id = -1)
1464 $page->changeTpl('admin/jobs.tpl');
1466 if (Env
::has('search')) {
1467 $res = XDB
::query("SELECT id, name, acronym
1468 FROM profile_job_enum
1469 WHERE name LIKE CONCAT('%', {?}, '%') OR acronym LIKE CONCAT('%', {?}, '%')",
1470 Env
::t('job'), Env
::t('job'));
1472 if ($res->numRows() <= 20) {
1473 $page->assign('jobs', $res->fetchAllAssoc());
1475 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1478 $page->assign('askedJob', Env
::v('job'));
1482 if (Env
::has('edit')) {
1483 S
::assert_xsrf_token();
1484 $selectedJob = Env
::has('selectedJob');
1486 Phone
::deletePhones(0, Phone
::LINK_COMPANY
, $id);
1487 Address
::deleteAddresses(null
, Address
::LINK_COMPANY
, $id);
1488 if (Env
::has('change')) {
1489 if (Env
::has('newJobId') && Env
::i('newJobId') > 0) {
1490 XDB
::execute('UPDATE profile_job
1493 Env
::i('newJobId'), $id);
1494 XDB
::execute('DELETE FROM profile_job_enum
1498 $page->trigSuccess("L'entreprise a bien été remplacée.");
1500 $page->trigError("L'entreprise n'a pas été remplacée car l'identifiant fourni n'est pas valide.");
1503 XDB
::execute('UPDATE profile_job_enum
1504 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1505 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1507 Env
::t('name'), Env
::t('acronym'), Env
::t('url'), Env
::t('email'),
1508 (Env
::t('NAF_code') == 0 ? null
: Env
::t('NAF_code')),
1509 (Env
::i('AX_code') == 0 ? null
: Env
::t('AX_code')),
1510 (Env
::i('holdingId') == 0 ? null
: Env
::t('holdingId')), $id);
1512 $phone = new Phone(array('display' => Env
::v('tel'), 'link_id' => $id, 'id' => 0, 'type' => 'fixed',
1513 'link_type' => Phone
::LINK_COMPANY
, 'pub' => 'public'));
1514 $fax = new Phone(array('display' => Env
::v('fax'), 'link_id' => $id, 'id' => 1, 'type' => 'fax',
1515 'link_type' => Phone
::LINK_COMPANY
, 'pub' => 'public'));
1516 $address = new Address(array('jobid' => $id, 'type' => Address
::LINK_COMPANY
, 'text' => Env
::t('address')));
1521 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1525 if (!Env
::has('change') && $id != -1) {
1526 $res = XDB
::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1527 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1528 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1529 FROM profile_job_enum AS e
1530 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
1531 LEFT JOIN profile_phones AS t ON (t.pid = e.id AND t.link_type = 'hq' AND t.tel_id = 0)
1532 LEFT JOIN profile_phones AS f ON (f.pid = e.id AND f.link_type = 'hq' AND f.tel_id = 1)
1533 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1537 if ($res->numRows() == 0) {
1538 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1540 $page->assign('selectedJob', $res->fetchOneAssoc());
1545 function handler_profile(&$page)
1547 $page->changeTpl('admin/profile.tpl');
1549 if (Post
::has('checked')) {
1550 S
::assert_xsrf_token();
1551 $res = XDB
::iterator('SELECT DISTINCT(pm.pid), pd.public_name
1552 FROM profile_modifications AS pm
1553 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1554 WHERE pm.type = \'self\'');
1556 while ($profile = $res->next()) {
1557 if (Post
::has('checked_' . $profile['pid'])) {
1558 XDB
::execute('DELETE FROM profile_modifications
1559 WHERE type = \'self\' AND pid = {?}', $profile['pid']);
1561 $page->trigSuccess('Profil de ' . $profile['public_name'] . ' vérifié.');
1566 $res = XDB
::iterator('SELECT p.hrpid, pm.pid, pd.directory_name, GROUP_CONCAT(pm.field SEPARATOR \', \') AS field
1567 FROM profile_modifications AS pm
1568 INNER JOIN profiles AS p ON (pm.pid = p.pid)
1569 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1570 WHERE pm.type = \'self\'
1571 GROUP BY pd.directory_name
1572 ORDER BY pd.directory_name');
1573 $page->assign('updates', $res);
1577 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: