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