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