User class moved into new file and added all methods needed to run stream
[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 // User flags
25 define('USER_FLAG_AUTH',     0x02);
26
27 define('USER_FLAG_MAP_AUTH', 0x0c);
28 define('USER_FLAG_LISTAUTH', 0x04);
29 define('USER_FLAG_ISOLAUTH', 0x08);
30
31 define('USER_FLAG_DBFAILED', 0x10);
32
33 //   user status
34 define('USER_FLAG_S_NORM',  0x000); // done
35 define('USER_FLAG_S_PAU',   0x100); // done
36 define('USER_FLAG_S_OUT',   0x200); // done
37 define('USER_FLAG_S_DOG',   0x300); // done
38 define('USER_FLAG_S_EAT',   0x400); // done
39 define('USER_FLAG_S_WRK',   0x500); // done
40 define('USER_FLAG_S_SMK',   0x600); // done
41 define('USER_FLAG_S_EYE',   0x700); // done
42 define('USER_FLAG_S_RABB',  0x800); // done
43 define('USER_FLAG_S_SOCC',  0x900); // done
44 define('USER_FLAG_S_BABY',  0xa00); // done
45 define('USER_FLAG_S_MOP',   0xb00); // done
46
47 define('USER_FLAG_S_ALL',   0xf00); // done
48
49 /* type of user normal, supporter etc ... */
50 define('USER_FLAG_TY_ALL',     0xff0000); // done
51 define('USER_FLAG_TY_NORM',    0x010000); // done
52 define('USER_FLAG_TY_SUPER',   0x020000); // done
53 //  ... other usefull status ...
54 define('USER_FLAG_TY_SUSPEND', 0x400000); // done
55 define('USER_FLAG_TY_DISABLE', 0x800000); // done
56
57 // 240 is the right value, 600 is for fwrite error test
58 define('RD_ENDTIME_DELTA',  240);
59 define('RD_KEEPALIVE_TOUT',   4);
60
61 $G_four_rnd_string = 
62  "GGZDGDRBXDWFXHGPYAAVDXEKFDUWSTEDTDVXBXQPMZAIFPNLRPTWMJAZRHXTIRNZ"
63 ."HTZXAUVJDCLXENDCLIZXSSEQQGUADYEKNNANJWEGRUFHPLUNSEROZQJSLMUYNUVG"
64 ."FPLQAGCMTTGIRRXZFBFQFTRBYPHTWFSXFKHKYBRDAOSOURCMEVGPVXJVUQAOCFPV"
65 ."OQSUBOYWOZLDGRPQQIBNOTHFUHTCRRZOBCUONAXIYUYCJBFTVNWIITVHBYLNMPWR"
66 ."LPMMIROZVRUNYXSJSMJINSXGACXDMJAEPNFFAERHVDJELXSPPJWKMNFGVGAPTIMR"
67 ."VMVMVCLWKMPOAJWZGPSPFEXVNQANXGLZIQSCBIYVFSTXZOODZYCXUVUZFCLFGHUJ"
68 ."TXZWFHSMFJQAZOQRANKZJAUJHFJIKHIIEQUSDXUBRPQBKMIAVTWYQEOIMYKKDTEV"
69 ."EYERPXKFJXWNIMJPOFFMWJCJSLFZKPNRNVXIDLUSRVBGLUCQZCUQCZNAORDXMRSS"
70 ."UBNMPXJDQXXLMQRCTOCCJJWHFSUWBNWXWZHPKWYYKPZIMBXTYAZXJJQSBLNAQGJI"
71 ."AIXZUHNTQYFSGUYMVOWEGUWWRBEMRJHXXOMLRXXWJZLPGLMKEANZWWXIXPIUTURJ"
72 ."TCXYIKIPNTSUIOWBCEVQHLTHYQNGBHAOPREWGJVOQKNUKTXVTMBRHCERDGYWQVXB"
73 ."BCZUGMIJXALLIOSXCYMEIDNTPLGRMKXKVFKWGRFKCBIRASOOYIFTLXFSBEOJSDFN"
74 ."PHSWPGERDYIGUPDX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OYSULGWUTSYTKGNMGZFWKXCCZXGOQGZNQFZJUK"
120 ."JMBQPQPZOPYTQMPEFTZUDLIIBZAZSZAPNILMIKMPKXJIRHRQMFSTJKAPIIQWOFYQ"
121 ."HGANJGJSUGDIENDVEQFEMUJBGMZBPHLOARCVGMUUCHLCDDNKSJSCKYSALUAGUZFN"
122 ."YVURVLREBESGXPANIDKGLPJZGXLKFKTPEQBQEINOYYZTBMPFBLBKIKVPAPFDKKRZ"
123 ."YMVUBYCYTRXCIICUPTXKGQOIJSVSWPYVALIROWGVXDXGNSRVZOLEJHNRSUKHNTRJ"
124 ."LQZQKBEFXYKIPXJRZMQMJKUGCNUKBZBWABPLHMAJJZVBCWOQYCLSGDUKJSTHTVXV"
125 ."OUGJVADGJWGVNBNXYRZDSNLOZDIQRKOQAKJJDKXRMMTXRVTLOMTETNROPDYNXAGR";
126
127 $S_load_stat = array( 'rU_heavy'      => 0,
128                       'lL_laccgarb'   => 0,
129                       'wU_lacc_upd'   => 0,
130                       'wR_garbage'    => 0,
131                       'wR_minusone'   => 0,
132                       'wR_the_end'    => 0 );
133
134 $mlang_indrd = array( 
135                      'btn_backtotab'  => array('it' => ' torna ai tavoli ',
136                                                'en' => ' back to tables '),
137                      'btn_btotabsup'  => array('it' => ' grazie della donazione, torna ai tavoli ',
138                                                'en' => ' thank you for donation, back to tables ') 
139                      );
140
141 class User {
142   var $room;       // reference to the room where the user is registered
143   var $idx;        // index in the users array when you are in game
144   var $idx_orig;   // index in the users array when you aren't in game
145   var $code;       // authentication code
146   var $name;       // name of the user
147   var $sess;       // session of the user
148   var $ip;         // ip of the user
149   var $lacc;       // last access (for the cleanup)
150   var $laccwr;     // last access (for the cleanup)
151   var $bantime;    // timeout to temporary ban
152   var $stat;       // status (outdoor, room, table, game, ...)
153   var $subst;      // substatus for each status   
154   var $step;       // step of the current status
155   var $trans_step; // step to enable transition between pages (disable == -1)
156
157   var $rd_socket;  // socket handle of push stream
158   var $rd_endtime; // end time for push stream
159   var $rd_stat;    // actual status of push stream
160   var $rd_subst;   // actual substatus of push stream
161   var $rd_step;    // actual step of push stream
162   var $rd_from;    // referer
163   var $rd_scristp; // current script step (for each session) 
164   var $rd_kalive;  // if no message are sent after RD_KEEPALIVE_TOUT secs we send a keepalive from server
165   var $rd_cache;   // place where store failed fwrite data
166
167   var $comm;       // commands array
168   // var $asta_card;  // 
169   // var $asta_pnt;   //
170   // var $handpt;     // Total card points at the beginning of the current hand.
171   // var $exitislock; // Player can exit from the table ?
172
173   // FIXME: the table_orig field must be removed after table field verify of index management (in spawned table
174   //        it is allways ZERO
175   var $table;      // id of the current table when you are in game
176   var $table_orig; // id of the current table when you aren't in game
177   var $table_pos;  // idx on the table
178   var $table_token;// token that identify a game on a table
179   var $flags;      // Bitfield with: AUTHENTICATE: 0x02 
180   var $the_end;    // Flag to change the end of the session
181
182   var $chat_lst;      // Last chat line
183   var $chattime;      // Array of chat times
184   var $chat_cur;      // Current chat line number
185   var $chat_ban;      // Time for ban chat
186   var $chat_dlt;      // Delta t for ban
187   var $shm_sz;
188
189   function User() {
190   }
191
192   function create(&$room, $idx, $name, $sess, $stat = "", $subst = "", $table = -1, $ip="0.0.0.0") {
193     if (($thiz = new User()) == FALSE)
194       return (FALSE);
195
196     $thiz->room       = &$room;
197     $thiz->idx        = $idx;
198     $thiz->idx_orig   = $idx;
199     $thiz->code       = -1;
200     $thiz->name       = $name;
201     $thiz->sess       = $sess;
202     $thiz->ip         = $ip;
203     $thiz->lacc       = time();
204     $thiz->laccwr     = time();
205     $thiz->bantime    = 0;
206     $thiz->stat       = $stat;
207     $thiz->subst      = $subst;
208     $thiz->step       = 1;
209     $thiz->trans_step = -1;
210     $thiz->comm       = array();
211
212     $thiz->rd_socket  = NULL;
213     $thiz->rd_endtime = -1;
214     $thiz->rd_stat    = -1;
215     $thiz->rd_subst   = "";
216     $thiz->rd_step    = -1;
217     $thiz->rd_from    = "";
218     $thiz->rd_scristp = -1;
219     $thiz->rd_kalive  = -1;
220     $thiz->rd_cache   = "";
221
222     $thiz->asta_card  = -2;
223     $thiz->asta_pnt   = -1;
224     $thiz->handpt     = -1;
225     $thiz->exitislock = TRUE;
226
227     $thiz->flags      = 0x00;
228     
229     $thiz->chattime   = array_fill(0, CHAT_N, 0);
230     $thiz->chat_cur   = 0;
231     $thiz->chat_lst   = "";
232     $thiz->chat_ban   = 0;
233     $thiz->chat_dlt   = 0;
234
235     $thiz->table_orig = $table;
236     $thiz->table      = $table;
237     $thiz->table_pos  = -1;
238     $thiz->table_token= "";
239     $thiz->shm_sz = SHM_DIMS_U_MIN;
240     return ($thiz);
241   }
242
243   function copy($from)
244   {
245     $this->idx        = $from->idx;
246     $this->idx_orig   = $from->idx;
247     $this->code       = $from->code;
248     $this->name       = $from->name;
249     $this->sess       = $from->sess;
250     $this->ip         = $from->ip;
251     $this->lacc       = $from->lacc;
252     $this->laccwr     = $from->laccwr;
253     $this->bantime    = $from->bantime;
254     $this->stat       = $from->stat;
255     $this->subst      = $from->subst;
256     $this->step       = $from->step;
257     $this->trans_step = $from->trans_step;
258     $this->comm       = array();
259
260     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
261     for ($i = $i_start ; $i < $from->step ; $i++) {
262         $ii = $i % COMM_N;
263         if (isset($from->comm[$ii])) {
264             $this->comm[$ii] = $from->comm[$ii];
265         }
266     }
267     $this->asta_card  = $from->asta_card;
268     $this->asta_pnt   = $from->asta_pnt;
269     $this->handpt     = $from->handpt;
270     $this->exitislock = $from->exitislock;
271
272     $this->flags      = $from->flags;
273
274     $this->chattime   = array();
275     for ($i = 0 ; $i < CHAT_N ; $i++)
276       $this->chattime[$i] = $from->chattime[$i];
277     $this->chat_cur   = $from->chat_cur;
278     $this->chat_lst   = $from->chat_lst;
279     $this->chat_ban   = $from->chat_ban;
280     $this->chat_dlt   = $from->chat_dlt;
281
282     $this->table_orig = $from->table_orig;
283     $this->table      = $from->table;
284     $this->table_pos  = $from->table_pos;
285     $this->table_token = $from->table_token;
286     $this->the_end    = $from->the_end;
287     $this->shm_sz     = $from->shm_sz;
288     return (TRUE);
289   }
290
291
292   function myclone($from)
293   {
294     if (($thiz = new User()) == FALSE)
295       return (FALSE);
296     
297     $thiz->copy($from);
298
299     return ($thiz);
300   }
301   
302   function spawn($from, $table, $table_pos)
303   {
304     if (($thiz = new User()) == FALSE)
305       return (FALSE);
306     
307     $thiz->idx        = $from->idx;
308     $thiz->idx_orig   = $from->idx;
309     $thiz->code       = $from->code;
310     $thiz->name       = $from->name;
311     $thiz->sess       = $from->sess;
312     $thiz->ip         = $from->ip;
313     $thiz->lacc       = $from->lacc;
314     $thiz->laccwr     = $from->laccwr;
315     $thiz->bantime    = $from->bantime;
316     $thiz->stat       = $from->stat;
317     $thiz->subst      = $from->subst;
318     $thiz->step       = $from->step;
319     $thiz->trans_step = $from->trans_step;
320     $thiz->comm       = array();
321
322     /*
323     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
324     for ($i = $i_start ; $i < $from->step ; $i++) {
325       log_wr("TRY PUSH:".$i);
326       $ii = $i % COMM_N;
327       $thiz->comm[$ii]   = $from->comm[$ii];
328     }
329     */
330     $thiz->asta_card  = $from->asta_card;
331     $thiz->asta_pnt   = $from->asta_pnt;
332     $thiz->handpt     = $from->handpt;
333     $thiz->exitislock = $from->exitislock;
334     $thiz->the_end    = $from->the_end;
335
336     $thiz->flags      = $from->flags;
337
338     $thiz->chattime   = array_fill(0, CHAT_N, 0);
339     $thiz->chat_cur   = 0;
340     $thiz->chat_lst   = "";
341     $thiz->chat_ban   = 0;
342     $thiz->chat_dlt   = 0;
343
344
345     $thiz->table_orig = $table;
346     $thiz->table      = 0;
347     $thiz->table_pos  = $table_pos;
348     $thiz->table_token = $from->table_token;
349     $thiz->shm_sz      = $from->shm_sz;
350
351     return ($thiz);
352   }
353
354   function rd_data_set($curtime, $stat, $subst, $step, $from)
355   {
356       $this->rd_endtime = $curtime + RD_ENDTIME_DELTA;
357       $this->rd_stat    = $stat;
358       $this->rd_subst   = $subst;
359       $this->rd_step    = $step;
360       $this->rd_from    = $from;
361       $this->rd_scristp = 0;
362       $this->rd_kalive  = $curtime + RD_KEEPALIVE_TOUT;
363   }
364
365   function rd_socket_get() {
366       return ($this->rd_socket);
367   }
368
369   function rd_socket_set($sock) {
370       $this->rd_socket = $sock;
371   }
372
373   function rd_kalive_get()
374   {
375       return ($this->rd_kalive);
376   }
377
378   function rd_kalive_set($tm)
379   {
380       $this->rd_kalive = $tm;
381   }
382
383   function rd_kalive_is_expired($tm)
384   {
385       // printf("rd_kalive %d tm %d\n", $this->rd_kalive, $tm);
386       return ($this->rd_kalive < $tm);
387   }
388
389   function rd_endtime_is_expired($tm)
390   {
391       // printf("rd_endtime %d tm %d\n", $this->rd_kalive, $tm);
392       return ($this->rd_endtime < $tm);
393   }
394
395   function rd_kalive_reset($tm)
396   {
397       $this->rd_kalive = $tm + RD_KEEPALIVE_TOUT;
398   }
399
400   function rd_cache_get()
401   {
402       return ($this->rd_cache);
403   }
404
405   function rd_cache_set($cache)
406   {
407       $this->rd_cache = $cache;
408   }
409
410   function idx_get() {
411       return ($this->idx);
412   }
413
414   function code_get() {
415       return ($this->code);
416   }
417   
418   function stat_set($stat) {
419     log_main("sess: [".$this->sess. "] NEW STAT: [".$stat."]"); 
420     $this->stat = "$stat";
421     
422     /*
423     if (validate_sess($this->sess)) {
424       if (file_exists(PROXY_PATH) == FALSE)
425         mkdir(PROXY_PATH, 0775, TRUE);
426       $fp = @fopen(PROXY_PATH."/".$this->sess.".stat", 'w');
427       fwrite($fp, sprintf("%s\n",$this->stat));
428       fclose($fp);
429     }
430     */
431   }
432
433   function step_set($step) 
434   {
435       $this->step = $step & 0x7fffffff;
436       
437       return (TRUE);
438   }
439
440   function step_inc($delta = 1) {
441       $this->step += $delta;
442       /* modularization because unpack() not manage unsigned 32bit int correctly */
443       $this->step &= 0x7fffffff;
444       
445       return TRUE;
446   }
447
448
449   function save_step() 
450   {
451       do {
452           if (validate_sess($this->sess) == FALSE)
453               break;
454           if (file_exists(PROXY_PATH) == FALSE)
455               mkdir(PROXY_PATH, 0775, TRUE);
456           if (($fp = @fopen(PROXY_PATH."/".$this->sess.".step", 'w')) == FALSE)
457               break;
458           fwrite($fp, pack("LL",$this->step, $this->idx));
459           fclose($fp);
460           
461           log_main("step_set [".$this->sess. "] [".$this->step."]"); 
462           
463           return (TRUE);
464       } while (0);
465       
466       return (FALSE);
467   }
468   
469   static function load_step($sess) 
470   {
471       $fp = FALSE;
472       do {
473           if (validate_sess($sess) == FALSE)
474               break;
475           
476           if (file_exists(PROXY_PATH) == FALSE)
477               mkdir(PROXY_PATH, 0775, TRUE);
478           if (($fp = @fopen(PROXY_PATH."/".$sess.".step", 'rb')) == FALSE)
479               break;
480           if (($s = fread($fp, 8)) == FALSE)
481               break;
482           if (mb_strlen($s, "ASCII") != 8)
483               break;
484           $arr = unpack('Ls/Li', $s);
485           fclose($fp);
486           
487           // log_rd2("A0: ".$arr[0]."  A1: ".$arr[1]);
488           return ($arr);
489       } while (0);
490       
491       if ($fp != FALSE)
492           fclose($fp);
493       
494       log_rd2("STEP_GET [".$sess."]: return false ");
495       
496       return (FALSE);
497   }
498
499   static function unproxy_step($sess) {
500       log_rd2("UNPROXY: ".PROXY_PATH."/".$sess.".step");
501       if (file_exists(PROXY_PATH) == FALSE)
502           return;
503       @unlink(PROXY_PATH."/".$sess.".step");
504   }
505
506   function reset() {
507     $curtime = time();
508     log_legal($curtime, 'xxx', $this, "STAT:LOGOUT", '');
509
510     $tmp_sess = $this->sess;
511     $this->sess = "";
512     self::unproxy_step($tmp_sess);
513     $this->name = "";  // OK here
514     while (array_pop($this->comm) != NULL);
515     $this->step = 0;
516     $this->chattime = array_fill(0, CHAT_N, 0);
517     $this->chat_cur = 0;
518     $this->chat_lst = "";
519     $this->chat_ban = 0;
520     $this->chat_dlt = 0;
521     $this->the_end = FALSE;
522   }
523
524   static function load_data($id, $sess) 
525   {
526       log_main("load_data: id [".$id."] sess [".($sess == FALSE ? "FALSE" : $sess)."] ");
527       
528       do {
529           if (($tok = @ftok(FTOK_PATH."/user".$id, "B")) == -1) {
530               log_main("ftok failed");
531               break;
532           }
533           
534           if (($shm_sz = sharedmem_sz($tok)) == -1) {
535               log_main("shmop_open failed");
536           }
537           
538           if ($shm_sz == -1)
539               $shm_sz = SHM_DIMS_U_MIN;
540           
541           if ($shm = shm_attach($tok, $shm_sz)) {
542               if (($user = @shm_get_var($shm, $tok)) == FALSE) {
543                   break;
544               }
545               if ($sess != FALSE && $user->sess != $sess) {
546                   break;
547               }
548               log_only("user ==  ".($user == FALSE ?   "FALSE" : "TRUE")."  user ===  ".($user === FALSE ? "FALSE" : "TRUE")."  user isset ".(isset($user) ?   "TRUE" : "FALSE"));
549               
550               if ($user == FALSE) {
551                   log_only("INIT MAIN DATA");
552                   
553                   // SHSPLIT FIXME: init_data for User class ??
554                   $user = self::create($id, "", "");
555                   if (@shm_put_var($shm, $tok, $user) == FALSE) {
556                       log_only("PUT_VAR FALLITA ".strlen(serialize($user)));
557                       log_only(serialize($user));
558                   }
559                   log_shme("User::save_data2");
560               }
561               else {
562                   if ($sess != FALSE) {
563                       /*
564                        *  NOTE:  this part is for check only, theoretically 
565                        *         user->step anch proxy_step are set allways at the same value
566                        */
567                       $old_step = $user->step;
568                       $arr = self::load_step($sess);
569                       $user->step = $arr['s'];
570                       if ($old_step != $user->step) {
571                           log_crit("steps are diffetents User->step ".$user->step." Old_step: ".$old_step);
572                       }
573                   }
574               }
575               $user->shm_sz = $shm_sz;
576               
577               shm_detach($shm);
578           }
579           
580           //  
581           // SHSPLIT: load users from the shared memory
582           //
583           return ($user);
584       } while (0);
585       
586       return (FALSE);
587   }
588   
589
590   static function save_data($user, $id) 
591   {
592       GLOBAL $sess;
593       
594       $shm =   FALSE;
595       
596       if (($tok = @ftok(FTOK_PATH."/user".$id, "B")) == -1) {
597           return (FALSE);
598       }
599       while ($user->shm_sz < SHM_DIMS_U_MAX) {
600           if (($shm = shm_attach($tok, $user->shm_sz)) == FALSE)
601               break;
602           
603           // log_only("PUT_VAR DI ".strlen(serialize($user)));
604           if (@shm_put_var($shm, $tok, $user) != FALSE) {
605               shm_detach($shm);
606               if ($user->sess != "")
607                   $user->save_step();
608
609               log_shme("User::save_data");
610
611               log_main("User[".$id."] saved.");
612               return (TRUE);
613           }
614           if (shm_remove($shm) === FALSE) {
615               log_only("REMOVE FALLITA");
616               break;
617           }
618           shm_detach($shm);
619           $user->shm_sz += SHM_DIMS_U_DLT;
620       } 
621       
622       if ($shm)
623           shm_detach($shm);
624       
625       return (FALSE);
626   }
627
628   function myname_innerHTML()
629   {
630       $class_id = ($this->flags & USER_FLAG_AUTH) + 1;
631       
632       return (sprintf('$("myname").innerHTML = "<span class=\"au%d\">%s</span>";', $class_id, 
633                       xcape($this->name,ENT_COMPAT,"UTF-8")));
634   }
635
636   /* INDEX_RD_IFRA PORT */
637
638   static function blocking_error($is_unrecoverable)
639   {
640       GLOBAL $is_page_streaming;
641       
642       $is_page_streaming = TRUE;
643       log_crit("BLOCKING_ERROR UNREC: ".($is_unrecoverable ? "TRUE" : "FALSE"));
644       return (sprintf(($is_unrecoverable ? 'hstm.stop(); ' : '').'window.onbeforeunload = null; window.onunload = null; document.location.assign("index.php");'));
645   }
646   
647   // FIXME TO SUPPORT iframe
648   static function page_sync($sess, $page, $table_idx, $table_token)
649   {
650       GLOBAL $is_page_streaming;
651       
652       log_rd2("page_sync:".var_export(debug_backtrace()));
653       
654       $is_page_streaming = TRUE;
655       
656       log_rd2("PAGE_SYNC");
657       return (sprintf('createCookie("table_idx", %d, 24*365, cookiepath); createCookie("table_token", "%s", 24*365, cookiepath); hstm.stop(); window.onunload = null; window.onbeforeunload = null; document.location.assign("%s");', $table_idx, $table_token, $page));
658   }
659
660
661
662
663   function maincheck($cur_stat, $cur_subst, $cur_step, &$new_stat, &$new_subst, &$new_step, $splashdate)
664   {
665       GLOBAL $G_lang, $mlang_indrd, $is_page_streaming;
666       // GLOBAL $first_loop;
667       GLOBAL $G_with_splash, $G_splash_content, $G_splash_interval, $G_splash_idx;
668       GLOBAL $G_splash_w, $G_splash_h, $G_splash_timeout;
669       $CO_splashdate = "CO_splashdate".$G_splash_idx;
670       $$CO_splashdate = $splashdate;
671       
672       GLOBAL $S_load_stat;
673       
674       log_rd("maincheck begin");
675       
676       $ret = FALSE;
677       $curtime = time();
678       
679       if ((($curtime - $this->lacc) >  STREAM_TIMEOUT) || Room::garbage_time_is_expired($curtime)) {
680           $S_load_stat['lL_laccgarb']++;
681           
682           if (($curtime - $this->lacc) >=  STREAM_TIMEOUT) {
683               $S_load_stat['wU_lacc_upd']++;
684               $this->lacc = $curtime;
685           }
686           
687           if (Room::garbage_time_is_expired($curtime)) {
688               log_only("F");
689               
690               $S_load_stat['wR_garbage']++;
691               log_main("pre garbage_manager TRE");
692               $this->room->garbage_manager(FALSE);
693           }
694       }
695       
696       /* Nothing changed, return. */
697       if ($cur_step == $this->step) 
698           return (FALSE);
699       
700       log_rd2("do other cur_stat[".$cur_stat."] user->stat[".$this->stat."] cur_step[".$cur_step."] user_step[".$this->step."]");
701       
702       if ($cur_step == -1) {
703           /*
704            *  if $cur_step == -1 load the current state from the main struct
705            */
706           
707           $S_load_stat['wR_minusone']++;
708           
709           if ($this->the_end == TRUE) { 
710               log_rd2("main_check: the end".var_export(debug_backtrace()));
711               $is_page_streaming = TRUE;
712           }
713           
714           if ($this->trans_step != -1) {
715               log_rd2("TRANS USATO ".$this->trans_step);
716               $cur_step = $this->trans_step;
717               $this->trans_step = -1;
718           }
719           else {
720               log_rd2("TRANS NON ATTIVATO");
721           }
722       }
723       
724       
725       /* this part I suppose is read only on $this->room structure */
726       if ($cur_step == -1) {
727           log_rd2("PRE-NEWSTAT: ".$this->stat);
728           
729           if ($this->stat == 'room') {
730               log_rd("roomma ".$this->step);
731               $curtime = time();
732               
733               if ($G_with_splash &&
734                   ($$CO_splashdate < $curtime - $G_splash_interval ||
735                    $$CO_splashdate > $curtime)) {
736                   $is_super = $this->flags & USER_FLAG_TY_SUPER;
737                   $ret .=  show_notify_ex(str_replace("\n", " ", $G_splash_content[$G_lang]), 
738                                           ($is_super ? 0 : $G_splash_timeout), 
739                                           $mlang_indrd[($is_super ? 'btn_btotabsup' : 'btn_backtotab')][$G_lang], 
740                                           $G_splash_w, $G_splash_h, true, 
741                                           ($is_super ? 0 : $G_splash_timeout));
742                   $ret .= sprintf('|createCookie("CO_splashdate%d", %d, 24*365, cookiepath);', $G_splash_idx, $curtime);
743               }
744               $ret .= $this->room->show_room($this->step, $this);
745               
746               // TODO uncomment and test
747               /* NOTE the sets went common */
748               $new_stat =  $this->stat;
749               $new_subst = $this->subst;
750               $new_step =  $this->step;
751           }
752           /***************
753            *             *
754            *    TABLE    *
755            *             *
756            ***************/
757           else if ($this->stat == 'table') {
758               log_load("RESYNC");
759               return (self::page_sync($this->sess, "briskin5/index.php", $this->table, $this->table_token));
760           }
761           log_rd2("NEWSTAT: ".$this->stat);
762       } /* if ($cur_step == -1) { */
763       else {
764           /* $sem = Room::lock_data(FALSE); */
765           $S_load_stat['rU_heavy']++;
766           
767           if ($cur_step < $this->step) {
768               do {
769                   if ($cur_step + COMM_N < $this->step) {
770                       if (($cur_stat != $this->stat)) {
771                           $to_stat = $this->stat;
772                           /* Room::unlock_data($sem); */
773                           log_load("RESYNC");
774                           return (self::page_sync($this->sess, ($to_stat == "table" ? "briskin5/index.php" : "index.php"), $this->table, $this->table_token));
775                       }
776                       log_rd2("lost history, refresh from scratch");
777                       $new_step = -1;
778                       break;
779                   } 
780                   for ($i = $cur_step ; $i < $this->step ; $i++) {
781                       $ii = $i % COMM_N;
782                       log_rd2("ADDED TO THE STREAM: ".$this->comm[$ii]);
783                       $ret .= $this->comm[$ii];
784                   }
785                   $new_stat =  $this->stat;
786                   $new_subst = $this->subst;
787                   $new_step =  $this->step;
788               } while (0);
789               
790               log_rd2($this->step, 'index_rd.php: after ret set');
791               
792               if ($this->the_end == TRUE) {
793                   log_rd2("LOGOUT BYE BYE!!");
794                   log_auth($this->sess, "Explicit logout.");
795                   
796                   if ($this->the_end == TRUE) {
797                       $this->reset();
798                       
799                       if ($this->subst == 'sitdown') {
800                           log_load("ROOM WAKEUP");
801                           $this->room->room_wakeup($this);
802                       }
803                       else if ($this->subst == 'standup')
804                           $this->room->room_outstandup($this);
805                       else
806                           log_rd2("LOGOUT FROM WHAT ???");
807                       
808                   } /* if ($this->the_end == TRUE) { ... */
809               } /* if ($this->the_end == TRUE) { ... */
810           } /* if ($cur_step < $this->step) { */
811           
812           /* Room::unlock_data($sem); */
813       }  /* else of if ($cur_step == -1) { */
814       
815     
816       return ($ret);
817   }  //   function maincheck (...
818
819 static function stream_fini($is_unrecoverable)
820 {
821     GLOBAL $G_four_rnd_string;
822
823     // IF IFRAME THEN:
824     $body = "";
825     $body .= sprintf("<html>
826 <head>
827 <script type=\"text/javascript\" src=\"commons.js\"></script>
828 <script type=\"text/javascript\" src=\"xynt-http-streaming-ifra.js\"></script>
829 <script type=\"text/javascript\">
830 var http_streaming = \"ready\";");
831     $body .= sprintf("
832 window.onload = function () { if (http_streaming != \"ready\") { http_streaming.reload(); } };
833 </script>
834 </head>
835 <body>");
836     $body .= sprintf("<!-- \n%s -->\n", $G_four_rnd_string);
837     $body .= sprintf("<script id='hs%d' type='text/javascript'><!--
838 push(\"%s\");
839 // -->
840 </script>", 0, escpush(self::blocking_error($is_unrecoverable)) );
841     // ELSE IF XHR THEN:
842     // return (self::blocking_error($is_unrecoverable));
843     return ($body);
844 }
845
846 /*
847  *  MAIN
848  */
849
850 /*
851    FROM THE EXTERN 
852    sess
853    stat
854    step
855 */
856 function stream_init(&$header_out, &$body, $get, $post, $cookie)
857 {
858     GLOBAL $G_four_rnd_string;
859
860     $curtime = time();
861
862     $is_page_streaming = FALSE; // (webservers_exceeded() || stristr($HTTP_USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; rv:5.0)") || stristr($HTTP_USER_AGENT, "MSIE") || stristr($HTTP_USER_AGENT, "CHROME") ? TRUE : FALSE);
863
864     $header_out['Cache-Control'] = 'no-cache, must-revalidate';     // HTTP/1.1
865     $header_out['Expires']       = 'Mon, 26 Jul 1997 05:00:00 GMT'; // Date in the past
866     $header_out['Content-type']  = 'text/html; charset="utf-8"';
867
868     log_load("index_rd_ifra_init.php");
869
870     if (($from  = gpcs_var('from', $get, $post, $cookie)) === FALSE)
871         $from = "";
872     if (($stat  = gpcs_var('stat', $get, $post, $cookie)) === FALSE) 
873         $stat = "";
874     if (($subst = gpcs_var('subst', $get, $post, $cookie)) === FALSE) 
875         $subst = "";
876     if (($step  = gpcs_var('step', $get, $post, $cookie)) === FALSE) 
877         unset($step);
878     
879     $this->rd_data_set($curtime, $stat, $subst, $step, $from);
880
881     $body .= sprintf("<html>
882 <head>
883 <script type=\"text/javascript\" src=\"commons.js\"></script>
884 <script type=\"text/javascript\" src=\"xynt-http-streaming-ifra.js\"></script>
885 <script type=\"text/javascript\">
886 var http_streaming = \"ready\";");
887     if ($this->rd_scristp > 0)
888         $body .= sprintf("last_clean = %d;\n", ($this->rd_scristp-1));
889     $body .= sprintf("
890 window.onload = function () { if (http_streaming != \"ready\") { http_streaming.reload(); } };
891 </script> 
892 </head>
893 <body>");
894     $body .= sprintf("<!-- \n%s -->\n", $G_four_rnd_string);
895
896     return TRUE;
897 }
898
899 function stream_main(&$body, $get, $post, $cookie)
900 {
901     GLOBAL $is_page_streaming, $G_splash_idx;
902     // FIXME: only to test fwrite
903     // GLOBAL $G_four_rnd_string;
904
905     $CO_splashdate = "CO_splashdate".$G_splash_idx;
906     if (($splashdate = gpcs_var("$CO_splashdate", $get, $post, $cookie)) === FALSE)
907         $splashdate = ""; 
908
909     $is_page_streaming = FALSE;
910     log_rd2("FROM OUTSIDE - STAT: ".$this->rd_stat." SUBST: ".$this->rd_subst." STEP: ".$this->rd_step." FROM: ".$this->rd_from. "IS_PAGE:" . $is_page_streaming);
911     
912     
913     $pre_main = gettimeofday(TRUE);
914     
915     $old_stat  = $this->rd_stat;
916     $old_subst = $this->rd_subst;
917     $old_step  = $this->rd_step;
918     if (($ret = maincheck($this, $old_stat, $old_subst, $old_step, $this->rd_stat, $this->rd_subst, $this->rd_step, $splashdate)) != FALSE) {
919         $body .= sprintf("<script id='hs%d' type='text/javascript'><!--
920 push(\"%s\");
921 // -->
922 </script>", $this->rd_scristp++, escpush($ret) );
923         
924         log_rd2(0, 'index_rd.php: after mop_flush (begin: '.sprintf("%f", $pre_main).')');
925         if ($is_page_streaming) 
926             return TRUE;
927     }
928     
929     return TRUE;
930 }
931
932 function stream_keepalive()
933 {
934     return (sprintf("<script id='hs%d' type='text/javascript'><!--
935 push(null);
936 // -->
937 </script>", $this->rd_scristp++));
938     
939 }
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971 } // end class User
972
973
974 ?>