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