Asset.php
[Pman.Core] / Asset.php
1 <?php
2  
3  /**
4   * Generic cached assset server... -- No security om this.. should only return compressed CSS/JS
5   *
6   * Does a few tricks with headers to improve caching...
7   *
8   *
9   * Also includes code to generate assets...
10   *
11   * methods outputJavascriptDir / outputCssDir generate links to 
12   *    BASEURL/Asset/css/xxxx.yyy.zzz
13   *    BASEURL/Asset/js/xxxx.yyy.zzz
14   *
15   *   then
16   *   we deliver the file from
17   *       SESSION-DIR/{$www-user}-{$ff->project}-$ff->version}-{js|css}-compile/{filename}/PATH';
18   *
19   *   
20   */
21  
22 require_once 'Pman.php';
23
24 class Pman_Core_Asset extends Pman {
25      
26     var $types = array(
27         'css' => 'text/css',
28         'js' => 'text/javascript',
29     );
30     
31     function getAuth()
32     {
33         return true;
34     }
35     
36     
37     function get($s='', $opts = Array())
38     {
39
40         
41         $this->sessionState(0);
42         
43         $bits = explode('/', $s);
44         
45         if (empty($bits[0]) || empty($bits[1])  || !isset($this->types[$bits[0]])) {
46             $this->jerr("invalid url");
47         }
48        
49         $s = str_replace('/', '-', $bits[1]);
50         
51         $ui = posix_getpwuid(posix_geteuid());
52         $ff = HTML_FlexyFramework::get();
53         
54         $compile = self::getCompileDir($bits[0]);
55         //'session_save_path() . '/' .
56          //       $ui['name'] . '-' . $ff->project . '-' . $ff->version .  '-'. $bits[0] . 'compile';
57      
58         $fn = $compile . '/'. $s .'.'. $bits[0];
59         
60         if (!file_exists($fn)) {
61             header('Content-Type: '. $this->types[$bits[0]]);
62         
63             echo "// compiled file not found = $fn";
64             exit;
65         }
66         
67         $supportsGzip = !empty($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip' ) !== false;
68
69         
70         $last_modified_time = filemtime($fn);
71         
72         
73         if (
74             (
75                 isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
76                 strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time
77             )
78             ||
79             (
80                  isset($_SERVER['HTTP_IF_NONE_MATCH']) &&
81                 trim($_SERVER['HTTP_IF_NONE_MATCH']) == md5($fn)
82             )) { 
83             header("HTTP/1.1 304 Not Modified");
84             exit;
85         }
86         
87         header('Content-Type: '. $this->types[$bits[0]]);
88         
89         
90         header("Pragma: public");
91         
92         header('Cache-Control: max-age=2592000, public');
93         header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 2592000));
94         header('Last-Modified: '.gmdate('D, d M Y H:i:s \G\M\T', $last_modified_time));
95         header('Etag: '. md5($fn)); 
96         
97          if ( $supportsGzip ) {
98             $content = gzencode( file_get_contents($fn) , 9);
99             
100             header('Content-Encoding: gzip');
101             header('Vary: Accept-Encoding');
102             header('Content-Length: '. strlen($content));
103             
104             echo $content;
105             
106         } else {
107             
108             
109             $fh = fopen($fn,'r');
110             fpassthru($fh);
111             fclose($fh);
112             $content = $data;
113         }
114         
115         
116         
117         exit;
118         
119     }
120     
121     function post($s='') {
122         if(!empty($_REQUEST['_clear_cache'])) {
123             $this->clearCompiledFilesCache();
124         }
125         
126         die('invalid');
127     }
128      
129     static function getCompileDir($type, $module = '', $is_mkdir = true)
130     {
131         $ff = HTML_FlexyFramework::get();
132         
133         $ui = posix_getpwuid(posix_geteuid());
134         
135         $compile_dir = session_save_path() . "/";
136         
137         if (empty($module)) {
138             $module = $ff->project . (isset($ff->appNameShort) ?  '_' . $ff->appNameShort : '');
139         }
140         
141         
142         switch($type) {
143             case 'js':
144             case 'css':
145                 $compile_dir .= implode("-", array(
146                     $ui['name'],
147                     $module,
148                     $ff->version,
149                     "{$type}compile"
150                 ));
151                 break;
152             // template config?
153             default:
154                 return false;
155         }
156         
157         if (file_exists($compile_dir)) {
158             return $compile_dir;
159         }
160         
161         if(!$is_mkdir) {
162             return false;
163         }
164         
165         if(mkdir($compile_dir, 0700, true)) {
166             return $compile_dir;
167         }
168         
169         return false;
170     }
171     
172     function clearCompiledFilesCache()
173     {
174         $au = $this->getAuthUser();
175         if (!$au && !in_array($_SERVER['REMOTE_ADDR'] , array('127.0.0.1','::1'))) {
176             $this->jerr("Cache can only be cleared by authenticated users");
177         }
178         
179         require_once 'System.php';
180         
181         $mods = $this->modulesList();
182         $mods[] = $ff->project; // Pman
183         $mods[] = ''; // Pman + appshortname..
184         
185         foreach ($mods as $module) {
186             $compile_dir = $this->getCompileDir('js', $module, false);
187         
188             if(!empty($compile_dir)) {
189                 System::rm(array('-r', $compile_dir));
190             }
191             $compile_dir = $this->getCompileDir('css', $module, false);
192         
193             if(!empty($compile_dir)) {
194                 System::rm(array('-r', $compile_dir));
195             }
196         }
197          
198         $this->jok('DONE');
199     }
200 }