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