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     
27     var $types = array(
28         'css' => 'text/css',
29         'js' => 'text/javascript',
30     );
31     
32     function getAuth()
33     {
34         return true;
35     }
36     
37     
38     function get($s='')
39     {
40        
41         $bits = explode('/', $s);
42         
43         if (empty($bits[0]) || empty($bits[1])  || !isset($this->types[$bits[0]])) {
44             $this->jerr("invalid url");
45         }
46        
47         $s = str_replace('/', '-', $bits[1]);
48         
49         $ui = posix_getpwuid(posix_geteuid());
50         $ff = HTML_FlexyFramework::get();
51         
52         $compile = session_save_path() . '/' .
53                 $ui['name'] . '-' . $ff->project . '-' . $ff->version .  '-'. $bits[0] . 'compile';
54      
55         $fn = $compile . '/'. $s .'.'. $bits[0];
56         
57         
58         
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         $last_modified_time = filemtime($fn);
68         
69         
70         if (
71             (
72                 isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
73                 strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time
74             )
75             ||
76             (
77                  isset($_SERVER['HTTP_IF_NONE_MATCH']) &&
78                 trim($_SERVER['HTTP_IF_NONE_MATCH']) == md5($fn)
79             )) { 
80             header("HTTP/1.1 304 Not Modified");
81             exit;
82         }
83         
84         header('Content-Type: '. $this->types[$bits[0]]);
85         
86         
87         header("Pragma: public");
88         header('Content-Length: '. filesize($fn));
89         header('Cache-Control: max-age=2592000, public');
90         header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 2592000));
91         header('Last-Modified: '.gmdate('D, d M Y H:i:s \G\M\T', $last_modified_time));
92         header('Etag: '. md5($fn)); 
93         
94         $fh = fopen($fn,'r');
95         fpassthru($fh);
96         fclose($fh);
97         exit;
98         
99     }
100     function post($s='') {
101         die('invalid');
102     }
103      
104     
105 }
106
107 // a little experimental... we are going to use the same name as the class. for these..
108
109 trait Pman_Core_Asset_Trait {
110     
111     
112     
113      /**
114      * usage in template
115      * {outputJavascriptDir(#Hydra#,#Hydra.js",#.......#)}
116      *
117      * call_user
118      * 
119      */
120     
121     function outputJavascriptDir($path)
122     {
123         die("jsdir");
124         $relpath = $this->rootURL . '/' . $path .'/';
125         $ff = HTML_FlexyFramework::get();
126         $dir =   $this->rootDir.'/' . $path;
127         
128         $args = func_get_args();
129         $ar = array();
130         if (count($args) < 2) {
131             $ar = glob($dir . '/*.js');
132         } else {
133             array_shift($args);
134             foreach($args as $f) {
135                 if (strpos($f,'*') > -1) {
136  
137                     $ar = array_merge($ar ,  glob($dir . '/'. $f));
138                     continue;
139                 }
140                 
141                 $ar[] = $dir .'/'. $f;
142             }
143           
144         }
145          // cached version?? - how do we decide if it's expired?
146         // while scanning the directory is slow... - it's faster than serving every file...
147         
148         
149         //$path = $this->rootURL ."/Pman/$mod/";
150         
151         
152         
153         $files = array();
154         $arfiles = array();
155         $maxtime = 0;
156         $mtime = 0;
157         foreach($ar as $fn) {
158             $f = basename($fn);
159             // got the 'module file..'
160             $mtime = filemtime($dir . '/'. $f);
161             $maxtime = max($mtime, $maxtime);
162             $arfiles[$fn] = $mtime;
163             $files[] = $relpath  . $f . '?ts='.$mtime;
164         }
165         
166         ksort($arfiles); // just sort by name so it's consistant for serialize..
167         
168         $ui = posix_getpwuid(posix_geteuid());
169        
170         
171         $compiledir = session_save_path() . '/' .
172                 $ui['name'] . '-' . $ff->project . '-' . $ff->version . '-jscompile';
173         
174         if (!file_exists($compiledir)) {
175             mkdir($compiledir,0700,true);
176         }
177         
178          
179         
180         $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
181         usort($files, $lsort);
182         
183         
184         if (!empty($this->bootLoader->isDev) && !empty($_REQUEST['isDev'])) {
185             echo "<!-- Javascript compile turned off (isDev on) -->\n";
186             $this->assetArrayToHtml($files,'js');
187             return;
188         }
189         
190         
191         $smod = str_replace('/','.',$path);
192         
193         $output = date('Y-m-d-H-i-s-', $maxtime). $smod .'-'.md5(serialize($arfiles)) .'.js';
194          
195          
196         
197         // where are we going to write all of this..
198         // This has to be done via a 
199         if (!file_exists($compiledir.'/'.$output) || !filesize($compiledir.'/'.$output)) {
200             require_once 'Pman/Core/JsCompile.php';
201             $x = new Pman_Core_JsCompile();
202             
203             $x->pack($arfiles,$compiledir.'/'.$output, false);
204             clearstatcache();
205             if (!file_exists($compiledir.'/'.$output) ||
206                 !filesize($compiledir.'/'.$output)) {
207                 echo "<!-- compile did not generate files : {$compiledir}/{$output} -->\n";
208                 $this->assetArrayToHtml($files,'js');
209                 return;
210             } 
211             
212         } else {
213          //   echo "<!-- file already exists: {$basedir}/{$output} -->\n";
214         }
215         //$this->arrayToJsInclude(  $files);
216         $this->assetArrayToHtml(  array(
217             $this->baseURL.'/Asset/js/'. $output,
218           
219         ), 'js');
220         
221     }
222     
223     function assetArrayToHtml($ar, $type)
224     {
225         foreach($ar as $f) {
226             switch( $type) {
227                 case 'js':
228                     echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
229                     break;
230                 case 'css':
231                     echo '<link rel="stylesheet" href="'. $f. '"/>'."\n";
232                     break;
233        
234             }
235             
236         }
237     }
238     
239     
240     /**
241      * usage in template
242      * {outputCssDir(#{Hydra/templates/images/css/#,#Hydra.js",#.......#)}
243      */
244     
245     function outputCssDir($path)
246     {
247         $relpath = $this->rootURL . '/' . $path .'/';
248         $ff = HTML_FlexyFramework::get();
249         $dir =   $this->rootDir.'/' . $path;
250         
251         $args = func_get_args();
252         $ar = array();
253         if (count($args) < 2) {
254             $ar = glob($dir . '/*.css');
255         } else {
256             array_shift($args);
257             foreach($args as $f) {
258                 if (strpos($f,'*') > -1) {
259  
260                     $ar = array_merge($ar ,  glob($dir . '/'. $f));
261                     continue;
262                 }
263                 // what if the fiel does not exist???
264                 $ar[] = $dir .'/'. $f;
265             }
266           
267         }
268         
269         
270          // cached version?? - how do we decide if it's expired?
271         // while scanning the directory is slow... - it's faster than serving every file...
272         
273         
274         //$path = $this->rootURL ."/Pman/$mod/";
275         
276         //print_R($ar);exit;
277         
278         $files = array();
279         $arfiles = array();
280         $relfiles = array(); // array of files without the path part...
281         $maxtime = 0;
282         $mtime = 0;
283         foreach($ar as $fn) {
284             $relfiles[] = substr($fn, strlen($dir)+1);
285             $f = basename($fn);
286             // got the 'module file..'
287             $mtime = filemtime($dir . '/'. $f);
288             $maxtime = max($mtime, $maxtime);
289             $arfiles[$fn] = $mtime;
290             $files[] = $relpath  . $f . '?ts='.$mtime;
291             
292             
293             
294         }
295          
296         //print_r($relfiles);
297         
298         $ui = posix_getpwuid(posix_geteuid());
299        
300         
301         $compiledir = session_save_path() . '/' .
302                 $ui['name'] . '-' . $ff->project . '-'. $ff->version . '-csscompile';
303         
304         if (!file_exists($compiledir)) {
305             mkdir($compiledir,0700,true);
306         }
307         
308          
309         // no sorting???
310         //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
311         //usort($files, $lsort);
312         
313         
314         if (!empty($this->bootLoader->isDev) && !empty($_REQUEST['isDev'])) {
315             echo "<!-- CSS compile turned off (isDev on) -->\n";
316             $this->assetArrayToHtml($files,'css');
317             return;
318         }
319         
320         
321         $smod = str_replace('/','.',$path);
322         
323         $output = date('Y-m-d-H-i-s-', $maxtime). $smod .'-'.md5(serialize($arfiles)) .'.css';
324          
325          
326         
327         // where are we going to write all of this..
328         // This has to be done via a 
329         if (true || !file_exists($compiledir.'/'.$output) || !filesize($compiledir.'/'.$output)) {
330             
331             
332             
333             require_once 'HTML/CSS/Minify.php';
334             $x = new HTML_CSS_Minify(substr($relpath,0,-1), $dir, $relfiles);
335             
336             file_put_contents($compiledir.'/'.$output , $x->minify( $this->baseURL.'/Asset/css'));
337             clearstatcache();
338             if (!file_exists($compiledir.'/'.$output) ||
339                 !filesize($compiledir.'/'.$routput)) {
340                 echo "<!-- compile did not generate files : {$compiledir}/{$output} -->\n";
341                 $this->assetArrayToHtml($files,'css');
342                 return;
343             } 
344             
345         } else {
346          //   echo "<!-- file already exists: {$basedir}/{$output} -->\n";
347         }
348         //$this->arrayToJsInclude(  $files);
349         $this->assetArrayToHtml(  array(
350             $this->baseURL.'/Asset/css/'. $output,
351           
352         ),'css');
353         
354     }
355     
356     
357     
358 }