Merge remote branch 'origin/platal-1.0.0'
[platal.git] / modules / admin.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 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 'get_rights' => $this->make_hook('get_rights', AUTH_MDP, 'admin'),
29 'admin' => $this->make_hook('default', 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/user' => $this->make_hook('user', AUTH_MDP, 'admin'),
43 'admin/add_accounts' => $this->make_hook('add_accounts', AUTH_MDP, 'admin'),
44 'admin/validate' => $this->make_hook('validate', AUTH_MDP, 'admin'),
45 'admin/validate/answers' => $this->make_hook('validate_answers', AUTH_MDP, 'admin'),
46 'admin/wiki' => $this->make_hook('wiki', AUTH_MDP, 'admin'),
47 'admin/ipwatch' => $this->make_hook('ipwatch', AUTH_MDP, 'admin'),
48 'admin/icons' => $this->make_hook('icons', AUTH_MDP, 'admin'),
49 'admin/accounts' => $this->make_hook('accounts', AUTH_MDP, 'admin'),
50 'admin/account/types' => $this->make_hook('account_types', 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_get_rights(&$page, $level)
62 {
63 if (S::suid()) {
64 $page->kill('Déjà en SUID');
65 }
66 $user =& S::user();
67 Platal::session()->startSUID($user, $level);
68
69 pl_redirect('/');
70 }
71
72 function handler_default(&$page)
73 {
74 $page->changeTpl('admin/index.tpl');
75 $page->setTitle('Administration');
76 }
77
78 function handler_postfix_delayed(&$page)
79 {
80 $page->changeTpl('admin/postfix_delayed.tpl');
81 $page->setTitle('Administration - Postfix : Retardés');
82
83 if (Env::has('del')) {
84 $crc = Env::v('crc');
85 XDB::execute("UPDATE postfix_mailseen SET release = 'del' WHERE crc = {?}", $crc);
86 $page->trigSuccess($crc . " verra tous ses emails supprimés&nbsp;!");
87 } elseif (Env::has('ok')) {
88 $crc = Env::v('crc');
89 XDB::execute("UPDATE postfix_mailseen SET release = 'ok' WHERE crc = {?}", $crc);
90 $page->trigSuccess($crc . " a le droit de passer&nbsp;!");
91 }
92
93 $sql = XDB::iterator(
94 "SELECT crc, nb, update_time, create_time,
95 FIND_IN_SET('del', p.release) AS del,
96 FIND_IN_SET('ok', p.release) AS ok
97 FROM postfix_mailseen AS p
98 WHERE nb >= 30
99 ORDER BY p.release != ''");
100
101 $page->assign_by_ref('mails', $sql);
102 }
103
104 function handler_postfix_regexpsbounces(&$page, $new = null) {
105 $page->changeTpl('admin/emails_bounces_re.tpl');
106 $page->setTitle('Administration - Postfix : Regexps Bounces');
107 $page->assign('new', $new);
108
109 if (Post::has('submit')) {
110 foreach (Env::v('lvl') as $id=>$val) {
111 XDB::query(
112 "REPLACE INTO emails_bounces_re (id,pos,lvl,re,text) VALUES ({?}, {?}, {?}, {?}, {?})",
113 $id, $_POST['pos'][$id], $_POST['lvl'][$id], $_POST['re'][$id], $_POST['text'][$id]
114 );
115 }
116 }
117
118 $page->assign('bre', XDB::iterator("SELECT * FROM emails_bounces_re ORDER BY pos"));
119 }
120
121 // {{{ logger view
122
123 /** Retrieves the available days for a given year and month.
124 * Obtain a list of days of the given month in the given year
125 * that are within the range of dates that we have log entries for.
126 *
127 * @param integer year
128 * @param integer month
129 * @return array days in that month we have log entries covering.
130 * @private
131 */
132 function _getDays($year, $month)
133 {
134 // give a 'no filter' option
135 $days = array();
136 $days[0] = "----";
137
138 if ($year && $month) {
139 $day_max = Array(-1, 31, checkdate(2, 29, $year) ? 29 : 28 , 31,
140 30, 31, 30, 31, 31, 30, 31, 30, 31);
141 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
142 MONTH(MAX(start)), MONTH(MIN(start)),
143 DAYOFMONTH(MAX(start)),
144 DAYOFMONTH(MIN(start))
145 FROM log_sessions");
146 list($ymax, $ymin, $mmax, $mmin, $dmax, $dmin) = $res->fetchOneRow();
147
148 if (($year < $ymin) || ($year == $ymin && $month < $mmin)) {
149 return array();
150 }
151
152 if (($year > $ymax) || ($year == $ymax && $month > $mmax)) {
153 return array();
154 }
155
156 $min = ($year==$ymin && $month==$mmin) ? intval($dmin) : 1;
157 $max = ($year==$ymax && $month==$mmax) ? intval($dmax) : $day_max[$month];
158
159 for($i = $min; $i<=$max; $i++) {
160 $days[$i] = $i;
161 }
162 }
163 return $days;
164 }
165
166
167 /** Retrieves the available months for a given year.
168 * Obtains a list of month numbers that are within the timeframe that
169 * we have log entries for.
170 *
171 * @param integer year
172 * @return array List of month numbers we have log info for.
173 * @private
174 */
175 function _getMonths($year)
176 {
177 // give a 'no filter' option
178 $months = array();
179 $months[0] = "----";
180
181 if ($year) {
182 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
183 MONTH(MAX(start)), MONTH(MIN(start))
184 FROM log_sessions");
185 list($ymax, $ymin, $mmax, $mmin) = $res->fetchOneRow();
186
187 if (($year < $ymin) || ($year > $ymax)) {
188 return array();
189 }
190
191 $min = $year == $ymin ? intval($mmin) : 1;
192 $max = $year == $ymax ? intval($mmax) : 12;
193
194 for($i = $min; $i<=$max; $i++) {
195 $months[$i] = $i;
196 }
197 }
198 return $months;
199 }
200
201
202 /** Retrieves the available years.
203 * Obtains a list of years that we have log entries covering.
204 *
205 * @return array years we have log entries for.
206 * @private
207 */
208 function _getYears()
209 {
210 // give a 'no filter' option
211 $years = array();
212 $years[0] = "----";
213
214 // retrieve available years
215 $res = XDB::query("select YEAR(MAX(start)), YEAR(MIN(start)) FROM log_sessions");
216 list($max, $min) = $res->fetchOneRow();
217
218 for($i = intval($min); $i<=$max; $i++) {
219 $years[$i] = $i;
220 }
221 return $years;
222 }
223
224
225 /** Make a where clause to get a user's sessions.
226 * Prepare the where clause request that will retrieve the sessions.
227 *
228 * @param $year INTEGER Only get log entries made during the given year.
229 * @param $month INTEGER Only get log entries made during the given month.
230 * @param $day INTEGER Only get log entries made during the given day.
231 * @param $uid INTEGER Only get log entries referring to the given user ID.
232 *
233 * @return STRING the WHERE clause of a query, including the 'WHERE' keyword
234 * @private
235 */
236 function _makeWhere($year, $month, $day, $uid)
237 {
238 // start constructing the "where" clause
239 $where = array();
240
241 if ($uid)
242 array_push($where, "s.uid='$uid'");
243
244 // we were given at least a year
245 if ($year) {
246 if ($day) {
247 $dmin = mktime(0, 0, 0, $month, $day, $year);
248 $dmax = mktime(0, 0, 0, $month, $day+1, $year);
249 } elseif ($month) {
250 $dmin = mktime(0, 0, 0, $month, 1, $year);
251 $dmax = mktime(0, 0, 0, $month+1, 1, $year);
252 } else {
253 $dmin = mktime(0, 0, 0, 1, 1, $year);
254 $dmax = mktime(0, 0, 0, 1, 1, $year+1);
255 }
256 $where[] = "start >= " . date("Ymd000000", $dmin);
257 $where[] = "start < " . date("Ymd000000", $dmax);
258 }
259
260 if (!empty($where)) {
261 return ' WHERE ' . implode($where, " AND ");
262 } else {
263 return '';
264 }
265 // WE know it's totally reversed, so better use array_reverse than a SORT BY start DESC
266 }
267
268 // }}}
269
270 function handler_logger(&$page, $action = null, $arg = null) {
271 if ($action == 'session') {
272
273 // we are viewing a session
274 $res = XDB::query("SELECT ls.*, a.alias AS username, sa.alias AS suer
275 FROM log_sessions AS ls
276 LEFT JOIN aliases AS a ON (a.uid = ls.uid AND a.type='a_vie')
277 LEFT JOIN aliases AS sa ON (sa.uid = ls.suid AND sa.type='a_vie')
278 WHERE ls.id = {?}", $arg);
279
280 $page->assign('session', $a = $res->fetchOneAssoc());
281
282 $res = XDB::iterator('SELECT a.text, e.data, e.stamp
283 FROM log_events AS e
284 LEFT JOIN log_actions AS a ON e.action=a.id
285 WHERE e.session={?}', $arg);
286 while ($myarr = $res->next()) {
287 $page->append('events', $myarr);
288 }
289
290 } else {
291 $loguser = $action == 'user' ? $arg : Env::v('loguser');
292
293 $res = XDB::query('SELECT uid FROM aliases WHERE alias={?}',
294 $loguser);
295 $loguid = $res->fetchOneCell();
296
297 if ($loguid) {
298 $year = Env::i('year');
299 $month = Env::i('month');
300 $day = Env::i('day');
301 } else {
302 $year = Env::i('year', intval(date('Y')));
303 $month = Env::i('month', intval(date('m')));
304 $day = Env::i('day', intval(date('d')));
305 }
306
307 if (!$year)
308 $month = 0;
309 if (!$month)
310 $day = 0;
311
312 // smarty assignments
313 // retrieve available years
314 $page->assign('years', $this->_getYears());
315 $page->assign('year', $year);
316
317 // retrieve available months for the current year
318 $page->assign('months', $this->_getMonths($year));
319 $page->assign('month', $month);
320
321 // retrieve available days for the current year and month
322 $page->assign('days', $this->_getDays($year, $month));
323 $page->assign('day', $day);
324
325 $page->assign('loguser', $loguser);
326 // smarty assignments
327
328 if ($loguid || $year) {
329
330 // get the requested sessions
331 $where = $this->_makeWhere($year, $month, $day, $loguid);
332 $select = "SELECT s.id, s.start, s.uid,
333 a.alias as username
334 FROM log_sessions AS s
335 LEFT JOIN aliases AS a ON (a.uid = s.uid AND a.type='a_vie')
336 $where
337 ORDER BY start DESC";
338 $res = XDB::iterator($select);
339
340 $sessions = array();
341 while ($mysess = $res->next()) {
342 $mysess['events'] = array();
343 $sessions[$mysess['id']] = $mysess;
344 }
345 array_reverse($sessions);
346
347 // attach events
348 $sql = "SELECT s.id, a.text
349 FROM log_sessions AS s
350 LEFT JOIN log_events AS e ON(e.session=s.id)
351 INNER JOIN log_actions AS a ON(a.id=e.action)
352 $where";
353
354 $res = XDB::iterator($sql);
355 while ($event = $res->next()) {
356 array_push($sessions[$event['id']]['events'], $event['text']);
357 }
358 $page->assign_by_ref('sessions', $sessions);
359 } else {
360 $page->assign('msg_nofilters', "Sélectionner une annuée et/ou un utilisateur");
361 }
362 }
363
364 $page->changeTpl('admin/logger-view.tpl');
365
366 $page->setTitle('Administration - Logs des sessions');
367 }
368
369 function handler_user(&$page, $login = false)
370 {
371 global $globals;
372 $page->changeTpl('admin/user.tpl');
373 $page->setTitle('Administration - Compte');
374
375 if (S::suid()) {
376 $page->kill("Déjà en SUID&nbsp;!!!");
377 }
378
379 // Loads the user identity using the environment.
380 if ($login) {
381 $user = User::get($login);
382 }
383 if (empty($user)) {
384 return;
385 }
386
387 $login = $user->login();
388 $registered = ($user->state != 'pending');
389
390 // Form processing
391 if (!empty($_POST)) {
392 S::assert_xsrf_token();
393 if (Post::has('uid') && Post::i('uid') != $user->id()) {
394 $page->kill('Une erreur s\'est produite');
395 }
396 }
397
398 // Handles specific requests (AX sync, su, ...).
399 if(Post::has('log_account')) {
400 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
401 }
402
403 if(Post::has('su_account') && $registered) {
404 if (!Platal::session()->startSUID($user)) {
405 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->login());
406 } else {
407 pl_redirect("");
408 }
409 }
410
411 // Account Form {{{
412 $to_update = array();
413 if (Post::has('disable_weak_access')) {
414 $to_update['weak_password'] = null;
415 } else if (Post::has('update_account')) {
416 if (!$user->hasProfile()) {
417 if (Post::s('full_name') != $user->fullName()) {
418 $to_update['full_name'] = Post::s('full_name');
419 }
420 if (Post::s('display_name') != $user->displayName()) {
421 $to_update['display_name'] = Post::s('display_name');
422 }
423 if (Post::s('directory_name') != $user->directoryName()) {
424 $to_update['directory_name'] = Post::s('directory_name');
425 }
426 }
427 if (Post::s('sex') != ($user->isFemale() ? 'female' : 'male')) {
428 $to_update['sex'] = Post::s('sex');
429 if ($user->hasProfile()) {
430 XDB::execute('UPDATE profiles
431 SET sex = {?}
432 WHERE pid = {?}',
433 Post::s('sex'), $user->profile()->id());
434 }
435 }
436 if (!Post::blank('hashpass')) {
437 $to_update['password'] = Post::s('hashpass');
438 $account = new GoogleAppsAccount($user);
439 if ($account->active() && $account->sync_password) {
440 $account->set_password(Post::s('hashpass'));
441 }
442 }
443 if (!Post::blank('weak_password')) {
444 $to_update['weak_password'] = Post::s('weak_password');
445 }
446 if (Post::i('token_access', 0) != ($user->token_access ? 1 : 0)) {
447 $to_update['token'] = Post::i('token_access') ? rand_url_id(16) : null;
448 }
449 if (Post::i('skin') != $user->skin) {
450 $to_update['skin'] = Post::i('skin');
451 if ($to_update['skin'] == 0) {
452 $to_update['skin'] = null;
453 }
454 }
455 if (Post::s('state') != $user->state) {
456 $to_update['state'] = Post::s('state');
457 }
458 if (Post::i('is_admin', 0) != ($user->is_admin ? 1 : 0)) {
459 $to_update['is_admin'] = Post::b('is_admin');
460 }
461 if (Post::s('type') != $user->type) {
462 $to_update['type'] = Post::s('type');
463 }
464 if (Post::i('watch', 0) != ($user->watch ? 1 : 0)) {
465 $to_update['flags'] = new PlFlagset();
466 $to_update['flags']->addFlag('watch', Post::i('watch'));
467 }
468 if (Post::t('comment') != $user->comment) {
469 $to_update['comment'] = Post::blank('comment') ? null : Post::t('comment');
470 }
471 }
472 if (!empty($to_update)) {
473 $res = XDB::query('SELECT *
474 FROM accounts
475 WHERE uid = {?}', $user->id());
476 $oldValues = $res->fetchAllAssoc();
477 $oldValues = $oldValues[0];
478
479 $set = array();
480 $diff = array();
481 foreach ($to_update as $k => $value) {
482 $value = XDB::format('{?}', $value);
483 $set[] = $k . ' = ' . $value;
484 $diff[$k] = array($oldValues[$k], trim($value, "'"));
485 unset($oldValues[$k]);
486 }
487 XDB::execute('UPDATE accounts
488 SET ' . implode(', ', $set) . '
489 WHERE uid = ' . XDB::format('{?}', $user->id()));
490 $page->trigSuccess('Données du compte mise à jour avec succès');
491 $user = User::getWithUID($user->id());
492
493 /* Formats the $diff and send it to the site administrators. The rules are the folowing:
494 * -formats: password, token, weak_password
495 */
496 foreach (array('password', 'token', 'weak_password') as $key) {
497 if (isset($diff[$key])) {
498 $diff[$key] = array('old value', 'new value');
499 } else {
500 $oldValues[$key] = 'old value';
501 }
502 }
503
504 $mail = new PlMailer('admin/useredit.mail.tpl');
505 $mail->assign('admin', S::user()->hruid);
506 $mail->assign('hruid', $user->hruid);
507 $mail->assign('diff', $diff);
508 $mail->assign('oldValues', $oldValues);
509 $mail->send();
510 }
511 // }}}
512
513 // Profile form {{{
514 if (Post::has('add_profile') || Post::has('del_profile') || Post::has('owner')) {
515 if (Post::i('del_profile', 0) != 0) {
516 XDB::execute('DELETE FROM account_profiles
517 WHERE uid = {?} AND pid = {?}',
518 $user->id(), Post::i('del_profile'));
519 } else if (!Post::blank('new_profile')) {
520 $profile = Profile::get(Post::t('new_profile'));
521 if (!$profile) {
522 $page->trigError('Le profil ' . Post::t('new_profile') . ' n\'existe pas');
523 } else {
524 XDB::execute('INSERT IGNORE INTO account_profiles (uid, pid)
525 VALUES ({?}, {?})',
526 $user->id(), $profile->id());
527 }
528 }
529 XDB::execute('UPDATE account_profiles
530 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
531 WHERE uid = {?}',
532 Post::i('owner'), $user->id());
533 }
534 // }}}
535
536 // Email forwards form {{{
537 require_once("emails.inc.php");
538 $redirect = ($registered ? new Redirect($user) : null);
539 if (Post::has('add_fwd')) {
540 $email = Post::t('email');
541 if (!isvalid_email_redirection($email)) {
542 $page->trigError("Email non valide: $email");
543 } else {
544 $redirect->add_email($email);
545 $page->trigSuccess("Ajout de $email effectué");
546 }
547 } else if (!Post::blank('del_fwd')) {
548 $redirect->delete_email(Post::t('del_fwd'));
549 } else if (!Post::blank('activate_fwd')) {
550 $redirect->modify_one_email(Post::t('activate_fwd', true));
551 } else if (!Post::blank('deactivate_fwd')) {
552 $redirect->modify_one_email(Post::t('deactivate_fwd', false));
553 } else if (Post::has('disable_fwd')) {
554 $redirect->disable();
555 } else if (Post::has('enable_fwd')) {
556 $redirect->enable();
557 } else if (!Post::blank('clean_fwd')) {
558 $redirect->clean_errors(Post::t('clean_fwd'));
559 }
560 // }}}
561
562 // Email alias form {{{
563 if (Post::has('add_alias')) {
564 // Splits new alias in user and fqdn.
565 $alias = Env::t('email');
566 if (strpos($alias, '@') !== false) {
567 list($alias, $domain) = explode('@', $alias);
568 } else {
569 $domain = $globals->mail->domain;
570 }
571
572 // Checks for alias' user validity.
573 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
574 $page->trigError("'$alias' n'est pas un alias valide");
575 }
576
577 // Eventually adds the alias to the right domain.
578 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
579 $req = new AliasReq($user, $alias, 'Admin request', false);
580 if ($req->commit()) {
581 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué");
582 } else {
583 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué");
584 }
585 } elseif ($domain == $globals->mail->domain || $domain == $globals->mail->domain2) {
586 $res = XDB::execute("INSERT INTO aliases (uid, alias, type)
587 VALUES ({?}, {?}, 'alias')",
588 $user->id(), $alias);
589 $page->trigSuccess("Nouvel alias '$alias' ajouté");
590 } else {
591 $page->trigError("Le domaine '$domain' n'est pas valide");
592 }
593 } else if (!Post::blank('del_alias')) {
594 XDB::execute("DELETE FROM aliases
595 WHERE uid = {?} AND alias = {?} AND
596 type NOT IN ('a_vie', 'homonyme')",
597 $user->id(), $val);
598 XDB::execute("UPDATE emails
599 SET rewrite = ''
600 WHERE uid = {?} AND rewrite LIKE CONCAT({?}, '@%')",
601 $user->id(), $val);
602 fix_bestalias($user);
603 $page->trigSuccess("L'alias '$val' a été supprimé");
604 } else if (!Post::blank('best')) {
605 XDB::execute("UPDATE aliases
606 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
607 WHERE uid = {?}", $user->id());
608 XDB::execute("UPDATE aliases
609 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
610 WHERE uid = {?} AND alias = {?}", $user->id(), $val);
611 // As having a non-null bestalias value is critical in
612 // plat/al's code, we do an a posteriori check on the
613 // validity of the bestalias.
614 fix_bestalias($user);
615 }
616 // }}}
617
618 // OpenId form {{{
619 if (Post::has('del_openid')) {
620 XDB::execute('DELETE FROM account_auth_openid
621 WHERE id = {?}', Post::i('del_openid'));
622 }
623 // }}}
624
625 // Forum form {{{
626 if (Post::has('b_edit')) {
627 XDB::execute("DELETE FROM forum_innd
628 WHERE uid = {?}", $user->id());
629 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
630 XDB::execute("INSERT INTO forum_innd
631 SET ipmin = '0', ipmax = '4294967295',
632 write_perm = {?}, read_perm = {?},
633 comment = {?}, priority = '200', uid = {?}",
634 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
635 }
636 }
637 // }}}
638
639
640 $page->addJsLink('jquery.ui.core.js');
641 $page->addJsLink('jquery.ui.tabs.js');
642
643 // Displays last login and last host information.
644 $res = XDB::query("SELECT start, host
645 FROM log_sessions
646 WHERE uid = {?} AND suid = 0
647 ORDER BY start DESC
648 LIMIT 1", $user->id());
649 list($lastlogin,$host) = $res->fetchOneRow();
650 $page->assign('lastlogin', $lastlogin);
651 $page->assign('host', $host);
652
653 // Display active aliases.
654 $page->assign('virtuals', $user->emailAliases());
655 $page->assign('aliases', XDB::iterator("SELECT alias, type='a_vie' AS for_life,
656 FIND_IN_SET('bestalias',flags) AS best, expire
657 FROM aliases
658 WHERE uid = {?} AND type != 'homonyme'
659 ORDER BY type != 'a_vie'", $user->id()));
660 $page->assign('account_types', XDB::iterator('SELECT * FROM account_types ORDER BY type'));
661 $page->assign('skins', XDB::iterator('SELECT id, name FROM skins ORDER BY name'));
662 $page->assign('profiles', XDB::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
663 FROM account_profiles AS ap
664 INNER JOIN profiles AS p ON (ap.pid = p.pid)
665 WHERE ap.uid = {?}', $user->id()));
666 $page->assign('openid', XDB::iterator('SELECT id, url
667 FROM account_auth_openid
668 WHERE uid = {?}', $user->id()));
669
670 // Displays email redirection and the general profile.
671 if ($registered && $redirect) {
672 $page->assign('emails', $redirect->emails);
673 }
674
675 $page->assign('user', $user);
676 $page->assign('hasProfile', $user->hasProfile());
677
678 // Displays forum bans.
679 $res = XDB::query("SELECT write_perm, read_perm, comment
680 FROM forum_innd
681 WHERE uid = {?}", $user->id());
682 $bans = $res->fetchOneAssoc();
683 $page->assign('bans', $bans);
684 }
685
686 private static function getHrid($firstname, $lastname, $promo)
687 {
688 if ($firstname != null && $lastname != null && $promo != null) {
689 return User::makeHrid($firstname, $lastname, $promo);
690 }
691 return null;
692 }
693
694 private static function formatNewUser(&$page, $infosLine, $separator, $promo, $size)
695 {
696 $infos = explode($separator, $infosLine);
697 if (sizeof($infos) > $size || sizeof($infos) < 2) {
698 $page->trigError("La ligne $infosLine n'a pas été ajoutée.");
699 return false;
700 }
701
702 array_map('trim', $infos);
703 $hrid = self::getHrid($infos[1], $infos[0], $promo);
704 $res1 = XDB::query('SELECT COUNT(*)
705 FROM accounts
706 WHERE hruid = {?}', $hrid);
707 $res2 = XDB::query('SELECT COUNT(*)
708 FROM profiles
709 WHERE hrpid = {?}', $hrid);
710 if (is_null($hrid) || $res1->fetchOneCell() > 0 || $res2->fetchOneCell() > 0) {
711 $page->trigError("La ligne $infosLine n'a pas été ajoutée.");
712 return false;
713 }
714 $infos['hrid'] = $hrid;
715 return $infos;
716 }
717
718 private static function formatSex(&$page, $sex, $line)
719 {
720 switch ($sex) {
721 case 'F':
722 return PlUser::GENDER_FEMALE;
723 case 'M':
724 return PlUser::GENDER_MALE;
725 default:
726 $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
727 return null;
728 }
729 }
730
731 private static function formatBirthDate($birthDate)
732 {
733 return date("Y-m-d", strtotime($birthDate));
734 }
735
736 function handler_add_accounts(&$page, $action = null, $promo = null)
737 {
738 $page->changeTpl('admin/add_accounts.tpl');
739
740 if (Env::has('add_type') && Env::has('people')) {
741 $lines = explode("\n", Env::t('people'));
742 $separator = Env::t('separator');
743 $promotion = Env::i('promotion');
744 $nameTypes = DirEnum::getOptions(DirEnum::NAMETYPES);
745 $nameTypes = array_flip($nameTypes);
746
747 if (Env::t('add_type') == 'promo') {
748 $type = 'x';
749 $eduSchools = DirEnum::getOptions(DirEnum::EDUSCHOOLS);
750 $eduSchools = array_flip($eduSchools);
751 $eduDegrees = DirEnum::getOptions(DirEnum::EDUDEGREES);
752 $eduDegrees = array_flip($eduDegrees);
753 switch (Env::t('edu_type')) {
754 case 'X':
755 $degreeid = $eduDegrees[Profile::DEGREE_X];
756 $entry_year = $promotion;
757 $grad_year = $promotion + 3;
758 $promo = 'X' . $promotion;
759 break;
760 case 'M':
761 $degreeid = $eduDegrees[Profile::DEGREE_M];
762 $grad_year = $promotion;
763 $entry_year = $promotion - 2;
764 $promo = 'M' . $promotion;
765 break;
766 case 'D':
767 $degreeid = $eduDegrees[Profile::DEGREE_D];
768 $grad_year = $promotion;
769 $entry_year = $promotion - 3;
770 $promo = 'D' . $promotion;
771 break;
772 default:
773 $page->killError("La formation n'est pas reconnue:" . Env::t('edu_type') . '.');
774 }
775
776 foreach ($lines as $line) {
777 if ($infos = self::formatNewUser($page, $line, $separator, $promotion, 6)) {
778 $sex = self::formatSex($page, $infos[3], $line);
779 if (!is_null($sex)) {
780 $name = $infos[1] . ' ' . $infos[0];
781 $birthDate = self::formatBirthDate($infos[2]);
782 $xorgId = Profile::getXorgId($infos[4]);
783 if (is_null($xorgId)) {
784 $page->trigError("La ligne $line n'a pas été ajoutée car le matricule École est mal renseigné.");
785 continue;
786 }
787
788 XDB::execute('INSERT INTO profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex)
789 VALUES ({?}, {?}, {?}, {?}, {?})',
790 $infos['hrid'], $xorgId, $infos[5], $birthDate, $sex);
791 $pid = XDB::insertId();
792 XDB::execute('INSERT INTO profile_name (pid, name, typeid)
793 VALUES ({?}, {?}, {?})',
794 $pid, $infos[0], $nameTypes['name_ini']);
795 XDB::execute('INSERT INTO profile_name (pid, name, typeid)
796 VALUES ({?}, {?}, {?})',
797 $pid, $infos[1], $nameTypes['firstname_ini']);
798 XDB::execute('INSERT INTO profile_display (pid, yourself, public_name, private_name,
799 directory_name, short_name, sort_name, promo)
800 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
801 $pid, $infos[1], $name, $name, $name, $name, $infos[0] . ' ' . $infos[1], $promo);
802 XDB::execute('INSERT INTO profile_education (pid, eduid, degreeid, entry_year, grad_year, flags)
803 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
804 $pid, $eduSchools[Profile::EDU_X], $degreeid, $entry_year, $grad_year, 'primary');
805 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, full_name, display_name, sex)
806 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
807 $infos['hrid'], $type, 0, 'active', $name, $infos[1], $sex);
808 $uid = XDB::insertId();
809 XDB::execute('INSERT INTO account_profiles (uid, pid, perms)
810 VALUES ({?}, {?}, {?})',
811 $uid, $pid, 'owner');
812 }
813 }
814 }
815 } else if (Env::t('add_type') == 'account') {
816 $type = Env::t('type');
817 $newAccounts = array();
818 foreach ($lines as $line) {
819 if ($infos = self::formatNewUser($page, $line, $separator, $type, 4)) {
820 $sex = self::formatSex($page, $infos[3], $line);
821 if (!is_null($sex)) {
822 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, email, full_name, display_name, sex)
823 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
824 $infos['hrid'], $type, 0, 'active', $infos[2], $infos[1] . ' ' . $infos[0], $infos[1], $sex);
825 $newAccounts[$infos['hrid']] = $infos[1] . ' ' . $infos[0];
826 }
827 }
828 }
829 if (!empty($newAccounts)) {
830 $page->assign('newAccounts', $newAccounts);
831 }
832 } else if (Env::t('add_type') == 'ax_id') {
833 $type = 'x';
834 foreach ($lines as $line) {
835 if ($infos = self::formatNewUser($page, $line, $separator, $promotion, 3)) {
836 XDB::execute('UPDATE profiles
837 SET ax_id = {?}
838 WHERE hrpid = {?}',
839 $infos[2], $infos['hrid']);
840 }
841 }
842 }
843
844 $errors = $page->nb_errs();
845 if ($errors == 0) {
846 $page->trigSuccess("L'opération a été effectuée avec succès.");
847 } else {
848 $page->trigSuccess('L\'opération a été effectuée avec succès, sauf pour '
849 . (($errors == 1) ? 'l\'erreur signalée' : "les $errors erreurs signalées") . ' ci-dessus.');
850 }
851 } else if (Env::has('add_type')) {
852 $res = XDB::query('SELECT type
853 FROM account_types');
854 $page->assign('account_types', $res->fetchColumn());
855 $page->assign('add_type', Env::s('add_type'));
856 }
857 }
858
859 function handler_homonyms(&$page, $op = 'list', $target = null)
860 {
861 $page->changeTpl('admin/homonymes.tpl');
862 $page->setTitle('Administration - Homonymes');
863 $this->load("homonyms.inc.php");
864
865 if ($target) {
866 $user = User::getSilent($target);
867 if (!$user || !($loginbis = select_if_homonyme($user))) {
868 $target = 0;
869 } else {
870 $page->assign('user', $user);
871 $page->assign('loginbis',$loginbis);
872 }
873 }
874
875 $page->assign('op', $op);
876 $page->assign('target', $target);
877
878 // on a un $target valide, on prepare les mails
879 if ($target) {
880 // on examine l'op a effectuer
881 switch ($op) {
882 case 'mail':
883 S::assert_xsrf_token();
884
885 send_warning_homonyme($user, $loginbis);
886 switch_bestalias($user, $loginbis);
887 $op = 'list';
888 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
889 break;
890
891 case 'correct':
892 S::assert_xsrf_token();
893
894 switch_bestalias($user, $loginbis);
895 XDB::execute("UPDATE aliases
896 SET type = 'homonyme', expire=NOW()
897 WHERE alias = {?}", $loginbis);
898 XDB::execute("REPLACE INTO homonyms (homonyme_id, uid)
899 VALUES ({?}, {?})", $target, $target);
900 send_robot_homonyme($user, $loginbis);
901 $op = 'list';
902 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
903 break;
904 }
905 }
906
907 if ($op == 'list') {
908 $res = XDB::iterator(
909 "SELECT a.alias AS homonyme, s.alias AS forlife,
910 IF(h.homonyme_id = s.uid, a.expire, NULL) AS expire,
911 IF(h.homonyme_id = s.uid, a.type, NULL) AS type, ac.uid
912 FROM aliases AS a
913 LEFT JOIN homonyms AS h ON (h.homonyme_id = a.uid)
914 INNER JOIN aliases AS s ON (s.uid = h.uid AND s.type = 'a_vie')
915 INNER JOIN accounts AS ac ON (ac.uid = a.uid)
916 WHERE a.type = 'homonyme' OR a.expire != ''
917 ORDER BY a.alias, forlife");
918 $hnymes = Array();
919 while ($tab = $res->next()) {
920 $hnymes[$tab['homonyme']][] = $tab;
921 }
922 $page->assign_by_ref('hnymes', $hnymes);
923 }
924 }
925
926 function handler_deaths(&$page, $promo = 0, $validate = false)
927 {
928 $page->changeTpl('admin/deces_promo.tpl');
929 $page->setTitle('Administration - Deces');
930
931 if (!$promo) {
932 $promo = Env::t('promo', 'X1923');
933 }
934 $page->assign('promo', $promo);
935 if (!$promo) {
936 return;
937 }
938
939 if ($validate) {
940 S::assert_xsrf_token();
941
942 $res = XDB::iterRow('SELECT p.pid, pd.directory_name, p.deathdate
943 FROM profiles AS p
944 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
945 WHERE pd.promo = {?}', $promo);
946 while (list($pid, $name, $death) = $res->next()) {
947 $val = Env::v('death_' . $pid);
948 if($val == $death || empty($val)) {
949 continue;
950 }
951
952 XDB::execute('UPDATE profiles
953 SET deathdate = {?}, deathdate_rec = NOW()
954 WHERE pid = {?}', $val, $pid);
955 $page->trigSuccess('Ajout du décès de ' . $name . ' le ' . $val . '.');
956 if($death == '0000-00-00' || empty($death)) {
957 $profile = Profile::get($pid);
958 $profile->clear();
959 $profile->owner()->clear(false);
960 }
961 }
962 }
963
964 $res = XDB::iterator('SELECT p.pid, pd.directory_name, p.deathdate
965 FROM profiles AS p
966 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
967 WHERE pd.promo = {?}
968 ORDER BY pd.sort_name', $promo);
969 $page->assign('decedes', $res);
970 }
971
972 function handler_dead_but_active(&$page)
973 {
974 $page->changeTpl('admin/dead_but_active.tpl');
975 $page->setTitle('Administration - Décédés');
976
977 $res = XDB::iterator(
978 "SELECT a.hruid, pd.promo, p.ax_id, pd.directory_name, p.deathdate, DATE(MAX(s.start)) AS last
979 FROM accounts AS a
980 INNER JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET('owner', ap.perms))
981 INNER JOIN profiles AS p ON (p.pid = ap.pid)
982 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
983 LEFT JOIN log_sessions AS s ON (s.uid = a.uid AND suid = 0)
984 WHERE a.state = 'active' AND p.deathdate IS NOT NULL
985 GROUP BY a.uid
986 ORDER BY pd.promo, pd.sort_name");
987 $page->assign('dead', $res);
988 }
989
990 function handler_validate(&$page, $action = 'list', $id = null)
991 {
992 $page->changeTpl('admin/validation.tpl');
993 $page->setTitle('Administration - Valider une demande');
994 $page->addCssLink('nl.css');
995 $page->addJsLink('ajax.js');
996 require_once("validations.inc.php");
997
998
999 if ($action == 'edit' and !is_null($id)) {
1000 $page->assign('preview_id', $id);
1001 }
1002
1003 if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
1004 S::assert_xsrf_token();
1005
1006 $req = Validate::get_typed_request(Env::v('uid'), Env::v('type'), Env::v('stamp'));
1007 if ($req) {
1008 $req->handle_formu();
1009 } else {
1010 $page->trigWarning('La validation a déjà été effectuée.');
1011 }
1012 }
1013
1014 $r = XDB::iterator('SHOW COLUMNS FROM requests_answers');
1015 while (($a = $r->next()) && $a['Field'] != 'category');
1016 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
1017
1018 $hidden = array();
1019 $res = XDB::query('SELECT hidden_requests
1020 FROM requests_hidden
1021 WHERE uid = {?}', S::v('uid'));
1022 $hide_requests = $res->fetchOneCell();
1023 if (Post::has('hide')) {
1024 $hide = array();
1025 foreach ($categories as $cat)
1026 if (!Post::v($cat)) {
1027 $hidden[$cat] = 1;
1028 $hide[] = $cat;
1029 }
1030 $hide_requests = join(',', $hide);
1031 XDB::query('REPLACE INTO requests_hidden (uid, hidden_requests)
1032 VALUES ({?}, {?})',
1033 S::v('uid'), $hide_requests);
1034 } elseif ($hide_requests) {
1035 foreach (explode(',', $hide_requests) as $hide_type)
1036 $hidden[$hide_type] = true;
1037 }
1038 $page->assign('hide_requests', $hidden);
1039
1040 // Update the count of item to validate here... useful in development configuration
1041 // where several copies of the site use the same DB, but not the same "dynamic configuration"
1042 global $globals;
1043 $globals->updateNbValid();
1044 $page->assign('vit', new ValidateIterator());
1045 }
1046
1047 function handler_validate_answers(&$page, $action = 'list', $id = null)
1048 {
1049 $page->setTitle('Administration - Réponses automatiques de validation');
1050 $page->assign('title', 'Gestion des réponses automatiques');
1051 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
1052 $table_editor->describe('category','catégorie',true);
1053 $table_editor->describe('title','titre',true);
1054 $table_editor->describe('answer','texte',false);
1055 $table_editor->apply($page, $action, $id);
1056 }
1057
1058 function handler_skins(&$page, $action = 'list', $id = null)
1059 {
1060 $page->setTitle('Administration - Skins');
1061 $page->assign('title', 'Gestion des skins');
1062 $table_editor = new PLTableEditor('admin/skins','skins','id');
1063 $table_editor->describe('name','nom',true);
1064 $table_editor->describe('skin_tpl','nom du template',true);
1065 $table_editor->describe('auteur','auteur',false);
1066 $table_editor->describe('comment','commentaire',true);
1067 $table_editor->describe('date','date',false);
1068 $table_editor->describe('ext','extension du screenshot',false);
1069 $table_editor->apply($page, $action, $id);
1070 }
1071
1072 function handler_postfix_blacklist(&$page, $action = 'list', $id = null)
1073 {
1074 $page->setTitle('Administration - Postfix : Blacklist');
1075 $page->assign('title', 'Blacklist de postfix');
1076 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true);
1077 $table_editor->describe('reject_text','Texte de rejet',true);
1078 $table_editor->describe('email','email',true);
1079 $table_editor->apply($page, $action, $id);
1080 }
1081
1082 function handler_postfix_whitelist(&$page, $action = 'list', $id = null)
1083 {
1084 $page->setTitle('Administration - Postfix : Whitelist');
1085 $page->assign('title', 'Whitelist de postfix');
1086 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true);
1087 $table_editor->describe('email','email',true);
1088 $table_editor->apply($page, $action, $id);
1089 }
1090
1091 function handler_mx_broken(&$page, $action = 'list', $id = null)
1092 {
1093 $page->setTitle('Administration - MX Défaillants');
1094 $page->assign('title', 'MX Défaillant');
1095 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true);
1096 $table_editor->describe('host', 'Masque', true);
1097 $table_editor->describe('state', 'Niveau', true);
1098 $table_editor->describe('text', 'Description du problème', false);
1099 $table_editor->apply($page, $action, $id);
1100 }
1101
1102 function handler_logger_actions(&$page, $action = 'list', $id = null)
1103 {
1104 $page->setTitle('Administration - Actions');
1105 $page->assign('title', 'Gestion des actions de logger');
1106 $table_editor = new PLTableEditor('admin/logger/actions','log_actions','id');
1107 $table_editor->describe('text','intitulé',true);
1108 $table_editor->describe('description','description',true);
1109 $table_editor->apply($page, $action, $id);
1110 }
1111
1112 function handler_downtime(&$page, $action = 'list', $id = null)
1113 {
1114 $page->setTitle('Administration - Coupures');
1115 $page->assign('title', 'Gestion des coupures');
1116 $table_editor = new PLTableEditor('admin/downtime','downtimes','id');
1117 $table_editor->describe('debut','date',true);
1118 $table_editor->describe('duree','durée',false);
1119 $table_editor->describe('resume','résumé',true);
1120 $table_editor->describe('services','services affectés',true);
1121 $table_editor->describe('description','description',false);
1122 $table_editor->apply($page, $action, $id);
1123 }
1124
1125 function handler_account_types(&$page, $action = 'list', $id = null)
1126 {
1127 $page->setTitle('Administration - Types de comptes');
1128 $page->assign('title', 'Gestion des types de comptes');
1129 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true);
1130 $table_editor->describe('type', 'Catégorie', true);
1131 $table_editor->describe('perms', 'Permissions associées', true);
1132 $table_editor->apply($page, $action, $id);
1133 }
1134
1135 function handler_wiki(&$page, $action = 'list', $wikipage = null, $wikipage2 = null)
1136 {
1137 if (S::hasAuthToken()) {
1138 $page->setRssLink('Changement Récents',
1139 '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::v('token'));
1140 }
1141
1142 // update wiki perms
1143 if ($action == 'update') {
1144 S::assert_xsrf_token();
1145
1146 $perms_read = Post::v('read');
1147 $perms_edit = Post::v('edit');
1148 if ($perms_read || $perms_edit) {
1149 foreach ($_POST as $wiki_page => $val) {
1150 if ($val == 'on') {
1151 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1152 if ($wp->setPerms($perms_read ? $perms_read : $wp->readPerms(),
1153 $perms_edit ? $perms_edit : $wp->writePerms())) {
1154 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1155 } else {
1156 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1157 }
1158 }
1159 }
1160 }
1161 } else if ($action != 'list' && !empty($wikipage)) {
1162 $wp = new PlWikiPage($wikipage);
1163 S::assert_xsrf_token();
1164
1165 if ($action == 'delete') {
1166 if ($wp->delete()) {
1167 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1168 } else {
1169 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1170 }
1171 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1172 if ($changedLinks = $wp->rename($wikipage2)) {
1173 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1174 if (is_numeric($changedLinks)) {
1175 $s .= $changedLinks.' lien'.(($changedLinks>1)?'s ont été modifiés.':' a été modifié.');
1176 }
1177 $page->trigSuccess($s);
1178 } else {
1179 $page->trigError("Impossible de déplacer la page ".$wikipage);
1180 }
1181 }
1182 }
1183
1184 $perms = PlWikiPage::permOptions();
1185
1186 // list wiki pages and their perms
1187 $wiki_pages = PlWikiPage::listPages();
1188 ksort($wiki_pages);
1189 $wiki_tree = array();
1190 foreach ($wiki_pages as $file => $desc) {
1191 list($cat, $name) = explode('.', $file);
1192 if (!isset($wiki_tree[$cat])) {
1193 $wiki_tree[$cat] = array();
1194 }
1195 $wiki_tree[$cat][$name] = $desc;
1196 }
1197
1198 $page->changeTpl('admin/wiki.tpl');
1199 $page->assign('wiki_pages', $wiki_tree);
1200 $page->assign('perms_opts', $perms);
1201 }
1202
1203 function handler_ipwatch(&$page, $action = 'list', $ip = null)
1204 {
1205 $page->changeTpl('admin/ipwatcher.tpl');
1206
1207 $states = array('safe' => 'Ne pas surveiller',
1208 'unsafe' => 'Surveiller les inscriptions',
1209 'dangerous' => 'Surveiller tous les accès',
1210 'ban' => 'Bannir cette adresse');
1211 $page->assign('states', $states);
1212
1213 switch (Post::v('action')) {
1214 case 'create':
1215 if (trim(Post::v('ipN')) != '') {
1216 S::assert_xsrf_token();
1217 Xdb::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1218 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1219 ip_to_uint(trim(Post::v('ipN'))), ip_to_uint(trim(Post::v('maskN'))),
1220 Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
1221 };
1222 break;
1223
1224 case 'edit':
1225 S::assert_xsrf_token();
1226 Xdb::execute('UPDATE ip_watch
1227 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1228 WHERE ip = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'),
1229 ip_to_uint(Post::v('maskN')), ip_to_uint(Post::v('ipN')));
1230 break;
1231
1232 default:
1233 if ($action == 'delete' && !is_null($ip)) {
1234 S::assert_xsrf_token();
1235 Xdb::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1236 }
1237 }
1238 if ($action != 'create' && $action != 'edit') {
1239 $action = 'list';
1240 }
1241 $page->assign('action', $action);
1242
1243 if ($action == 'list') {
1244 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1245 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1246 IF(w.ip = s.ip, s.host, s.forward_host)),
1247 w.mask, w.detection, w.state, a.hruid
1248 FROM ip_watch AS w
1249 LEFT JOIN log_sessions AS s ON (s.ip = w.ip)
1250 LEFT JOIN log_sessions AS s2 ON (s2.forward_ip = w.ip)
1251 LEFT JOIN accounts AS a ON (a.uid = s.uid)
1252 GROUP BY w.ip, a.hruid
1253 ORDER BY w.state, w.ip, a.hruid";
1254 $it = Xdb::iterRow($sql);
1255
1256 $table = array();
1257 $props = array();
1258 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1259 $ip = uint_to_ip($ip);
1260 $mask = uint_to_ip($mask);
1261 if (count($props) == 0 || $props['ip'] != $ip) {
1262 if (count($props) > 0) {
1263 $table[] = $props;
1264 }
1265 $props = array('ip' => $ip,
1266 'mask' => $mask,
1267 'host' => $host,
1268 'detection' => $date,
1269 'state' => $state,
1270 'users' => array($hruid));
1271 } else {
1272 $props['users'][] = $hruid;
1273 }
1274 }
1275 if (count($props) > 0) {
1276 $table[] = $props;
1277 }
1278 $page->assign('table', $table);
1279 } elseif ($action == 'edit') {
1280 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1281 a1.hruid AS edit, a2.hruid AS hruid, s.host
1282 FROM ip_watch AS w
1283 LEFT JOIN accounts AS a1 ON (a1.uid = w.uid)
1284 LEFT JOIN log_sessions AS s ON (w.ip = s.ip)
1285 LEFT JOIN accounts AS a2 ON (a2.uid = s.uid)
1286 WHERE w.ip = {?}
1287 GROUP BY a2.hruid
1288 ORDER BY a2.hruid";
1289 $it = Xdb::iterRow($sql, ip_to_uint($ip));
1290
1291 $props = array();
1292 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1293 if (count($props) == 0) {
1294 $props = array('ip' => $ip,
1295 'mask' => uint_to_ip($mask),
1296 'host' => $host,
1297 'detection' => $detection,
1298 'state' => $state,
1299 'last' => $last,
1300 'description' => $description,
1301 'edit' => $edit,
1302 'users' => array($hruid));
1303 } else {
1304 $props['users'][] = $hruid;
1305 }
1306 }
1307 $page->assign('ip', $props);
1308 }
1309 }
1310
1311 function handler_icons(&$page)
1312 {
1313 $page->changeTpl('admin/icons.tpl');
1314 $dh = opendir('../htdocs/images/icons');
1315 if (!$dh) {
1316 $page->trigError('Dossier des icones introuvables.');
1317 }
1318 $icons = array();
1319 while (($file = readdir($dh)) !== false) {
1320 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1321 array_push($icons, substr($file, 0, -4));
1322 }
1323 }
1324 sort($icons);
1325 $page->assign('icons', $icons);
1326 }
1327
1328 function handler_accounts(&$page)
1329 {
1330 $page->changeTpl('admin/accounts.tpl');
1331 $page->assign('disabled', XDB::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1332 a.state = \'disabled\' AS disabled, a.comment
1333 FROM accounts AS a
1334 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1335 ORDER BY a.hruid'));
1336 $page->assign('admins', XDB::iterator('SELECT a.hruid
1337 FROM accounts AS a
1338 WHERE a.is_admin
1339 ORDER BY a.hruid'));
1340 }
1341
1342 function handler_jobs(&$page, $id = -1)
1343 {
1344 $page->changeTpl('admin/jobs.tpl');
1345
1346 if (Env::has('search')) {
1347 $res = XDB::query("SELECT e.id, e.name, e.acronym
1348 FROM profile_job_enum AS e
1349 WHERE e.name LIKE CONCAT('% ', {?}, '%') OR e.acronym LIKE CONCAT('% ', {?}, '%')",
1350 Env::t('job'), Env::t('job'));
1351
1352 if ($res->numRows() <= 20) {
1353 $page->assign('jobs', $res->fetchAllAssoc());
1354 } else {
1355 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1356 }
1357
1358 $page->assign('askedJob', Env::v('job'));
1359 return;
1360 }
1361
1362 if (Env::has('edit')) {
1363 // TODO: use address and phone classes to update profile_job_enum and profile_phones once they are done.
1364
1365 S::assert_xsrf_token();
1366 $selectedJob = Env::has('selectedJob');
1367
1368 XDB::execute("DELETE FROM profile_phones
1369 WHERE pid = {?} AND link_type = 'hq'",
1370 $id);
1371 XDB::execute("DELETE FROM profile_addresses
1372 WHERE jobid = {?} AND type = 'hq'",
1373 $id);
1374 XDB::execute('DELETE FROM profile_job_enum
1375 WHERE id = {?}',
1376 $id);
1377
1378 if (Env::has('change')) {
1379 XDB::execute('UPDATE profile_job
1380 SET jobid = {?}
1381 WHERE jobid = {?}',
1382 Env::i('newJobId'), $id);
1383
1384 $page->trigSuccess("L'entreprise a bien été remplacée.");
1385 } else {
1386 require_once 'profil.func.inc.php';
1387 require_once 'geocoding.inc.php';
1388
1389 $display_tel = format_display_number(Env::v('tel'), $error_tel);
1390 $display_fax = format_display_number(Env::v('fax'), $error_fax);
1391 $gmapsGeocoder = new GMapsGeocoder();
1392 $address = array('text' => Env::t('address'));
1393 $address = $gmapsGeocoder->getGeocodedAddress($address);
1394 Geocoder::getAreaId($address, 'administrativeArea');
1395 Geocoder::getAreaId($address, 'subAdministrativeArea');
1396 Geocoder::getAreaId($address, 'locality');
1397
1398 XDB::execute('UPDATE profile_job_enum
1399 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1400 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1401 WHERE id = {?}',
1402 Env::t('name'), Env::t('acronym'), Env::t('url'), Env::t('email'),
1403 Env::t('NAF_code'), Env::i('AX_code'), Env::i('holdingId'), $id);
1404
1405 XDB::execute("INSERT INTO profile_phones (pid, link_type, link_id, tel_id, tel_type,
1406 search_tel, display_tel, pub)
1407 VALUES ({?}, 'hq', 0, 0, 'fixed', {?}, {?}, 'public'),
1408 ({?}, 'hq', 0, 1, 'fax', {?}, {?}, 'public')",
1409 $id, format_phone_number(Env::v('tel')), $display_tel,
1410 $id, format_phone_number(Env::v('fax')), $display_fax);
1411
1412 XDB::execute("INSERT INTO profile_addresses (jobid, type, id, accuracy,
1413 text, postalText, postalCode, localityId,
1414 subAdministrativeAreaId, administrativeAreaId,
1415 countryId, latitude, longitude, updateTime,
1416 north, south, east, west)
1417 VALUES ({?}, 'hq', 0, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
1418 {?}, {?}, FROM_UNIXTIME({?}), {?}, {?}, {?}, {?})",
1419 $id, $address['accuracy'], $address['text'], $address['postalText'],
1420 $address['postalCode'], $address['localityId'],
1421 $address['subAdministrativeAreaId'], $address['administrativeAreaId'],
1422 $address['countryId'], $address['latitude'], $address['longitude'],
1423 $address['updateTime'], $address['north'], $address['south'],
1424 $address['east'], $address['west']);
1425
1426 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1427 }
1428 }
1429
1430 if (!Env::has('change') && $id != -1) {
1431 $res = XDB::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1432 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1433 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1434 FROM profile_job_enum AS e
1435 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
1436 LEFT JOIN profile_phones AS t ON (t.pid = e.id AND t.link_type = 'hq' AND t.tel_id = 0)
1437 LEFT JOIN profile_phones AS f ON (f.pid = e.id AND f.link_type = 'hq' AND f.tel_id = 1)
1438 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1439 WHERE e.id = {?}",
1440 $id);
1441
1442 if ($res->numRows() == 0) {
1443 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1444 } else {
1445 $page->assign('selectedJob', $res->fetchOneAssoc());
1446 }
1447 }
1448 }
1449 }
1450
1451 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1452 ?>