122492b28a3e6bcd8e61830c8bd6c147678c29cd
[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 $user->profile()->clear();
417 $user->clear(true);
418 $page->trigSuccess("L'utilisateur $name ($uid) a bien été supprimé.");
419 }
420
421 // Account Form {{{
422 $to_update = array();
423 if (Post::has('disable_weak_access')) {
424 $to_update['weak_password'] = null;
425 } else if (Post::has('update_account')) {
426 if (!$user->hasProfile()) {
427 if (Post::s('full_name') != $user->fullName()) {
428 $to_update['full_name'] = Post::s('full_name');
429 }
430 if (Post::s('display_name') != $user->displayName()) {
431 $to_update['display_name'] = Post::s('display_name');
432 }
433 if (Post::s('directory_name') != $user->directoryName()) {
434 $to_update['directory_name'] = Post::s('directory_name');
435 }
436 }
437 if (Post::s('sex') != ($user->isFemale() ? 'female' : 'male')) {
438 $to_update['sex'] = Post::s('sex');
439 if ($user->hasProfile()) {
440 XDB::execute('UPDATE profiles
441 SET sex = {?}
442 WHERE pid = {?}',
443 Post::s('sex'), $user->profile()->id());
444 }
445 }
446 if (!Post::blank('pwhash')) {
447 $to_update['password'] = Post::s('pwhash');
448 require_once 'googleapps.inc.php';
449 $account = new GoogleAppsAccount($user);
450 if ($account->active() && $account->sync_password) {
451 $account->set_password(Post::s('pwhash'));
452 }
453 }
454 if (!Post::blank('weak_password')) {
455 $to_update['weak_password'] = Post::s('weak_password');
456 }
457 if (Post::i('token_access', 0) != ($user->token_access ? 1 : 0)) {
458 $to_update['token'] = Post::i('token_access') ? rand_url_id(16) : null;
459 }
460 if (Post::i('skin') != $user->skin) {
461 $to_update['skin'] = Post::i('skin');
462 if ($to_update['skin'] == 0) {
463 $to_update['skin'] = null;
464 }
465 }
466 if (Post::s('state') != $user->state) {
467 $to_update['state'] = Post::s('state');
468 }
469 if (Post::i('is_admin', 0) != ($user->is_admin ? 1 : 0)) {
470 $to_update['is_admin'] = Post::b('is_admin');
471 }
472 if (Post::s('type') != $user->type) {
473 $to_update['type'] = Post::s('type');
474 }
475 if (Post::i('watch', 0) != ($user->watch ? 1 : 0)) {
476 $to_update['flags'] = new PlFlagset();
477 $to_update['flags']->addFlag('watch', Post::i('watch'));
478 }
479 if (Post::t('comment') != $user->comment) {
480 $to_update['comment'] = Post::blank('comment') ? null : Post::t('comment');
481 }
482 }
483 if (!empty($to_update)) {
484 $res = XDB::query('SELECT *
485 FROM accounts
486 WHERE uid = {?}', $user->id());
487 $oldValues = $res->fetchAllAssoc();
488 $oldValues = $oldValues[0];
489
490 $set = array();
491 $diff = array();
492 foreach ($to_update as $k => $value) {
493 $value = XDB::format('{?}', $value);
494 $set[] = $k . ' = ' . $value;
495 $diff[$k] = array($oldValues[$k], trim($value, "'"));
496 unset($oldValues[$k]);
497 }
498 XDB::execute('UPDATE accounts
499 SET ' . implode(', ', $set) . '
500 WHERE uid = ' . XDB::format('{?}', $user->id()));
501 $page->trigSuccess('Données du compte mise à jour avec succès');
502 $user = User::getWithUID($user->id());
503
504 /* Formats the $diff and send it to the site administrators. The rules are the folowing:
505 * -formats: password, token, weak_password
506 */
507 foreach (array('password', 'token', 'weak_password') as $key) {
508 if (isset($diff[$key])) {
509 $diff[$key] = array('old value', 'new value');
510 } else {
511 $oldValues[$key] = 'old value';
512 }
513 }
514
515 $mail = new PlMailer('admin/useredit.mail.tpl');
516 $mail->assign('admin', S::user()->hruid);
517 $mail->assign('hruid', $user->hruid);
518 $mail->assign('diff', $diff);
519 $mail->assign('oldValues', $oldValues);
520 $mail->send();
521 }
522 // }}}
523
524 // Profile form {{{
525 if (Post::has('add_profile') || Post::has('del_profile') || Post::has('owner')) {
526 if (Post::i('del_profile', 0) != 0) {
527 XDB::execute('DELETE FROM account_profiles
528 WHERE uid = {?} AND pid = {?}',
529 $user->id(), Post::i('del_profile'));
530 } else if (!Post::blank('new_profile')) {
531 $profile = Profile::get(Post::t('new_profile'));
532 if (!$profile) {
533 $page->trigError('Le profil ' . Post::t('new_profile') . ' n\'existe pas');
534 } else {
535 XDB::execute('INSERT IGNORE INTO account_profiles (uid, pid)
536 VALUES ({?}, {?})',
537 $user->id(), $profile->id());
538 }
539 }
540 XDB::execute('UPDATE account_profiles
541 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
542 WHERE uid = {?}',
543 Post::i('owner'), $user->id());
544 }
545 // }}}
546
547 // Email forwards form {{{
548 require_once("emails.inc.php");
549 $redirect = ($registered ? new Redirect($user) : null);
550 if (Post::has('add_fwd')) {
551 $email = Post::t('email');
552 if (!isvalid_email_redirection($email)) {
553 $page->trigError("Email non valide: $email");
554 } else {
555 $redirect->add_email($email);
556 $page->trigSuccess("Ajout de $email effectué");
557 }
558 } else if (!Post::blank('del_fwd')) {
559 $redirect->delete_email(Post::t('del_fwd'));
560 } else if (!Post::blank('activate_fwd')) {
561 $redirect->modify_one_email(Post::t('activate_fwd', true));
562 } else if (!Post::blank('deactivate_fwd')) {
563 $redirect->modify_one_email(Post::t('deactivate_fwd', false));
564 } else if (Post::has('disable_fwd')) {
565 $redirect->disable();
566 } else if (Post::has('enable_fwd')) {
567 $redirect->enable();
568 } else if (!Post::blank('clean_fwd')) {
569 $redirect->clean_errors(Post::t('clean_fwd'));
570 }
571 // }}}
572
573 // Email alias form {{{
574 if (Post::has('add_alias')) {
575 // Splits new alias in user and fqdn.
576 $alias = Env::t('email');
577 if (strpos($alias, '@') !== false) {
578 list($alias, $domain) = explode('@', $alias);
579 } else {
580 $domain = $globals->mail->domain;
581 }
582
583 // Checks for alias' user validity.
584 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
585 $page->trigError("'$alias' n'est pas un alias valide");
586 }
587
588 // Eventually adds the alias to the right domain.
589 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
590 $req = new AliasReq($user, $alias, 'Admin request', false);
591 if ($req->commit()) {
592 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué");
593 } else {
594 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué");
595 }
596 } elseif ($domain == $globals->mail->domain || $domain == $globals->mail->domain2) {
597 $res = XDB::execute("INSERT INTO aliases (uid, alias, type)
598 VALUES ({?}, {?}, 'alias')",
599 $user->id(), $alias);
600 $page->trigSuccess("Nouvel alias '$alias' ajouté");
601 } else {
602 $page->trigError("Le domaine '$domain' n'est pas valide");
603 }
604 } else if (!Post::blank('del_alias')) {
605 XDB::execute("DELETE FROM aliases
606 WHERE uid = {?} AND alias = {?} AND
607 type NOT IN ('a_vie', 'homonyme')",
608 $user->id(), $val);
609 XDB::execute("UPDATE emails
610 SET rewrite = ''
611 WHERE uid = {?} AND rewrite LIKE CONCAT({?}, '@%')",
612 $user->id(), $val);
613 fix_bestalias($user);
614 $page->trigSuccess("L'alias '$val' a été supprimé");
615 } else if (!Post::blank('best')) {
616 XDB::execute("UPDATE aliases
617 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
618 WHERE uid = {?}", $user->id());
619 XDB::execute("UPDATE aliases
620 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
621 WHERE uid = {?} AND alias = {?}", $user->id(), $val);
622 // As having a non-null bestalias value is critical in
623 // plat/al's code, we do an a posteriori check on the
624 // validity of the bestalias.
625 fix_bestalias($user);
626 }
627 // }}}
628
629 // OpenId form {{{
630 if (Post::has('del_openid')) {
631 XDB::execute('DELETE FROM account_auth_openid
632 WHERE id = {?}', Post::i('del_openid'));
633 }
634 // }}}
635
636 // Forum form {{{
637 if (Post::has('b_edit')) {
638 XDB::execute("DELETE FROM forum_innd
639 WHERE uid = {?}", $user->id());
640 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
641 XDB::execute("INSERT INTO forum_innd
642 SET ipmin = '0', ipmax = '4294967295',
643 write_perm = {?}, read_perm = {?},
644 comment = {?}, priority = '200', uid = {?}",
645 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
646 }
647 }
648 // }}}
649
650
651 $page->addJsLink('jquery.ui.core.js');
652 $page->addJsLink('jquery.ui.tabs.js');
653 $page->addJsLink('password.js');
654
655 // Displays last login and last host information.
656 $res = XDB::query("SELECT start, host
657 FROM log_sessions
658 WHERE uid = {?} AND suid = 0
659 ORDER BY start DESC
660 LIMIT 1", $user->id());
661 list($lastlogin,$host) = $res->fetchOneRow();
662 $page->assign('lastlogin', $lastlogin);
663 $page->assign('host', $host);
664
665 // Display active aliases.
666 $page->assign('virtuals', $user->emailAliases());
667 $page->assign('aliases', XDB::iterator("SELECT alias, type='a_vie' AS for_life,
668 FIND_IN_SET('bestalias',flags) AS best, expire
669 FROM aliases
670 WHERE uid = {?} AND type != 'homonyme'
671 ORDER BY type != 'a_vie'", $user->id()));
672 $page->assign('account_types', XDB::iterator('SELECT * FROM account_types ORDER BY type'));
673 $page->assign('skins', XDB::iterator('SELECT id, name FROM skins ORDER BY name'));
674 $page->assign('profiles', XDB::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
675 FROM account_profiles AS ap
676 INNER JOIN profiles AS p ON (ap.pid = p.pid)
677 WHERE ap.uid = {?}', $user->id()));
678 $page->assign('openid', XDB::iterator('SELECT id, url
679 FROM account_auth_openid
680 WHERE uid = {?}', $user->id()));
681
682 // Displays email redirection and the general profile.
683 if ($registered && $redirect) {
684 $page->assign('emails', $redirect->emails);
685 }
686
687 $page->assign('user', $user);
688 $page->assign('hasProfile', $user->hasProfile());
689
690 // Displays forum bans.
691 $res = XDB::query("SELECT write_perm, read_perm, comment
692 FROM forum_innd
693 WHERE uid = {?}", $user->id());
694 $bans = $res->fetchOneAssoc();
695 $page->assign('bans', $bans);
696 }
697
698 private static function getHrid($firstname, $lastname, $promo)
699 {
700 if ($firstname != null && $lastname != null && $promo != null) {
701 return User::makeHrid($firstname, $lastname, $promo);
702 }
703 return null;
704 }
705
706 private static function formatNewUser(&$page, $infosLine, $separator, $promo, $size)
707 {
708 $infos = explode($separator, $infosLine);
709 if (sizeof($infos) > $size || sizeof($infos) < 2) {
710 $page->trigError("La ligne $infosLine n'a pas été ajoutée.");
711 return false;
712 }
713
714 array_map('trim', $infos);
715 $hrid = self::getHrid($infos[1], $infos[0], $promo);
716 $res1 = XDB::query('SELECT COUNT(*)
717 FROM accounts
718 WHERE hruid = {?}', $hrid);
719 $res2 = XDB::query('SELECT COUNT(*)
720 FROM profiles
721 WHERE hrpid = {?}', $hrid);
722 if (is_null($hrid) || $res1->fetchOneCell() > 0 || $res2->fetchOneCell() > 0) {
723 $page->trigError("La ligne $infosLine n'a pas été ajoutée.");
724 return false;
725 }
726 $infos['hrid'] = $hrid;
727 return $infos;
728 }
729
730 private static function formatSex(&$page, $sex, $line)
731 {
732 switch ($sex) {
733 case 'F':
734 return PlUser::GENDER_FEMALE;
735 case 'M':
736 return PlUser::GENDER_MALE;
737 default:
738 $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
739 return null;
740 }
741 }
742
743 private static function formatBirthDate($birthDate)
744 {
745 return date("Y-m-d", strtotime($birthDate));
746 }
747
748 function handler_add_accounts(&$page, $action = null, $promo = null)
749 {
750 $page->changeTpl('admin/add_accounts.tpl');
751
752 if (Env::has('add_type') && Env::has('people')) {
753 $lines = explode("\n", Env::t('people'));
754 $separator = Env::t('separator');
755 $promotion = Env::i('promotion');
756 $nameTypes = DirEnum::getOptions(DirEnum::NAMETYPES);
757 $nameTypes = array_flip($nameTypes);
758
759 if (Env::t('add_type') == 'promo') {
760 $type = 'x';
761 $eduSchools = DirEnum::getOptions(DirEnum::EDUSCHOOLS);
762 $eduSchools = array_flip($eduSchools);
763 $eduDegrees = DirEnum::getOptions(DirEnum::EDUDEGREES);
764 $eduDegrees = array_flip($eduDegrees);
765 switch (Env::t('edu_type')) {
766 case 'X':
767 $degreeid = $eduDegrees[Profile::DEGREE_X];
768 $entry_year = $promotion;
769 $grad_year = $promotion + 3;
770 $promo = 'X' . $promotion;
771 break;
772 case 'M':
773 $degreeid = $eduDegrees[Profile::DEGREE_M];
774 $grad_year = $promotion;
775 $entry_year = $promotion - 2;
776 $promo = 'M' . $promotion;
777 break;
778 case 'D':
779 $degreeid = $eduDegrees[Profile::DEGREE_D];
780 $grad_year = $promotion;
781 $entry_year = $promotion - 3;
782 $promo = 'D' . $promotion;
783 break;
784 default:
785 $page->killError("La formation n'est pas reconnue:" . Env::t('edu_type') . '.');
786 }
787
788 foreach ($lines as $line) {
789 if ($infos = self::formatNewUser($page, $line, $separator, $promotion, 6)) {
790 $sex = self::formatSex($page, $infos[3], $line);
791 if (!is_null($sex)) {
792 $fullName = $infos[1] . ' ' . $infos[0];
793 $directoryName = $infos[0] . ' ' . $infos[1];
794 $birthDate = self::formatBirthDate($infos[2]);
795 $xorgId = Profile::getXorgId($infos[4]);
796 if (is_null($xorgId)) {
797 $page->trigError("La ligne $line n'a pas été ajoutée car le matricule École est mal renseigné.");
798 continue;
799 }
800
801 XDB::execute('INSERT INTO profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex)
802 VALUES ({?}, {?}, {?}, {?}, {?})',
803 $infos['hrid'], $xorgId, $infos[5], $birthDate, $sex);
804 $pid = XDB::insertId();
805 XDB::execute('INSERT INTO profile_name (pid, name, typeid)
806 VALUES ({?}, {?}, {?})',
807 $pid, $infos[0], $nameTypes['name_ini']);
808 XDB::execute('INSERT INTO profile_name (pid, name, typeid)
809 VALUES ({?}, {?}, {?})',
810 $pid, $infos[1], $nameTypes['firstname_ini']);
811 XDB::execute('INSERT INTO profile_display (pid, yourself, public_name, private_name,
812 directory_name, short_name, sort_name, promo)
813 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
814 $pid, $infos[1], $fullName, $fullName, $directoryName, $fullName, $directoryName, $promo);
815 XDB::execute('INSERT INTO profile_education (pid, eduid, degreeid, entry_year, grad_year, flags)
816 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
817 $pid, $eduSchools[Profile::EDU_X], $degreeid, $entry_year, $grad_year, 'primary');
818 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, full_name, directory_name, display_name, sex)
819 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
820 $infos['hrid'], $type, 0, 'active', $fullName, $directoryName, $infos[1], $sex);
821 $uid = XDB::insertId();
822 XDB::execute('INSERT INTO account_profiles (uid, pid, perms)
823 VALUES ({?}, {?}, {?})',
824 $uid, $pid, 'owner');
825 }
826 }
827 }
828 } else if (Env::t('add_type') == 'account') {
829 $type = Env::t('type');
830 $newAccounts = array();
831 foreach ($lines as $line) {
832 if ($infos = self::formatNewUser($page, $line, $separator, $type, 4)) {
833 $sex = self::formatSex($page, $infos[3], $line);
834 if (!is_null($sex)) {
835 $fullName = $infos[1] . ' ' . $infos[0];
836 $directoryName = $infos[0] . ' ' . $infos[1];
837 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, email, full_name, directory_name, display_name, sex)
838 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
839 $infos['hrid'], $type, 0, 'active', $infos[2], $fullName, $directoryName, $infos[1], $sex);
840 $newAccounts[$infos['hrid']] = $infos[1] . ' ' . $infos[0];
841 }
842 }
843 }
844 if (!empty($newAccounts)) {
845 $page->assign('newAccounts', $newAccounts);
846 }
847 } else if (Env::t('add_type') == 'ax_id') {
848 $type = 'x';
849 foreach ($lines as $line) {
850 if ($infos = self::formatNewUser($page, $line, $separator, $promotion, 3)) {
851 XDB::execute('UPDATE profiles
852 SET ax_id = {?}
853 WHERE hrpid = {?}',
854 $infos[2], $infos['hrid']);
855 }
856 }
857 }
858
859 $errors = $page->nb_errs();
860 if ($errors == 0) {
861 $page->trigSuccess("L'opération a été effectuée avec succès.");
862 } else {
863 $page->trigSuccess('L\'opération a été effectuée avec succès, sauf pour '
864 . (($errors == 1) ? 'l\'erreur signalée' : "les $errors erreurs signalées") . ' ci-dessus.');
865 }
866 } else if (Env::has('add_type')) {
867 $res = XDB::query('SELECT type
868 FROM account_types');
869 $page->assign('account_types', $res->fetchColumn());
870 $page->assign('add_type', Env::s('add_type'));
871 }
872 }
873
874 function handler_homonyms(&$page, $op = 'list', $target = null)
875 {
876 $page->changeTpl('admin/homonymes.tpl');
877 $page->setTitle('Administration - Homonymes');
878 $this->load("homonyms.inc.php");
879
880 if ($target) {
881 $user = User::getSilent($target);
882 if (!$user || !($loginbis = select_if_homonyme($user))) {
883 $target = 0;
884 } else {
885 $page->assign('user', $user);
886 $page->assign('loginbis',$loginbis);
887 }
888 }
889
890 $page->assign('op', $op);
891 $page->assign('target', $target);
892
893 // on a un $target valide, on prepare les mails
894 if ($target) {
895 // on examine l'op a effectuer
896 switch ($op) {
897 case 'mail':
898 S::assert_xsrf_token();
899
900 send_warning_homonyme($user, $loginbis);
901 switch_bestalias($user, $loginbis);
902 $op = 'list';
903 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
904 break;
905
906 case 'correct':
907 S::assert_xsrf_token();
908
909 switch_bestalias($user, $loginbis);
910 XDB::execute("UPDATE aliases
911 SET type = 'homonyme', expire=NOW()
912 WHERE alias = {?}", $loginbis);
913 XDB::execute("REPLACE INTO homonyms (homonyme_id, uid)
914 VALUES ({?}, {?})", $target, $target);
915 send_robot_homonyme($user, $loginbis);
916 $op = 'list';
917 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
918 break;
919 }
920 }
921
922 if ($op == 'list') {
923 $res = XDB::iterator(
924 "SELECT a.alias AS homonyme, s.alias AS forlife,
925 IF(h.homonyme_id = s.uid, a.expire, NULL) AS expire,
926 IF(h.homonyme_id = s.uid, a.type, NULL) AS type, ac.uid
927 FROM aliases AS a
928 LEFT JOIN homonyms AS h ON (h.homonyme_id = a.uid)
929 INNER JOIN aliases AS s ON (s.uid = h.uid AND s.type = 'a_vie')
930 INNER JOIN accounts AS ac ON (ac.uid = a.uid)
931 WHERE a.type = 'homonyme' OR a.expire != ''
932 ORDER BY a.alias, forlife");
933 $hnymes = Array();
934 while ($tab = $res->next()) {
935 $hnymes[$tab['homonyme']][] = $tab;
936 }
937 $page->assign_by_ref('hnymes', $hnymes);
938 }
939 }
940
941 function handler_deaths(&$page, $promo = 0, $validate = false)
942 {
943 $page->changeTpl('admin/deces_promo.tpl');
944 $page->setTitle('Administration - Deces');
945
946 if (!$promo) {
947 $promo = Env::t('promo', 'X1923');
948 }
949 $page->assign('promo', $promo);
950 if (!$promo) {
951 return;
952 }
953
954 if ($validate) {
955 S::assert_xsrf_token();
956
957 $res = XDB::iterRow('SELECT p.pid, pd.directory_name, p.deathdate
958 FROM profiles AS p
959 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
960 WHERE pd.promo = {?}', $promo);
961 while (list($pid, $name, $death) = $res->next()) {
962 $val = Env::v('death_' . $pid);
963 if ($val == $death) {
964 continue;
965 }
966
967 if (empty($val)) {
968 $val = null;
969 }
970 XDB::execute('UPDATE profiles
971 SET deathdate = {?}, deathdate_rec = NOW()
972 WHERE pid = {?}', $val, $pid);
973
974 $page->trigSuccess('Édition du décès de ' . $name . ' (' . ($val ? $val : 'ressuscité') . ').');
975 if ($val && ($death == '0000-00-00' || empty($death))) {
976 $profile = Profile::get($pid);
977 $profile->clear();
978 $profile->owner()->clear(false);
979 }
980 }
981 }
982
983 $res = XDB::iterator('SELECT p.pid, pd.directory_name, p.deathdate
984 FROM profiles AS p
985 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
986 WHERE pd.promo = {?}
987 ORDER BY pd.sort_name', $promo);
988 $page->assign('profileList', $res);
989 }
990
991 function handler_dead_but_active(&$page)
992 {
993 $page->changeTpl('admin/dead_but_active.tpl');
994 $page->setTitle('Administration - Décédés');
995
996 $res = XDB::iterator(
997 "SELECT a.hruid, pd.promo, p.ax_id, pd.directory_name, p.deathdate, DATE(MAX(s.start)) AS last
998 FROM accounts AS a
999 INNER JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET('owner', ap.perms))
1000 INNER JOIN profiles AS p ON (p.pid = ap.pid)
1001 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
1002 LEFT JOIN log_sessions AS s ON (s.uid = a.uid AND suid = 0)
1003 WHERE a.state = 'active' AND p.deathdate IS NOT NULL
1004 GROUP BY a.uid
1005 ORDER BY pd.promo, pd.sort_name");
1006 $page->assign('dead', $res);
1007 }
1008
1009 function handler_validate(&$page, $action = 'list', $id = null)
1010 {
1011 $page->changeTpl('admin/validation.tpl');
1012 $page->setTitle('Administration - Valider une demande');
1013 $page->addCssLink('nl.css');
1014 $page->addJsLink('ajax.js');
1015 require_once 'validations.inc.php';
1016
1017 if ($action == 'edit' && !is_null($id)) {
1018 $page->assign('preview_id', $id);
1019 } else {
1020 $page->assign('preview_id', null);
1021 }
1022
1023 if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
1024 S::assert_xsrf_token();
1025
1026 $req = Validate::get_typed_request(Env::v('uid'), Env::v('type'), Env::v('stamp'));
1027 if ($req) {
1028 $req->handle_formu();
1029 } else {
1030 $page->trigWarning('La validation a déjà été effectuée.');
1031 }
1032 }
1033
1034 $r = XDB::iterator('SHOW COLUMNS FROM requests_answers');
1035 while (($a = $r->next()) && $a['Field'] != 'category');
1036 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
1037
1038 $hidden = array();
1039 $res = XDB::query('SELECT hidden_requests
1040 FROM requests_hidden
1041 WHERE uid = {?}', S::v('uid'));
1042 $hide_requests = $res->fetchOneCell();
1043 if (Post::has('hide')) {
1044 $hide = array();
1045 foreach ($categories as $cat)
1046 if (!Post::v($cat)) {
1047 $hidden[$cat] = 1;
1048 $hide[] = $cat;
1049 }
1050 $hide_requests = join(',', $hide);
1051 XDB::query('REPLACE INTO requests_hidden (uid, hidden_requests)
1052 VALUES ({?}, {?})',
1053 S::v('uid'), $hide_requests);
1054 } elseif ($hide_requests) {
1055 foreach (explode(',', $hide_requests) as $hide_type)
1056 $hidden[$hide_type] = true;
1057 }
1058 $page->assign('hide_requests', $hidden);
1059
1060 // Update the count of item to validate here... useful in development configuration
1061 // where several copies of the site use the same DB, but not the same "dynamic configuration"
1062 global $globals;
1063 $globals->updateNbValid();
1064 $page->assign('vit', new ValidateIterator());
1065 }
1066
1067 function handler_validate_answers(&$page, $action = 'list', $id = null)
1068 {
1069 $page->setTitle('Administration - Réponses automatiques de validation');
1070 $page->assign('title', 'Gestion des réponses automatiques');
1071 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
1072 $table_editor->describe('category','catégorie',true);
1073 $table_editor->describe('title','titre',true);
1074 $table_editor->describe('answer','texte',false);
1075 $table_editor->apply($page, $action, $id);
1076 }
1077
1078 function handler_skins(&$page, $action = 'list', $id = null)
1079 {
1080 $page->setTitle('Administration - Skins');
1081 $page->assign('title', 'Gestion des skins');
1082 $table_editor = new PLTableEditor('admin/skins','skins','id');
1083 $table_editor->describe('name','nom',true);
1084 $table_editor->describe('skin_tpl','nom du template',true);
1085 $table_editor->describe('auteur','auteur',false);
1086 $table_editor->describe('comment','commentaire',true);
1087 $table_editor->describe('date','date',false);
1088 $table_editor->describe('ext','extension du screenshot',false);
1089 $table_editor->apply($page, $action, $id);
1090 }
1091
1092 function handler_postfix_blacklist(&$page, $action = 'list', $id = null)
1093 {
1094 $page->setTitle('Administration - Postfix : Blacklist');
1095 $page->assign('title', 'Blacklist de postfix');
1096 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true);
1097 $table_editor->describe('reject_text','Texte de rejet',true);
1098 $table_editor->describe('email','email',true);
1099 $table_editor->apply($page, $action, $id);
1100 }
1101
1102 function handler_postfix_whitelist(&$page, $action = 'list', $id = null)
1103 {
1104 $page->setTitle('Administration - Postfix : Whitelist');
1105 $page->assign('title', 'Whitelist de postfix');
1106 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true);
1107 $table_editor->describe('email','email',true);
1108 $table_editor->apply($page, $action, $id);
1109 }
1110
1111 function handler_mx_broken(&$page, $action = 'list', $id = null)
1112 {
1113 $page->setTitle('Administration - MX Défaillants');
1114 $page->assign('title', 'MX Défaillant');
1115 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true);
1116 $table_editor->describe('host', 'Masque', true);
1117 $table_editor->describe('state', 'Niveau', true);
1118 $table_editor->describe('text', 'Description du problème', false);
1119 $table_editor->apply($page, $action, $id);
1120 }
1121
1122 function handler_logger_actions(&$page, $action = 'list', $id = null)
1123 {
1124 $page->setTitle('Administration - Actions');
1125 $page->assign('title', 'Gestion des actions de logger');
1126 $table_editor = new PLTableEditor('admin/logger/actions','log_actions','id');
1127 $table_editor->describe('text','intitulé',true);
1128 $table_editor->describe('description','description',true);
1129 $table_editor->apply($page, $action, $id);
1130 }
1131
1132 function handler_downtime(&$page, $action = 'list', $id = null)
1133 {
1134 $page->setTitle('Administration - Coupures');
1135 $page->assign('title', 'Gestion des coupures');
1136 $table_editor = new PLTableEditor('admin/downtime','downtimes','id');
1137 $table_editor->describe('debut','date',true);
1138 $table_editor->describe('duree','durée',false);
1139 $table_editor->describe('resume','résumé',true);
1140 $table_editor->describe('services','services affectés',true);
1141 $table_editor->describe('description','description',false);
1142 $table_editor->apply($page, $action, $id);
1143 }
1144
1145 function handler_accounts(PlPage $page)
1146 {
1147 $page->changeTpl('admin/accounts.tpl');
1148 $page->setTitle('Administration - Comptes');
1149 $page->addJsLink('password.js');
1150
1151 if (Post::has('create_account')) {
1152 S::assert_xsrf_token();
1153 $firstname = Post::t('firstname');
1154 $lastname = strtoupper(Post::t('lastname'));
1155 $sex = Post::b('sex') ? User::GENDER_FEMALE : User::GENDER_FEMALE;
1156 $email = Post::t('email');
1157 $login = PlUser::makeHrid($firstname, $lastname, 'ax');
1158 if (!isvalid_email($email)) {
1159 $page->trigError("Invalid email address: $email");
1160 } else if (strlen(Post::s('pwhash')) != 40) {
1161 $page->trigError("Invalid password hash");
1162 } else {
1163 $full_name = $firstname . ' ' . $lastname;
1164 $directory_name = $lastname . ' ' . $firstname;
1165 XDB::execute("INSERT INTO accounts (hruid, type, state, password,
1166 registration_date, email, full_name,
1167 display_name, sex, directory_name)
1168 VALUES ({?}, 'ax', 'active', {?}, NOW(), {?}, {?}, {?}, {?}, {?})",
1169 $login, Post::s('pwhash'), $email, $full_name, $full_name, $sex,
1170 $directory_name);
1171 }
1172 }
1173
1174 $uf = new UserFilter(new UFC_AccountType('ax'));
1175 $page->assign('users', $uf->iterUsers(new PlLimit(10)));
1176
1177 }
1178
1179 function handler_account_types(&$page, $action = 'list', $id = null)
1180 {
1181 $page->setTitle('Administration - Types de comptes');
1182 $page->assign('title', 'Gestion des types de comptes');
1183 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true);
1184 $table_editor->describe('type', 'Catégorie', true);
1185 $table_editor->describe('perms', 'Permissions associées', true);
1186 $table_editor->apply($page, $action, $id);
1187 }
1188
1189 function handler_wiki(&$page, $action = 'list', $wikipage = null, $wikipage2 = null)
1190 {
1191 if (S::hasAuthToken()) {
1192 $page->setRssLink('Changement Récents',
1193 '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::user()->token);
1194 }
1195
1196 // update wiki perms
1197 if ($action == 'update') {
1198 S::assert_xsrf_token();
1199
1200 $perms_read = Post::v('read');
1201 $perms_edit = Post::v('edit');
1202 if ($perms_read || $perms_edit) {
1203 foreach ($_POST as $wiki_page => $val) {
1204 if ($val == 'on') {
1205 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1206 if ($wp->setPerms($perms_read ? $perms_read : $wp->readPerms(),
1207 $perms_edit ? $perms_edit : $wp->writePerms())) {
1208 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1209 } else {
1210 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1211 }
1212 }
1213 }
1214 }
1215 } else if ($action != 'list' && !empty($wikipage)) {
1216 $wp = new PlWikiPage($wikipage);
1217 S::assert_xsrf_token();
1218
1219 if ($action == 'delete') {
1220 if ($wp->delete()) {
1221 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1222 } else {
1223 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1224 }
1225 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1226 if ($changedLinks = $wp->rename($wikipage2)) {
1227 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1228 if (is_numeric($changedLinks)) {
1229 $s .= $changedLinks.' lien'.(($changedLinks>1)?'s ont été modifiés.':' a été modifié.');
1230 }
1231 $page->trigSuccess($s);
1232 } else {
1233 $page->trigError("Impossible de déplacer la page ".$wikipage);
1234 }
1235 }
1236 }
1237
1238 $perms = PlWikiPage::permOptions();
1239
1240 // list wiki pages and their perms
1241 $wiki_pages = PlWikiPage::listPages();
1242 ksort($wiki_pages);
1243 $wiki_tree = array();
1244 foreach ($wiki_pages as $file => $desc) {
1245 list($cat, $name) = explode('.', $file);
1246 if (!isset($wiki_tree[$cat])) {
1247 $wiki_tree[$cat] = array();
1248 }
1249 $wiki_tree[$cat][$name] = $desc;
1250 }
1251
1252 $page->changeTpl('admin/wiki.tpl');
1253 $page->assign('wiki_pages', $wiki_tree);
1254 $page->assign('perms_opts', $perms);
1255 }
1256
1257 function handler_ipwatch(&$page, $action = 'list', $ip = null)
1258 {
1259 $page->changeTpl('admin/ipwatcher.tpl');
1260
1261 $states = array('safe' => 'Ne pas surveiller',
1262 'unsafe' => 'Surveiller les inscriptions',
1263 'dangerous' => 'Surveiller tous les accès',
1264 'ban' => 'Bannir cette adresse');
1265 $page->assign('states', $states);
1266
1267 switch (Post::v('action')) {
1268 case 'create':
1269 if (trim(Post::v('ipN')) != '') {
1270 S::assert_xsrf_token();
1271 Xdb::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1272 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1273 ip_to_uint(trim(Post::v('ipN'))), ip_to_uint(trim(Post::v('maskN'))),
1274 Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
1275 };
1276 break;
1277
1278 case 'edit':
1279 S::assert_xsrf_token();
1280 Xdb::execute('UPDATE ip_watch
1281 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1282 WHERE ip = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'),
1283 ip_to_uint(Post::v('maskN')), ip_to_uint(Post::v('ipN')));
1284 break;
1285
1286 default:
1287 if ($action == 'delete' && !is_null($ip)) {
1288 S::assert_xsrf_token();
1289 Xdb::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1290 }
1291 }
1292 if ($action != 'create' && $action != 'edit') {
1293 $action = 'list';
1294 }
1295 $page->assign('action', $action);
1296
1297 if ($action == 'list') {
1298 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1299 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1300 IF(w.ip = s.ip, s.host, s.forward_host)),
1301 w.mask, w.detection, w.state, a.hruid
1302 FROM ip_watch AS w
1303 LEFT JOIN log_sessions AS s ON (s.ip = w.ip)
1304 LEFT JOIN log_sessions AS s2 ON (s2.forward_ip = w.ip)
1305 LEFT JOIN accounts AS a ON (a.uid = s.uid)
1306 GROUP BY w.ip, a.hruid
1307 ORDER BY w.state, w.ip, a.hruid";
1308 $it = Xdb::iterRow($sql);
1309
1310 $table = array();
1311 $props = array();
1312 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1313 $ip = uint_to_ip($ip);
1314 $mask = uint_to_ip($mask);
1315 if (count($props) == 0 || $props['ip'] != $ip) {
1316 if (count($props) > 0) {
1317 $table[] = $props;
1318 }
1319 $props = array('ip' => $ip,
1320 'mask' => $mask,
1321 'host' => $host,
1322 'detection' => $date,
1323 'state' => $state,
1324 'users' => array($hruid));
1325 } else {
1326 $props['users'][] = $hruid;
1327 }
1328 }
1329 if (count($props) > 0) {
1330 $table[] = $props;
1331 }
1332 $page->assign('table', $table);
1333 } elseif ($action == 'edit') {
1334 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1335 a1.hruid AS edit, a2.hruid AS hruid, s.host
1336 FROM ip_watch AS w
1337 LEFT JOIN accounts AS a1 ON (a1.uid = w.uid)
1338 LEFT JOIN log_sessions AS s ON (w.ip = s.ip)
1339 LEFT JOIN accounts AS a2 ON (a2.uid = s.uid)
1340 WHERE w.ip = {?}
1341 GROUP BY a2.hruid
1342 ORDER BY a2.hruid";
1343 $it = Xdb::iterRow($sql, ip_to_uint($ip));
1344
1345 $props = array();
1346 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1347 if (count($props) == 0) {
1348 $props = array('ip' => $ip,
1349 'mask' => uint_to_ip($mask),
1350 'host' => $host,
1351 'detection' => $detection,
1352 'state' => $state,
1353 'last' => $last,
1354 'description' => $description,
1355 'edit' => $edit,
1356 'users' => array($hruid));
1357 } else {
1358 $props['users'][] = $hruid;
1359 }
1360 }
1361 $page->assign('ip', $props);
1362 }
1363 }
1364
1365 function handler_icons(&$page)
1366 {
1367 $page->changeTpl('admin/icons.tpl');
1368 $dh = opendir('../htdocs/images/icons');
1369 if (!$dh) {
1370 $page->trigError('Dossier des icones introuvables.');
1371 }
1372 $icons = array();
1373 while (($file = readdir($dh)) !== false) {
1374 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1375 array_push($icons, substr($file, 0, -4));
1376 }
1377 }
1378 sort($icons);
1379 $page->assign('icons', $icons);
1380 }
1381
1382 function handler_account_watch(&$page)
1383 {
1384 $page->changeTpl('admin/accounts.tpl');
1385 $page->assign('disabled', XDB::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1386 a.state = \'disabled\' AS disabled, a.comment
1387 FROM accounts AS a
1388 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1389 ORDER BY a.hruid'));
1390 $page->assign('admins', XDB::iterator('SELECT a.hruid
1391 FROM accounts AS a
1392 WHERE a.is_admin
1393 ORDER BY a.hruid'));
1394 }
1395
1396 function handler_jobs(&$page, $id = -1)
1397 {
1398 $page->changeTpl('admin/jobs.tpl');
1399
1400 if (Env::has('search')) {
1401 $res = XDB::query("SELECT e.id, e.name, e.acronym
1402 FROM profile_job_enum AS e
1403 WHERE e.name LIKE CONCAT('% ', {?}, '%') OR e.acronym LIKE CONCAT('% ', {?}, '%')",
1404 Env::t('job'), Env::t('job'));
1405
1406 if ($res->numRows() <= 20) {
1407 $page->assign('jobs', $res->fetchAllAssoc());
1408 } else {
1409 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1410 }
1411
1412 $page->assign('askedJob', Env::v('job'));
1413 return;
1414 }
1415
1416 if (Env::has('edit')) {
1417 // TODO: use address class to update profile_job_enum once it is done.
1418
1419 S::assert_xsrf_token();
1420 $selectedJob = Env::has('selectedJob');
1421
1422 Phone::deletePhones(0, Phone::LINK_COMPANY, $id);
1423 XDB::execute("DELETE FROM profile_addresses
1424 WHERE jobid = {?} AND type = 'hq'",
1425 $id);
1426
1427 if (Env::has('change')) {
1428 XDB::execute('UPDATE profile_job
1429 SET jobid = {?}
1430 WHERE jobid = {?}',
1431 Env::i('newJobId'), $id);
1432 XDB::execute('DELETE FROM profile_job_enum
1433 WHERE id = {?}',
1434 $id);
1435
1436 $page->trigSuccess("L'entreprise a bien été remplacée.");
1437 } else {
1438 require_once 'geocoding.inc.php';
1439
1440 $gmapsGeocoder = new GMapsGeocoder();
1441 $address = array('text' => Env::t('address'));
1442 $address = $gmapsGeocoder->getGeocodedAddress($address);
1443 Geocoder::getAreaId($address, 'administrativeArea');
1444 Geocoder::getAreaId($address, 'subAdministrativeArea');
1445 Geocoder::getAreaId($address, 'locality');
1446
1447 XDB::execute('UPDATE profile_job_enum
1448 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1449 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1450 WHERE id = {?}',
1451 Env::t('name'), Env::t('acronym'), Env::t('url'), Env::t('email'),
1452 Env::t('NAF_code'), Env::i('AX_code'), Env::i('holdingId'), $id);
1453
1454 $phone = new Phone(array('display' => Env::v('tel'), 'link_id' => $id, 'id' => 0, 'type' => 'fixed',
1455 'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
1456 $fax = new Phone(array('display' => Env::v('fax'), 'link_id' => $id, 'id' => 1, 'type' => 'fax',
1457 'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
1458 $phone->save();
1459 $fax->save();
1460
1461 XDB::execute("INSERT INTO profile_addresses (jobid, type, id, accuracy,
1462 text, postalText, postalCode, localityId,
1463 subAdministrativeAreaId, administrativeAreaId,
1464 countryId, latitude, longitude,
1465 north, south, east, west)
1466 VALUES ({?}, 'hq', 0, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
1467 {?}, {?}, {?}, {?}, {?}, {?})",
1468 $id, $address['accuracy'], $address['text'], $address['postalText'],
1469 $address['postalCode'], $address['localityId'],
1470 $address['subAdministrativeAreaId'], $address['administrativeAreaId'],
1471 $address['countryId'], $address['latitude'], $address['longitude'],
1472 $address['north'], $address['south'],
1473 $address['east'], $address['west']);
1474
1475 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1476 }
1477 }
1478
1479 if (!Env::has('change') && $id != -1) {
1480 $res = XDB::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1481 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1482 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1483 FROM profile_job_enum AS e
1484 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
1485 LEFT JOIN profile_phones AS t ON (t.pid = e.id AND t.link_type = 'hq' AND t.tel_id = 0)
1486 LEFT JOIN profile_phones AS f ON (f.pid = e.id AND f.link_type = 'hq' AND f.tel_id = 1)
1487 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1488 WHERE e.id = {?}",
1489 $id);
1490
1491 if ($res->numRows() == 0) {
1492 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1493 } else {
1494 $page->assign('selectedJob', $res->fetchOneAssoc());
1495 }
1496 }
1497 }
1498 }
1499
1500 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1501 ?>