1: <?php
2: /**
3: * This filter cleans up javascript output by running it through an
4: * optimizer/compressor.
5: *
6: * Copyright 2009-2012 Horde LLC (http://www.horde.org/)
7: *
8: * See the enclosed file COPYING for license information (LGPL). If you
9: * did not receive this file, see http://www.horde.org/licenses/lgpl21.
10: *
11: * @author Michael Slusarz <slusarz@horde.org>
12: * @category Horde
13: * @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
14: * @package Text_Filter
15: */
16: class Horde_Text_Filter_JavascriptMinify extends Horde_Text_Filter_Base
17: {
18: /**
19: * Filter parameters.
20: *
21: * @var array
22: */
23: protected $_params = array(
24: 'closure' => null,
25: 'java' => null,
26: 'yui' => null
27: );
28:
29: /**
30: * Executes any code necessary after applying the filter patterns.
31: *
32: * @param string $text The text after the filtering.
33: *
34: * @return string The modified text.
35: */
36: public function postProcess($text)
37: {
38: if (!empty($this->_params['java'])) {
39: /* Are we using the YUI Compressor? */
40: if (!empty($this->_params['yui'])) {
41: return $this->_runCompressor($text, $this->_params['yui'], ' --type js');
42: }
43:
44: /* Are we using the Google Closure Compiler? */
45: if (!empty($this->_params['closure'])) {
46: return $this->_runCompressor($text, $this->_params['closure']);
47: }
48: }
49:
50: /* Use PHP-based minifier. */
51: $jsmin = new Horde_Text_Filter_JavascriptMinify_JsMin($text);
52: try {
53: return $jsmin->minify();
54: } catch (Exception $e) {
55: return $text;
56: }
57: }
58:
59: /**
60: * Passes javascript through a java compressor (YUI or Closure).
61: *
62: * @param string $text The javascript text.
63: * @param string $jar The JAR location.
64: * @param string $args Additional command line arguments.
65: *
66: * @return string The modified text.
67: */
68: protected function _runCompressor($jar, $args = '')
69: {
70: if (!is_executable($this->_params['java']) ||
71: !file_exists($jar)) {
72: return $text;
73: }
74:
75: $descspec = array(
76: 0 => array('pipe', 'r'),
77: 1 => array('pipe', 'w'),
78: 2 => array('pipe', 'w')
79: );
80:
81: $process = proc_open(escapeshellcmd($this->_params['java']) . ' -jar ' . escapeshellarg($jar) . $args, $descspec, $pipes);
82:
83: fwrite($pipes[0], $text);
84: fclose($pipes[0]);
85:
86: $out = '';
87: while (!feof($pipes[1])) {
88: $out .= fread($pipes[1], 8192);
89: }
90: fclose($pipes[1]);
91: fclose($pipes[2]);
92: proc_close($process);
93:
94: return $out;
95: }
96:
97: }
98: