441d2eb225955c0e54db0bcfdd0ba2a7cc7bd304
[brisk.git] / web / Obj / sac-a-push.phh
1 <?php
2 /*
3  *  brisk - Obj/sac-a-push.phh
4  *
5  *  Copyright (C) 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 define('SITE_PREFIX', '/brisk/');
26 define('SITE_PREFIX_LEN', 7);
27
28
29 function global_dump()
30 {
31     GLOBAL $G_alarm_passwd, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
32     GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
33     GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
34     GLOBAL $G_room_roadmap, $G_shutdown, $G_sidebanner, $G_sidebanner2;
35     GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
36     GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
37     GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
38     GLOBAL $G_with_sidebanner, $G_with_sidebanner2, $G_with_splash;
39     GLOBAL $G_with_topbanner;
40
41     fprintf(STDERR, "G_alarm_passwd = [%s]\n", print_r($G_alarm_passwd, TRUE));
42     fprintf(STDERR, "G_black_list = [%s]\n", print_r($G_black_list, TRUE));
43     fprintf(STDERR, "G_btrace_pref_sub = [%s]\n", print_r($G_btrace_pref_sub, TRUE));
44     fprintf(STDERR, "G_dbauth = [%s]\n", print_r($G_dbauth, TRUE));
45     fprintf(STDERR, "G_dbpfx = [%s]\n", print_r($G_dbpfx, TRUE));
46     fprintf(STDERR, "G_donors_all = [%s]\n", print_r($G_donors_all, TRUE));
47     fprintf(STDERR, "G_donors_cur = [%s]\n", print_r($G_donors_cur, TRUE));
48     fprintf(STDERR, "G_is_local = [%s]\n", print_r($G_is_local, TRUE));
49     fprintf(STDERR, "G_lang = [%s]\n", print_r($G_lang, TRUE));
50     fprintf(STDERR, "G_poll_entries = [%s]\n", print_r($G_poll_entries, TRUE));
51     fprintf(STDERR, "G_poll_name = [%s]\n", print_r($G_poll_name, TRUE));
52     fprintf(STDERR, "G_poll_title = [%s]\n", print_r($G_poll_title, TRUE));
53     fprintf(STDERR, "G_proxy_white_list = [%s]\n", print_r($G_proxy_white_list, TRUE));
54     fprintf(STDERR, "G_room_roadmap = [%s]\n", print_r($G_room_roadmap, TRUE));
55     fprintf(STDERR, "G_shutdown = [%s]\n", print_r($G_shutdown, TRUE));
56     fprintf(STDERR, "G_sidebanner = [%s]\n", print_r($G_sidebanner, TRUE));
57     fprintf(STDERR, "G_sidebanner2 = [%s]\n", print_r($G_sidebanner2, TRUE));
58     fprintf(STDERR, "G_splash_content = [%s]\n", print_r($G_splash_content, TRUE));
59     fprintf(STDERR, "G_splash_contents = [%s]\n", print_r($G_splash_contents, TRUE));
60     fprintf(STDERR, "G_splash_cont_idx = [%s]\n", print_r($G_splash_cont_idx, TRUE));
61     fprintf(STDERR, "G_splash_h = [%s]\n", print_r($G_splash_h, TRUE));
62     fprintf(STDERR, "G_splash_idx = [%s]\n", print_r($G_splash_idx, TRUE));
63     fprintf(STDERR, "G_splash_interval = [%s]\n", print_r($G_splash_interval, TRUE));
64     fprintf(STDERR, "G_splash_timeout = [%s]\n", print_r($G_splash_timeout, TRUE));
65     fprintf(STDERR, "G_splash_w = [%s]\n", print_r($G_splash_w, TRUE));
66     fprintf(STDERR, "G_topbanner = [%s]\n", print_r($G_topbanner, TRUE));
67     fprintf(STDERR, "G_with_donors = [%s]\n", print_r($G_with_donors, TRUE));
68     fprintf(STDERR, "G_with_poll = [%s]\n", print_r($G_with_poll, TRUE));
69     fprintf(STDERR, "G_with_sidebanner = [%s]\n", print_r($G_with_sidebanner, TRUE));
70     fprintf(STDERR, "G_with_sidebanner2 = [%s]\n", print_r($G_with_sidebanner2, TRUE));
71     fprintf(STDERR, "G_with_splash = [%s]\n", print_r($G_with_splash, TRUE));
72     fprintf(STDERR, "G_with_topbanner = [%s]\n", print_r($G_with_topbanner, TRUE));
73 }
74
75 function pid_save()
76 {
77     $pid = getmypid();
78     $fname = LEGAL_PATH."/brisk.pid";
79
80     if (file_exists($fname)) {
81         log_crit("WARN: brisk.pid already exists");
82     }
83     file_put_contents($fname, sprintf("%d\n", $pid));
84 }
85
86 function pid_remove()
87 {
88     $fname = LEGAL_PATH."/brisk.pid";
89
90     if (file_exists($fname)) {
91         unlink($fname);
92     }
93 }
94
95 function spu_process_info($stream_info, $method, &$header, &$get, &$post, &$cookie)
96 {
97     $check_post = FALSE;
98     $header = array();
99     $get = array();
100     $post = array();
101     foreach(preg_split("/(\r?\n)/", $stream_info) as $line) {
102         // printf("LINE: [%s]\n", $line);
103         if ($check_post) {
104             if (!isset($header['The-Request'])) {
105                 return FALSE;
106             }
107             $req = explode(" ", $header['The-Request']);
108             $method = $req[0];
109
110             if (isset($header['Cookie'])) {
111                 $cookies = explode(";", $header['Cookie']);
112                 for ($i = 0 ; $i < count($cookies) ; $i++) {
113                     $nameval = explode("=", trim($cookies[$i]));
114                     if (count($nameval) != 2) {
115                         printf("WARNING: malformat cookie element [%s]\n", $cookies[$i]);
116                         continue;
117                     }
118                     $cookie[$nameval[0]] = urldecode($nameval[1]);
119                 }
120             }
121             // GET params management
122             $get_vars = explode('?', $req[1], 2);
123             $path =   $get_vars[0];
124             if (count($get_vars) > 1) {
125                 $a = explode('&', $get_vars[1]);
126                 printf("A COUNT: [%s] %d\n", $a[0], count($a));
127                 for ($i = 0 ; $i < count($a) ; $i++) {
128                     $b = explode('=', $a[$i]);
129                     $get[$b[0]] = urldecode($b[1]);
130                 }
131             }
132             // POST params management
133             if ($req[0] == 'POST') {
134                 if ($header['Content-Type'] != 'application/x-www-form-urlencoded' 
135                     || !isset($header['Content-Length'])) {
136                     return FALSE;
137                 }
138                 $post_len = mb_strlen($line, "latin1");
139                 $a = explode('&', $line);
140                 for ($i = 0 ; $i < count($a) ; $i++) {
141                     $b = explode('=', $a[$i]);
142                     $post[$b[0]] = urldecode($b[1]);
143                 }
144                 printf("INFO: postlen: %d\n", $post_len);
145             }
146             break;
147         }
148         if ($line == "") {
149             $check_post = TRUE;
150             continue;
151         }
152         $split = explode(":", $line, 2);
153         $header[$split[0]] = $split[1];        
154     }
155     return $path;
156 }
157
158 function gpcs_var($name, $get, $post, $cookie)
159 {
160     if (isset($GLOBALS[$name])) 
161         return FALSE;
162     else if (isset($cookie[$name])) 
163         return ($cookie[$name]);
164     else if (isset($post[$name])) 
165         return ($post[$name]);
166     else if (isset($get[$name])) 
167         return ($get[$name]);
168
169     return FALSE;
170 }
171
172 function headers_render($header, $len)
173 {
174     $cookies = "";
175
176     if (isset($header['cookies'])) {
177         $cookies = $header['cookies']->render();
178         unset($header['cookies']);
179     }
180     if (isset($header['Location'])) {
181         $s = sprintf("HTTP/1.1 302 OK\r\n%sLocation: %s\r\n", $cookies, $header['Location']);
182     }
183     else {
184         $s = "HTTP/1.1 200 OK\r\n";
185
186         if (!isset($header['Date']))
187             $s .= sprintf("Date: %s\r\n", date(DATE_RFC822));
188         if (!isset($header['Connection']))
189             $s .= "Connection: close\r\n";
190         if (!isset($header['Content-Type']))
191             $s .= "Content-Type: text/html\r\n";
192         foreach($header as $key => $value) {
193             $s .= sprintf("%s: %s\r\n", $key, $value);
194         }
195         if ($len >= 0) {
196             $s .= sprintf("Content-Length: %d\r\n", $len);
197         }
198         else {
199             $s .= "Cache-Control: no-cache, must-revalidate\r\n";
200             $s .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n";
201             if (!isset($header['Content-Encoding'])) {
202                 $s .= "Content-Encoding: chunked\r\n";
203             }
204             $s .= "Transfer-Encoding: chunked\r\n";
205         }
206         $s .= $cookies;
207     }
208     $s .= "\r\n";
209
210     return ($s);
211 }
212
213 /*
214  *  Caching system using ob php system to cache old style pages
215  *  to a var and than send it with more calm
216  */
217
218 function shutta()
219 {
220   log_rd2("SHUTTA [".connection_status()."] !");
221 }
222
223 register_shutdown_function('shutta');
224
225 /*
226  *  MAIN
227  */
228
229 function chunked_content($zls, $content)
230 {
231     if ($zls) {
232         $cont_comp = $zls->compress_chunk($content);
233     }
234     else {
235         $cont_comp = $content;
236     }
237     $cont_comp_l = mb_strlen($cont_comp, "ASCII");
238     printf("CHUNK: [%s]\n", $content);
239
240     return (sprintf("%X\r\n", $cont_comp_l).$cont_comp."\r\n");
241 }
242
243 function chunked_fini()
244 {
245     return sprintf("0\r\n");
246 }
247
248 function get_encoding($header)
249 {
250     $enc = "plain";
251     if (isset($header['Accept-Encoding'])) {
252         $acc = explode(',', $header['Accept-Encoding']);
253
254         if (array_search('gzip', $acc) !== FALSE) {
255             $enc = 'gzip';
256         }
257         else if (array_search('deflate', $acc) !== FALSE) {
258             $enc = 'deflate';
259         }
260     }
261
262     return ($enc);
263 }
264
265 class Cookie {
266     var $attr;
267     // Set-Cookie: reg_fb_gate=deleted; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.foo.com; HttpOnly
268     // string $name  [, string $value  [, int $expire = 0  [, string $path  [, string $domain  [, bool $secure = false  [, bool $httponly = false  ]]]]]] )
269     function Cookie()
270     {
271         $this->attr = array();
272     }
273
274     static function create($name)
275     {
276         $thiz = new Cookie();
277
278         $thiz->attr[$name] = "";
279
280         $argc = func_num_args();
281         for ($i = 1 ; $i < $argc ; $i++) {
282             $arg = func_get_arg($i);
283             switch ($i) {
284             case 1:
285                 $thiz->attr[$name] = urlencode($arg);
286                 break;
287             case 2:
288                 $thiz->attr['Expires'] = gmdate('D, d M Y H:i:s \G\M\T', $arg); // RFC 1211 format
289                 break;
290             case 3:
291                 $thiz->attr['Path'] = $arg;
292                 break;
293             case 4:
294                 $thiz->attr['Domain'] = $arg;
295                 break;
296             case 5:
297                 if ($arg == TRUE) {
298                     $thiz->attr['Secure'] = NULL;
299                 }
300                 break;
301             case 6:
302                 if ($arg == TRUE) {
303                     $thiz->attr['HttpOnly'] = NULL;
304                 }
305                 break;
306             default:
307                 return FALSE;
308             }
309         }
310
311         return $thiz;
312     }
313
314     function render()
315     {
316         $r = "Set-Cookie: ";
317         $isfirst = TRUE;
318
319         foreach ($this->attr as $k => $v) {
320             if ($v == NULL) {
321                 $r .= sprintf("%s%s", ($isfirst ? "" : "; "), $k);
322             }
323             else {
324                 $r .= sprintf("%s%s=%s", ($isfirst ? "" : "; "), $k, $v);
325             }
326             $isfirst = FALSE;
327         }
328         $r .= "\r\n";
329
330         return $r;
331     }
332 }
333
334 class Cookies {
335     var $cookies;
336
337     function Cookies()
338     {
339         $this->cookies = array();
340     }
341
342     function add($name)
343     {
344         if (($cookie = call_user_func_array("Cookie::create", func_get_args())) == FALSE)
345             return (FALSE);
346
347         array_push($this->cookies, $cookie);
348
349         return (TRUE);
350     }
351
352     function render()
353     {
354         $r = "";
355         foreach ($this->cookies as $cookie) {
356             $r .= $cookie->render();
357         }
358
359         return ($r);
360     }
361 }
362
363
364 class Sac_a_push {
365     static $fixed_fd = 2;
366     
367     var $file_socket;
368     var $unix_socket;
369     var $socks;
370     var $s2u;
371     var $pages_flush;
372
373     var $list;
374     var $in;
375
376     var $debug;
377     var $blocking_mode;
378
379     var $app;
380
381     var $curtime;
382
383     var $rndstr;
384     var $main_loop;
385
386     function Sac_a_push()
387     {
388     }
389
390     // Sac_a_push::create("/tmp/brisk.sock", 0, 0
391
392     static function create(&$app, $sockname, $debug, $blocking_mode)
393     {        
394         $thiz = new Sac_a_push();
395         
396         $thiz->app = $app;
397         $thiz->file_socket = $sockname;
398         $thiz->unix_socket = "unix://$sockname";
399         $thiz->debug = $debug;
400         $thiz->socks = array();
401         $thiz->s2u  = array();
402         $thiz->pages_flush = array();
403
404         $thiz->blocking_mode = 0; // 0 for non-blocking
405
406         $thiz->rndstr = "";
407         for ($i = 0 ; $i < 4096 ; $i++) {
408             if (($i % 128) == 0)
409                 $thiz->rndstr .= " ";
410             else
411                 $thiz->rndstr .= chr(mt_rand(65, 90));
412         }
413         
414         if (file_exists($thiz->file_socket)) {
415             unlink($thiz->file_socket);
416         }
417     
418         $old_umask = umask(0);
419         if (($thiz->list = stream_socket_server($thiz->unix_socket, $err, $errs)) === FALSE) {
420             return (FALSE);
421         }
422         umask($old_umask);
423         stream_set_blocking($thiz->list, $thiz->blocking_mode); # Set the stream to non-blocking
424
425         if (($thiz->in = fopen("php://stdin", "r")) === FALSE) {
426             return(FALSE);
427         }
428
429         $thiz->main_loop = FALSE;
430
431         return ($thiz);
432     }
433
434     function socks_set($sock, $user)
435     {
436         $id = intval($sock);
437
438         $this->s2u[$id]   = $user;
439         $this->socks[$id] = $sock;
440     }
441
442     function socks_unset($sock)
443     {
444         $id = intval($sock);
445
446         unset($this->s2u[$id]);
447         unset($this->socks[$id]);
448     }
449
450     function pgflush_try_add($enc, &$new_socket, $tout, $header_out, $content)
451     {
452         $pgflush = new PageFlush($new_socket, $enc, $this->curtime, $tout, $header_out, $content);
453
454         if ($pgflush->try_flush($this->curtime) == FALSE) {
455             // Add $pgflush to the pgflush array
456             $this->pgflush_add($pgflush);
457         }
458     }
459
460     function pgflush_add($pgflush)
461     {
462         array_push($this->pages_flush, $pgflush);
463     }
464
465     function garbage_manager($force)
466     {
467         $this->app->garbage_manager($force);
468
469         foreach ($this->socks as $k => $sock) {
470             if ($this->s2u[intval($sock)]->sess == '') {
471                 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
472                     $this->s2u[intval($sock)]->rd_socket_set(NULL);
473                 }
474                 unset($this->socks[intval($sock)]);
475                 unset($this->s2u[intval($sock)]);
476                 fclose($sock);
477                 printf("CLOSE ON GARBAGE MANAGER\n");
478             }
479         }
480     }
481
482     function run()
483     {
484         GLOBAL $DOCUMENT_ROOT, $HTTP_HOST;
485
486         GLOBAL $G_alarm_passwd, $G_black_list, $G_btrace_pref_sub, $G_dbauth;
487         GLOBAL $G_dbpfx, $G_donors_all, $G_donors_cur, $G_is_local, $G_lang;
488         GLOBAL $G_poll_entries, $G_poll_name, $G_poll_title, $G_proxy_white_list;
489         GLOBAL $G_room_roadmap, $G_shutdown, $G_sidebanner, $G_sidebanner2;
490         GLOBAL $G_splash_content, $G_splash_contents, $G_splash_cont_idx;
491         GLOBAL $G_splash_h, $G_splash_idx, $G_splash_interval, $G_splash_timeout;
492         GLOBAL $G_splash_w, $G_topbanner, $G_with_donors, $G_with_poll;
493         GLOBAL $G_with_sidebanner, $G_with_sidebanner2, $G_with_splash;
494         GLOBAL $G_with_topbanner;
495
496         if ($this->main_loop) {
497             return (FALSE);
498         }
499         
500         $this->main_loop = TRUE;
501         
502         while ($this->main_loop) {
503             $this->curtime = time();
504             printf("IN LOOP: Current opened: %d  pages_flush: %d - ", count($this->socks), count($this->pages_flush));
505             
506             /* Prepare the read array */
507             /* // when we manage it ... */
508             /* if ($shutdown)  */
509             /*     $read   = array_merge(array("$in" => $in), $socks); */
510             /* else */
511             $read   = array_merge(array(intval($this->list) => $this->list, intval($this->in) => $this->in),
512                                   $this->socks);
513             
514             if ($this->debug > 1) {
515                 printf("PRE_SELECT\n");
516                 print_r($read);
517             }
518             $write  = NULL;
519             $except = NULL;
520             $num_changed_sockets = stream_select($read, $write, $except, 0, 500000);
521         
522             if ($num_changed_sockets == 0) {
523                 printf(" no data in 5 secs, splash [%d]\n", $G_with_splash);
524             } 
525             else if ($num_changed_sockets > 0) {
526                 printf("num sock %d num_of_socket: %d\n", $num_changed_sockets, count($read));
527                 if ($this->debug > 1) {
528                     print_r($read);
529                 }
530                 /* At least at one of the sockets something interesting happened */
531                 foreach ($read as $i => $sock) {
532                     /* is_resource check is required because there is the possibility that
533                        during new request an old connection is closed */
534                     if (!is_resource($sock)) {
535                         continue;
536                     }
537                     if ($sock === $this->list) {
538                         printf("NUOVA CONNEX\n");
539                         if (($new_unix = stream_socket_accept($this->list)) == FALSE) {
540                             printf("SOCKET_ACCEPT FAILED\n");
541                             continue;
542                         }
543                         $stream_info = "";
544                         $method      = "";
545                         $get         = array();
546                         $post        = array();
547                         $cookie      = array();
548                         if (($new_socket = ancillary_getstream($new_unix, $stream_info)) !== FALSE) {
549                             printf("NEW_SOCKET: %d\n", intval($new_socket));
550                             stream_set_blocking($new_socket, $this->blocking_mode); // Set the stream to non-blocking
551                             printf("RECEIVED HEADER:\n%s", $stream_info);
552                             $path = spu_process_info($stream_info, $method, $header, $get, $post, $cookie);
553                             printf("PATH: [%s]\n", $path);
554                             printf("M: %s\nHEADER:\n", $method);
555                             print_r($header);
556                             printf("GET:\n");
557                             print_r($get);
558                             printf("POST:\n");
559                             print_r($post);
560                             printf("COOKIE:\n");
561                             print_r($cookie);
562                             $addr = stream_socket_get_name($new_socket, TRUE);
563                             $header_out = array();
564
565                             $subs = SITE_PREFIX."briskin5/";
566                             $subs_l = strlen($subs);
567                             $rret = FALSE;
568                             if (!strncmp($path, SITE_PREFIX, SITE_PREFIX_LEN)) {
569                                 $rret = $this->app->request_mgr($this, $header, $header_out, $new_socket, substr($path, SITE_PREFIX_LEN), $addr, $get, $post, $cookie);
570                             }
571                             if ($rret == FALSE) { 
572                                 // FIXME: manage 404 !!!
573                                 printf("TODO: fix unknown page\n");
574                             }
575                             printf("number of sockets after %d\n", count($this->socks));
576                         }
577                         else {
578                             printf("WARNING: ancillary_getstream failed\n");
579                         }
580                     }
581                     else {
582                         $buf = fread($sock, 512);
583                         // if socket is closed
584                         if ($buf == FALSE || strlen($buf) == 0) {
585                             if ($buf == FALSE) {
586                                 printf("ERROR READING\n");
587                             }
588                             if ($sock === $this->list) {
589                                 printf("Arrivati %d bytes da list\n", strlen($buf));
590                                 return(21);
591                             }
592                             else if ($sock === $this->in) {
593                                 printf("Arrivati %d bytes da stdin\n", strlen($buf));
594                                 return(22);
595                             }
596                             else {
597                                 // $user_a[$s2u[intval($sock)]]->disable();
598                                 if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
599                                     $this->s2u[intval($sock)]->rd_socket_set(NULL);
600                                 }
601                                 unset($this->socks[intval($sock)]);
602                                 unset($this->s2u[intval($sock)]);
603                             }
604                             fclose($sock);
605                             printf("CLOSE ON READ\n");
606
607                             if ($this->debug > 1) {
608                                 printf("post unset\n");
609                                 print_r($this->socks);
610                             }
611                         }
612                         else {
613                             if ($this->debug > 1) {
614                                 print_r($read);
615                             }
616                             if ($sock === $this->list) {
617                                 printf("Arrivati %d bytes da list\n", strlen($buf));
618                             }
619                             else if ($sock === $this->in) {
620                                 printf("Arrivati %d bytes da stdin\n", strlen($buf));
621                                 $line = trim($buf);
622                                 if ($line == "reload") {
623                                     require("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
624
625                                     global_dump();
626                                 }
627                                 else if ($line == "shutdown") {
628                                     if ($this->app->dump_data()) {
629                                         return(0);
630                                     }
631                                     else {
632                                         return(1);
633                                     }
634                                 }
635                             }
636                             else {
637                                 $key = array_search("$sock", $this->socks);
638                                 printf("Arrivati %d bytes dalla socket n. %d\n", strlen($buf), $key);
639                             }
640                         }
641                     }
642                 }
643             }
644
645             $this->garbage_manager(FALSE);
646
647             /* manage unfinished pages */
648             foreach ($this->pages_flush as $k => $pgflush) {
649                 if ($pgflush->try_flush($this->curtime) == TRUE) {
650                     unset($this->pages_flush[$k]);
651                 }
652             }
653             
654             /*
655                $response:                        raw stream data not sent
656                $content:                         html consistent data (<script bla bla>)
657                $user->stream_keepalive($w_ping)  ping srv->cli OR srv->cli + cli->srv if $w_ping == TRUE
658             */
659
660             /* manage open streaming */
661             foreach ($this->socks as $k => $sock) {
662                 if (isset($this->s2u[intval($sock)])) {
663                     $user = $this->s2u[intval($sock)];
664                     $response = $user->rd_cache_get();
665                     $do_ping = FALSE;
666                     if (($this->curtime - $user->lacc) > (EXPIRE_TIME_RD / 3)) {
667                         $do_ping = TRUE;
668                     }
669                     else {
670                         $user->ping_req = FALSE;
671                     }
672
673                     if ($response == "") {
674                         $content = "";
675                         $user->stream_main($content, $get, $post, $cookie);
676                         printf("[%s] [%d] [%d]\n", $user->name, $user->lacc, $this->curtime);
677                         if ($do_ping && $user->ping_req == FALSE) {
678                             $content .= $user->stream_keepalive(TRUE);
679                             $user->ping_req = TRUE;
680                         }
681                         else if ($content == "" && $user->rd_kalive_is_expired($this->curtime)) {
682                             $content = $user->stream_keepalive(FALSE);
683                         }
684                         if ($content != "") {
685                             $response = chunked_content($user->rd_zls_get(), $content);
686                         }
687                     }
688                     
689                     if ($response != "") {
690                         // echo "SPIA: [".substr($response, 0, 60)."...]\n";
691                         echo "SPIA: [".$response."]\n";
692                         $response_l = mb_strlen($response, "ASCII");
693                         $wret = @fwrite($sock, $response);
694                         if ($wret < $response_l) {
695                             printf("TROUBLE WITH FWRITE: %d\n", $wret);
696                             $user->rd_cache_set(mb_substr($response, $wret, $response_l - $wret, "ASCII"));
697                         }
698                         else {
699                             $user->rd_cache_set("");
700                         }
701                         fflush($sock);
702                         $user->rd_kalive_reset($this->curtime);
703                     }
704                     
705                     // close socket after a while to prevent client memory consumption
706                     if ($user->rd_endtime_is_expired($this->curtime)) {
707                         if ($this->s2u[intval($sock)]->rd_socket_get() != NULL) {
708                             $this->s2u[intval($sock)]->rd_socket_set(NULL);
709                         }
710                         unset($this->socks[intval($sock)]);
711                         unset($this->s2u[intval($sock)]);
712                         fclose($sock);
713                         printf("CLOSE ON LOOP\n");
714                     }
715                 }
716             }  // foreach ($this->socks...
717             printf("\n");
718         }  // while (...
719     }  // function run(...
720 }
721
722 ?>