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