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&nbsp;!");
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&nbsp;!");
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 #x4dat#.aliases AS a ON (a.id = ls.uid AND a.type='a_vie')
263 LEFT JOIN #x4dat#.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 #x4dat#.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&nbsp;!!!");
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 break;
469 }
470
471 // Eventually adds the alias to the right domain.
472 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
473 $req = new AliasReq($user, $alias, 'Admin request', false);
474 if ($req->commit()) {
475 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué");
476 } else {
477 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué");
478 }
479 } elseif ($domain == $globals->mail->domain || $domain == $globals->mail->domain2) {
480 $res = XDB::execute("INSERT INTO aliases (id,alias,type) VALUES ({?}, {?}, 'alias')",
481 $user->id(), $alias);
482 if ($res) {
483 $page->trigSuccess("Nouvel alias '$alias' ajouté");
484 } else {
485 $page->trigError("Impossible d'ajouter l'alias '$alias', il est probablement déjà attribué");
486 }
487 } else {
488 $page->trigError("Le domaine '$domain' n'est pas valide");
489 }
490 break;
491
492 case "del_alias":
493 if (!empty($val)) {
494 XDB::execute("DELETE FROM aliases
495 WHERE id = {?} AND alias = {?} AND
496 type NOT IN ('a_vie', 'homonyme')",
497 $user->id(), $val);
498 XDB::execute("UPDATE emails
499 SET rewrite = ''
500 WHERE uid = {?} AND rewrite LIKE CONCAT({?}, '@%')",
501 $user->id(), $val);
502 fix_bestalias($user);
503 $page->trigSuccess("L'alias '$val' a été supprimé");
504 }
505 break;
506
507 case "best":
508 XDB::execute("UPDATE aliases
509 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
510 WHERE id = {?}", $user->id());
511 XDB::execute("UPDATE aliases
512 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
513 WHERE id = {?} AND alias = {?}", $user->id(), $val);
514
515 // As having a non-null bestalias value is critical in
516 // plat/al's code, we do an a posteriori check on the
517 // validity of the bestalias.
518 fix_bestalias($user);
519 break;
520
521 // Profile edition.
522 case "u_edit":
523 // Loads new values from environment.
524 require_once('secure_hash.inc.php');
525 $pass_encrypted = Env::v('newpass_clair') != "********" ? hash_encrypt(Env::v('newpass_clair')) : Env::v('passw');
526 $naiss = Env::v('naissanceN');
527 $deces = Env::v('decesN');
528 $perms = Env::v('permsN');
529 $prenom = Env::v('prenomN');
530 $nom = Env::v('nomN');
531 $nomusage = Env::v('nomusageN');
532 $promo = Env::i('promoN');
533 $sexe = Env::v('sexeN');
534 $comm = trim(Env::v('commentN'));
535 $watch = Env::v('watchN');
536
537 $flags = ($sexe ? 'femme' : '');
538 if ($watch) {
539 $flags .= ($flags ? ',watch' : 'watch');
540 }
541 if ($watch && !$comm) {
542 $page->trigError("Il est nécessaire de mettre un commentaire pour surveiller un compte");
543 break;
544 }
545
546 // Fetches fields to watch for changes.
547 $watch_query = "SELECT naissance, deces, password, perms, nom_usage,
548 prenom, nom, flags, promo, comment
549 FROM auth_user_md5
550 WHERE user_id = {?}";
551 $old_fields = XDB::query($watch_query, $user->id())->fetchOneAssoc();
552
553 // If user was newly banned, we need to ensure her php session
554 // is killed. This hack is ugly (and largely overkill); it should
555 // however suits our needs.
556 if ($perms == 'disabled' && $old_fields['perms'] != 'disabled') {
557 kill_sessions();
558
559 // Also serve a reminder to the admin: disabling an account
560 // does not deactivate email forwarding.
561 $page->trigWarning("N'oubliez pas, le cas échéant, de désactiver les redirections et le compte GoogleApps de l'utilisateur.");
562 }
563
564 // Updates the user profile with the new values.
565 $res = XDB::execute("UPDATE auth_user_md5
566 SET naissance = {?}, deces = {?}, password = {?},
567 perms = {?}, prenom = {?}, nom = {?}, nom_usage = {?},
568 flags = {?}, promo = {?}, comment = {?}
569 WHERE user_id = {?}",
570 $naiss, $deces, $pass_encrypted,
571 $perms, $prenom, $nom, $nomusage,
572 $flags, $promo, $comm, $user->id());
573 if ($res) {
574 require_once("user.func.inc.php");
575 user_reindex($user->id());
576 $new_fields = XDB::query($watch_query, $user->id())->fetchOneAssoc();
577
578 // Redacts the password in the notification, to avoid transmitting
579 // sensitive information by email.
580 $new_fields['password'] = ($old_fields['password'] != $new_fields['password'] ? 'new' : 'old');
581 $old_fields['password'] = 'old';
582
583 // Notifies the admins of the profile update.
584 $mailer = new PlMailer("admin/useredit.mail.tpl");
585 $mailer->assign("admin", S::user()->login());
586 $mailer->assign("user", $user->login());
587 $mailer->assign('old', $old_fields);
588 $mailer->assign('new', $new_fields);
589 $mailer->send();
590
591 $globals->updateNbIns();
592 $page->trigSuccess("La mise à jour a été faite avec succès.");
593 } else {
594 $page->trigError("La mise à jour a échoué. S'il te plaît, vérifie les valeurs.");
595 }
596
597 // Checks for changes, and updates other tables of plat/al.
598 if (Env::v('nomusageN') != $mr['nom_usage']) {
599 set_new_usage($user->id(), Env::v('nomusageN'), make_username(Env::v('prenomN'), Env::v('nomusageN')));
600 }
601 if (Env::v('decesN') != $mr['deces']) {
602 require_once 'notifs.inc.php';
603 register_watch_op($user->id(), WATCH_DEATH, $mr['deces']);
604 user_clear_all_subs($user->id(), false);
605 }
606
607 // Eventually updates the Google Apps account.
608 if ($globals->mailstorage->googleapps_domain) {
609 // If the user did choose to use synchronized passwords,
610 // and the password was changed, updates the Google Apps
611 // password as well.
612 if (Env::v('newpass_clair') != "********") {
613 require_once 'googleapps.inc.php';
614 $account = new GoogleAppsAccount($user);
615 if ($account->active() && $account->sync_password) {
616 $account->set_password($pass_encrypted);
617 }
618 }
619 }
620
621
622 // Reloads the user profile, to ensure the latest version will
623 // be served to the administrator.
624 $mr = XDB::query($userinfo_query, $user->id())->fetchOneAssoc();
625
626 break;
627
628 // User re-registration.
629 case "u_kill":
630 require_once('user.func.inc.php');
631 user_clear_all_subs($user->id());
632 $globals->updateNbIns();
633 $page->trigSuccess($user->login() . ' a été désinscrit&nbsp;!');
634
635 $mailer = new PlMailer("admin/useredit.mail.tpl");
636 $mailer->assign("admin", S::user()->login());
637 $mailer->assign("user", $user->login());
638 $mailer->assign("deletion", true);
639 $mailer->send();
640 break;
641
642 // Forum ban update.
643 case "b_edit":
644 XDB::execute("DELETE FROM #forums#.innd WHERE uid = {?}", $user->id());
645 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
646 XDB::execute("INSERT INTO #forums#.innd
647 SET ipmin = '0', ipmax = '4294967295',
648 write_perm = {?}, read_perm = {?},
649 comment = {?}, priority = '200', uid = {?}",
650 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
651 }
652 break;
653 }
654 }
655
656 // Displays last login and last host information.
657 $res = XDB::query("SELECT start, host
658 FROM #logger#.sessions
659 WHERE uid = {?} AND suid = 0
660 ORDER BY start DESC
661 LIMIT 1", $user->id());
662 list($lastlogin,$host) = $res->fetchOneRow();
663 $page->assign('lastlogin', $lastlogin);
664 $page->assign('host', $host);
665
666 // Display active aliases.
667 $page->assign('virtuals', XDB::iterator(
668 "SELECT alias
669 FROM virtual
670 INNER JOIN virtual_redirect USING (vid)
671 WHERE type = 'user' AND (redirect = {?} OR redirect = {?})",
672 $user->forlifeEmail(),
673 // TODO: remove this über-ugly hack. The issue is that you need
674 // to remove all @m4x.org addresses in virtual_redirect first.
675 $user->login() . '@' . $globals->mail->domain2));
676
677 $page->assign('aliases', XDB::iterator(
678 "SELECT alias, type='a_vie' AS for_life,FIND_IN_SET('bestalias',flags) AS best,expire
679 FROM aliases
680 WHERE id = {?} AND type != 'homonyme'
681 ORDER BY type != 'a_vie'", $user->id()));
682
683 // Displays email redirection and the general profile.
684 if ($registered && $redirect) {
685 $page->assign('emails', $redirect->emails);
686 }
687
688 $page->assign('mr', $mr);
689 $page->assign('user', $user);
690
691 // Displays forum bans.
692 $res = XDB::query("SELECT write_perm, read_perm, comment
693 FROM #forums#.innd
694 WHERE uid = {?}", $user->id());
695 $bans = $res->fetchOneAssoc();
696 $page->assign('bans', $bans);
697 }
698
699 function getHruid($line, $key, $relation)
700 {
701 $prenom = CSVImporter::getValue($line, 'prenom', $relation['prenom']);
702 $nom = CSVImporter::getValue($line, 'nom', $relation['nom']);
703 $promo = CSVImporter::getValue($line, 'promo', $relation['promo']);
704
705 if ($prenom != 'NULL' && $nom != 'NULL' && $promo != 'NULL') {
706 return make_forlife($prenom, $nom, $promo);
707 }
708 return null;
709 }
710
711 function getMatricule($line, $key, $relation)
712 {
713 $mat = $line['matricule'];
714 $year = intval(substr($mat, 0, 3));
715 $rang = intval(substr($mat, 3, 3));
716 if ($year > 200) { $year /= 10; };
717 if ($year < 96) {
718 return null;
719 } else {
720 return sprintf('%04u%04u', 1900+$year, $rang);
721 }
722 }
723
724 function handler_promo(&$page, $action = null, $promo = null)
725 {
726 if (Env::has('promo')) {
727 if(Env::i('promo') > 1900 && Env::i('promo') < 2050) {
728 $action = Env::v('valid_promo') == 'Ajouter des membres' ? 'add' : 'ax';
729 pl_redirect('admin/promo/' . $action . '/' . Env::i('promo'));
730 } else {
731 $page->trigError('Promotion non valide.');
732 }
733 }
734
735 $page->changeTpl('admin/promo.tpl');
736 if ($promo > 1900 && $promo < 2050 && ($action == 'add' || $action == 'ax')) {
737 $page->assign('promo', $promo);
738 } else {
739 return;
740 }
741
742 $importer = new CSVImporter('auth_user_md5', 'matricule');
743 $importer->registerFunction('matricule', 'matricule Ecole vers X.org', array($this, 'getMatricule'));
744 switch ($action) {
745 case 'add':
746 $fields = array('hruid', 'nom', 'nom_ini', 'prenom', 'naissance_ini',
747 'prenom_ini', 'promo', 'promo_sortie', 'flags',
748 'matricule', 'matricule_ax', 'perms');
749 $importer->forceValue('hruid', array($this, 'getHruid'));
750 $importer->forceValue('promo', $promo);
751 $importer->forceValue('promo_sortie', $promo + 3);
752 break;
753 case 'ax':
754 $fields = array('matricule', 'matricule_ax');
755 break;
756 }
757 $importer->apply($page, "admin/promo/$action/$promo", $fields);
758 }
759
760 function handler_homonyms(&$page, $op = 'list', $target = null)
761 {
762 $page->changeTpl('admin/homonymes.tpl');
763 $page->setTitle('Administration - Homonymes');
764 require_once("homonymes.inc.php");
765
766 if ($target) {
767 if (! list($prenom,$nom,$forlife,$loginbis) = select_if_homonyme($target)) {
768 $target=0;
769 } else {
770 $page->assign('nom',$nom);
771 $page->assign('prenom',$prenom);
772 $page->assign('forlife',$forlife);
773 $page->assign('loginbis',$loginbis);
774 }
775 }
776
777 $page->assign('op', $op);
778 $page->assign('target', $target);
779
780 // on a un $target valide, on prepare les mails
781 if ($target) {
782 // on examine l'op a effectuer
783 switch ($op) {
784 case 'mail':
785 S::assert_xsrf_token();
786
787 send_warning_homonyme($prenom, $nom, $forlife, $loginbis);
788 switch_bestalias($target, $loginbis);
789 $op = 'list';
790 $page->trigSuccess('Email envoyé à ' . $forlife . '.');
791 break;
792
793 case 'correct':
794 S::assert_xsrf_token();
795
796 switch_bestalias($target, $loginbis);
797 XDB::execute("UPDATE aliases SET type='homonyme',expire=NOW() WHERE alias={?}", $loginbis);
798 XDB::execute("REPLACE INTO homonymes (homonyme_id,user_id) VALUES({?},{?})", $target, $target);
799 send_robot_homonyme($prenom, $nom, $forlife, $loginbis);
800 $op = 'list';
801 $page->trigSuccess('Email envoyé à ' . $forlife . ', alias supprimé.');
802 break;
803 }
804 }
805
806 if ($op == 'list') {
807 $res = XDB::iterator(
808 "SELECT a.alias AS homonyme,s.id AS user_id,s.alias AS forlife,
809 promo,prenom,nom,
810 IF(h.homonyme_id=s.id, a.expire, NULL) AS expire,
811 IF(h.homonyme_id=s.id, a.type, NULL) AS type
812 FROM aliases AS a
813 LEFT JOIN homonymes AS h ON (h.homonyme_id = a.id)
814 INNER JOIN aliases AS s ON (s.id = h.user_id AND s.type='a_vie')
815 INNER JOIN auth_user_md5 AS u ON (s.id=u.user_id)
816 WHERE a.type='homonyme' OR a.expire!=''
817 ORDER BY a.alias,promo");
818 $hnymes = Array();
819 while ($tab = $res->next()) {
820 $hnymes[$tab['homonyme']][] = $tab;
821 }
822 $page->assign_by_ref('hnymes',$hnymes);
823 }
824 }
825
826 function handler_ax_xorg(&$page) {
827 $page->changeTpl('admin/ax-xorg.tpl');
828 $page->setTitle('Administration - AX/X.org');
829
830 // liste des différences
831 $res = XDB::query(
832 '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
833 FROM auth_user_md5 AS u
834 INNER JOIN identification_ax AS ia ON u.matricule_ax = ia.matricule_ax
835 WHERE (SOUNDEX(u.nom) != SOUNDEX(ia.nom) AND SOUNDEX(CONCAT(ia.particule,u.nom)) != SOUNDEX(ia.nom)
836 AND SOUNDEX(u.nom) != SOUNDEX(ia.nom_patro) AND SOUNDEX(CONCAT(ia.particule,u.nom)) != SOUNDEX(ia.nom_patro))
837 OR u.prenom != ia.prenom OR (u.promo != ia.promo AND u.promo != ia.promo+1 AND u.promo != ia.promo-1)
838 ORDER BY u.promo,u.nom,u.prenom');
839 $page->assign('diffs', $res->fetchAllAssoc());
840
841 // gens à l'ax mais pas chez nous
842 $res = XDB::query(
843 'SELECT ia.promo,ia.nom,ia.nom_patro,ia.prenom
844 FROM identification_ax as ia
845 LEFT JOIN auth_user_md5 AS u ON u.matricule_ax = ia.matricule_ax
846 WHERE u.nom IS NULL');
847 $page->assign('mank', $res->fetchAllAssoc());
848
849 // gens chez nous et pas à l'ax
850 $res = XDB::query('SELECT promo,nom,prenom FROM auth_user_md5 WHERE matricule_ax IS NULL');
851 $page->assign('plus', $res->fetchAllAssoc());
852 }
853
854 function handler_deaths(&$page, $promo = 0, $validate = false) {
855 $page->changeTpl('admin/deces_promo.tpl');
856 $page->setTitle('Administration - Deces');
857
858 if (!$promo)
859 $promo = Env::i('promo');
860 if (Env::has('sub10')) $promo -= 10;
861 if (Env::has('sub01')) $promo -= 1;
862 if (Env::has('add01')) $promo += 1;
863 if (Env::has('add10')) $promo += 10;
864
865 $page->assign('promo',$promo);
866
867 if ($validate) {
868 S::assert_xsrf_token();
869
870 $res = XDB::iterRow("SELECT user_id,matricule,nom,prenom,deces FROM auth_user_md5 WHERE promo = {?}", $promo);
871 while (list($uid,$mat,$nom,$prenom,$deces) = $res->next()) {
872 $val = Env::v($mat);
873 if($val == $deces || empty($val)) {
874 continue;
875 }
876
877 XDB::execute('UPDATE auth_user_md5 SET deces={?} WHERE matricule = {?}', $val, $mat);
878 $page->trigSuccess('Ajout du décès de ' . $prenom . " " . $nom . ' le ' . $val . '.');
879 if($deces == '0000-00-00' || empty($deces)) {
880 require_once('notifs.inc.php');
881 register_watch_op($uid, WATCH_DEATH, $val);
882 require_once('user.func.inc.php');
883 user_clear_all_subs($uid, false); // by default, dead ppl do not loose their email
884 }
885 }
886 }
887
888 $res = XDB::iterator('SELECT matricule, nom, prenom, deces FROM auth_user_md5 WHERE promo = {?} ORDER BY nom,prenom', $promo);
889 $page->assign('decedes', $res);
890 }
891
892 function handler_dead_but_active(&$page) {
893 $page->changeTpl('admin/dead_but_active.tpl');
894 $page->setTitle('Administration - Décédés');
895
896 $res = XDB::iterator(
897 "SELECT u.promo, u.nom, u.prenom, u.deces, u.hruid, DATE(MAX(s.start)) AS last
898 FROM #x4dat#.auth_user_md5 AS u
899 LEFT JOIN #logger#.sessions AS s ON (s.uid = u.user_id AND suid = 0)
900 WHERE perms IN ('admin', 'user') AND deces <> 0
901 GROUP BY u.user_id
902 ORDER BY u.promo, u.nom");
903 $page->assign('dead', $res);
904 }
905
906 function handler_synchro_ax(&$page, $login = null, $action = null) {
907 $page->changeTpl('admin/synchro_ax.tpl');
908 $page->setTitle('Administration - Synchro AX');
909
910 // Checks for synchronization requirements.
911 require_once('synchro_ax.inc.php');
912 if (is_ax_key_missing()) {
913 $page->assign('no_private_key', true);
914 $page->run();
915 }
916
917 // Determines user identity using environment.
918 if ($login) {
919 $user = User::get($login);
920 } else if (Env::has('user')) {
921 $user = User::get(Env::v('user'));
922 } else if (Env::has('mat')) {
923 $res = XDB::query("SELECT user_id FROM auth_user_md5 WHERE matricule = {?}", Env::i('mat'));
924 $user = User::get($res->fetchOneCell());
925 } else {
926 return;
927 }
928
929 // Finally synchronizes the AX and plat/al information.
930 if ($action == 'import') {
931 ax_synchronize($user->login(), S::v('uid'));
932 }
933
934 require_once 'profil.func.inc.php';
935 $userxorg = get_user_details($user->login(), S::v('uid'), 'ax');
936 $userax = get_user_ax($userxorg['matricule_ax']);
937 $diff = diff_user_details($userax, $userxorg, 'ax');
938
939 $page->assign('x', $userxorg);
940 $page->assign('diff', $diff);
941 }
942
943 function handler_validate(&$page, $action = 'list', $id = null)
944 {
945 $page->changeTpl('admin/valider.tpl');
946 $page->setTitle('Administration - Valider une demande');
947 $page->addCssLink('nl.css');
948 $page->addJsLink('ajax.js');
949 require_once("validations.inc.php");
950
951
952 if ($action == 'edit' and !is_null($id)) {
953 $page->assign('preview_id', $id);
954 }
955
956 if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
957 S::assert_xsrf_token();
958
959 $req = Validate::get_typed_request(Env::v('uid'), Env::v('type'), Env::v('stamp'));
960 if ($req) {
961 $req->handle_formu();
962 } else {
963 $page->trigWarning('La validation a déjà été effectuée.');
964 }
965 }
966
967 $r = XDB::iterator('SHOW COLUMNS FROM requests_answers');
968 while (($a = $r->next()) && $a['Field'] != 'category');
969 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
970
971 $hidden = array();
972 $res = XDB::query('SELECT hidden_requests FROM requests_hidden WHERE user_id = {?}', S::v('uid'));
973 $hide_requests = $res->fetchOneCell();
974 if (Post::has('hide')) {
975 $hide = array();
976 foreach ($categories as $cat)
977 if (!Post::v($cat)) {
978 $hidden[$cat] = 1;
979 $hide[] = $cat;
980 }
981 $hide_requests = join(',', $hide);
982 XDB::query('REPLACE INTO requests_hidden (user_id, hidden_requests) VALUES({?}, {?})',
983 S::v('uid'), $hide_requests);
984 } elseif ($hide_requests) {
985 foreach (explode(',', $hide_requests) as $hide_type)
986 $hidden[$hide_type] = true;
987 }
988 $page->assign('hide_requests', $hidden);
989
990 // Update the count of item to validate here... useful in development configuration
991 // where several copies of the site use the same DB, but not the same "dynamic configuration"
992 global $globals;
993 $globals->updateNbValid();
994 $page->assign('vit', new ValidateIterator());
995 }
996
997 function handler_validate_answers(&$page, $action = 'list', $id = null) {
998 $page->setTitle('Administration - Réponses automatiques de validation');
999 $page->assign('title', 'Gestion des réponses automatiques');
1000 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
1001 $table_editor->describe('category','catégorie',true);
1002 $table_editor->describe('title','titre',true);
1003 $table_editor->describe('answer','texte',false);
1004 $table_editor->apply($page, $action, $id);
1005 }
1006 function handler_skins(&$page, $action = 'list', $id = null) {
1007 $page->setTitle('Administration - Skins');
1008 $page->assign('title', 'Gestion des skins');
1009 $table_editor = new PLTableEditor('admin/skins','skins','id');
1010 $table_editor->describe('name','nom',true);
1011 $table_editor->describe('skin_tpl','nom du template',true);
1012 $table_editor->describe('auteur','auteur',false);
1013 $table_editor->describe('comment','commentaire',true);
1014 $table_editor->describe('date','date',false);
1015 $table_editor->describe('ext','extension du screenshot',false);
1016 $table_editor->apply($page, $action, $id);
1017 }
1018
1019 function handler_postfix_blacklist(&$page, $action = 'list', $id = null) {
1020 $page->setTitle('Administration - Postfix : Blacklist');
1021 $page->assign('title', 'Blacklist de postfix');
1022 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true);
1023 $table_editor->describe('reject_text','Texte de rejet',true);
1024 $table_editor->describe('email','email',true);
1025 $table_editor->apply($page, $action, $id);
1026 }
1027 function handler_postfix_whitelist(&$page, $action = 'list', $id = null) {
1028 $page->setTitle('Administration - Postfix : Whitelist');
1029 $page->assign('title', 'Whitelist de postfix');
1030 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true);
1031 $table_editor->describe('email','email',true);
1032 $table_editor->apply($page, $action, $id);
1033 }
1034 function handler_mx_broken(&$page, $action = 'list', $id = null) {
1035 $page->setTitle('Administration - MX Défaillants');
1036 $page->assign('title', 'MX Défaillant');
1037 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true);
1038 $table_editor->describe('host', 'Masque', true);
1039 $table_editor->describe('state', 'Niveau', true);
1040 $table_editor->describe('text', 'Description du problème', false);
1041 $table_editor->apply($page, $action, $id);
1042 }
1043 function handler_logger_actions(&$page, $action = 'list', $id = null) {
1044 $page->setTitle('Administration - Actions');
1045 $page->assign('title', 'Gestion des actions de logger');
1046 $table_editor = new PLTableEditor('admin/logger/actions','#logger#.actions','id');
1047 $table_editor->describe('text','intitulé',true);
1048 $table_editor->describe('description','description',true);
1049 $table_editor->apply($page, $action, $id);
1050 }
1051 function handler_downtime(&$page, $action = 'list', $id = null) {
1052 $page->setTitle('Administration - Coupures');
1053 $page->assign('title', 'Gestion des coupures');
1054 $table_editor = new PLTableEditor('admin/downtime','coupures','id');
1055 $table_editor->describe('debut','date',true);
1056 $table_editor->describe('duree','durée',false);
1057 $table_editor->describe('resume','résumé',true);
1058 $table_editor->describe('services','services affectés',true);
1059 $table_editor->describe('description','description',false);
1060 $table_editor->apply($page, $action, $id);
1061 }
1062
1063 function handler_wiki(&$page, $action = 'list', $wikipage = null, $wikipage2 = null)
1064 {
1065 if (S::v('core_rss_hash')) {
1066 $page->setRssLink('Changement Récents',
1067 '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::v('core_rss_hash'));
1068 }
1069
1070 // update wiki perms
1071 if ($action == 'update') {
1072 S::assert_xsrf_token();
1073
1074 $perms_read = Post::v('read');
1075 $perms_edit = Post::v('edit');
1076 if ($perms_read || $perms_edit) {
1077 foreach ($_POST as $wiki_page => $val) {
1078 if ($val == 'on') {
1079 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1080 if ($wp->setPerms($perms_read ? $perms_read : $wp->readPerms(),
1081 $perms_edit ? $perms_edit : $wp->writePerms())) {
1082 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1083 } else {
1084 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1085 }
1086 }
1087 }
1088 }
1089 } else if ($action != 'list' && !empty($wikipage)) {
1090 $wp = new PlWikiPage($wikipage);
1091 S::assert_xsrf_token();
1092
1093 if ($action == 'delete') {
1094 if ($wp->delete()) {
1095 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1096 } else {
1097 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1098 }
1099 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1100 if ($changedLinks = $wp->rename($wikipage2)) {
1101 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1102 if (is_numeric($changedLinks)) {
1103 $s .= $changedLinks.' lien'.(($changedLinks>1)?'s ont été modifiés.':' a été modifié.');
1104 }
1105 $page->trigSuccess($s);
1106 } else {
1107 $page->trigError("Impossible de déplacer la page ".$wikipage);
1108 }
1109 }
1110 }
1111
1112 $perms = PlWikiPage::permOptions();
1113
1114 // list wiki pages and their perms
1115 $wiki_pages = PlWikiPage::listPages();
1116 ksort($wiki_pages);
1117 $wiki_tree = array();
1118 foreach ($wiki_pages as $file => $desc) {
1119 list($cat, $name) = explode('.', $file);
1120 if (!isset($wiki_tree[$cat])) {
1121 $wiki_tree[$cat] = array();
1122 }
1123 $wiki_tree[$cat][$name] = $desc;
1124 }
1125
1126 $page->changeTpl('admin/wiki.tpl');
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 #x4dat#.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 #x4dat#.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 #x4dat#.ip_watch AS w
1211 LEFT JOIN #x4dat#.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 #x4dat#.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 ?>