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