fix not authnticated usersnet management
[brisk.git] / web / index_wr.php
1 <?php
2 /*
3  *  brisk - index_wr.php
4  *
5  *  Copyright (C) 2006-2015 Matteo Nastasi
6  *                          mailto: nastasi@alternativeoutput.it
7  *                                  matteo.nastasi@milug.org
8  *                          web: http://www.alternativeoutput.it
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABLILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details. You should have received a
19  * copy of the GNU General Public License along with this program; if
20  * not, write to the Free Software Foundation, Inc, 59 Temple Place -
21  * Suite 330, Boston, MA 02111-1307, USA.
22  *
23  */
24
25 $mlang_indwr = array( 'unknownerr'    => array( 'it' => 'errore sconosciuto',
26                                                 'en' => 'unknown error'),
27                       'btn_backtotab' => array( 'it' => 'Torna ai tavoli.',
28                                                 'en' => 'Back to tables.' ),
29                       'warrrepl'  => array( 'it' => '<br>Il nominativo &egrave; stato inoltrato all\'amministratore.<br><br>Nell\'arco di pochi giorni verr&agrave;<br><br>notificata al garantito l\'avvenuta registrazione.',
30                                             'en' => '<br>The subscription was forwarded to the administrator.<br><br>In a few days we will notify<br><br>your friend the occurred registration.'),
31                       'btn_close' => array( 'it' => 'chiudi',
32                                             'en' => 'close' ),
33                       'commerr' => array( 'it' => '<b>E\' occorso un errore durante il salvataggio, riprova o contatta l\'amministratore.</b>',
34                                           'en' => '<b>An error was occurred during the saving, try again or contact the administrator.</b>'),
35                       'coerrdb' => array( 'it' => '<b>Il database è temporaneamente irraggiungibile, riprova più tardi o contatta l\'amministratore.</b>',
36                                           'en' => '<b>The database is temporarly unavailable, retry to later or conctact the administrator.</b>'),
37                       'warrmust' => array( 'it' => '<b>Per autenticare qualcuno devi a tua volta essere autenticato e certificato.</b>',
38                                            'en' => 'To authenticate somebody you have to be authenticated and certified yourown'),
39                       'mesgrepl' => array( 'it' => '<br><br>Il messaggio &egrave; stato inoltrato all\'amministratore.',
40                                            'en' => '<br><br>The message was forwarded to the administrator'),
41                       'mesgmust' => array( 'it' => '<b>Per mandare messaggi all\'amministratore devi essere autenticato.</b>',
42                                            'en' => 'To send a message to the administrator you have to be authenticated'),
43                       'shutmsg'  => array( 'it' => '<b>Il server sta per essere riavviato, non possono avere inizio nuove partite.</b>',
44                                            'en' => '<b>The server is going to be rebooted, new games are not allowed.</b>'),
45                       'mustappr' => array( 'it' => '<b>Il tavolo a cui volevi sederti richiede autentifica o apprendistato.</b>',
46                                            'en' => '<b>The table where you want to sit require authentication or apprentice</b>'),
47                       'mustauth' => array( 'it' => '<b>Il tavolo a cui volevi sederti richiede autentifica.</b>',
48                                            'en' => '<b>The table where you want to sit require authentication</b>'),
49                       'mustcert' => array( 'it' => '<b>Il tavolo a cui volevi sederti richiede autentifica e certificazione.</b>',
50                                            'en' => '<b>The table where you want to sit require authentication and certification</b>'),
51                       'tabwait'=> array( 'it' => '<b>Il tavolo si &egrave; appena liberato, ci si potr&agrave; sedere tra %d secondi.',
52                                            'en' => '<b>The table is only just opened, you will sit down in %d seconds.'),
53                       'mustfirst'=> array( 'it' => '<b>Il tuo utente può sedersi al tavolo solo per primo.</b>',
54                                            'en' => '<b>Your can sit down as first user only.' ),
55                       'pollmust' => array( 'it' => '<b>Per partecipare al sondaggio devi essere autenticato.</b>',
56                                            'en' => '<b>To vote for the poll you have to be authenticated</b>'),
57                       'pollnone' => array( 'it' => '<br><br>Al momento non è attivo alcun sondaggio.',
58                                            'en' => '<br><br>At this moment no polls are active.'),
59                       'pollchoo' => array( 'it' => '<br><br>Non hai espresso nessuna preferenza.',
60                                            'en' => '<br><br>You don\'t choose any preference, do it'),
61                       'pollagai' => array( 'it' => '<br>Per questo sondaggio hai già votato.<br><br>Non si può esprimere la propria preferenza più di una volta.',
62                                            'en' => '<br>You just express your preference about this poll.<br><br>You cannot do it again.'),
63                       'pollrec'  => array ('it' => '<br><br>Il tuo voto è stato registrato.',
64                                            'en' => '<br><br>Your vote had be stored.'),
65                       'badwake_a'=> array( 'it' => '<br>Ti sei alzato da un tavolo senza il consenso degli altri giocatori.<br><br>Dovrai aspettare ancora ',
66                                            'en' => '<br>You stand up without the permission of the other players.<br><br>You will wait '),
67                       'badwake_b'=> array( 'it' => ' prima di poterti sedere nuovamente.',
68                                            'en' => ' before you can sit down again.'),
69                       'btn_stays'=> array( 'it' => 'resta in piedi.',
70                                            'en' => 'stay standing.'),
71                       'badsit_a' => array( 'it' => '<br>Tu o qualcuno col tuo stesso indirizzo IP si è alzato da un tavolo senza il consenso degli altri giocatori.<br><br>Dovrai aspettare ancora ',
72                                            'en' => '<br>You or someone with your same IP address is standing up from a table without the permission of the other players <br><br>You will wait '),
73                       'badsit_b' => array( 'it' => ' prima di poterti sedere nuovamente.<br><br>Se non sei stato tu ad alzarti e possiedi un login con password, autenticandoti con quello, potrai accedere.',
74                                            'en' => ' before you can sit down again. If you don\'t leave the table and you have a login with a password, authenticating with this one you will access'),
75                       'nu_netguard' => array('it' => "Di recente è già arrivata una richiesta da un indirizzo IP simile al tuo, riprova tra qualche tempo.",
76                                              'en' => "EN di recente è già arrivata una richiesta da un indirizzo IP simile al tuo, riprova tra qualche tempo."),
77                       'nu_unkerr' => array('it' => "Si è verificato un errore inatteso, contattare l'amministratore.",
78                                            'en' => "EN Si è verificato un errore inatteso, contattare l'amministratore."),
79                       'nu_loginau' => array('it' => "login già in uso",
80                                             'en' => "login already in use"),
81                       'nu_emailau' => array('it' => "email già utilizzata",
82                                             'en' => "email already in use"),
83                       'nu_msubj' => array( 'it' => 'Brisk: verifica email',
84                                            'en' => 'Brisk: email verification'),
85                       // %s(guar) %s(login) %s(baseurl) %d(code) %s(hash)
86                       'nu_mtext' => array( 'it' =>
87 'Ciao, sono l\' amministratore del sito di Brisk.
88
89 L\' utente \'%s\' ha garantito per te col nickname \'%s\',
90 vai al link: <%s>
91 per confermare il tuo indirizzo di posta elettronica.
92
93 Ciò è necessario per ottenere la password.
94
95 Saluti e buone partite, mop.',
96                                            'en' => 'EN mtext [%s] [%s] [%s]'),
97                       'nu_mhtml' => array( 'it' => 'Ciao, sono l\' amministratore del sito di Brisk.<br><br>
98 L\' utente \'%s\' ha garantito per te col nickname \'%s\',<br>
99 <a href="%s">clicca qui</a> per confermare il tuo indirizzo di posta elettronica.<br><br>
100 Ciò è necessario per ottenere la password.<br><br>
101 Saluti e buone partite, mop.<br>',
102                                            'en' => 'EN mhtml [%s] [%s] [%s]'),
103
104                       'ap_mtext' => array( 'it' =>
105 'Ciao, sono l\' amministratore del sito di Brisk.
106
107 Ti sei registrato col nickname \'%s\',
108 vai al link: <%s>
109 per confermare il tuo indirizzo di posta elettronica.
110
111 Ciò è necessario per ottenere la password.
112
113 Saluti e buone partite, mop.',
114                                            'en' => 'EN mtext [%s] [%s]'),
115
116                       'ap_mhtml' => array( 'it' => 'Ciao, sono l\' amministratore del sito di Brisk.<br><br>
117 Ti sei registrato col nickname \'%s\',<br>
118 <a href="%s">clicca qui</a> per confermare il tuo indirizzo di posta elettronica.<br><br>
119 Ciò è necessario per ottenere la password.<br><br>
120 Saluti e buone partite, mop.<br>',
121                                            'en' => 'EN mhtml [%s] [%s]'),
122                       'info_err' => array( 'it' => 'E\' occorso un errore (%d), riprova più tardi.',
123                                            'en' => 'Some error occurs (%d), retry later.'),
124                       'info_auth' => array('it' => 'Non essendo autenticato non puoi costruire una rete di preferenze.',
125                                            'en' => 'Some error occurs (%d), retry later.')
126                       );
127
128 define('LICMGR_CHO_ACCEPT', 0);
129 define('LICMGR_CHO_REFUSE', 1);
130 define('LICMGR_CHO_AFTER',  2);
131
132 function index_wr_main(&$brisk, $remote_addr_full, $get, $post, $cookie)
133 {
134     GLOBAL $G_domain, $G_webbase, $G_mail_seed, $G_notguar_code;
135     GLOBAL $G_shutdown, $G_alarm_passwd, $G_ban_list, $G_black_list, $G_lang, $G_room_help, $G_room_about;
136     GLOBAL $G_room_passwdhowto, $mlang_indwr;
137     GLOBAL $G_tos_vers;
138
139     log_load("index_wr.php");
140     $remote_addr = addrtoipv4($remote_addr_full);
141     $remote_ip = ip2int($remote_addr);
142
143     if (($mesg = gpcs_var('mesg', $get, $post, $cookie)) === FALSE)
144         unset($mesg);
145
146     if (($cl_step = gpcs_var('stp', $get, NULL, NULL)) === FALSE)
147         $cl_step = -2;
148
149     if (($sess = gpcs_var('sess', $get, $post, $cookie)) === FALSE)
150         $sess = "";
151
152
153     if (DEBUGGING == "local" && $remote_addr != '127.0.0.1') {
154         echo "Debugging time!";
155         return (FALSE);
156     }
157
158     /*
159      *  MAIN
160      */
161     $is_spawn = FALSE;
162
163     log_wr(0, 'index_wr.php: COMM: '.xcapemesg($mesg));
164     log_wr('COMM: '.xcapemesg($mesg));
165
166     $curtime = time();
167     $dt = date("H:i ", $curtime);
168
169     if (($user = $brisk->get_user($sess, &$idx)) == FALSE) {
170         $argz = explode('|', xcapemesg($mesg));
171
172         if ($argz[0] == 'getchallenge') {
173             if (isset($get['cli_name']))
174                 $cli_name = $get['cli_name'];
175             if (($a_sem = Challenges::lock_data(TRUE)) != FALSE) {
176                 log_main("chal lock data success");
177
178                 if (($chals = &Challenges::load_data()) != FALSE) {
179
180                     $token =  uniqid("");
181                     // echo '2|'.$argz[1].'|'.$token.'|'.$remote_addr.'|'.$curtime.'|';
182                     // exit;
183
184                     if (($login_new = validate_name(urldecode($cli_name))) != FALSE) {
185                         if ($chals->add($login_new, $token, $remote_addr, $curtime) != FALSE) {
186                             log_send("SUCCESS: token:".$token);
187                             echo '0|'.$token;
188                         }
189                         else {
190                             log_send("getchallenge FAILED");
191                             echo '1|';
192                         }
193                     }
194                     else {
195                         log_send("getchallenge FAILED");
196                         echo '1|';
197                     }
198                     if ($chals->ismod()) {
199                         Challenges::save_data(&$chals);
200                     }
201                 }
202
203
204                 Challenges::unlock_data($a_sem);
205             }
206             else {
207                 echo "CHALLENGE LOCK FAILED\n";
208                 return FALSE;
209             }
210         }
211         else if ($argz[0] == 'auth') {
212             printf("challenge|ok");
213         }
214         else if ($argz[0] == 'help') {
215             /* MLANG: "torna ai tavoli" */
216             echo show_notify(str_replace("\n", " ", $G_room_help[$G_lang]), 0, $mlang_indwr['btn_close'][$G_lang], 600, 500);
217         }
218         else if ($argz[0] == 'about') {
219             echo show_notify(str_replace("\n", " ", $G_room_about[$G_lang]), 0, $mlang_indwr['btn_close'][$G_lang], 400, 230);
220         }
221         else if ($argz[0] == 'passwdhowto') {
222             echo show_notify(str_replace("\n", " ", $G_room_passwdhowto[$G_lang]), 0, $mlang_indwr['btn_close'][$G_lang], 400, 200);
223         }
224         else if ($argz[0] == 'roadmap') {
225             echo show_notify(str_replace("\n", " ", $G_room_roadmap[$G_lang]), 0, $mlang_indwr['btn_close'][$G_lang], 400, 200);
226         }
227         else if ($argz[0] == 'placing') {
228             require_once("briskin5/Obj/briskin5.phh");
229             require_once("briskin5/Obj/placing.phh");
230
231             echo show_notify(str_replace("\n", " ", placings_show(FALSE)), 0, $mlang_indwr['btn_close'][$G_lang], 800, 600);
232         }
233         else if ($argz[0] == 'apprentice') {
234             if (($cli_name = gpcs_var('cli_name', $get, $post, $cookie)) === FALSE)
235                 $cli_name = "";
236
237             if (($cli_email = gpcs_var('cli_email', $get, $post, $cookie)) === FALSE)
238                 $cli_email = "";
239
240             $mesg_to_user = "";
241
242             // check existence of username or email
243             $is_trans = FALSE;
244             do {
245                 error_log($cli_name);
246                 if (login_consistency($cli_name) == FALSE) {
247                     $mesg_to_user = "Il nickname non è conforme alle regole per la sua costruzione.";
248                     break;
249                 }
250
251                 if (($bdb = BriskDB::create()) == FALSE) {
252                     $mesg_to_user = "Connessione al database fallita";
253                     break;
254                 }
255
256                 // check IP address as previous requirer
257                 if ($bdb->selfreg_check($remote_ip) == FALSE) {
258                     $mesg_to_user = $mlang_indwr['nu_netguard'][$G_lang];
259                     break;
260                 }
261
262                 $cli_name = urldecode($cli_name);
263                 $cli_email = urldecode($cli_email);
264
265                 // check for already used fields
266                 if (($idret = $bdb->check_record_by_login_or_email($cli_name, $cli_email)) != 0) {
267                     $mesg_to_user = ($idret == 1 ?  $mlang_indwr['nu_loginau'][$G_lang] :
268                                      ($idret == 2 ? $mlang_indwr['nu_emailau'][$G_lang] :
269                                       $mlang_indwr['unknownerr'][$G_lang]));
270                     break;
271                 }
272
273                 $bdb->transaction('BEGIN');
274                 $is_trans = TRUE;
275                 //   insert the new user disabled with reason NU_MAILED
276                 // FIXME: move 'no-guaran' user into configuration file
277                 if (($usr_obj = $bdb->user_add($cli_name, 'THE_PASS', $cli_email,
278                                                USER_FLAG_TY_DISABLE | USER_FLAG_TY_APPR,
279                                                USER_DIS_REA_NU_MAILED, $G_notguar_code)) == FALSE) {
280                     fprintf(STDERR, "ERROR: user_add FAILED\n");
281                     $mesg_to_user = "Fallito inserimento nel database.";
282                     break;
283                 }
284
285                 if (($mail_code = $bdb->mail_reserve_code()) == FALSE) {
286                     fprintf(STDERR, "ERROR: mail reserve code FAILED\n");
287                     $mesg_to_user = "Fallita creazione codice email.";
288                     break;
289                 }
290                 $hash = md5($curtime . $G_alarm_passwd . $cli_name . $cli_email);
291
292                 $confirm_page = sprintf("http://%s/%s/mailmgr.php?f_act=checkmail&f_code=%d&f_hash=%s",
293                                         $G_domain, $G_webbase, $mail_code, $hash);
294                 $subj = $mlang_indwr['nu_msubj'][$G_lang];
295                 $body_txt = sprintf($mlang_indwr['ap_mtext'][$G_lang],
296                                     $cli_name, $confirm_page);
297                 $body_htm = sprintf($mlang_indwr['ap_mhtml'][$G_lang],
298                                     $cli_name, $confirm_page);
299
300                 $mail_item = new MailDBItem($mail_code, $usr_obj->code, MAIL_TYP_CHECK,
301                                             $curtime, $subj, $body_txt, $body_htm, $hash);
302
303                 // save the mail
304                 if ($mail_item->store($bdb) == FALSE) {
305                     // store mail error
306                     fprintf(STDERR, "ERROR: store mail FAILED\n");
307                     $mesg_to_user = "Fallita procedura di store.";
308                     break;
309                 }
310
311                 // check IP address as previous requirer
312                 if ($bdb->selfreg_set($remote_ip) == FALSE) {
313                     $mesg_to_user = $mlang_indwr['nu_unkerr'][$G_lang];
314                     break;
315                 }
316
317                 if (brisk_mail($cli_email, $subj, $body_txt, $body_htm) == FALSE) {
318                     // mail error
319                     fprintf(STDERR, "ERROR: mail send FAILED\n");
320                     $mesg_to_user = "Fallito invio email.";
321                     break;
322                 }
323
324                 $bdb->transaction('COMMIT');
325                 fprintf(STDERR, "REMOTE: %d\n", $remote_ip);
326                 echo "1";
327                 return TRUE;
328             } while(FALSE);
329             if ($is_trans)
330                 $bdb->transaction('ROLLBACK');
331             echo "$mesg_to_user";
332             return FALSE;
333         }
334         else {
335             log_wr("Get User Error");
336             echo "Get User Error:" + $argz[0];
337             return FALSE;
338         }
339         return TRUE;
340     } // end if (($user = $brisk->get_user($sess, ... == FALSE) {
341
342     $brisk->sess_cur_set($user->sess);
343     $argz = explode('|', xcapemesg($mesg));
344
345     log_wr('POSTSPLIT: '.$argz[0]);
346
347     // LACC UPDATED
348     $user->lacc = $curtime;
349     if ($user->cl_step < $cl_step) {
350         log_step(sprintf("%s|%s|%d|%d|%d|%d", $user->sess, $user->name, $user->step, $user->cl_step, $cl_step, $user->step - $user->cl_step));
351         $user->cl_step = $cl_step;
352     }
353
354     if ( ( ! $user->is_auth() ) &&
355         $brisk->ban_check($user->ip)) {
356         // TODO: find a way to add a nonblocking sleep(5) here
357         return (FALSE);
358     }
359
360     if ($argz[0] == 'ping') {
361         log_wr("PING RECEIVED");
362     }
363     else if ($argz[0] == 'info') {
364         if ($user->is_auth()) {
365             if ($argz[1] == 'save') {
366                 if (!isset($post['info'])) {
367                     return FALSE;
368                 }
369                 if (($ret = $brisk->info_save($user, $post['info'])) == 0) {
370                     echo "1";
371                     return TRUE;
372                 }
373
374                 printf($mlang_indwr['info_err'][$G_lang], $ret);
375                 return FALSE;
376             }
377         }
378         else {
379             printf($mlang_indwr['info_auth'][$G_lang]);
380             return FALSE;
381         }
382     }
383     else if ($argz[0] == 'prefs') {
384         if ($argz[1] == 'save') {
385             if (!isset($post['prefs'])) {
386                 return FALSE;
387             }
388
389             if (($prefs = Client_prefs::from_json($post['prefs'])) == FALSE) {
390                 $prefs = Client_prefs::from_user($user);
391             }
392             $prefs->store($user, TRUE);
393         }
394         else { // reset case as default
395             $prefs = Client_prefs::from_user($user);
396         }
397         $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
398         $user->comm[$user->step % COMM_N] .=  sprintf('prefs_load(\'%s\', true, %s);', json_encode($prefs),
399                                                       'false');
400         $user->step_inc();
401
402         if ($argz[1] == 'save') {
403             if ($user->stat == 'room' && $user->subst == 'standup') {
404                 $brisk->standup_update($user);
405             }
406             else if ($user->stat == 'room' && $user->subst == 'sitdown') {
407                 log_main("chatt_send pre table update");
408                 $brisk->table_update($user);
409                 log_main("chatt_send post table update");
410             }
411         }
412         echo "1";
413         return TRUE;
414     }
415     else if ($argz[0] == 'shutdown') {
416         log_auth($user->sess, "Shutdown session.");
417
418         $user->the_end = TRUE;
419
420         log_rd2("AUTO LOGOUT.");
421         if ($user->subst == 'sitdown' || $user->stat == 'table')
422             $brisk->room_wakeup($user);
423         else if ($user->subst == 'standup')
424             $brisk->room_outstandup(&$user);
425         else {
426             log_rd2("SHUTDOWN FROM WHAT ???");
427         }
428     }
429     else if ($argz[0] == 'warranty') {
430         if (($cli_name = gpcs_var('cli_name', $get, $post, $cookie)) === FALSE)
431             $cli_name = "";
432
433         if (($cli_email = gpcs_var('cli_email', $get, $post, $cookie)) === FALSE)
434             $cli_email = "";
435
436         $mesg_to_user = "";
437
438         log_wr("INFO:SKIP:argz == warranty name: [".$cli_name."] CERT: ".$user->is_cert());
439         if ($user->is_cert()) {
440             if (0 == 1) {
441                 if (($wa_lock = Warrant::lock_data(TRUE)) != FALSE) {
442                     if (($fp = @fopen(LEGAL_PATH."/warrant.txt", 'a')) != FALSE) {
443                         /* Unix time | session | nickname | IP | where was | mesg */
444                         fwrite($fp, sprintf("%ld|%s|%s|%s|\n", $curtime, xcapelt($user->name), xcapelt(trim(urldecode($cli_name))), xcapelt(trim(urldecode($cli_email)))));
445                         fclose($fp);
446                     }
447                     Warrant::unlock_data($wa_lock);
448                     $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
449                     /* MLANG: "<br>Il nominativo &egrave; stato inoltrato all\'amministratore.<br><br>Nell\'arco di pochi giorni vi verr&agrave;<br><br>notificata l\'avvenuta registrazione." */
450                     $user->comm[$user->step % COMM_N] .=  show_notify($mlang_indwr['warrrepl'][$G_lang], 0, $mlang_indwr['btn_close'][$G_lang], 400, 150);
451                     $user->step_inc();
452                     echo "1";
453                 }
454                 else {
455                     /* MLANG: "<b>E\' occorso un errore durante il salvataggio, riprova o contatta l\'amministratore.</b>" */
456                     $mesg_to_user = nickserv_msg($dt, $mlang_indwr['commerr'][$G_lang]);
457                 }
458             } // 0 == 1
459             else {
460                 // check existence of username or email
461                 $is_trans = FALSE;
462                 do {
463                     if (($bdb = BriskDB::create()) == FALSE)
464                         break;
465
466                     $cli_name = trim(urldecode($cli_name));
467                     $cli_email = trim(urldecode($cli_email));
468
469                     // check for already used fields
470                     if (($idret = $bdb->check_record_by_login_or_email($cli_name, $cli_email)) != 0) {
471                         $mesg_to_user = nickserv_msg($dt, ($idret == 1 ?  $mlang_indwr['nu_loginau'][$G_lang] :
472                                                            ($idret == 2 ? $mlang_indwr['nu_emailau'][$G_lang]
473                                                             : $mlang_indwr['unknownerr'][$G_lang])));
474                         break;
475                     }
476                     $bdb->transaction('BEGIN');
477                     $is_trans = TRUE;
478                     //   insert the new user disabled with reason NU_MAILED
479                     if (($usr_obj = $bdb->user_add($cli_name, 'THE_PASS', $cli_email,
480                                                    USER_FLAG_TY_DISABLE | USER_FLAG_TY_NORM,
481                                                    USER_DIS_REA_NU_MAILED, $user->code)) == FALSE) {
482                         fprintf(STDERR, "ERROR: user_add FAILED\n");
483                         break;
484                     }
485                     if (($mail_code = $bdb->mail_reserve_code()) == FALSE) {
486                         fprintf(STDERR, "ERROR: mail reserve code FAILED\n");
487                         break;
488                     }
489                     $hash = md5($curtime . $G_alarm_passwd . $cli_name . $cli_email);
490
491                     $confirm_page = sprintf("http://%s/%s/mailmgr.php?f_act=checkmail&f_code=%d&f_hash=%s",
492                                             $G_domain, $G_webbase, $mail_code, $hash);
493                     $subj = $mlang_indwr['nu_msubj'][$G_lang];
494                     $body_txt = sprintf($mlang_indwr['nu_mtext'][$G_lang],
495                                         $user->name, $cli_name, $confirm_page);
496                     $body_htm = sprintf($mlang_indwr['nu_mhtml'][$G_lang],
497                                         $user->name, $cli_name, $confirm_page);
498
499                     $mail_item = new MailDBItem($mail_code, $usr_obj->code, MAIL_TYP_CHECK,
500                                                 $curtime, $subj, $body_txt, $body_htm, $hash);
501
502                     if (brisk_mail($cli_email, $subj, $body_txt, $body_htm) == FALSE) {
503                         // mail error
504                         fprintf(STDERR, "ERROR: mail send FAILED\n");
505                         break;
506                     }
507                     // save the mail
508                     if ($mail_item->store($bdb) == FALSE) {
509                         // store mail error
510                         fprintf(STDERR, "ERROR: store mail FAILED\n");
511                         break;
512                     }
513                     $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
514                     /* MLANG: "<br>Il nominativo &egrave; stato inoltrato all\'amministratore.<br><br>Nell\'arco di pochi giorni vi verr&agrave;<br><br>notificata l\'avvenuta registrazione." */
515                     $user->comm[$user->step % COMM_N] .=  show_notify($mlang_indwr['warrrepl'][$G_lang], 0, $mlang_indwr['btn_close'][$G_lang], 400, 150);
516                     $user->step_inc();
517                     echo "1";
518                     $bdb->transaction('COMMIT');
519                 } while(FALSE);
520                 $bdb->transaction('ROLLBACK');
521             }
522
523         }
524         else {
525             /* MLANG: "<b>Per autenticare qualcuno devi a tua volta essere autenticato.</b>" */
526             $mesg_to_user = nickserv_msg($dt, $mlang_indwr['warrmust'][$G_lang]);
527         }
528
529         if ($mesg_to_user != "") {
530             $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
531
532             $user->comm[$user->step % COMM_N] .= $mesg_to_user;
533             $user->step_inc();
534         }
535     }
536     else if ($argz[0] == 'mesgtoadm') {
537         if (($cli_subj = gpcs_var('cli_subj', $get, $post, $cookie)) === FALSE)
538             $cli_subj = "";
539
540         if (($cli_mesg = gpcs_var('cli_mesg', $get, $post, $cookie)) === FALSE)
541             $cli_mesg = "";
542
543         $mesg_to_user = "";
544
545         log_wr("INFO:SKIP:argz == mesgtoadm name: [".$user->name."] AUTH: ".$user->is_auth());
546         if ($user->is_auth()) {
547             if (($wa_lock = Warrant::lock_data(TRUE)) != FALSE) {
548                 if (($bdb = BriskDB::create()) != FALSE) {
549                     $bdb->users_load();
550
551                     if (($ema = $bdb->getmail($user->name)) != FALSE) {
552                         //  mail("nastasi",
553                         mail("brisk@alternativeoutput.it", urldecode($cli_subj), urldecode($cli_mesg), sprintf("From: %s <%s>", $user->name, $ema));
554                     }
555
556                     if (($fp = @fopen(LEGAL_PATH."/messages.txt", 'a')) != FALSE) {
557                         /* Unix time | session | nickname | IP | where was | mesg */
558                         fwrite($fp, sprintf("%ld|%s|%s|%s\n", $curtime, $user->name,
559                                             xcapelt(urldecode($cli_subj)), xcapelt(urldecode($cli_mesg))));
560                         fclose($fp);
561                     }
562                     Warrant::unlock_data($wa_lock);
563                     $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
564                     /* MLANG: "" */
565                     $user->comm[$user->step % COMM_N] .=  show_notify($mlang_indwr['mesgrepl'][$G_lang], 0, $mlang_indwr['btn_close'][$G_lang], 400, 110);
566                     $user->step_inc();
567                     echo "1";
568                 }
569                 else {
570                     /* MLANG: "<b>Il database è temporaneamente irraggiungibile, riprova più tardi o contatta l\'amministratore.</b>" */
571                     $mesg_to_user = nickserv_msg($dt, $mlang_indwr['coerrdb'][$G_lang]);
572                     $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
573                 }
574             }
575             else {
576                 /* MLANG: "<b>E\' occorso un errore durante il salvataggio, riprova o contatta l\'amministratore.</b>" */
577                 $mesg_to_user = nickserv_msg($dt, $mlang_indwr['commerr'][$G_lang]);
578             }
579
580         }
581         else {
582             /* MLANG: "<b>Per autenticare qualcuno devi a tua volta essere autenticato.</b>" */
583             $mesg_to_user = nickserv_msg($dt, $mlang_indwr['mesgmust'][$G_lang]);
584         }
585
586         if ($mesg_to_user != "") {
587             $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
588
589             $user->comm[$user->step % COMM_N] .= $mesg_to_user;
590             $user->step_inc();
591         }
592     }
593
594
595
596     else if ($argz[0] == 'poll') {
597         GLOBAL $G_with_poll, $G_poll_name;
598         if (($cli_choose = gpcs_var('cli_choose', $get, $post, $cookie)) === FALSE)
599             $cli_choose = "";
600
601         if (($cli_poll_name = gpcs_var('cli_poll_name', $get, $post, $cookie)) === FALSE)
602             $cli_poll_name = "";
603
604         $poll_lock = FALSE;
605         $mesg_to_user = "";
606
607         $fp = FALSE;
608         $echont = "0";
609
610   /*
611           DONE - autorizzato ?
612           DONE - ci sono poll attivi ?
613           - verifica che il poll_name del client sia uguale a quello sul server
614           DONE - lock
615           DONE - apro file r+ con fallback in w+
616           DONE - vedo se ha già votato
617           DONE - se si: messaggio di voto già dato
618           se no: accetto il voto e lo segno; messaggio
619           chiudo file
620   */
621
622         $dobreak = FALSE;
623         do {
624             log_wr("INFO:SKIP:argz == poll name: [".$cli_poll_name."] AUTH: ".$user->is_auth());
625             if ( ! $user->is_auth() || $user->is_appr() ) {
626                 // MLANG: <b>Per partecipare al sondaggio devi essere autenticato.</b>
627                 $mesg_to_user = nickserv_msg($dt, $mlang_indwr['pollmust'][$G_lang]);
628                 log_wr("break1");
629                 break;
630             }
631
632             if ($G_with_poll == FALSE && $G_poll_name != FALSE && $G_poll_name != "") {
633                 $mesg_to_user = show_notify($mlang_indwr['pollnone'][$G_lang], 0, $mlang_indwr['btn_close'][$G_lang], 400, 110);
634                 log_wr("break2");
635                 break;
636             }
637
638             if ($cli_choose == "" || !isset($cli_choose)) {
639                 $mesg_to_user = show_notify($mlang_indwr['pollchoo'][$G_lang], 0, $mlang_indwr['btn_close'][$G_lang], 400, 110);
640                 log_wr("break2.5");
641                 break;
642             }
643
644             if (($poll_lock = Poll::lock_data(TRUE)) == FALSE) {
645                 /* MLANG: "<b>E\' occorso un errore durante il salvataggio, riprova o contatta l\'amministratore.</b>" */
646                 $mesg_to_user = nickserv_msg($dt, $mlang_indwr['commerr'][$G_lang]);
647                 log_wr("break3");
648                 break;
649             }
650
651             if (($fp = @fopen(LEGAL_PATH."/".$G_poll_name.".txt", 'r+')) == FALSE)
652                 $fp = @fopen(LEGAL_PATH."/".$G_poll_name.".txt", 'w+');
653
654             if ($fp == FALSE) {
655                 $mesg_to_user = nickserv_msg($dt, $mlang_indwr['commerr'][$G_lang]);
656                 log_wr("break4");
657                 break;
658             }
659
660             log_wr("poll: cp");
661             fseek($fp, 0);
662
663             log_wr("poll: cp2");
664             while (!feof($fp)) {
665                 log_wr("poll: cp3");
666                 $bf = fgets($fp, 4096);
667                 log_wr("poll: cp3.1");
668                 $arli = csplitter($bf, '|');
669                 if (count($arli) == 0)
670                     break;
671                 log_wr("poll: cp3.2");
672                 if (strcasecmp($arli[1], $user->name) == 0) {
673                     $mesg_to_user = show_notify($mlang_indwr['pollagai'][$G_lang], 0, $mlang_indwr['btn_close'][$G_lang], 400, 110);
674                     $dobreak = TRUE;
675                     break;
676                 }
677             }
678             log_wr("poll: cp4");
679
680             if ($dobreak) {
681                 log_wr("break5");
682                 break;
683             }
684
685             /* Unix time | nickname | choose */
686             fwrite($fp, sprintf("%ld|%s|%s\n", $curtime, xcapelt($user->name), xcapelt(urldecode($cli_choose))));
687             fflush($fp);
688             $mesg_to_user =  show_notify($mlang_indwr['pollrec'][$G_lang], 0, $mlang_indwr['btn_close'][$G_lang], 400, 110);
689             $echont = "1";
690             log_wr("poll: cp5");
691         } while (0);
692
693         if ($fp != FALSE)
694             fclose($fp);
695
696         if ($poll_lock != FALSE)
697             Poll::unlock_data($poll_lock);
698
699         if ($mesg_to_user != "") {
700             $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
701
702             $user->comm[$user->step % COMM_N] .= $mesg_to_user;
703             $user->step_inc();
704         }
705
706         echo "$echont";
707     }
708
709     /******************
710      *                *
711      *   STAT: room   *
712      *                *
713      ******************/
714     else if ($user->stat == 'room') {
715         $user->laccwr = time();
716
717         if ($argz[0] == 'help') {
718             $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
719             $user->comm[$user->step % COMM_N] .=  show_notify(str_replace("\n", " ", $G_room_help[$G_lang]), 0, $mlang_indwr['btn_backtotab'][$G_lang], 600, 500);
720
721             log_wr($user->comm[$user->step % COMM_N]);
722             $user->step_inc();
723
724         }
725         else if ($argz[0] == 'passwdhowto') {
726             $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
727             $user->comm[$user->step % COMM_N] .=  show_notify(str_replace("\n", " ", $G_room_passwdhowto[$G_lang]), 0, $mlang_indwr['btn_backtotab'][$G_lang], 600, 500);
728
729             log_wr($user->comm[$user->step % COMM_N]);
730             $user->step_inc();
731
732         }
733         else if ($argz[0] == 'splash') {
734             GLOBAL $G_with_splash, $G_splash_content, $G_splash_interval, $G_splash_idx;
735             GLOBAL $G_splash_w, $G_splash_h, $G_splash_timeout;
736             $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
737
738             $user->comm[$user->step % COMM_N] .=  show_notify_ex(str_replace("\n", " ", $G_splash_content[$G_lang]), 0, $mlang_indwr['btn_backtotab'][$G_lang], $G_splash_w, $G_splash_h, true, 0);
739
740             log_wr($user->comm[$user->step % COMM_N]);
741             $user->step_inc();
742         }
743         else if ($argz[0] == 'about') {
744             $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
745             $user->comm[$user->step % COMM_N] .=  show_notify(str_replace("\n", " ", $G_room_about[$G_lang]), 0, $mlang_indwr['btn_backtotab'][$G_lang], 400, 200);
746
747             log_wr($user->comm[$user->step % COMM_N]);
748             $user->step_inc();
749
750         }
751         else if ($argz[0] == 'placing') {
752             require_once("briskin5/Obj/briskin5.phh");
753             require_once("briskin5/Obj/placing.phh");
754
755             $user->comm[$user->step % COMM_N] =  "gst.st = ".($user->step+1)."; ";
756             $user->comm[$user->step % COMM_N] .= show_notify_ex(str_replace("\n", " ", placings_show($user)), 0, $mlang_indwr['btn_backtotab'][$G_lang], 800, 600, TRUE, 0);
757
758             log_wr($user->comm[$user->step % COMM_N]);
759             $user->step_inc();
760         }
761         else if ($argz[0] == 'roadmap') {
762             $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
763             $user->comm[$user->step % COMM_N] .=  show_notify(str_replace("\n", " ", $G_room_roadmap[$G_lang]), 0, $mlang_indwr['btn_backtotab'][$G_lang], 400, 200);
764
765             log_wr($user->comm[$user->step % COMM_N]);
766             $user->step_inc();
767
768         }
769         else if ($argz[0] == 'chatt') {
770             $brisk->chatt_send(&$user, xcapemesg($mesg), $mlang_indwr);
771         }
772         else if ($argz[0] == 'tosmgr') {
773             // check IF is authnticated user, both terms of service versions matches
774             if ($user->is_auth() && count($argz) == 5) {
775                 $f_type = $argz[1];      $f_code = $argz[2];
776                 $f_tos_curr = $argz[3]; $f_tos_vers = $argz[4];
777
778                 if ("$f_tos_curr" == $user->rec->tos_vers_get()  &&
779                     "$f_tos_vers" == "$G_tos_vers") {
780                     if ("$f_type" == "soft" || "$f_type" == "hard") {
781                         $res = 100;
782                         switch ($f_code) {
783                         case LICMGR_CHO_ACCEPT:
784                             $user->rec->tos_vers_set($G_tos_vers);
785                             $res = $user->tos_store();
786                             break;
787                         case LICMGR_CHO_REFUSE:
788                             $user->flags_set(USER_FLAG_TY_DISABLE, USER_FLAG_TY_ALL);
789                             $user->rec->disa_reas_set(USER_DIS_REA_LICENCE);
790                             $res = $user->state_store();
791
792                             $user->comm[$user->step % COMM_N] = $user->blocking_error(TRUE);
793                             $user->the_end = TRUE;
794                             $user->step_inc();
795                             break;
796                         }
797                     }
798                 }
799             }
800         }
801         /**********************
802          *                    *
803          *   SUBST: standup   *
804          *                    *
805          **********************/
806         else if ($user->subst == 'standup') {
807             if ($argz[0] == 'sitdown') {
808                 log_wr("SITDOWN command");
809
810                 if ($user->the_end == TRUE) {
811                     log_wr("INFO:SKIP:argz == sitdown && ->the_end == TRUE => ignore request.");
812                     return FALSE;
813                 }
814
815                 // Take parameters
816                 $table_idx = (int)$argz[1];
817                 $table = &$brisk->table[$table_idx];
818
819                 $not_allowed_msg = "";
820                 if ($G_shutdown) {
821                         $not_allowed_msg = nickserv_msg($dt, $mlang_indwr['shutmsg'][$G_lang]);
822                 }
823                 else if ($table->wakeup_time > $curtime) {
824                     $not_allowed_msg = nickserv_msg($dt, sprintf($mlang_indwr['tabwait'][$G_lang],
825                                                                  $table->wakeup_time - $curtime));
826                 }
827                 else if ( $table->auth_type == TABLE_AUTH_TY_CERT &&
828                           (!$user->is_cert() || $user->is_appr()) ) {
829                     $not_allowed_msg = nickserv_msg($dt, $mlang_indwr['mustcert'][$G_lang]);
830                 }
831                 else if ( $table->auth_type == TABLE_AUTH_TY_AUTH &&
832                           (!$user->is_auth() || $user->is_appr()) ) {
833                     $not_allowed_msg = nickserv_msg($dt, $mlang_indwr['mustauth'][$G_lang]);
834                 }
835                 else if ( $table->auth_type == TABLE_AUTH_TY_APPR &&
836                           (!$user->is_auth()) ) {
837                     $not_allowed_msg = nickserv_msg($dt, $mlang_indwr['mustappr'][$G_lang]);
838                 }
839                 else if ($user->flags & USER_FLAG_TY_FIRONLY && $table->player_n > 0) {
840                     $not_allowed_msg = nickserv_msg($dt, $mlang_indwr['mustfirst'][$G_lang]);
841                 }
842                 if ($not_allowed_msg != "") {
843                     $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ".$not_allowed_msg;
844                     $user->step_inc();
845                     return TRUE;
846                 }
847
848                 /* TODO: refact to a function */
849                 // if ($user->bantime > $user->laccwr) {
850                 require_once("Obj/hardban.phh");
851
852                 if (($bantime = Hardbans::check(($user->is_auth() ? $user->name : FALSE),
853                                                 $user->ip, $user->sess)) != -1) {
854                     $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
855                     /* MLANG: "<br>Ti sei alzato da un tavolo senza il consenso degli altri giocatori. <br><br>Dovrai aspettare ancora ".secstoword($user->bantime - $user->laccwr)." prima di poterti sedere nuovamente.", "resta in piedi.", "<br>Tu o qualcuno col tuo stesso indirizzo IP si è alzato da un tavolo senza il consenso degli altri giocatori.<br><br>Dovrai aspettare ancora ".secstoword($bantime - $user->laccwr)." prima di poterti sedere nuovamente.<br><br>Se non sei stato tu ad alzarti e possiedi un login con password, autenticandoti con quello, potrai accedere." */
856                     if ($user->is_auth()) {
857                         $user->comm[$user->step % COMM_N] .= show_notify($mlang_indwr['badwake_a'][$G_lang].secstoword($bantime - $user->laccwr).$mlang_indwr['badwake_b'][$G_lang], 2000, $mlang_indwr['btn_stays'][$G_lang], 400, 140);
858                     }
859                     else {
860                         $user->comm[$user->step % COMM_N] .= show_notify($mlang_indwr['badsit_a'][$G_lang].secstoword($bantime - $user->laccwr).$mlang_indwr['badsit_a'][$G_lang], 2000, $mlang_indwr['btn_stays'][$G_lang], 400, 180);
861                     }
862                     $user->step_inc();
863                     return TRUE;
864                 }
865
866                 if ($table->player_n == PLAYERS_N) {
867                     log_wr("WARN:FSM: Sitdown unreachable, table full.");
868                     return FALSE;
869                 }
870
871                 // set new status
872                 $user->subst = "sitdown";
873                 $user->table = $table_idx;
874                 $user->table_pos = $table->user_add($idx);
875
876                 log_wr("MOP before");
877
878                 if ($table->player_n == PLAYERS_N) {
879                     require_once("briskin5/Obj/briskin5.phh");
880                     log_wr("MOP inall");
881
882                     // Start game for this table.
883                     log_wr("Start game!");
884         
885                     //
886                     //  START THE SPAWN HERE!!!!
887                     //
888
889                     // Create new spawned table
890                     // $bin5_sem = Bin5::lock_data(TRUE, $table_idx);
891                     $table_token = uniqid("");
892                     $brisk->table[$table_idx]->table_token = $table_token;
893                     $brisk->table[$table_idx]->table_start = $curtime;
894
895                     $plist = "$table_token|$user->table|$table->player_n";
896                     for ($i = 0 ; $i < $table->player_n ; $i++) {
897                         $plist .= '|'.$brisk->user[$table->player[$i]]->sess;
898                     }
899                     log_legal($curtime, $user->ip, $user, "STAT:CREATE_GAME", $plist);
900
901                     log_wr("pre new Bin5");
902                     if (($bin5 = new Bin5($brisk, $table_idx, $table_token, $get, $post, $cookie)) == FALSE)
903                         log_wr("bri create: FALSE");
904                     else
905                         log_wr("bri create: ".serialize($bin5));
906
907                     log_wr("pre init table");
908                     // init table
909                     $bin5_table = $bin5->table[0];
910                     $bin5_table->init($bin5->user);
911                     $bin5_table->game_init($bin5->user);
912                     //
913                     // Init spawned users.
914                     //
915                     //  MULTIGAME: here init of selected game instead of hardcabled briskin5 init (look subst status)
916                     //
917                     log_wr("game_init after");
918                     for ($i = 0 ; $i < $table->player_n ; $i++) {
919                         $bin5_user_cur = $bin5->user[$i];
920                         $user_cur = $brisk->user[$table->player[$i]];
921
922                         $bin5_user_cur->laccwr = $curtime;
923                         $bin5_user_cur->trans_step = $user_cur->step + 1;
924                         $bin5_user_cur->comm[$bin5_user_cur->step % COMM_N] = "";
925                         $bin5_user_cur->step_inc();
926                         $bin5_user_cur->comm[$bin5_user_cur->step % COMM_N] = show_table(&$bin5,&$bin5_user_cur,$bin5_user_cur->step+1,TRUE,FALSE);
927                         $bin5_user_cur->step_inc();
928
929                         log_wr("TRY PRESAVE: ".$bin5_user_cur->step." TRANS STEP: ".$bin5_user_cur->trans_step);
930
931                         log_wr("Pre if!");
932
933                         //          ARRAY_POP DISABLED
934                         //          // CHECK
935                         while (array_pop($user_cur->comm) != NULL);
936
937                         $user_cur->trans_step = $user_cur->step + 1;
938                         $user_cur->comm[$user_cur->step % COMM_N] = sprintf('gst.st_loc++; gst.st=%d; createCookie("table_idx", %d, 24*365, cookiepath); createCookie("table_token", "%s", 24*365, cookiepath); createCookie("lang", "%s", 24*365, cookiepath); xstm.stop(); window.onunload = null ; window.onbeforeunload = null ; document.location.assign("briskin5/index.php");|', $user_cur->step+1, $table_idx, $table_token, $G_lang);
939                         log_wr("TRANS ATTIVATO");
940
941                         $user_cur->stat_set('table');
942                         $user_cur->subst = 'asta';
943                         $user_cur->laccwr = $curtime;
944                         $user_cur->step_inc();
945                     }
946                     log_wr("presave bri");
947                     $brisk->match_add($table_idx, $bin5);
948                     log_wr("postsave bri");
949                 }
950                 // change room
951                 $brisk->room_sitdown($user, $table_idx);
952
953                 log_wr("MOP finish");
954             }
955             else if ($argz[0] == 'logout') {
956                 $brisk->ghost_sess->push($curtime, $user->sess, GHOST_SESS_REAS_LOUT);
957                 $user->the_end = TRUE;
958
959                 if ($user->subst == 'sitdown') {
960                     log_load("ROOM WAKEUP");
961                     $brisk->room_wakeup($user);
962                 }
963                 else if ($user->subst == 'standup')
964                     $brisk->room_outstandup($user);
965                 else
966                     log_rd2("LOGOUT FROM WHAT ???");
967             }
968         }
969         /**********************
970          *                    *
971          *   SUBST: sitdown   *
972          *                    *
973          **********************/
974         else if ($user->subst == 'sitdown') {
975             if ($user->the_end == TRUE) {
976                 log_wr("INFO:SKIP:argz == sitdown && ->the_end == TRUE => ignore request.");
977                 return FALSE;
978             }
979
980             if ($argz[0] == 'wakeup') {
981                 $brisk->room_wakeup($user);
982             }
983             else if ($argz[0] == 'logout') {
984                 $brisk->ghost_sess->push($curtime, $user->sess, GHOST_SESS_REAS_LOUT);
985                 $user->the_end = TRUE;
986
987                 $brisk->room_wakeup($user);
988             }
989         }
990     }
991
992     return (FALSE);
993 }
994 ?>