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