Fix AX ID updating in admin/add_accounts page
[platal.git] / modules / admin.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2014 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 XDB::execute('DELETE FROM profiles
606 WHERE pid = {?}',
607 Post::i('del_profile'));
608 } else if (!Post::blank('new_profile')) {
609 $profile = Profile::get(Post::t('new_profile'));
610 if (!$profile) {
611 $page->trigError('Le profil ' . Post::t('new_profile') . ' n\'existe pas');
612 } else {
613 XDB::execute('INSERT IGNORE INTO account_profiles (uid, pid)
614 VALUES ({?}, {?})',
615 $user->id(), $profile->id());
616 }
617 }
618 XDB::execute('UPDATE account_profiles
619 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
620 WHERE uid = {?}',
621 Post::i('owner'), $user->id());
622 }
623 // }}}
624
625 // Email forwards form {{{
626 $redirect = ($registered ? new Redirect($user) : null);
627 if (Post::has('add_fwd')) {
628 $email = Post::t('email');
629 if (!isvalid_email_redirection($email, $user)) {
630 $page->trigError("Email non valide: $email");
631 } else {
632 $redirect->add_email($email);
633 $page->trigSuccess("Ajout de $email effectué");
634 }
635 } else if (!Post::blank('del_fwd')) {
636 $redirect->delete_email(Post::t('del_fwd'));
637 } else if (!Post::blank('activate_fwd')) {
638 $redirect->modify_one_email(Post::t('activate_fwd'), true);
639 } else if (!Post::blank('deactivate_fwd')) {
640 $redirect->modify_one_email(Post::t('deactivate_fwd'), false);
641 } else if (Post::has('disable_fwd')) {
642 $redirect->disable();
643 } else if (Post::has('enable_fwd')) {
644 $redirect->enable();
645 } else if (!Post::blank('clean_fwd')) {
646 $redirect->clean_errors(Post::t('clean_fwd'));
647 }
648 // }}}
649
650 // Email alias form {{{
651 if (Post::has('add_alias')) {
652 // Splits new alias in user and fqdn.
653 $alias = Env::t('email');
654 if (strpos($alias, '@') !== false) {
655 list($alias, $domain) = explode('@', $alias);
656 } else {
657 $domain = $user->mainEmailDomain();
658 }
659
660 // Checks for alias' user validity.
661 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
662 $page->trigError("'$alias' n'est pas un alias valide");
663 }
664
665 // Eventually adds the alias to the right domain.
666 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
667 $req = new AliasReq($user, $alias, 'Admin request', false);
668 if ($req->commit()) {
669 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué.");
670 } else {
671 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué.");
672 }
673 } elseif ($domain == $user->mainEmailDomain()) {
674 XDB::execute('INSERT INTO email_source_account (email, uid, domain, type, flags)
675 SELECT {?}, {?}, id, \'alias\', \'\'
676 FROM email_virtual_domains
677 WHERE name = {?}',
678 $alias, $user->id(), $domain);
679 $page->trigSuccess("Nouvel alias '$alias' ajouté");
680 } else {
681 $page->trigError("Le domaine '$domain' n'est pas valide pour cet utilisateur.");
682 }
683 } else if (!Post::blank('del_alias')) {
684 $delete_alias = Post::t('del_alias');
685 list($email, $domain) = explode('@', $delete_alias);
686 XDB::execute('DELETE s
687 FROM email_source_account AS s
688 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
689 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
690 WHERE s.email = {?} AND s.uid = {?} AND d.name = {?} AND type != \'forlife\'',
691 $email, $user->id(), $domain);
692 XDB::execute('UPDATE email_redirect_account AS r
693 INNER JOIN email_virtual_domains AS m ON (m.name = {?})
694 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
695 SET r.rewrite = \'\'
696 WHERE r.uid = {?} AND r.rewrite = CONCAT({?}, \'@\', d.name)',
697 $domain, $user->id(), $email);
698 fix_bestalias($user);
699 $page->trigSuccess("L'alias '$delete_alias' a été supprimé");
700 } else if (!Post::blank('best')) {
701 $best_alias = Post::t('best');
702 // First delete the bestalias flag from all this user's emails.
703 XDB::execute("UPDATE email_source_account
704 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
705 WHERE uid = {?}", $user->id());
706 // Then gives the bestalias flag to the given email.
707 list($email, $domain) = explode('@', $best_alias);
708 XDB::execute("UPDATE email_source_account
709 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
710 WHERE uid = {?} AND email = {?}", $user->id(), $email);
711
712 // As having a non-null bestalias value is critical in
713 // plat/al's code, we do an a posteriori check on the
714 // validity of the bestalias.
715 fix_bestalias($user);
716 }
717 // }}}
718
719 // OpenId form {{{
720 if (Post::has('del_openid')) {
721 XDB::execute('DELETE FROM account_auth_openid
722 WHERE id = {?}', Post::i('del_openid'));
723 }
724 // }}}
725
726 // Forum form {{{
727 if (Post::has('b_edit')) {
728 XDB::execute("DELETE FROM forum_innd
729 WHERE uid = {?}", $user->id());
730 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
731 XDB::execute("INSERT INTO forum_innd
732 SET ipmin = '0', ipmax = '4294967295',
733 write_perm = {?}, read_perm = {?},
734 comment = {?}, priority = '200', uid = {?}",
735 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
736 }
737 }
738 // }}}
739
740
741 $page->addJsLink('jquery.ui.xorg.js');
742
743 // Displays last login and last host information.
744 $res = XDB::query("SELECT start, host
745 FROM log_sessions
746 WHERE uid = {?} AND suid IS NULL
747 ORDER BY start DESC
748 LIMIT 1", $user->id());
749 list($lastlogin,$host) = $res->fetchOneRow();
750 $page->assign('lastlogin', $lastlogin);
751 $page->assign('host', $host);
752
753 // Display mailing lists
754 $page->assign('mlists', $listClient->get_all_user_lists($user->forlifeEmail()));
755
756 // Display active aliases.
757 $page->assign('virtuals', $user->emailGroupAliases());
758 $aliases = XDB::iterator("SELECT CONCAT(s.email, '@', d.name) AS email, (s.type = 'forlife') AS forlife,
759 (s.email REGEXP '\\\\.[0-9]{2}$') AS hundred_year,
760 FIND_IN_SET('bestalias', s.flags) AS bestalias, s.expire,
761 (s.type = 'alias_aux') AS alias
762 FROM email_source_account AS s
763 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
764 WHERE s.uid = {?}
765 ORDER BY !alias, s.email",
766 $user->id());
767 $page->assign('aliases', $aliases);
768 $page->assign('account_types', XDB::iterator('SELECT * FROM account_types ORDER BY type'));
769 $page->assign('skins', XDB::iterator('SELECT id, name FROM skins ORDER BY name'));
770 $page->assign('profiles', XDB::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner, p.ax_id
771 FROM account_profiles AS ap
772 INNER JOIN profiles AS p ON (ap.pid = p.pid)
773 WHERE ap.uid = {?}', $user->id()));
774 $page->assign('openid', XDB::iterator('SELECT id, url
775 FROM account_auth_openid
776 WHERE uid = {?}', $user->id()));
777
778 // Displays email redirection and the general profile.
779 if ($registered && $redirect) {
780 $page->assign('emails', $redirect->emails);
781 }
782
783 $page->assign('user', $user);
784 $page->assign('hasProfile', $user->hasProfile());
785
786 // Displays forum bans.
787 $res = XDB::query("SELECT write_perm, read_perm, comment
788 FROM forum_innd
789 WHERE uid = {?}", $user->id());
790 $bans = $res->fetchOneAssoc();
791 $page->assign('bans', $bans);
792 }
793
794 private static function getHrid($firstname, $lastname, $promo)
795 {
796 if ($firstname != null && $lastname != null && $promo != null) {
797 return User::makeHrid($firstname, $lastname, $promo);
798 }
799 return null;
800 }
801
802 private static function formatNewUser($page, $infosLine, $separator, $promo, $size)
803 {
804 $infos = explode($separator, $infosLine);
805 if (sizeof($infos) > $size || sizeof($infos) < 2) {
806 $page->trigError("La ligne $infosLine n'a pas été ajoutée.");
807 return false;
808 }
809
810 $infos = array_map('trim', $infos);
811 $hrid = self::getHrid($infos[1], $infos[0], $promo);
812 $res1 = XDB::query('SELECT COUNT(*)
813 FROM accounts
814 WHERE hruid = {?}', $hrid);
815 $res2 = XDB::query('SELECT COUNT(*)
816 FROM profiles
817 WHERE hrpid = {?}', $hrid);
818 if (is_null($hrid) || $res1->fetchOneCell() > 0 || $res2->fetchOneCell() > 0) {
819 $page->trigError("La ligne $infosLine n'a pas été ajoutée: une entrée similaire existe déjà");
820 return false;
821 }
822 $infos['hrid'] = $hrid;
823 return $infos;
824 }
825
826 private static function formatSex($page, $sex, $line)
827 {
828 switch ($sex) {
829 case 'F':
830 return 'female';
831 case 'M':
832 return 'male';
833 default:
834 $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
835 return null;
836 }
837 }
838
839 private static function formatBirthDate($birthDate)
840 {
841 // strtotime believes dd/mm/yyyy to be an US date (i.e mm/dd/yyyy), and
842 // dd-mm-yyyy to be a normal date (i.e dd-mm-yyyy)...
843 return date("Y-m-d", strtotime(str_replace('/', '-', $birthDate)));
844 }
845
846 function handler_add_accounts($page, $action = null, $promo = null)
847 {
848 require_once 'name.func.inc.php';
849 $page->changeTpl('admin/add_accounts.tpl');
850
851 if (Env::has('add_type') && Env::has('people')) {
852 static $titles = array('male' => 'M', 'female' => 'MLLE');
853 $lines = explode("\n", Env::t('people'));
854 $separator = Env::t('separator');
855 $promotion = Env::i('promotion');
856
857 if (Env::t('add_type') == 'promo') {
858 $eduSchools = DirEnum::getOptions(DirEnum::EDUSCHOOLS);
859 $eduSchools = array_flip($eduSchools);
860 $eduDegrees = DirEnum::getOptions(DirEnum::EDUDEGREES);
861 $eduDegrees = array_flip($eduDegrees);
862 switch (Env::t('edu_type')) {
863 case 'X':
864 $degreeid = $eduDegrees[Profile::DEGREE_X];
865 $entry_year = $promotion;
866 $grad_year = $promotion + 3;
867 $promo = 'X' . $promotion;
868 $hrpromo = $promotion;
869 $type = 'x';
870 break;
871 case 'M':
872 $degreeid = $eduDegrees[Profile::DEGREE_M];
873 $grad_year = $promotion;
874 $entry_year = $promotion - 2;
875 $promo = 'M' . $promotion;
876 $hrpromo = $promo;
877 $type = 'master';
878 break;
879 case 'D':
880 $degreeid = $eduDegrees[Profile::DEGREE_D];
881 $grad_year = $promotion;
882 $entry_year = $promotion - 3;
883 $promo = 'D (en cours)';
884 $hrpromo = 'D' . $promotion;
885 $type = 'phd';
886 break;
887 default:
888 $page->killError("La formation n'est pas reconnue : " . Env::t('edu_type') . '.');
889 }
890 $best_domain = XDB::fetchOneCell('SELECT id
891 FROM email_virtual_domains
892 WHERE name = {?}',
893 User::$sub_mail_domains[$type] . Platal::globals()->mail->domain);
894
895 XDB::startTransaction();
896 foreach ($lines as $line) {
897 if ($infos = self::formatNewUser($page, $line, $separator, $hrpromo, 6)) {
898 $sex = self::formatSex($page, $infos[3], $line);
899 $lastname = capitalize_name($infos[0]);
900 $firstname = capitalize_name($infos[1]);
901 if (!is_null($sex)) {
902 $fullName = build_full_name($firstname, $lastname);
903 $directoryName = build_directory_name($firstname, $lastname);
904 $sortName = build_sort_name($firstname, $lastname);
905 $birthDate = self::formatBirthDate($infos[2]);
906 if ($type == 'x') {
907 $xorgId = Profile::getXorgId($infos[4]);
908 } elseif (isset($infos[4])) {
909 $xorgId = trim($infos[4]);
910 } else {
911 $xorgId = 0;
912 }
913 if (is_null($xorgId)) {
914 $page->trigError("La ligne $line n'a pas été ajoutée car le matricule École est mal renseigné.");
915 continue;
916 }
917
918 XDB::execute('INSERT INTO profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex, title)
919 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
920 $infos['hrid'], $xorgId, (isset($infos[5]) ? $infos[5] : null),
921 $birthDate, $sex, $titles[$sex]);
922 $pid = XDB::insertId();
923 XDB::execute('INSERT INTO profile_public_names (pid, lastname_initial, lastname_main, firstname_initial, firstname_main)
924 VALUES ({?}, {?}, {?}, {?}, {?})',
925 $pid, $lastname, $lastname, $firstname, $firstname);
926 XDB::execute('INSERT INTO profile_display (pid, yourself, public_name, private_name,
927 directory_name, short_name, sort_name, promo)
928 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
929 $pid, $firstname, $fullName, $fullName, $directoryName, $fullName, $sortName, $promo);
930 XDB::execute('INSERT INTO profile_education (id, pid, eduid, degreeid, entry_year, grad_year, promo_year, flags)
931 VALUES (100, {?}, {?}, {?}, {?}, {?}, {?}, \'primary\')',
932 $pid, $eduSchools[Profile::EDU_X], $degreeid, $entry_year, $grad_year, $promotion);
933 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, full_name, directory_name,
934 sort_name, display_name, lastname, firstname, sex, best_domain)
935 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
936 $infos['hrid'], $type, 0, 'pending', $fullName, $directoryName, $sortName,
937 $firstname, $lastname, $firstname, $sex, $best_domain);
938 $uid = XDB::insertId();
939 XDB::execute('INSERT INTO account_profiles (uid, pid, perms)
940 VALUES ({?}, {?}, {?})',
941 $uid, $pid, 'owner');
942 Profile::rebuildSearchTokens($pid, false);
943 }
944 }
945 }
946 XDB::commit();
947 } else if (Env::t('add_type') == 'account') {
948 $type = Env::t('type');
949 $newAccounts = array();
950 foreach ($lines as $line) {
951 if ($infos = self::formatNewUser($page, $line, $separator, $type, 4)) {
952 $sex = self::formatSex($page, $infos[3], $line);
953 if (!is_null($sex)) {
954 $lastname = capitalize_name($infos[0]);
955 $firstname = capitalize_name($infos[1]);
956 $fullName = build_full_name($firstname, $lastname);
957 $directoryName = build_directory_name($firstname, $lastname);
958 $sortName = build_sort_name($firstname, $lastname);
959 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, email, full_name, directory_name,
960 sort_name, display_name, lastname, firstname, sex)
961 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
962 $infos['hrid'], $type, 0, 'pending', $infos[2], $fullName, $directoryName,
963 $sortName ,$firstname, $lastname, $firstname, $sex);
964 $newAccounts[$infos['hrid']] = $fullName;
965 }
966 }
967 }
968 if (!empty($newAccounts)) {
969 $page->assign('newAccounts', $newAccounts);
970 }
971 } else if (Env::t('add_type') == 'ax_id') {
972 $type = 'x';
973 foreach ($lines as $line) {
974 $infos = explode($separator, $line);
975 if (sizeof($infos) > 3 || sizeof($infos) < 2) {
976 $page->trigError("La ligne $line n'a pas été ajoutée : mauvais nombre de champs.");
977 continue;
978 }
979 $infos = array_map('trim', $infos);
980 if (sizeof($infos) == 3) {
981 // Get human readable ID with first name and last name
982 $hrid = User::makeHrid($infos[1], $infos[0], $promotion);
983 $user = User::getSilent($hrid);
984 } else {
985 // The first column is the hrid, possibly without the promotion
986 $user = User::getSilent($infos[0] . '.' . $promotion);
987 if (is_null($user)) {
988 $user = User::getSilent($infos[0]);
989 }
990 }
991 if (is_null($user)) {
992 $page->trigError("La ligne $line n'a pas été ajoutée : aucun compte trouvé.");
993 continue;
994 }
995 $profile = $user->profile();
996 if ($profile->ax_id) {
997 $page->trigError("Le profil " . $profile->hrpid . " a déjà l'ID AX " . $profile->ax_id);
998 continue;
999 }
1000 XDB::execute('UPDATE profiles
1001 SET ax_id = {?}
1002 WHERE pid = {?}',
1003 $infos[2], $profile->id());
1004
1005 }
1006 }
1007
1008 $errors = $page->nb_errs();
1009 if ($errors == 0) {
1010 $page->trigSuccess("L'opération a été effectuée avec succès.");
1011 } else {
1012 $page->trigSuccess('L\'opération a été effectuée avec succès, sauf pour '
1013 . (($errors == 1) ? 'l\'erreur signalée' : "les $errors erreurs signalées") . ' ci-dessus.');
1014 }
1015 } else if (Env::has('add_type')) {
1016 $res = XDB::query('SELECT type
1017 FROM account_types');
1018 $page->assign('account_types', $res->fetchColumn());
1019 $page->assign('add_type', Env::s('add_type'));
1020 }
1021 }
1022
1023 function handler_homonyms($page, $op = 'list', $target = null)
1024 {
1025 $page->changeTpl('admin/homonymes.tpl');
1026 $page->setTitle('Administration - Homonymes');
1027 $this->load("homonyms.inc.php");
1028
1029 if ($target) {
1030 $user = User::getSilentWithUID($target);
1031 if (!$user || !($loginbis = select_if_homonym($user))) {
1032 $target = 0;
1033 } else {
1034 $page->assign('user', $user);
1035 $page->assign('loginbis',$loginbis);
1036 }
1037 }
1038
1039 $page->assign('op', $op);
1040 $page->assign('target', $target);
1041
1042 // When we have a valid target, prepare emails.
1043 if ($target) {
1044 // Examine what operation needs to be performed.
1045 switch ($op) {
1046 case 'mail':
1047 S::assert_xsrf_token();
1048
1049 send_warning_homonym($user, $loginbis);
1050 $op = 'list';
1051 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
1052 break;
1053
1054 case 'correct':
1055 S::assert_xsrf_token();
1056
1057 fix_homonym($user, $loginbis);
1058 send_robot_homonym($user, $loginbis);
1059 $op = 'list';
1060 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
1061 break;
1062 }
1063 }
1064
1065 if ($op == 'list') {
1066 // Retrieves homonyms that are already been fixed.
1067 $res = XDB::iterator('SELECT o.email AS homonym, f.email AS forlife, o.expire, f.uid
1068 FROM email_source_other AS o
1069 INNER JOIN homonyms_list AS h ON (o.hrmid = h.hrmid)
1070 INNER JOIN email_source_account AS f ON (h.uid = f.uid AND f.type = \'forlife\')
1071 WHERE o.expire IS NOT NULL
1072 ORDER BY homonym, forlife');
1073 $homonyms = array();
1074 while ($item = $res->next()) {
1075 $homonyms[$item['homonym']][] = $item;
1076 }
1077 $page->assign_by_ref('homonyms', $homonyms);
1078
1079 // Retrieves homonyms that needs to be fixed.
1080 $res = XDB::iterator('SELECT e.email AS homonym, f.email AS forlife, e.expire, e.uid, (e.expire < NOW()) AS urgent
1081 FROM email_source_account AS e
1082 INNER JOIN homonyms_list AS l ON (e.uid = l.uid)
1083 INNER JOIN homonyms_list AS h ON (l.hrmid = h.hrmid)
1084 INNER JOIN email_source_account AS f ON (h.uid = f.uid AND f.type = \'forlife\')
1085 WHERE e.expire IS NOT NULL
1086 ORDER BY homonym, forlife');
1087 $homonyms_to_fix = array();
1088 while ($item = $res->next()) {
1089 $homonyms_to_fix[$item['homonym']][] = $item;
1090 }
1091 $page->assign_by_ref('homonyms_to_fix', $homonyms_to_fix);
1092 }
1093
1094 if ($op == 'correct-conf') {
1095 $page->assign('robot_mail_text', get_robot_mail_text($user, $loginbis));
1096 }
1097
1098 if ($op == 'mail-conf') {
1099 $page->assign('warning_mail_text', get_warning_mail_text($user, $loginbis));
1100 }
1101 }
1102
1103 function handler_deaths($page, $promo = 0, $validate = false)
1104 {
1105 $page->changeTpl('admin/deces_promo.tpl');
1106 $page->setTitle('Administration - Deces');
1107
1108 if (!$promo) {
1109 $promo = Env::t('promo', 'X1923');
1110 }
1111 $page->assign('promo', $promo);
1112 if (!$promo) {
1113 return;
1114 }
1115
1116 if ($validate) {
1117 S::assert_xsrf_token();
1118
1119 $res = XDB::iterRow('SELECT p.pid, pd.directory_name, p.deathdate
1120 FROM profiles AS p
1121 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1122 WHERE pd.promo = {?}', $promo);
1123 while (list($pid, $name, $death) = $res->next()) {
1124 $val = Env::v('death_' . $pid);
1125 if ($val == $death) {
1126 continue;
1127 }
1128
1129 if (empty($val)) {
1130 $val = null;
1131 }
1132 XDB::execute('UPDATE profiles
1133 SET deathdate = {?}, deathdate_rec = NOW()
1134 WHERE pid = {?}', $val, $pid);
1135
1136 $page->trigSuccess('Édition du décès de ' . $name . ' (' . ($val ? $val : 'ressuscité') . ').');
1137 if ($val && ($death == '0000-00-00' || empty($death))) {
1138 $profile = Profile::get($pid);
1139 $profile->clear();
1140 $profile->owner()->clear(false);
1141 }
1142 }
1143 }
1144
1145 $res = XDB::iterator('SELECT p.pid, pd.directory_name, p.deathdate
1146 FROM profiles AS p
1147 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1148 WHERE pd.promo = {?}
1149 ORDER BY pd.sort_name', $promo);
1150 $page->assign('profileList', $res);
1151 }
1152
1153 function handler_dead_but_active($page)
1154 {
1155 $page->changeTpl('admin/dead_but_active.tpl');
1156 $page->setTitle('Administration - Décédés');
1157
1158 $res = XDB::iterator(
1159 "SELECT a.hruid, pd.promo, p.ax_id, pd.directory_name, p.deathdate, DATE(MAX(s.start)) AS last
1160 FROM accounts AS a
1161 INNER JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET('owner', ap.perms))
1162 INNER JOIN profiles AS p ON (p.pid = ap.pid)
1163 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
1164 LEFT JOIN log_sessions AS s ON (s.uid = a.uid AND suid = 0)
1165 WHERE a.state = 'active' AND p.deathdate IS NOT NULL
1166 GROUP BY a.uid
1167 ORDER BY pd.promo, pd.sort_name");
1168 $page->assign('dead', $res);
1169 }
1170
1171 function handler_validate($page, $action = 'list', $id = null)
1172 {
1173 $page->changeTpl('admin/validation.tpl');
1174 $page->setTitle('Administration - Valider une demande');
1175 $page->addCssLink('nl.Polytechnique.org.css');
1176
1177 if ($action == 'edit' && !is_null($id)) {
1178 $page->assign('preview_id', $id);
1179 } else {
1180 $page->assign('preview_id', null);
1181 }
1182
1183 if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
1184 S::assert_xsrf_token();
1185
1186 $req = Validate::get_typed_request(Env::v('uid'), Env::v('type'), Env::v('stamp'));
1187 if ($req) {
1188 $req->handle_formu();
1189 } else {
1190 $page->trigWarning('La validation a déjà été effectuée.');
1191 }
1192 }
1193
1194 $r = XDB::iterator('SHOW COLUMNS FROM requests_answers');
1195 while (($a = $r->next()) && $a['Field'] != 'category');
1196 $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1)));
1197 sort($categories);
1198 $page->assign('categories', $categories);
1199
1200 $hidden = array();
1201 $res = XDB::query('SELECT hidden_requests
1202 FROM requests_hidden
1203 WHERE uid = {?}', S::v('uid'));
1204 $hide_requests = $res->fetchOneCell();
1205 if (Post::has('hide')) {
1206 $hide = array();
1207 foreach ($categories as $cat)
1208 if (!Post::v($cat)) {
1209 $hidden[$cat] = 1;
1210 $hide[] = $cat;
1211 }
1212 $hide_requests = join(',', $hide);
1213 XDB::query('INSERT INTO requests_hidden (uid, hidden_requests)
1214 VALUES ({?}, {?})
1215 ON DUPLICATE KEY UPDATE hidden_requests = VALUES(hidden_requests)',
1216 S::v('uid'), $hide_requests);
1217 } elseif ($hide_requests) {
1218 foreach (explode(',', $hide_requests) as $hide_type)
1219 $hidden[$hide_type] = true;
1220 }
1221 $page->assign('hide_requests', $hidden);
1222
1223 // Update the count of item to validate here... useful in development configuration
1224 // where several copies of the site use the same DB, but not the same "dynamic configuration"
1225 global $globals;
1226 $globals->updateNbValid();
1227 $page->assign('vit', Validate::iterate());
1228 $page->assign('isAdmin', S::admin());
1229 }
1230
1231 function handler_validate_answers($page, $action = 'list', $id = null)
1232 {
1233 $page->setTitle('Administration - Réponses automatiques de validation');
1234 $page->assign('title', 'Gestion des réponses automatiques');
1235 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
1236 $table_editor->describe('category','catégorie',true);
1237 $table_editor->describe('title','titre',true);
1238 $table_editor->describe('answer','texte',false, true);
1239 $table_editor->apply($page, $action, $id);
1240 }
1241
1242 function handler_skins($page, $action = 'list', $id = null)
1243 {
1244 $page->setTitle('Administration - Skins');
1245 $page->assign('title', 'Gestion des skins');
1246 $table_editor = new PLTableEditor('admin/skins','skins','id');
1247 $table_editor->describe('name','nom',true);
1248 $table_editor->describe('skin_tpl','nom du template',true);
1249 $table_editor->describe('auteur','auteur',false, true);
1250 $table_editor->describe('comment','commentaire',true);
1251 $table_editor->describe('date','date',false, true);
1252 $table_editor->describe('ext','extension du screenshot',false, true);
1253 $table_editor->apply($page, $action, $id);
1254 }
1255
1256 function handler_postfix_blacklist($page, $action = 'list', $id = null)
1257 {
1258 $page->setTitle('Administration - Postfix : Blacklist');
1259 $page->assign('title', 'Blacklist de postfix');
1260 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true);
1261 $table_editor->describe('reject_text','Texte de rejet',true);
1262 $table_editor->describe('email','email',true);
1263 $table_editor->apply($page, $action, $id);
1264 }
1265
1266 function handler_postfix_whitelist($page, $action = 'list', $id = null)
1267 {
1268 $page->setTitle('Administration - Postfix : Whitelist');
1269 $page->assign('title', 'Whitelist de postfix');
1270 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true);
1271 $table_editor->describe('email','email',true);
1272 $table_editor->apply($page, $action, $id);
1273 }
1274
1275 function handler_mx_broken($page, $action = 'list', $id = null)
1276 {
1277 $page->setTitle('Administration - MX Défaillants');
1278 $page->assign('title', 'MX Défaillant');
1279 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true);
1280 $table_editor->describe('host', 'Masque', true);
1281 $table_editor->describe('state', 'Niveau', true);
1282 $table_editor->describe('text', 'Description du problème', false, true);
1283 $table_editor->apply($page, $action, $id);
1284 }
1285
1286 function handler_logger_actions($page, $action = 'list', $id = null)
1287 {
1288 $page->setTitle('Administration - Actions');
1289 $page->assign('title', 'Gestion des actions de logger');
1290 $table_editor = new PLTableEditor('admin/logger/actions','log_actions','id');
1291 $table_editor->describe('text','intitulé',true);
1292 $table_editor->describe('description','description',true);
1293 $table_editor->apply($page, $action, $id);
1294 }
1295
1296 function handler_downtime($page, $action = 'list', $id = null)
1297 {
1298 $page->setTitle('Administration - Coupures');
1299 $page->assign('title', 'Gestion des coupures');
1300 $table_editor = new PLTableEditor('admin/downtime','downtimes','id');
1301 $table_editor->describe('debut','date',true);
1302 $table_editor->describe('duree','durée',false, true);
1303 $table_editor->describe('resume','résumé',true);
1304 $table_editor->describe('services','services affectés',true);
1305 $table_editor->describe('description','description',false, true);
1306 $table_editor->apply($page, $action, $id);
1307 }
1308
1309 private static function isCountryIncomplete(array &$item)
1310 {
1311 $warning = false;
1312 foreach (array('worldRegion', 'country', 'capital', 'phonePrefix', 'licensePlate', 'countryPlain') as $field) {
1313 if ($item[$field] == '') {
1314 $item[$field . '_warning'] = true;
1315 $warning = true;
1316 }
1317 }
1318 if (is_null($item['belongsTo'])) {
1319 foreach (array('nationality', 'nationalityEn') as $field) {
1320 if ($item[$field] == '') {
1321 $item[$field . '_warning'] = true;
1322 $warning = true;
1323 }
1324 }
1325 }
1326 return $warning;
1327 }
1328
1329 private static function updateCountry(array $item)
1330 {
1331 XDB::execute('UPDATE geoloc_countries
1332 SET countryPlain = {?}
1333 WHERE iso_3166_1_a2 = {?}',
1334 mb_strtoupper(replace_accent($item['country'])), $item['iso_3166_1_a2']);
1335 }
1336
1337 private static function isLanguageIncomplete(array &$item)
1338 {
1339 if ($item['language'] == '') {
1340 $item['language_warning'] = true;
1341 return true;
1342 }
1343 return false;
1344 }
1345
1346 private static function updateLanguage(array $item) {}
1347
1348 function handler_geocoding($page, $category = null, $action = null, $id = null)
1349 {
1350 // Warning, this handler requires the following packages:
1351 // * pkg-isocodes
1352 // * isoquery
1353
1354 static $properties = array(
1355 'country' => array(
1356 'name' => 'pays',
1357 'isocode' => '3166',
1358 'table' => 'geoloc_countries',
1359 'id' => 'iso_3166_1_a2',
1360 'main_fields' => array('iso_3166_1_a3', 'iso_3166_1_num', 'countryEn'),
1361 'other_fields' => array('worldRegion', 'country', 'capital', 'nationality', 'nationalityEn',
1362 'phonePrefix', 'phoneFormat', 'licensePlate', 'belongsTo')
1363 ),
1364 'language' => array(
1365 'name' => 'langages',
1366 'isocode' => '639',
1367 'table' => 'profile_langskill_enum',
1368 'id' => 'iso_639_2b',
1369 'main_fields' => array('iso_639_2t', 'iso_639_1', 'language_en'),
1370 'other_fields' => array('language')
1371
1372 )
1373 );
1374
1375 if (is_null($category) || !array_key_exists($category, $properties)) {
1376 pl_redirect('admin');
1377 }
1378
1379 $data = $properties[$category];
1380
1381 if ($action == 'edit' || $action == 'add') {
1382 $main_fields = array_merge(array($data['id']), $data['main_fields']);
1383 $all_fields = array_merge($main_fields, $data['other_fields']);
1384
1385 if (is_null($id)) {
1386 if (Post::has('new_id')) {
1387 $id = Post::v('new_id');
1388 } else {
1389 pl_redirect('admin/geocoding/' . $category);
1390 }
1391 }
1392
1393 $list = array();
1394 exec('isoquery --iso=' . $data['isocode'] . ' ' . $id, $list);
1395 if (count($list) == 1) {
1396 $array = explode("\t", $list[0]);
1397 foreach ($main_fields as $i => $field) {
1398 $iso[$field] = $array[$i];
1399 }
1400 } else {
1401 $iso = array();
1402 }
1403
1404 if ($action == 'add') {
1405 if (Post::has('new_id')) {
1406 S::assert_xsrf_token();
1407 }
1408
1409 if (count($iso)) {
1410 $item = $iso;
1411 } else {
1412 $item = array($data['id'] => $id);
1413 }
1414 XDB::execute('INSERT INTO ' . $data['table'] . '(' . implode(', ', array_keys($item)) . ')
1415 VALUES ' . XDB::formatArray($item));
1416 $page->trigSuccess($id . ' a bien été ajouté à la base.');
1417 } elseif ($action == 'edit') {
1418 if (Post::has('edit')) {
1419 S::assert_xsrf_token();
1420
1421 $item = array();
1422 $set = array();
1423 foreach ($all_fields as $field) {
1424 $item[$field] = Post::t($field);
1425 $set[] = $field . XDB::format(' = {?}', ($item[$field] ? $item[$field] : null));
1426 }
1427 XDB::execute('UPDATE ' . $data['table'] . '
1428 SET ' . implode(', ', $set) . '
1429 WHERE ' . $data['id'] . ' = {?}',
1430 $id);
1431 call_user_func_array(array('self', 'update' . ucfirst($category)), array($item));
1432 $page->trigSuccess($id . ' a bien été mis à jour.');
1433 } elseif (Post::has('del')) {
1434 S::assert_xsrf_token();
1435
1436 XDB::execute('DELETE FROM ' . $data['table'] . '
1437 WHERE ' . $data['id'] . ' = {?}',
1438 $id);
1439 $page->trigSuccessRedirect($id . ' a bien été supprimé.', 'admin/geocoding/' . $category);
1440 } else {
1441 $item = XDB::fetchOneAssoc('SELECT *
1442 FROM ' . $data['table'] . '
1443 WHERE ' . $data['id'] . ' = {?}',
1444 $id);
1445 }
1446 }
1447
1448 $page->changeTpl('admin/geocoding_edit.tpl');
1449 $page->setTitle('Administration - ' . ucfirst($data['name']));
1450 $page->assign('category', $category);
1451 $page->assign('name', $data['name']);
1452 $page->assign('all_fields', $all_fields);
1453 $page->assign('id', $id);
1454 $page->assign('iso', $iso);
1455 $page->assign('item', $item);
1456 return;
1457 }
1458
1459 $page->changeTpl('admin/geocoding.tpl');
1460 $page->setTitle('Administration - ' . ucfirst($data['name']));
1461 $page->assign('category', $category);
1462 $page->assign('name', $data['name']);
1463 $page->assign('id', $data['id']);
1464 $page->assign('main_fields', $data['main_fields']);
1465 $page->assign('all_fields', array_merge($data['main_fields'], $data['other_fields']));
1466
1467 // First build the list provided by the iso codes.
1468 $list = array();
1469 exec('isoquery --iso=' . $data['isocode'], $list);
1470
1471 foreach ($list as $key => $item) {
1472 $array = explode("\t", $item);
1473 unset($list[$key]);
1474 $list[$array[0]] = array();
1475 foreach ($data['main_fields'] as $i => $field) {
1476 $list[$array[0]][$field] = $array[$i + 1];
1477 }
1478 }
1479 ksort($list);
1480
1481 // Retrieve all data from the database.
1482 $db_list = XDB::rawFetchAllAssoc('SELECT *
1483 FROM ' . $data['table'] . '
1484 ORDER BY ' . $data['id'],
1485 $data['id']);
1486
1487 // Sort both iso and database data into 5 categories:
1488 // $missing: data from the iso list not in the database,
1489 // $non_existing: data from the database not in the iso list,
1490 // $erroneous: data that differ on main fields,
1491 // $incomplete: data with empty fields in the data base,
1492 // $remaining: remaining correct and complete data from the database.
1493
1494 $missing = $non_existing = $erroneous = $incomplete = $remaining = array();
1495 foreach (array_keys($list) as $id) {
1496 if (!array_key_exists($id, $db_list)) {
1497 $missing[$id] = $list[$id];
1498 }
1499 }
1500
1501 foreach ($db_list as $id => $item) {
1502 if (!array_key_exists($id, $list)) {
1503 $non_existing[$id] = $item;
1504 } else {
1505 $error = false;
1506 foreach ($data['main_fields'] as $field) {
1507 if ($item[$field] != $list[$id][$field]) {
1508 $item[$field . '_error'] = true;
1509 $error = true;
1510 }
1511 }
1512 if ($error == true) {
1513 $erroneous[$id] = $item;
1514 } elseif (call_user_func_array(array('self', 'is' . ucfirst($category) . 'Incomplete'), array(&$item))) {
1515 $incomplete[$id] = $item;
1516 } else {
1517 $remaining[$id] = $item;
1518 }
1519 }
1520 }
1521
1522 $page->assign('lists', array(
1523 'manquant' => $missing,
1524 'disparu' => $non_existing,
1525 'erroné' => $erroneous,
1526 'incomplet' => $incomplete,
1527 'restant' => $remaining
1528 ));
1529 }
1530
1531 function handler_accounts(PlPage $page)
1532 {
1533 $page->changeTpl('admin/accounts.tpl');
1534 $page->setTitle('Administration - Comptes');
1535
1536 if (Post::has('create_account')) {
1537 S::assert_xsrf_token();
1538 $firstname = Post::t('firstname');
1539 $lastname = mb_strtoupper(Post::t('lastname'));
1540 $sex = Post::s('sex');
1541 $email = Post::t('email');
1542 $type = Post::s('type');
1543 if (!$type) {
1544 $page->trigError("Empty account type");
1545 } elseif (!isvalid_email($email)) {
1546 $page->trigError("Invalid email address: $email");
1547 } elseif (strlen(Post::s('pwhash')) != 40) {
1548 $page->trigError("Invalid password hash");
1549 } else {
1550 $login = PlUser::makeHrid($firstname, $lastname, $type);
1551 $full_name = $firstname . ' ' . $lastname;
1552 $directory_name = $lastname . ' ' . $firstname;
1553 XDB::execute("INSERT INTO accounts (hruid, type, state, password,
1554 registration_date, email, full_name,
1555 display_name, sex, directory_name,
1556 lastname, firstname)
1557 VALUES ({?}, {?}, 'active', {?}, NOW(), {?}, {?}, {?}, {?}, {?}, {?}, {?})",
1558 $login, $type, Post::s('pwhash'), $email, $full_name, $full_name, $sex,
1559 $directory_name, $lastname, $firstname);
1560 }
1561 }
1562
1563 $uf = new UserFilter(new UFC_AccountType('ax', 'school', 'fx'));
1564 $page->assign('users', $uf->iterUsers());
1565
1566 }
1567
1568 function handler_account_types($page, $action = 'list', $id = null)
1569 {
1570 $page->setTitle('Administration - Types de comptes');
1571 $page->assign('title', 'Gestion des types de comptes');
1572 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true);
1573 $table_editor->describe('type', 'Catégorie', true);
1574 $table_editor->describe('perms', 'Permissions associées', true);
1575 $table_editor->apply($page, $action, $id);
1576
1577 $page->trigWarning(
1578 'Le niveau de visibilité "ax", utilisé par la permission "directory_ax", ' .
1579 'correspond à la visibilité dans l\'annuaire papier.');
1580 }
1581
1582 function handler_wiki($page, $action = 'list', $wikipage = null, $wikipage2 = null)
1583 {
1584 if (S::hasAuthToken()) {
1585 $page->setRssLink('Changement Récents',
1586 '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::user()->token);
1587 }
1588
1589 // update wiki perms
1590 if ($action == 'update') {
1591 S::assert_xsrf_token();
1592
1593 $perms_read = Post::v('read');
1594 $perms_edit = Post::v('edit');
1595 if ($perms_read || $perms_edit) {
1596 foreach ($_POST as $wiki_page => $val) {
1597 if ($val == 'on') {
1598 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1599 if ($wp->setPerms($perms_read ? $perms_read : $wp->readPerms(),
1600 $perms_edit ? $perms_edit : $wp->writePerms())) {
1601 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1602 } else {
1603 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1604 }
1605 }
1606 }
1607 }
1608 } else if ($action != 'list' && !empty($wikipage)) {
1609 $wp = new PlWikiPage($wikipage);
1610 S::assert_xsrf_token();
1611
1612 if ($action == 'delete') {
1613 if ($wp->delete()) {
1614 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1615 } else {
1616 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1617 }
1618 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1619 if ($changedLinks = $wp->rename($wikipage2)) {
1620 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1621 if (is_numeric($changedLinks)) {
1622 $s .= $changedLinks.' lien'.(($changedLinks>1)?'s ont été modifiés.':' a été modifié.');
1623 }
1624 $page->trigSuccess($s);
1625 } else {
1626 $page->trigError("Impossible de déplacer la page ".$wikipage);
1627 }
1628 }
1629 }
1630
1631 $perms = PlWikiPage::permOptions();
1632
1633 // list wiki pages and their perms
1634 $wiki_pages = PlWikiPage::listPages();
1635 ksort($wiki_pages);
1636 $wiki_tree = array();
1637 foreach ($wiki_pages as $file => $desc) {
1638 list($cat, $name) = explode('.', $file);
1639 if (!isset($wiki_tree[$cat])) {
1640 $wiki_tree[$cat] = array();
1641 }
1642 $wiki_tree[$cat][$name] = $desc;
1643 }
1644
1645 $page->changeTpl('admin/wiki.tpl');
1646 $page->assign('wiki_pages', $wiki_tree);
1647 $page->assign('perms_opts', $perms);
1648 }
1649
1650 function handler_ipwatch($page, $action = 'list', $ip = null)
1651 {
1652 $page->changeTpl('admin/ipwatcher.tpl');
1653
1654 $states = array('safe' => 'Ne pas surveiller',
1655 'unsafe' => 'Surveiller les inscriptions',
1656 'dangerous' => 'Surveiller tous les accès',
1657 'ban' => 'Bannir cette adresse');
1658 $page->assign('states', $states);
1659
1660 switch (Post::v('action')) {
1661 case 'create':
1662 if (trim(Post::v('ipN')) != '') {
1663 S::assert_xsrf_token();
1664 Xdb::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1665 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1666 ip_to_uint(trim(Post::v('ipN'))), ip_to_uint(trim(Post::v('maskN'))),
1667 Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
1668 };
1669 break;
1670
1671 case 'edit':
1672 S::assert_xsrf_token();
1673 Xdb::execute('UPDATE ip_watch
1674 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1675 WHERE ip = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'),
1676 ip_to_uint(Post::v('maskN')), ip_to_uint(Post::v('ipN')));
1677 break;
1678
1679 default:
1680 if ($action == 'delete' && !is_null($ip)) {
1681 S::assert_xsrf_token();
1682 Xdb::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1683 }
1684 }
1685 if ($action != 'create' && $action != 'edit') {
1686 $action = 'list';
1687 }
1688 $page->assign('action', $action);
1689
1690 if ($action == 'list') {
1691 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1692 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1693 IF(w.ip = s.ip, s.host, s.forward_host)),
1694 w.mask, w.detection, w.state, a.hruid
1695 FROM ip_watch AS w
1696 LEFT JOIN log_sessions AS s ON (s.ip = w.ip)
1697 LEFT JOIN log_sessions AS s2 ON (s2.forward_ip = w.ip)
1698 LEFT JOIN accounts AS a ON (a.uid = s.uid)
1699 GROUP BY w.ip, a.hruid
1700 ORDER BY w.state, w.ip, a.hruid";
1701 $it = Xdb::iterRow($sql);
1702
1703 $table = array();
1704 $props = array();
1705 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1706 $ip = uint_to_ip($ip);
1707 $mask = uint_to_ip($mask);
1708 if (count($props) == 0 || $props['ip'] != $ip) {
1709 if (count($props) > 0) {
1710 $table[] = $props;
1711 }
1712 $props = array('ip' => $ip,
1713 'mask' => $mask,
1714 'host' => $host,
1715 'detection' => $date,
1716 'state' => $state,
1717 'users' => array($hruid));
1718 } else {
1719 $props['users'][] = $hruid;
1720 }
1721 }
1722 if (count($props) > 0) {
1723 $table[] = $props;
1724 }
1725 $page->assign('table', $table);
1726 } elseif ($action == 'edit') {
1727 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1728 a1.hruid AS edit, a2.hruid AS hruid, s.host
1729 FROM ip_watch AS w
1730 LEFT JOIN accounts AS a1 ON (a1.uid = w.uid)
1731 LEFT JOIN log_sessions AS s ON (w.ip = s.ip)
1732 LEFT JOIN accounts AS a2 ON (a2.uid = s.uid)
1733 WHERE w.ip = {?}
1734 GROUP BY a2.hruid
1735 ORDER BY a2.hruid";
1736 $it = Xdb::iterRow($sql, ip_to_uint($ip));
1737
1738 $props = array();
1739 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1740 if (count($props) == 0) {
1741 $props = array('ip' => $ip,
1742 'mask' => uint_to_ip($mask),
1743 'host' => $host,
1744 'detection' => $detection,
1745 'state' => $state,
1746 'last' => $last,
1747 'description' => $description,
1748 'edit' => $edit,
1749 'users' => array($hruid));
1750 } else {
1751 $props['users'][] = $hruid;
1752 }
1753 }
1754 $page->assign('ip', $props);
1755 }
1756 }
1757
1758 function handler_icons($page)
1759 {
1760 $page->changeTpl('admin/icons.tpl');
1761 $dh = opendir('../htdocs/images/icons');
1762 if (!$dh) {
1763 $page->trigError('Dossier des icones introuvables.');
1764 }
1765 $icons = array();
1766 while (($file = readdir($dh)) !== false) {
1767 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1768 array_push($icons, substr($file, 0, -4));
1769 }
1770 }
1771 sort($icons);
1772 $page->assign('icons', $icons);
1773 }
1774
1775 function handler_account_watch($page)
1776 {
1777 $page->changeTpl('admin/accounts.tpl');
1778 $page->assign('disabled', XDB::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1779 a.state = \'disabled\' AS disabled, a.comment
1780 FROM accounts AS a
1781 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1782 ORDER BY a.hruid'));
1783 $page->assign('admins', XDB::iterator('SELECT a.hruid
1784 FROM accounts AS a
1785 WHERE a.is_admin
1786 ORDER BY a.hruid'));
1787 }
1788
1789 function handler_xnet_without_group($page)
1790 {
1791 $page->changeTpl('admin/xnet_without_group.tpl');
1792 $page->assign('accounts', XDB::iterator('SELECT a.hruid, a.state
1793 FROM accounts AS a
1794 LEFT JOIN group_members AS m ON (a.uid = m.uid)
1795 WHERE a.type = \'xnet\' AND m.uid IS NULL
1796 ORDER BY a.state, a.hruid'));
1797 }
1798
1799 function handler_jobs($page, $id = -1)
1800 {
1801 $page->changeTpl('admin/jobs.tpl');
1802
1803 if (Env::has('search')) {
1804 $res = XDB::query("SELECT id, name, acronym
1805 FROM profile_job_enum
1806 WHERE name LIKE CONCAT('%', {?}, '%') OR acronym LIKE CONCAT('%', {?}, '%')",
1807 Env::t('job'), Env::t('job'));
1808
1809 if ($res->numRows() <= 20) {
1810 $page->assign('jobs', $res->fetchAllAssoc());
1811 } else {
1812 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1813 }
1814
1815 $page->assign('askedJob', Env::v('job'));
1816 return;
1817 }
1818
1819 if (Env::has('edit')) {
1820 S::assert_xsrf_token();
1821 $selectedJob = Env::has('selectedJob');
1822
1823 Phone::deletePhones(0, Phone::LINK_COMPANY, $id);
1824 Address::deleteAddresses(null, Address::LINK_COMPANY, $id);
1825 if (Env::has('change')) {
1826 if (Env::has('newJobId') && Env::i('newJobId') > 0) {
1827 XDB::execute('UPDATE profile_job
1828 SET jobid = {?}
1829 WHERE jobid = {?}',
1830 Env::i('newJobId'), $id);
1831 XDB::execute('DELETE FROM profile_job_enum
1832 WHERE id = {?}',
1833 $id);
1834
1835 $page->trigSuccess("L'entreprise a bien été remplacée.");
1836 } else {
1837 $page->trigError("L'entreprise n'a pas été remplacée car l'identifiant fourni n'est pas valide.");
1838 }
1839 } else {
1840 XDB::execute('UPDATE profile_job_enum
1841 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1842 SIREN_code = {?}, NAF_code = {?}, AX_code = {?}, holdingid = {?}
1843 WHERE id = {?}',
1844 Env::t('name'), Env::t('acronym'), Env::t('url'), Env::t('email'),
1845 (Env::t('SIREN') == 0 ? null : Env::t('SIREN')),
1846 (Env::t('NAF_code') == 0 ? null : Env::t('NAF_code')),
1847 (Env::i('AX_code') == 0 ? null : Env::t('AX_code')),
1848 (Env::i('holdingId') == 0 ? null : Env::t('holdingId')), $id);
1849
1850 $phone = new Phone(array('display' => Env::v('tel'), 'link_id' => $id, 'id' => 0, 'type' => 'fixed',
1851 'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
1852 $fax = new Phone(array('display' => Env::v('fax'), 'link_id' => $id, 'id' => 1, 'type' => 'fax',
1853 'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
1854 $address = new Address(array('jobid' => $id, 'type' => Address::LINK_COMPANY, 'text' => Env::t('address')));
1855 $phone->save();
1856 $fax->save();
1857 $address->save();
1858
1859 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1860 }
1861 }
1862
1863 if (!Env::has('change') && $id != -1) {
1864 $res = XDB::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.SIREN_code AS SIREN, e.NAF_code, e.AX_code,
1865 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1866 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1867 FROM profile_job_enum AS e
1868 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
1869 LEFT JOIN profile_phones AS t ON (t.pid = e.id AND t.link_type = 'hq' AND t.tel_id = 0)
1870 LEFT JOIN profile_phones AS f ON (f.pid = e.id AND f.link_type = 'hq' AND f.tel_id = 1)
1871 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1872 WHERE e.id = {?}",
1873 $id);
1874
1875 if ($res->numRows() == 0) {
1876 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1877 } else {
1878 $page->assign('selectedJob', $res->fetchOneAssoc());
1879 }
1880 }
1881 }
1882
1883 function handler_profile($page)
1884 {
1885 $page->changeTpl('admin/profile.tpl');
1886
1887 if (Post::has('checked')) {
1888 S::assert_xsrf_token();
1889 $res = XDB::iterator('SELECT DISTINCT(pm.pid), pd.public_name
1890 FROM profile_modifications AS pm
1891 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1892 WHERE pm.type = \'self\'');
1893
1894 while ($profile = $res->next()) {
1895 if (Post::has('checked_' . $profile['pid'])) {
1896 XDB::execute('DELETE FROM profile_modifications
1897 WHERE type = \'self\' AND pid = {?}', $profile['pid']);
1898
1899 $page->trigSuccess('Profil de ' . $profile['public_name'] . ' vérifié.');
1900 }
1901 }
1902 }
1903
1904 $res = XDB::iterator('SELECT p.hrpid, pm.pid, pd.directory_name, GROUP_CONCAT(pm.field SEPARATOR \', \') AS field
1905 FROM profile_modifications AS pm
1906 INNER JOIN profiles AS p ON (pm.pid = p.pid)
1907 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1908 WHERE pm.type = \'self\'
1909 GROUP BY pd.directory_name
1910 ORDER BY pd.directory_name');
1911 $page->assign('updates', $res);
1912 }
1913
1914 function handler_phd($page, $promo = null, $validate = false)
1915 {
1916 $page->changeTpl('admin/phd.tpl');
1917 $eduDegrees = DirEnum::getOptions(DirEnum::EDUDEGREES);
1918 $eduDegrees = array_flip($eduDegrees);
1919
1920 if (is_null($promo)) {
1921 $promo_list = XDB::fetchColumn('SELECT DISTINCT(grad_year)
1922 FROM profile_education
1923 WHERE FIND_IN_SET(\'primary\', flags) AND NOT FIND_IN_SET(\'completed\', flags) AND degreeid = {?}
1924 ORDER BY grad_year',
1925 $eduDegrees[Profile::DEGREE_D]);
1926 $page->assign('promo_list', $promo_list);
1927 $page->assign('nothing', count($promo_list) == 0);
1928 return;
1929 }
1930
1931 if ($validate) {
1932 S::assert_xsrf_token();
1933
1934 $list = XDB::iterator('SELECT pe.pid, pd.directory_name
1935 FROM profile_education AS pe
1936 INNER JOIN profile_display AS pd ON (pe.pid = pd.pid)
1937 WHERE FIND_IN_SET(\'primary\', pe.flags) AND NOT FIND_IN_SET(\'completed\', pe.flags)
1938 AND pe.degreeid = {?} AND pe.grad_year = {?}',
1939 $eduDegrees[Profile::DEGREE_D], $promo);
1940 while ($res = $list->next()) {
1941 $pid = $res['pid'];
1942 $name = $res['directory_name'];
1943 if (Post::b('completed_' . $pid)) {
1944 $grad_year = Post::t('grad_year_' . $pid);
1945 XDB::execute('UPDATE profile_education
1946 SET flags = \'primary,completed\', grad_year = {?}
1947 WHERE FIND_IN_SET(\'primary\', flags) AND pid = {?}',
1948 $grad_year, $pid);
1949 XDB::execute('UPDATE profile_display
1950 SET promo = {?}
1951 WHERE pid = {?}',
1952 'D' . $grad_year, $pid);
1953 $page->trigSuccess("Promotion de $name validée.");
1954 }
1955 }
1956 }
1957
1958 $list = XDB::iterator('SELECT pe.pid, pd.directory_name
1959 FROM profile_education AS pe
1960 INNER JOIN profile_display AS pd ON (pe.pid = pd.pid)
1961 WHERE FIND_IN_SET(\'primary\', pe.flags) AND NOT FIND_IN_SET(\'completed\', pe.flags)
1962 AND pe.degreeid = {?} AND pe.grad_year = {?}
1963 ORDER BY pd.directory_name',
1964 $eduDegrees[Profile::DEGREE_D], $promo);
1965 $page->assign('list', $list);
1966 $page->assign('promo', $promo);
1967 }
1968
1969 function handler_add_secondary_edu($page)
1970 {
1971 $page->changeTpl('admin/add_secondary_edu.tpl');
1972
1973 if (!(Post::has('verify') || Post::has('add'))) {
1974 return;
1975 } elseif (!Post::has('people')) {
1976 $page->trigWarning("Aucune information n'a été fournie.");
1977 return;
1978 }
1979
1980 require_once 'name.func.inc.php';
1981 $lines = explode("\n", Post::t('people'));
1982 $separator = Post::t('separator');
1983 $degree = Post::v('degree');
1984 $promotion = Post::i('promotion');
1985 $schoolsList = array_flip(DirEnum::getOptions(DirEnum::EDUSCHOOLS));
1986 $degreesList = array_flip(DirEnum::getOptions(DirEnum::EDUDEGREES));
1987 $edu_id = $schoolsList[Profile::EDU_X];
1988 $degree_id = $degreesList[$degree];
1989
1990 $res = array(
1991 'incomplete' => array(),
1992 'empty' => array(),
1993 'multiple' => array(),
1994 'already' => array(),
1995 'new' => array()
1996 );
1997 $old_pids = array();
1998 $new_pids = array();
1999 foreach ($lines as $line) {
2000 $line = trim($line);
2001 $line_array = explode($separator, $line);
2002 array_walk($line_array, 'trim');
2003 if (count($line_array) != 3) {
2004 $page->trigError("La ligne « $line » est incomplète.");
2005 $res['incomplete'][] = $line;
2006 continue;
2007 }
2008 $cond = new PFC_And(new UFC_NameTokens(split_name_for_search($line_array[0]), array(), false, false, Profile::LASTNAME));
2009 $cond->addChild(new UFC_NameTokens(split_name_for_search($line_array[1]), array(), false, false, Profile::FIRSTNAME));
2010 $cond->addChild(new UFC_Promo('=', UserFilter::DISPLAY, $line_array[2]));
2011 $uf = new UserFilter($cond);
2012 $pid = $uf->getPIDs();
2013 $count = count($pid);
2014 if ($count == 0) {
2015 $page->trigError("La ligne « $line » ne correspond à aucun profil existant.");
2016 $res['empty'][] = $line;
2017 continue;
2018 } elseif ($count > 1) {
2019 $page->trigError("La ligne « $line » correspond à plusieurs profils existant.");
2020 $res['multiple'][] = $line;
2021 continue;
2022 } else {
2023 $count = XDB::fetchOneCell('SELECT COUNT(*) AS count
2024 FROM profile_education
2025 WHERE pid = {?} AND eduid = {?} AND degreeid = {?}',
2026 $pid, $edu_id, $degree_id);
2027 if ($count == 1) {
2028 $res['already'][] = $line;
2029 $old_pids[] = $pid[0];
2030 } else {
2031 $res['new'][] = $line;
2032 $new_pids[] = $pid[0];
2033 }
2034 }
2035 }
2036
2037 $display = array();
2038 foreach ($res as $type => $res_type) {
2039 if (count($res_type) > 0) {
2040 $display = array_merge($display, array('--------------------' . $type . ':'), $res_type);
2041 }
2042 }
2043 $page->assign('people', implode("\n", $display));
2044 $page->assign('promotion', $promotion);
2045 $page->assign('degree', $degree);
2046
2047 if (Post::has('add')) {
2048 $entry_year = $promotion - Profile::educationDuration($degree);
2049
2050 if (Post::b('force_addition')) {
2051 $pids = array_unique(array_merge($old_pids, $new_pids));
2052 } else {
2053 $pids = array_unique($new_pids);
2054
2055 // Updates years.
2056 if (count($old_pids)) {
2057 XDB::execute('UPDATE profile_education
2058 SET entry_year = {?}, grad_year = {?}, promo_year = {?}
2059 WHERE pid IN {?} AND eduid = {?} AND degreeid = {?}',
2060 $entry_year, $promotion, $promotion, $old_pids, $edu_id, $degree_id);
2061 }
2062 }
2063
2064 // Precomputes values common to all users.
2065 $select = XDB::format('MAX(id) + 1, pid, {?}, {?}, {?}, {?}, {?}, \'secondary\'',
2066 $edu_id, $degree_id, $entry_year, $promotion, $promotion );
2067 XDB::startTransaction();
2068 foreach ($pids as $pid) {
2069 XDB::execute('INSERT INTO profile_education (id, pid, eduid, degreeid, entry_year, grad_year, promo_year, flags)
2070 SELECT ' . $select . '
2071 FROM profile_education
2072 WHERE pid = {?}
2073 GROUP BY pid',
2074 $pid);
2075 }
2076 XDB::commit();
2077 }
2078
2079 }
2080
2081 function handler_admin_name($page, $hruid = null)
2082 {
2083 $page->changeTpl('admin/admin_name.tpl');
2084
2085 if (Post::has('id')) {
2086 $user = User::get(Post::t('id'));
2087 if (is_null($user)) {
2088 $page->trigError("L'identifiant donné ne correspond à personne ou est ambigu.");
2089 exit();
2090 }
2091 pl_redirect('admin/name/' . $user->hruid);
2092 }
2093
2094 $user = User::getSilent($hruid);
2095 if (!is_null($user)) {
2096 require_once 'name.func.inc.php';
2097
2098 if ($user->hasProfile()) {
2099 $name_types = array(
2100 'lastname_main' => 'Nom patronymique',
2101 'lastname_marital' => 'Nom marital',
2102 'lastname_ordinary' => 'Nom usuel',
2103 'firstname_main' => 'Prénom',
2104 'firstname_ordinary' => 'Prénom usuel',
2105 'pseudonym' => 'Pseudonyme'
2106 );
2107 $names = XDB::fetchOneAssoc('SELECT lastname_main, lastname_marital, lastname_ordinary,
2108 firstname_main, firstname_ordinary, pseudonym
2109 FROM profile_public_names
2110 WHERE pid = {?}',
2111 $user->profile()->id());
2112 } else {
2113 $name_types = array(
2114 'lastname' => 'Nom',
2115 'firstname' => 'Prénom'
2116 );
2117 $names = XDB::fetchOneAssoc('SELECT lastname, firstname
2118 FROM accounts
2119 WHERE uid = {?}',
2120 $user->id());
2121 }
2122
2123 if (Post::has('correct')) {
2124 $new_names = array();
2125 $update = true;
2126 foreach ($name_types as $key => $fullname) {
2127 $new_names[$key] = Post::t($key);
2128 if (mb_strtolower($new_names[$key]) != mb_strtolower($names[$key])) {
2129 $update = false;
2130 }
2131 }
2132
2133 if ($update) {
2134 if ($user->hasProfile()) {
2135 update_public_names($user->profile()->id(), $new_names);
2136 update_display_names($user->profile(), $new_names);
2137 } else {
2138 $new_names['full_name'] = build_full_name($new_names['firstname'], $new_names['lastname']);
2139 $new_names['directory_name'] = build_directory_name($new_names['firstname'], $new_names['lastname']);
2140 $new_names['sort_name'] = build_sort_name($new_names['firstname'], $new_names['lastname']);
2141 XDB::execute('UPDATE accounts
2142 SET lastname = {?}, firstname = {?}, full_name = {?},
2143 directory_name = {?}, sort_name = {?}
2144 WHERE uid = {?}',
2145 $new_names['lastname'], $new_names['firstname'], $new_names['full_name'],
2146 $new_names['directory_name'], $new_names['sort_name'], $user->id());
2147 }
2148 $page->trigSuccess('Mise à jour réussie.');
2149 } else {
2150 $page->trigError('Seuls des changements de casse sont autorisés ici.');
2151 }
2152 }
2153
2154 if ($user->hasProfile()) {
2155 $names = XDB::fetchOneAssoc('SELECT lastname_main, lastname_marital, lastname_ordinary,
2156 firstname_main, firstname_ordinary, pseudonym
2157 FROM profile_public_names
2158 WHERE pid = {?}',
2159 $user->profile()->id());
2160 } else {
2161 $names = XDB::fetchOneAssoc('SELECT lastname, firstname
2162 FROM accounts
2163 WHERE uid = {?}',
2164 $user->id());
2165 }
2166
2167 foreach ($names as $key => $name) {
2168 $names[$key] = array(
2169 'value' => $name,
2170 'standard' => capitalize_name($name)
2171 );
2172 $names[$key]['different'] = ($names[$key]['value'] != $names[$key]['standard']);
2173 }
2174
2175 $page->assign('uid', $user->id());
2176 $page->assign('hruid', $user->hruid);
2177 $page->assign('names', $names);
2178 $page->assign('name_types', $name_types);
2179 }
2180 }
2181 }
2182
2183 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8:
2184 ?>