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