from html_streaming to xynt_streaming object name
[brisk.git] / web / index_rd.php
1 <?php
2 /*
3  *  brisk - index_rd.php
4  *
5  *  Copyright (C) 2006-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
25 $G_base = "";
26
27 require_once("Obj/brisk.phh");
28 // require_once("Obj/proxyscan.phh");
29 require_once("briskin5/Obj/briskin5.phh");
30
31 $S_load_stat = array( 'rU_heavy'      => 0,
32                       'lL_laccgarb'   => 0,
33                       'wU_lacc_upd'   => 0,
34                       'wR_garbage'    => 0,
35                       'wR_minusone'   => 0,
36                       'wR_the_end'    => 0 );
37
38 $mlang_indrd = array( 
39                      'btn_backtotab'  => array('it' => ' torna ai tavoli ',
40                                                'en' => ' back to tables '),
41                      'btn_btotabsup'  => array('it' => ' grazie della donazione, torna ai tavoli ',
42                                                'en' => ' thank you for donation, back to tables ') 
43                      );
44
45 // Use of proxies isn't allowed.
46 // if (is_proxy()) {
47 //   sleep(5);
48 //   exit;
49 //}
50 log_load("index_rd.php");
51
52 // $first_loop = TRUE;
53 $the_end = FALSE;
54
55 if (DEBUGGING == "local" && $_SERVER['REMOTE_ADDR'] != '127.0.0.1') {
56   echo "Debugging time!";
57   exit;
58 }
59
60 function shutta()
61 {
62   log_rd2("SHUTTA [".connection_status()."] !");
63 }
64
65 register_shutdown_function(shutta);
66
67 function blocking_error($is_unrecoverable)
68 {
69   GLOBAL $is_page_streaming;
70
71   $is_page_streaming = TRUE;
72   log_crit("BLOCKING_ERROR UNREC: ".($is_unrecoverable ? "TRUE" : "FALSE"));
73   return (sprintf(($is_unrecoverable ? 'xstm.stop(); ' : '').'window.onbeforeunload = null; window.onunload = null; document.location.assign("index.php");'));
74 }
75
76 function page_sync($sess, $page, $table_idx, $table_token)
77 {
78   GLOBAL $is_page_streaming;
79
80   log_rd2("page_sync:".var_export(debug_backtrace()));
81
82   $is_page_streaming = TRUE;
83
84   log_rd2("PAGE_SYNC");
85   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));
86 }
87
88
89
90
91 function maincheck($sess, $cur_stat, $cur_subst, $cur_step, &$new_stat, &$new_subst, &$new_step)
92 {
93     GLOBAL $G_lang, $mlang_indrd, $is_page_streaming;
94     // GLOBAL $first_loop;
95     GLOBAL $G_with_splash, $G_splash_content, $G_splash_interval, $G_splash_idx;
96     GLOBAL $G_splash_w, $G_splash_h, $G_splash_timeout;
97     $CO_splashdate = "CO_splashdate".$G_splash_idx;
98     GLOBAL $$CO_splashdate;
99     
100     GLOBAL $S_load_stat;
101
102     log_rd("maincheck begin");
103
104     $ret = FALSE;
105     $room = FALSE;
106     $user = FALSE;
107     $curtime = time();
108     
109     // NOTE: qui forse si potrebbe fallback-are a una User::load_data 
110     //       anche se non ce ne dovrebbe essere mai la necessità
111     if (($proxy_step = User::load_step($sess)) == FALSE) {
112         log_only2("R");
113         ignore_user_abort(FALSE);
114         return (blocking_error(TRUE));
115     }
116     
117     // log_rd2("M");
118     /* Sync check (read only without modifications */
119     ignore_user_abort(TRUE);
120
121
122     /* shared locking to load info */
123     if (($sem = Room::lock_data(FALSE)) == FALSE) { 
124         // wait 20 secs, then restart the xhr 
125         ignore_user_abort(FALSE);
126         return ("sleep(gst,20000);|xstm.xhr_abort();");
127     }
128     
129     // Verifica l'expire time lato server
130     if (($user = User::load_data($proxy_step['i'], $sess)) == FALSE) {
131         Room::unlock_data($sem);
132         ignore_user_abort(FALSE);
133         return (blocking_error(TRUE));
134     }
135     /* if lacc time great than STREAM_TIMEOUT or the room garbage_time is expired 
136          switch to exclusive locking and verify again the conditions */
137     if ((($curtime - $user->lacc) >  STREAM_TIMEOUT) || Room::garbage_time_is_expired($curtime)) {
138         /* there is some info that require to change data, switch to exclusive locking */
139         Room::unlock_data($sem);
140         if (($sem = Room::lock_data(TRUE)) == FALSE) { 
141             // wait 20 secs, then restart the xhr 
142             ignore_user_abort(FALSE);
143             return ("sleep(gst,20000);|xstm.xhr_abort();");
144         }
145         $S_load_stat['lL_laccgarb']++;
146
147         // load again the data after locking
148         unset($user);
149         // Verifica l'expire time lato server
150         if (($user = User::load_data($proxy_step['i'], $sess)) == FALSE) {
151             Room::unlock_data($sem);
152             ignore_user_abort(FALSE);
153             return (blocking_error(TRUE));
154         }
155
156         if (($curtime - $user->lacc) >=  STREAM_TIMEOUT) {
157             $S_load_stat['wU_lacc_upd']++;
158             $user->lacc = $curtime;
159             // lacc field updated
160             User::save_data($user, $user->idx);
161         }
162         
163         if (Room::garbage_time_is_expired($curtime)) {
164             log_only("F");
165             
166             $S_load_stat['wR_garbage']++;
167             if (($room = Room::load_data()) == FALSE) {
168                 Room::unlock_data($sem);
169                 ignore_user_abort(FALSE);
170                 return (blocking_error(TRUE));
171             }
172             log_main("pre garbage_manager TRE");
173             $room->garbage_manager(FALSE);
174             Room::save_data($room);
175             unset($room);
176         }
177     }
178     log_main("infolock: U");
179     Room::unlock_data($sem);
180     ignore_user_abort(FALSE);
181
182     
183     
184 //     if  ($first_loop == TRUE) {
185 //         if (($sem = Room::lock_data(TRUE)) != FALSE) { 
186 //             // Aggiorna l'expire time lato server
187 //             $S_load_stat['U_first_loop']++;
188 //             if (($user = User::load_data($proxy_step['i'], $sess)) == FALSE) {
189 //                 Room::unlock_data($sem);
190 //                 ignore_user_abort(FALSE);
191 //                 return (blocking_error(TRUE));
192 //             }
193 //             $user->lacc = $curtime;
194 //             // lacc field updated
195 //             User::save_data($user, $user->idx);
196             
197 //             if (Room::garbage_time_is_expired($curtime)) {
198 //                 log_only("F");
199                 
200 //                 $S_load_stat['R_garbage']++;
201 //                 if (($room = Room::load_data()) == FALSE) {
202 //                     Room::unlock_data($sem);
203 //                     ignore_user_abort(FALSE);
204 //                     return (blocking_error(TRUE));
205 //                 }
206 //                 log_main("pre garbage_manager TRE");
207 //                 $room->garbage_manager(FALSE);
208 //                 Room::save_data($room);
209 //                 unset($room);
210 //             }
211 //             log_main("infolock: U");
212 //             Room::unlock_data($sem);
213 //             ignore_user_abort(FALSE);
214 //         } // if (($sem = Room::lock_data(TRUE)) != FALSE) { 
215 //         else {
216 //             // wait 20 secs, then restart the xhr 
217 //             ignore_user_abort(FALSE);
218             
219 //             return ("sleep(gst,20000);|xstm.xhr_abort();");
220 //         }
221 //         $first_loop = FALSE;
222 //     } // if  ($first_loop == TRUE) {
223     
224     if ($cur_step == $proxy_step['s']) {
225         log_main("infolock: P");
226         return (FALSE);
227     }
228     else {
229         log_only2("R");
230     }
231
232     $S_load_stat['rU_heavy']++;
233     if ($user == FALSE) {
234         do {
235             ignore_user_abort(TRUE);
236             if (($sem = Room::lock_data(FALSE)) == FALSE) 
237                 break;
238             
239             log_main("infolock: P");
240             if (($user = User::load_data($proxy_step['i'], $sess)) == FALSE) {
241                 break;
242             }
243         } while (0);
244         
245         if ($sem != FALSE)
246             Room::unlock_data($sem);
247         
248         ignore_user_abort(FALSE);
249         if ($user == FALSE) {
250             return (blocking_error(TRUE));
251         }
252     }
253     
254     /* Nothing changed, return. */
255     if ($cur_step == $user->step) 
256         return (FALSE);
257     
258     log_rd2("do other cur_stat[".$cur_stat."] user->stat[".$user->stat."] cur_step[".$cur_step."] user_step[".$user->step."]");
259     
260     if ($cur_step == -1) {
261         /*
262          *  if $cur_step == -1 load the current state from the main struct
263          */
264
265         /* unset the $user var to reload it from main structure */
266         unset($user);
267
268         ignore_user_abort(TRUE);
269         $sem = Room::lock_data(TRUE);
270         if (($room = Room::load_data()) == FALSE) {
271             Room::unlock_data($sem);
272             ignore_user_abort(FALSE);
273             return (blocking_error(TRUE));
274         }
275         $S_load_stat['wR_minusone']++;
276         
277         if (($user = $room->get_user($sess, $idx)) == FALSE) {
278             Room::unlock_data($sem);
279             ignore_user_abort(FALSE);
280             return (blocking_error(TRUE));
281         }
282         
283         if ($user->the_end == TRUE) { 
284             log_rd2("main_check: the end".var_export(debug_backtrace()));
285             $is_page_streaming = TRUE;
286         }
287         
288         if ($user->trans_step != -1) {
289             log_rd2("TRANS USATO ".$user->trans_step);
290             $cur_step = $user->trans_step;
291             $user->trans_step = -1;
292             
293             Room::save_data($room);
294             Room::unlock_data($sem);
295             ignore_user_abort(FALSE);
296         }
297         else {
298             log_rd2("TRANS NON ATTIVATO");
299             //        ARRAY_POP DISABLED
300             //        log_rd2("TRANS NON ATTIVATO, clean del comm array");
301             //        while (($el = array_pop($user->comm)) != NULL) { 
302             //          log_rd2("clean element [".$el."]");
303             //        }
304             //        //        $user->step_inc(COMM_N + 1);
305             //        Room::save_data($room);
306             //        //        $new_step = $user->step;
307             
308             Room::unlock_data($sem);
309             ignore_user_abort(FALSE);
310         }
311     }
312     
313     
314     /* this part I suppose is read only on $room structure */
315     if ($cur_step == -1) {
316         log_rd2("PRE-NEWSTAT: ".$user->stat);
317         
318         if ($user->stat == 'room') {
319             log_rd("roomma ".$user->step);
320             $curtime = time();
321             
322             if ($G_with_splash &&
323                 ($$CO_splashdate < $curtime - $G_splash_interval ||
324                  $$CO_splashdate > $curtime)) {
325                 $is_super = $user->flags & USER_FLAG_TY_SUPER;
326                 $ret .=  show_notify_ex(str_replace("\n", " ", $G_splash_content[$G_lang]), 
327                                         ($is_super ? 0 : $G_splash_timeout), 
328                                         $mlang_indrd[($is_super ? 'btn_btotabsup' : 'btn_backtotab')][$G_lang], 
329                                         $G_splash_w, $G_splash_h, true, 
330                                         ($is_super ? 0 : $G_splash_timeout));
331                 $ret .= sprintf('|createCookie("CO_splashdate%d", %d, 24*365, cookiepath);', $G_splash_idx, $curtime);
332             }
333             $ret .= $room->show_room($user->step, $user);
334             
335             // TODO uncomment and test
336             /* NOTE the sets went common */
337             $new_stat =  $user->stat;
338             $new_subst = $user->subst;
339             $new_step =  $user->step;
340         }
341         /***************
342          *             *
343          *    TABLE    *
344          *             *
345          ***************/
346         else if ($user->stat == 'table') {
347             log_load("RESYNC");
348             return (page_sync($user->sess, "briskin5/index.php", $user->table, $user->table_token));
349         }
350         log_rd2("NEWSTAT: ".$user->stat);
351     } /* if ($cur_step == -1) { */
352     else {
353         ignore_user_abort(TRUE);
354         $sem = Room::lock_data(FALSE);
355         $S_load_stat['rU_heavy']++;
356         if (($user = User::load_data($proxy_step['i'], $sess)) == FALSE) {
357             Room::unlock_data($sem);
358             ignore_user_abort(FALSE);
359             return (blocking_error(TRUE));
360         }
361         
362         if ($cur_step < $user->step) {
363             do {
364                 if ($cur_step + COMM_N < $user->step) {
365                     if (($cur_stat != $user->stat)) {
366                         $to_stat = $user->stat;
367                         Room::unlock_data($sem);
368                         ignore_user_abort(FALSE);
369                         log_load("RESYNC");
370                         return (page_sync($user->sess, ($to_stat == "table" ? "briskin5/index.php" : "index.php"), $user->table, $user->table_token));
371                     }
372                     log_rd2("lost history, refresh from scratch");
373                     $new_step = -1;
374                     break;
375                 } 
376                 for ($i = $cur_step ; $i < $user->step ; $i++) {
377                     $ii = $i % COMM_N;
378                     log_rd2("ADDED TO THE STREAM: ".$user->comm[$ii]);
379                     $ret .= $user->comm[$ii];
380                 }
381                 $new_stat =  $user->stat;
382                 $new_subst = $user->subst;
383                 $new_step =  $user->step;
384             } while (0);
385             
386             log_rd2($user->step, 'index_rd.php: after ret set');
387             
388             if ($user->the_end == TRUE) {
389                 Room::unlock_data($sem);
390                 
391                 /* Switch to exclusive locking */
392                 $sem = Room::lock_data(TRUE);
393
394                 unset($user);
395
396                 $S_load_stat['wR_the_end']++;
397                 if (($room = Room::load_data()) == FALSE) {
398                     Room::unlock_data($sem);
399                     ignore_user_abort(FALSE);
400                     return (blocking_error(TRUE));
401                 }
402
403                 if (($user = $room->get_user($sess, $idx)) == FALSE) {
404                     Room::unlock_data($sem);
405                     ignore_user_abort(FALSE);
406                     return (blocking_error(TRUE));
407                 }              
408
409                 log_rd2("LOGOUT BYE BYE!!");
410                 log_auth($user->sess, "Explicit logout.");
411                 
412                 if ($user->the_end == TRUE) {
413                     $user->reset();
414                     
415                     if ($user->subst == 'sitdown') {
416                         log_load("ROOM WAKEUP");
417                         $room->room_wakeup($user);
418                     }
419                     else if ($user->subst == 'standup')
420                         $room->room_outstandup($user);
421                     else
422                         log_rd2("LOGOUT FROM WHAT ???");
423                     
424                     Room::save_data($room);
425                 } /* if ($user->the_end == TRUE) { ... */
426             } /* if ($user->the_end == TRUE) { ... */
427         } /* if ($cur_step < $user->step) { */
428         
429         Room::unlock_data($sem);
430         ignore_user_abort(FALSE);
431     }  /* else of if ($cur_step == -1) { */
432     
433     
434     return ($ret);
435 }
436
437 /*
438  *  MAIN
439  */
440
441 /*
442    FROM THE EXTERN 
443    sess
444    stat
445    step
446 */
447
448 $is_page_streaming = (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);
449
450 header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
451 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
452 header('Content-type: application/xml; charset="utf-8"',true);
453
454 if (!isset($from))
455      $from = "";
456 if (!isset($subst))
457      $subst = "";
458 log_rd2("FROM OUTSIDE - STAT: ".$stat." SUBST: ".$subst." STEP: ".$step." FROM: ".$from. "IS_PAGE:" . $is_page_streaming);
459
460
461 $endtime = time() + STREAM_TIMEOUT;
462 $old_stat =  $stat;
463 $old_subst = $subst;
464 $old_step =  $ext_step = $step;
465
466 for ($i = 0 ; time() < $endtime ; $i++) {
467   // log_rd("PRE MAIN ".$step);;
468   $pre_main = gettimeofday(TRUE);
469   if (($ret = maincheck($sess, $old_stat, $old_subst, $old_step, &$stat, &$subst, &$step)) != FALSE) {
470     echo '@BEGIN@';
471     // log_rd2(sprintf("\nSESS: [%s]\nOLD_STAT: [%s] OLD_SUBST: [%s] OLD_STEP: [%s] \nSTAT: [%s] SUBST: [%s] STEP: [%s] \nCOMM: [%s]\n", $sess, $old_stat, $old_subst, $old_step, $stat, $subst, $step, $ret));
472     echo "$ret";
473     echo ' @END@'; 
474     log_send("IS_PAGE: ".($is_page_streaming == TRUE ? "TRUE" : "FALSE")."EXT_STEP: ".$ext_step." ENDTIME: [".$endtime."] ".$ret);
475     mop_flush();
476     log_rd2(0, 'index_rd.php: after mop_flush (begin: '.sprintf("%f", $pre_main).')');
477     if ($is_page_streaming) 
478         break;
479   }
480   $old_stat =  $stat;
481   $old_subst = $subst;
482   $old_step =  $step;
483   // log_rd("POST MAIN ".$step);;
484   usleep(400000);
485   if (($i % 10) == 0) {
486     // log_rd2("TIME: ".time());
487     echo '_';
488     mop_flush();
489     log_crit("flush");
490   }
491  }
492
493 $s = ""; 
494 $tr = 0;
495 $tw = 0;
496 foreach ($S_load_stat as $key => $value) {
497     $s .= sprintf("%s: %d - ", $key, $value);
498     if (substr($key, 0, 1) == "w")
499         $tw += $value;
500     else if (substr($key, 0, 1) == "r")
501         $tr += $value;
502 }
503 $s = sprintf("index_rd.php stats:  R: %d W: %d - %s", $tr, $tw, $s);
504 log_crit($s);
505 ?>