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