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