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