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