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