Merge commit 'origin/fusionax' into account
[platal.git] / modules / admin.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2009 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 class AdminModule extends PLModule
23 {
24 function handlers()
25 {
26 return array(
27 'phpinfo' => $this->make_hook('phpinfo', AUTH_MDP, 'admin'),
28 'get_rights' => $this->make_hook('get_rights', AUTH_MDP, 'admin'),
29 'admin' => $this->make_hook('default', AUTH_MDP, 'admin'),
30 'admin/ax-xorg' => $this->make_hook('ax_xorg', AUTH_MDP, 'admin'),
31 'admin/dead-but-active' => $this->make_hook('dead_but_active', AUTH_MDP, 'admin'),
32 'admin/deaths' => $this->make_hook('deaths', AUTH_MDP, 'admin'),
33 'admin/downtime' => $this->make_hook('downtime', AUTH_MDP, 'admin'),
34 'admin/homonyms' => $this->make_hook('homonyms', AUTH_MDP, 'admin'),
35 'admin/logger' => $this->make_hook('logger', AUTH_MDP, 'admin'),
36 'admin/logger/actions' => $this->make_hook('logger_actions', AUTH_MDP, 'admin'),
37 'admin/postfix/blacklist' => $this->make_hook('postfix_blacklist', AUTH_MDP, 'admin'),
38 'admin/postfix/delayed' => $this->make_hook('postfix_delayed', AUTH_MDP, 'admin'),
39 'admin/postfix/regexp_bounces' => $this->make_hook('postfix_regexpsbounces', AUTH_MDP, 'admin'),
40 'admin/postfix/whitelist' => $this->make_hook('postfix_whitelist', AUTH_MDP, 'admin'),
41 'admin/mx/broken' => $this->make_hook('mx_broken', AUTH_MDP, 'admin'),
42 'admin/skins' => $this->make_hook('skins', AUTH_MDP, 'admin'),
43 'admin/synchro_ax' => $this->make_hook('synchro_ax', AUTH_MDP, 'admin'),
44 'admin/user' => $this->make_hook('user', AUTH_MDP, 'admin'),
45 'admin/promo' => $this->make_hook('promo', AUTH_MDP, 'admin'),
46 'admin/validate' => $this->make_hook('validate', AUTH_MDP, 'admin'),
47 'admin/validate/answers' => $this->make_hook('validate_answers', AUTH_MDP, 'admin'),
48 'admin/wiki' => $this->make_hook('wiki', AUTH_MDP, 'admin'),
49 'admin/ipwatch' => $this->make_hook('ipwatch', AUTH_MDP, 'admin'),
50 'admin/icons' => $this->make_hook('icons', AUTH_MDP, 'admin'),
51 'admin/accounts' => $this->make_hook('accounts', AUTH_MDP, 'admin'),
52 'admin/account/types' => $this->make_hook('account_types', AUTH_MDP, 'admin'),
53 'admin/jobs' => $this->make_hook('jobs', AUTH_MDP, 'admin'),
54 );
55 }
56
57 function handler_phpinfo(&$page)
58 {
59 phpinfo();
60 exit;
61 }
62
63 function handler_get_rights(&$page, $level)
64 {
65 if (S::suid()) {
66 $page->kill('Déjà en SUID');
67 }
68 $user =& S::user();
69 Platal::session()->startSUID($user, $level);
70
71 pl_redirect('/');
72 }
73
74 function handler_default(&$page)
75 {
76 $page->changeTpl('admin/index.tpl');
77 $page->setTitle('Administration');
78 }
79
80 function handler_postfix_delayed(&$page)
81 {
82 $page->changeTpl('admin/postfix_delayed.tpl');
83 $page->setTitle('Administration - Postfix : Retardés');
84
85 if (Env::has('del')) {
86 $crc = Env::v('crc');
87 XDB::execute("UPDATE postfix_mailseen SET release = 'del' WHERE crc = {?}", $crc);
88 $page->trigSuccess($crc . " verra tous ses emails supprimés&nbsp;!");
89 } elseif (Env::has('ok')) {
90 $crc = Env::v('crc');
91 XDB::execute("UPDATE postfix_mailseen SET release = 'ok' WHERE crc = {?}", $crc);
92 $page->trigSuccess($crc . " a le droit de passer&nbsp;!");
93 }
94
95 $sql = XDB::iterator(
96 "SELECT crc, nb, update_time, create_time,
97 FIND_IN_SET('del', p.release) AS del,
98 FIND_IN_SET('ok', p.release) AS ok
99 FROM postfix_mailseen AS p
100 WHERE nb >= 30
101 ORDER BY p.release != ''");
102
103 $page->assign_by_ref('mails', $sql);
104 }
105
106 function handler_postfix_regexpsbounces(&$page, $new = null) {
107 $page->changeTpl('admin/emails_bounces_re.tpl');
108 $page->setTitle('Administration - Postfix : Regexps Bounces');
109 $page->assign('new', $new);
110
111 if (Post::has('submit')) {
112 foreach (Env::v('lvl') as $id=>$val) {
113 XDB::query(
114 "REPLACE INTO emails_bounces_re (id,pos,lvl,re,text) VALUES ({?}, {?}, {?}, {?}, {?})",
115 $id, $_POST['pos'][$id], $_POST['lvl'][$id], $_POST['re'][$id], $_POST['text'][$id]
116 );
117 }
118 }
119
120 $page->assign('bre', XDB::iterator("SELECT * FROM emails_bounces_re ORDER BY pos"));
121 }
122
123 // {{{ logger view
124
125 /** Retrieves the available days for a given year and month.
126 * Obtain a list of days of the given month in the given year
127 * that are within the range of dates that we have log entries for.
128 *
129 * @param integer year
130 * @param integer month
131 * @return array days in that month we have log entries covering.
132 * @private
133 */
134 function _getDays($year, $month)
135 {
136 // give a 'no filter' option
137 $months[0] = "----";
138
139 if ($year && $month) {
140 $day_max = Array(-1, 31, checkdate(2, 29, $year) ? 29 : 28 , 31,
141 30, 31, 30, 31, 31, 30, 31, 30, 31);
142 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
143 MONTH(MAX(start)), MONTH(MIN(start)),
144 DAYOFMONTH(MAX(start)),
145 DAYOFMONTH(MIN(start))
146 FROM #logger#.sessions");
147 list($ymax, $ymin, $mmax, $mmin, $dmax, $dmin) = $res->fetchOneRow();
148
149 if (($year < $ymin) || ($year == $ymin && $month < $mmin)) {
150 return array();
151 }
152
153 if (($year > $ymax) || ($year == $ymax && $month > $mmax)) {
154 return array();
155 }
156
157 $min = ($year==$ymin && $month==$mmin) ? intval($dmin) : 1;
158 $max = ($year==$ymax && $month==$mmax) ? intval($dmax) : $day_max[$month];
159
160 for($i = $min; $i<=$max; $i++) {
161 $days[$i] = $i;
162 }
163 }
164 return $days;
165 }
166
167
168 /** Retrieves the available months for a given year.
169 * Obtains a list of month numbers that are within the timeframe that
170 * we have log entries for.
171 *
172 * @param integer year
173 * @return array List of month numbers we have log info for.
174 * @private
175 */
176 function _getMonths($year)
177 {
178 // give a 'no filter' option
179 $months[0] = "----";
180
181 if ($year) {
182 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
183 MONTH(MAX(start)), MONTH(MIN(start))
184 FROM #logger#.sessions");
185 list($ymax, $ymin, $mmax, $mmin) = $res->fetchOneRow();
186
187 if (($year < $ymin) || ($year > $ymax)) {
188 return array();
189 }
190
191 $min = $year == $ymin ? intval($mmin) : 1;
192 $max = $year == $ymax ? intval($mmax) : 12;
193
194 for($i = $min; $i<=$max; $i++) {
195 $months[$i] = $i;
196 }
197 }
198 return $months;
199 }
200
201
202 /** Retrieves the available years.
203 * Obtains a list of years that we have log entries covering.
204 *
205 * @return array years we have log entries for.
206 * @private
207 */
208 function _getYears()
209 {
210 // give a 'no filter' option
211 $years[0] = "----";
212
213 // retrieve available years
214 $res = XDB::query("select YEAR(MAX(start)), YEAR(MIN(start)) FROM #logger#.sessions");
215 list($max, $min) = $res->fetchOneRow();
216
217 for($i = intval($min); $i<=$max; $i++) {
218 $years[$i] = $i;
219 }
220 return $years;
221 }
222
223
224 /** Make a where clause to get a user's sessions.
225 * Prepare the where clause request that will retrieve the sessions.
226 *
227 * @param $year INTEGER Only get log entries made during the given year.
228 * @param $month INTEGER Only get log entries made during the given month.
229 * @param $day INTEGER Only get log entries made during the given day.
230 * @param $uid INTEGER Only get log entries referring to the given user ID.
231 *
232 * @return STRING the WHERE clause of a query, including the 'WHERE' keyword
233 * @private
234 */
235 function _makeWhere($year, $month, $day, $uid)
236 {
237 // start constructing the "where" clause
238 $where = array();
239
240 if ($uid)
241 array_push($where, "uid='$uid'");
242
243 // we were given at least a year
244 if ($year) {
245 if ($day) {
246 $dmin = mktime(0, 0, 0, $month, $day, $year);
247 $dmax = mktime(0, 0, 0, $month, $day+1, $year);
248 } elseif ($month) {
249 $dmin = mktime(0, 0, 0, $month, 1, $year);
250 $dmax = mktime(0, 0, 0, $month+1, 1, $year);
251 } else {
252 $dmin = mktime(0, 0, 0, 1, 1, $year);
253 $dmax = mktime(0, 0, 0, 1, 1, $year+1);
254 }
255 $where[] = "start >= " . date("Ymd000000", $dmin);
256 $where[] = "start < " . date("Ymd000000", $dmax);
257 }
258
259 if (!empty($where)) {
260 return ' WHERE ' . implode($where, " AND ");
261 } else {
262 return '';
263 }
264 // WE know it's totally reversed, so better use array_reverse than a SORT BY start DESC
265 }
266
267 // }}}
268
269 function handler_logger(&$page, $action = null, $arg = null) {
270 if ($action == 'session') {
271
272 // we are viewing a session
273 $res = XDB::query("SELECT ls.*, a.alias AS username, sa.alias AS suer
274 FROM #logger#.sessions AS ls
275 LEFT JOIN #x4dat#.aliases AS a ON (a.id = ls.uid AND a.type='a_vie')
276 LEFT JOIN #x4dat#.aliases AS sa ON (sa.id = ls.suid AND sa.type='a_vie')
277 WHERE ls.id = {?}", $arg);
278
279 $page->assign('session', $a = $res->fetchOneAssoc());
280
281 $res = XDB::iterator('SELECT a.text, e.data, e.stamp
282 FROM #logger#.events AS e
283 LEFT JOIN #logger#.actions AS a ON e.action=a.id
284 WHERE e.session={?}', $arg);
285 while ($myarr = $res->next()) {
286 $page->append('events', $myarr);
287 }
288
289 } else {
290 $loguser = $action == 'user' ? $arg : Env::v('loguser');
291
292 $res = XDB::query('SELECT id FROM aliases WHERE alias={?}',
293 $loguser);
294 $loguid = $res->fetchOneCell();
295
296 if ($loguid) {
297 $year = Env::i('year');
298 $month = Env::i('month');
299 $day = Env::i('day');
300 } else {
301 $year = Env::i('year', intval(date('Y')));
302 $month = Env::i('month', intval(date('m')));
303 $day = Env::i('day', intval(date('d')));
304 }
305
306 if (!$year)
307 $month = 0;
308 if (!$month)
309 $day = 0;
310
311 // smarty assignments
312 // retrieve available years
313 $page->assign('years', $this->_getYears());
314 $page->assign('year', $year);
315
316 // retrieve available months for the current year
317 $page->assign('months', $this->_getMonths($year));
318 $page->assign('month', $month);
319
320 // retrieve available days for the current year and month
321 $page->assign('days', $this->_getDays($year, $month));
322 $page->assign('day', $day);
323
324 $page->assign('loguser', $loguser);
325 // smarty assignments
326
327 if ($loguid || $year) {
328
329 // get the requested sessions
330 $where = $this->_makeWhere($year, $month, $day, $loguid);
331 $select = "SELECT s.id, s.start, s.uid,
332 a.alias as username
333 FROM #logger#.sessions AS s
334 LEFT JOIN #x4dat#.aliases AS a ON (a.id = s.uid AND a.type='a_vie')
335 $where
336 ORDER BY start DESC";
337 $res = XDB::iterator($select);
338
339 $sessions = array();
340 while ($mysess = $res->next()) {
341 $mysess['events'] = array();
342 $sessions[$mysess['id']] = $mysess;
343 }
344 array_reverse($sessions);
345
346 // attach events
347 $sql = "SELECT s.id, a.text
348 FROM #logger#.sessions AS s
349 LEFT JOIN #logger#.events AS e ON(e.session=s.id)
350 INNER JOIN #logger#.actions AS a ON(a.id=e.action)
351 $where";
352
353 $res = XDB::iterator($sql);
354 while ($event = $res->next()) {
355 array_push($sessions[$event['id']]['events'], $event['text']);
356 }
357 $page->assign_by_ref('sessions', $sessions);
358 } else {
359 $page->assign('msg_nofilters', "Sélectionner une annuée et/ou un utilisateur");
360 }
361 }
362
363 $page->changeTpl('admin/logger-view.tpl');
364
365 $page->setTitle('Administration - Logs des sessions');
366 }
367
368 function handler_user(&$page, $login = false)
369 {
370 global $globals;
371 $page->changeTpl('admin/user.tpl');
372 $page->setTitle('Administration - Compte');
373
374 if (S::suid()) {
375 $page->kill("Déjà en SUID&nbsp;!!!");
376 }
377
378 // Loads the user identity using the environment.
379 $user = User::get($login);
380 if (!$user) {
381 return;
382 }
383
384 $login = $user->login();
385 $registered = ($user->state != 'pending');
386
387 // Form processing
388 if (!empty($_POST)) {
389 S::assert_xsrf_token();
390 if (Post::has('uid') && Post::i('uid') != $user->id()) {
391 $page->kill('Une erreur s\'est produite');
392 }
393 }
394
395 // Handles specific requests (AX sync, su, ...).
396 if(Post::has('logs_account')) {
397 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
398 }
399
400 if(Post::has('su_button') && $registered) {
401 if (!Platal::session()->startSUID($user)) {
402 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->login());
403 } else {
404 pl_redirect("");
405 }
406 }
407
408 // Account Form {{{
409 $to_update = array();
410 if (Post::has('disable_weak_access')) {
411 $to_update['weak_password'] = null;
412 } else if (Post::has('update_account')) {
413 if (Post::s('full_name') != $user->fullName()) {
414 // XXX: Update profile if a profile is associated
415 $to_update['full_name'] = Post::s('full_name');
416 }
417 if (Post::s('display_name') != $user->displayName()) {
418 // XXX: Update profile if a profile is associated
419 $to_update['display_name'] = Post::s('display_name');
420 }
421 if (Post::s('sex') != ($user->isFemale() ? 'female' : 'male')) {
422 $to_update['sex'] = Post::s('sex');
423 }
424 if (!Post::blank('hashpass')) {
425 $to_update['password'] = Post::s('hashpass');
426 // TODO: Propagate the password update to GoogleApps, when required. Eg:
427 // $account = new GoogleAppsAccount($user);
428 // if ($account->active() && $account->sync_password) {
429 // $account->set_password($pass_encrypted);
430 // }
431 }
432 if (!Post::blank('weak_password')) {
433 $to_update['weak_password'] = Post::s('weak_password');
434 }
435 if (Post::i('token_access', 0) != ($user->token_access ? 1 : 0)) {
436 $to_update['token'] = Post::i('token_access') ? rand_url_id(16) : null;
437 }
438 if (Post::i('skin', 0) != $user->skin) {
439 $to_update['skin'] = Post::i('skin', 0);
440 if ($to_update['skin'] == 0) {
441 $to_update['skin'] = null;
442 }
443 }
444 if (Post::s('state') != $user->state) {
445 $to_update['state'] = Post::s('state');
446 }
447 if (Post::i('is_admin', 0) != ($user->is_admin ? 1 : 0)) {
448 $to_update['is_admin'] = Post::b('is_admin');
449 }
450 if (Post::s('type') != $user->type) {
451 $to_update['type'] = Post::s('type');
452 }
453 if (Post::i('watch', 0) != ($user->watch ? 1 : 0)) {
454 $to_update['flags'] = new PlFlagset();
455 $to_update['flags']->addFlag('watch', Post::i('watch'));
456 }
457 if (Post::t('comment') != $user->comment) {
458 $to_update['comment'] = Post::blank('comment') ? null : Post::t('comment');
459 }
460 }
461 if (!empty($to_update)) {
462 // TODO: fetch the initial values of the fields, and eventually send
463 // a summary of the changes to an admin.
464 $set = array();
465 foreach ($to_update as $k => $value) {
466 $set[] = XDB::format($k . ' = {?}', $value);
467 }
468 XDB::execute('UPDATE accounts
469 SET ' . implode(', ', $set) . '
470 WHERE uid = ' . XDB::format('{?}', $user->id()));
471 $page->trigSuccess('Données du compte mise à jour avec succès');
472 $user = User::getWithUID($user->id());
473 }
474 // }}}
475
476 // Profile form {{{
477 if (Post::has('add_profile') || Post::has('del_profile') || Post::has('owner')) {
478 if (Post::i('del_profile', 0) != 0) {
479 XDB::execute('DELETE FROM account_profiles
480 WHERE uid = {?} AND pid = {?}',
481 $user->id(), Post::i('del_profile'));
482 } else if (!Post::blank('new_profile')) {
483 $profile = Profile::get(Post::t('new_profile'));
484 if (!$profile) {
485 $page->trigError('Le profil ' . Post::t('new_profile') . ' n\'existe pas');
486 } else {
487 XDB::execute('INSERT IGNORE INTO account_profiles (uid, pid)
488 VALUES ({?}, {?})',
489 $user->id(), $profile->id());
490 }
491 }
492 XDB::execute('UPDATE account_profiles
493 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
494 WHERE uid = {?}',
495 Post::i('owner'), $user->id());
496 }
497 // }}}
498
499 // Email forwards form {{{
500 require_once("emails.inc.php");
501 $redirect = ($registered ? new Redirect($user) : null);
502 if (Post::has('add_fwd')) {
503 $email = Post::t('email');
504 if (!isvalid_email_redirection($email)) {
505 $page->trigError("Email non valide: $email");
506 } else {
507 $redirect->add_email($email);
508 $page->trigSuccess("Ajout de $email effectué");
509 }
510 } else if (!Post::blank('del_fwd')) {
511 $redirect->delete_email(Post::t('del_fwd'));
512 } else if (!Post::blank('activate_fwd')) {
513 $redirect->modify_one_email(Post::t('activate_fwd', true));
514 } else if (!Post::blank('deactivate_fwd')) {
515 $redirect->modify_one_email(Post::t('deactivate_fwd', false));
516 } else if (Post::has('disable_fwd')) {
517 $redirect->disable();
518 } else if (Post::has('enable_fwd')) {
519 $redirect->enable();
520 } else if (!Post::blank('clean_fwd')) {
521 $redirect->clean_errors(Post::t('clean_fwd'));
522 }
523 // }}}
524
525 // Email alias form {{{
526 if (Post::has('add_alias')) {
527 // Splits new alias in user and fqdn.
528 $alias = Env::t('email');
529 if (strpos($alias, '@') !== false) {
530 list($alias, $domain) = explode('@', $alias);
531 } else {
532 $domain = $globals->mail->domain;
533 }
534
535 // Checks for alias' user validity.
536 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
537 $page->trigError("'$alias' n'est pas un alias valide");
538 }
539
540 // Eventually adds the alias to the right domain.
541 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
542 $req = new AliasReq($user, $alias, 'Admin request', false);
543 if ($req->commit()) {
544 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué");
545 } else {
546 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué");
547 }
548 } elseif ($domain == $globals->mail->domain || $domain == $globals->mail->domain2) {
549 $res = XDB::execute("INSERT INTO aliases (id, alias, type)
550 VALUES ({?}, {?}, 'alias')",
551 $user->id(), $alias);
552 $page->trigSuccess("Nouvel alias '$alias' ajouté");
553 } else {
554 $page->trigError("Le domaine '$domain' n'est pas valide");
555 }
556 } else if (!Post::blank('del_alias')) {
557 XDB::execute("DELETE FROM aliases
558 WHERE id = {?} AND alias = {?} AND
559 type NOT IN ('a_vie', 'homonyme')",
560 $user->id(), $val);
561 XDB::execute("UPDATE emails
562 SET rewrite = ''
563 WHERE uid = {?} AND rewrite LIKE CONCAT({?}, '@%')",
564 $user->id(), $val);
565 fix_bestalias($user);
566 $page->trigSuccess("L'alias '$val' a été supprimé");
567 } else if (!Post::blank('best')) {
568 XDB::execute("UPDATE aliases
569 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
570 WHERE id = {?}", $user->id());
571 XDB::execute("UPDATE aliases
572 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
573 WHERE id = {?} AND alias = {?}", $user->id(), $val);
574 // As having a non-null bestalias value is critical in
575 // plat/al's code, we do an a posteriori check on the
576 // validity of the bestalias.
577 fix_bestalias($user);
578 }
579 // }}}
580
581 // Forum form {{{
582 if (Post::has('b_edit')) {
583 XDB::execute("DELETE FROM forum_innd
584 WHERE uid = {?}", $user->id());
585 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
586 XDB::execute("INSERT INTO forum_innd
587 SET ipmin = '0', ipmax = '4294967295',
588 write_perm = {?}, read_perm = {?},
589 comment = {?}, priority = '200', uid = {?}",
590 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
591 }
592 }
593 // }}}
594
595
596 $page->addJsLink('ui.core.js');
597 $page->addJsLink('ui.tabs.js');
598
599 // Displays last login and last host information.
600 $res = XDB::query("SELECT start, host
601 FROM #logger#.sessions
602 WHERE uid = {?} AND suid = 0
603 ORDER BY start DESC
604 LIMIT 1", $user->id());
605 list($lastlogin,$host) = $res->fetchOneRow();
606 $page->assign('lastlogin', $lastlogin);
607 $page->assign('host', $host);
608
609 // Display active aliases.
610 $page->assign('virtuals', $user->emailAliases());
611 $page->assign('aliases', XDB::iterator("SELECT alias, type='a_vie' AS for_life,
612 FIND_IN_SET('bestalias',flags) AS best, expire
613 FROM aliases
614 WHERE id = {?} AND type != 'homonyme'
615 ORDER BY type != 'a_vie'", $user->id()));
616 $page->assign('account_types', XDB::iterator('SELECT * FROM account_types ORDER BY type'));
617 $page->assign('skins', XDB::iterator('SELECT id, name FROM skins ORDER BY name'));
618 $page->assign('profiles', XDB::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
619 FROM account_profiles AS ap
620 INNER JOIN profiles AS p ON (ap.pid = p.pid)
621 WHERE ap.uid = {?}', $user->id()));
622
623 // Displays email redirection and the general profile.
624 if ($registered && $redirect) {
625 $page->assign('emails', $redirect->emails);
626 }
627
628 $page->assign('user', $user);
629
630 // Displays forum bans.
631 $res = XDB::query("SELECT write_perm, read_perm, comment
632 FROM forum_innd
633 WHERE uid = {?}", $user->id());
634 $bans = $res->fetchOneAssoc();
635 $page->assign('bans', $bans);
636 }
637
638 function getHruid($line, $key, $relation)
639 {
640 $prenom = CSVImporter::getValue($line, 'prenom', $relation['prenom']);
641 $nom = CSVImporter::getValue($line, 'nom', $relation['nom']);
642 $promo = CSVImporter::getValue($line, 'promo', $relation['promo']);
643
644 if ($prenom != 'NULL' && $nom != 'NULL' && $promo != 'NULL') {
645 return make_forlife($prenom, $nom, $promo);
646 }
647 return null;
648 }
649
650 function getMatricule($line, $key, $relation)
651 {
652 $mat = $line['matricule'];
653 $year = intval(substr($mat, 0, 3));
654 $rang = intval(substr($mat, 3, 3));
655 if ($year > 200) { $year /= 10; };
656 if ($year < 96) {
657 return null;
658 } else {
659 return sprintf('%04u%04u', 1900+$year, $rang);
660 }
661 }
662
663 function handler_promo(&$page, $action = null, $promo = null)
664 {
665 if (Env::has('promo')) {
666 if(Env::i('promo') > 1900 && Env::i('promo') < 2050) {
667 $action = Env::v('valid_promo') == 'Ajouter des membres' ? 'add' : 'ax';
668 pl_redirect('admin/promo/' . $action . '/' . Env::i('promo'));
669 } else {
670 $page->trigError('Promotion non valide.');
671 }
672 }
673
674 $page->changeTpl('admin/promo.tpl');
675 if ($promo > 1900 && $promo < 2050 && ($action == 'add' || $action == 'ax')) {
676 $page->assign('promo', $promo);
677 } else {
678 return;
679 }
680
681 $importer = new CSVImporter('auth_user_md5', 'matricule');
682 $importer->registerFunction('matricule', 'matricule Ecole vers X.org', array($this, 'getMatricule'));
683 switch ($action) {
684 case 'add':
685 $fields = array('hruid', 'nom', 'nom_ini', 'prenom', 'naissance_ini',
686 'prenom_ini', 'promo', 'promo_sortie', 'flags',
687 'matricule', 'matricule_ax', 'perms');
688 $importer->forceValue('hruid', array($this, 'getHruid'));
689 $importer->forceValue('promo', $promo);
690 $importer->forceValue('promo_sortie', $promo + 3);
691 break;
692 case 'ax':
693 $fields = array('matricule', 'matricule_ax');
694 break;
695 }
696 $importer->apply($page, "admin/promo/$action/$promo", $fields);
697 }
698
699 function handler_homonyms(&$page, $op = 'list', $target = null)
700 {
701 $page->changeTpl('admin/homonymes.tpl');
702 $page->setTitle('Administration - Homonymes');
703 $this->load("homonyms.inc.php");
704
705 if ($target) {
706 $user = User::getSilent($target);
707 if (!$user || !($loginbis = select_if_homonyme($user))) {
708 $target = 0;
709 } else {
710 $page->assign('user', $user);
711 $page->assign('loginbis',$loginbis);
712 }
713 }
714
715 $page->assign('op', $op);
716 $page->assign('target', $target);
717
718 // on a un $target valide, on prepare les mails
719 if ($target) {
720 // on examine l'op a effectuer
721 switch ($op) {
722 case 'mail':
723 S::assert_xsrf_token();
724
725 send_warning_homonyme($user, $loginbis);
726 switch_bestalias($user, $loginbis);
727 $op = 'list';
728 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
729 break;
730
731 case 'correct':
732 S::assert_xsrf_token();
733
734 switch_bestalias($user, $loginbis);
735 XDB::execute("UPDATE aliases
736 SET type = 'homonyme', expire=NOW()
737 WHERE alias = {?}", $loginbis);
738 XDB::execute("REPLACE INTO homonymes (homonyme_id,user_id)
739 VALUES ({?}, {?})", $target, $target);
740 send_robot_homonyme($user, $loginbis);
741 $op = 'list';
742 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
743 break;
744 }
745 }
746
747 if ($op == 'list') {
748 $res = XDB::iterator(
749 "SELECT a.alias AS homonyme, s.alias AS forlife,
750 IF(h.homonyme_id = s.id, a.expire, NULL) AS expire,
751 IF(h.homonyme_id = s.id, a.type, NULL) AS type,
752 ac.uid AS user_id
753 FROM aliases AS a
754 LEFT JOIN homonymes AS h ON (h.homonyme_id = a.id)
755 INNER JOIN aliases AS s ON (s.id = h.user_id AND s.type='a_vie')
756 INNER JOIN accounts AS ac ON (ac.uid = a.id)
757 WHERE a.type = 'homonyme' OR a.expire != ''
758 ORDER BY a.alias, forlife");
759 $hnymes = Array();
760 while ($tab = $res->next()) {
761 $hnymes[$tab['homonyme']][] = $tab;
762 }
763 $page->assign_by_ref('hnymes',$hnymes);
764 }
765 }
766
767 function handler_deaths(&$page, $promo = 0, $validate = false)
768 {
769 $page->changeTpl('admin/deces_promo.tpl');
770 $page->setTitle('Administration - Deces');
771
772 if (!$promo) {
773 $promo = Env::t('promo', 'X1923');
774 }
775 $page->assign('promo', $promo);
776 if (!$promo) {
777 return;
778 }
779
780 if ($validate) {
781 S::assert_xsrf_token();
782
783 $res = XDB::iterRow('SELECT p.hrpid, pd.directory_name, p.deathdate
784 FROM profiles AS p
785 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
786 WHERE pd.promo = {?}', $promo);
787 while (list($pid, $name, $death) = $res->next()) {
788 $val = Env::v($pid);
789 if($val == $deces || empty($val)) {
790 continue;
791 }
792
793 XDB::execute('UPDATE profiles
794 SET deathdate = {?}, deathdate_rec = NOW()
795 WHERE hrpid = {?}', $val, $pid);
796 $page->trigSuccess('Ajout du décès de ' . $name . ' le ' . $val . '.');
797 if($death == '0000-00-00' || empty($death)) {
798 // TODO: FIX THIS DEPRECATED CALL
799 require_once('user.func.inc.php');
800 user_clear_all_subs($uid, false); // by default, dead ppl do not loose their email
801 }
802 }
803 }
804
805 $res = XDB::iterator('SELECT p.hrpid, pd.directory_name, p.deathdate
806 FROM profiles AS p
807 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
808 WHERE pd.promo = {?}
809 ORDER BY pd.sort_name', $promo);
810 $page->assign('decedes', $res);
811 }
812
813 function handler_dead_but_active(&$page)
814 {
815 $page->changeTpl('admin/dead_but_active.tpl');
816 $page->setTitle('Administration - Décédés');
817
818 $res = XDB::iterator(
819 "SELECT a.hruid, pd.promo, p.ax_id, pd.directory_name, p.deathdate, DATE(MAX(s.start)) AS last
820 FROM #x4dat#.accounts AS a
821 INNER JOIN #x4dat#.account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET('owner', ap.perms))
822 INNER JOIN #x4dat#.profiles AS p ON (p.pid = ap.pid)
823 INNER JOIN #x4dat#.profile_display AS pd ON (pd.pid = p.pid)
824 LEFT JOIN #logger#.sessions AS s ON (s.uid = a.uid AND suid = 0)
825 WHERE a.state = 'active' AND p.deathdate IS NOT NULL
826 GROUP BY a.uid
827 ORDER BY pd.promo, pd.sort_name");
828 $page->assign('dead', $res);
829 }
830
831 function handler_validate(&$page, $action = 'list', $id = null)
832 {
833 $page->changeTpl('admin/valider.tpl');
834 $page->setTitle('Administration - Valider une demande');
835 $page->addCssLink('nl.css');
836 $page->addJsLink('ajax.js');
837 require_once("validations.inc.php");
838
839
840 if ($action == 'edit' and !is_null($id)) {
841 $page->assign('preview_id', $id);
842 }
843
844 if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
845 S::assert_xsrf_token();
846
847 $req = Validate::get_typed_request(Env::v('uid'), Env::v('type'), Env::v('stamp'));
848 if ($req) {
849 $req->handle_formu();
850 } else {
851 $page->trigWarning('La validation a déjà été effectuée.');
852 }
853 }
854
855 $r = XDB::iterator('SHOW COLUMNS FROM requests_answers');
856 while (($a = $r->next()) && $a['Field'] != 'category');
857 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
858
859 $hidden = array();
860 $res = XDB::query('SELECT hidden_requests FROM requests_hidden WHERE user_id = {?}', S::v('uid'));
861 $hide_requests = $res->fetchOneCell();
862 if (Post::has('hide')) {
863 $hide = array();
864 foreach ($categories as $cat)
865 if (!Post::v($cat)) {
866 $hidden[$cat] = 1;
867 $hide[] = $cat;
868 }
869 $hide_requests = join(',', $hide);
870 XDB::query('REPLACE INTO requests_hidden (user_id, hidden_requests) VALUES({?}, {?})',
871 S::v('uid'), $hide_requests);
872 } elseif ($hide_requests) {
873 foreach (explode(',', $hide_requests) as $hide_type)
874 $hidden[$hide_type] = true;
875 }
876 $page->assign('hide_requests', $hidden);
877
878 // Update the count of item to validate here... useful in development configuration
879 // where several copies of the site use the same DB, but not the same "dynamic configuration"
880 global $globals;
881 $globals->updateNbValid();
882 $page->assign('vit', new ValidateIterator());
883 }
884
885 function handler_validate_answers(&$page, $action = 'list', $id = null)
886 {
887 $page->setTitle('Administration - Réponses automatiques de validation');
888 $page->assign('title', 'Gestion des réponses automatiques');
889 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
890 $table_editor->describe('category','catégorie',true);
891 $table_editor->describe('title','titre',true);
892 $table_editor->describe('answer','texte',false);
893 $table_editor->apply($page, $action, $id);
894 }
895
896 function handler_skins(&$page, $action = 'list', $id = null)
897 {
898 $page->setTitle('Administration - Skins');
899 $page->assign('title', 'Gestion des skins');
900 $table_editor = new PLTableEditor('admin/skins','skins','id');
901 $table_editor->describe('name','nom',true);
902 $table_editor->describe('skin_tpl','nom du template',true);
903 $table_editor->describe('auteur','auteur',false);
904 $table_editor->describe('comment','commentaire',true);
905 $table_editor->describe('date','date',false);
906 $table_editor->describe('ext','extension du screenshot',false);
907 $table_editor->apply($page, $action, $id);
908 }
909
910 function handler_postfix_blacklist(&$page, $action = 'list', $id = null)
911 {
912 $page->setTitle('Administration - Postfix : Blacklist');
913 $page->assign('title', 'Blacklist de postfix');
914 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true);
915 $table_editor->describe('reject_text','Texte de rejet',true);
916 $table_editor->describe('email','email',true);
917 $table_editor->apply($page, $action, $id);
918 }
919
920 function handler_postfix_whitelist(&$page, $action = 'list', $id = null)
921 {
922 $page->setTitle('Administration - Postfix : Whitelist');
923 $page->assign('title', 'Whitelist de postfix');
924 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true);
925 $table_editor->describe('email','email',true);
926 $table_editor->apply($page, $action, $id);
927 }
928
929 function handler_mx_broken(&$page, $action = 'list', $id = null)
930 {
931 $page->setTitle('Administration - MX Défaillants');
932 $page->assign('title', 'MX Défaillant');
933 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true);
934 $table_editor->describe('host', 'Masque', true);
935 $table_editor->describe('state', 'Niveau', true);
936 $table_editor->describe('text', 'Description du problème', false);
937 $table_editor->apply($page, $action, $id);
938 }
939
940 function handler_logger_actions(&$page, $action = 'list', $id = null)
941 {
942 $page->setTitle('Administration - Actions');
943 $page->assign('title', 'Gestion des actions de logger');
944 $table_editor = new PLTableEditor('admin/logger/actions','#logger#.actions','id');
945 $table_editor->describe('text','intitulé',true);
946 $table_editor->describe('description','description',true);
947 $table_editor->apply($page, $action, $id);
948 }
949
950 function handler_downtime(&$page, $action = 'list', $id = null)
951 {
952 $page->setTitle('Administration - Coupures');
953 $page->assign('title', 'Gestion des coupures');
954 $table_editor = new PLTableEditor('admin/downtime','coupures','id');
955 $table_editor->describe('debut','date',true);
956 $table_editor->describe('duree','durée',false);
957 $table_editor->describe('resume','résumé',true);
958 $table_editor->describe('services','services affectés',true);
959 $table_editor->describe('description','description',false);
960 $table_editor->apply($page, $action, $id);
961 }
962
963 function handler_account_types(&$page, $action = 'list', $id = null)
964 {
965 $page->setTitle('Administration - Types de comptes');
966 $page->assign('title', 'Gestion des types de comptes');
967 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true);
968 $table_editor->describe('type', 'Catégorie', true);
969 $table_editor->describe('perms', 'Permissions associées', true);
970 $table_editor->apply($page, $action, $id);
971 }
972
973 function handler_wiki(&$page, $action = 'list', $wikipage = null, $wikipage2 = null)
974 {
975 if (S::hasAuthToken()) {
976 $page->setRssLink('Changement Récents',
977 '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::v('token'));
978 }
979
980 // update wiki perms
981 if ($action == 'update') {
982 S::assert_xsrf_token();
983
984 $perms_read = Post::v('read');
985 $perms_edit = Post::v('edit');
986 if ($perms_read || $perms_edit) {
987 foreach ($_POST as $wiki_page => $val) {
988 if ($val == 'on') {
989 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
990 if ($wp->setPerms($perms_read ? $perms_read : $wp->readPerms(),
991 $perms_edit ? $perms_edit : $wp->writePerms())) {
992 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
993 } else {
994 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
995 }
996 }
997 }
998 }
999 } else if ($action != 'list' && !empty($wikipage)) {
1000 $wp = new PlWikiPage($wikipage);
1001 S::assert_xsrf_token();
1002
1003 if ($action == 'delete') {
1004 if ($wp->delete()) {
1005 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1006 } else {
1007 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1008 }
1009 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1010 if ($changedLinks = $wp->rename($wikipage2)) {
1011 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1012 if (is_numeric($changedLinks)) {
1013 $s .= $changedLinks.' lien'.(($changedLinks>1)?'s ont été modifiés.':' a été modifié.');
1014 }
1015 $page->trigSuccess($s);
1016 } else {
1017 $page->trigError("Impossible de déplacer la page ".$wikipage);
1018 }
1019 }
1020 }
1021
1022 $perms = PlWikiPage::permOptions();
1023
1024 // list wiki pages and their perms
1025 $wiki_pages = PlWikiPage::listPages();
1026 ksort($wiki_pages);
1027 $wiki_tree = array();
1028 foreach ($wiki_pages as $file => $desc) {
1029 list($cat, $name) = explode('.', $file);
1030 if (!isset($wiki_tree[$cat])) {
1031 $wiki_tree[$cat] = array();
1032 }
1033 $wiki_tree[$cat][$name] = $desc;
1034 }
1035
1036 $page->changeTpl('admin/wiki.tpl');
1037 $page->assign('wiki_pages', $wiki_tree);
1038 $page->assign('perms_opts', $perms);
1039 }
1040
1041 function handler_ipwatch(&$page, $action = 'list', $ip = null)
1042 {
1043 $page->changeTpl('admin/ipwatcher.tpl');
1044
1045 $states = array('safe' => 'Ne pas surveiller',
1046 'unsafe' => 'Surveiller les inscriptions',
1047 'dangerous' => 'Surveiller tous les accès',
1048 'ban' => 'Bannir cette adresse');
1049 $page->assign('states', $states);
1050
1051 switch (Post::v('action')) {
1052 case 'create':
1053 if (trim(Post::v('ipN')) != '') {
1054 S::assert_xsrf_token();
1055 Xdb::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1056 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1057 ip_to_uint(trim(Post::v('ipN'))), ip_to_uint(trim(Post::v('maskN'))),
1058 Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
1059 };
1060 break;
1061
1062 case 'edit':
1063 S::assert_xsrf_token();
1064 Xdb::execute('UPDATE ip_watch
1065 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1066 WHERE ip = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'),
1067 ip_to_uint(Post::v('maskN')), ip_to_uint(Post::v('ipN')));
1068 break;
1069
1070 default:
1071 if ($action == 'delete' && !is_null($ip)) {
1072 S::assert_xsrf_token();
1073 Xdb::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1074 }
1075 }
1076 if ($action != 'create' && $action != 'edit') {
1077 $action = 'list';
1078 }
1079 $page->assign('action', $action);
1080
1081 if ($action == 'list') {
1082 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1083 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1084 IF(w.ip = s.ip, s.host, s.forward_host)),
1085 w.mask, w.detection, w.state, a.hruid
1086 FROM #x4dat#.ip_watch AS w
1087 LEFT JOIN #logger#.sessions AS s ON (s.ip = w.ip)
1088 LEFT JOIN #logger#.sessions AS s2 ON (s2.forward_ip = w.ip)
1089 LEFT JOIN #x4dat#.accounts AS a ON (a.uid = s.uid)
1090 GROUP BY w.ip, a.hruid
1091 ORDER BY w.state, w.ip, a.hruid";
1092 $it = Xdb::iterRow($sql);
1093
1094 $table = array();
1095 $props = array();
1096 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1097 $ip = uint_to_ip($ip);
1098 $mask = uint_to_ip($mask);
1099 if (count($props) == 0 || $props['ip'] != $ip) {
1100 if (count($props) > 0) {
1101 $table[] = $props;
1102 }
1103 $props = array('ip' => $ip,
1104 'mask' => $mask,
1105 'host' => $host,
1106 'detection' => $date,
1107 'state' => $state,
1108 'users' => array($hruid));
1109 } else {
1110 $props['users'][] = $hruid;
1111 }
1112 }
1113 if (count($props) > 0) {
1114 $table[] = $props;
1115 }
1116 $page->assign('table', $table);
1117 } elseif ($action == 'edit') {
1118 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1119 a1.hruid AS edit, a2.hruid AS hruid, s.host
1120 FROM #x4dat#.ip_watch AS w
1121 LEFT JOIN #x4dat#.accounts AS a1 ON (a1.uid = w.uid)
1122 LEFT JOIN #logger#.sessions AS s ON (w.ip = s.ip)
1123 LEFT JOIN #x4dat#.accounts AS a2 ON (a2.uid = s.uid)
1124 WHERE w.ip = {?}
1125 GROUP BY a2.hruid
1126 ORDER BY a2.hruid";
1127 $it = Xdb::iterRow($sql, ip_to_uint($ip));
1128
1129 $props = array();
1130 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1131 if (count($props) == 0) {
1132 $props = array('ip' => $ip,
1133 'mask' => uint_to_ip($mask),
1134 'host' => $host,
1135 'detection' => $detection,
1136 'state' => $state,
1137 'last' => $last,
1138 'description' => $description,
1139 'edit' => $edit,
1140 'users' => array($hruid));
1141 } else {
1142 $props['users'][] = $hruid;
1143 }
1144 }
1145 $page->assign('ip', $props);
1146 }
1147 }
1148
1149 function handler_icons(&$page)
1150 {
1151 $page->changeTpl('admin/icons.tpl');
1152 $dh = opendir('../htdocs/images/icons');
1153 if (!$dh) {
1154 $page->trigError('Dossier des icones introuvables.');
1155 }
1156 $icons = array();
1157 while (($file = readdir($dh)) !== false) {
1158 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1159 array_push($icons, substr($file, 0, -4));
1160 }
1161 }
1162 sort($icons);
1163 $page->assign('icons', $icons);
1164 }
1165
1166 function handler_accounts(&$page)
1167 {
1168 $page->changeTpl('admin/accounts.tpl');
1169 $page->assign('disabled', XDB::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1170 a.state = \'disabled\' AS disabled, a.comment
1171 FROM accounts AS a
1172 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1173 ORDER BY a.hruid'));
1174 $page->assign('admins', XDB::iterator('SELECT a.hruid
1175 FROM accounts AS a
1176 WHERE a.is_admin
1177 ORDER BY a.hruid'));
1178 }
1179
1180 function handler_jobs(&$page, $id = -1)
1181 {
1182 $page->changeTpl('admin/jobs.tpl');
1183
1184 if (Env::has('search')) {
1185 $res = XDB::query("SELECT e.id, e.name, e.acronym
1186 FROM profile_job_enum AS e
1187 WHERE e.name LIKE CONCAT('% ', {?}, '%') OR e.acronym LIKE CONCAT('% ', {?}, '%')",
1188 Env::t('job'), Env::t('job'));
1189
1190 if ($res->numRows() <= 20) {
1191 $page->assign('jobs', $res->fetchAllAssoc());
1192 } else {
1193 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1194 }
1195
1196 $page->assign('askedJob', Env::v('job'));
1197 return;
1198 }
1199
1200 if (Env::has('edit')) {
1201 // TODO: use address and phone classes to update profile_job_enum and profile_phones once they are done.
1202
1203 S::assert_xsrf_token();
1204 $selectedJob = Env::has('selectedJob');
1205
1206 XDB::execute("DELETE FROM profile_phones
1207 WHERE uid = {?} AND link_type = 'hq'",
1208 $id);
1209 XDB::execute("DELETE FROM profile_addresses
1210 WHERE jobid = {?} AND type = 'hq'",
1211 $id);
1212 XDB::execute('DELETE FROM profile_job_enum
1213 WHERE id = {?}',
1214 $id);
1215
1216 if (Env::has('change')) {
1217 XDB::execute('UPDATE profile_job
1218 SET jobid = {?}
1219 WHERE jobid = {?}',
1220 Env::i('newJobId'), $id);
1221
1222 $page->trigSuccess("L'entreprise a bien été remplacée.");
1223 } else {
1224 require_once 'profil.func.inc.php';
1225 require_once 'geocoding.inc.php';
1226
1227 $display_tel = format_display_number(Env::v('tel'), $error_tel);
1228 $display_fax = format_display_number(Env::v('fax'), $error_fax);
1229 $gmapsGeocoder = new GMapsGeocoder();
1230 $address = array('text' => Env::t('address'));
1231 $address = $gmapsGeocoder->getGeocodedAddress($address);
1232 Geocoder::getAreaId($address, 'administrativeArea');
1233 Geocoder::getAreaId($address, 'subAdministrativeArea');
1234 Geocoder::getAreaId($address, 'locality');
1235
1236 XDB::execute('UPDATE profile_job_enum
1237 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1238 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1239 WHERE id = {?}',
1240 Env::t('name'), Env::t('acronym'), Env::t('url'), Env::t('email'),
1241 Env::t('NAF_code'), Env::i('AX_code'), Env::i('holdingId'), $id);
1242
1243 XDB::execute("INSERT INTO profile_phones (uid, link_type, link_id, tel_id, tel_type,
1244 search_tel, display_tel, pub)
1245 VALUES ({?}, 'hq', 0, 0, 'fixed', {?}, {?}, 'public'),
1246 ({?}, 'hq', 0, 1, 'fax', {?}, {?}, 'public')",
1247 $id, format_phone_number(Env::v('tel')), $display_tel,
1248 $id, format_phone_number(Env::v('fax')), $display_fax);
1249
1250 XDB::execute("INSERT INTO profile_addresses (jobid, type, id, accuracy,
1251 text, postalText, postalCode, localityId,
1252 subAdministrativeAreaId, administrativeAreaId,
1253 countryId, latitude, longitude, updateTime,
1254 north, south, east, west)
1255 VALUES ({?}, 'hq', 0, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
1256 {?}, {?}, FROM_UNIXTIME({?}), {?}, {?}, {?}, {?})",
1257 $id, $address['accuracy'], $address['text'], $address['postalText'],
1258 $address['postalCode'], $address['localityId'],
1259 $address['subAdministrativeAreaId'], $address['administrativeAreaId'],
1260 $address['countryId'], $address['latitude'], $address['longitude'],
1261 $address['updateTime'], $address['north'], $address['south'],
1262 $address['east'], $address['west']);
1263
1264 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1265 }
1266 }
1267
1268 if (!Env::has('change') && $id != -1) {
1269 $res = XDB::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1270 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1271 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1272 FROM profile_job_enum AS e
1273 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
1274 LEFT JOIN profile_phones AS t ON (t.uid = e.id AND link_type = 'hq' AND tel_id = 0)
1275 LEFT JOIN profile_phones AS f ON (f.uid = e.id AND link_type = 'hq' AND tel_id = 1)
1276 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1277 WHERE e.id = {?}",
1278 $id);
1279
1280 if ($res->numRows() == 0) {
1281 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1282 } else {
1283 $page->assign('selectedJob', $res->fetchOneAssoc());
1284 }
1285 }
1286 }
1287 }
1288
1289 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1290 ?>