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         
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           
248         $relpath = $this->rootURL . '/' . $path .'/';
249         $ff = HTML_FlexyFramework::get();
250         $dir =   $this->rootDir.'/' . $path;
251         
252         $args = func_get_args();
253         $ar = array();
254         if (count($args) < 2) {
255             $ar = glob($dir . '/*.css');
256         } else {
257             array_shift($args);
258             foreach($args as $f) {
259                 if (strpos($f,'*') > -1) {
260  
261                     $ar = array_merge($ar ,  glob($dir . '/'. $f));
262                     continue;
263                 }
264                 // what if the fiel does not exist???
265                 $ar[] = $dir .'/'. $f;
266             }
267           
268         }
269         
270         
271          // cached version?? - how do we decide if it's expired?
272         // while scanning the directory is slow... - it's faster than serving every file...
273         
274         
275         //$path = $this->rootURL ."/Pman/$mod/";
276         
277         //print_R($ar);exit;
278         $missing_files  = false;
279         $files = array();
280         $arfiles = array();
281         $relfiles = array(); // array of files without the path part...
282         $maxtime = 0;
283         $mtime = 0;
284         foreach($ar as $fn) {
285             $relfiles[] = substr($fn, strlen($dir)+1);
286             $f = basename($fn);
287             // got the 'module file..'
288             
289             if (!file_exists($dir . '/'. $f)) {
290                 echo "<!-- missing {$relpath}/{$f} -->\n";
291                 $files[] = $relpath  . $f . '?ts='.$mtime;
292                 $missing_files = true;
293                 continue;
294             }
295             
296             $mtime = filemtime($dir . '/'. $f);
297             $maxtime = max($mtime, $maxtime);
298             $arfiles[$fn] = $mtime;
299             
300             
301             
302             
303         }
304         if ($missing_files) {
305             $this->assetArrayToHtml($files, 'css');
306             return;
307             
308         }
309         
310          
311         //print_r($relfiles);
312         
313         $ui = posix_getpwuid(posix_geteuid());
314        
315         
316         $compiledir = session_save_path() . '/' .
317                 $ui['name'] . '-' . $ff->project . '-'. $ff->version . '-csscompile';
318         
319         if (!file_exists($compiledir)) {
320             mkdir($compiledir,0700,true);
321         }
322         
323          
324         // no sorting???
325         //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
326         //usort($files, $lsort);
327         
328         
329         if (!empty($this->bootLoader->isDev) && !empty($_REQUEST['isDev'])) {
330             echo "<!-- CSS compile turned off (isDev on) -->\n";
331             $this->assetArrayToHtml($files,'css');
332             return;
333         }
334         
335         
336         $smod = str_replace('/','.',$path);
337         
338         $output = date('Y-m-d-H-i-s-', $maxtime). $smod .'-'.md5(serialize($arfiles)) .'.css';
339          
340          
341         
342         // where are we going to write all of this..
343         // This has to be done via a 
344         if (true || !file_exists($compiledir.'/'.$output) || !filesize($compiledir.'/'.$output)) {
345             
346             
347             
348             require_once 'HTML/CSS/Minify.php';
349             $x = new HTML_CSS_Minify(substr($relpath,0,-1), $dir, $relfiles);
350             
351             file_put_contents($compiledir.'/'.$output , $x->minify( $this->baseURL.'/Asset/css'));
352             clearstatcache();
353             if (!file_exists($compiledir.'/'.$output) ||
354                 !filesize($compiledir.'/'.$routput)) {
355                 echo "<!-- compile did not generate files : {$compiledir}/{$output} -->\n";
356                 $this->assetArrayToHtml($files,'css');
357                 return;
358             } 
359             
360         } else {
361          //   echo "<!-- file already exists: {$basedir}/{$output} -->\n";
362         }
363         //$this->arrayToJsInclude(  $files);
364         $this->assetArrayToHtml(  array(
365             $this->baseURL.'/Asset/css/'. $output,
366           
367         ),'css');
368         
369     }
370     
371     
372     
373 }