convert css compression to use csstidy
[Pman.Core] / JsCompile.php
1 <?php
2
3 /**
4 * wrapper code around js builder...
5
6 *  -- we will use this later to compile on the fly...
7 *
8 *  -- updated to use roojspacker https://github.com/roojs/roojspacker
9 *
10 *
11 * For general usage:
12 *  $x = new Pman_Core_JsCompile();
13 *  $x->pack('/path/to/files/', 'destination')
14 *  
15 */
16 require_once 'Pman.php';
17
18
19 class Pman_Core_JsCompile  extends Pman
20 {
21     
22     static $cli_desc = "Wrapper around Javascript compression tools
23                         Runs the javascript compiler - merging all the JS files so the load faster.
24                         Note: cfg option Pman_Builder['jspacker'] must be set to location of jstoolkit code 
25 ";
26     
27     var $cli = false;
28     function getAuth()
29     {
30         // command line only ATM
31         $this->cli = HTML_FlexyFramework::get()->cli;
32       //  var_dump($this->cli);
33         if ($this->cli) {
34             return true;
35         }
36         return  false;
37     }
38     
39     
40     function get($proj, $args=array())
41     {
42         if (empty($args)) {
43             die("missing action : eg. build or install");
44         }
45         // list of projects.
46         if (empty($args[1])) {
47             
48             $ar = $this->gatherProjects();
49              echo "SELECT Component to build\n";
50             print_r($ar);
51             exit;
52         } else {
53             $ar = array($args[1]); 
54             //$ar = $args;
55             //array_shift($ar);
56         }
57         
58         switch ($args[0]) {
59             case 'build':
60              
61                 foreach($ar as $p) {
62                     $this->build($p);
63                     //$this->install($p);
64                 }
65                 break;
66             case 'install' :     // needed for install on remote sites..
67                 die('not yet..');
68                 foreach($ar as $p) {
69                     $this->install($p);
70                 }
71                 break;
72         }
73         exit;
74     }
75     /**
76      * packScript:
77      *
78      * @param {String} basedir absolute path to files
79      * @param {Array}  list of files (ontop of basedir) 
80      * @param {String} output url (path to basedir basically), or false
81      *                  to not compile
82      * 
83      *
84      */
85     
86     static function jsSort($a,$b)
87     {
88         $a = substr($a, 0, -3);
89         $b=  substr($b, 0, -3);
90         if ($a == $b) {
91             return 0;
92         }
93         return ($a > $b) ? +1 : -1;
94     }
95     
96     
97     function packScript($basedir, $files,  $output_url, $compile=true)
98     {
99         // this outputs <script tags..>
100         // either for just the original files,
101         // or the compressed version.
102         // first expand files..
103         
104         echo "<!-- compiling   $basedir  -->\n";
105         
106         $arfiles = array();
107         $ofiles = array();
108         foreach($files as $f) {
109              if (!file_exists($basedir .'/' .$f)) {
110                 continue;
111             }
112             if (!is_dir($basedir .'/' .$f)) {
113                 
114                 $arfiles[$basedir .'/' .$f] = filemtime($basedir .'/' .$f);
115                 $ofiles[] = $f;
116                 continue;
117             }
118             
119             foreach(glob($basedir .'/' .$f.'/*.js') as $fx) {
120                 
121                 $arfiles[$fx] = filemtime($fx);
122                 $ofiles [] = $f . '/'. basename($fx);
123             }
124         }
125         $tf = 
126         // sort exc. the .js
127         usort($ofiles,function($a,$b) { return Pman_Core_JsCompile::jsSort($a,$b); });
128         
129         //print_R($ofiles);
130         
131         $output = md5(serialize($arfiles)) .'.js';
132         
133         if ( $compile && !file_exists($basedir.'/_cache_/'.$output)) {
134             $this->pack($arfiles,$basedir.'/_cache_/'.$output);
135         }
136         
137         if ($compile && file_exists($basedir.'/_cache_/'.$output)) {
138             
139             echo '<script type="text/javascript" src="'.$output_url.'/_cache_/'. $output.'"></script>';
140             return;
141         }
142         foreach($ofiles as $f) {
143             echo '<script type="text/javascript" src="'.$output_url.'/'.$f.'"></script>'."\n";
144             
145         }
146           
147     }
148     
149     // this is depricated... - we can use the pear CSS library for this..
150     
151     function packCss($basedir, $files,   $output_url)
152     {
153         // this outputs <script tags..>
154         // either for just the original files,
155         // or the compressed version.
156         // first expand files..
157         
158         $arfiles = array();
159         $ofiles = array();
160         //print_R($files);
161         foreach($files as $f) {
162             if (!file_exists($basedir .'/' .$f)) {
163                 continue;
164             }
165             if (!is_dir($basedir .'/' .$f)) {
166                 $arfiles[$basedir .'/' .$f] = filemtime($basedir .'/' .$f);
167                 $ofiles[] = $f;
168                 continue;
169             }
170             foreach(glob($basedir .'/' .$f.'/*.css') as $fx) {
171                 $arfiles[$fx] = filemtime($fx);
172                 $ofiles [] = $f . '/'. basename($fx);
173             }
174         }
175         
176         $output = md5(serialize($arfiles)) .'.css';
177         
178         if (!file_exists($basedir.'/_cache_/'.$output)) {
179             $this->packCssCore($arfiles,$basedir.'/_cache_/'.$output);
180         }
181         //var_dump()$basedir. '/_cache_/'.$output);
182         if (file_exists($basedir. '/_cache_/'.$output)) {
183             echo '<link type="text/css" rel="stylesheet" media="screen" href="'.$output_url. '/_cache_/'. $output.'" />';
184             return;
185         }
186         foreach($ofiles as $f ) {
187             echo '<link type="text/css" rel="stylesheet" media="screen" href="'.$output_url.'/'.$f.'" />'."\n";
188              
189         }
190          
191         
192     }
193      /**
194      * wrapper arroudn packer...
195      * @param {Array} map of $files => filemtime the files to pack
196      * @param {String} $output name fo file to output
197      *
198      */
199     function packCssCore($files, $output)
200     {
201         
202
203         // csstidy 
204         // cat  x a b c | csstidy - --preserve_css=true --remove_bslash=false --silent=true --template=highest {out}
205         
206         
207         require_once 'System.php';
208         
209         $csstidy= System::which('csstidy');
210         $cat = System::which('cat');
211         
212         
213         if (!$csstidy) {
214             echo '<!-- csstidy not installed -->';
215             return false;
216             
217         }
218         $targetm = file_exists($output) ? filemtime($output) : 0;
219         $max = 0;
220         $ofiles = array();
221         foreach($files as $f => $mt) {
222             $max = max($max,$mt);
223             $ofiles[] = escapeshellarg($f);
224         }
225         if ($max < $targetm)  {
226             return true;
227         }
228         if (!file_exists(dirname($output))) {
229             mkdir(dirname($output), 0755, true);
230         }
231         $eoutput = escapeshellarg($output);
232         
233         $cmd = "$cat " . implode($ofiles, " ") . " | $csstidy   - --preserve_css=true --remove_bslash=false --silent=true --template=highest $eoutput";
234         
235         //echo "<PRE>$cmd\n"; echo `$cmd`; exit;
236         `$cmd`;
237         
238         
239         // we should do more checking.. return val etc..
240         if (file_exists($output) && ($max < filemtime($output) ) ) {
241             return true;
242         }
243         return false;
244         
245     }
246     /**
247      * wrapper arround packer...
248      * uses the translation module & puts index in __tra
249      * 
250      * @param {Array} map of $files => filemtime the files to pack
251      * @param {String} $output name fo file to output
252      *
253      */
254     
255     function pack($files, $output, $translation_base=false)
256     {
257         
258         if (empty($files)) {
259             return false;
260         }
261         
262         $o = HTML_FlexyFramework::get()->Pman_Core;
263         if (isset($o['packseed'])) {
264             return $this->packSeed($files,$output,$translation_base);
265         }
266         
267         
268         require_once 'System.php';
269         $packer = System::which('roojspacker');
270         
271         
272         if (!$packer) {
273             echo '<!-- roojspacker is not installed -->';
274             return false;
275             
276         }
277         $targetm = file_exists($output) && filesize($output) ? filemtime($output) : 0;
278         $max = 0;
279         $ofiles = array();
280         foreach($files as $f => $mt) {
281             $max = max($max,$mt);
282             $ofiles[] = escapeshellarg($f);
283         }
284         if ($max < $targetm) {
285             echo '<!--  use cached compile. -->';
286             return true;
287         }
288         
289         if (file_exists($output)) {
290             unlink($output);
291         }
292         
293          
294         if (!file_exists(dirname($output))) {
295             mkdir(dirname($output), 0755, true);
296         }
297         
298         usort($ofiles, function($a,$b)  { return strlen($a) > strlen($b) ? 1 : -1; });
299         
300         //$eoutput = " -k  -o " . escapeshellarg($output) ; // with whitespace..
301         $eoutput = "  -t " . escapeshellarg($output) ;
302           
303         // no support for translation any more?         
304         //if (  $translation_base) {
305         //    $toutput = " -t ". escapeshellarg(preg_replace('/\.js$/', '.__translation__.js', $output)) .
306         //            " -p " . escapeshellarg($translation_base) ;//." -k "; // this kills the compression.
307         //            
308         //}
309         
310     
311         $cmd = "$packer  $eoutput  -f " . implode(' -f ', $ofiles) . ' 2>&1';
312         //echo "<PRE>$cmd\n";
313         //echo `$cmd`;
314         
315          echo "<!-- Compile javascript
316           
317             " . htmlspecialchars($cmd) . "
318             
319             -->";
320             
321        // return false;
322         
323         $res = `$cmd`;
324         //exit;
325         file_put_contents($output.'.log', $cmd."\n\n". $res);
326         // since this only appears when we change.. it's ok to dump it out..
327         echo "<!-- Compiled javascript
328             " . htmlspecialchars($res) . "
329             -->";
330         clearstatcache();
331         // we should do more checking.. return val etc..
332         if (file_exists($output) && filesize($output) && ($max < filemtime($output) ) ) {
333             echo "<!-- file looks like its been generated -->\n";
334             return true;
335         }
336         echo '<script type="text/javascript"> alert('. json_encode("Error: Javascript Compile failed\n" . $res) .');</script>';
337      
338         
339         echo "<!-- JS COMPILE ERROR: packed file did not exist  -->";
340         return false;
341         
342     }
343     
344     // depricated verison using seed.
345     function packSeed($files, $output, $translation_base=false)
346     {
347         
348          
349         $o = HTML_FlexyFramework::get()->Pman_Core;
350         
351         if (empty($o['packseed']) || !file_exists($o['jspacker'].'/pack.js')) {
352             echo '<!-- JS COMPILE ERROR: option: Pman_Core[jspacker] not set to directory -->';
353             return false;
354             
355         }
356         require_once 'System.php';
357         $seed= System::which('seed');
358         $gjs = System::which('gjs');
359         
360         if (!$seed && !$gjs) {
361             echo '<!-- seed or gjs are  not installed -->';
362             return false;
363             
364         }
365         $targetm = file_exists($output) && filesize($output) ? filemtime($output) : 0;
366         $max = 0;
367         $ofiles = array();
368         foreach($files as $f => $mt) {
369             $max = max($max,$mt);
370             $ofiles[] = escapeshellarg($f);
371         }
372         if ($max < $targetm) {
373             echo '<!--  use cached compile. -->';
374             return true;
375         }
376         //var_dump($output);
377         if (!file_exists(dirname($output))) {
378             mkdir(dirname($output), 0755, true);
379         }
380         $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
381         usort($ofiles, $lsort);
382         
383         //$eoutput = " -k  -o " . escapeshellarg($output) ; // with whitespace..
384         $eoutput = "  -o " . escapeshellarg($output) ;
385                    
386         if (  $translation_base) {
387             $toutput = " -t ". escapeshellarg(preg_replace('/\.js$/', '.__translation__.js', $output)) .
388                     " -p " . escapeshellarg($translation_base) ;//." -k "; // this kills the compression.
389                     
390         }
391         
392         
393         $cmd = ($seed ?
394              "$seed {$o['packseed']}/pack.js " :
395              "$gjs -I {$o['packseed']} -I {$o['packseed']}/JSDOC  {$o['packseed']}/pack.js -- -- " 
396               
397              ) . " $eoutput  $toutput " . implode($ofiles, ' ') . ' 2>&1';
398         //echo "<PRE>$cmd\n";
399         //echo `$cmd`;
400         
401          echo "<!-- Compile javascript
402           
403             " . htmlspecialchars($cmd) . "
404             
405             -->";
406             
407        // return false;
408         
409         $res = `$cmd`;
410         //exit;
411         file_put_contents($output.'.log', $cmd."\n\n". $res);
412         // since this only appears when we change.. it's ok to dump it out..
413         echo "<!-- Compiled javascript
414             " . htmlspecialchars($res) . "
415             -->";
416             
417         // we should do more checking.. return val etc..
418         if (file_exists($output) && ($max < filemtime($output) ) ) {
419             
420             return true;
421         }
422         
423          
424         echo "\n<!-- JS COMPILE ERROR: packed file did not exist  -->\n";
425         return false;
426         
427     }
428     
429     
430     /***
431      * build:
432      *
433      * @param {String} $proj name of Pman component to build
434      * runs pack.js -m {proj} -a $src/*.js
435      * 
436      *
437      */
438       
439     function build($proj) 
440     {
441         echo "Building $proj\n";
442        // var_dump($proj);
443         if (empty($proj)) {
444             $this->err = "no project";
445             if ($this->cli) echo $this->err;
446             return;
447         }
448         // first item in path is always the app start directory..
449         $src= array_shift(explode(PATH_SEPARATOR, ini_get('include_path'))) .'/Pman/'. $proj;
450         
451         
452         
453        //$tmp = ini_get('session.save_path')."/{$proj}_". posix_getuid(). '_'.md5($src);
454         
455         
456         require_once 'System.php';
457         $seed= System::which('seed');
458         if (!$seed) {
459             $this->err ="no seed installed";
460             if ($this->cli) echo $this->err;
461             return false;
462         }
463         
464         $o = HTML_FlexyFramework::get()->Pman_Core;
465         
466         if (empty($o['packseed']) || !file_exists($o['packseed'].'/pack.js')) {
467             $this->err ="no jstoolkit path set [Pman_Core][packseed] to the
468                     introspection documentation directory where pack.js is located.";
469             if ($this->cli) echo $this->err;
470             return false;
471         }  
472         
473         // should we be more specirfic!??!?!?
474          
475         $cmd = "$seed {$o['packseed']}/pack.js -m $proj  -a  $src/*.js";
476         echo "$cmd\n";
477         passthru($cmd);
478         // technically we should trash old compiled files.. 
479         // or we move towards a 'cache in session directory model..'
480         
481         
482         /*
483         
484         $ret = $tmp . '/'. $proj . '.js';
485         if ($this->cli) {
486             echo "BUILT:  $ret \n";
487             exit;
488         }
489         return $ret;
490         */
491         
492     }
493     // link {PROJECT}/compiled/{PROJECT}.js to _compiled_ folder to make it live.
494         
495     function install($proj) 
496     {
497        
498         $base = dirname(realpath($_SERVER["SCRIPT_FILENAME"]));
499         if (empty($base )) {
500             $base = getcwd();
501         }
502         var_dump($base .'/Pman/'. $proj.'/compiled/'.$proj .'.js');
503         $src =  realpath($base .'/Pman/'. $proj.'/compiled/'.$proj .'.js');
504         if (!$src) {
505             echo "SKIP : no js file $proj\n";
506             return;
507         }
508         if (!file_exists("$base/_compiled_")) {
509             mkdir ("$base/_compiled_", 0755, true);
510         }
511         $target = "$base/_compiled_/".$proj .'.js';
512         print_R(array($src,$target));
513         if (file_exists($target)) {
514             return; // already installed.
515         }
516         
517         symlink($src, $target);
518         
519         
520     }
521     
522     function gatherProjects() {
523         $src= array_shift(explode(PATH_SEPARATOR, ini_get('include_path'))) .'/Pman';
524         
525         $ret = array();
526         foreach(scandir($src) as $f) {
527             if (!strlen($f) || $f[0] == '.') {
528                 continue;
529             }
530             
531             $fp = "$src/$f";
532             if (!is_dir($fp)) {
533                 continue;
534             }
535             if ($f == 'templates') {
536                 continue;
537             }
538             $ret[] = $f;
539             
540             
541         }
542         return $ret;
543     }
544 }
545