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