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