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