webservers_exceeded() and check_webservers() functions added to change behaviour...
[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(TRUE)) != 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             // lacc field updated
129             User::save_data($user, $user->idx);
130             
131             if (Room::garbage_time_is_expired($curtime)) {
132                 log_only("F");
133                 
134                 $S_load_stat['R_garbage']++;
135                 if (($room = Room::load_data()) == FALSE) {
136                     Room::unlock_data($sem);
137                     ignore_user_abort(FALSE);
138                     return (blocking_error(TRUE));
139                 }
140                 log_main("pre garbage_manager TRE");
141                 $room->garbage_manager(FALSE);
142                 Room::save_data($room);
143                 unset($room);
144             }
145             log_main("infolock: U");
146             Room::unlock_data($sem);
147             ignore_user_abort(FALSE);
148         } // if (($sem = Room::lock_data(TRUE)) != FALSE) { 
149         else {
150             // wait 20 secs, then restart the xhr 
151             ignore_user_abort(FALSE);
152             
153             return ("sleep(gst,20000);|xhr_rd_abort(xhr_rd);");
154         }
155         $first_loop = FALSE;
156     } // if  ($first_loop == TRUE) {
157     
158     if ($cur_step == $proxy_step['s']) {
159         log_main("infolock: P");
160         return (FALSE);
161     }
162     else {
163         log_only2("R");
164     }
165     
166
167     if ($user == FALSE) {
168         do {
169             ignore_user_abort(TRUE);
170             if (($sem = Room::lock_data(FALSE)) == FALSE) 
171                 break;
172             
173             log_main("infolock: P");
174             $S_load_stat['U_heavy']++;
175             if (($user = User::load_data($proxy_step['i'], $sess)) == FALSE) {
176                 break;
177             }
178         } while (0);
179         
180         if ($sem != FALSE)
181             Room::unlock_data($sem);
182         
183         ignore_user_abort(FALSE);
184         if ($user == FALSE) {
185             return (blocking_error(TRUE));
186         }
187     }
188     
189     /* Nothing changed, return. */
190     if ($cur_step == $user->step) 
191         return (FALSE);
192     
193     log_rd2("do other cur_stat[".$cur_stat."] user->stat[".$user->stat."] cur_step[".$cur_step."] user_step[".$user->step."]");
194     
195     if ($cur_step == -1) {
196         /*
197          *  if $cur_step == -1 load the current state from the main struct
198          */
199
200         /* unset the $user var to reload it from main structure */
201         unset($user);
202
203         ignore_user_abort(TRUE);
204         $sem = Room::lock_data(TRUE);
205         if (($room = Room::load_data()) == FALSE) {
206             Room::unlock_data($sem);
207             ignore_user_abort(FALSE);
208             return (blocking_error(TRUE));
209         }
210         $S_load_stat['R_minusone']++;
211         
212         if (($user = $room->get_user($sess, $idx)) == FALSE) {
213             Room::unlock_data($sem);
214             ignore_user_abort(FALSE);
215             return (blocking_error(TRUE));
216         }
217         
218         if ($user->the_end) { 
219             log_rd2("main_check: the end".var_export(debug_backtrace()));
220             $is_page_streaming = TRUE;
221         }
222         
223         if ($user->trans_step != -1) {
224             log_rd2("TRANS USATO ".$user->trans_step);
225             $cur_step = $user->trans_step;
226             $user->trans_step = -1;
227             
228             Room::save_data($room);
229             Room::unlock_data($sem);
230             ignore_user_abort(FALSE);
231         }
232         else {
233             log_rd2("TRANS NON ATTIVATO");
234             //        ARRAY_POP DISABLED
235             //        log_rd2("TRANS NON ATTIVATO, clean del comm array");
236             //        while (($el = array_pop($user->comm)) != NULL) { 
237             //          log_rd2("clean element [".$el."]");
238             //        }
239             //        //        $user->step_inc(COMM_N + 1);
240             //        Room::save_data($room);
241             //        //        $new_step = $user->step;
242             
243             Room::unlock_data($sem);
244             ignore_user_abort(FALSE);
245         }
246     }
247     
248     
249     /* this part I suppose is read only on $room structure */
250     if ($cur_step == -1) {
251         log_rd2("PRE-NEWSTAT: ".$user->stat);
252         
253         if ($user->stat == 'room') {
254             log_rd("roomma ".$user->step);
255             $curtime = time();
256             
257             if ($G_with_splash &&
258                 ($$CO_splashdate < $curtime - $G_splash_interval ||
259                  $$CO_splashdate > $curtime)) {
260                 $is_super = $user->flags & USER_FLAG_TY_SUPER;
261                 $ret .=  show_notify_ex(str_replace("\n", " ", $G_splash_content[$G_lang]), 
262                                         ($is_super ? 0 : $G_splash_timeout), 
263                                         $mlang_indrd[($is_super ? 'btn_btotabsup' : 'btn_backtotab')][$G_lang], 
264                                         $G_splash_w, $G_splash_h, true, 
265                                         ($is_super ? 0 : $G_splash_timeout));
266                 $ret .= sprintf('|createCookie("CO_splashdate%d", %d, 24*365, cookiepath);', $G_splash_idx, $curtime);
267             }
268             $ret .= $room->show_room($user->step, $user);
269             
270             // TODO uncomment and test
271             /* NOTE the sets went common */
272             $new_stat =  $user->stat;
273             $new_subst = $user->subst;
274             $new_step =  $user->step;
275         }
276         /***************
277          *             *
278          *    TABLE    *
279          *             *
280          ***************/
281         else if ($user->stat == 'table') {
282             log_load("RESYNC");
283             return (page_sync($user->sess, "briskin5/index.php", $user->table, $user->table_token));
284         }
285         log_rd2("NEWSTAT: ".$user->stat);
286     }
287     else {
288         ignore_user_abort(TRUE);
289         $sem = Room::lock_data(FALSE);
290         $S_load_stat['U_heavy']++;
291         if (($user = User::load_data($proxy_step['i'], $sess)) == FALSE) {
292             Room::unlock_data($sem);
293             ignore_user_abort(FALSE);
294             return (blocking_error(TRUE));
295         }
296         
297         if ($cur_step < $user->step) {
298             do {
299                 if ($cur_step + COMM_N < $user->step) {
300                     if (($cur_stat != $user->stat)) {
301                         $to_stat = $user->stat;
302                         Room::unlock_data($sem);
303                         ignore_user_abort(FALSE);
304                         log_load("RESYNC");
305                         return (page_sync($user->sess, ($to_stat == "table" ? "briskin5/index.php" : "index.php"), $user->table, $user->table_token));
306                     }
307                     log_rd2("lost history, refresh from scratch");
308                     $new_step = -1;
309                     break;
310                 } 
311                 for ($i = $cur_step ; $i < $user->step ; $i++) {
312                     $ii = $i % COMM_N;
313                     log_rd2("ADDED TO THE STREAM: ".$user->comm[$ii]);
314                     $ret .= $user->comm[$ii];
315                 }
316                 $new_stat =  $user->stat;
317                 $new_subst = $user->subst;
318                 $new_step =  $user->step;
319             } while (0);
320             
321             log_mop($user->step, 'index_rd.php: after ret set');
322             
323             if ($user->the_end == TRUE) {
324                 Room::unlock_data($sem);
325                 
326                 /* Switch to exclusive locking */
327                 $sem = Room::lock_data(TRUE);
328
329                 unset($user);
330
331                 $S_load_stat['R_the_end']++;
332                 if (($room = Room::load_data()) == FALSE) {
333                     Room::unlock_data($sem);
334                     ignore_user_abort(FALSE);
335                     return (blocking_error(TRUE));
336                 }
337
338                 if (($user = $room->get_user($sess, $idx)) == FALSE) {
339                     Room::unlock_data($sem);
340                     ignore_user_abort(FALSE);
341                     return (blocking_error(TRUE));
342                 }              
343
344                 log_rd2("LOGOUT BYE BYE!!");
345                 log_auth($user->sess, "Explicit logout.");
346                 
347                 if ($user->the_end == TRUE) {
348                     $user->reset();
349                     
350                     if ($user->subst == 'sitdown') {
351                         log_load("ROOM WAKEUP");
352                         $room->room_wakeup($user);
353                     }
354                     else if ($user->subst == 'standup')
355                         $room->room_outstandup($user);
356                     else
357                         log_rd2("LOGOUT FROM WHAT ???");
358                     
359                     Room::save_data($room);
360                 }
361             }
362         }
363         
364         Room::unlock_data($sem);
365         ignore_user_abort(FALSE);
366     }
367     
368     
369     return ($ret);
370 }
371
372 /*
373  *  MAIN
374  */
375
376 /*
377    FROM THE EXTERN 
378    sess
379    stat
380    step
381 */
382
383 $is_page_streaming =  (webservers_exceeded() || stristr($HTTP_USER_AGENT, "MSIE") || stristr($HTTP_USER_AGENT, "CHROME") ? TRUE : FALSE);
384
385 header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
386 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
387 header('Content-type: application/xml; charset="utf-8"',true);
388
389 if (!isset($myfrom))
390      $myfrom = "";
391 if (!isset($subst))
392      $subst = "";
393 log_rd2("FROM OUTSIDE - STAT: ".$stat." SUBST: ".$subst." STEP: ".$step." MYFROM: ".$myfrom. "IS_PAGE:" . $is_page_streaming);
394
395
396 $endtime = time() + STREAM_TIMEOUT;
397 $old_stat =  $stat;
398 $old_subst = $subst;
399 $old_step =  $ext_step = $step;
400
401 for ($i = 0 ; time() < $endtime ; $i++) {
402   // log_rd("PRE MAIN ".$step);;
403   $pre_main = gettimeofday(TRUE);
404   if (($ret = maincheck($sess, $old_stat, $old_subst, $old_step, &$stat, &$subst, &$step)) != FALSE) {
405     echo '@BEGIN@';
406     // 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));
407     echo "$ret";
408     echo ' @END@'; 
409     log_send("IS_PAGE: ".($is_page_streaming == TRUE ? "TRUE" : "FALSE")."EXT_STEP: ".$ext_step." ENDTIME: [".$endtime."] ".$ret);
410     flush();
411     log_mop(0, 'index_rd.php: after flush (begin: '.sprintf("%f", $pre_main).')');
412     if ($is_page_streaming)
413       break;
414   }
415   $old_stat =  $stat;
416   $old_subst = $subst;
417   $old_step =  $step;
418   // log_rd("POST MAIN ".$step);;
419   usleep(400000);
420   if (($i % 10) == 0) {
421     // log_rd2("TIME: ".time());
422     echo '_';
423     flush();
424   }
425  }
426
427 $s = "[".$sess."] index_rd.php stats: ";
428 foreach ($S_load_stat as $key => $value) {
429     $s .= sprintf("%s: %d - ", $key, $value);
430 }
431 log_crit($s);
432
433
434 ?>