3ca1f97d6f7aad42a62dcff89cfc44c0dc2036c8
[brisk.git] / web / Obj / user.phh
1 <?php
2 /*
3  *  brisk - Obj/user.phh
4  *
5  *  Copyright (C) 2012-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 require_once("${G_base}Obj/transports.phh");
25
26
27 // User flags
28 define('USER_FLAG_AUTH',     0x02);
29
30 define('USER_FLAG_MAP_AUTH', 0x0c);
31 define('USER_FLAG_LISTAUTH', 0x04);
32 define('USER_FLAG_ISOLAUTH', 0x08);
33
34 define('USER_FLAG_DBFAILED', 0x10);
35
36 //   user status
37 define('USER_FLAG_S_NORM',  0x000); // done
38 define('USER_FLAG_S_PAU',   0x100); // done
39 define('USER_FLAG_S_OUT',   0x200); // done
40 define('USER_FLAG_S_DOG',   0x300); // done
41 define('USER_FLAG_S_EAT',   0x400); // done
42 define('USER_FLAG_S_WRK',   0x500); // done
43 define('USER_FLAG_S_SMK',   0x600); // done
44 define('USER_FLAG_S_EYE',   0x700); // done
45 define('USER_FLAG_S_RABB',  0x800); // done
46 define('USER_FLAG_S_SOCC',  0x900); // done
47 define('USER_FLAG_S_BABY',  0xa00); // done
48 define('USER_FLAG_S_MOP',   0xb00); // done
49 define('USER_FLAG_S_BABBO',   0xc00); // done
50 define('USER_FLAG_S_RENNA',   0xd00); // done
51 define('USER_FLAG_S_PUPAZ',   0xe00); // done
52 define('USER_FLAG_S_VISCH',   0xf00); // done
53
54 define('USER_FLAG_S_ALL',   0xf00); // done
55
56 /* type of user normal, supporter etc ... */
57 define('USER_FLAG_TY_ALL',     0xff0000); // done
58 define('USER_FLAG_TY_NORM',    0x010000); // done
59 define('USER_FLAG_TY_SUPER',   0x020000); // done
60 define('USER_FLAG_TY_CERT',    0x040000); // done
61 define('USER_FLAG_TY_APPR',    0x080000); // done
62 //  ... other usefull status ...
63 define('USER_FLAG_TY_FIRONLY', 0x200000); // done
64 define('USER_FLAG_TY_ADMIN',   0x400000); // done
65 define('USER_FLAG_TY_DISABLE', 0x800000); // done
66
67 // ... reasons for disabling account ...
68 define('USER_DIS_REA_NONE',       0);
69 define('USER_DIS_REA_INVMAIL',    1);
70 define('USER_DIS_REA_LICENCE',    2);
71 define('USER_DIS_REA_BANNED',     3);
72 define('USER_DIS_REA_MALICIOUS',  4);
73 define('USER_DIS_REA_NU_ADDED',   5); // new user: new user added by hand or external sql
74 define('USER_DIS_REA_NU_MAILED',  6); // new user: mail sent to be confirmed
75 define('USER_DIS_REA_NU_TOBECHK', 7); // new user: name verification
76
77
78
79 // 240 is the right value, 600 is for fwrite error test
80 define('RD_ENDTIME_DELTA',  240);
81 define('RD_KEEPALIVE_TOUT',   4);
82
83 $S_load_stat = array( 'rU_heavy'      => 0,
84                       'lL_laccgarb'   => 0,
85                       'wU_lacc_upd'   => 0,
86                       'wR_garbage'    => 0,
87                       'wR_minusone'   => 0,
88                       'wR_the_end'    => 0 );
89
90 $mlang_user = array(
91                      'btn_backtotab'  => array('it' => ' torna ai tavoli ',
92                                                'en' => ' back to tables '),
93                      'btn_btotabsup'  => array('it' => ' grazie della donazione, torna ai tavoli ',
94                                                'en' => ' thank you for donation, back to tables '),
95
96                      'btn_agree'      => array('it' => ' accetto ',
97                                                'en' => ' agree '),
98                      'btn_refuse'     => array('it' => ' rifiuto ',
99                                                'en' => ' refuse '),
100                      'btn_dload'      => array('it' => ' scarico ',
101                                                'en' => ' download '),
102                      'btn_later'      => array('it' => ' leggo poi ',
103                                                'en' => ' read later '),
104                      'toc_date_dscl'  => array('it' => 'I nuovi termini di servizio entreranno in vigore il %s.',
105                                                'en' => 'EN I nuovi termini di servizio entreranno in vigore il %s.')
106                      );
107
108 class User {
109   var $brisk;      // reference to the room where the user is registered
110   var $idx;        // index in the room users array when you are in game
111   var $idx_orig;   // index in the room table users array when you aren't in game
112   var $code;       // authentication code
113   var $name;       // name of the user
114   var $sess;       // session of the user
115   var $ip;         // ip of the user
116   var $lacc;       // last access (for the cleanup)
117   var $laccwr;     // last access (for the cleanup)
118   var $bantime;    // timeout to temporary ban
119   var $stat;       // status (outdoor, room, table, game, ...)
120   var $subst;      // substatus for each status   
121   var $step;       // step of the current status
122   var $trans_step; // step to enable transition between pages (disable == -1)
123   var $cl_step;    // current step returned by client
124   var $ping_req;   // ping is already requested ?
125
126   var $pend_async; // number of async check that must be returned
127
128   var $rd_socket;  // socket handle of push stream
129   var $rd_endtime; // end time for push stream
130   var $rd_stat;    // actual status of push stream
131   var $rd_subst;   // actual substatus of push stream
132   var $rd_step;    // actual step of push stream
133   var $rd_from;    // referer
134   var $rd_scristp; // current script step (for each session) 
135   var $rd_kalive;  // if no message are sent after RD_KEEPALIVE_TOUT secs we send a keepalive from server
136   var $rd_cache;   // place where store failed fwrite data
137   var $rd_toflush; // bool to inform about unfflushed socket
138   var $rd_zls;     // zlibstream object handle if compressed stream, else FALSE
139   var $rd_transp;  // class that define stream encapsulation type (iframe, xhr, ...)
140   var $rd_is_chunked; // is the transport chunked or not ?
141
142   var $comm;       // commands array
143   // var $asta_card;  // 
144   // var $asta_pnt;   //
145   // var $handpt;     // Total card points at the beginning of the current hand.
146   // var $exitislock; // Player can exit from the table ?
147
148   // FIXME: the table_orig field must be removed after table field verify of index management (in spawned table
149   //        it is allways ZERO
150   var $table;      // id of the current table when you are in game
151   var $table_orig; // id of the current table when you aren't in game
152   var $table_pos;  // idx on the table
153   var $table_token;// token that identify a game on a table
154   var $flags;      // Bitfield with: AUTHENTICATE: 0x02 
155   var $rec;        // field with user db record or FALSE
156   var $the_end;    // Flag to change the end of the session
157
158   var $chat_lst;      // Last chat line
159   var $chattime;      // Array of chat times
160   var $chat_cur;      // Current chat line number
161   var $chat_ban;      // Time for ban chat
162   var $chat_dlt;      // Delta t for ban
163   var $shm_sz;
164
165   const BASE = "";    // basepath for absolute web references
166
167   function User() {
168   }
169
170   static function create(&$brisk, $idx, $name, $sess, $stat = "", $subst = "", $table = -1, $ip="0.0.0.0") {
171     if (($thiz = new User()) == FALSE)
172       return (FALSE);
173
174     $thiz->room       = &$brisk;
175     $thiz->idx        = $idx;
176     $thiz->idx_orig   = $idx;
177     $thiz->code       = -1;
178     $thiz->name       = $name;
179     $thiz->sess       = $sess;
180     $thiz->ip         = $ip;
181     $thiz->lacc       = time();
182     $thiz->laccwr     = time();
183     $thiz->bantime    = 0;
184     $thiz->stat       = $stat;
185     $thiz->subst      = $subst;
186     $thiz->step       = 1;
187     $thiz->trans_step = -1;
188     $thiz->cl_step    = -1;
189     $thiz->ping_req   = FALSE;
190     $thiz->pend_async = 0;
191     $thiz->comm       = array();
192
193     $thiz->rd_socket  = NULL;
194     $thiz->rd_endtime = -1;
195     $thiz->rd_stat    = -1;
196     $thiz->rd_subst   = "";
197     $thiz->rd_step    = -1;
198     $thiz->rd_from    = "";
199     $thiz->rd_scristp = -1;
200     $thiz->rd_kalive  = -1;
201     $thiz->rd_cache   = "";
202     $thiz->td_toflush = FALSE;
203     $thiz->rd_zls     = FALSE;
204     $thiz->rd_transp  = NULL;
205     $thiz->rd_is_chunked = FALSE;
206
207     $thiz->asta_card  = -2;
208     $thiz->asta_pnt   = -1;
209     $thiz->handpt     = -1;
210     $thiz->exitislock = TRUE;
211
212     $thiz->flags      = 0x00;
213     $thiz->rec        = FALSE;
214
215     $thiz->chattime   = array_fill(0, CHAT_N, 0);
216     $thiz->chat_cur   = 0;
217     $thiz->chat_lst   = "";
218     $thiz->chat_ban   = 0;
219     $thiz->chat_dlt   = 0;
220
221     $thiz->table_orig = $table;
222     $thiz->table      = $table;
223     $thiz->table_pos  = -1;
224     $thiz->table_token= "";
225     $thiz->shm_sz = SHM_DIMS_U_MIN;
226     return ($thiz);
227   }
228
229   function copy($from)
230   {
231     $this->idx        = $from->idx;
232     $this->idx_orig   = $from->idx;
233     $this->code       = $from->code;
234     $this->name       = $from->name;
235     $this->sess       = $from->sess;
236     $this->ip         = $from->ip;
237     $this->lacc       = $from->lacc;
238     $this->laccwr     = $from->laccwr;
239     $this->bantime    = $from->bantime;
240     $this->stat       = $from->stat;
241     $this->subst      = $from->subst;
242     $this->step       = $from->step;
243     $this->trans_step = $from->trans_step;
244     $this->cl_step    = $from->cl_step;
245     $this->ping_req   = $from->ping_req;
246     $this->pend_async = $from->pend_async;
247     $this->comm       = array();
248
249     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
250     for ($i = $i_start ; $i < $from->step ; $i++) {
251         $ii = $i % COMM_N;
252         if (isset($from->comm[$ii])) {
253             $this->comm[$ii] = $from->comm[$ii];
254         }
255     }
256     $this->asta_card  = $from->asta_card;
257     $this->asta_pnt   = $from->asta_pnt;
258     $this->handpt     = $from->handpt;
259     $this->exitislock = $from->exitislock;
260
261     $this->flags      = $from->flags;
262     $this->rec        = $from->rec;
263
264     $this->chattime   = array();
265     for ($i = 0 ; $i < CHAT_N ; $i++)
266       $this->chattime[$i] = $from->chattime[$i];
267     $this->chat_cur   = $from->chat_cur;
268     $this->chat_lst   = $from->chat_lst;
269     $this->chat_ban   = $from->chat_ban;
270     $this->chat_dlt   = $from->chat_dlt;
271
272     $this->table_orig = $from->table_orig;
273     $this->table      = $from->table;
274     $this->table_pos  = $from->table_pos;
275     $this->table_token = $from->table_token;
276     $this->the_end    = $from->the_end;
277     $this->shm_sz     = $from->shm_sz;
278     return (TRUE);
279   }
280
281
282   static function myclone($from)
283   {
284     if (($thiz = new User()) == FALSE)
285       return (FALSE);
286     
287     $thiz->copy($from);
288
289     return ($thiz);
290   }
291   
292   static function spawn($from, $table, $table_pos)
293   {
294     if (($thiz = new User()) == FALSE)
295       return (FALSE);
296     
297     $thiz->idx        = $from->idx;
298     $thiz->idx_orig   = $from->idx;
299     $thiz->code       = $from->code;
300     $thiz->name       = $from->name;
301     $thiz->sess       = $from->sess;
302     $thiz->ip         = $from->ip;
303     $thiz->lacc       = $from->lacc;
304     $thiz->laccwr     = $from->laccwr;
305     $thiz->bantime    = $from->bantime;
306     $thiz->stat       = $from->stat;
307     $thiz->subst      = $from->subst;
308     $thiz->step       = $from->step;
309     $thiz->trans_step = $from->trans_step;
310     $thiz->cl_step    = $from->cl_step;
311     $thiz->ping_req   = $from->ping_req;
312     $thiz->pend_async = $from->pend_async;
313     $thiz->comm       = array();
314
315     /*
316     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
317     for ($i = $i_start ; $i < $from->step ; $i++) {
318       log_wr("TRY PUSH:".$i);
319       $ii = $i % COMM_N;
320       $thiz->comm[$ii]   = $from->comm[$ii];
321     }
322     */
323     $thiz->asta_card  = $from->asta_card;
324     $thiz->asta_pnt   = $from->asta_pnt;
325     $thiz->handpt     = $from->handpt;
326     $thiz->exitislock = $from->exitislock;
327     $thiz->the_end    = $from->the_end;
328
329     $thiz->flags      = $from->flags;
330     $thiz->rec        = $from->rec;
331
332     $thiz->chattime   = array_fill(0, CHAT_N, 0);
333     $thiz->chat_cur   = 0;
334     $thiz->chat_lst   = "";
335     $thiz->chat_ban   = 0;
336     $thiz->chat_dlt   = 0;
337
338
339     $thiz->table_orig = $table;
340     $thiz->table      = 0;
341     $thiz->table_pos  = $table_pos;
342     $thiz->table_token = $from->table_token;
343     $thiz->shm_sz      = $from->shm_sz;
344
345     return ($thiz);
346   }
347
348   function is_auth()
349   {
350       return ($this->flags & USER_FLAG_AUTH);
351   }
352
353   function is_cert()
354   {
355       return (($this->flags & USER_FLAG_AUTH) && ($this->flags & USER_FLAG_TY_CERT));
356   }
357
358   function is_empty()
359   {
360       return ($this->sess == "");
361   }
362
363   function is_active()
364   {
365       if ($this->sess != "" && !$this->the_end) // OK: is_active()
366           return TRUE;
367       return FALSE;
368   }
369
370   function flags_set($flags, $mask)
371   {
372       $flags_old = $this->flags & (~$mask);
373       $this->flags = ($flags_old | ($flags & $mask));
374
375       return ($flags_old);
376   }
377
378   function prefs_store()
379   {
380       if (($bdb = BriskDB::create()) == FALSE) {
381           return FALSE;
382       }
383       return ($bdb->user_prefs_update($this->code, ($this->flags & (USER_FLAG_TY_ALL | USER_FLAG_MAP_AUTH)),
384                                       $this->rec->supp_comp_get()));
385   }
386
387   function tos_store()
388   {
389       if (($bdb = BriskDB::create()) == FALSE) {
390           return FALSE;
391       }
392       return ($bdb->user_tos_update($this->code, $this->rec->tos_vers_get()));
393   }
394
395   function state_store()
396   {
397    if (($bdb = BriskDB::create()) == FALSE) {
398           return FALSE;
399       }
400       return ($bdb->user_state_update($this->code, ($this->flags & (USER_FLAG_TY_ALL | USER_FLAG_MAP_AUTH)),
401                                       $this->rec->disa_reas_get()));
402   }
403
404   function rd_data_set($curtime, $transp, $enc, $stat, $subst, $step, $from)
405   {
406       $this->rd_endtime = $curtime + RD_ENDTIME_DELTA;
407       $this->rd_stat    = $stat;
408       $this->rd_subst   = $subst;
409       $this->rd_step    = $step; // TRACKED
410       $this->rd_from    = $from;
411       $this->rd_scristp = 0;
412       $this->rd_kalive  = $curtime + RD_KEEPALIVE_TOUT;
413       $this->rd_zls     = ZLibStream::create($enc);
414       $this->rd_transp  = Transport::create($transp);
415       $this->rd_is_chunked = $this->rd_transp->is_chunked();
416   }
417
418   function rd_socket_get() {
419       return ($this->rd_socket);
420   }
421
422   function rd_socket_set($sock) {
423       if ($sock == NULL) {
424           if ($this->rd_zls) {
425               $this->rd_zls->destroy();
426               $this->rd_zls = FALSE;
427           }
428       }
429       $this->rd_socket = $sock;
430   }
431
432   function rd_kalive_get()
433   {
434       return ($this->rd_kalive);
435   }
436
437   function rd_kalive_set($tm)
438   {
439       $this->rd_kalive = $tm;
440   }
441
442   function rd_kalive_is_expired($tm)
443   {
444       // printf("rd_kalive %d tm %d\n", $this->rd_kalive, $tm);
445       return ($this->rd_kalive < $tm);
446   }
447
448   function rd_endtime_is_expired($tm)
449   {
450       // printf("rd_endtime %d tm %d\n", $this->rd_kalive, $tm);
451       return ($this->rd_endtime < $tm);
452   }
453
454   function rd_kalive_reset($tm)
455   {
456       $this->rd_kalive = $tm + RD_KEEPALIVE_TOUT;
457   }
458
459   function rd_cache_get()
460   {
461       return ($this->rd_cache);
462   }
463
464   function rd_cache_set($cache)
465   {
466       $this->rd_cache = $cache;
467   }
468
469   function rd_zls_get()
470   {
471       return ($this->rd_zls);
472   }
473
474   function idx_get() {
475       return ($this->idx);
476   }
477
478   function code_get() {
479       return ($this->code);
480   }
481   
482   function stat_set($stat) {
483     log_main("sess: [".$this->sess. "] NEW STAT: [".$stat."]"); 
484     $this->stat = "$stat";
485     
486     /*
487     if (validate_sess($this->sess)) {
488       if (file_exists(PROXY_PATH) == FALSE)
489         mkdir(PROXY_PATH, 0775, TRUE);
490       $fp = @fopen(PROXY_PATH."/".$this->sess.".stat", 'w');
491       fwrite($fp, sprintf("%s\n",$this->stat));
492       fclose($fp);
493     }
494     */
495   }
496
497   function step_set($step) 
498   {
499       $this->step = $step & 0x7fffffff;
500       
501       return (TRUE);
502   }
503
504   function step_inc($delta = 1) {
505       $this->step += $delta;
506       /* modularization because unpack() not manage unsigned 32bit int correctly */
507       $this->step &= 0x7fffffff;
508       
509       return TRUE;
510   }
511
512
513   function save_step() 
514   {
515       do {
516           if (validate_sess($this->sess) == FALSE)
517               break;
518           if (file_exists(PROXY_PATH) == FALSE)
519               mkdir(PROXY_PATH, 0775, TRUE);
520           if (($fp = @fopen(PROXY_PATH."/".$this->sess.".step", 'w')) == FALSE)
521               break;
522           fwrite($fp, pack("LL",$this->step, $this->idx));
523           fclose($fp);
524           
525           log_main("step_set [".$this->sess. "] [".$this->step."]"); 
526           
527           return (TRUE);
528       } while (0);
529       
530       return (FALSE);
531   }
532   
533   static function load_step($sess) 
534   {
535       $fp = FALSE;
536       do {
537           if (validate_sess($sess) == FALSE)
538               break;
539           
540           if (file_exists(PROXY_PATH) == FALSE)
541               mkdir(PROXY_PATH, 0775, TRUE);
542           if (($fp = @fopen(PROXY_PATH."/".$sess.".step", 'rb')) == FALSE)
543               break;
544           if (($s = fread($fp, 8)) == FALSE)
545               break;
546           if (mb_strlen($s, "ASCII") != 8)
547               break;
548           $arr = unpack('Ls/Li', $s);
549           fclose($fp);
550           
551           // log_rd2("A0: ".$arr[0]."  A1: ".$arr[1]);
552           return ($arr);
553       } while (0);
554       
555       if ($fp != FALSE)
556           fclose($fp);
557       
558       log_rd2("STEP_GET [".$sess."]: return false ");
559       
560       return (FALSE);
561   }
562
563   static function unproxy_step($sess) {
564       log_rd2("UNPROXY: ".PROXY_PATH."/".$sess.".step");
565       if (file_exists(PROXY_PATH) == FALSE)
566           return;
567       @unlink(PROXY_PATH."/".$sess.".step");
568   }
569
570   function reset() {
571     $curtime = time();
572     log_legal($curtime, $this->ip, $this, "STAT:LOGOUT", '');
573
574     $tmp_sess = $this->sess;
575     $this->sess = "";
576     self::unproxy_step($tmp_sess);
577     $this->name = "";  // OK here
578     while (array_pop($this->comm) != NULL);
579     $this->step = 0;
580     $this->chattime = array_fill(0, CHAT_N, 0);
581     $this->chat_cur = 0;
582     $this->chat_lst = "";
583     $this->chat_ban = 0;
584     $this->chat_dlt = 0;
585     $this->the_end = FALSE;
586   }
587
588   function myname_innerHTML()
589   {
590       // 4 -> is certified
591       // 2 -> is authorized
592       // 1 -> is myself
593       $class_ids = (($this->flags & USER_FLAG_TY_CERT) >> 16) | ($this->flags & USER_FLAG_AUTH) | 1;
594       $sp = "";
595       $cl = "";
596
597       for ($i = 0 ; $i < 3 ; $i++) {
598           if ($class_ids & (1 << $i)) {
599               $cl .= sprintf("%sau%d", $sp, $i);
600               $sp = " ";
601           }
602       }
603       return (sprintf('$("myname").innerHTML = "<span class=\"%s\">%s</span>";', $cl,
604                       xcape($this->name,ENT_COMPAT,"UTF-8")));
605   }
606
607   /* INDEX_RD PORT */
608
609   static function blocking_error($is_unrecoverable)
610   {
611       log_crit("BLOCKING_ERROR UNREC: ".($is_unrecoverable ? "TRUE" : "FALSE"));
612       return (sprintf(($is_unrecoverable ? 'xstm.stop(); ' : '').'window.onbeforeunload = null; window.onunload = null; document.location.assign("index.php");'));
613   }
614   
615   // FIXME TO SUPPORT iframe
616   protected function page_sync($sess, $page, $table_idx, $table_token)
617   {
618       // log_rd2("page_sync:".var_export(debug_backtrace()));
619       
620       log_rd2("PAGE_SYNC");
621       printf("xXx USER::PAGE_SYNC [%s]\n", get_class($this));
622       return (sprintf('createCookie("table_idx", %d, 24*365, cookiepath); createCookie("table_token", "%s", 24*365, cookiepath); xstm.stop(); window.onunload = null; window.onbeforeunload = null; document.location.assign("%s");', $table_idx, $table_token, $page));
623   }
624
625   protected function maincheck($get, $post, $cookie)
626   {
627       GLOBAL $G_lang, $G_base, $G_doc_path, $mlang_user;
628       // GLOBAL $first_loop;
629       GLOBAL $G_with_splash, $G_splash_content, $G_splash_interval, $G_splash_idx;
630       GLOBAL $G_splash_w, $G_splash_h, $G_splash_timeout;
631       GLOBAL $G_tos_vers, $G_tos_fname, $G_tos_dthard, $G_tos_dtsoft, $G_tos_idx;
632
633       GLOBAL $S_load_stat;
634       
635       $CO_splashdate = "CO_splashdate".$G_splash_idx;
636
637       if (($splashdate = gpcs_var("$CO_splashdate", $get, $post, $cookie)) === FALSE)
638           $splashdate = "";
639
640       log_rd("maincheck begin");
641       
642       $ret = "";
643       $curtime = time();
644
645       /* Nothing changed, return. */
646       if ($this->rd_step == $this->step)
647           return (FALSE);
648       
649       log_rd2("do other cur_stat[".$this->rd_stat."] user->stat[".$this->stat."] cur_step[".$this->rd_step."] user_step[".$this->step."]");
650       
651       fprintf(STDERR, "ASYNC: %d %d\n", $this->rd_step, $this->pend_async);
652       if ($this->rd_step == -1 && $this->pend_async == 0) {
653           /*  if $this->rd_step == -1 load the current state from the main struct  */
654           $S_load_stat['wR_minusone']++;
655
656           if ($this->trans_step != -1) {
657               log_rd2("TRANS USATO ".$this->trans_step);
658               $this->rd_step = $this->step = $this->trans_step; // TRACKED
659               $ret .= $this->room->show_room($this->step, $this);
660               $this->trans_step = -1;
661           }
662           else {
663               log_rd2("TRANS NON ATTIVATO");
664           }
665       }
666       
667       if ($this->pend_async > 0) {
668           return (FALSE);
669       }
670       /* this part I suppose is read only on $this->room structure */
671       if ($this->rd_step == -1) {
672           log_rd2("PRE-NEWSTAT: ".$this->stat);
673           
674           if ($this->stat == 'room') {
675               log_rd("roomma ".$this->step);
676               if ($this->rec !== FALSE) {
677                   $doc_filepath = $G_base.$G_doc_path.sprintf($G_tos_fname, $G_tos_vers, $G_lang);
678                   $doc_filename = basename($doc_filepath);
679                   if ($curtime > $G_tos_dtsoft || $curtime > $G_tos_dthard) {
680                       if (versions_cmp($this->rec->tos_vers_get(), $G_tos_vers) < 0) { // comparison between user version and current version
681                           $buttons = array($mlang_user['btn_agree'][$G_lang], $mlang_user['btn_refuse'][$G_lang],
682                                            $mlang_user['btn_dload'][$G_lang]);
683                           if ($curtime > $G_tos_dtsoft && $curtime < $G_tos_dthard) {
684                               // call notify soft (same as soft + later button)
685                               array_push($buttons, $mlang_user['btn_later'][$G_lang]);
686                               $type = "soft";
687                               $preface = sprintf("<div class='doc_alert'>%s</div>",
688                                                  sprintf($mlang_user['toc_date_dscl'][$G_lang],
689                                                          strftime("%e/%m/%Y", $G_tos_dthard)));
690                           }
691                           else {
692                               // call notify hard
693                               $type = "hard";
694                               $preface = "";
695                           }
696                           $ret .=  show_notify_document($preface.esclfhtml(file_get_contents($doc_filepath)), 0, $buttons,
697                                      "tos_confirm", sprintf("[ '%s/doc_download.php?doc=%s' ]", SITE_PREFIX,
698                                        basename($doc_filename, ".txt")), 600, 600, TRUE, 0);
699
700                           $ret .= sprintf("act_tosmgr('%s', g_nd.ret_get(), '%s', '%s');", $type,
701                                           xcape($this->rec->tos_vers_get()), xcape($G_tos_vers));
702                       }
703                   }
704               }
705               if ($G_with_splash &&
706                   ($splashdate < $curtime - $G_splash_interval ||
707                    $splashdate > $curtime)) {
708                   $is_super = $this->flags & USER_FLAG_TY_SUPER;
709                   $ret .=  show_notify_ex(str_replace("\n", " ", $G_splash_content[$G_lang]),
710                                           ($is_super ? 0 : $G_splash_timeout),
711                                           // $mlang_user[($is_super ? 'btn_btotabsup' : 'btn_backtotab')][$G_lang],
712                                           $mlang_user['btn_backtotab'][$G_lang],
713                                           $G_splash_w, $G_splash_h, true,
714                                           ($is_super ? 0 : $G_splash_timeout));
715                   $ret .= sprintf('|createCookie("CO_splashdate%d", %d, 24*365, cookiepath);', $G_splash_idx, $curtime);
716               }
717               $this->room->standup_update($this);
718               $ret .= $this->room->show_room($this->step, $this);
719               
720               // TODO uncomment and test
721               /* NOTE the sets went common */
722               $this->rd_stat =  $this->stat;
723               $this->rd_subst = $this->subst;
724               $this->rd_step =  $this->step; // TRACKED
725           }
726           /***************
727            *             *
728            *    TABLE    *
729            *             *
730            ***************/
731           else if ($this->stat == 'table') {
732               log_load("RESYNC");
733               printf("xXx USER::MAINCHECK1 [%s]\n", get_class($this));
734
735               return ($this->page_sync($this->sess, "briskin5/index.php", $this->table, $this->table_token));
736           }
737           log_rd2("NEWSTAT: ".$this->stat);
738       } /* if ($this->rd_step == -1) { */
739       else {
740           $S_load_stat['rU_heavy']++;
741           
742           if ($this->rd_step < $this->step) {
743               do {
744                   if ($this->rd_step + COMM_N < $this->step) {
745                       if (($this->rd_stat != $this->stat)) {
746                           $to_stat = $this->stat;
747                           log_load("RESYNC");
748                           printf("xXx USER::MAINCHECK2 [%s]\n", get_class($this));
749                           return ($this->page_sync($this->sess, ($to_stat == "table" ? "briskin5/index.php" : "index.php"), $this->table, $this->table_token));
750                       }
751                       log_rd2("lost history, refresh from scratch");
752                       $this->rd_step = -1;
753                       break;
754                   } 
755                   for ($i = $this->rd_step ; $i < $this->step ; $i++) {
756                       $ii = $i % COMM_N;
757                       log_rd2("ADDED TO THE STREAM: ".$this->comm[$ii]);
758                       if ($this->comm[$ii] == "") {
759                           if ($i == $this->rd_step)
760                               continue;
761                           else
762                               break;
763                       }
764                       $ret .= $this->comm[$ii];
765                   }
766                   $this->rd_stat =  $this->stat;
767                   $this->rd_subst = $this->subst;
768                   $this->rd_step = $this->step;
769               } while (0);
770               
771               log_rd2($this->step, 'index_rd.php: after ret set');
772
773               // if ($this->the_end == TRUE) { management is moved
774               // in the spush scope
775           } /* if ($this->rd_step < $this->step) { */
776       }  /* else of if ($this->rd_step == -1) { */
777
778       if ($ret == "")
779           $ret = FALSE;
780     
781       return ($ret);
782   }  //   function maincheck(...
783
784   public static function stream_fini($transp, $init_string, $is_unrecoverable)
785 {
786     printf("xXx user::stream_fini\n");
787
788     // FIXME: dynamic "Transport_" type
789     $trans_class = Transport::gettype($transp);
790     $body = $trans_class::fini($init_string, self::base_get(), static::blocking_error($is_unrecoverable));
791
792     // ELSE IF XHR THEN:
793     // return (static::blocking_error($is_unrecoverable));
794     return ($body);
795 }
796
797 /*
798  *  MAIN
799  */
800
801 /*
802    FROM THE EXTERN 
803    sess
804    stat
805    step
806 */
807 function stream_init($init_string, $enc, $header, &$header_out, &$body, $get, $post, $cookie)
808 {
809     $curtime = time();
810     
811     printf("CLASS: [%s] base: [%s]\n", get_class($this), self::base_get());
812
813     log_load("index_rd_init.php");
814     
815     if (($from  = gpcs_var('from', $get, $post, $cookie)) === FALSE)
816         $from = "";
817     if (($stat  = gpcs_var('stat', $get, $post, $cookie)) === FALSE) 
818         $stat = "";
819     if (($subst = gpcs_var('subst', $get, $post, $cookie)) === FALSE) 
820         $subst = "";
821     if (($step  = gpcs_var('step', $get, $post, $cookie)) === FALSE) 
822         unset($step);
823     if (($transp  = gpcs_var('transp', $get, $post, $cookie)) === FALSE)
824         $transp = "iframe";
825     
826     $this->rd_data_set($curtime, $transp, $enc, $stat, $subst, $step, $from);
827     
828     $ret = $this->rd_transp->init($enc, $header, &$header_out, $init_string, self::base_get(), $this->rd_scristp);
829
830     if ($ret === FALSE) {
831         return FALSE;
832     }
833
834     $body .= $ret;
835
836     return TRUE;
837   }
838
839 function stream_main(&$body, $get, $post, $cookie)
840 {
841     log_rd2("FROM OUTSIDE - STAT: ".$this->rd_stat." SUBST: ".$this->rd_subst." STEP: ".$this->rd_step." FROM: ".$this->rd_from);
842     
843     
844     $pre_main = gettimeofday(TRUE);
845     
846     printf("xXx PRE : rd_step %d\n", $this->rd_step);
847     if (($ret = $this->maincheck($get, $post, $cookie)) != FALSE) {
848         $body .= $this->rd_transp->chunk( $this->rd_scristp++, $ret);
849         log_rd2(0, 'index_rd.php: after mop_flush (begin: '.sprintf("%f", $pre_main).')');
850     }
851     printf("xXx POST: rd_step %d\n", $this->rd_step);
852
853     return TRUE;
854 }
855
856 function stream_keepalive($with_ping)
857 {
858     return ($this->rd_transp->chunk( $this->rd_scristp++, ($with_ping ? "act_ping();" : NULL)));
859 }
860
861 function stream_close()
862 {
863     return ($this->rd_transp->close());
864 }
865
866 static function base_get()
867 {
868     $c = get_called_class();
869     printf("CALLED_CLASS: [%s]\n", $c);
870     return $c::BASE;
871 }
872
873 function is_supp_custom()
874 {
875     if ($this->rec != FALSE) {
876         if ($this->flags & USER_FLAG_TY_SUPER) {
877             return (TRUE);
878         }
879         /*
880           if ($this->rec->last_dona_get() > 1356994800) {
881               return (TRUE);
882           }
883         */
884     }
885     return (FALSE);
886 }
887
888 function is_chunked()
889 {
890     return $this->rd_is_chunked;
891 }
892
893
894 function chunked_content($content)
895 {
896     if ($this->rd_zls) {
897         $cont_comp = $this->rd_zls->compress_chunk($content);
898     }
899     else {
900         $cont_comp = $content;
901     }
902     $cont_comp_l = mb_strlen($cont_comp, "ASCII");
903     // printf("CHUNK: [%s]\n", $content);
904
905     if ($this->is_chunked()) {
906         return (sprintf("%X\r\n", $cont_comp_l).$cont_comp."\r\n");
907     }
908     else {
909         return $cont_comp;
910     }
911 }
912
913 function chunked_fini()
914 {
915     return sprintf("0\r\n");
916 }
917
918
919 } // end class User
920
921
922 ?>