jscompile remove css
[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         
204         echo '<!-- JSCOMPILE - should not be used for CSS packing ?? -->';
205         return false;
206         // if we did.. use this?
207         
208         //require_once 'HTML/CSS/Minify.php';
209         //$x = new HTML_CSS_Minify(substr($relpath,0,-1), $dir, $relfiles);
210             
211           //  file_put_contents($compiledir.'/'.$output , $x->minify( $this->baseURL.$asset));
212         
213         
214     }
215     /**
216      * wrapper arround packer...
217      * uses the translation module & puts index in __tra
218      * 
219      * @param {Array} map of $files => filemtime the files to pack
220      * @param {String} $output name fo file to output
221      *
222      */
223     
224     function pack($files, $output, $translation_base=false)
225     {
226         
227         if (empty($files)) {
228             return false;
229         }
230         
231         $o = HTML_FlexyFramework::get()->Pman_Core;
232         if (isset($o['packseed'])) {
233             return $this->packSeed($files,$output,$translation_base);
234         }
235         
236         
237         require_once 'System.php';
238         $packer = System::which('roojspacker');
239         
240         
241         if (!$packer) {
242             echo '<!-- roojspacker is not installed -->';
243             return false;
244             
245         }
246         $targetm = file_exists($output) && filesize($output) ? filemtime($output) : 0;
247         $max = 0;
248         $ofiles = array();
249         foreach($files as $f => $mt) {
250             $max = max($max,$mt);
251             $ofiles[] = escapeshellarg($f);
252         }
253         if ($max < $targetm) {
254             echo '<!--  use cached compile. -->';
255             return true;
256         }
257         
258         if (file_exists($output)) {
259             unlink($output);
260         }
261         
262          
263         if (!file_exists(dirname($output))) {
264             mkdir(dirname($output), 0755, true);
265         }
266         
267         usort($ofiles, function($a,$b)  { return strlen($a) > strlen($b) ? 1 : -1; });
268         
269         //$eoutput = " -k  -o " . escapeshellarg($output) ; // with whitespace..
270         $eoutput = "  -t " . escapeshellarg($output) ;
271           
272         // no support for translation any more?         
273         //if (  $translation_base) {
274         //    $toutput = " -t ". escapeshellarg(preg_replace('/\.js$/', '.__translation__.js', $output)) .
275         //            " -p " . escapeshellarg($translation_base) ;//." -k "; // this kills the compression.
276         //            
277         //}
278         
279     
280         $cmd = "$packer  $eoutput  -f " . implode(' -f ', $ofiles) . ' 2>&1';
281         //echo "<PRE>$cmd\n";
282         //echo `$cmd`;
283         
284          echo "<!-- Compile javascript
285           
286             " . htmlspecialchars($cmd) . "
287             
288             -->";
289             
290        // return false;
291         
292         $res = `$cmd`;
293         //exit;
294         file_put_contents($output.'.log', $cmd."\n\n". $res);
295         // since this only appears when we change.. it's ok to dump it out..
296         echo "<!-- Compiled javascript
297             " . htmlspecialchars($res) . "
298             -->";
299         clearstatcache();
300         // we should do more checking.. return val etc..
301         if (file_exists($output) && filesize($output) && ($max < filemtime($output) ) ) {
302             echo "<!-- file looks like its been generated -->\n";
303             return true;
304         }
305         echo '<script type="text/javascript"> alert('. json_encode("Error: Javascript Compile failed\n" . $res) .');</script>';
306      
307         
308         echo "<!-- JS COMPILE ERROR: packed file did not exist  -->";
309         return false;
310         
311     }
312     
313     // depricated verison using seed.
314     function packSeed($files, $output, $translation_base=false)
315     {
316         
317          
318         $o = HTML_FlexyFramework::get()->Pman_Core;
319         
320         if (empty($o['packseed']) || !file_exists($o['jspacker'].'/pack.js')) {
321             echo '<!-- JS COMPILE ERROR: option: Pman_Core[jspacker] not set to directory -->';
322             return false;
323             
324         }
325         require_once 'System.php';
326         $seed= System::which('seed');
327         $gjs = System::which('gjs');
328         
329         if (!$seed && !$gjs) {
330             echo '<!-- seed or gjs are  not installed -->';
331             return false;
332             
333         }
334         $targetm = file_exists($output) && filesize($output) ? filemtime($output) : 0;
335         $max = 0;
336         $ofiles = array();
337         foreach($files as $f => $mt) {
338             $max = max($max,$mt);
339             $ofiles[] = escapeshellarg($f);
340         }
341         if ($max < $targetm) {
342             echo '<!--  use cached compile. -->';
343             return true;
344         }
345         //var_dump($output);
346         if (!file_exists(dirname($output))) {
347             mkdir(dirname($output), 0755, true);
348         }
349         $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
350         usort($ofiles, $lsort);
351         
352         //$eoutput = " -k  -o " . escapeshellarg($output) ; // with whitespace..
353         $eoutput = "  -o " . escapeshellarg($output) ;
354                    
355         if (  $translation_base) {
356             $toutput = " -t ". escapeshellarg(preg_replace('/\.js$/', '.__translation__.js', $output)) .
357                     " -p " . escapeshellarg($translation_base) ;//." -k "; // this kills the compression.
358                     
359         }
360         
361         
362         $cmd = ($seed ?
363              "$seed {$o['packseed']}/pack.js " :
364              "$gjs -I {$o['packseed']} -I {$o['packseed']}/JSDOC  {$o['packseed']}/pack.js -- -- " 
365               
366              ) . " $eoutput  $toutput " . implode($ofiles, ' ') . ' 2>&1';
367         //echo "<PRE>$cmd\n";
368         //echo `$cmd`;
369         
370          echo "<!-- Compile javascript
371           
372             " . htmlspecialchars($cmd) . "
373             
374             -->";
375             
376        // return false;
377         
378         $res = `$cmd`;
379         //exit;
380         file_put_contents($output.'.log', $cmd."\n\n". $res);
381         // since this only appears when we change.. it's ok to dump it out..
382         echo "<!-- Compiled javascript
383             " . htmlspecialchars($res) . "
384             -->";
385             
386         // we should do more checking.. return val etc..
387         if (file_exists($output) && ($max < filemtime($output) ) ) {
388             
389             return true;
390         }
391         
392          
393         echo "\n<!-- JS COMPILE ERROR: packed file did not exist  -->\n";
394         return false;
395         
396     }
397     
398     
399     /***
400      * build:
401      *
402      * @param {String} $proj name of Pman component to build
403      * runs pack.js -m {proj} -a $src/*.js
404      * 
405      *
406      */
407       
408     function build($proj) 
409     {
410         echo "Building $proj\n";
411        // var_dump($proj);
412         if (empty($proj)) {
413             $this->err = "no project";
414             if ($this->cli) echo $this->err;
415             return;
416         }
417         // first item in path is always the app start directory..
418         $src= array_shift(explode(PATH_SEPARATOR, ini_get('include_path'))) .'/Pman/'. $proj;
419         
420         
421         
422        //$tmp = ini_get('session.save_path')."/{$proj}_". posix_getuid(). '_'.md5($src);
423         
424         
425         require_once 'System.php';
426         $seed= System::which('seed');
427         if (!$seed) {
428             $this->err ="no seed installed";
429             if ($this->cli) echo $this->err;
430             return false;
431         }
432         
433         $o = HTML_FlexyFramework::get()->Pman_Core;
434         
435         if (empty($o['packseed']) || !file_exists($o['packseed'].'/pack.js')) {
436             $this->err ="no jstoolkit path set [Pman_Core][packseed] to the
437                     introspection documentation directory where pack.js is located.";
438             if ($this->cli) echo $this->err;
439             return false;
440         }  
441         
442         // should we be more specirfic!??!?!?
443          
444         $cmd = "$seed {$o['packseed']}/pack.js -m $proj  -a  $src/*.js";
445         echo "$cmd\n";
446         passthru($cmd);
447         // technically we should trash old compiled files.. 
448         // or we move towards a 'cache in session directory model..'
449         
450         
451         /*
452         
453         $ret = $tmp . '/'. $proj . '.js';
454         if ($this->cli) {
455             echo "BUILT:  $ret \n";
456             exit;
457         }
458         return $ret;
459         */
460         
461     }
462     // link {PROJECT}/compiled/{PROJECT}.js to _compiled_ folder to make it live.
463         
464     function install($proj) 
465     {
466        
467         $base = dirname(realpath($_SERVER["SCRIPT_FILENAME"]));
468         if (empty($base )) {
469             $base = getcwd();
470         }
471         var_dump($base .'/Pman/'. $proj.'/compiled/'.$proj .'.js');
472         $src =  realpath($base .'/Pman/'. $proj.'/compiled/'.$proj .'.js');
473         if (!$src) {
474             echo "SKIP : no js file $proj\n";
475             return;
476         }
477         if (!file_exists("$base/_compiled_")) {
478             mkdir ("$base/_compiled_", 0755, true);
479         }
480         $target = "$base/_compiled_/".$proj .'.js';
481         print_R(array($src,$target));
482         if (file_exists($target)) {
483             return; // already installed.
484         }
485         
486         symlink($src, $target);
487         
488         
489     }
490     
491     function gatherProjects() {
492         $src= array_shift(explode(PATH_SEPARATOR, ini_get('include_path'))) .'/Pman';
493         
494         $ret = array();
495         foreach(scandir($src) as $f) {
496             if (!strlen($f) || $f[0] == '.') {
497                 continue;
498             }
499             
500             $fp = "$src/$f";
501             if (!is_dir($fp)) {
502                 continue;
503             }
504             if ($f == 'templates') {
505                 continue;
506             }
507             $ret[] = $f;
508             
509             
510         }
511         return $ret;
512     }
513 }
514