Merge commit 'origin/master' into fusionax
[platal.git] / modules / admin.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2009 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
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. *
10 * *
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. *
15 * *
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 *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 class AdminModule extends PLModule
23 {
24 function handlers()
25 {
26 return array(
27 'phpinfo' => $this->make_hook('phpinfo', AUTH_MDP, 'admin'),
28 'admin' => $this->make_hook('default', AUTH_MDP, 'admin'),
29 'admin/ax-xorg' => $this->make_hook('ax_xorg', AUTH_MDP, 'admin'),
30 'admin/dead-but-active' => $this->make_hook('dead_but_active', AUTH_MDP, 'admin'),
31 'admin/deaths' => $this->make_hook('deaths', AUTH_MDP, 'admin'),
32 'admin/downtime' => $this->make_hook('downtime', AUTH_MDP, 'admin'),
33 'admin/homonyms' => $this->make_hook('homonyms', AUTH_MDP, 'admin'),
34 'admin/logger' => $this->make_hook('logger', AUTH_MDP, 'admin'),
35 'admin/logger/actions' => $this->make_hook('logger_actions', AUTH_MDP, 'admin'),
36 'admin/postfix/blacklist' => $this->make_hook('postfix_blacklist', AUTH_MDP, 'admin'),
37 'admin/postfix/delayed' => $this->make_hook('postfix_delayed', AUTH_MDP, 'admin'),
38 'admin/postfix/regexp_bounces' => $this->make_hook('postfix_regexpsbounces', AUTH_MDP, 'admin'),
39 'admin/postfix/whitelist' => $this->make_hook('postfix_whitelist', AUTH_MDP, 'admin'),
40 'admin/mx/broken' => $this->make_hook('mx_broken', AUTH_MDP, 'admin'),
41 'admin/skins' => $this->make_hook('skins', AUTH_MDP, 'admin'),
42 'admin/synchro_ax' => $this->make_hook('synchro_ax', AUTH_MDP, 'admin'),
43 'admin/user' => $this->make_hook('user', AUTH_MDP, 'admin'),
44 'admin/promo' => $this->make_hook('promo', 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/jobs' => $this->make_hook('jobs', AUTH_MDP, 'admin'),
52 );
53 }
54
55 function handler_phpinfo(&$page)
56 {
57 phpinfo();
58 exit;
59 }
60
61 function handler_default(&$page)
62 {
63 $page->changeTpl('admin/index.tpl');
64 $page->setTitle('Administration');
65 }
66
67 function handler_postfix_delayed(&$page)
68 {
69 $page->changeTpl('admin/postfix_delayed.tpl');
70 $page->setTitle('Administration - Postfix : Retardés');
71
72 if (Env::has('del')) {
73 $crc = Env::v('crc');
74 XDB::execute("UPDATE postfix_mailseen SET release = 'del' WHERE crc = {?}", $crc);
75 $page->trigSuccess($crc." verra tous ses emails supprimés !");
76 } elseif (Env::has('ok')) {
77 $crc = Env::v('crc');
78 XDB::execute("UPDATE postfix_mailseen SET release = 'ok' WHERE crc = {?}", $crc);
79 $page->trigSuccess($crc." a le droit de passer !");
80 }
81
82 $sql = XDB::iterator(
83 "SELECT crc, nb, update_time, create_time,
84 FIND_IN_SET('del', release) AS del,
85 FIND_IN_SET('ok', release) AS ok
86 FROM postfix_mailseen
87 WHERE nb >= 30
88 ORDER BY release != ''");
89
90 $page->assign_by_ref('mails', $sql);
91 }
92
93 function handler_postfix_regexpsbounces(&$page, $new = null) {
94 $page->changeTpl('admin/emails_bounces_re.tpl');
95 $page->setTitle('Administration - Postfix : Regexps Bounces');
96 $page->assign('new', $new);
97
98 if (Post::has('submit')) {
99 foreach (Env::v('lvl') as $id=>$val) {
100 XDB::query(
101 "REPLACE INTO emails_bounces_re (id,pos,lvl,re,text) VALUES ({?}, {?}, {?}, {?}, {?})",
102 $id, $_POST['pos'][$id], $_POST['lvl'][$id], $_POST['re'][$id], $_POST['text'][$id]
103 );
104 }
105 }
106
107 $page->assign('bre', XDB::iterator("SELECT * FROM emails_bounces_re ORDER BY pos"));
108 }
109
110 // {{{ logger view
111
112 /** Retrieves the available days for a given year and month.
113 * Obtain a list of days of the given month in the given year
114 * that are within the range of dates that we have log entries for.
115 *
116 * @param integer year
117 * @param integer month
118 * @return array days in that month we have log entries covering.
119 * @private
120 */
121 function _getDays($year, $month)
122 {
123 // give a 'no filter' option
124 $months[0] = "----";
125
126 if ($year && $month) {
127 $day_max = Array(-1, 31, checkdate(2, 29, $year) ? 29 : 28 , 31,
128 30, 31, 30, 31, 31, 30, 31, 30, 31);
129 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
130 MONTH(MAX(start)), MONTH(MIN(start)),
131 DAYOFMONTH(MAX(start)),
132 DAYOFMONTH(MIN(start))
133 FROM logger.sessions");
134 list($ymax, $ymin, $mmax, $mmin, $dmax, $dmin) = $res->fetchOneRow();
135
136 if (($year < $ymin) || ($year == $ymin && $month < $mmin)) {
137 return array();
138 }
139
140 if (($year > $ymax) || ($year == $ymax && $month > $mmax)) {
141 return array();
142 }
143
144 $min = ($year==$ymin && $month==$mmin) ? intval($dmin) : 1;
145 $max = ($year==$ymax && $month==$mmax) ? intval($dmax) : $day_max[$month];
146
147 for($i = $min; $i<=$max; $i++) {
148 $days[$i] = $i;
149 }
150 }
151 return $days;
152 }
153
154
155 /** Retrieves the available months for a given year.
156 * Obtains a list of month numbers that are within the timeframe that
157 * we have log entries for.
158 *
159 * @param integer year
160 * @return array List of month numbers we have log info for.
161 * @private
162 */
163 function _getMonths($year)
164 {
165 // give a 'no filter' option
166 $months[0] = "----";
167
168 if ($year) {
169 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
170 MONTH(MAX(start)), MONTH(MIN(start))
171 FROM logger.sessions");
172 list($ymax, $ymin, $mmax, $mmin) = $res->fetchOneRow();
173
174 if (($year < $ymin) || ($year > $ymax)) {
175 return array();
176 }
177
178 $min = $year == $ymin ? intval($mmin) : 1;
179 $max = $year == $ymax ? intval($mmax) : 12;
180
181 for($i = $min; $i<=$max; $i++) {
182 $months[$i] = $i;
183 }
184 }
185 return $months;
186 }
187
188
189 /** Retrieves the available years.
190 * Obtains a list of years that we have log entries covering.
191 *
192 * @return array years we have log entries for.
193 * @private
194 */
195 function _getYears()
196 {
197 // give a 'no filter' option
198 $years[0] = "----";
199
200 // retrieve available years
201 $res = XDB::query("select YEAR(MAX(start)), YEAR(MIN(start)) FROM logger.sessions");
202 list($max, $min) = $res->fetchOneRow();
203
204 for($i = intval($min); $i<=$max; $i++) {
205 $years[$i] = $i;
206 }
207 return $years;
208 }
209
210
211 /** Make a where clause to get a user's sessions.
212 * Prepare the where clause request that will retrieve the sessions.
213 *
214 * @param $year INTEGER Only get log entries made during the given year.
215 * @param $month INTEGER Only get log entries made during the given month.
216 * @param $day INTEGER Only get log entries made during the given day.
217 * @param $uid INTEGER Only get log entries referring to the given user ID.
218 *
219 * @return STRING the WHERE clause of a query, including the 'WHERE' keyword
220 * @private
221 */
222 function _makeWhere($year, $month, $day, $uid)
223 {
224 // start constructing the "where" clause
225 $where = array();
226
227 if ($uid)
228 array_push($where, "uid='$uid'");
229
230 // we were given at least a year
231 if ($year) {
232 if ($day) {
233 $dmin = mktime(0, 0, 0, $month, $day, $year);
234 $dmax = mktime(0, 0, 0, $month, $day+1, $year);
235 } elseif ($month) {
236 $dmin = mktime(0, 0, 0, $month, 1, $year);
237 $dmax = mktime(0, 0, 0, $month+1, 1, $year);
238 } else {
239 $dmin = mktime(0, 0, 0, 1, 1, $year);
240 $dmax = mktime(0, 0, 0, 1, 1, $year+1);
241 }
242 $where[] = "start >= " . date("Ymd000000", $dmin);
243 $where[] = "start < " . date("Ymd000000", $dmax);
244 }
245
246 if (!empty($where)) {
247 return ' WHERE ' . implode($where, " AND ");
248 } else {
249 return '';
250 }
251 // WE know it's totally reversed, so better use array_reverse than a SORT BY start DESC
252 }
253
254 // }}}
255
256 function handler_logger(&$page, $action = null, $arg = null) {
257 if ($action == 'session') {
258
259 // we are viewing a session
260 $res = XDB::query("SELECT ls.*, a.alias AS username, sa.alias AS suer
261 FROM logger.sessions AS ls
262 LEFT JOIN aliases AS a ON (a.id = ls.uid AND a.type='a_vie')
263 LEFT JOIN aliases AS sa ON (sa.id = ls.suid AND sa.type='a_vie')
264 WHERE ls.id = {?}", $arg);
265
266 $page->assign('session', $a = $res->fetchOneAssoc());
267
268 $res = XDB::iterator('SELECT a.text, e.data, e.stamp
269 FROM logger.events AS e
270 LEFT JOIN logger.actions AS a ON e.action=a.id
271 WHERE e.session={?}', $arg);
272 while ($myarr = $res->next()) {
273 $page->append('events', $myarr);
274 }
275
276 } else {
277 $loguser = $action == 'user' ? $arg : Env::v('loguser');
278
279 $res = XDB::query('SELECT id FROM aliases WHERE alias={?}',
280 $loguser);
281 $loguid = $res->fetchOneCell();
282
283 if ($loguid) {
284 $year = Env::i('year');
285 $month = Env::i('month');
286 $day = Env::i('day');
287 } else {
288 $year = Env::i('year', intval(date('Y')));
289 $month = Env::i('month', intval(date('m')));
290 $day = Env::i('day', intval(date('d')));
291 }
292
293 if (!$year)
294 $month = 0;
295 if (!$month)
296 $day = 0;
297
298 // smarty assignments
299 // retrieve available years
300 $page->assign('years', $this->_getYears());
301 $page->assign('year', $year);
302
303 // retrieve available months for the current year
304 $page->assign('months', $this->_getMonths($year));
305 $page->assign('month', $month);
306
307 // retrieve available days for the current year and month
308 $page->assign('days', $this->_getDays($year, $month));
309 $page->assign('day', $day);
310
311 $page->assign('loguser', $loguser);
312 // smarty assignments
313
314 if ($loguid || $year) {
315
316 // get the requested sessions
317 $where = $this->_makeWhere($year, $month, $day, $loguid);
318 $select = "SELECT s.id, s.start, s.uid,
319 a.alias as username
320 FROM logger.sessions AS s
321 LEFT JOIN aliases AS a ON (a.id = s.uid AND a.type='a_vie')
322 $where
323 ORDER BY start DESC";
324 $res = XDB::iterator($select);
325
326 $sessions = array();
327 while ($mysess = $res->next()) {
328 $mysess['events'] = array();
329 $sessions[$mysess['id']] = $mysess;
330 }
331 array_reverse($sessions);
332
333 // attach events
334 $sql = "SELECT s.id, a.text
335 FROM logger.sessions AS s
336 LEFT JOIN logger.events AS e ON(e.session=s.id)
337 INNER JOIN logger.actions AS a ON(a.id=e.action)
338 $where";
339
340 $res = XDB::iterator($sql);
341 while ($event = $res->next()) {
342 array_push($sessions[$event['id']]['events'], $event['text']);
343 }
344 $page->assign_by_ref('sessions', $sessions);
345 } else {
346 $page->assign('msg_nofilters', "Sélectionner une annuée et/ou un utilisateur");
347 }
348 }
349
350 $page->changeTpl('admin/logger-view.tpl');
351
352 $page->setTitle('Administration - Logs des sessions');
353 }
354
355 function handler_user(&$page, $login = false)
356 {
357 global $globals;
358 $page->changeTpl('admin/utilisateurs.tpl');
359 $page->setTitle('Administration - Edit/Su/Log');
360 require_once("emails.inc.php");
361
362 if (S::has('suid')) {
363 $page->kill("Déjà en SUID !!!");
364 }
365
366 // Loads the user identity using the environment.
367 if ($login) {
368 $user = User::get($login);
369 } else if (Env::has('user_id')) {
370 $user = User::get(Env::i('user_id'));
371 } else if (Env::has('login')) {
372 $user = User::get(Env::v('login'));
373 }
374
375 if ($user) {
376 $login = $user->login();
377 $registered = ($user->forlifeEmail() != null);
378 } else {
379 return;
380 }
381
382 // Handles specific requests (AX sync, su, ...).
383 if(Env::has('logs_button') && $registered) {
384 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
385 }
386
387 if (Env::has('ax_button') && $registered) {
388 pl_redirect("admin/synchro_ax/" . $user->login());
389 }
390
391 if(Env::has('suid_button') && $registered) {
392 S::logger()->log("suid_start", "login on " . $user->login());
393 if (!Platal::session()->startSUID($user->id())) {
394 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->id());
395 } else {
396 pl_redirect("");
397 }
398 }
399
400 // Fetches user data.
401 $userinfo_query = "SELECT *, FIND_IN_SET('watch', flags) AS watch, FIND_IN_SET('femme', flags) AS sexe,
402 (year(naissance) > promo - 15 or year(naissance) < promo - 25) AS naiss_err
403 FROM auth_user_md5
404 WHERE user_id = {?}";
405 $mr = XDB::query($userinfo_query, $user->id())->fetchOneAssoc();
406 $redirect = ($registered ? new Redirect($user) : null);
407
408 // Processes admin requests, if any.
409 foreach($_POST as $key => $val) {
410 S::assert_xsrf_token();
411
412 switch ($key) {
413 // Email redirection actions.
414 case "add_fwd":
415 $email = trim(Env::v('email'));
416 if (!isvalid_email_redirection($email)) {
417 $page->trigError("Email non valide: $email");
418 } else {
419 $redirect->add_email($email);
420 $page->trigSuccess("Ajout de $email effectué");
421 }
422 break;
423
424 case "del_fwd":
425 if (!empty($val)) {
426 $redirect->delete_email($val);
427 }
428 break;
429
430 case "activate_fwd":
431 if (!empty($val)) {
432 $redirect->modify_one_email($val, true);
433 }
434 break;
435 case "deactivate_fwd":
436 if (!empty($val)) {
437 $redirect->modify_one_email($val, false);
438 }
439 break;
440 case "disable_fwd":
441 $redirect->disable();
442 break;
443 case "enable_fwd":
444 $redirect->enable();
445 break;
446 case "clean_fwd":
447 if (!empty($val)) {
448 $redirect->clean_errors($val);
449 }
450 break;
451
452 // Alias actions.
453 case "add_alias":
454 global $globals;
455
456 // Splits new alias in user and fqdn.
457 $alias = trim(Env::v('email'));
458 if (strpos($alias, '@') !== false) {
459 list($alias, $domain) = explode('@', $alias);
460 } else {
461 $domain = $globals->mail->domain;
462 }
463
464 // Checks for alias' user validity.
465 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
466 $page->trigError("'$alias' n'est pas un alias valide");
467 }
468
469 // Eventually adds the alias to the right domain.
470 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
471 $req = new AliasReq($user, $alias, 'Admin request', false);
472 if ($req->commit()) {
473 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué");
474 } else {
475 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué");
476 }
477 } elseif ($domain == $globals->mail->domain || $domain == $globals->mail->domain2) {
478 $res = XDB::execute("INSERT INTO aliases (id,alias,type) VALUES ({?}, {?}, 'alias')",
479 $user->id(), $alias);
480 if ($res) {
481 $page->trigSuccess("Nouvel alias '$alias' ajouté");
482 } else {
483 $page->trigError("Impossible d'ajouter l'alias '$alias', il est probablement déjà attribué");
484 }
485 } else {
486 $page->trigError("Le domaine '$domain' n'est pas valide");
487 }
488 break;
489
490 case "del_alias":
491 if (!empty($val)) {
492 XDB::execute("DELETE FROM aliases
493 WHERE id = {?} AND alias = {?} AND
494 type NOT IN ('a_vie', 'homonyme')",
495 $user->id(), $val);
496 XDB::execute("UPDATE emails
497 SET rewrite = ''
498 WHERE uid = {?} AND rewrite LIKE CONCAT({?}, '@%')",
499 $user->id(), $val);
500 fix_bestalias($user);
501 $page->trigSuccess("L'alias '$val' a été supprimé");
502 }
503 break;
504
505 case "best":
506 XDB::execute("UPDATE aliases
507 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
508 WHERE id = {?}", $user->id());
509 XDB::execute("UPDATE aliases
510 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
511 WHERE id = {?} AND alias = {?}", $user->id(), $val);
512
513 // As having a non-null bestalias value is critical in
514 // plat/al's code, we do an a posteriori check on the
515 // validity of the bestalias.
516 fix_bestalias($user);
517 break;
518
519 // Profile edition.
520 case "u_edit":
521 // Loads new values from environment.
522 require_once('secure_hash.inc.php');
523 $pass_encrypted = Env::v('newpass_clair') != "********" ? hash_encrypt(Env::v('newpass_clair')) : Env::v('passw');
524 $naiss = Env::v('naissanceN');
525 $deces = Env::v('decesN');
526 $perms = Env::v('permsN');
527 $prenom = Env::v('prenomN');
528 $nom = Env::v('nomN');
529 $nomusage = Env::v('nomusageN');
530 $promo = Env::i('promoN');
531 $sexe = Env::v('sexeN');
532 $comm = trim(Env::v('commentN'));
533 $watch = Env::v('watchN');
534
535 $flags = ($sexe ? 'femme' : '');
536 if ($watch) {
537 $flags .= ($flags ? ',watch' : 'watch');
538 }
539 if ($watch && !$comm) {
540 $page->trigError("Il est nécessaire de mettre un commentaire pour surveiller un compte");
541 break;
542 }
543
544 // Fetches fields to watch for changes.
545 $watch_query = "SELECT naissance, deces, password, perms, nom_usage,
546 prenom, nom, flags, promo, comment
547 FROM auth_user_md5
548 WHERE user_id = {?}";
549 $old_fields = XDB::query($watch_query, $user->id())->fetchOneAssoc();
550
551 // If user was newly banned, we need to ensure her php session
552 // is killed. This hack is ugly (and largely overkill); it should
553 // however suits our needs.
554 if ($perms == 'disabled' && $old_fields['perms'] != 'disabled') {
555 kill_sessions();
556
557 // Also serve a reminder to the admin: disabling an account
558 // does not deactivate email forwarding.
559 $page->trigWarning("N'oubliez pas, le cas échéant, de désactiver les redirections et le compte GoogleApps de l'utilisateur.");
560 }
561
562 // Updates the user profile with the new values.
563 $res = XDB::execute("UPDATE auth_user_md5
564 SET naissance = {?}, deces = {?}, password = {?},
565 perms = {?}, prenom = {?}, nom = {?}, nom_usage = {?},
566 flags = {?}, promo = {?}, comment = {?}
567 WHERE user_id = {?}",
568 $naiss, $deces, $pass_encrypted,
569 $perms, $prenom, $nom, $nomusage,
570 $flags, $promo, $comm, $user->id());
571 if ($res) {
572 require_once("user.func.inc.php");
573 user_reindex($user->id());
574 $new_fields = XDB::query($watch_query, $user->id())->fetchOneAssoc();
575
576 // Redacts the password in the notification, to avoid transmitting
577 // sensitive information by email.
578 $new_fields['password'] = ($old_fields['password'] != $new_fields['password'] ? 'new' : 'old');
579 $old_fields['password'] = 'old';
580
581 // Notifies the admins of the profile update.
582 $mailer = new PlMailer("admin/useredit.mail.tpl");
583 $mailer->assign("admin", S::user()->login());
584 $mailer->assign("user", $user->login());
585 $mailer->assign('old', $old_fields);
586 $mailer->assign('new', $new_fields);
587 $mailer->send();
588
589 $globals->updateNbIns();
590 $page->trigSuccess("Update was successful.");
591 } else {
592 $page->trigError("Update failed, please double check your values.");
593 }
594
595 // Checks for changes, and updates other tables of plat/al.
596 if (Env::v('nomusageN') != $mr['nom_usage']) {
597 set_new_usage($user->id(), Env::v('nomusageN'), make_username(Env::v('prenomN'), Env::v('nomusageN')));
598 }
599 if (Env::v('decesN') != $mr['deces']) {
600 require_once 'notifs.inc.php';
601 register_watch_op($user->id(), WATCH_DEATH, $mr['deces']);
602 user_clear_all_subs($user->id(), false);
603 }
604
605 // Eventually updates the Google Apps account.
606 if ($globals->mailstorage->googleapps_domain) {
607 // If the user did choose to use synchronized passwords,
608 // and the password was changed, updates the Google Apps
609 // password as well.
610 if (Env::v('newpass_clair') != "********") {
611 require_once 'googleapps.inc.php';
612 $account = new GoogleAppsAccount($user);
613 if ($account->active() && $account->sync_password) {
614 $account->set_password($pass_encrypted);
615 }
616 }
617 }
618
619
620 // Reloads the user profile, to ensure the latest version will
621 // be served to the administrator.
622 $mr = XDB::query($userinfo_query, $user->id())->fetchOneAssoc();
623
624 break;
625
626 // User re-registration.
627 case "u_kill":
628 require_once('user.func.inc.php');
629 user_clear_all_subs($user->id());
630 $globals->updateNbIns();
631 $page->trigSuccess("'" . $user->id() . "' a été désinscrit !");
632
633 $mailer = new PlMailer("admin/useredit.mail.tpl");
634 $mailer->assign("admin", S::user()->login());
635 $mailer->assign("user", $user->login());
636 $mailer->assign("deletion", true);
637 $mailer->send();
638 break;
639
640 // Forum ban update.
641 case "b_edit":
642 XDB::execute("DELETE FROM forums.innd WHERE uid = {?}", $user->id());
643 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
644 XDB::execute("INSERT INTO forums.innd
645 SET ipmin = '0', ipmax = '4294967295',
646 write_perm = {?}, read_perm = {?},
647 comment = {?}, priority = '200', uid = {?}",
648 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
649 }
650 break;
651 }
652 }
653
654 // Displays last login and last host information.
655 $res = XDB::query("SELECT start, host
656 FROM logger.sessions
657 WHERE uid = {?} AND suid = 0
658 ORDER BY start DESC
659 LIMIT 1", $user->id());
660 list($lastlogin,$host) = $res->fetchOneRow();
661 $page->assign('lastlogin', $lastlogin);
662 $page->assign('host', $host);
663
664 // Display active aliases.
665 $page->assign('virtuals', XDB::iterator(
666 "SELECT alias
667 FROM virtual
668 INNER JOIN virtual_redirect USING (vid)
669 WHERE type = 'user' AND (redirect = {?} OR redirect = {?})",
670 $user->forlifeEmail(),
671 // TODO: remove this über-ugly hack. The issue is that you need
672 // to remove all @m4x.org addresses in virtual_redirect first.
673 $user->login() . '@' . $globals->mail->domain2));
674
675 $page->assign('aliases', XDB::iterator(
676 "SELECT alias, type='a_vie' AS for_life,FIND_IN_SET('bestalias',flags) AS best,expire
677 FROM aliases
678 WHERE id = {?} AND type != 'homonyme'
679 ORDER BY type != 'a_vie'", $user->id()));
680
681 // Displays email redirection and the general profile.
682 if ($registered && $redirect) {
683 $page->assign('emails', $redirect->emails);
684 }
685
686 $page->assign('mr', $mr);
687 $page->assign('user', $user);
688
689 // Displays forum bans.
690 $res = XDB::query("SELECT write_perm, read_perm, comment
691 FROM forums.innd
692 WHERE uid = {?}", $user->id());
693 $bans = $res->fetchOneAssoc();
694 $page->assign('bans', $bans);
695 }
696
697 function getHruid($line, $partial_result, $key)
698 {
699 if (!isset($partial_result['nom']) ||
700 !isset($partial_result['prenom']) ||
701 !isset($partial_result['promo'])) {
702 return null;
703 }
704 return make_forlife($partial_result['prenom'], $partial_result['nom'], $partial_result['promo']);
705 }
706
707 function getMatricule($line, $key)
708 {
709 $mat = $line['matricule'];
710 $year = intval(substr($mat, 0, 3));
711 $rang = intval(substr($mat, 3, 3));
712 if ($year > 200) { $year /= 10; };
713 if ($year < 96) {
714 return null;
715 } else {
716 return sprintf('%04u%04u', 1900+$year, $rang);
717 }
718 }
719
720 function handler_promo(&$page, $action = null, $promo = null)
721 {
722 if (Env::has('promo')) {
723 if(Env::i('promo') > 1900 && Env::i('promo') < 2050) {
724 $action = Env::v('valid_promo') == 'Ajouter des membres' ? 'add' : 'ax';
725 pl_redirect('admin/promo/' . $action . '/' . Env::i('promo'));
726 } else {
727 $page->trigError('Promotion non valide.');
728 }
729 }
730
731 $page->changeTpl('admin/promo.tpl');
732 if ($promo > 1900 && $promo < 2050 && ($action == 'add' || $action == 'ax')) {
733 $page->assign('promo', $promo);
734 } else {
735 return;
736 }
737
738 $importer = new CSVImporter('auth_user_md5', 'matricule');
739 $importer->registerFunction('matricule', 'matricule Ecole vers X.org', array($this, 'getMatricule'));
740 switch ($action) {
741 case 'add':
742 $fields = array('hruid', 'nom', 'nom_ini', 'prenom', 'naissance_ini',
743 'prenom_ini', 'promo', 'promo_sortie', 'flags',
744 'matricule', 'matricule_ax', 'perms');
745 $importer->forceValue('promo', $promo);
746 $importer->forceValue('promo_sortie', $promo + 3);
747 // The hruid generation callback is set last, so that it is called once 'promo'
748 // has already been computed for that line.
749 $importer->forceValue('hruid', array($this, 'getHruid'));
750 break;
751 case 'ax':
752 $fields = array('matricule', 'matricule_ax');
753 break;
754 }
755 $importer->apply($page, "admin/promo/$action/$promo", $fields);
756 }
757
758 function handler_homonyms(&$page, $op = 'list', $target = null)
759 {
760 $page->changeTpl('admin/homonymes.tpl');
761 $page->setTitle('Administration - Homonymes');
762 require_once("homonymes.inc.php");
763
764 if ($target) {
765 if (! list($prenom,$nom,$forlife,$loginbis) = select_if_homonyme($target)) {
766 $target=0;
767 } else {
768 $page->assign('nom',$nom);
769 $page->assign('prenom',$prenom);
770 $page->assign('forlife',$forlife);
771 $page->assign('loginbis',$loginbis);
772 }
773 }
774
775 $page->assign('op', $op);
776 $page->assign('target', $target);
777
778 // on a un $target valide, on prepare les mails
779 if ($target) {
780 // on examine l'op a effectuer
781 switch ($op) {
782 case 'mail':
783 S::assert_xsrf_token();
784
785 send_warning_homonyme($prenom, $nom, $forlife, $loginbis);
786 switch_bestalias($target, $loginbis);
787 $op = 'list';
788 $page->trigSuccess('Email envoyé à ' . $forlife . '.');
789 break;
790
791 case 'correct':
792 S::assert_xsrf_token();
793
794 switch_bestalias($target, $loginbis);
795 XDB::execute("UPDATE aliases SET type='homonyme',expire=NOW() WHERE alias={?}", $loginbis);
796 XDB::execute("REPLACE INTO homonymes (homonyme_id,user_id) VALUES({?},{?})", $target, $target);
797 send_robot_homonyme($prenom, $nom, $forlife, $loginbis);
798 $op = 'list';
799 $page->trigSuccess('Email envoyé à ' . $forlife . ', alias supprimé.');
800 break;
801 }
802 }
803
804 if ($op == 'list') {
805 $res = XDB::iterator(
806 "SELECT a.alias AS homonyme,s.id AS user_id,s.alias AS forlife,
807 promo,prenom,nom,
808 IF(h.homonyme_id=s.id, a.expire, NULL) AS expire,
809 IF(h.homonyme_id=s.id, a.type, NULL) AS type
810 FROM aliases AS a
811 LEFT JOIN homonymes AS h ON (h.homonyme_id = a.id)
812 INNER JOIN aliases AS s ON (s.id = h.user_id AND s.type='a_vie')
813 INNER JOIN auth_user_md5 AS u ON (s.id=u.user_id)
814 WHERE a.type='homonyme' OR a.expire!=''
815 ORDER BY a.alias,promo");
816 $hnymes = Array();
817 while ($tab = $res->next()) {
818 $hnymes[$tab['homonyme']][] = $tab;
819 }
820 $page->assign_by_ref('hnymes',$hnymes);
821 }
822 }
823
824 function handler_ax_xorg(&$page) {
825 $page->changeTpl('admin/ax-xorg.tpl');
826 $page->setTitle('Administration - AX/X.org');
827
828 // liste des différences
829 $res = XDB::query(
830 'SELECT u.promo,u.nom AS nom,u.prenom AS prenom,ia.nom AS nomax,ia.prenom AS prenomax,u.matricule AS mat,ia.matricule_ax AS matax
831 FROM auth_user_md5 AS u
832 INNER JOIN identification_ax AS ia ON u.matricule_ax = ia.matricule_ax
833 WHERE (SOUNDEX(u.nom) != SOUNDEX(ia.nom) AND SOUNDEX(CONCAT(ia.particule,u.nom)) != SOUNDEX(ia.nom)
834 AND SOUNDEX(u.nom) != SOUNDEX(ia.nom_patro) AND SOUNDEX(CONCAT(ia.particule,u.nom)) != SOUNDEX(ia.nom_patro))
835 OR u.prenom != ia.prenom OR (u.promo != ia.promo AND u.promo != ia.promo+1 AND u.promo != ia.promo-1)
836 ORDER BY u.promo,u.nom,u.prenom');
837 $page->assign('diffs', $res->fetchAllAssoc());
838
839 // gens à l'ax mais pas chez nous
840 $res = XDB::query(
841 'SELECT ia.promo,ia.nom,ia.nom_patro,ia.prenom
842 FROM identification_ax as ia
843 LEFT JOIN auth_user_md5 AS u ON u.matricule_ax = ia.matricule_ax
844 WHERE u.nom IS NULL');
845 $page->assign('mank', $res->fetchAllAssoc());
846
847 // gens chez nous et pas à l'ax
848 $res = XDB::query('SELECT promo,nom,prenom FROM auth_user_md5 WHERE matricule_ax IS NULL');
849 $page->assign('plus', $res->fetchAllAssoc());
850 }
851
852 function handler_deaths(&$page, $promo = 0, $validate = false) {
853 $page->changeTpl('admin/deces_promo.tpl');
854 $page->setTitle('Administration - Deces');
855
856 if (!$promo)
857 $promo = Env::i('promo');
858 if (Env::has('sub10')) $promo -= 10;
859 if (Env::has('sub01')) $promo -= 1;
860 if (Env::has('add01')) $promo += 1;
861 if (Env::has('add10')) $promo += 10;
862
863 $page->assign('promo',$promo);
864
865 if ($validate) {
866 S::assert_xsrf_token();
867
868 $res = XDB::iterRow("SELECT user_id,matricule,nom,prenom,deces FROM auth_user_md5 WHERE promo = {?}", $promo);
869 while (list($uid,$mat,$nom,$prenom,$deces) = $res->next()) {
870 $val = Env::v($mat);
871 if($val == $deces || empty($val)) {
872 continue;
873 }
874
875 XDB::execute('UPDATE auth_user_md5 SET deces={?} WHERE matricule = {?}', $val, $mat);
876 $page->trigSuccess('Ajout du décès de ' . $prenom . " " . $nom . ' le ' . $val . '.');
877 if($deces == '0000-00-00' || empty($deces)) {
878 require_once('notifs.inc.php');
879 register_watch_op($uid, WATCH_DEATH, $val);
880 require_once('user.func.inc.php');
881 user_clear_all_subs($uid, false); // by default, dead ppl do not loose their email
882 }
883 }
884 }
885
886 $res = XDB::iterator('SELECT matricule, nom, prenom, deces FROM auth_user_md5 WHERE promo = {?} ORDER BY nom,prenom', $promo);
887 $page->assign('decedes', $res);
888 }
889
890 function handler_dead_but_active(&$page) {
891 $page->changeTpl('admin/dead_but_active.tpl');
892 $page->setTitle('Administration - Décédés');
893
894 $res = XDB::iterator(
895 "SELECT u.promo, u.nom, u.prenom, u.deces, u.matricule_ax, u.hruid, DATE(MAX(s.start)) AS last
896 FROM auth_user_md5 AS u
897 LEFT JOIN logger.sessions AS s ON (s.uid = u.user_id AND suid = 0)
898 WHERE perms IN ('admin', 'user') AND deces <> 0
899 GROUP BY u.user_id
900 ORDER BY u.promo, u.nom");
901 $page->assign('dead', $res);
902 }
903
904 function handler_synchro_ax(&$page, $login = null, $action = null) {
905 $page->changeTpl('admin/synchro_ax.tpl');
906 $page->setTitle('Administration - Synchro AX');
907
908 // Checks for synchronization requirements.
909 require_once('synchro_ax.inc.php');
910 if (is_ax_key_missing()) {
911 $page->assign('no_private_key', true);
912 $page->run();
913 }
914
915 // Determines user identity using environment.
916 if ($login) {
917 $user = User::get($login);
918 } else if (Env::has('user')) {
919 $user = User::get(Env::v('user'));
920 } else if (Env::has('mat')) {
921 $res = XDB::query("SELECT user_id FROM auth_user_md5 WHERE matricule = {?}", Env::i('mat'));
922 $user = User::get($res->fetchOneCell());
923 } else {
924 return;
925 }
926
927 // Finally synchronizes the AX and plat/al information.
928 if ($action == 'import') {
929 ax_synchronize($user->login(), S::v('uid'));
930 }
931
932 require_once 'profil.func.inc.php';
933 $userxorg = get_user_details($user->login(), S::v('uid'), 'ax');
934 $userax = get_user_ax($userxorg['matricule_ax']);
935 $diff = diff_user_details($userax, $userxorg, 'ax');
936
937 $page->assign('x', $userxorg);
938 $page->assign('diff', $diff);
939 }
940
941 function handler_validate(&$page, $action = 'list', $id = null)
942 {
943 $page->changeTpl('admin/valider.tpl');
944 $page->setTitle('Administration - Valider une demande');
945 $page->addCssLink('nl.css');
946 $page->addJsLink('ajax.js');
947 require_once("validations.inc.php");
948
949
950 if ($action == 'edit' and !is_null($id)) {
951 $page->assign('preview_id', $id);
952 }
953
954 if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
955 S::assert_xsrf_token();
956
957 $req = Validate::get_typed_request(Env::v('uid'), Env::v('type'), Env::v('stamp'));
958 if ($req) {
959 $req->handle_formu();
960 } else {
961 $page->trigWarning('La validation a déjà été effectuée.');
962 }
963 }
964
965 $r = XDB::iterator('SHOW COLUMNS FROM requests_answers');
966 while (($a = $r->next()) && $a['Field'] != 'category');
967 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
968
969 $hidden = array();
970 $res = XDB::query('SELECT hidden_requests FROM requests_hidden WHERE user_id = {?}', S::v('uid'));
971 $hide_requests = $res->fetchOneCell();
972 if (Post::has('hide')) {
973 $hide = array();
974 foreach ($categories as $cat)
975 if (!Post::v($cat)) {
976 $hidden[$cat] = 1;
977 $hide[] = $cat;
978 }
979 $hide_requests = join(',', $hide);
980 XDB::query('REPLACE INTO requests_hidden (user_id, hidden_requests) VALUES({?}, {?})',
981 S::v('uid'), $hide_requests);
982 } elseif ($hide_requests) {
983 foreach (explode(',', $hide_requests) as $hide_type)
984 $hidden[$hide_type] = true;
985 }
986 $page->assign('hide_requests', $hidden);
987
988 // Update the count of item to validate here... useful in development configuration
989 // where several copies of the site use the same DB, but not the same "dynamic configuration"
990 global $globals;
991 $globals->updateNbValid();
992 $page->assign('vit', new ValidateIterator());
993 }
994
995 function handler_validate_answers(&$page, $action = 'list', $id = null) {
996 $page->setTitle('Administration - Réponses automatiques de validation');
997 $page->assign('title', 'Gestion des réponses automatiques');
998 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
999 $table_editor->describe('category','catégorie',true);
1000 $table_editor->describe('title','titre',true);
1001 $table_editor->describe('answer','texte',false);
1002 $table_editor->apply($page, $action, $id);
1003 }
1004 function handler_skins(&$page, $action = 'list', $id = null) {
1005 $page->setTitle('Administration - Skins');
1006 $page->assign('title', 'Gestion des skins');
1007 $table_editor = new PLTableEditor('admin/skins','skins','id');
1008 $table_editor->describe('name','nom',true);
1009 $table_editor->describe('skin_tpl','nom du template',true);
1010 $table_editor->describe('auteur','auteur',false);
1011 $table_editor->describe('comment','commentaire',true);
1012 $table_editor->describe('date','date',false);
1013 $table_editor->describe('ext','extension du screenshot',false);
1014 $table_editor->apply($page, $action, $id);
1015 }
1016
1017 function handler_postfix_blacklist(&$page, $action = 'list', $id = null) {
1018 $page->setTitle('Administration - Postfix : Blacklist');
1019 $page->assign('title', 'Blacklist de postfix');
1020 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true);
1021 $table_editor->describe('reject_text','Texte de rejet',true);
1022 $table_editor->describe('email','email',true);
1023 $table_editor->apply($page, $action, $id);
1024 }
1025 function handler_postfix_whitelist(&$page, $action = 'list', $id = null) {
1026 $page->setTitle('Administration - Postfix : Whitelist');
1027 $page->assign('title', 'Whitelist de postfix');
1028 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true);
1029 $table_editor->describe('email','email',true);
1030 $table_editor->apply($page, $action, $id);
1031 }
1032 function handler_mx_broken(&$page, $action = 'list', $id = null) {
1033 $page->setTitle('Administration - MX Défaillants');
1034 $page->assign('title', 'MX Défaillant');
1035 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true);
1036 $table_editor->describe('host', 'Masque', true);
1037 $table_editor->describe('state', 'Niveau', true);
1038 $table_editor->describe('text', 'Description du problème', false);
1039 $table_editor->apply($page, $action, $id);
1040 }
1041 function handler_logger_actions(&$page, $action = 'list', $id = null) {
1042 $page->setTitle('Administration - Actions');
1043 $page->assign('title', 'Gestion des actions de logger');
1044 $table_editor = new PLTableEditor('admin/logger/actions','logger.actions','id');
1045 $table_editor->describe('text','intitulé',true);
1046 $table_editor->describe('description','description',true);
1047 $table_editor->apply($page, $action, $id);
1048 }
1049 function handler_downtime(&$page, $action = 'list', $id = null) {
1050 $page->setTitle('Administration - Coupures');
1051 $page->assign('title', 'Gestion des coupures');
1052 $table_editor = new PLTableEditor('admin/downtime','coupures','id');
1053 $table_editor->describe('debut','date',true);
1054 $table_editor->describe('duree','durée',false);
1055 $table_editor->describe('resume','résumé',true);
1056 $table_editor->describe('services','services affectés',true);
1057 $table_editor->describe('description','description',false);
1058 $table_editor->apply($page, $action, $id);
1059 }
1060
1061 function handler_wiki(&$page, $action = 'list', $wikipage = null, $wikipage2 = null)
1062 {
1063 if (S::v('core_rss_hash')) {
1064 $page->setRssLink('Changement Récents',
1065 '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::v('core_rss_hash'));
1066 }
1067
1068 // update wiki perms
1069 if ($action == 'update') {
1070 S::assert_xsrf_token();
1071
1072 $perms_read = Post::v('read');
1073 $perms_edit = Post::v('edit');
1074 if ($perms_read || $perms_edit) {
1075 foreach ($_POST as $wiki_page => $val) {
1076 if ($val == 'on') {
1077 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1078 if ($wp->setPerms($perms_read ? $perms_read : $wp->readPerms(),
1079 $perms_edit ? $perms_edit : $wp->writePerms())) {
1080 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1081 } else {
1082 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1083 }
1084 }
1085 }
1086 }
1087 } else if ($action != 'list' && !empty($wikipage)) {
1088 $wp = new PlWikiPage($wikipage);
1089 S::assert_xsrf_token();
1090
1091 if ($action == 'delete') {
1092 if ($wp->delete()) {
1093 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1094 } else {
1095 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1096 }
1097 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1098 if ($changedLinks = $wp->rename($wikipage2)) {
1099 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1100 if (is_numeric($changedLinks)) {
1101 $s .= $changedLinks.' lien'.(($changedLinks>1)?'s ont été modifiés.':' a été modifié.');
1102 }
1103 $page->trigSuccess($s);
1104 } else {
1105 $page->trigError("Impossible de déplacer la page ".$wikipage);
1106 }
1107 }
1108 }
1109
1110 $perms = PlWikiPage::permOptions();
1111
1112 // list wiki pages and their perms
1113 $wiki_pages = PlWikiPage::listPages();
1114 ksort($wiki_pages);
1115 $wiki_tree = array();
1116 foreach ($wiki_pages as $file => $desc) {
1117 list($cat, $name) = explode('.', $file);
1118 if (!isset($wiki_tree[$cat])) {
1119 $wiki_tree[$cat] = array();
1120 }
1121 $wiki_tree[$cat][$name] = $desc;
1122 }
1123
1124 $page->changeTpl('admin/wiki.tpl');
1125 $page->addJsLink('jquery.js');
1126 $page->assign('wiki_pages', $wiki_tree);
1127 $page->assign('perms_opts', $perms);
1128 }
1129
1130 function handler_ipwatch(&$page, $action = 'list', $ip = null)
1131 {
1132 $page->changeTpl('admin/ipwatcher.tpl');
1133
1134 $states = array('safe' => 'Ne pas surveiller',
1135 'unsafe' => 'Surveiller les inscriptions',
1136 'dangerous' => 'Surveiller tous les accès',
1137 'ban' => 'Bannir cette adresse');
1138 $page->assign('states', $states);
1139
1140 switch (Post::v('action')) {
1141 case 'create':
1142 if (trim(Post::v('ipN')) != '') {
1143 S::assert_xsrf_token();
1144 Xdb::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1145 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1146 ip_to_uint(trim(Post::v('ipN'))), ip_to_uint(trim(Post::v('maskN'))),
1147 Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
1148 };
1149 break;
1150
1151 case 'edit':
1152 S::assert_xsrf_token();
1153 Xdb::execute('UPDATE ip_watch
1154 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1155 WHERE ip = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'),
1156 ip_to_uint(Post::v('maskN')), ip_to_uint(Post::v('ipN')));
1157 break;
1158
1159 default:
1160 if ($action == 'delete' && !is_null($ip)) {
1161 S::assert_xsrf_token();
1162 Xdb::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1163 }
1164 }
1165 if ($action != 'create' && $action != 'edit') {
1166 $action = 'list';
1167 }
1168 $page->assign('action', $action);
1169
1170 if ($action == 'list') {
1171 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1172 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1173 IF(w.ip = s.ip, s.host, s.forward_host)),
1174 w.mask, w.detection, w.state, u.hruid
1175 FROM ip_watch AS w
1176 LEFT JOIN logger.sessions AS s ON (s.ip = w.ip)
1177 LEFT JOIN logger.sessions AS s2 ON (s2.forward_ip = w.ip)
1178 LEFT JOIN auth_user_md5 AS u ON (u.user_id = s.uid)
1179 GROUP BY w.ip, u.hruid
1180 ORDER BY w.state, w.ip, u.hruid";
1181 $it = Xdb::iterRow($sql);
1182
1183 $table = array();
1184 $props = array();
1185 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1186 $ip = uint_to_ip($ip);
1187 $mask = uint_to_ip($mask);
1188 if (count($props) == 0 || $props['ip'] != $ip) {
1189 if (count($props) > 0) {
1190 $table[] = $props;
1191 }
1192 $props = array('ip' => $ip,
1193 'mask' => $mask,
1194 'host' => $host,
1195 'detection' => $date,
1196 'state' => $state,
1197 'users' => array($hruid));
1198 } else {
1199 $props['users'][] = $hruid;
1200 }
1201 }
1202 if (count($props) > 0) {
1203 $table[] = $props;
1204 }
1205 $page->assign('table', $table);
1206 } elseif ($action == 'edit') {
1207 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1208 u1.hruid AS edit, u2.hruid AS hruid, s.host
1209 FROM ip_watch AS w
1210 LEFT JOIN auth_user_md5 AS u1 ON (u1.user_id = w.uid)
1211 LEFT JOIN logger.sessions AS s ON (w.ip = s.ip)
1212 LEFT JOIN auth_user_md5 AS u2 ON (u2.user_id = s.uid)
1213 WHERE w.ip = {?}
1214 GROUP BY u2.hruid
1215 ORDER BY u2.hruid";
1216 $it = Xdb::iterRow($sql, ip_to_uint($ip));
1217
1218 $props = array();
1219 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1220 if (count($props) == 0) {
1221 $props = array('ip' => $ip,
1222 'mask' => uint_to_ip($mask),
1223 'host' => $host,
1224 'detection' => $detection,
1225 'state' => $state,
1226 'last' => $last,
1227 'description' => $description,
1228 'edit' => $edit,
1229 'users' => array($hruid));
1230 } else {
1231 $props['users'][] = $hruid;
1232 }
1233 }
1234 $page->assign('ip', $props);
1235 }
1236 }
1237
1238 function handler_icons(&$page)
1239 {
1240 $page->changeTpl('admin/icons.tpl');
1241 $dh = opendir('../htdocs/images/icons');
1242 if (!$dh) {
1243 $page->trigError('Dossier des icones introuvables.');
1244 }
1245 $icons = array();
1246 while (($file = readdir($dh)) !== false) {
1247 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1248 array_push($icons, substr($file, 0, -4));
1249 }
1250 }
1251 sort($icons);
1252 $page->assign('icons', $icons);
1253 }
1254
1255 function handler_accounts(&$page)
1256 {
1257 $page->changeTpl('admin/accounts.tpl');
1258 $page->assign('disabled', XDB::iterator('SELECT u.nom, u.prenom, u.promo, u.comment, u.hruid
1259 FROM auth_user_md5 AS u
1260 WHERE perms = \'disabled\'
1261 ORDER BY nom, prenom'));
1262 $page->assign('admins', XDB::iterator('SELECT u.nom, u.prenom, u.promo, u.hruid
1263 FROM auth_user_md5 AS u
1264 WHERE perms = \'admin\'
1265 ORDER BY nom, prenom'));
1266 }
1267
1268 function handler_jobs(&$page, $id = -1)
1269 {
1270 $page->changeTpl('admin/jobs.tpl');
1271
1272 if (Env::has('search')) {
1273 $res = XDB::query("SELECT e.id, e.name, e.acronym
1274 FROM profile_job_enum AS e
1275 WHERE e.name LIKE CONCAT('% ', {?}, '%') OR e.acronym LIKE CONCAT('% ', {?}, '%')",
1276 Env::t('job'), Env::t('job'));
1277
1278 if ($res->numRows() <= 20) {
1279 $page->assign('jobs', $res->fetchAllAssoc());
1280 } else {
1281 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1282 }
1283
1284 $page->assign('askedJob', Env::v('job'));
1285 return;
1286 }
1287
1288 if (Env::has('edit')) {
1289 // TODO: use address and phone classes to update profile_job_enum and profile_phones once they are done.
1290
1291 S::assert_xsrf_token();
1292 $selectedJob = Env::has('selectedJob');
1293
1294 XDB::execute("DELETE FROM profile_phones
1295 WHERE uid = {?} AND link_type = 'hq'",
1296 $id);
1297 XDB::execute("DELETE FROM profile_addresses
1298 WHERE jobid = {?} AND type = 'hq'",
1299 $id);
1300 XDB::execute('DELETE FROM profile_job_enum
1301 WHERE id = {?}',
1302 $id);
1303
1304 if (Env::has('change')) {
1305 XDB::execute('UPDATE profile_job
1306 SET jobid = {?}
1307 WHERE jobid = {?}',
1308 Env::i('newJobId'), $id);
1309
1310 $page->trigSuccess("L'entreprise a bien été remplacée.");
1311 } else {
1312 require_once 'profil.func.inc.php';
1313 require_once 'geocoding.inc.php';
1314
1315 $display_tel = format_display_number(Env::v('tel'), $error_tel);
1316 $display_fax = format_display_number(Env::v('fax'), $error_fax);
1317 $gmapsGeocoder = new GMapsGeocoder();
1318 $address = array('text' => Env::t('address'));
1319 $address = $gmapsGeocoder->getGeocodedAddress($address);
1320 Geocoder::getAreaId($address, 'administrativeArea');
1321 Geocoder::getAreaId($address, 'subAdministrativeArea');
1322 Geocoder::getAreaId($address, 'locality');
1323
1324 XDB::execute('UPDATE profile_job_enum
1325 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1326 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1327 WHERE id = {?}',
1328 Env::t('name'), Env::t('acronym'), Env::t('url'), Env::t('email'),
1329 Env::t('NAF_code'), Env::i('AX_code'), Env::i('holdingId'), $id);
1330
1331 XDB::execute("INSERT INTO profile_phones (uid, link_type, link_id, tel_id, tel_type,
1332 search_tel, display_tel, pub)
1333 VALUES ({?}, 'hq', 0, 0, 'fixed', {?}, {?}, 'public'),
1334 ({?}, 'hq', 0, 1, 'fax', {?}, {?}, 'public')",
1335 $id, format_phone_number(Env::v('tel')), $display_tel,
1336 $id, format_phone_number(Env::v('fax')), $display_fax);
1337
1338 XDB::execute("INSERT INTO profile_addresses (jobid, type, id, accuracy,
1339 text, postalText, postalCode, localityId,
1340 subAdministrativeAreaId, administrativeAreaId,
1341 countryId, latitude, longitude, updateTime,
1342 north, south, east, west)
1343 VALUES ({?}, 'hq', 0, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
1344 {?}, {?}, FROM_UNIXTIME({?}), {?}, {?}, {?}, {?})",
1345 $id, $address['accuracy'], $address['text'], $address['postalText'],
1346 $address['postalCode'], $address['localityId'],
1347 $address['subAdministrativeAreaId'], $address['administrativeAreaId'],
1348 $address['countryId'], $address['latitude'], $address['longitude'],
1349 $address['updateTime'], $address['north'], $address['south'],
1350 $address['east'], $address['west']);
1351
1352 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1353 }
1354 }
1355
1356 if (!Env::has('change') && $id != -1) {
1357 $res = XDB::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1358 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1359 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1360 FROM profile_job_enum AS e
1361 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
1362 LEFT JOIN profile_phones AS t ON (t.uid = e.id AND link_type = 'hq' AND tel_id = 0)
1363 LEFT JOIN profile_phones AS f ON (f.uid = e.id AND link_type = 'hq' AND tel_id = 1)
1364 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1365 WHERE e.id = {?}",
1366 $id);
1367
1368 if ($res->numRows() == 0) {
1369 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1370 } else {
1371 $page->assign('selectedJob', $res->fetchOneAssoc());
1372 }
1373 }
1374 }
1375 }
1376
1377 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1378 ?>