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