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