stream_ping functionalities added to stream_keepalive function
[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 ."PHSWPGERDYIGUPD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BOYSULGWUTSYTKGNMGZFWKXCCZXGOQGZNQFZJUK"
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   const BASE = "";    // basepath for absolute web references
190
191   function User() {
192   }
193
194   function create(&$room, $idx, $name, $sess, $stat = "", $subst = "", $table = -1, $ip="0.0.0.0") {
195     if (($thiz = new User()) == FALSE)
196       return (FALSE);
197
198     $thiz->room       = &$room;
199     $thiz->idx        = $idx;
200     $thiz->idx_orig   = $idx;
201     $thiz->code       = -1;
202     $thiz->name       = $name;
203     $thiz->sess       = $sess;
204     $thiz->ip         = $ip;
205     $thiz->lacc       = time();
206     $thiz->laccwr     = time();
207     $thiz->bantime    = 0;
208     $thiz->stat       = $stat;
209     $thiz->subst      = $subst;
210     $thiz->step       = 1;
211     $thiz->trans_step = -1;
212     $thiz->comm       = array();
213
214     $thiz->rd_socket  = NULL;
215     $thiz->rd_endtime = -1;
216     $thiz->rd_stat    = -1;
217     $thiz->rd_subst   = "";
218     $thiz->rd_step    = -1;
219     $thiz->rd_from    = "";
220     $thiz->rd_scristp = -1;
221     $thiz->rd_kalive  = -1;
222     $thiz->rd_cache   = "";
223
224     $thiz->asta_card  = -2;
225     $thiz->asta_pnt   = -1;
226     $thiz->handpt     = -1;
227     $thiz->exitislock = TRUE;
228
229     $thiz->flags      = 0x00;
230     
231     $thiz->chattime   = array_fill(0, CHAT_N, 0);
232     $thiz->chat_cur   = 0;
233     $thiz->chat_lst   = "";
234     $thiz->chat_ban   = 0;
235     $thiz->chat_dlt   = 0;
236
237     $thiz->table_orig = $table;
238     $thiz->table      = $table;
239     $thiz->table_pos  = -1;
240     $thiz->table_token= "";
241     $thiz->shm_sz = SHM_DIMS_U_MIN;
242     return ($thiz);
243   }
244
245   function copy($from)
246   {
247     $this->idx        = $from->idx;
248     $this->idx_orig   = $from->idx;
249     $this->code       = $from->code;
250     $this->name       = $from->name;
251     $this->sess       = $from->sess;
252     $this->ip         = $from->ip;
253     $this->lacc       = $from->lacc;
254     $this->laccwr     = $from->laccwr;
255     $this->bantime    = $from->bantime;
256     $this->stat       = $from->stat;
257     $this->subst      = $from->subst;
258     $this->step       = $from->step;
259     $this->trans_step = $from->trans_step;
260     $this->comm       = array();
261
262     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
263     for ($i = $i_start ; $i < $from->step ; $i++) {
264         $ii = $i % COMM_N;
265         if (isset($from->comm[$ii])) {
266             $this->comm[$ii] = $from->comm[$ii];
267         }
268     }
269     $this->asta_card  = $from->asta_card;
270     $this->asta_pnt   = $from->asta_pnt;
271     $this->handpt     = $from->handpt;
272     $this->exitislock = $from->exitislock;
273
274     $this->flags      = $from->flags;
275
276     $this->chattime   = array();
277     for ($i = 0 ; $i < CHAT_N ; $i++)
278       $this->chattime[$i] = $from->chattime[$i];
279     $this->chat_cur   = $from->chat_cur;
280     $this->chat_lst   = $from->chat_lst;
281     $this->chat_ban   = $from->chat_ban;
282     $this->chat_dlt   = $from->chat_dlt;
283
284     $this->table_orig = $from->table_orig;
285     $this->table      = $from->table;
286     $this->table_pos  = $from->table_pos;
287     $this->table_token = $from->table_token;
288     $this->the_end    = $from->the_end;
289     $this->shm_sz     = $from->shm_sz;
290     return (TRUE);
291   }
292
293
294   function myclone($from)
295   {
296     if (($thiz = new User()) == FALSE)
297       return (FALSE);
298     
299     $thiz->copy($from);
300
301     return ($thiz);
302   }
303   
304   function spawn($from, $table, $table_pos)
305   {
306     if (($thiz = new User()) == FALSE)
307       return (FALSE);
308     
309     $thiz->idx        = $from->idx;
310     $thiz->idx_orig   = $from->idx;
311     $thiz->code       = $from->code;
312     $thiz->name       = $from->name;
313     $thiz->sess       = $from->sess;
314     $thiz->ip         = $from->ip;
315     $thiz->lacc       = $from->lacc;
316     $thiz->laccwr     = $from->laccwr;
317     $thiz->bantime    = $from->bantime;
318     $thiz->stat       = $from->stat;
319     $thiz->subst      = $from->subst;
320     $thiz->step       = $from->step;
321     $thiz->trans_step = $from->trans_step;
322     $thiz->comm       = array();
323
324     /*
325     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
326     for ($i = $i_start ; $i < $from->step ; $i++) {
327       log_wr("TRY PUSH:".$i);
328       $ii = $i % COMM_N;
329       $thiz->comm[$ii]   = $from->comm[$ii];
330     }
331     */
332     $thiz->asta_card  = $from->asta_card;
333     $thiz->asta_pnt   = $from->asta_pnt;
334     $thiz->handpt     = $from->handpt;
335     $thiz->exitislock = $from->exitislock;
336     $thiz->the_end    = $from->the_end;
337
338     $thiz->flags      = $from->flags;
339
340     $thiz->chattime   = array_fill(0, CHAT_N, 0);
341     $thiz->chat_cur   = 0;
342     $thiz->chat_lst   = "";
343     $thiz->chat_ban   = 0;
344     $thiz->chat_dlt   = 0;
345
346
347     $thiz->table_orig = $table;
348     $thiz->table      = 0;
349     $thiz->table_pos  = $table_pos;
350     $thiz->table_token = $from->table_token;
351     $thiz->shm_sz      = $from->shm_sz;
352
353     return ($thiz);
354   }
355
356   function rd_data_set($curtime, $stat, $subst, $step, $from)
357   {
358       $this->rd_endtime = $curtime + RD_ENDTIME_DELTA;
359       $this->rd_stat    = $stat;
360       $this->rd_subst   = $subst;
361       $this->rd_step    = $step;
362       $this->rd_from    = $from;
363       $this->rd_scristp = 0;
364       $this->rd_kalive  = $curtime + RD_KEEPALIVE_TOUT;
365   }
366
367   function rd_socket_get() {
368       return ($this->rd_socket);
369   }
370
371   function rd_socket_set($sock) {
372       $this->rd_socket = $sock;
373   }
374
375   function rd_kalive_get()
376   {
377       return ($this->rd_kalive);
378   }
379
380   function rd_kalive_set($tm)
381   {
382       $this->rd_kalive = $tm;
383   }
384
385   function rd_kalive_is_expired($tm)
386   {
387       // printf("rd_kalive %d tm %d\n", $this->rd_kalive, $tm);
388       return ($this->rd_kalive < $tm);
389   }
390
391   function rd_endtime_is_expired($tm)
392   {
393       // printf("rd_endtime %d tm %d\n", $this->rd_kalive, $tm);
394       return ($this->rd_endtime < $tm);
395   }
396
397   function rd_kalive_reset($tm)
398   {
399       $this->rd_kalive = $tm + RD_KEEPALIVE_TOUT;
400   }
401
402   function rd_cache_get()
403   {
404       return ($this->rd_cache);
405   }
406
407   function rd_cache_set($cache)
408   {
409       $this->rd_cache = $cache;
410   }
411
412   function idx_get() {
413       return ($this->idx);
414   }
415
416   function code_get() {
417       return ($this->code);
418   }
419   
420   function stat_set($stat) {
421     log_main("sess: [".$this->sess. "] NEW STAT: [".$stat."]"); 
422     $this->stat = "$stat";
423     
424     /*
425     if (validate_sess($this->sess)) {
426       if (file_exists(PROXY_PATH) == FALSE)
427         mkdir(PROXY_PATH, 0775, TRUE);
428       $fp = @fopen(PROXY_PATH."/".$this->sess.".stat", 'w');
429       fwrite($fp, sprintf("%s\n",$this->stat));
430       fclose($fp);
431     }
432     */
433   }
434
435   function step_set($step) 
436   {
437       $this->step = $step & 0x7fffffff;
438       
439       return (TRUE);
440   }
441
442   function step_inc($delta = 1) {
443       $this->step += $delta;
444       /* modularization because unpack() not manage unsigned 32bit int correctly */
445       $this->step &= 0x7fffffff;
446       
447       return TRUE;
448   }
449
450
451   function save_step() 
452   {
453       do {
454           if (validate_sess($this->sess) == FALSE)
455               break;
456           if (file_exists(PROXY_PATH) == FALSE)
457               mkdir(PROXY_PATH, 0775, TRUE);
458           if (($fp = @fopen(PROXY_PATH."/".$this->sess.".step", 'w')) == FALSE)
459               break;
460           fwrite($fp, pack("LL",$this->step, $this->idx));
461           fclose($fp);
462           
463           log_main("step_set [".$this->sess. "] [".$this->step."]"); 
464           
465           return (TRUE);
466       } while (0);
467       
468       return (FALSE);
469   }
470   
471   static function load_step($sess) 
472   {
473       $fp = FALSE;
474       do {
475           if (validate_sess($sess) == FALSE)
476               break;
477           
478           if (file_exists(PROXY_PATH) == FALSE)
479               mkdir(PROXY_PATH, 0775, TRUE);
480           if (($fp = @fopen(PROXY_PATH."/".$sess.".step", 'rb')) == FALSE)
481               break;
482           if (($s = fread($fp, 8)) == FALSE)
483               break;
484           if (mb_strlen($s, "ASCII") != 8)
485               break;
486           $arr = unpack('Ls/Li', $s);
487           fclose($fp);
488           
489           // log_rd2("A0: ".$arr[0]."  A1: ".$arr[1]);
490           return ($arr);
491       } while (0);
492       
493       if ($fp != FALSE)
494           fclose($fp);
495       
496       log_rd2("STEP_GET [".$sess."]: return false ");
497       
498       return (FALSE);
499   }
500
501   static function unproxy_step($sess) {
502       log_rd2("UNPROXY: ".PROXY_PATH."/".$sess.".step");
503       if (file_exists(PROXY_PATH) == FALSE)
504           return;
505       @unlink(PROXY_PATH."/".$sess.".step");
506   }
507
508   function reset() {
509     $curtime = time();
510     log_legal($curtime, 'xxx', $this, "STAT:LOGOUT", '');
511
512     $tmp_sess = $this->sess;
513     $this->sess = "";
514     self::unproxy_step($tmp_sess);
515     $this->name = "";  // OK here
516     while (array_pop($this->comm) != NULL);
517     $this->step = 0;
518     $this->chattime = array_fill(0, CHAT_N, 0);
519     $this->chat_cur = 0;
520     $this->chat_lst = "";
521     $this->chat_ban = 0;
522     $this->chat_dlt = 0;
523     $this->the_end = FALSE;
524   }
525
526   static function load_data($id, $sess) 
527   {
528       log_main("load_data: id [".$id."] sess [".($sess == FALSE ? "FALSE" : $sess)."] ");
529       
530       do {
531           if (($tok = @ftok(FTOK_PATH."/user".$id, "B")) == -1) {
532               log_main("ftok failed");
533               break;
534           }
535           
536           if (($shm_sz = sharedmem_sz($tok)) == -1) {
537               log_main("shmop_open failed");
538           }
539           
540           if ($shm_sz == -1)
541               $shm_sz = SHM_DIMS_U_MIN;
542           
543           if ($shm = shm_attach($tok, $shm_sz)) {
544               if (($user = @shm_get_var($shm, $tok)) == FALSE) {
545                   break;
546               }
547               if ($sess != FALSE && $user->sess != $sess) {
548                   break;
549               }
550               log_only("user ==  ".($user == FALSE ?   "FALSE" : "TRUE")."  user ===  ".($user === FALSE ? "FALSE" : "TRUE")."  user isset ".(isset($user) ?   "TRUE" : "FALSE"));
551               
552               if ($user == FALSE) {
553                   log_only("INIT MAIN DATA");
554                   
555                   // SHSPLIT FIXME: init_data for User class ??
556                   $user = self::create($id, "", "");
557                   if (@shm_put_var($shm, $tok, $user) == FALSE) {
558                       log_only("PUT_VAR FALLITA ".strlen(serialize($user)));
559                       log_only(serialize($user));
560                   }
561                   log_shme("User::save_data2");
562               }
563               else {
564                   if ($sess != FALSE) {
565                       /*
566                        *  NOTE:  this part is for check only, theoretically 
567                        *         user->step anch proxy_step are set allways at the same value
568                        */
569                       $old_step = $user->step;
570                       $arr = self::load_step($sess);
571                       $user->step = $arr['s'];
572                       if ($old_step != $user->step) {
573                           log_crit("steps are diffetents User->step ".$user->step." Old_step: ".$old_step);
574                       }
575                   }
576               }
577               $user->shm_sz = $shm_sz;
578               
579               shm_detach($shm);
580           }
581           
582           //  
583           // SHSPLIT: load users from the shared memory
584           //
585           return ($user);
586       } while (0);
587       
588       return (FALSE);
589   }
590   
591
592   static function save_data($user, $id) 
593   {
594       GLOBAL $sess;
595       
596       $shm =   FALSE;
597       
598       if (($tok = @ftok(FTOK_PATH."/user".$id, "B")) == -1) {
599           return (FALSE);
600       }
601       while ($user->shm_sz < SHM_DIMS_U_MAX) {
602           if (($shm = shm_attach($tok, $user->shm_sz)) == FALSE)
603               break;
604           
605           // log_only("PUT_VAR DI ".strlen(serialize($user)));
606           if (@shm_put_var($shm, $tok, $user) != FALSE) {
607               shm_detach($shm);
608               if ($user->sess != "")
609                   $user->save_step();
610
611               log_shme("User::save_data");
612
613               log_main("User[".$id."] saved.");
614               return (TRUE);
615           }
616           if (shm_remove($shm) === FALSE) {
617               log_only("REMOVE FALLITA");
618               break;
619           }
620           shm_detach($shm);
621           $user->shm_sz += SHM_DIMS_U_DLT;
622       } 
623       
624       if ($shm)
625           shm_detach($shm);
626       
627       return (FALSE);
628   }
629
630   function myname_innerHTML()
631   {
632       $class_id = ($this->flags & USER_FLAG_AUTH) + 1;
633       
634       return (sprintf('$("myname").innerHTML = "<span class=\"au%d\">%s</span>";', $class_id, 
635                       xcape($this->name,ENT_COMPAT,"UTF-8")));
636   }
637
638   /* INDEX_RD_IFRA PORT */
639
640   protected function blocking_error($is_unrecoverable)
641   {
642       GLOBAL $is_page_streaming;
643       
644       $is_page_streaming = TRUE;
645       log_crit("BLOCKING_ERROR UNREC: ".($is_unrecoverable ? "TRUE" : "FALSE"));
646       return (sprintf(($is_unrecoverable ? 'hstm.stop(); ' : '').'window.onbeforeunload = null; window.onunload = null; document.location.assign("index.php");'));
647   }
648   
649   // FIXME TO SUPPORT iframe
650   protected function page_sync($sess, $page, $table_idx, $table_token)
651   {
652       GLOBAL $is_page_streaming;
653       
654       // log_rd2("page_sync:".var_export(debug_backtrace()));
655       
656       $is_page_streaming = TRUE;
657       
658       log_rd2("PAGE_SYNC");
659       printf("xXx USER::PAGE_SYNC [%s]\n", get_class($this));
660       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));
661   }
662
663
664
665
666   protected function maincheck($cur_stat, $cur_subst, $cur_step, &$new_stat, &$new_subst, &$new_step, $splashdate, $table_idx, $table_token)
667   {
668       GLOBAL $G_lang, $mlang_indrd, $is_page_streaming;
669       // GLOBAL $first_loop;
670       GLOBAL $G_with_splash, $G_splash_content, $G_splash_interval, $G_splash_idx;
671       GLOBAL $G_splash_w, $G_splash_h, $G_splash_timeout;
672       $CO_splashdate = "CO_splashdate".$G_splash_idx;
673       $$CO_splashdate = $splashdate;
674       
675       GLOBAL $S_load_stat;
676       
677       log_rd("maincheck begin");
678       
679       $ret = FALSE;
680       $curtime = time();
681       
682       /* if ((($curtime - $this->lacc) >  STREAM_TIMEOUT) || Room::garbage_time_is_expired($curtime)) { */
683       /*     $S_load_stat['lL_laccgarb']++; */
684           
685       /*     if (($curtime - $this->lacc) >=  STREAM_TIMEOUT) { */
686       /*         $S_load_stat['wU_lacc_upd']++; */
687       /*         $this->lacc = $curtime; */
688       /*     } */
689           
690       /*     if (Room::garbage_time_is_expired($curtime)) { */
691       /*         log_only("F"); */
692               
693       /*         $S_load_stat['wR_garbage']++; */
694       /*         log_main("pre garbage_manager TRE"); */
695       /*         $this->room->garbage_manager(FALSE); */
696       /*     } */
697       /* } */
698       
699       /* Nothing changed, return. */
700       if ($cur_step == $this->step) 
701           return (FALSE);
702       
703       log_rd2("do other cur_stat[".$cur_stat."] user->stat[".$this->stat."] cur_step[".$cur_step."] user_step[".$this->step."]");
704       
705       if ($cur_step == -1) {
706           /*
707            *  if $cur_step == -1 load the current state from the main struct
708            */
709           
710           $S_load_stat['wR_minusone']++;
711           
712           if ($this->the_end == TRUE) { 
713               log_rd2("main_check: the end".var_export(debug_backtrace()));
714               $is_page_streaming = TRUE;
715           }
716           
717           if ($this->trans_step != -1) {
718               log_rd2("TRANS USATO ".$this->trans_step);
719               $cur_step = $this->trans_step;
720               $this->trans_step = -1;
721           }
722           else {
723               log_rd2("TRANS NON ATTIVATO");
724           }
725       }
726       
727       
728       /* this part I suppose is read only on $this->room structure */
729       if ($cur_step == -1) {
730           log_rd2("PRE-NEWSTAT: ".$this->stat);
731           
732           if ($this->stat == 'room') {
733               log_rd("roomma ".$this->step);
734               $curtime = time();
735               
736               if ($G_with_splash &&
737                   ($$CO_splashdate < $curtime - $G_splash_interval ||
738                    $$CO_splashdate > $curtime)) {
739                   $is_super = $this->flags & USER_FLAG_TY_SUPER;
740                   $ret .=  show_notify_ex(str_replace("\n", " ", $G_splash_content[$G_lang]), 
741                                           ($is_super ? 0 : $G_splash_timeout), 
742                                           $mlang_indrd[($is_super ? 'btn_btotabsup' : 'btn_backtotab')][$G_lang], 
743                                           $G_splash_w, $G_splash_h, true, 
744                                           ($is_super ? 0 : $G_splash_timeout));
745                   $ret .= sprintf('|createCookie("CO_splashdate%d", %d, 24*365, cookiepath);', $G_splash_idx, $curtime);
746               }
747               $ret .= $this->room->show_room($this->step, $this);
748               
749               // TODO uncomment and test
750               /* NOTE the sets went common */
751               $new_stat =  $this->stat;
752               $new_subst = $this->subst;
753               $new_step =  $this->step;
754           }
755           /***************
756            *             *
757            *    TABLE    *
758            *             *
759            ***************/
760           else if ($this->stat == 'table') {
761               log_load("RESYNC");
762               printf("xXx USER::MAINCHECK1 [%s]\n", get_class($this));
763
764               return ($this->page_sync($this->sess, "briskin5/index.php", $this->table, $this->table_token));
765           }
766           log_rd2("NEWSTAT: ".$this->stat);
767       } /* if ($cur_step == -1) { */
768       else {
769           /* $sem = Room::lock_data(FALSE); */
770           $S_load_stat['rU_heavy']++;
771           
772           if ($cur_step < $this->step) {
773               do {
774                   if ($cur_step + COMM_N < $this->step) {
775                       if (($cur_stat != $this->stat)) {
776                           $to_stat = $this->stat;
777                           /* Room::unlock_data($sem); */
778                           log_load("RESYNC");
779                           printf("xXx USER::MAINCHECK2 [%s]\n", get_class($this));
780                           return ($this->page_sync($this->sess, ($to_stat == "table" ? "briskin5/index.php" : "index.php"), $this->table, $this->table_token));
781                       }
782                       log_rd2("lost history, refresh from scratch");
783                       $new_step = -1;
784                       break;
785                   } 
786                   for ($i = $cur_step ; $i < $this->step ; $i++) {
787                       $ii = $i % COMM_N;
788                       log_rd2("ADDED TO THE STREAM: ".$this->comm[$ii]);
789                       $ret .= $this->comm[$ii];
790                   }
791                   $new_stat =  $this->stat;
792                   $new_subst = $this->subst;
793                   $new_step =  $this->step;
794               } while (0);
795               
796               log_rd2($this->step, 'index_rd.php: after ret set');
797               
798               if ($this->the_end == TRUE) {
799                   log_rd2("LOGOUT BYE BYE!!");
800                   log_auth($this->sess, "Explicit logout.");
801                   
802                   if ($this->the_end == TRUE) {
803                       $this->reset();
804                       
805                       if ($this->subst == 'sitdown') {
806                           log_load("ROOM WAKEUP");
807                           $this->room->room_wakeup($this);
808                       }
809                       else if ($this->subst == 'standup')
810                           $this->room->room_outstandup($this);
811                       else
812                           log_rd2("LOGOUT FROM WHAT ???");
813                       
814                   } /* if ($this->the_end == TRUE) { ... */
815               } /* if ($this->the_end == TRUE) { ... */
816           } /* if ($cur_step < $this->step) { */
817           
818           /* Room::unlock_data($sem); */
819       }  /* else of if ($cur_step == -1) { */
820       
821     
822       return ($ret);
823   }  //   function maincheck (...
824
825 public static function stream_fini($is_unrecoverable)
826 {
827     GLOBAL $G_four_rnd_string;
828
829     // IF IFRAME THEN:
830     $body = "";
831     $body .= sprintf("<html>
832 <head>
833 <script type=\"text/javascript\" src=\"%scommons.js\"></script>
834 <script type=\"text/javascript\" src=\"%sxynt-http-streaming-ifra.js\"></script>
835 <script type=\"text/javascript\">
836 var http_streaming = \"ready\";", self::base_get(), self::base_get());
837     $body .= sprintf("
838 window.onload = function () { if (http_streaming != \"ready\") { http_streaming.reload(); } };
839 </script>
840 </head>
841 <body>");
842     $body .= sprintf("<!-- \n%s -->\n", $G_four_rnd_string);
843     $body .= sprintf("<script id='hs%d' type='text/javascript'><!--
844 push(\"%s\");
845 // -->
846 </script>", 0, escpush(self::blocking_error($is_unrecoverable)) );
847     // ELSE IF XHR THEN:
848     // return (self::blocking_error($is_unrecoverable));
849     return ($body);
850 }
851
852 /*
853  *  MAIN
854  */
855
856 /*
857    FROM THE EXTERN 
858    sess
859    stat
860    step
861 */
862 function stream_init(&$header_out, &$body, $get, $post, $cookie)
863 {
864     GLOBAL $G_four_rnd_string;
865
866     $curtime = time();
867
868     printf("CLASS: [%s] base: [%s]\n", get_class($this), self::base_get());
869
870     $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);
871
872     $header_out['Cache-Control'] = 'no-cache, must-revalidate';     // HTTP/1.1
873     $header_out['Expires']       = 'Mon, 26 Jul 1997 05:00:00 GMT'; // Date in the past
874     $header_out['Content-type']  = 'text/html; charset="utf-8"';
875
876     log_load("index_rd_ifra_init.php");
877
878     if (($from  = gpcs_var('from', $get, $post, $cookie)) === FALSE)
879         $from = "";
880     if (($stat  = gpcs_var('stat', $get, $post, $cookie)) === FALSE) 
881         $stat = "";
882     if (($subst = gpcs_var('subst', $get, $post, $cookie)) === FALSE) 
883         $subst = "";
884     if (($step  = gpcs_var('step', $get, $post, $cookie)) === FALSE) 
885         unset($step);
886     
887     $this->rd_data_set($curtime, $stat, $subst, $step, $from);
888     $cc = get_called_class();
889
890     $body .= sprintf("<html>
891 <head>
892 <script type=\"text/javascript\" src=\"%scommons.js\"></script>
893 <script type=\"text/javascript\" src=\"%sxynt-http-streaming-ifra.js\"></script>
894 <script type=\"text/javascript\">
895 var http_streaming = \"ready\";", self::base_get(), self::base_get());
896     if ($this->rd_scristp > 0)
897         $body .= sprintf("last_clean = %d;\n", ($this->rd_scristp-1));
898     $body .= sprintf("
899 window.onload = function () { if (http_streaming != \"ready\") { http_streaming.reload(); } };
900 </script> 
901 </head>
902 <body>");
903     $body .= sprintf("<!-- \n%s -->\n", $G_four_rnd_string);
904
905     return TRUE;
906 }
907
908 function stream_main(&$body, $get, $post, $cookie)
909 {
910     GLOBAL $is_page_streaming, $G_splash_idx;
911     // FIXME: only to test fwrite
912     // GLOBAL $G_four_rnd_string;
913
914     $CO_splashdate = "CO_splashdate".$G_splash_idx;
915     if (($splashdate = gpcs_var("$CO_splashdate", $get, $post, $cookie)) === FALSE)
916         $splashdate = ""; 
917     if (($table_idx = gpcs_var("table_idx", $get, $post, $cookie)) === FALSE)
918         $table_idx = ""; 
919     if (($table_token = gpcs_var("table_token", $get, $post, $cookie)) === FALSE)
920         $table_token = ""; 
921
922     $is_page_streaming = FALSE;
923     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);
924     
925     
926     $pre_main = gettimeofday(TRUE);
927     
928     $old_stat  = $this->rd_stat;
929     $old_subst = $this->rd_subst;
930     $old_step  = $this->rd_step;
931     printf("xXx PRE : rd_step %d\n", $this->rd_step);
932     if (($ret = $this->maincheck($old_stat, $old_subst, $old_step, $this->rd_stat, $this->rd_subst, $this->rd_step, $splashdate, $table_idx, $table_token)) != FALSE) {
933         $body .= sprintf("<script id='hs%d' type='text/javascript'><!--
934 push(\"%s\");
935 // -->
936 </script>", $this->rd_scristp++, escpush($ret) );
937         
938         log_rd2(0, 'index_rd.php: after mop_flush (begin: '.sprintf("%f", $pre_main).')');
939         if ($is_page_streaming) 
940             return TRUE;
941     }
942     printf("xXx POST: rd_step %d\n", $this->rd_step);
943
944     return TRUE;
945 }
946
947 function stream_keepalive($with_ping)
948 {
949     return (sprintf("<script id='hs%d' type='text/javascript'><!--
950 push(%s);
951 // -->
952 </script>", $this->rd_scristp++, ($with_ping ? "\"act_ping();\"" : "null")));
953     
954 }
955
956 static function base_get()
957 {
958     $c = get_called_class();
959     printf("CALLED_CLASS: [%s]\n", $c);
960     return $c::BASE;
961 }
962
963 } // end class User
964
965
966 ?>