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