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