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', p.release) AS del,
85 FIND_IN_SET('ok', p.release) AS ok
86 FROM postfix_mailseen AS p
87 WHERE nb >= 30
88 ORDER BY p.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 $user = null;
368 if ($login) {
369 $user = User::get($login);
370 } else if (Env::has('user_id')) {
371 $user = User::get(Env::i('user_id'));
372 } else if (Env::has('login')) {
373 $user = User::get(Env::v('login'));
374 }
375
376 if ($user) {
377 $login = $user->login();
378 $registered = ($user->forlifeEmail() != null);
379 } else {
380 return;
381 }
382
383 // Handles specific requests (AX sync, su, ...).
384 if(Env::has('logs_button') && $registered) {
385 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
386 }
387
388 if (Env::has('ax_button') && $registered) {
389 pl_redirect("admin/synchro_ax/" . $user->login());
390 }
391
392 if(Env::has('suid_button') && $registered) {
393 S::logger()->log("suid_start", "login on " . $user->login());
394 if (!Platal::session()->startSUID($user->id())) {
395 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->id());
396 } else {
397 pl_redirect("");
398 }
399 }
400
401 // Fetches user data.
402 $userinfo_query = "SELECT *, FIND_IN_SET('watch', flags) AS watch, FIND_IN_SET('femme', flags) AS sexe,
403 (year(naissance) > promo - 15 or year(naissance) < promo - 25) AS naiss_err
404 FROM auth_user_md5
405 WHERE user_id = {?}";
406 $mr = XDB::query($userinfo_query, $user->id())->fetchOneAssoc();
407 $redirect = ($registered ? new Redirect($user) : null);
408
409 // Processes admin requests, if any.
410 foreach($_POST as $key => $val) {
411 S::assert_xsrf_token();
412
413 switch ($key) {
414 // Email redirection actions.
415 case "add_fwd":
416 $email = trim(Env::v('email'));
417 if (!isvalid_email_redirection($email)) {
418 $page->trigError("Email non valide: $email");
419 } else {
420 $redirect->add_email($email);
421 $page->trigSuccess("Ajout de $email effectué");
422 }
423 break;
424
425 case "del_fwd":
426 if (!empty($val)) {
427 $redirect->delete_email($val);
428 }
429 break;
430
431 case "activate_fwd":
432 if (!empty($val)) {
433 $redirect->modify_one_email($val, true);
434 }
435 break;
436 case "deactivate_fwd":
437 if (!empty($val)) {
438 $redirect->modify_one_email($val, false);
439 }
440 break;
441 case "disable_fwd":
442 $redirect->disable();
443 break;
444 case "enable_fwd":
445 $redirect->enable();
446 break;
447 case "clean_fwd":
448 if (!empty($val)) {
449 $redirect->clean_errors($val);
450 }
451 break;
452
453 // Alias actions.
454 case "add_alias":
455 global $globals;
456
457 // Splits new alias in user and fqdn.
458 $alias = trim(Env::v('email'));
459 if (strpos($alias, '@') !== false) {
460 list($alias, $domain) = explode('@', $alias);
461 } else {
462 $domain = $globals->mail->domain;
463 }
464
465 // Checks for alias' user validity.
466 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
467 $page->trigError("'$alias' n'est pas un alias valide");
468 }
469
470 // Eventually adds the alias to the right domain.
471 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
472 $req = new AliasReq($user, $alias, 'Admin request', false);
473 if ($req->commit()) {
474 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué");
475 } else {
476 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué");
477 }
478 } elseif ($domain == $globals->mail->domain || $domain == $globals->mail->domain2) {
479 $res = XDB::execute("INSERT INTO aliases (id,alias,type) VALUES ({?}, {?}, 'alias')",
480 $user->id(), $alias);
481 if ($res) {
482 $page->trigSuccess("Nouvel alias '$alias' ajouté");
483 } else {
484 $page->trigError("Impossible d'ajouter l'alias '$alias', il est probablement déjà attribué");
485 }
486 } else {
487 $page->trigError("Le domaine '$domain' n'est pas valide");
488 }
489 break;
490
491 case "del_alias":
492 if (!empty($val)) {
493 XDB::execute("DELETE FROM aliases
494 WHERE id = {?} AND alias = {?} AND
495 type NOT IN ('a_vie', 'homonyme')",
496 $user->id(), $val);
497 XDB::execute("UPDATE emails
498 SET rewrite = ''
499 WHERE uid = {?} AND rewrite LIKE CONCAT({?}, '@%')",
500 $user->id(), $val);
501 fix_bestalias($user);
502 $page->trigSuccess("L'alias '$val' a été supprimé");
503 }
504 break;
505
506 case "best":
507 XDB::execute("UPDATE aliases
508 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
509 WHERE id = {?}", $user->id());
510 XDB::execute("UPDATE aliases
511 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
512 WHERE id = {?} AND alias = {?}", $user->id(), $val);
513
514 // As having a non-null bestalias value is critical in
515 // plat/al's code, we do an a posteriori check on the
516 // validity of the bestalias.
517 fix_bestalias($user);
518 break;
519
520 // Profile edition.
521 case "u_edit":
522 // Loads new values from environment.
523 require_once('secure_hash.inc.php');
524 $pass_encrypted = Env::v('newpass_clair') != "********" ? hash_encrypt(Env::v('newpass_clair')) : Env::v('passw');
525 $naiss = Env::v('naissanceN');
526 $deces = Env::v('decesN');
527 $perms = Env::v('permsN');
528 $prenom = Env::v('prenomN');
529 $nom = Env::v('nomN');
530 $nomusage = Env::v('nomusageN');
531 $promo = Env::i('promoN');
532 $sexe = Env::v('sexeN');
533 $comm = trim(Env::v('commentN'));
534 $watch = Env::v('watchN');
535
536 $flags = ($sexe ? 'femme' : '');
537 if ($watch) {
538 $flags .= ($flags ? ',watch' : 'watch');
539 }
540 if ($watch && !$comm) {
541 $page->trigError("Il est nécessaire de mettre un commentaire pour surveiller un compte");
542 break;
543 }
544
545 // Fetches fields to watch for changes.
546 $watch_query = "SELECT naissance, deces, password, perms, nom_usage,
547 prenom, nom, flags, promo, comment
548 FROM auth_user_md5
549 WHERE user_id = {?}";
550 $old_fields = XDB::query($watch_query, $user->id())->fetchOneAssoc();
551
552 // If user was newly banned, we need to ensure her php session
553 // is killed. This hack is ugly (and largely overkill); it should
554 // however suits our needs.
555 if ($perms == 'disabled' && $old_fields['perms'] != 'disabled') {
556 kill_sessions();
557
558 // Also serve a reminder to the admin: disabling an account
559 // does not deactivate email forwarding.
560 $page->trigWarning("N'oubliez pas, le cas échéant, de désactiver les redirections et le compte GoogleApps de l'utilisateur.");
561 }
562
563 // Updates the user profile with the new values.
564 $res = XDB::execute("UPDATE auth_user_md5
565 SET naissance = {?}, deces = {?}, password = {?},
566 perms = {?}, prenom = {?}, nom = {?}, nom_usage = {?},
567 flags = {?}, promo = {?}, comment = {?}
568 WHERE user_id = {?}",
569 $naiss, $deces, $pass_encrypted,
570 $perms, $prenom, $nom, $nomusage,
571 $flags, $promo, $comm, $user->id());
572 if ($res) {
573 require_once("user.func.inc.php");
574 user_reindex($user->id());
575 $new_fields = XDB::query($watch_query, $user->id())->fetchOneAssoc();
576
577 // Redacts the password in the notification, to avoid transmitting
578 // sensitive information by email.
579 $new_fields['password'] = ($old_fields['password'] != $new_fields['password'] ? 'new' : 'old');
580 $old_fields['password'] = 'old';
581
582 // Notifies the admins of the profile update.
583 $mailer = new PlMailer("admin/useredit.mail.tpl");
584 $mailer->assign("admin", S::user()->login());
585 $mailer->assign("user", $user->login());
586 $mailer->assign('old', $old_fields);
587 $mailer->assign('new', $new_fields);
588 $mailer->send();
589
590 $globals->updateNbIns();
591 $page->trigSuccess("La mise à jour a été faite avec succès.");
592 } else {
593 $page->trigError("La mise à jour a échoué. S'il te plaît, vérifie les valeurs.");
594 }
595
596 // Checks for changes, and updates other tables of plat/al.
597 if (Env::v('nomusageN') != $mr['nom_usage']) {
598 set_new_usage($user->id(), Env::v('nomusageN'), make_username(Env::v('prenomN'), Env::v('nomusageN')));
599 }
600 if (Env::v('decesN') != $mr['deces']) {
601 require_once 'notifs.inc.php';
602 register_watch_op($user->id(), WATCH_DEATH, $mr['deces']);
603 user_clear_all_subs($user->id(), false);
604 }
605
606 // Eventually updates the Google Apps account.
607 if ($globals->mailstorage->googleapps_domain) {
608 // If the user did choose to use synchronized passwords,
609 // and the password was changed, updates the Google Apps
610 // password as well.
611 if (Env::v('newpass_clair') != "********") {
612 require_once 'googleapps.inc.php';
613 $account = new GoogleAppsAccount($user);
614 if ($account->active() && $account->sync_password) {
615 $account->set_password($pass_encrypted);
616 }
617 }
618 }
619
620
621 // Reloads the user profile, to ensure the latest version will
622 // be served to the administrator.
623 $mr = XDB::query($userinfo_query, $user->id())->fetchOneAssoc();
624
625 break;
626
627 // User re-registration.
628 case "u_kill":
629 require_once('user.func.inc.php');
630 user_clear_all_subs($user->id());
631 $globals->updateNbIns();
632 $page->trigSuccess($user->login() . ' a été désinscrit !');
633
634 $mailer = new PlMailer("admin/useredit.mail.tpl");
635 $mailer->assign("admin", S::user()->login());
636 $mailer->assign("user", $user->login());
637 $mailer->assign("deletion", true);
638 $mailer->send();
639 break;
640
641 // Forum ban update.
642 case "b_edit":
643 XDB::execute("DELETE FROM forums.innd WHERE uid = {?}", $user->id());
644 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
645 XDB::execute("INSERT INTO forums.innd
646 SET ipmin = '0', ipmax = '4294967295',
647 write_perm = {?}, read_perm = {?},
648 comment = {?}, priority = '200', uid = {?}",
649 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
650 }
651 break;
652 }
653 }
654
655 // Displays last login and last host information.
656 $res = XDB::query("SELECT start, host
657 FROM logger.sessions
658 WHERE uid = {?} AND suid = 0
659 ORDER BY start DESC
660 LIMIT 1", $user->id());
661 list($lastlogin,$host) = $res->fetchOneRow();
662 $page->assign('lastlogin', $lastlogin);
663 $page->assign('host', $host);
664
665 // Display active aliases.
666 $page->assign('virtuals', XDB::iterator(
667 "SELECT alias
668 FROM virtual
669 INNER JOIN virtual_redirect USING (vid)
670 WHERE type = 'user' AND (redirect = {?} OR redirect = {?})",
671 $user->forlifeEmail(),
672 // TODO: remove this über-ugly hack. The issue is that you need
673 // to remove all @m4x.org addresses in virtual_redirect first.
674 $user->login() . '@' . $globals->mail->domain2));
675
676 $page->assign('aliases', XDB::iterator(
677 "SELECT alias, type='a_vie' AS for_life,FIND_IN_SET('bestalias',flags) AS best,expire
678 FROM aliases
679 WHERE id = {?} AND type != 'homonyme'
680 ORDER BY type != 'a_vie'", $user->id()));
681
682 // Displays email redirection and the general profile.
683 if ($registered && $redirect) {
684 $page->assign('emails', $redirect->emails);
685 }
686
687 $page->assign('mr', $mr);
688 $page->assign('user', $user);
689
690 // Displays forum bans.
691 $res = XDB::query("SELECT write_perm, read_perm, comment
692 FROM forums.innd
693 WHERE uid = {?}", $user->id());
694 $bans = $res->fetchOneAssoc();
695 $page->assign('bans', $bans);
696 }
697
698 function getHruid($line, $key, $relation)
699 {
700 $prenom = CSVImporter::getValue($line, 'prenom', $relation['prenom']);
701 $nom = CSVImporter::getValue($line, 'nom', $relation['nom']);
702 $promo = CSVImporter::getValue($line, 'promo', $relation['promo']);
703
704 if ($prenom != 'NULL' && $nom != 'NULL' && $promo != 'NULL') {
705 return make_forlife($prenom, $nom, $promo);
706 }
707 return null;
708 }
709
710 function getMatricule($line, $key, $relation)
711 {
712 $mat = $line['matricule'];
713 $year = intval(substr($mat, 0, 3));
714 $rang = intval(substr($mat, 3, 3));
715 if ($year > 200) { $year /= 10; };
716 if ($year < 96) {
717 return null;
718 } else {
719 return sprintf('%04u%04u', 1900+$year, $rang);
720 }
721 }
722
723 function handler_promo(&$page, $action = null, $promo = null)
724 {
725 if (Env::has('promo')) {
726 if(Env::i('promo') > 1900 && Env::i('promo') < 2050) {
727 $action = Env::v('valid_promo') == 'Ajouter des membres' ? 'add' : 'ax';
728 pl_redirect('admin/promo/' . $action . '/' . Env::i('promo'));
729 } else {
730 $page->trigError('Promotion non valide.');
731 }
732 }
733
734 $page->changeTpl('admin/promo.tpl');
735 if ($promo > 1900 && $promo < 2050 && ($action == 'add' || $action == 'ax')) {
736 $page->assign('promo', $promo);
737 } else {
738 return;
739 }
740
741 $importer = new CSVImporter('auth_user_md5', 'matricule');
742 $importer->registerFunction('matricule', 'matricule Ecole vers X.org', array($this, 'getMatricule'));
743 switch ($action) {
744 case 'add':
745 $fields = array('hruid', 'nom', 'nom_ini', 'prenom', 'naissance_ini',
746 'prenom_ini', 'promo', 'promo_sortie', 'flags',
747 'matricule', 'matricule_ax', 'perms');
748 $importer->forceValue('hruid', array($this, 'getHruid'));
749 $importer->forceValue('promo', $promo);
750 $importer->forceValue('promo_sortie', $promo + 3);
751 break;
752 case 'ax':
753 $fields = array('matricule', 'matricule_ax');
754 break;
755 }
756 $importer->apply($page, "admin/promo/$action/$promo", $fields);
757 }
758
759 function handler_homonyms(&$page, $op = 'list', $target = null)
760 {
761 $page->changeTpl('admin/homonymes.tpl');
762 $page->setTitle('Administration - Homonymes');
763 require_once("homonymes.inc.php");
764
765 if ($target) {
766 if (! list($prenom,$nom,$forlife,$loginbis) = select_if_homonyme($target)) {
767 $target=0;
768 } else {
769 $page->assign('nom',$nom);
770 $page->assign('prenom',$prenom);
771 $page->assign('forlife',$forlife);
772 $page->assign('loginbis',$loginbis);
773 }
774 }
775
776 $page->assign('op', $op);
777 $page->assign('target', $target);
778
779 // on a un $target valide, on prepare les mails
780 if ($target) {
781 // on examine l'op a effectuer
782 switch ($op) {
783 case 'mail':
784 S::assert_xsrf_token();
785
786 send_warning_homonyme($prenom, $nom, $forlife, $loginbis);
787 switch_bestalias($target, $loginbis);
788 $op = 'list';
789 $page->trigSuccess('Email envoyé à ' . $forlife . '.');
790 break;
791
792 case 'correct':
793 S::assert_xsrf_token();
794
795 switch_bestalias($target, $loginbis);
796 XDB::execute("UPDATE aliases SET type='homonyme',expire=NOW() WHERE alias={?}", $loginbis);
797 XDB::execute("REPLACE INTO homonymes (homonyme_id,user_id) VALUES({?},{?})", $target, $target);
798 send_robot_homonyme($prenom, $nom, $forlife, $loginbis);
799 $op = 'list';
800 $page->trigSuccess('Email envoyé à ' . $forlife . ', alias supprimé.');
801 break;
802 }
803 }
804
805 if ($op == 'list') {
806 $res = XDB::iterator(
807 "SELECT a.alias AS homonyme,s.id AS user_id,s.alias AS forlife,
808 promo,prenom,nom,
809 IF(h.homonyme_id=s.id, a.expire, NULL) AS expire,
810 IF(h.homonyme_id=s.id, a.type, NULL) AS type
811 FROM aliases AS a
812 LEFT JOIN homonymes AS h ON (h.homonyme_id = a.id)
813 INNER JOIN aliases AS s ON (s.id = h.user_id AND s.type='a_vie')
814 INNER JOIN auth_user_md5 AS u ON (s.id=u.user_id)
815 WHERE a.type='homonyme' OR a.expire!=''
816 ORDER BY a.alias,promo");
817 $hnymes = Array();
818 while ($tab = $res->next()) {
819 $hnymes[$tab['homonyme']][] = $tab;
820 }
821 $page->assign_by_ref('hnymes',$hnymes);
822 }
823 }
824
825 function handler_ax_xorg(&$page) {
826 $page->changeTpl('admin/ax-xorg.tpl');
827 $page->setTitle('Administration - AX/X.org');
828
829 // liste des différences
830 $res = XDB::query(
831 '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
832 FROM auth_user_md5 AS u
833 INNER JOIN identification_ax AS ia ON u.matricule_ax = ia.matricule_ax
834 WHERE (SOUNDEX(u.nom) != SOUNDEX(ia.nom) AND SOUNDEX(CONCAT(ia.particule,u.nom)) != SOUNDEX(ia.nom)
835 AND SOUNDEX(u.nom) != SOUNDEX(ia.nom_patro) AND SOUNDEX(CONCAT(ia.particule,u.nom)) != SOUNDEX(ia.nom_patro))
836 OR u.prenom != ia.prenom OR (u.promo != ia.promo AND u.promo != ia.promo+1 AND u.promo != ia.promo-1)
837 ORDER BY u.promo,u.nom,u.prenom');
838 $page->assign('diffs', $res->fetchAllAssoc());
839
840 // gens à l'ax mais pas chez nous
841 $res = XDB::query(
842 'SELECT ia.promo,ia.nom,ia.nom_patro,ia.prenom
843 FROM identification_ax as ia
844 LEFT JOIN auth_user_md5 AS u ON u.matricule_ax = ia.matricule_ax
845 WHERE u.nom IS NULL');
846 $page->assign('mank', $res->fetchAllAssoc());
847
848 // gens chez nous et pas à l'ax
849 $res = XDB::query('SELECT promo,nom,prenom FROM auth_user_md5 WHERE matricule_ax IS NULL');
850 $page->assign('plus', $res->fetchAllAssoc());
851 }
852
853 function handler_deaths(&$page, $promo = 0, $validate = false) {
854 $page->changeTpl('admin/deces_promo.tpl');
855 $page->setTitle('Administration - Deces');
856
857 if (!$promo)
858 $promo = Env::i('promo');
859 if (Env::has('sub10')) $promo -= 10;
860 if (Env::has('sub01')) $promo -= 1;
861 if (Env::has('add01')) $promo += 1;
862 if (Env::has('add10')) $promo += 10;
863
864 $page->assign('promo',$promo);
865
866 if ($validate) {
867 S::assert_xsrf_token();
868
869 $res = XDB::iterRow("SELECT user_id,matricule,nom,prenom,deces FROM auth_user_md5 WHERE promo = {?}", $promo);
870 while (list($uid,$mat,$nom,$prenom,$deces) = $res->next()) {
871 $val = Env::v($mat);
872 if($val == $deces || empty($val)) {
873 continue;
874 }
875
876 XDB::execute('UPDATE auth_user_md5 SET deces={?} WHERE matricule = {?}', $val, $mat);
877 $page->trigSuccess('Ajout du décès de ' . $prenom . " " . $nom . ' le ' . $val . '.');
878 if($deces == '0000-00-00' || empty($deces)) {
879 require_once('notifs.inc.php');
880 register_watch_op($uid, WATCH_DEATH, $val);
881 require_once('user.func.inc.php');
882 user_clear_all_subs($uid, false); // by default, dead ppl do not loose their email
883 }
884 }
885 }
886
887 $res = XDB::iterator('SELECT matricule, nom, prenom, deces FROM auth_user_md5 WHERE promo = {?} ORDER BY nom,prenom', $promo);
888 $page->assign('decedes', $res);
889 }
890
891 function handler_dead_but_active(&$page) {
892 $page->changeTpl('admin/dead_but_active.tpl');
893 $page->setTitle('Administration - Décédés');
894
895 $res = XDB::iterator(
896 "SELECT u.promo, u.nom, u.prenom, u.deces, u.matricule_ax, u.hruid, DATE(MAX(s.start)) AS last
897 FROM auth_user_md5 AS u
898 LEFT JOIN logger.sessions AS s ON (s.uid = u.user_id AND suid = 0)
899 WHERE perms IN ('admin', 'user') AND deces <> 0
900 GROUP BY u.user_id
901 ORDER BY u.promo, u.nom");
902 $page->assign('dead', $res);
903 }
904
905 function handler_synchro_ax(&$page, $login = null, $action = null) {
906 $page->changeTpl('admin/synchro_ax.tpl');
907 $page->setTitle('Administration - Synchro AX');
908
909 // Checks for synchronization requirements.
910 require_once('synchro_ax.inc.php');
911 if (is_ax_key_missing()) {
912 $page->assign('no_private_key', true);
913 $page->run();
914 }
915
916 // Determines user identity using environment.
917 if ($login) {
918 $user = User::get($login);
919 } else if (Env::has('user')) {
920 $user = User::get(Env::v('user'));
921 } else if (Env::has('mat')) {
922 $res = XDB::query("SELECT user_id FROM auth_user_md5 WHERE matricule = {?}", Env::i('mat'));
923 $user = User::get($res->fetchOneCell());
924 } else {
925 return;
926 }
927
928 // Finally synchronizes the AX and plat/al information.
929 if ($action == 'import') {
930 ax_synchronize($user->login(), S::v('uid'));
931 }
932
933 require_once 'profil.func.inc.php';
934 $userxorg = get_user_details($user->login(), S::v('uid'), 'ax');
935 $userax = get_user_ax($userxorg['matricule_ax']);
936 $diff = diff_user_details($userax, $userxorg, 'ax');
937
938 $page->assign('x', $userxorg);
939 $page->assign('diff', $diff);
940 }
941
942 function handler_validate(&$page, $action = 'list', $id = null)
943 {
944 $page->changeTpl('admin/valider.tpl');
945 $page->setTitle('Administration - Valider une demande');
946 $page->addCssLink('nl.css');
947 $page->addJsLink('ajax.js');
948 require_once("validations.inc.php");
949
950
951 if ($action == 'edit' and !is_null($id)) {
952 $page->assign('preview_id', $id);
953 }
954
955 if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
956 S::assert_xsrf_token();
957
958 $req = Validate::get_typed_request(Env::v('uid'), Env::v('type'), Env::v('stamp'));
959 if ($req) {
960 $req->handle_formu();
961 } else {
962 $page->trigWarning('La validation a déjà été effectuée.');
963 }
964 }
965
966 $r = XDB::iterator('SHOW COLUMNS FROM requests_answers');
967 while (($a = $r->next()) && $a['Field'] != 'category');
968 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
969
970 $hidden = array();
971 $res = XDB::query('SELECT hidden_requests FROM requests_hidden WHERE user_id = {?}', S::v('uid'));
972 $hide_requests = $res->fetchOneCell();
973 if (Post::has('hide')) {
974 $hide = array();
975 foreach ($categories as $cat)
976 if (!Post::v($cat)) {
977 $hidden[$cat] = 1;
978 $hide[] = $cat;
979 }
980 $hide_requests = join(',', $hide);
981 XDB::query('REPLACE INTO requests_hidden (user_id, hidden_requests) VALUES({?}, {?})',
982 S::v('uid'), $hide_requests);
983 } elseif ($hide_requests) {
984 foreach (explode(',', $hide_requests) as $hide_type)
985 $hidden[$hide_type] = true;
986 }
987 $page->assign('hide_requests', $hidden);
988
989 // Update the count of item to validate here... useful in development configuration
990 // where several copies of the site use the same DB, but not the same "dynamic configuration"
991 global $globals;
992 $globals->updateNbValid();
993 $page->assign('vit', new ValidateIterator());
994 }
995
996 function handler_validate_answers(&$page, $action = 'list', $id = null) {
997 $page->setTitle('Administration - Réponses automatiques de validation');
998 $page->assign('title', 'Gestion des réponses automatiques');
999 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
1000 $table_editor->describe('category','catégorie',true);
1001 $table_editor->describe('title','titre',true);
1002 $table_editor->describe('answer','texte',false);
1003 $table_editor->apply($page, $action, $id);
1004 }
1005 function handler_skins(&$page, $action = 'list', $id = null) {
1006 $page->setTitle('Administration - Skins');
1007 $page->assign('title', 'Gestion des skins');
1008 $table_editor = new PLTableEditor('admin/skins','skins','id');
1009 $table_editor->describe('name','nom',true);
1010 $table_editor->describe('skin_tpl','nom du template',true);
1011 $table_editor->describe('auteur','auteur',false);
1012 $table_editor->describe('comment','commentaire',true);
1013 $table_editor->describe('date','date',false);
1014 $table_editor->describe('ext','extension du screenshot',false);
1015 $table_editor->apply($page, $action, $id);
1016 }
1017
1018 function handler_postfix_blacklist(&$page, $action = 'list', $id = null) {
1019 $page->setTitle('Administration - Postfix : Blacklist');
1020 $page->assign('title', 'Blacklist de postfix');
1021 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true);
1022 $table_editor->describe('reject_text','Texte de rejet',true);
1023 $table_editor->describe('email','email',true);
1024 $table_editor->apply($page, $action, $id);
1025 }
1026 function handler_postfix_whitelist(&$page, $action = 'list', $id = null) {
1027 $page->setTitle('Administration - Postfix : Whitelist');
1028 $page->assign('title', 'Whitelist de postfix');
1029 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true);
1030 $table_editor->describe('email','email',true);
1031 $table_editor->apply($page, $action, $id);
1032 }
1033 function handler_mx_broken(&$page, $action = 'list', $id = null) {
1034 $page->setTitle('Administration - MX Défaillants');
1035 $page->assign('title', 'MX Défaillant');
1036 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true);
1037 $table_editor->describe('host', 'Masque', true);
1038 $table_editor->describe('state', 'Niveau', true);
1039 $table_editor->describe('text', 'Description du problème', false);
1040 $table_editor->apply($page, $action, $id);
1041 }
1042 function handler_logger_actions(&$page, $action = 'list', $id = null) {
1043 $page->setTitle('Administration - Actions');
1044 $page->assign('title', 'Gestion des actions de logger');
1045 $table_editor = new PLTableEditor('admin/logger/actions','logger.actions','id');
1046 $table_editor->describe('text','intitulé',true);
1047 $table_editor->describe('description','description',true);
1048 $table_editor->apply($page, $action, $id);
1049 }
1050 function handler_downtime(&$page, $action = 'list', $id = null) {
1051 $page->setTitle('Administration - Coupures');
1052 $page->assign('title', 'Gestion des coupures');
1053 $table_editor = new PLTableEditor('admin/downtime','coupures','id');
1054 $table_editor->describe('debut','date',true);
1055 $table_editor->describe('duree','durée',false);
1056 $table_editor->describe('resume','résumé',true);
1057 $table_editor->describe('services','services affectés',true);
1058 $table_editor->describe('description','description',false);
1059 $table_editor->apply($page, $action, $id);
1060 }
1061
1062 function handler_wiki(&$page, $action = 'list', $wikipage = null, $wikipage2 = null)
1063 {
1064 if (S::v('core_rss_hash')) {
1065 $page->setRssLink('Changement Récents',
1066 '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::v('core_rss_hash'));
1067 }
1068
1069 // update wiki perms
1070 if ($action == 'update') {
1071 S::assert_xsrf_token();
1072
1073 $perms_read = Post::v('read');
1074 $perms_edit = Post::v('edit');
1075 if ($perms_read || $perms_edit) {
1076 foreach ($_POST as $wiki_page => $val) {
1077 if ($val == 'on') {
1078 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1079 if ($wp->setPerms($perms_read ? $perms_read : $wp->readPerms(),
1080 $perms_edit ? $perms_edit : $wp->writePerms())) {
1081 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1082 } else {
1083 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1084 }
1085 }
1086 }
1087 }
1088 } else if ($action != 'list' && !empty($wikipage)) {
1089 $wp = new PlWikiPage($wikipage);
1090 S::assert_xsrf_token();
1091
1092 if ($action == 'delete') {
1093 if ($wp->delete()) {
1094 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1095 } else {
1096 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1097 }
1098 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1099 if ($changedLinks = $wp->rename($wikipage2)) {
1100 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1101 if (is_numeric($changedLinks)) {
1102 $s .= $changedLinks.' lien'.(($changedLinks>1)?'s ont été modifiés.':' a été modifié.');
1103 }
1104 $page->trigSuccess($s);
1105 } else {
1106 $page->trigError("Impossible de déplacer la page ".$wikipage);
1107 }
1108 }
1109 }
1110
1111 $perms = PlWikiPage::permOptions();
1112
1113 // list wiki pages and their perms
1114 $wiki_pages = PlWikiPage::listPages();
1115 ksort($wiki_pages);
1116 $wiki_tree = array();
1117 foreach ($wiki_pages as $file => $desc) {
1118 list($cat, $name) = explode('.', $file);
1119 if (!isset($wiki_tree[$cat])) {
1120 $wiki_tree[$cat] = array();
1121 }
1122 $wiki_tree[$cat][$name] = $desc;
1123 }
1124
1125 $page->changeTpl('admin/wiki.tpl');
1126 $page->addJsLink('jquery.js');
1127 $page->assign('wiki_pages', $wiki_tree);
1128 $page->assign('perms_opts', $perms);
1129 }
1130
1131 function handler_ipwatch(&$page, $action = 'list', $ip = null)
1132 {
1133 $page->changeTpl('admin/ipwatcher.tpl');
1134
1135 $states = array('safe' => 'Ne pas surveiller',
1136 'unsafe' => 'Surveiller les inscriptions',
1137 'dangerous' => 'Surveiller tous les accès',
1138 'ban' => 'Bannir cette adresse');
1139 $page->assign('states', $states);
1140
1141 switch (Post::v('action')) {
1142 case 'create':
1143 if (trim(Post::v('ipN')) != '') {
1144 S::assert_xsrf_token();
1145 Xdb::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1146 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1147 ip_to_uint(trim(Post::v('ipN'))), ip_to_uint(trim(Post::v('maskN'))),
1148 Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
1149 };
1150 break;
1151
1152 case 'edit':
1153 S::assert_xsrf_token();
1154 Xdb::execute('UPDATE ip_watch
1155 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1156 WHERE ip = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'),
1157 ip_to_uint(Post::v('maskN')), ip_to_uint(Post::v('ipN')));
1158 break;
1159
1160 default:
1161 if ($action == 'delete' && !is_null($ip)) {
1162 S::assert_xsrf_token();
1163 Xdb::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1164 }
1165 }
1166 if ($action != 'create' && $action != 'edit') {
1167 $action = 'list';
1168 }
1169 $page->assign('action', $action);
1170
1171 if ($action == 'list') {
1172 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1173 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1174 IF(w.ip = s.ip, s.host, s.forward_host)),
1175 w.mask, w.detection, w.state, u.hruid
1176 FROM ip_watch AS w
1177 LEFT JOIN logger.sessions AS s ON (s.ip = w.ip)
1178 LEFT JOIN logger.sessions AS s2 ON (s2.forward_ip = w.ip)
1179 LEFT JOIN auth_user_md5 AS u ON (u.user_id = s.uid)
1180 GROUP BY w.ip, u.hruid
1181 ORDER BY w.state, w.ip, u.hruid";
1182 $it = Xdb::iterRow($sql);
1183
1184 $table = array();
1185 $props = array();
1186 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1187 $ip = uint_to_ip($ip);
1188 $mask = uint_to_ip($mask);
1189 if (count($props) == 0 || $props['ip'] != $ip) {
1190 if (count($props) > 0) {
1191 $table[] = $props;
1192 }
1193 $props = array('ip' => $ip,
1194 'mask' => $mask,
1195 'host' => $host,
1196 'detection' => $date,
1197 'state' => $state,
1198 'users' => array($hruid));
1199 } else {
1200 $props['users'][] = $hruid;
1201 }
1202 }
1203 if (count($props) > 0) {
1204 $table[] = $props;
1205 }
1206 $page->assign('table', $table);
1207 } elseif ($action == 'edit') {
1208 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1209 u1.hruid AS edit, u2.hruid AS hruid, s.host
1210 FROM ip_watch AS w
1211 LEFT JOIN auth_user_md5 AS u1 ON (u1.user_id = w.uid)
1212 LEFT JOIN logger.sessions AS s ON (w.ip = s.ip)
1213 LEFT JOIN auth_user_md5 AS u2 ON (u2.user_id = s.uid)
1214 WHERE w.ip = {?}
1215 GROUP BY u2.hruid
1216 ORDER BY u2.hruid";
1217 $it = Xdb::iterRow($sql, ip_to_uint($ip));
1218
1219 $props = array();
1220 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1221 if (count($props) == 0) {
1222 $props = array('ip' => $ip,
1223 'mask' => uint_to_ip($mask),
1224 'host' => $host,
1225 'detection' => $detection,
1226 'state' => $state,
1227 'last' => $last,
1228 'description' => $description,
1229 'edit' => $edit,
1230 'users' => array($hruid));
1231 } else {
1232 $props['users'][] = $hruid;
1233 }
1234 }
1235 $page->assign('ip', $props);
1236 }
1237 }
1238
1239 function handler_icons(&$page)
1240 {
1241 $page->changeTpl('admin/icons.tpl');
1242 $dh = opendir('../htdocs/images/icons');
1243 if (!$dh) {
1244 $page->trigError('Dossier des icones introuvables.');
1245 }
1246 $icons = array();
1247 while (($file = readdir($dh)) !== false) {
1248 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1249 array_push($icons, substr($file, 0, -4));
1250 }
1251 }
1252 sort($icons);
1253 $page->assign('icons', $icons);
1254 }
1255
1256 function handler_accounts(&$page)
1257 {
1258 $page->changeTpl('admin/accounts.tpl');
1259 $page->assign('disabled', XDB::iterator('SELECT u.nom, u.prenom, u.promo, u.comment, u.hruid
1260 FROM auth_user_md5 AS u
1261 WHERE perms = \'disabled\'
1262 ORDER BY nom, prenom'));
1263 $page->assign('admins', XDB::iterator('SELECT u.nom, u.prenom, u.promo, u.hruid
1264 FROM auth_user_md5 AS u
1265 WHERE perms = \'admin\'
1266 ORDER BY nom, prenom'));
1267 }
1268
1269 function handler_jobs(&$page, $id = -1)
1270 {
1271 $page->changeTpl('admin/jobs.tpl');
1272
1273 if (Env::has('search')) {
1274 $res = XDB::query("SELECT e.id, e.name, e.acronym
1275 FROM profile_job_enum AS e
1276 WHERE e.name LIKE CONCAT('% ', {?}, '%') OR e.acronym LIKE CONCAT('% ', {?}, '%')",
1277 Env::t('job'), Env::t('job'));
1278
1279 if ($res->numRows() <= 20) {
1280 $page->assign('jobs', $res->fetchAllAssoc());
1281 } else {
1282 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1283 }
1284
1285 $page->assign('askedJob', Env::v('job'));
1286 return;
1287 }
1288
1289 if (Env::has('edit')) {
1290 // TODO: use address and phone classes to update profile_job_enum and profile_phones once they are done.
1291
1292 S::assert_xsrf_token();
1293 $selectedJob = Env::has('selectedJob');
1294
1295 XDB::execute("DELETE FROM profile_phones
1296 WHERE uid = {?} AND link_type = 'hq'",
1297 $id);
1298 XDB::execute("DELETE FROM profile_addresses
1299 WHERE jobid = {?} AND type = 'hq'",
1300 $id);
1301 XDB::execute('DELETE FROM profile_job_enum
1302 WHERE id = {?}',
1303 $id);
1304
1305 if (Env::has('change')) {
1306 XDB::execute('UPDATE profile_job
1307 SET jobid = {?}
1308 WHERE jobid = {?}',
1309 Env::i('newJobId'), $id);
1310
1311 $page->trigSuccess("L'entreprise a bien été remplacée.");
1312 } else {
1313 require_once 'profil.func.inc.php';
1314 require_once 'geocoding.inc.php';
1315
1316 $display_tel = format_display_number(Env::v('tel'), $error_tel);
1317 $display_fax = format_display_number(Env::v('fax'), $error_fax);
1318 $gmapsGeocoder = new GMapsGeocoder();
1319 $address = array('text' => Env::t('address'));
1320 $address = $gmapsGeocoder->getGeocodedAddress($address);
1321 Geocoder::getAreaId($address, 'administrativeArea');
1322 Geocoder::getAreaId($address, 'subAdministrativeArea');
1323 Geocoder::getAreaId($address, 'locality');
1324
1325 XDB::execute('UPDATE profile_job_enum
1326 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1327 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1328 WHERE id = {?}',
1329 Env::t('name'), Env::t('acronym'), Env::t('url'), Env::t('email'),
1330 Env::t('NAF_code'), Env::i('AX_code'), Env::i('holdingId'), $id);
1331
1332 XDB::execute("INSERT INTO profile_phones (uid, link_type, link_id, tel_id, tel_type,
1333 search_tel, display_tel, pub)
1334 VALUES ({?}, 'hq', 0, 0, 'fixed', {?}, {?}, 'public'),
1335 ({?}, 'hq', 0, 1, 'fax', {?}, {?}, 'public')",
1336 $id, format_phone_number(Env::v('tel')), $display_tel,
1337 $id, format_phone_number(Env::v('fax')), $display_fax);
1338
1339 XDB::execute("INSERT INTO profile_addresses (jobid, type, id, accuracy,
1340 text, postalText, postalCode, localityId,
1341 subAdministrativeAreaId, administrativeAreaId,
1342 countryId, latitude, longitude, updateTime,
1343 north, south, east, west)
1344 VALUES ({?}, 'hq', 0, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
1345 {?}, {?}, FROM_UNIXTIME({?}), {?}, {?}, {?}, {?})",
1346 $id, $address['accuracy'], $address['text'], $address['postalText'],
1347 $address['postalCode'], $address['localityId'],
1348 $address['subAdministrativeAreaId'], $address['administrativeAreaId'],
1349 $address['countryId'], $address['latitude'], $address['longitude'],
1350 $address['updateTime'], $address['north'], $address['south'],
1351 $address['east'], $address['west']);
1352
1353 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1354 }
1355 }
1356
1357 if (!Env::has('change') && $id != -1) {
1358 $res = XDB::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1359 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1360 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1361 FROM profile_job_enum AS e
1362 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
1363 LEFT JOIN profile_phones AS t ON (t.uid = e.id AND link_type = 'hq' AND tel_id = 0)
1364 LEFT JOIN profile_phones AS f ON (f.uid = e.id AND link_type = 'hq' AND tel_id = 1)
1365 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1366 WHERE e.id = {?}",
1367 $id);
1368
1369 if ($res->numRows() == 0) {
1370 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1371 } else {
1372 $page->assign('selectedJob', $res->fetchOneAssoc());
1373 }
1374 }
1375 }
1376 }
1377
1378 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1379 ?>