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