HTTP digest authentication can be used with the URI router.
* HTTP digest is much more recommended over the use of HTTP Basic auth which doesn't provide any encryption.
* If you are running PHP on Apache in CGI/FastCGI mode, you would need to
* add the following line to your .htaccess for digest auth to work correctly.
This class is tested under Apache 2.2 and Cherokee web server. It should work in both mod_php and cgi mode.
*
* @author Leng Sheng Hong
* @version $Id: DooDigestAuth.php 1000 2009-07-7 18:27:22
* @package doo.auth
* @since 1.0
*/
class DooDigestAuth{
/**
* Authenticate against a list of username and passwords.
*
*
HTTP Digest Authentication doesn't work with PHP in CGI mode,
* you have to add this into your .htaccess RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
*
* @param string $realm Name of the authentication session
* @param array $users An assoc array of username and password: array('uname1'=>'pwd1', 'uname2'=>'pwd2')
* @param string $fail_msg Message to be displayed if the User cancel the login
* @param string $fail_url URL to be redirect if the User cancel the login
* @return string The username if login success.
*/
public static function http_auth($realm, $users, $fail_msg=NULL, $fail_url=NULL){
$realm = "Restricted area - $realm";
//user => password
//$users = array('admin' => '1234', 'guest' => 'guest');
if(!empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && strpos($_SERVER['REDIRECT_HTTP_AUTHORIZATION'], 'Digest')===0){
$_SERVER['PHP_AUTH_DIGEST'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
}
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
header('HTTP/1.1 401 Unauthorized');
if($fail_msg!=NULL)
die($fail_msg);
if($fail_url!=NULL)
die("");
exit;
}
// analyze the PHP_AUTH_DIGEST variable
if (!($data = self::http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || !isset($users[$data['username']])){
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
header('HTTP/1.1 401 Unauthorized');
if($fail_msg!=NULL)
die($fail_msg);
if($fail_url!=NULL)
die("");
exit;
}
// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
if ($data['response'] != $valid_response){
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
if($fail_msg!=NULL)
die($fail_msg);
if($fail_url!=NULL)
die("");
exit;
}
// ok, valid username & password
return $data['username'];
}
/**
* Method to parse the http auth header, works with IE.
*
* Internet Explorer returns a qop="xxxxxxxxxxx" in the header instead of qop=xxxxxxxxxxx as most browsers do.
*
* @param string $txt header string to parse
* @return array An assoc array of the digest auth session
*/
private static function http_digest_parse($txt)
{
$res = preg_match("/username=\"([^\"]+)\"/i", $txt, $match);
$data['username'] = (isset($match[1]))?$match[1]:null;
$res = preg_match('/nonce=\"([^\"]+)\"/i', $txt, $match);
$data['nonce'] = $match[1];
$res = preg_match('/nc=([0-9]+)/i', $txt, $match);
$data['nc'] = $match[1];
$res = preg_match('/cnonce=\"([^\"]+)\"/i', $txt, $match);
$data['cnonce'] = $match[1];
$res = preg_match('/qop=([^,]+)/i', $txt, $match);
$data['qop'] = str_replace('"','',$match[1]);
$res = preg_match('/uri=\"([^\"]+)\"/i', $txt, $match);
$data['uri'] = $match[1];
$res = preg_match('/response=\"([^\"]+)\"/i', $txt, $match);
$data['response'] = $match[1];
return $data;
}
}
PK ^GM= = min/lib/JSMin.phpnu W+A
* $minifiedJs = JSMin::minify($js);
*
*
* This is a modified port of jsmin.c. Improvements:
*
* Does not choke on some regexp literals containing quote characters. E.g. /'/
*
* Spaces are preserved after some add/sub operators, so they are not mistakenly
* converted to post-inc/dec. E.g. a + ++b -> a+ ++b
*
* Preserves multi-line comments that begin with /*!
*
* PHP 5 or higher is required.
*
* Permission is hereby granted to use this version of the library under the
* same terms as jsmin.c, which has the following license:
*
* --
* Copyright (c) 2002 Douglas Crockford (www.crockford.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* The Software shall be used for Good, not Evil.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* --
*
* @package JSMin
* @author Ryan Grove (PHP port)
* @author Steve Clay (modifications + cleanup)
* @author Andrea Giammarchi (spaceBeforeRegExp)
* @copyright 2002 Douglas Crockford (jsmin.c)
* @copyright 2008 Ryan Grove (PHP port)
* @license http://opensource.org/licenses/mit-license.php MIT License
* @link http://code.google.com/p/jsmin-php/
*/
class JSMin {
const ORD_LF = 10;
const ORD_SPACE = 32;
const ACTION_KEEP_A = 1;
const ACTION_DELETE_A = 2;
const ACTION_DELETE_A_B = 3;
protected $a = "\n";
protected $b = '';
protected $input = '';
protected $inputIndex = 0;
protected $inputLength = 0;
protected $lookAhead = null;
protected $output = '';
protected $lastByteOut = '';
protected $keptComment = '';
/**
* Minify Javascript.
*
* @param string $js Javascript to be minified
*
* @return string
*/
public static function minify($js)
{
$jsmin = new JSMin($js);
return $jsmin->min();
}
/**
* @param string $input
*/
public function __construct($input)
{
$this->input = $input;
}
/**
* Perform minification, return result
*
* @return string
*/
public function min()
{
if ($this->output !== '') { // min already run
return $this->output;
}
$mbIntEnc = null;
if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
$mbIntEnc = mb_internal_encoding();
mb_internal_encoding('8bit');
}
$this->input = str_replace("\r\n", "\n", $this->input);
$this->inputLength = strlen($this->input);
$this->action(self::ACTION_DELETE_A_B);
while ($this->a !== null) {
// determine next command
$command = self::ACTION_KEEP_A; // default
if ($this->a === ' ') {
if (($this->lastByteOut === '+' || $this->lastByteOut === '-')
&& ($this->b === $this->lastByteOut)) {
// Don't delete this space. If we do, the addition/subtraction
// could be parsed as a post-increment
} elseif (! $this->isAlphaNum($this->b)) {
$command = self::ACTION_DELETE_A;
}
} elseif ($this->a === "\n") {
if ($this->b === ' ') {
$command = self::ACTION_DELETE_A_B;
// in case of mbstring.func_overload & 2, must check for null b,
// otherwise mb_strpos will give WARNING
} elseif ($this->b === null
|| (false === strpos('{[(+-!~', $this->b)
&& ! $this->isAlphaNum($this->b))) {
$command = self::ACTION_DELETE_A;
}
} elseif (! $this->isAlphaNum($this->a)) {
if ($this->b === ' '
|| ($this->b === "\n"
&& (false === strpos('}])+-"\'', $this->a)))) {
$command = self::ACTION_DELETE_A_B;
}
}
$this->action($command);
}
$this->output = trim($this->output);
if ($mbIntEnc !== null) {
mb_internal_encoding($mbIntEnc);
}
return $this->output;
}
/**
* ACTION_KEEP_A = Output A. Copy B to A. Get the next B.
* ACTION_DELETE_A = Copy B to A. Get the next B.
* ACTION_DELETE_A_B = Get the next B.
*
* @param int $command
* @throws JSMin_UnterminatedRegExpException|JSMin_UnterminatedStringException
*/
protected function action($command)
{
// make sure we don't compress "a + ++b" to "a+++b", etc.
if ($command === self::ACTION_DELETE_A_B
&& $this->b === ' '
&& ($this->a === '+' || $this->a === '-')) {
// Note: we're at an addition/substraction operator; the inputIndex
// will certainly be a valid index
if ($this->input[$this->inputIndex] === $this->a) {
// This is "+ +" or "- -". Don't delete the space.
$command = self::ACTION_KEEP_A;
}
}
switch ($command) {
case self::ACTION_KEEP_A: // 1
$this->output .= $this->a;
if ($this->keptComment) {
$this->output = rtrim($this->output, "\n");
$this->output .= $this->keptComment;
$this->keptComment = '';
}
$this->lastByteOut = $this->a;
// fallthrough intentional
case self::ACTION_DELETE_A: // 2
$this->a = $this->b;
if ($this->a === "'" || $this->a === '"') { // string literal
$str = $this->a; // in case needed for exception
for(;;) {
$this->output .= $this->a;
$this->lastByteOut = $this->a;
$this->a = $this->get();
if ($this->a === $this->b) { // end quote
break;
}
if ($this->isEOF($this->a)) {
$byte = $this->inputIndex - 1;
throw new JSMin_UnterminatedStringException(
"JSMin: Unterminated String at byte {$byte}: {$str}");
}
$str .= $this->a;
if ($this->a === '\\') {
$this->output .= $this->a;
$this->lastByteOut = $this->a;
$this->a = $this->get();
$str .= $this->a;
}
}
}
// fallthrough intentional
case self::ACTION_DELETE_A_B: // 3
$this->b = $this->next();
if ($this->b === '/' && $this->isRegexpLiteral()) {
$this->output .= $this->a . $this->b;
$pattern = '/'; // keep entire pattern in case we need to report it in the exception
for(;;) {
$this->a = $this->get();
$pattern .= $this->a;
if ($this->a === '[') {
for(;;) {
$this->output .= $this->a;
$this->a = $this->get();
$pattern .= $this->a;
if ($this->a === ']') {
break;
}
if ($this->a === '\\') {
$this->output .= $this->a;
$this->a = $this->get();
$pattern .= $this->a;
}
if ($this->isEOF($this->a)) {
throw new JSMin_UnterminatedRegExpException(
"JSMin: Unterminated set in RegExp at byte "
. $this->inputIndex .": {$pattern}");
}
}
}
if ($this->a === '/') { // end pattern
break; // while (true)
} elseif ($this->a === '\\') {
$this->output .= $this->a;
$this->a = $this->get();
$pattern .= $this->a;
} elseif ($this->isEOF($this->a)) {
$byte = $this->inputIndex - 1;
throw new JSMin_UnterminatedRegExpException(
"JSMin: Unterminated RegExp at byte {$byte}: {$pattern}");
}
$this->output .= $this->a;
$this->lastByteOut = $this->a;
}
$this->b = $this->next();
}
// end case ACTION_DELETE_A_B
}
}
/**
* @return bool
*/
protected function isRegexpLiteral()
{
if (false !== strpos("(,=:[!&|?+-~*{;", $this->a)) {
// we obviously aren't dividing
return true;
}
// we have to check for a preceding keyword, and we don't need to pattern
// match over the whole output.
$recentOutput = substr($this->output, -10);
// check if return/typeof directly precede a pattern without a space
foreach (array('return', 'typeof') as $keyword) {
if ($this->a !== substr($keyword, -1)) {
// certainly wasn't keyword
continue;
}
if (preg_match("~(^|[\\s\\S])" . substr($keyword, 0, -1) . "$~", $recentOutput, $m)) {
if ($m[1] === '' || !$this->isAlphaNum($m[1])) {
return true;
}
}
}
// check all keywords
if ($this->a === ' ' || $this->a === "\n") {
if (preg_match('~(^|[\\s\\S])(?:case|else|in|return|typeof)$~', $recentOutput, $m)) {
if ($m[1] === '' || !$this->isAlphaNum($m[1])) {
return true;
}
}
}
return false;
}
/**
* Return the next character from stdin. Watch out for lookahead. If the character is a control character,
* translate it to a space or linefeed.
*
* @return string
*/
protected function get()
{
$c = $this->lookAhead;
$this->lookAhead = null;
if ($c === null) {
// getc(stdin)
if ($this->inputIndex < $this->inputLength) {
$c = $this->input[$this->inputIndex];
$this->inputIndex += 1;
} else {
$c = null;
}
}
if (ord($c) >= self::ORD_SPACE || $c === "\n" || $c === null) {
return $c;
}
if ($c === "\r") {
return "\n";
}
return ' ';
}
/**
* Does $a indicate end of input?
*
* @param string $a
* @return bool
*/
protected function isEOF($a)
{
return ord($a) <= self::ORD_LF;
}
/**
* Get next char (without getting it). If is ctrl character, translate to a space or newline.
*
* @return string
*/
protected function peek()
{
$this->lookAhead = $this->get();
return $this->lookAhead;
}
/**
* Return true if the character is a letter, digit, underscore, dollar sign, or non-ASCII character.
*
* @param string $c
*
* @return bool
*/
protected function isAlphaNum($c)
{
return (preg_match('/^[a-z0-9A-Z_\\$\\\\]$/', $c) || ord($c) > 126);
}
/**
* Consume a single line comment from input (possibly retaining it)
*/
protected function consumeSingleLineComment()
{
$comment = '';
while (true) {
$get = $this->get();
$comment .= $get;
if (ord($get) <= self::ORD_LF) { // end of line reached
// if IE conditional comment
if (preg_match('/^\\/@(?:cc_on|if|elif|else|end)\\b/', $comment)) {
$this->keptComment .= "/{$comment}";
}
return;
}
}
}
/**
* Consume a multiple line comment from input (possibly retaining it)
*
* @throws JSMin_UnterminatedCommentException
*/
protected function consumeMultipleLineComment()
{
$this->get();
$comment = '';
for(;;) {
$get = $this->get();
if ($get === '*') {
if ($this->peek() === '/') { // end of comment reached
$this->get();
if (0 === strpos($comment, '!')) {
// preserved by YUI Compressor
if (!$this->keptComment) {
// don't prepend a newline if two comments right after one another
$this->keptComment = "\n";
}
$this->keptComment .= "/*!" . substr($comment, 1) . "*/\n";
} else if (preg_match('/^@(?:cc_on|if|elif|else|end)\\b/', $comment)) {
// IE conditional
$this->keptComment .= "/*{$comment}*/";
}
return;
}
} elseif ($get === null) {
throw new JSMin_UnterminatedCommentException(
"JSMin: Unterminated comment at byte {$this->inputIndex}: /*{$comment}");
}
$comment .= $get;
}
}
/**
* Get the next character, skipping over comments. Some comments may be preserved.
*
* @return string
*/
protected function next()
{
$get = $this->get();
if ($get === '/') {
switch ($this->peek()) {
case '/':
$this->consumeSingleLineComment();
$get = "\n";
break;
case '*':
$this->consumeMultipleLineComment();
$get = ' ';
break;
}
}
return $get;
}
}
class JSMin_UnterminatedStringException extends Exception {}
class JSMin_UnterminatedCommentException extends Exception {}
class JSMin_UnterminatedRegExpException extends Exception {}
PK ^GM.Kf f min/lib/FirePHP.phpnu W+A
* @license http://www.opensource.org/licenses/bsd-license.php
* @package FirePHP
*/
/**
* Sends the given data to the FirePHP Firefox Extension.
* The data can be displayed in the Firebug Console or in the
* "Server" request tab.
*
* For more information see: http://www.firephp.org/
*
* @copyright Copyright (C) 2007-2008 Christoph Dorn
* @author Christoph Dorn
* @license http://www.opensource.org/licenses/bsd-license.php
* @package FirePHP
*/
class FirePHP {
/**
* FirePHP version
*
* @var string
*/
const VERSION = '0.2.0';
/**
* Firebug LOG level
*
* Logs a message to firebug console.
*
* @var string
*/
const LOG = 'LOG';
/**
* Firebug INFO level
*
* Logs a message to firebug console and displays an info icon before the message.
*
* @var string
*/
const INFO = 'INFO';
/**
* Firebug WARN level
*
* Logs a message to firebug console, displays an warning icon before the message and colors the line turquoise.
*
* @var string
*/
const WARN = 'WARN';
/**
* Firebug ERROR level
*
* Logs a message to firebug console, displays an error icon before the message and colors the line yellow. Also increments the firebug error count.
*
* @var string
*/
const ERROR = 'ERROR';
/**
* Dumps a variable to firebug's server panel
*
* @var string
*/
const DUMP = 'DUMP';
/**
* Displays a stack trace in firebug console
*
* @var string
*/
const TRACE = 'TRACE';
/**
* Displays an exception in firebug console
*
* Increments the firebug error count.
*
* @var string
*/
const EXCEPTION = 'EXCEPTION';
/**
* Displays an table in firebug console
*
* @var string
*/
const TABLE = 'TABLE';
/**
* Starts a group in firebug console
*
* @var string
*/
const GROUP_START = 'GROUP_START';
/**
* Ends a group in firebug console
*
* @var string
*/
const GROUP_END = 'GROUP_END';
/**
* Singleton instance of FirePHP
*
* @var FirePHP
*/
protected static $instance = null;
/**
* Wildfire protocol message index
*
* @var int
*/
protected $messageIndex = 1;
/**
* Options for the library
*
* @var array
*/
protected $options = array();
/**
* Filters used to exclude object members when encoding
*
* @var array
*/
protected $objectFilters = array();
/**
* A stack of objects used to detect recursion during object encoding
*
* @var object
*/
protected $objectStack = array();
/**
* Flag to enable/disable logging
*
* @var boolean
*/
protected $enabled = true;
/**
* The object constructor
*/
function __construct() {
$this->options['maxObjectDepth'] = 10;
$this->options['maxArrayDepth'] = 20;
$this->options['useNativeJsonEncode'] = true;
$this->options['includeLineNumbers'] = true;
}
/**
* When the object gets serialized only include specific object members.
*
* @return array
*/
public function __sleep() {
return array('options','objectFilters','enabled');
}
/**
* Gets singleton instance of FirePHP
*
* @param boolean $AutoCreate
* @return FirePHP
*/
public static function getInstance($AutoCreate=false) {
if($AutoCreate===true && !self::$instance) {
self::init();
}
return self::$instance;
}
/**
* Creates FirePHP object and stores it for singleton access
*
* @return FirePHP
*/
public static function init() {
return self::$instance = new self();
}
/**
* Enable and disable logging to Firebug
*
* @param boolean $Enabled TRUE to enable, FALSE to disable
* @return void
*/
public function setEnabled($Enabled) {
$this->enabled = $Enabled;
}
/**
* Check if logging is enabled
*
* @return boolean TRUE if enabled
*/
public function getEnabled() {
return $this->enabled;
}
/**
* Specify a filter to be used when encoding an object
*
* Filters are used to exclude object members.
*
* @param string $Class The class name of the object
* @param array $Filter An array or members to exclude
* @return void
*/
public function setObjectFilter($Class, $Filter) {
$this->objectFilters[$Class] = $Filter;
}
/**
* Set some options for the library
*
* Options:
* - maxObjectDepth: The maximum depth to traverse objects (default: 10)
* - maxArrayDepth: The maximum depth to traverse arrays (default: 20)
* - useNativeJsonEncode: If true will use json_encode() (default: true)
* - includeLineNumbers: If true will include line numbers and filenames (default: true)
*
* @param array $Options The options to be set
* @return void
*/
public function setOptions($Options) {
$this->options = array_merge($this->options,$Options);
}
/**
* Register FirePHP as your error handler
*
* Will throw exceptions for each php error.
*/
public function registerErrorHandler()
{
//NOTE: The following errors will not be caught by this error handler:
// E_ERROR, E_PARSE, E_CORE_ERROR,
// E_CORE_WARNING, E_COMPILE_ERROR,
// E_COMPILE_WARNING, E_STRICT
set_error_handler(array($this,'errorHandler'));
}
/**
* FirePHP's error handler
*
* Throws exception for each php error that will occur.
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param array $errcontext
*/
public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext)
{
// Don't throw exception if error reporting is switched off
if (error_reporting() == 0) {
return;
}
// Only throw exceptions for errors we are asking for
if (error_reporting() & $errno) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
}
/**
* Register FirePHP as your exception handler
*/
public function registerExceptionHandler()
{
set_exception_handler(array($this,'exceptionHandler'));
}
/**
* FirePHP's exception handler
*
* Logs all exceptions to your firebug console and then stops the script.
*
* @param Exception $Exception
* @throws Exception
*/
function exceptionHandler($Exception) {
$this->fb($Exception);
}
/**
* Set custom processor url for FirePHP
*
* @param string $URL
*/
public function setProcessorUrl($URL)
{
$this->setHeader('X-FirePHP-ProcessorURL', $URL);
}
/**
* Set custom renderer url for FirePHP
*
* @param string $URL
*/
public function setRendererUrl($URL)
{
$this->setHeader('X-FirePHP-RendererURL', $URL);
}
/**
* Start a group for following messages
*
* @param string $Name
* @return true
* @throws Exception
*/
public function group($Name) {
return $this->fb(null, $Name, FirePHP::GROUP_START);
}
/**
* Ends a group you have started before
*
* @return true
* @throws Exception
*/
public function groupEnd() {
return $this->fb(null, null, FirePHP::GROUP_END);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::LOG
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public function log($Object, $Label=null) {
return $this->fb($Object, $Label, FirePHP::LOG);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::INFO
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public function info($Object, $Label=null) {
return $this->fb($Object, $Label, FirePHP::INFO);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::WARN
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public function warn($Object, $Label=null) {
return $this->fb($Object, $Label, FirePHP::WARN);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::ERROR
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public function error($Object, $Label=null) {
return $this->fb($Object, $Label, FirePHP::ERROR);
}
/**
* Dumps key and variable to firebug server panel
*
* @see FirePHP::DUMP
* @param string $Key
* @param mixed $Variable
* @return true
* @throws Exception
*/
public function dump($Key, $Variable) {
return $this->fb($Variable, $Key, FirePHP::DUMP);
}
/**
* Log a trace in the firebug console
*
* @see FirePHP::TRACE
* @param string $Label
* @return true
* @throws Exception
*/
public function trace($Label) {
return $this->fb($Label, FirePHP::TRACE);
}
/**
* Log a table in the firebug console
*
* @see FirePHP::TABLE
* @param string $Label
* @param string $Table
* @return true
* @throws Exception
*/
public function table($Label, $Table) {
return $this->fb($Table, $Label, FirePHP::TABLE);
}
/**
* Check if FirePHP is installed on client
*
* @return boolean
*/
public function detectClientExtension() {
/* Check if FirePHP is installed on client */
if(!@preg_match_all('/\sFirePHP\/([\.|\d]*)\s?/si',$this->getUserAgent(),$m) ||
!version_compare($m[1][0],'0.0.6','>=')) {
return false;
}
return true;
}
/**
* Log varible to Firebug
*
* @see http://www.firephp.org/Wiki/Reference/Fb
* @param mixed $Object The variable to be logged
* @return true Return TRUE if message was added to headers, FALSE otherwise
* @throws Exception
*/
public function fb($Object) {
if(!$this->enabled) {
return false;
}
if (headers_sent($filename, $linenum)) {
throw $this->newException('Headers already sent in '.$filename.' on line '.$linenum.'. Cannot send log data to FirePHP. You must have Output Buffering enabled via ob_start() or output_buffering ini directive.');
}
$Type = null;
$Label = null;
if(func_num_args()==1) {
} else
if(func_num_args()==2) {
switch(func_get_arg(1)) {
case self::LOG:
case self::INFO:
case self::WARN:
case self::ERROR:
case self::DUMP:
case self::TRACE:
case self::EXCEPTION:
case self::TABLE:
case self::GROUP_START:
case self::GROUP_END:
$Type = func_get_arg(1);
break;
default:
$Label = func_get_arg(1);
break;
}
} else
if(func_num_args()==3) {
$Type = func_get_arg(2);
$Label = func_get_arg(1);
} else {
throw $this->newException('Wrong number of arguments to fb() function!');
}
if(!$this->detectClientExtension()) {
return false;
}
$meta = array();
$skipFinalObjectEncode = false;
if($Object instanceof Exception) {
$meta['file'] = $this->_escapeTraceFile($Object->getFile());
$meta['line'] = $Object->getLine();
$trace = $Object->getTrace();
if($Object instanceof ErrorException
&& isset($trace[0]['function'])
&& $trace[0]['function']=='errorHandler'
&& isset($trace[0]['class'])
&& $trace[0]['class']=='FirePHP') {
$severity = false;
switch($Object->getSeverity()) {
case E_WARNING: $severity = 'E_WARNING'; break;
case E_NOTICE: $severity = 'E_NOTICE'; break;
case E_USER_ERROR: $severity = 'E_USER_ERROR'; break;
case E_USER_WARNING: $severity = 'E_USER_WARNING'; break;
case E_USER_NOTICE: $severity = 'E_USER_NOTICE'; break;
case E_STRICT: $severity = 'E_STRICT'; break;
case E_RECOVERABLE_ERROR: $severity = 'E_RECOVERABLE_ERROR'; break;
case E_DEPRECATED: $severity = 'E_DEPRECATED'; break;
case E_USER_DEPRECATED: $severity = 'E_USER_DEPRECATED'; break;
}
$Object = array('Class'=>get_class($Object),
'Message'=>$severity.': '.$Object->getMessage(),
'File'=>$this->_escapeTraceFile($Object->getFile()),
'Line'=>$Object->getLine(),
'Type'=>'trigger',
'Trace'=>$this->_escapeTrace(array_splice($trace,2)));
$skipFinalObjectEncode = true;
} else {
$Object = array('Class'=>get_class($Object),
'Message'=>$Object->getMessage(),
'File'=>$this->_escapeTraceFile($Object->getFile()),
'Line'=>$Object->getLine(),
'Type'=>'throw',
'Trace'=>$this->_escapeTrace($trace));
$skipFinalObjectEncode = true;
}
$Type = self::EXCEPTION;
} else
if($Type==self::TRACE) {
$trace = debug_backtrace();
if(!$trace) return false;
for( $i=0 ; $i_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php'
|| substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) {
/* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */
} else
if(isset($trace[$i]['class'])
&& isset($trace[$i+1]['file'])
&& $trace[$i]['class']=='FirePHP'
&& substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') {
/* Skip fb() */
} else
if($trace[$i]['function']=='fb'
|| $trace[$i]['function']=='trace'
|| $trace[$i]['function']=='send') {
$Object = array('Class'=>isset($trace[$i]['class'])?$trace[$i]['class']:'',
'Type'=>isset($trace[$i]['type'])?$trace[$i]['type']:'',
'Function'=>isset($trace[$i]['function'])?$trace[$i]['function']:'',
'Message'=>$trace[$i]['args'][0],
'File'=>isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'',
'Line'=>isset($trace[$i]['line'])?$trace[$i]['line']:'',
'Args'=>isset($trace[$i]['args'])?$this->encodeObject($trace[$i]['args']):'',
'Trace'=>$this->_escapeTrace(array_splice($trace,$i+1)));
$skipFinalObjectEncode = true;
$meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'';
$meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:'';
break;
}
}
} else
if($Type==self::TABLE) {
if(isset($Object[0]) && is_string($Object[0])) {
$Object[1] = $this->encodeTable($Object[1]);
} else {
$Object = $this->encodeTable($Object);
}
$skipFinalObjectEncode = true;
} else {
if($Type===null) {
$Type = self::LOG;
}
}
if($this->options['includeLineNumbers']) {
if(!isset($meta['file']) || !isset($meta['line'])) {
$trace = debug_backtrace();
for( $i=0 ; $trace && $i_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php'
|| substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) {
/* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */
} else
if(isset($trace[$i]['class'])
&& isset($trace[$i+1]['file'])
&& $trace[$i]['class']=='FirePHP'
&& substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') {
/* Skip fb() */
} else
if(isset($trace[$i]['file'])
&& substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php') {
/* Skip FB::fb() */
} else {
$meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'';
$meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:'';
break;
}
}
}
} else {
unset($meta['file']);
unset($meta['line']);
}
$this->setHeader('X-Wf-Protocol-1','http://meta.wildfirehq.org/Protocol/JsonStream/0.2');
$this->setHeader('X-Wf-1-Plugin-1','http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/'.self::VERSION);
$structure_index = 1;
if($Type==self::DUMP) {
$structure_index = 2;
$this->setHeader('X-Wf-1-Structure-2','http://meta.firephp.org/Wildfire/Structure/FirePHP/Dump/0.1');
} else {
$this->setHeader('X-Wf-1-Structure-1','http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1');
}
if($Type==self::DUMP) {
$msg = '{"'.$Label.'":'.$this->jsonEncode($Object, $skipFinalObjectEncode).'}';
} else {
$msg_meta = array('Type'=>$Type);
if($Label!==null) {
$msg_meta['Label'] = $Label;
}
if(isset($meta['file'])) {
$msg_meta['File'] = $meta['file'];
}
if(isset($meta['line'])) {
$msg_meta['Line'] = $meta['line'];
}
$msg = '['.$this->jsonEncode($msg_meta).','.$this->jsonEncode($Object, $skipFinalObjectEncode).']';
}
$parts = explode("\n",chunk_split($msg, 5000, "\n"));
for( $i=0 ; $i2) {
// Message needs to be split into multiple parts
$this->setHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex,
(($i==0)?strlen($msg):'')
. '|' . $part . '|'
. (($isetHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex,
strlen($part) . '|' . $part . '|');
}
$this->messageIndex++;
if ($this->messageIndex > 99999) {
throw new Exception('Maximum number (99,999) of messages reached!');
}
}
}
$this->setHeader('X-Wf-1-Index',$this->messageIndex-1);
return true;
}
/**
* Standardizes path for windows systems.
*
* @param string $Path
* @return string
*/
protected function _standardizePath($Path) {
return preg_replace('/\\\\+/','/',$Path);
}
/**
* Escape trace path for windows systems
*
* @param array $Trace
* @return array
*/
protected function _escapeTrace($Trace) {
if(!$Trace) return $Trace;
for( $i=0 ; $i_escapeTraceFile($Trace[$i]['file']);
}
if(isset($Trace[$i]['args'])) {
$Trace[$i]['args'] = $this->encodeObject($Trace[$i]['args']);
}
}
return $Trace;
}
/**
* Escape file information of trace for windows systems
*
* @param string $File
* @return string
*/
protected function _escapeTraceFile($File) {
/* Check if we have a windows filepath */
if(strpos($File,'\\')) {
/* First strip down to single \ */
$file = preg_replace('/\\\\+/','\\',$File);
return $file;
}
return $File;
}
/**
* Send header
*
* @param string $Name
* @param string_type $Value
*/
protected function setHeader($Name, $Value) {
return header($Name.': '.$Value);
}
/**
* Get user agent
*
* @return string|false
*/
protected function getUserAgent() {
if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
return $_SERVER['HTTP_USER_AGENT'];
}
/**
* Returns a new exception
*
* @param string $Message
* @return Exception
*/
protected function newException($Message) {
return new Exception($Message);
}
/**
* Encode an object into a JSON string
*
* Uses PHP's jeson_encode() if available
*
* @param object $Object The object to be encoded
* @return string The JSON string
*/
protected function jsonEncode($Object, $skipObjectEncode=false)
{
if(!$skipObjectEncode) {
$Object = $this->encodeObject($Object);
}
if(function_exists('json_encode')
&& $this->options['useNativeJsonEncode']!=false) {
return json_encode($Object);
} else {
return $this->json_encode($Object);
}
}
/**
* Encodes a table by encoding each row and column with encodeObject()
*
* @param array $Table The table to be encoded
* @return array
*/
protected function encodeTable($Table) {
if(!$Table) return $Table;
for( $i=0 ; $iencodeObject($Table[$i][$j]);
}
}
}
return $Table;
}
/**
* Encodes an object including members with
* protected and private visibility
*
* @param Object $Object The object to be encoded
* @param int $Depth The current traversal depth
* @return array All members of the object
*/
protected function encodeObject($Object, $ObjectDepth = 1, $ArrayDepth = 1)
{
$return = array();
if (is_object($Object)) {
if ($ObjectDepth > $this->options['maxObjectDepth']) {
return '** Max Object Depth ('.$this->options['maxObjectDepth'].') **';
}
foreach ($this->objectStack as $refVal) {
if ($refVal === $Object) {
return '** Recursion ('.get_class($Object).') **';
}
}
array_push($this->objectStack, $Object);
$return['__className'] = $class = get_class($Object);
$reflectionClass = new ReflectionClass($class);
$properties = array();
foreach( $reflectionClass->getProperties() as $property) {
$properties[$property->getName()] = $property;
}
$members = (array)$Object;
foreach( $properties as $raw_name => $property ) {
$name = $raw_name;
if($property->isStatic()) {
$name = 'static:'.$name;
}
if($property->isPublic()) {
$name = 'public:'.$name;
} else
if($property->isPrivate()) {
$name = 'private:'.$name;
$raw_name = "\0".$class."\0".$raw_name;
} else
if($property->isProtected()) {
$name = 'protected:'.$name;
$raw_name = "\0".'*'."\0".$raw_name;
}
if(!(isset($this->objectFilters[$class])
&& is_array($this->objectFilters[$class])
&& in_array($raw_name,$this->objectFilters[$class]))) {
if(array_key_exists($raw_name,$members)
&& !$property->isStatic()) {
$return[$name] = $this->encodeObject($members[$raw_name], $ObjectDepth + 1, 1);
} else {
if(method_exists($property,'setAccessible')) {
$property->setAccessible(true);
$return[$name] = $this->encodeObject($property->getValue($Object), $ObjectDepth + 1, 1);
} else
if($property->isPublic()) {
$return[$name] = $this->encodeObject($property->getValue($Object), $ObjectDepth + 1, 1);
} else {
$return[$name] = '** Need PHP 5.3 to get value **';
}
}
} else {
$return[$name] = '** Excluded by Filter **';
}
}
// Include all members that are not defined in the class
// but exist in the object
foreach( $members as $raw_name => $value ) {
$name = $raw_name;
if ($name{0} == "\0") {
$parts = explode("\0", $name);
$name = $parts[2];
}
if(!isset($properties[$name])) {
$name = 'undeclared:'.$name;
if(!(isset($this->objectFilters[$class])
&& is_array($this->objectFilters[$class])
&& in_array($raw_name,$this->objectFilters[$class]))) {
$return[$name] = $this->encodeObject($value, $ObjectDepth + 1, 1);
} else {
$return[$name] = '** Excluded by Filter **';
}
}
}
array_pop($this->objectStack);
} elseif (is_array($Object)) {
if ($ArrayDepth > $this->options['maxArrayDepth']) {
return '** Max Array Depth ('.$this->options['maxArrayDepth'].') **';
}
foreach ($Object as $key => $val) {
// Encoding the $GLOBALS PHP array causes an infinite loop
// if the recursion is not reset here as it contains
// a reference to itself. This is the only way I have come up
// with to stop infinite recursion in this case.
if($key=='GLOBALS'
&& is_array($val)
&& array_key_exists('GLOBALS',$val)) {
$val['GLOBALS'] = '** Recursion (GLOBALS) **';
}
$return[$key] = $this->encodeObject($val, 1, $ArrayDepth + 1);
}
} else {
if(self::is_utf8($Object)) {
return $Object;
} else {
return utf8_encode($Object);
}
}
return $return;
}
/**
* Returns true if $string is valid UTF-8 and false otherwise.
*
* @param mixed $str String to be tested
* @return boolean
*/
protected static function is_utf8($str) {
$c=0; $b=0;
$bits=0;
$len=strlen($str);
for($i=0; $i<$len; $i++){
$c=ord($str[$i]);
if($c > 128){
if(($c >= 254)) return false;
elseif($c >= 252) $bits=6;
elseif($c >= 248) $bits=5;
elseif($c >= 240) $bits=4;
elseif($c >= 224) $bits=3;
elseif($c >= 192) $bits=2;
else return false;
if(($i+$bits) > $len) return false;
while($bits > 1){
$i++;
$b=ord($str[$i]);
if($b < 128 || $b > 191) return false;
$bits--;
}
}
}
return true;
}
/**
* Converts to and from JSON format.
*
* JSON (JavaScript Object Notation) is a lightweight data-interchange
* format. It is easy for humans to read and write. It is easy for machines
* to parse and generate. It is based on a subset of the JavaScript
* Programming Language, Standard ECMA-262 3rd Edition - December 1999.
* This feature can also be found in Python. JSON is a text format that is
* completely language independent but uses conventions that are familiar
* to programmers of the C-family of languages, including C, C++, C#, Java,
* JavaScript, Perl, TCL, and many others. These properties make JSON an
* ideal data-interchange language.
*
* This package provides a simple encoder and decoder for JSON notation. It
* is intended for use with client-side Javascript applications that make
* use of HTTPRequest to perform server communication functions - data can
* be encoded into JSON notation for use in a client-side javascript, or
* decoded from incoming Javascript requests. JSON format is native to
* Javascript, and can be directly eval()'ed with no further parsing
* overhead
*
* All strings should be in ASCII or UTF-8 format!
*
* LICENSE: Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met: Redistributions of source code must retain the
* above copyright notice, this list of conditions and the following
* disclaimer. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* @category
* @package Services_JSON
* @author Michal Migurski
* @author Matt Knapp
* @author Brett Stimmerman
* @author Christoph Dorn
* @copyright 2005 Michal Migurski
* @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
* @license http://www.opensource.org/licenses/bsd-license.php
* @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
*/
/**
* Keep a list of objects as we descend into the array so we can detect recursion.
*/
private $json_objectStack = array();
/**
* convert a string from one UTF-8 char to one UTF-16 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf8 UTF-8 character
* @return string UTF-16 character
* @access private
*/
private function json_utf82utf16($utf8)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
}
switch(strlen($utf8)) {
case 1:
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return $utf8;
case 2:
// return a UTF-16 character from a 2-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x07 & (ord($utf8{0}) >> 2))
. chr((0xC0 & (ord($utf8{0}) << 6))
| (0x3F & ord($utf8{1})));
case 3:
// return a UTF-16 character from a 3-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr((0xF0 & (ord($utf8{0}) << 4))
| (0x0F & (ord($utf8{1}) >> 2)))
. chr((0xC0 & (ord($utf8{1}) << 6))
| (0x7F & ord($utf8{2})));
}
// ignoring UTF-32 for now, sorry
return '';
}
/**
* encodes an arbitrary variable into JSON format
*
* @param mixed $var any number, boolean, string, array, or object to be encoded.
* see argument 1 to Services_JSON() above for array-parsing behavior.
* if var is a strng, note that encode() always expects it
* to be in ASCII or UTF-8 format!
*
* @return mixed JSON string representation of input var or an error if a problem occurs
* @access public
*/
private function json_encode($var)
{
if(is_object($var)) {
if(in_array($var,$this->json_objectStack)) {
return '"** Recursion **"';
}
}
switch (gettype($var)) {
case 'boolean':
return $var ? 'true' : 'false';
case 'NULL':
return 'null';
case 'integer':
return (int) $var;
case 'double':
case 'float':
return (float) $var;
case 'string':
// STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
$ascii = '';
$strlen_var = strlen($var);
/*
* Iterate over every character in the string,
* escaping with a slash or encoding to UTF-8 where necessary
*/
for ($c = 0; $c < $strlen_var; ++$c) {
$ord_var_c = ord($var{$c});
switch (true) {
case $ord_var_c == 0x08:
$ascii .= '\b';
break;
case $ord_var_c == 0x09:
$ascii .= '\t';
break;
case $ord_var_c == 0x0A:
$ascii .= '\n';
break;
case $ord_var_c == 0x0C:
$ascii .= '\f';
break;
case $ord_var_c == 0x0D:
$ascii .= '\r';
break;
case $ord_var_c == 0x22:
case $ord_var_c == 0x2F:
case $ord_var_c == 0x5C:
// double quote, slash, slosh
$ascii .= '\\'.$var{$c};
break;
case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
// characters U-00000000 - U-0000007F (same as ASCII)
$ascii .= $var{$c};
break;
case (($ord_var_c & 0xE0) == 0xC0):
// characters U-00000080 - U-000007FF, mask 110XXXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c, ord($var{$c + 1}));
$c += 1;
$utf16 = $this->json_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF0) == 0xE0):
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}));
$c += 2;
$utf16 = $this->json_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF8) == 0xF0):
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}));
$c += 3;
$utf16 = $this->json_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFC) == 0xF8):
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}));
$c += 4;
$utf16 = $this->json_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFE) == 0xFC):
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}),
ord($var{$c + 5}));
$c += 5;
$utf16 = $this->json_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
}
}
return '"'.$ascii.'"';
case 'array':
/*
* As per JSON spec if any array key is not an integer
* we must treat the the whole array as an object. We
* also try to catch a sparsely populated associative
* array with numeric keys here because some JS engines
* will create an array with empty indexes up to
* max_index which can cause memory issues and because
* the keys, which may be relevant, will be remapped
* otherwise.
*
* As per the ECMA and JSON specification an object may
* have any string as a property. Unfortunately due to
* a hole in the ECMA specification if the key is a
* ECMA reserved word or starts with a digit the
* parameter is only accessible using ECMAScript's
* bracket notation.
*/
// treat as a JSON object
if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
$this->json_objectStack[] = $var;
$properties = array_map(array($this, 'json_name_value'),
array_keys($var),
array_values($var));
array_pop($this->json_objectStack);
foreach($properties as $property) {
if($property instanceof Exception) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
}
$this->json_objectStack[] = $var;
// treat it like a regular array
$elements = array_map(array($this, 'json_encode'), $var);
array_pop($this->json_objectStack);
foreach($elements as $element) {
if($element instanceof Exception) {
return $element;
}
}
return '[' . join(',', $elements) . ']';
case 'object':
$vars = self::encodeObject($var);
$this->json_objectStack[] = $var;
$properties = array_map(array($this, 'json_name_value'),
array_keys($vars),
array_values($vars));
array_pop($this->json_objectStack);
foreach($properties as $property) {
if($property instanceof Exception) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
default:
return null;
}
}
/**
* array-walking function for use in generating JSON-formatted name-value pairs
*
* @param string $name name of key to use
* @param mixed $value reference to an array element to be encoded
*
* @return string JSON-formatted name-value pair, like '"name":value'
* @access private
*/
private function json_name_value($name, $value)
{
// Encoding the $GLOBALS PHP array causes an infinite loop
// if the recursion is not reset here as it contains
// a reference to itself. This is the only way I have come up
// with to stop infinite recursion in this case.
if($name=='GLOBALS'
&& is_array($value)
&& array_key_exists('GLOBALS',$value)) {
$value['GLOBALS'] = '** Recursion **';
}
$encoded_value = $this->json_encode($value);
if($encoded_value instanceof Exception) {
return $encoded_value;
}
return $this->json_encode(strval($name)) . ':' . $encoded_value;
}
}
PK ^GM\d- - min/lib/MrClay/Cli.phpnu W+A values.
*
* You may also specify that some arguments be used to provide input/output. By communicating
* solely through the file pointers provided by openInput()/openOutput(), you can make your
* app more flexible to end users.
*
* @author Steve Clay
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
class Cli {
/**
* @var array validation errors
*/
public $errors = array();
/**
* @var array option values available after validation.
*
* E.g. array(
* 'a' => false // option was missing
* ,'b' => true // option was present
* ,'c' => "Hello" // option had value
* ,'f' => "/home/user/file" // file path from root
* ,'f.raw' => "~/file" // file path as given to option
* )
*/
public $values = array();
/**
* @var array
*/
public $moreArgs = array();
/**
* @var array
*/
public $debug = array();
/**
* @var bool The user wants help info
*/
public $isHelpRequest = false;
/**
* @var Arg[]
*/
protected $_args = array();
/**
* @var resource
*/
protected $_stdin = null;
/**
* @var resource
*/
protected $_stdout = null;
/**
* @param bool $exitIfNoStdin (default true) Exit() if STDIN is not defined
*/
public function __construct($exitIfNoStdin = true)
{
if ($exitIfNoStdin && ! defined('STDIN')) {
exit('This script is for command-line use only.');
}
if (isset($GLOBALS['argv'][1])
&& ($GLOBALS['argv'][1] === '-?' || $GLOBALS['argv'][1] === '--help')) {
$this->isHelpRequest = true;
}
}
/**
* @param Arg|string $letter
* @return Arg
*/
public function addOptionalArg($letter)
{
return $this->addArgument($letter, false);
}
/**
* @param Arg|string $letter
* @return Arg
*/
public function addRequiredArg($letter)
{
return $this->addArgument($letter, true);
}
/**
* @param string $letter
* @param bool $required
* @param Arg|null $arg
* @return Arg
* @throws InvalidArgumentException
*/
public function addArgument($letter, $required, Arg $arg = null)
{
if (! preg_match('/^[a-zA-Z]$/', $letter)) {
throw new InvalidArgumentException('$letter must be in [a-zA-Z]');
}
if (! $arg) {
$arg = new Arg($required);
}
$this->_args[$letter] = $arg;
return $arg;
}
/**
* @param string $letter
* @return Arg|null
*/
public function getArgument($letter)
{
return isset($this->_args[$letter]) ? $this->_args[$letter] : null;
}
/*
* Read and validate options
*
* @return bool true if all options are valid
*/
public function validate()
{
$options = '';
$this->errors = array();
$this->values = array();
$this->_stdin = null;
if ($this->isHelpRequest) {
return false;
}
$lettersUsed = '';
foreach ($this->_args as $letter => $arg) {
/* @var Arg $arg */
$options .= $letter;
$lettersUsed .= $letter;
if ($arg->mayHaveValue || $arg->mustHaveValue) {
$options .= ($arg->mustHaveValue ? ':' : '::');
}
}
$this->debug['argv'] = $GLOBALS['argv'];
$argvCopy = array_slice($GLOBALS['argv'], 1);
$o = getopt($options);
$this->debug['getopt_options'] = $options;
$this->debug['getopt_return'] = $o;
foreach ($this->_args as $letter => $arg) {
/* @var Arg $arg */
$this->values[$letter] = false;
if (isset($o[$letter])) {
if (is_bool($o[$letter])) {
// remove from argv copy
$k = array_search("-$letter", $argvCopy);
if ($k !== false) {
array_splice($argvCopy, $k, 1);
}
if ($arg->mustHaveValue) {
$this->addError($letter, "Missing value");
} else {
$this->values[$letter] = true;
}
} else {
// string
$this->values[$letter] = $o[$letter];
$v =& $this->values[$letter];
// remove from argv copy
// first look for -ovalue or -o=value
$pattern = "/^-{$letter}=?" . preg_quote($v, '/') . "$/";
$foundInArgv = false;
foreach ($argvCopy as $k => $argV) {
if (preg_match($pattern, $argV)) {
array_splice($argvCopy, $k, 1);
$foundInArgv = true;
break;
}
}
if (! $foundInArgv) {
// space separated
$k = array_search("-$letter", $argvCopy);
if ($k !== false) {
array_splice($argvCopy, $k, 2);
}
}
// check that value isn't really another option
if (strlen($lettersUsed) > 1) {
$pattern = "/^-[" . str_replace($letter, '', $lettersUsed) . "]/i";
if (preg_match($pattern, $v)) {
$this->addError($letter, "Value was read as another option: %s", $v);
return false;
}
}
if ($arg->assertFile || $arg->assertDir) {
if ($v[0] !== '/' && $v[0] !== '~') {
$this->values["$letter.raw"] = $v;
$v = getcwd() . "/$v";
}
}
if ($arg->assertFile) {
if ($arg->useAsInfile) {
$this->_stdin = $v;
} elseif ($arg->useAsOutfile) {
$this->_stdout = $v;
}
if ($arg->assertReadable && ! is_readable($v)) {
$this->addError($letter, "File not readable: %s", $v);
continue;
}
if ($arg->assertWritable) {
if (is_file($v)) {
if (! is_writable($v)) {
$this->addError($letter, "File not writable: %s", $v);
}
} else {
if (! is_writable(dirname($v))) {
$this->addError($letter, "Directory not writable: %s", dirname($v));
}
}
}
} elseif ($arg->assertDir && $arg->assertWritable && ! is_writable($v)) {
$this->addError($letter, "Directory not readable: %s", $v);
}
}
} else {
if ($arg->isRequired()) {
$this->addError($letter, "Missing");
}
}
}
$this->moreArgs = $argvCopy;
reset($this->moreArgs);
return empty($this->errors);
}
/**
* Get the full paths of file(s) passed in as unspecified arguments
*
* @return array
*/
public function getPathArgs()
{
$r = $this->moreArgs;
foreach ($r as $k => $v) {
if ($v[0] !== '/' && $v[0] !== '~') {
$v = getcwd() . "/$v";
$v = str_replace('/./', '/', $v);
do {
$v = preg_replace('@/[^/]+/\\.\\./@', '/', $v, 1, $changed);
} while ($changed);
$r[$k] = $v;
}
}
return $r;
}
/**
* Get a short list of errors with options
*
* @return string
*/
public function getErrorReport()
{
if (empty($this->errors)) {
return '';
}
$r = "Some arguments did not pass validation:\n";
foreach ($this->errors as $letter => $arr) {
$r .= " $letter : " . implode(', ', $arr) . "\n";
}
$r .= "\n";
return $r;
}
/**
* @return string
*/
public function getArgumentsListing()
{
$r = "\n";
foreach ($this->_args as $letter => $arg) {
/* @var Arg $arg */
$desc = $arg->getDescription();
$flag = " -$letter ";
if ($arg->mayHaveValue) {
$flag .= "[VAL]";
} elseif ($arg->mustHaveValue) {
$flag .= "VAL";
}
if ($arg->assertFile) {
$flag = str_replace('VAL', 'FILE', $flag);
} elseif ($arg->assertDir) {
$flag = str_replace('VAL', 'DIR', $flag);
}
if ($arg->isRequired()) {
$desc = "(required) $desc";
}
$flag = str_pad($flag, 12, " ", STR_PAD_RIGHT);
$desc = wordwrap($desc, 70);
$r .= $flag . str_replace("\n", "\n ", $desc) . "\n\n";
}
return $r;
}
/**
* Get resource of open input stream. May be STDIN or a file pointer
* to the file specified by an option with 'STDIN'.
*
* @return resource
*/
public function openInput()
{
if (null === $this->_stdin) {
return STDIN;
} else {
$this->_stdin = fopen($this->_stdin, 'rb');
return $this->_stdin;
}
}
public function closeInput()
{
if (null !== $this->_stdin) {
fclose($this->_stdin);
}
}
/**
* Get resource of open output stream. May be STDOUT or a file pointer
* to the file specified by an option with 'STDOUT'. The file will be
* truncated to 0 bytes on opening.
*
* @return resource
*/
public function openOutput()
{
if (null === $this->_stdout) {
return STDOUT;
} else {
$this->_stdout = fopen($this->_stdout, 'wb');
return $this->_stdout;
}
}
public function closeOutput()
{
if (null !== $this->_stdout) {
fclose($this->_stdout);
}
}
/**
* @param string $letter
* @param string $msg
* @param string $value
*/
protected function addError($letter, $msg, $value = null)
{
if ($value !== null) {
$value = var_export($value, 1);
}
$this->errors[$letter][] = sprintf($msg, $value);
}
}
PK ^GMa? min/lib/MrClay/Cli/Arg.phpnu W+A values['f.raw']
*
* Use assertReadable()/assertWritable() to cause the validator to test the file/dir for
* read/write permissions respectively.
*
* @method \MrClay\Cli\Arg mayHaveValue() Assert that the argument, if present, may receive a string value
* @method \MrClay\Cli\Arg mustHaveValue() Assert that the argument, if present, must receive a string value
* @method \MrClay\Cli\Arg assertFile() Assert that the argument's value must specify a file
* @method \MrClay\Cli\Arg assertDir() Assert that the argument's value must specify a directory
* @method \MrClay\Cli\Arg assertReadable() Assert that the specified file/dir must be readable
* @method \MrClay\Cli\Arg assertWritable() Assert that the specified file/dir must be writable
*
* @property-read bool mayHaveValue
* @property-read bool mustHaveValue
* @property-read bool assertFile
* @property-read bool assertDir
* @property-read bool assertReadable
* @property-read bool assertWritable
* @property-read bool useAsInfile
* @property-read bool useAsOutfile
*
* @author Steve Clay
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
class Arg {
/**
* @return array
*/
public function getDefaultSpec()
{
return array(
'mayHaveValue' => false,
'mustHaveValue' => false,
'assertFile' => false,
'assertDir' => false,
'assertReadable' => false,
'assertWritable' => false,
'useAsInfile' => false,
'useAsOutfile' => false,
);
}
/**
* @var array
*/
protected $spec = array();
/**
* @var bool
*/
protected $required = false;
/**
* @var string
*/
protected $description = '';
/**
* @param bool $isRequired
*/
public function __construct($isRequired = false)
{
$this->spec = $this->getDefaultSpec();
$this->required = (bool) $isRequired;
if ($isRequired) {
$this->spec['mustHaveValue'] = true;
}
}
/**
* Assert that the argument's value points to a writable file. When
* Cli::openOutput() is called, a write pointer to this file will
* be provided.
* @return Arg
*/
public function useAsOutfile()
{
$this->spec['useAsOutfile'] = true;
return $this->assertFile()->assertWritable();
}
/**
* Assert that the argument's value points to a readable file. When
* Cli::openInput() is called, a read pointer to this file will
* be provided.
* @return Arg
*/
public function useAsInfile()
{
$this->spec['useAsInfile'] = true;
return $this->assertFile()->assertReadable();
}
/**
* @return array
*/
public function getSpec()
{
return $this->spec;
}
/**
* @param string $desc
* @return Arg
*/
public function setDescription($desc)
{
$this->description = $desc;
return $this;
}
/**
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* @return bool
*/
public function isRequired()
{
return $this->required;
}
/**
* Note: magic methods declared in class PHPDOC
*
* @param string $name
* @param array $args
* @return Arg
* @throws BadMethodCallException
*/
public function __call($name, array $args = array())
{
if (array_key_exists($name, $this->spec)) {
$this->spec[$name] = true;
if ($name === 'assertFile' || $name === 'assertDir') {
$this->spec['mustHaveValue'] = true;
}
} else {
throw new BadMethodCallException('Method does not exist');
}
return $this;
}
/**
* Note: magic properties declared in class PHPDOC
*
* @param string $name
* @return bool|null
*/
public function __get($name)
{
if (array_key_exists($name, $this->spec)) {
return $this->spec[$name];
}
return null;
}
}
PK ^GMuR min/lib/JSMinPlus.phpnu W+A
*
* Usage: $minified = JSMinPlus::minify($script [, $filename])
*
* Versionlog (see also changelog.txt):
* 23-07-2011 - remove dynamic creation of OP_* and KEYWORD_* defines and declare them on top
* reduce memory footprint by minifying by block-scope
* some small byte-saving and performance improvements
* 12-05-2009 - fixed hook:colon precedence, fixed empty body in loop and if-constructs
* 18-04-2009 - fixed crashbug in PHP 5.2.9 and several other bugfixes
* 12-04-2009 - some small bugfixes and performance improvements
* 09-04-2009 - initial open sourced version 1.0
*
* Latest version of this script: http://files.tweakers.net/jsminplus/jsminplus.zip
*
*/
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Narcissus JavaScript engine.
*
* The Initial Developer of the Original Code is
* Brendan Eich .
* Portions created by the Initial Developer are Copyright (C) 2004
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Tino Zijdel
* PHP port, modifications and minifier routine are (C) 2009-2011
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('TOKEN_END', 1);
define('TOKEN_NUMBER', 2);
define('TOKEN_IDENTIFIER', 3);
define('TOKEN_STRING', 4);
define('TOKEN_REGEXP', 5);
define('TOKEN_NEWLINE', 6);
define('TOKEN_CONDCOMMENT_START', 7);
define('TOKEN_CONDCOMMENT_END', 8);
define('JS_SCRIPT', 100);
define('JS_BLOCK', 101);
define('JS_LABEL', 102);
define('JS_FOR_IN', 103);
define('JS_CALL', 104);
define('JS_NEW_WITH_ARGS', 105);
define('JS_INDEX', 106);
define('JS_ARRAY_INIT', 107);
define('JS_OBJECT_INIT', 108);
define('JS_PROPERTY_INIT', 109);
define('JS_GETTER', 110);
define('JS_SETTER', 111);
define('JS_GROUP', 112);
define('JS_LIST', 113);
define('JS_MINIFIED', 999);
define('DECLARED_FORM', 0);
define('EXPRESSED_FORM', 1);
define('STATEMENT_FORM', 2);
/* Operators */
define('OP_SEMICOLON', ';');
define('OP_COMMA', ',');
define('OP_HOOK', '?');
define('OP_COLON', ':');
define('OP_OR', '||');
define('OP_AND', '&&');
define('OP_BITWISE_OR', '|');
define('OP_BITWISE_XOR', '^');
define('OP_BITWISE_AND', '&');
define('OP_STRICT_EQ', '===');
define('OP_EQ', '==');
define('OP_ASSIGN', '=');
define('OP_STRICT_NE', '!==');
define('OP_NE', '!=');
define('OP_LSH', '<<');
define('OP_LE', '<=');
define('OP_LT', '<');
define('OP_URSH', '>>>');
define('OP_RSH', '>>');
define('OP_GE', '>=');
define('OP_GT', '>');
define('OP_INCREMENT', '++');
define('OP_DECREMENT', '--');
define('OP_PLUS', '+');
define('OP_MINUS', '-');
define('OP_MUL', '*');
define('OP_DIV', '/');
define('OP_MOD', '%');
define('OP_NOT', '!');
define('OP_BITWISE_NOT', '~');
define('OP_DOT', '.');
define('OP_LEFT_BRACKET', '[');
define('OP_RIGHT_BRACKET', ']');
define('OP_LEFT_CURLY', '{');
define('OP_RIGHT_CURLY', '}');
define('OP_LEFT_PAREN', '(');
define('OP_RIGHT_PAREN', ')');
define('OP_CONDCOMMENT_END', '@*/');
define('OP_UNARY_PLUS', 'U+');
define('OP_UNARY_MINUS', 'U-');
/* Keywords */
define('KEYWORD_BREAK', 'break');
define('KEYWORD_CASE', 'case');
define('KEYWORD_CATCH', 'catch');
define('KEYWORD_CONST', 'const');
define('KEYWORD_CONTINUE', 'continue');
define('KEYWORD_DEBUGGER', 'debugger');
define('KEYWORD_DEFAULT', 'default');
define('KEYWORD_DELETE', 'delete');
define('KEYWORD_DO', 'do');
define('KEYWORD_ELSE', 'else');
define('KEYWORD_ENUM', 'enum');
define('KEYWORD_FALSE', 'false');
define('KEYWORD_FINALLY', 'finally');
define('KEYWORD_FOR', 'for');
define('KEYWORD_FUNCTION', 'function');
define('KEYWORD_IF', 'if');
define('KEYWORD_IN', 'in');
define('KEYWORD_INSTANCEOF', 'instanceof');
define('KEYWORD_NEW', 'new');
define('KEYWORD_NULL', 'null');
define('KEYWORD_RETURN', 'return');
define('KEYWORD_SWITCH', 'switch');
define('KEYWORD_THIS', 'this');
define('KEYWORD_THROW', 'throw');
define('KEYWORD_TRUE', 'true');
define('KEYWORD_TRY', 'try');
define('KEYWORD_TYPEOF', 'typeof');
define('KEYWORD_VAR', 'var');
define('KEYWORD_VOID', 'void');
define('KEYWORD_WHILE', 'while');
define('KEYWORD_WITH', 'with');
class JSMinPlus
{
private $parser;
private $reserved = array(
'break', 'case', 'catch', 'continue', 'default', 'delete', 'do',
'else', 'finally', 'for', 'function', 'if', 'in', 'instanceof',
'new', 'return', 'switch', 'this', 'throw', 'try', 'typeof', 'var',
'void', 'while', 'with',
// Words reserved for future use
'abstract', 'boolean', 'byte', 'char', 'class', 'const', 'debugger',
'double', 'enum', 'export', 'extends', 'final', 'float', 'goto',
'implements', 'import', 'int', 'interface', 'long', 'native',
'package', 'private', 'protected', 'public', 'short', 'static',
'super', 'synchronized', 'throws', 'transient', 'volatile',
// These are not reserved, but should be taken into account
// in isValidIdentifier (See jslint source code)
'arguments', 'eval', 'true', 'false', 'Infinity', 'NaN', 'null', 'undefined'
);
private function __construct()
{
$this->parser = new JSParser($this);
}
public static function minify($js, $filename='')
{
static $instance;
// this is a singleton
if(!$instance)
$instance = new JSMinPlus();
return $instance->min($js, $filename);
}
private function min($js, $filename)
{
try
{
$n = $this->parser->parse($js, $filename, 1);
return $this->parseTree($n);
}
catch(Exception $e)
{
echo $e->getMessage() . "\n";
}
return false;
}
public function parseTree($n, $noBlockGrouping = false)
{
$s = '';
switch ($n->type)
{
case JS_MINIFIED:
$s = $n->value;
break;
case JS_SCRIPT:
// we do nothing yet with funDecls or varDecls
$noBlockGrouping = true;
// FALL THROUGH
case JS_BLOCK:
$childs = $n->treeNodes;
$lastType = 0;
for ($c = 0, $i = 0, $j = count($childs); $i < $j; $i++)
{
$type = $childs[$i]->type;
$t = $this->parseTree($childs[$i]);
if (strlen($t))
{
if ($c)
{
$s = rtrim($s, ';');
if ($type == KEYWORD_FUNCTION && $childs[$i]->functionForm == DECLARED_FORM)
{
// put declared functions on a new line
$s .= "\n";
}
elseif ($type == KEYWORD_VAR && $type == $lastType)
{
// mutiple var-statements can go into one
$t = ',' . substr($t, 4);
}
else
{
// add terminator
$s .= ';';
}
}
$s .= $t;
$c++;
$lastType = $type;
}
}
if ($c > 1 && !$noBlockGrouping)
{
$s = '{' . $s . '}';
}
break;
case KEYWORD_FUNCTION:
$s .= 'function' . ($n->name ? ' ' . $n->name : '') . '(';
$params = $n->params;
for ($i = 0, $j = count($params); $i < $j; $i++)
$s .= ($i ? ',' : '') . $params[$i];
$s .= '){' . $this->parseTree($n->body, true) . '}';
break;
case KEYWORD_IF:
$s = 'if(' . $this->parseTree($n->condition) . ')';
$thenPart = $this->parseTree($n->thenPart);
$elsePart = $n->elsePart ? $this->parseTree($n->elsePart) : null;
// empty if-statement
if ($thenPart == '')
$thenPart = ';';
if ($elsePart)
{
// be carefull and always make a block out of the thenPart; could be more optimized but is a lot of trouble
if ($thenPart != ';' && $thenPart[0] != '{')
$thenPart = '{' . $thenPart . '}';
$s .= $thenPart . 'else';
// we could check for more, but that hardly ever applies so go for performance
if ($elsePart[0] != '{')
$s .= ' ';
$s .= $elsePart;
}
else
{
$s .= $thenPart;
}
break;
case KEYWORD_SWITCH:
$s = 'switch(' . $this->parseTree($n->discriminant) . '){';
$cases = $n->cases;
for ($i = 0, $j = count($cases); $i < $j; $i++)
{
$case = $cases[$i];
if ($case->type == KEYWORD_CASE)
$s .= 'case' . ($case->caseLabel->type != TOKEN_STRING ? ' ' : '') . $this->parseTree($case->caseLabel) . ':';
else
$s .= 'default:';
$statement = $this->parseTree($case->statements, true);
if ($statement)
{
$s .= $statement;
// no terminator for last statement
if ($i + 1 < $j)
$s .= ';';
}
}
$s .= '}';
break;
case KEYWORD_FOR:
$s = 'for(' . ($n->setup ? $this->parseTree($n->setup) : '')
. ';' . ($n->condition ? $this->parseTree($n->condition) : '')
. ';' . ($n->update ? $this->parseTree($n->update) : '') . ')';
$body = $this->parseTree($n->body);
if ($body == '')
$body = ';';
$s .= $body;
break;
case KEYWORD_WHILE:
$s = 'while(' . $this->parseTree($n->condition) . ')';
$body = $this->parseTree($n->body);
if ($body == '')
$body = ';';
$s .= $body;
break;
case JS_FOR_IN:
$s = 'for(' . ($n->varDecl ? $this->parseTree($n->varDecl) : $this->parseTree($n->iterator)) . ' in ' . $this->parseTree($n->object) . ')';
$body = $this->parseTree($n->body);
if ($body == '')
$body = ';';
$s .= $body;
break;
case KEYWORD_DO:
$s = 'do{' . $this->parseTree($n->body, true) . '}while(' . $this->parseTree($n->condition) . ')';
break;
case KEYWORD_BREAK:
case KEYWORD_CONTINUE:
$s = $n->value . ($n->label ? ' ' . $n->label : '');
break;
case KEYWORD_TRY:
$s = 'try{' . $this->parseTree($n->tryBlock, true) . '}';
$catchClauses = $n->catchClauses;
for ($i = 0, $j = count($catchClauses); $i < $j; $i++)
{
$t = $catchClauses[$i];
$s .= 'catch(' . $t->varName . ($t->guard ? ' if ' . $this->parseTree($t->guard) : '') . '){' . $this->parseTree($t->block, true) . '}';
}
if ($n->finallyBlock)
$s .= 'finally{' . $this->parseTree($n->finallyBlock, true) . '}';
break;
case KEYWORD_THROW:
case KEYWORD_RETURN:
$s = $n->type;
if ($n->value)
{
$t = $this->parseTree($n->value);
if (strlen($t))
{
if ($this->isWordChar($t[0]) || $t[0] == '\\')
$s .= ' ';
$s .= $t;
}
}
break;
case KEYWORD_WITH:
$s = 'with(' . $this->parseTree($n->object) . ')' . $this->parseTree($n->body);
break;
case KEYWORD_VAR:
case KEYWORD_CONST:
$s = $n->value . ' ';
$childs = $n->treeNodes;
for ($i = 0, $j = count($childs); $i < $j; $i++)
{
$t = $childs[$i];
$s .= ($i ? ',' : '') . $t->name;
$u = $t->initializer;
if ($u)
$s .= '=' . $this->parseTree($u);
}
break;
case KEYWORD_IN:
case KEYWORD_INSTANCEOF:
$left = $this->parseTree($n->treeNodes[0]);
$right = $this->parseTree($n->treeNodes[1]);
$s = $left;
if ($this->isWordChar(substr($left, -1)))
$s .= ' ';
$s .= $n->type;
if ($this->isWordChar($right[0]) || $right[0] == '\\')
$s .= ' ';
$s .= $right;
break;
case KEYWORD_DELETE:
case KEYWORD_TYPEOF:
$right = $this->parseTree($n->treeNodes[0]);
$s = $n->type;
if ($this->isWordChar($right[0]) || $right[0] == '\\')
$s .= ' ';
$s .= $right;
break;
case KEYWORD_VOID:
$s = 'void(' . $this->parseTree($n->treeNodes[0]) . ')';
break;
case KEYWORD_DEBUGGER:
throw new Exception('NOT IMPLEMENTED: DEBUGGER');
break;
case TOKEN_CONDCOMMENT_START:
case TOKEN_CONDCOMMENT_END:
$s = $n->value . ($n->type == TOKEN_CONDCOMMENT_START ? ' ' : '');
$childs = $n->treeNodes;
for ($i = 0, $j = count($childs); $i < $j; $i++)
$s .= $this->parseTree($childs[$i]);
break;
case OP_SEMICOLON:
if ($expression = $n->expression)
$s = $this->parseTree($expression);
break;
case JS_LABEL:
$s = $n->label . ':' . $this->parseTree($n->statement);
break;
case OP_COMMA:
$childs = $n->treeNodes;
for ($i = 0, $j = count($childs); $i < $j; $i++)
$s .= ($i ? ',' : '') . $this->parseTree($childs[$i]);
break;
case OP_ASSIGN:
$s = $this->parseTree($n->treeNodes[0]) . $n->value . $this->parseTree($n->treeNodes[1]);
break;
case OP_HOOK:
$s = $this->parseTree($n->treeNodes[0]) . '?' . $this->parseTree($n->treeNodes[1]) . ':' . $this->parseTree($n->treeNodes[2]);
break;
case OP_OR: case OP_AND:
case OP_BITWISE_OR: case OP_BITWISE_XOR: case OP_BITWISE_AND:
case OP_EQ: case OP_NE: case OP_STRICT_EQ: case OP_STRICT_NE:
case OP_LT: case OP_LE: case OP_GE: case OP_GT:
case OP_LSH: case OP_RSH: case OP_URSH:
case OP_MUL: case OP_DIV: case OP_MOD:
$s = $this->parseTree($n->treeNodes[0]) . $n->type . $this->parseTree($n->treeNodes[1]);
break;
case OP_PLUS:
case OP_MINUS:
$left = $this->parseTree($n->treeNodes[0]);
$right = $this->parseTree($n->treeNodes[1]);
switch ($n->treeNodes[1]->type)
{
case OP_PLUS:
case OP_MINUS:
case OP_INCREMENT:
case OP_DECREMENT:
case OP_UNARY_PLUS:
case OP_UNARY_MINUS:
$s = $left . $n->type . ' ' . $right;
break;
case TOKEN_STRING:
//combine concatted strings with same quotestyle
if ($n->type == OP_PLUS && substr($left, -1) == $right[0])
{
$s = substr($left, 0, -1) . substr($right, 1);
break;
}
// FALL THROUGH
default:
$s = $left . $n->type . $right;
}
break;
case OP_NOT:
case OP_BITWISE_NOT:
case OP_UNARY_PLUS:
case OP_UNARY_MINUS:
$s = $n->value . $this->parseTree($n->treeNodes[0]);
break;
case OP_INCREMENT:
case OP_DECREMENT:
if ($n->postfix)
$s = $this->parseTree($n->treeNodes[0]) . $n->value;
else
$s = $n->value . $this->parseTree($n->treeNodes[0]);
break;
case OP_DOT:
$s = $this->parseTree($n->treeNodes[0]) . '.' . $this->parseTree($n->treeNodes[1]);
break;
case JS_INDEX:
$s = $this->parseTree($n->treeNodes[0]);
// See if we can replace named index with a dot saving 3 bytes
if ( $n->treeNodes[0]->type == TOKEN_IDENTIFIER &&
$n->treeNodes[1]->type == TOKEN_STRING &&
$this->isValidIdentifier(substr($n->treeNodes[1]->value, 1, -1))
)
$s .= '.' . substr($n->treeNodes[1]->value, 1, -1);
else
$s .= '[' . $this->parseTree($n->treeNodes[1]) . ']';
break;
case JS_LIST:
$childs = $n->treeNodes;
for ($i = 0, $j = count($childs); $i < $j; $i++)
$s .= ($i ? ',' : '') . $this->parseTree($childs[$i]);
break;
case JS_CALL:
$s = $this->parseTree($n->treeNodes[0]) . '(' . $this->parseTree($n->treeNodes[1]) . ')';
break;
case KEYWORD_NEW:
case JS_NEW_WITH_ARGS:
$s = 'new ' . $this->parseTree($n->treeNodes[0]) . '(' . ($n->type == JS_NEW_WITH_ARGS ? $this->parseTree($n->treeNodes[1]) : '') . ')';
break;
case JS_ARRAY_INIT:
$s = '[';
$childs = $n->treeNodes;
for ($i = 0, $j = count($childs); $i < $j; $i++)
{
$s .= ($i ? ',' : '') . $this->parseTree($childs[$i]);
}
$s .= ']';
break;
case JS_OBJECT_INIT:
$s = '{';
$childs = $n->treeNodes;
for ($i = 0, $j = count($childs); $i < $j; $i++)
{
$t = $childs[$i];
if ($i)
$s .= ',';
if ($t->type == JS_PROPERTY_INIT)
{
// Ditch the quotes when the index is a valid identifier
if ( $t->treeNodes[0]->type == TOKEN_STRING &&
$this->isValidIdentifier(substr($t->treeNodes[0]->value, 1, -1))
)
$s .= substr($t->treeNodes[0]->value, 1, -1);
else
$s .= $t->treeNodes[0]->value;
$s .= ':' . $this->parseTree($t->treeNodes[1]);
}
else
{
$s .= $t->type == JS_GETTER ? 'get' : 'set';
$s .= ' ' . $t->name . '(';
$params = $t->params;
for ($i = 0, $j = count($params); $i < $j; $i++)
$s .= ($i ? ',' : '') . $params[$i];
$s .= '){' . $this->parseTree($t->body, true) . '}';
}
}
$s .= '}';
break;
case TOKEN_NUMBER:
$s = $n->value;
if (preg_match('/^([1-9]+)(0{3,})$/', $s, $m))
$s = $m[1] . 'e' . strlen($m[2]);
break;
case KEYWORD_NULL: case KEYWORD_THIS: case KEYWORD_TRUE: case KEYWORD_FALSE:
case TOKEN_IDENTIFIER: case TOKEN_STRING: case TOKEN_REGEXP:
$s = $n->value;
break;
case JS_GROUP:
if (in_array(
$n->treeNodes[0]->type,
array(
JS_ARRAY_INIT, JS_OBJECT_INIT, JS_GROUP,
TOKEN_NUMBER, TOKEN_STRING, TOKEN_REGEXP, TOKEN_IDENTIFIER,
KEYWORD_NULL, KEYWORD_THIS, KEYWORD_TRUE, KEYWORD_FALSE
)
))
{
$s = $this->parseTree($n->treeNodes[0]);
}
else
{
$s = '(' . $this->parseTree($n->treeNodes[0]) . ')';
}
break;
default:
throw new Exception('UNKNOWN TOKEN TYPE: ' . $n->type);
}
return $s;
}
private function isValidIdentifier($string)
{
return preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $string) && !in_array($string, $this->reserved);
}
private function isWordChar($char)
{
return $char == '_' || $char == '$' || ctype_alnum($char);
}
}
class JSParser
{
private $t;
private $minifier;
private $opPrecedence = array(
';' => 0,
',' => 1,
'=' => 2, '?' => 2, ':' => 2,
// The above all have to have the same precedence, see bug 330975
'||' => 4,
'&&' => 5,
'|' => 6,
'^' => 7,
'&' => 8,
'==' => 9, '!=' => 9, '===' => 9, '!==' => 9,
'<' => 10, '<=' => 10, '>=' => 10, '>' => 10, 'in' => 10, 'instanceof' => 10,
'<<' => 11, '>>' => 11, '>>>' => 11,
'+' => 12, '-' => 12,
'*' => 13, '/' => 13, '%' => 13,
'delete' => 14, 'void' => 14, 'typeof' => 14,
'!' => 14, '~' => 14, 'U+' => 14, 'U-' => 14,
'++' => 15, '--' => 15,
'new' => 16,
'.' => 17,
JS_NEW_WITH_ARGS => 0, JS_INDEX => 0, JS_CALL => 0,
JS_ARRAY_INIT => 0, JS_OBJECT_INIT => 0, JS_GROUP => 0
);
private $opArity = array(
',' => -2,
'=' => 2,
'?' => 3,
'||' => 2,
'&&' => 2,
'|' => 2,
'^' => 2,
'&' => 2,
'==' => 2, '!=' => 2, '===' => 2, '!==' => 2,
'<' => 2, '<=' => 2, '>=' => 2, '>' => 2, 'in' => 2, 'instanceof' => 2,
'<<' => 2, '>>' => 2, '>>>' => 2,
'+' => 2, '-' => 2,
'*' => 2, '/' => 2, '%' => 2,
'delete' => 1, 'void' => 1, 'typeof' => 1,
'!' => 1, '~' => 1, 'U+' => 1, 'U-' => 1,
'++' => 1, '--' => 1,
'new' => 1,
'.' => 2,
JS_NEW_WITH_ARGS => 2, JS_INDEX => 2, JS_CALL => 2,
JS_ARRAY_INIT => 1, JS_OBJECT_INIT => 1, JS_GROUP => 1,
TOKEN_CONDCOMMENT_START => 1, TOKEN_CONDCOMMENT_END => 1
);
public function __construct($minifier=null)
{
$this->minifier = $minifier;
$this->t = new JSTokenizer();
}
public function parse($s, $f, $l)
{
// initialize tokenizer
$this->t->init($s, $f, $l);
$x = new JSCompilerContext(false);
$n = $this->Script($x);
if (!$this->t->isDone())
throw $this->t->newSyntaxError('Syntax error');
return $n;
}
private function Script($x)
{
$n = $this->Statements($x);
$n->type = JS_SCRIPT;
$n->funDecls = $x->funDecls;
$n->varDecls = $x->varDecls;
// minify by scope
if ($this->minifier)
{
$n->value = $this->minifier->parseTree($n);
// clear tree from node to save memory
$n->treeNodes = null;
$n->funDecls = null;
$n->varDecls = null;
$n->type = JS_MINIFIED;
}
return $n;
}
private function Statements($x)
{
$n = new JSNode($this->t, JS_BLOCK);
array_push($x->stmtStack, $n);
while (!$this->t->isDone() && $this->t->peek() != OP_RIGHT_CURLY)
$n->addNode($this->Statement($x));
array_pop($x->stmtStack);
return $n;
}
private function Block($x)
{
$this->t->mustMatch(OP_LEFT_CURLY);
$n = $this->Statements($x);
$this->t->mustMatch(OP_RIGHT_CURLY);
return $n;
}
private function Statement($x)
{
$tt = $this->t->get();
$n2 = null;
// Cases for statements ending in a right curly return early, avoiding the
// common semicolon insertion magic after this switch.
switch ($tt)
{
case KEYWORD_FUNCTION:
return $this->FunctionDefinition(
$x,
true,
count($x->stmtStack) > 1 ? STATEMENT_FORM : DECLARED_FORM
);
break;
case OP_LEFT_CURLY:
$n = $this->Statements($x);
$this->t->mustMatch(OP_RIGHT_CURLY);
return $n;
case KEYWORD_IF:
$n = new JSNode($this->t);
$n->condition = $this->ParenExpression($x);
array_push($x->stmtStack, $n);
$n->thenPart = $this->Statement($x);
$n->elsePart = $this->t->match(KEYWORD_ELSE) ? $this->Statement($x) : null;
array_pop($x->stmtStack);
return $n;
case KEYWORD_SWITCH:
$n = new JSNode($this->t);
$this->t->mustMatch(OP_LEFT_PAREN);
$n->discriminant = $this->Expression($x);
$this->t->mustMatch(OP_RIGHT_PAREN);
$n->cases = array();
$n->defaultIndex = -1;
array_push($x->stmtStack, $n);
$this->t->mustMatch(OP_LEFT_CURLY);
while (($tt = $this->t->get()) != OP_RIGHT_CURLY)
{
switch ($tt)
{
case KEYWORD_DEFAULT:
if ($n->defaultIndex >= 0)
throw $this->t->newSyntaxError('More than one switch default');
// FALL THROUGH
case KEYWORD_CASE:
$n2 = new JSNode($this->t);
if ($tt == KEYWORD_DEFAULT)
$n->defaultIndex = count($n->cases);
else
$n2->caseLabel = $this->Expression($x, OP_COLON);
break;
default:
throw $this->t->newSyntaxError('Invalid switch case');
}
$this->t->mustMatch(OP_COLON);
$n2->statements = new JSNode($this->t, JS_BLOCK);
while (($tt = $this->t->peek()) != KEYWORD_CASE && $tt != KEYWORD_DEFAULT && $tt != OP_RIGHT_CURLY)
$n2->statements->addNode($this->Statement($x));
array_push($n->cases, $n2);
}
array_pop($x->stmtStack);
return $n;
case KEYWORD_FOR:
$n = new JSNode($this->t);
$n->isLoop = true;
$this->t->mustMatch(OP_LEFT_PAREN);
if (($tt = $this->t->peek()) != OP_SEMICOLON)
{
$x->inForLoopInit = true;
if ($tt == KEYWORD_VAR || $tt == KEYWORD_CONST)
{
$this->t->get();
$n2 = $this->Variables($x);
}
else
{
$n2 = $this->Expression($x);
}
$x->inForLoopInit = false;
}
if ($n2 && $this->t->match(KEYWORD_IN))
{
$n->type = JS_FOR_IN;
if ($n2->type == KEYWORD_VAR)
{
if (count($n2->treeNodes) != 1)
{
throw $this->t->SyntaxError(
'Invalid for..in left-hand side',
$this->t->filename,
$n2->lineno
);
}
// NB: n2[0].type == IDENTIFIER and n2[0].value == n2[0].name.
$n->iterator = $n2->treeNodes[0];
$n->varDecl = $n2;
}
else
{
$n->iterator = $n2;
$n->varDecl = null;
}
$n->object = $this->Expression($x);
}
else
{
$n->setup = $n2 ? $n2 : null;
$this->t->mustMatch(OP_SEMICOLON);
$n->condition = $this->t->peek() == OP_SEMICOLON ? null : $this->Expression($x);
$this->t->mustMatch(OP_SEMICOLON);
$n->update = $this->t->peek() == OP_RIGHT_PAREN ? null : $this->Expression($x);
}
$this->t->mustMatch(OP_RIGHT_PAREN);
$n->body = $this->nest($x, $n);
return $n;
case KEYWORD_WHILE:
$n = new JSNode($this->t);
$n->isLoop = true;
$n->condition = $this->ParenExpression($x);
$n->body = $this->nest($x, $n);
return $n;
case KEYWORD_DO:
$n = new JSNode($this->t);
$n->isLoop = true;
$n->body = $this->nest($x, $n, KEYWORD_WHILE);
$n->condition = $this->ParenExpression($x);
if (!$x->ecmaStrictMode)
{
// {$ws2}"
: "{$ws1}{$openScript}{$js}{$ws2}"
);
}
protected function _removeCdata($str)
{
return (false !== strpos($str, ''), '', $str)
: $str;
}
protected function _needsCdata($str)
{
return ($this->_isXhtml && preg_match('/(?:[<&]|\\-\\-|\\]\\]>)/', $str));
}
}
PK ^GMsO< % min/lib/Minify/JS/ClosureCompiler.phpnu W+A
*
* @todo can use a stream wrapper to unit test this?
*/
class Minify_JS_ClosureCompiler {
/**
* @var string The option key for the maximum POST byte size
*/
const OPTION_MAX_BYTES = 'maxBytes';
/**
* @var string The option key for additional params. @see __construct
*/
const OPTION_ADDITIONAL_OPTIONS = 'additionalParams';
/**
* @var string The option key for the fallback Minifier
*/
const OPTION_FALLBACK_FUNCTION = 'fallbackFunc';
/**
* @var string The option key for the service URL
*/
const OPTION_COMPILER_URL = 'compilerUrl';
/**
* @var int The default maximum POST byte size according to https://developers.google.com/closure/compiler/docs/api-ref
*/
const DEFAULT_MAX_BYTES = 200000;
/**
* @var string[] $DEFAULT_OPTIONS The default options to pass to the compiler service
*
* @note This would be a constant if PHP allowed it
*/
private static $DEFAULT_OPTIONS = array(
'output_format' => 'text',
'compilation_level' => 'SIMPLE_OPTIMIZATIONS'
);
/**
* @var string $url URL of compiler server. defaults to Google's
*/
protected $serviceUrl = 'http://closure-compiler.appspot.com/compile';
/**
* @var int $maxBytes The maximum JS size that can be sent to the compiler server in bytes
*/
protected $maxBytes = self::DEFAULT_MAX_BYTES;
/**
* @var string[] $additionalOptions Additional options to pass to the compiler service
*/
protected $additionalOptions = array();
/**
* @var callable Function to minify JS if service fails. Default is JSMin
*/
protected $fallbackMinifier = array('JSMin', 'minify');
/**
* Minify JavaScript code via HTTP request to a Closure Compiler API
*
* @param string $js input code
* @param array $options Options passed to __construct(). @see __construct
*
* @return string
*/
public static function minify($js, array $options = array())
{
$obj = new self($options);
return $obj->min($js);
}
/**
* @param array $options Options with keys available below:
*
* fallbackFunc : (callable) function to minify if service unavailable. Default is JSMin.
*
* compilerUrl : (string) URL to closure compiler server
*
* maxBytes : (int) The maximum amount of bytes to be sent as js_code in the POST request.
* Defaults to 200000.
*
* additionalParams : (string[]) Additional parameters to pass to the compiler server. Can be anything named
* in https://developers.google.com/closure/compiler/docs/api-ref except for js_code and
* output_info
*/
public function __construct(array $options = array())
{
if (isset($options[self::OPTION_FALLBACK_FUNCTION])) {
$this->fallbackMinifier = $options[self::OPTION_FALLBACK_FUNCTION];
}
if (isset($options[self::OPTION_COMPILER_URL])) {
$this->serviceUrl = $options[self::OPTION_COMPILER_URL];
}
if (isset($options[self::OPTION_ADDITIONAL_OPTIONS]) && is_array($options[self::OPTION_ADDITIONAL_OPTIONS])) {
$this->additionalOptions = $options[self::OPTION_ADDITIONAL_OPTIONS];
}
if (isset($options[self::OPTION_MAX_BYTES])) {
$this->maxBytes = (int) $options[self::OPTION_MAX_BYTES];
}
}
/**
* Call the service to perform the minification
*
* @param string $js JavaScript code
* @return string
* @throws Minify_JS_ClosureCompiler_Exception
*/
public function min($js)
{
$postBody = $this->buildPostBody($js);
if ($this->maxBytes > 0) {
$bytes = (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2))
? mb_strlen($postBody, '8bit')
: strlen($postBody);
if ($bytes > $this->maxBytes) {
throw new Minify_JS_ClosureCompiler_Exception(
'POST content larger than ' . $this->maxBytes . ' bytes'
);
}
}
$response = $this->getResponse($postBody);
if (preg_match('/^Error\(\d\d?\):/', $response)) {
if (is_callable($this->fallbackMinifier)) {
// use fallback
$response = "/* Received errors from Closure Compiler API:\n$response"
. "\n(Using fallback minifier)\n*/\n";
$response .= call_user_func($this->fallbackMinifier, $js);
} else {
throw new Minify_JS_ClosureCompiler_Exception($response);
}
}
if ($response === '') {
$errors = $this->getResponse($this->buildPostBody($js, true));
throw new Minify_JS_ClosureCompiler_Exception($errors);
}
return $response;
}
/**
* Get the response for a given POST body
*
* @param string $postBody
* @return string
* @throws Minify_JS_ClosureCompiler_Exception
*/
protected function getResponse($postBody)
{
$allowUrlFopen = preg_match('/1|yes|on|true/i', ini_get('allow_url_fopen'));
if ($allowUrlFopen) {
$contents = file_get_contents($this->serviceUrl, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\nConnection: close\r\n",
'content' => $postBody,
'max_redirects' => 0,
'timeout' => 15,
)
)));
} elseif (defined('CURLOPT_POST')) {
$ch = curl_init($this->serviceUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
$contents = curl_exec($ch);
curl_close($ch);
} else {
throw new Minify_JS_ClosureCompiler_Exception(
"Could not make HTTP request: allow_url_open is false and cURL not available"
);
}
if (false === $contents) {
throw new Minify_JS_ClosureCompiler_Exception(
"No HTTP response from server"
);
}
return trim($contents);
}
/**
* Build a POST request body
*
* @param string $js JavaScript code
* @param bool $returnErrors
* @return string
*/
protected function buildPostBody($js, $returnErrors = false)
{
return http_build_query(
array_merge(
self::$DEFAULT_OPTIONS,
$this->additionalOptions,
array(
'js_code' => $js,
'output_info' => ($returnErrors ? 'errors' : 'compiled_code')
)
),
null,
'&'
);
}
}
class Minify_JS_ClosureCompiler_Exception extends Exception {}
PK ^GMǁvd
min/lib/Minify/Build.phpnu W+A
* // in config file
* $groupSources = array(
* 'js' => array('file1.js', 'file2.js')
* ,'css' => array('file1.css', 'file2.css', 'file3.css')
* )
*
* // during HTML generation
* $jsBuild = new Minify_Build($groupSources['js']);
* $cssBuild = new Minify_Build($groupSources['css']);
*
* $script = "";
* $link = "";
*
* // in min.php
* Minify::serve('Groups', array(
* 'groups' => $groupSources
* ,'setExpires' => (time() + 86400 * 365)
* ));
*
*
* @package Minify
* @author Stephen Clay
*/
class Minify_Build {
/**
* Last modification time of all files in the build
*
* @var int
*/
public $lastModified = 0;
/**
* String to use as ampersand in uri(). Set this to '&' if
* you are not HTML-escaping URIs.
*
* @var string
*/
public static $ampersand = '&';
/**
* Get a time-stamped URI
*
*
* echo $b->uri('/site.js');
* // outputs "/site.js?1678242"
*
* echo $b->uri('/scriptaculous.js?load=effects');
* // outputs "/scriptaculous.js?load=effects&1678242"
*
*
* @param string $uri
* @param boolean $forceAmpersand (default = false) Force the use of ampersand to
* append the timestamp to the URI.
* @return string
*/
public function uri($uri, $forceAmpersand = false) {
$sep = ($forceAmpersand || strpos($uri, '?') !== false)
? self::$ampersand
: '?';
return "{$uri}{$sep}{$this->lastModified}";
}
/**
* Create a build object
*
* @param array $sources array of Minify_Source objects and/or file paths
*
* @return null
*/
public function __construct($sources)
{
$max = 0;
foreach ((array)$sources as $source) {
if ($source instanceof Minify_Source) {
$max = max($max, $source->lastModified);
} elseif (is_string($source)) {
if (0 === strpos($source, '//')) {
$source = $_SERVER['DOCUMENT_ROOT'] . substr($source, 1);
}
if (is_file($source)) {
$max = max($max, filemtime($source));
}
}
}
$this->lastModified = $max;
}
}
PK ^GM9}\
\
min/lib/Minify/CSS.phpnu W+A
* @author http://code.google.com/u/1stvamp/ (Issue 64 patch)
*/
class Minify_CSS {
/**
* Minify a CSS string
*
* @param string $css
*
* @param array $options available options:
*
* 'preserveComments': (default true) multi-line comments that begin
* with "/*!" will be preserved with newlines before and after to
* enhance readability.
*
* 'removeCharsets': (default true) remove all @charset at-rules
*
* 'prependRelativePath': (default null) if given, this string will be
* prepended to all relative URIs in import/url declarations
*
* 'currentDir': (default null) if given, this is assumed to be the
* directory of the current CSS file. Using this, minify will rewrite
* all relative URIs in import/url declarations to correctly point to
* the desired files. For this to work, the files *must* exist and be
* visible by the PHP process.
*
* 'symlinks': (default = array()) If the CSS file is stored in
* a symlink-ed directory, provide an array of link paths to
* target paths, where the link paths are within the document root. Because
* paths need to be normalized for this to work, use "//" to substitute
* the doc root in the link paths (the array keys). E.g.:
*
* array('//symlink' => '/real/target/path') // unix
* array('//static' => 'D:\\staticStorage') // Windows
*
*
* 'docRoot': (default = $_SERVER['DOCUMENT_ROOT'])
* see Minify_CSS_UriRewriter::rewrite
*
* @return string
*/
public static function minify($css, $options = array())
{
$options = array_merge(array(
'compress' => true,
'removeCharsets' => true,
'preserveComments' => true,
'currentDir' => null,
'docRoot' => $_SERVER['DOCUMENT_ROOT'],
'prependRelativePath' => null,
'symlinks' => array(),
), $options);
if ($options['removeCharsets']) {
$css = preg_replace('/@charset[^;]+;\\s*/', '', $css);
}
if ($options['compress']) {
if (! $options['preserveComments']) {
$css = Minify_CSS_Compressor::process($css, $options);
} else {
$css = Minify_CommentPreserver::process(
$css
,array('Minify_CSS_Compressor', 'process')
,array($options)
);
}
}
if (! $options['currentDir'] && ! $options['prependRelativePath']) {
return $css;
}
if ($options['currentDir']) {
return Minify_CSS_UriRewriter::rewrite(
$css
,$options['currentDir']
,$options['docRoot']
,$options['symlinks']
);
} else {
return Minify_CSS_UriRewriter::prepend(
$css
,$options['prependRelativePath']
);
}
}
}
PK ^GM( min/lib/Minify/CSSmin.phpnu W+A
*/
class Minify_CSSmin {
/**
* Minify a CSS string
*
* @param string $css
*
* @param array $options available options:
*
* 'removeCharsets': (default true) remove all @charset at-rules
*
* 'prependRelativePath': (default null) if given, this string will be
* prepended to all relative URIs in import/url declarations
*
* 'currentDir': (default null) if given, this is assumed to be the
* directory of the current CSS file. Using this, minify will rewrite
* all relative URIs in import/url declarations to correctly point to
* the desired files. For this to work, the files *must* exist and be
* visible by the PHP process.
*
* 'symlinks': (default = array()) If the CSS file is stored in
* a symlink-ed directory, provide an array of link paths to
* target paths, where the link paths are within the document root. Because
* paths need to be normalized for this to work, use "//" to substitute
* the doc root in the link paths (the array keys). E.g.:
*
* array('//symlink' => '/real/target/path') // unix
* array('//static' => 'D:\\staticStorage') // Windows
*
*
* 'docRoot': (default = $_SERVER['DOCUMENT_ROOT'])
* see Minify_CSS_UriRewriter::rewrite
*
* @return string
*/
public static function minify($css, $options = array())
{
$options = array_merge(array(
'compress' => true,
'removeCharsets' => true,
'currentDir' => null,
'docRoot' => $_SERVER['DOCUMENT_ROOT'],
'prependRelativePath' => null,
'symlinks' => array(),
), $options);
if ($options['removeCharsets']) {
$css = preg_replace('/@charset[^;]+;\\s*/', '', $css);
}
if ($options['compress']) {
$obj = new CSSmin();
$css = $obj->run($css);
}
if (! $options['currentDir'] && ! $options['prependRelativePath']) {
return $css;
}
if ($options['currentDir']) {
return Minify_CSS_UriRewriter::rewrite(
$css
,$options['currentDir']
,$options['docRoot']
,$options['symlinks']
);
} else {
return Minify_CSS_UriRewriter::prepend(
$css
,$options['prependRelativePath']
);
}
}
}
PK ^GM(EM M min/lib/Minify/Loader.phpnu W+A
*/
class Minify_Loader {
public function loadClass($class)
{
$file = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR;
$file .= strtr($class, "\\_", DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR) . '.php';
if (is_readable($file)) {
require $file;
}
}
static public function register()
{
$inst = new self();
spl_autoload_register(array($inst, 'loadClass'));
}
}
PK ^GMz+a
% min/lib/Minify/Cache/ZendPlatform.phpnu W+A
* Minify::setCache(new Minify_Cache_ZendPlatform());
*
*
* @package Minify
* @author Patrick van Dissel
*/
class Minify_Cache_ZendPlatform {
/**
* Create a Minify_Cache_ZendPlatform object, to be passed to
* Minify::setCache().
*
* @param int $expire seconds until expiration (default = 0
* meaning the item will not get an expiration date)
*
* @return null
*/
public function __construct($expire = 0)
{
$this->_exp = $expire;
}
/**
* Write data to cache.
*
* @param string $id cache id
*
* @param string $data
*
* @return bool success
*/
public function store($id, $data)
{
return output_cache_put($id, "{$_SERVER['REQUEST_TIME']}|{$data}");
}
/**
* Get the size of a cache entry
*
* @param string $id cache id
*
* @return int size in bytes
*/
public function getSize($id)
{
return $this->_fetch($id)
? strlen($this->_data)
: false;
}
/**
* Does a valid cache entry exist?
*
* @param string $id cache id
*
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
$ret = ($this->_fetch($id) && ($this->_lm >= $srcMtime));
return $ret;
}
/**
* Send the cached content to output
*
* @param string $id cache id
*/
public function display($id)
{
echo $this->_fetch($id)
? $this->_data
: '';
}
/**
* Fetch the cached content
*
* @param string $id cache id
*
* @return string
*/
public function fetch($id)
{
return $this->_fetch($id)
? $this->_data
: '';
}
private $_exp = null;
// cache of most recently fetched id
private $_lm = null;
private $_data = null;
private $_id = null;
/**
* Fetch data and timestamp from ZendPlatform, store in instance
*
* @param string $id
*
* @return bool success
*/
private function _fetch($id)
{
if ($this->_id === $id) {
return true;
}
$ret = output_cache_get($id, $this->_exp);
if (false === $ret) {
$this->_id = null;
return false;
}
list($this->_lm, $this->_data) = explode('|', $ret, 2);
$this->_id = $id;
return true;
}
}
PK ^GMaiA A min/lib/Minify/Cache/File.phpnu W+A _locking = $fileLocking;
$this->_path = $path;
}
/**
* Write data to cache.
*
* @param string $id cache id (e.g. a filename)
*
* @param string $data
*
* @return bool success
*/
public function store($id, $data)
{
$flag = $this->_locking
? LOCK_EX
: null;
$file = $this->_path . '/' . $id;
if (! @file_put_contents($file, $data, $flag)) {
$this->_log("Minify_Cache_File: Write failed to '$file'");
}
// write control
if ($data !== $this->fetch($id)) {
@unlink($file);
$this->_log("Minify_Cache_File: Post-write read failed for '$file'");
return false;
}
return true;
}
/**
* Get the size of a cache entry
*
* @param string $id cache id (e.g. a filename)
*
* @return int size in bytes
*/
public function getSize($id)
{
return filesize($this->_path . '/' . $id);
}
/**
* Does a valid cache entry exist?
*
* @param string $id cache id (e.g. a filename)
*
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
$file = $this->_path . '/' . $id;
return (is_file($file) && (filemtime($file) >= $srcMtime));
}
/**
* Send the cached content to output
*
* @param string $id cache id (e.g. a filename)
*/
public function display($id)
{
if ($this->_locking) {
$fp = fopen($this->_path . '/' . $id, 'rb');
flock($fp, LOCK_SH);
fpassthru($fp);
flock($fp, LOCK_UN);
fclose($fp);
} else {
readfile($this->_path . '/' . $id);
}
}
/**
* Fetch the cached content
*
* @param string $id cache id (e.g. a filename)
*
* @return string
*/
public function fetch($id)
{
if ($this->_locking) {
$fp = fopen($this->_path . '/' . $id, 'rb');
if (!$fp) {
return false;
}
flock($fp, LOCK_SH);
$ret = stream_get_contents($fp);
flock($fp, LOCK_UN);
fclose($fp);
return $ret;
} else {
return file_get_contents($this->_path . '/' . $id);
}
}
/**
* Fetch the cache path used
*
* @return string
*/
public function getPath()
{
return $this->_path;
}
/**
* Get a usable temp directory
*
* Adapted from Solar/Dir.php
* @author Paul M. Jones
* @license http://opensource.org/licenses/bsd-license.php BSD
* @link http://solarphp.com/trac/core/browser/trunk/Solar/Dir.php
*
* @return string
*/
public static function tmp()
{
static $tmp = null;
if (! $tmp) {
$tmp = function_exists('sys_get_temp_dir')
? sys_get_temp_dir()
: self::_tmp();
$tmp = rtrim($tmp, DIRECTORY_SEPARATOR);
}
return $tmp;
}
/**
* Returns the OS-specific directory for temporary files
*
* @author Paul M. Jones
* @license http://opensource.org/licenses/bsd-license.php BSD
* @link http://solarphp.com/trac/core/browser/trunk/Solar/Dir.php
*
* @return string
*/
protected static function _tmp()
{
// non-Windows system?
if (strtolower(substr(PHP_OS, 0, 3)) != 'win') {
$tmp = empty($_ENV['TMPDIR']) ? getenv('TMPDIR') : $_ENV['TMPDIR'];
if ($tmp) {
return $tmp;
} else {
return '/tmp';
}
}
// Windows 'TEMP'
$tmp = empty($_ENV['TEMP']) ? getenv('TEMP') : $_ENV['TEMP'];
if ($tmp) {
return $tmp;
}
// Windows 'TMP'
$tmp = empty($_ENV['TMP']) ? getenv('TMP') : $_ENV['TMP'];
if ($tmp) {
return $tmp;
}
// Windows 'windir'
$tmp = empty($_ENV['windir']) ? getenv('windir') : $_ENV['windir'];
if ($tmp) {
return $tmp;
}
// final fallback for Windows
return getenv('SystemRoot') . '\\temp';
}
/**
* Send message to the Minify logger
* @param string $msg
* @return null
*/
protected function _log($msg)
{
Minify_Logger::log($msg);
}
private $_path = null;
private $_locking = null;
}
PK ^GM~Ho o ! min/lib/Minify/Cache/WinCache.phpnu W+A
* Minify::setCache(new Minify_Cache_WinCache());
*
*
* @package Minify
* @author Matthias Fax
**/
class Minify_Cache_WinCache
{
/**
* Create a Minify_Cache_Wincache object, to be passed to
* Minify::setCache().
*
*
* @param int $expire seconds until expiration (default = 0
* meaning the item will not get an expiration date)
*/
public function __construct($expire = 0)
{
if (!function_exists('wincache_ucache_info')) {
throw new Exception("WinCache for PHP is not installed to be able to use Minify_Cache_WinCache!");
}
$this->_exp = $expire;
}
/**
* Write data to cache.
*
* @param string $id cache id
*
* @param string $data
*
* @return bool success
*/
public function store($id, $data)
{
return wincache_ucache_set($id, "{$_SERVER['REQUEST_TIME']}|{$data}", $this->_exp);
}
/**
* Get the size of a cache entry
*
* @param string $id cache id
*
* @return int size in bytes
*/
public function getSize($id)
{
if (!$this->_fetch($id)) {
return false;
}
return (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload') & 2)) ? mb_strlen($this->_data, '8bit') : strlen($this->_data);
}
/**
* Does a valid cache entry exist?
*
* @param string $id cache id
*
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
return ($this->_fetch($id) && ($this->_lm >= $srcMtime));
}
/**
* Send the cached content to output
*
* @param string $id cache id
*/
public function display($id)
{
echo $this->_fetch($id) ? $this->_data : '';
}
/**
* Fetch the cached content
*
* @param string $id cache id
*
* @return string
*/
public function fetch($id)
{
return $this->_fetch($id) ? $this->_data : '';
}
private $_exp = NULL;
// cache of most recently fetched id
private $_lm = NULL;
private $_data = NULL;
private $_id = NULL;
/**
* Fetch data and timestamp from WinCache, store in instance
*
* @param string $id
*
* @return bool success
*/
private function _fetch($id)
{
if ($this->_id === $id) {
return true;
}
$suc = false;
$ret = wincache_ucache_get($id, $suc);
if (!$suc) {
$this->_id = NULL;
return false;
}
list($this->_lm, $this->_data) = explode('|', $ret, 2);
$this->_id = $id;
return true;
}
}PK ^GM!9& & ! min/lib/Minify/Cache/Memcache.phpnu W+A
* // fall back to disk caching if memcache can't connect
* $memcache = new Memcache;
* if ($memcache->connect('localhost', 11211)) {
* Minify::setCache(new Minify_Cache_Memcache($memcache));
* } else {
* Minify::setCache();
* }
*
**/
class Minify_Cache_Memcache {
/**
* Create a Minify_Cache_Memcache object, to be passed to
* Minify::setCache().
*
* @param Memcache $memcache already-connected instance
*
* @param int $expire seconds until expiration (default = 0
* meaning the item will not get an expiration date)
*
* @return null
*/
public function __construct($memcache, $expire = 0)
{
$this->_mc = $memcache;
$this->_exp = $expire;
}
/**
* Write data to cache.
*
* @param string $id cache id
*
* @param string $data
*
* @return bool success
*/
public function store($id, $data)
{
return $this->_mc->set($id, "{$_SERVER['REQUEST_TIME']}|{$data}", 0, $this->_exp);
}
/**
* Get the size of a cache entry
*
* @param string $id cache id
*
* @return int size in bytes
*/
public function getSize($id)
{
if (! $this->_fetch($id)) {
return false;
}
return (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2))
? mb_strlen($this->_data, '8bit')
: strlen($this->_data);
}
/**
* Does a valid cache entry exist?
*
* @param string $id cache id
*
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
return ($this->_fetch($id) && ($this->_lm >= $srcMtime));
}
/**
* Send the cached content to output
*
* @param string $id cache id
*/
public function display($id)
{
echo $this->_fetch($id)
? $this->_data
: '';
}
/**
* Fetch the cached content
*
* @param string $id cache id
*
* @return string
*/
public function fetch($id)
{
return $this->_fetch($id)
? $this->_data
: '';
}
private $_mc = null;
private $_exp = null;
// cache of most recently fetched id
private $_lm = null;
private $_data = null;
private $_id = null;
/**
* Fetch data and timestamp from memcache, store in instance
*
* @param string $id
*
* @return bool success
*/
private function _fetch($id)
{
if ($this->_id === $id) {
return true;
}
$ret = $this->_mc->get($id);
if (false === $ret) {
$this->_id = null;
return false;
}
list($this->_lm, $this->_data) = explode('|', $ret, 2);
$this->_id = $id;
return true;
}
}
PK ^GML
min/lib/Minify/Cache/XCache.phpnu W+A
* Minify::setCache(new Minify_Cache_XCache());
*
*
* @package Minify
* @author Elan Ruusamäe
**/
class Minify_Cache_XCache {
/**
* Create a Minify_Cache_XCache object, to be passed to
* Minify::setCache().
*
* @param int $expire seconds until expiration (default = 0
* meaning the item will not get an expiration date)
*/
public function __construct($expire = 0)
{
$this->_exp = $expire;
}
/**
* Write data to cache.
*
* @param string $id cache id
* @param string $data
* @return bool success
*/
public function store($id, $data)
{
return xcache_set($id, "{$_SERVER['REQUEST_TIME']}|{$data}", $this->_exp);
}
/**
* Get the size of a cache entry
*
* @param string $id cache id
* @return int size in bytes
*/
public function getSize($id)
{
if (! $this->_fetch($id)) {
return false;
}
return (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2))
? mb_strlen($this->_data, '8bit')
: strlen($this->_data);
}
/**
* Does a valid cache entry exist?
*
* @param string $id cache id
* @param int $srcMtime mtime of the original source file(s)
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
return ($this->_fetch($id) && ($this->_lm >= $srcMtime));
}
/**
* Send the cached content to output
*
* @param string $id cache id
*/
public function display($id)
{
echo $this->_fetch($id)
? $this->_data
: '';
}
/**
* Fetch the cached content
*
* @param string $id cache id
* @return string
*/
public function fetch($id)
{
return $this->_fetch($id)
? $this->_data
: '';
}
private $_exp = null;
// cache of most recently fetched id
private $_lm = null;
private $_data = null;
private $_id = null;
/**
* Fetch data and timestamp from xcache, store in instance
*
* @param string $id
* @return bool success
*/
private function _fetch($id)
{
if ($this->_id === $id) {
return true;
}
$ret = xcache_get($id);
if (false === $ret) {
$this->_id = null;
return false;
}
list($this->_lm, $this->_data) = explode('|', $ret, 2);
$this->_id = $id;
return true;
}
}
PK ^GMh
min/lib/Minify/Cache/APC.phpnu W+A
* Minify::setCache(new Minify_Cache_APC());
*
*
* @package Minify
* @author Chris Edwards
**/
class Minify_Cache_APC {
/**
* Create a Minify_Cache_APC object, to be passed to
* Minify::setCache().
*
*
* @param int $expire seconds until expiration (default = 0
* meaning the item will not get an expiration date)
*
* @return null
*/
public function __construct($expire = 0)
{
$this->_exp = $expire;
}
/**
* Write data to cache.
*
* @param string $id cache id
*
* @param string $data
*
* @return bool success
*/
public function store($id, $data)
{
return apc_store($id, "{$_SERVER['REQUEST_TIME']}|{$data}", $this->_exp);
}
/**
* Get the size of a cache entry
*
* @param string $id cache id
*
* @return int size in bytes
*/
public function getSize($id)
{
if (! $this->_fetch($id)) {
return false;
}
return (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2))
? mb_strlen($this->_data, '8bit')
: strlen($this->_data);
}
/**
* Does a valid cache entry exist?
*
* @param string $id cache id
*
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
return ($this->_fetch($id) && ($this->_lm >= $srcMtime));
}
/**
* Send the cached content to output
*
* @param string $id cache id
*/
public function display($id)
{
echo $this->_fetch($id)
? $this->_data
: '';
}
/**
* Fetch the cached content
*
* @param string $id cache id
*
* @return string
*/
public function fetch($id)
{
return $this->_fetch($id)
? $this->_data
: '';
}
private $_exp = null;
// cache of most recently fetched id
private $_lm = null;
private $_data = null;
private $_id = null;
/**
* Fetch data and timestamp from apc, store in instance
*
* @param string $id
*
* @return bool success
*/
private function _fetch($id)
{
if ($this->_id === $id) {
return true;
}
$ret = apc_fetch($id);
if (false === $ret) {
$this->_id = null;
return false;
}
list($this->_lm, $this->_data) = explode('|', $ret, 2);
$this->_id = $id;
return true;
}
}
PK ^GMu/̃ min/lib/Minify/YUICompressor.phpnu W+A
* Minify_YUICompressor::$jarFile = '/path/to/yuicompressor-2.4.6.jar';
* Minify_YUICompressor::$tempDir = '/tmp';
* $code = Minify_YUICompressor::minifyJs(
* $code
* ,array('nomunge' => true, 'line-break' => 1000)
* );
*
*
* Note: In case you run out stack (default is 512k), you may increase stack size in $options:
* array('stack-size' => '2048k')
*
* @todo unit tests, $options docs
*
* @package Minify
* @author Stephen Clay
*/
class Minify_YUICompressor {
/**
* Filepath of the YUI Compressor jar file. This must be set before
* calling minifyJs() or minifyCss().
*
* @var string
*/
public static $jarFile = null;
/**
* Writable temp directory. This must be set before calling minifyJs()
* or minifyCss().
*
* @var string
*/
public static $tempDir = null;
/**
* Filepath of "java" executable (may be needed if not in shell's PATH)
*
* @var string
*/
public static $javaExecutable = 'java';
/**
* Minify a Javascript string
*
* @param string $js
*
* @param array $options (verbose is ignored)
*
* @see http://www.julienlecomte.net/yuicompressor/README
*
* @return string
*/
public static function minifyJs($js, $options = array())
{
return self::_minify('js', $js, $options);
}
/**
* Minify a CSS string
*
* @param string $css
*
* @param array $options (verbose is ignored)
*
* @see http://www.julienlecomte.net/yuicompressor/README
*
* @return string
*/
public static function minifyCss($css, $options = array())
{
return self::_minify('css', $css, $options);
}
private static function _minify($type, $content, $options)
{
self::_prepare();
if (! ($tmpFile = tempnam(self::$tempDir, 'yuic_'))) {
throw new Exception('Minify_YUICompressor : could not create temp file in "'.self::$tempDir.'".');
}
file_put_contents($tmpFile, $content);
exec(self::_getCmd($options, $type, $tmpFile), $output, $result_code);
unlink($tmpFile);
if ($result_code != 0) {
throw new Exception('Minify_YUICompressor : YUI compressor execution failed.');
}
return implode("\n", $output);
}
private static function _getCmd($userOptions, $type, $tmpFile)
{
$o = array_merge(
array(
'charset' => ''
,'line-break' => 5000
,'type' => $type
,'nomunge' => false
,'preserve-semi' => false
,'disable-optimizations' => false
,'stack-size' => ''
)
,$userOptions
);
$cmd = self::$javaExecutable
. (!empty($o['stack-size'])
? ' -Xss' . $o['stack-size']
: '')
. ' -jar ' . escapeshellarg(self::$jarFile)
. " --type {$type}"
. (preg_match('/^[\\da-zA-Z0-9\\-]+$/', $o['charset'])
? " --charset {$o['charset']}"
: '')
. (is_numeric($o['line-break']) && $o['line-break'] >= 0
? ' --line-break ' . (int)$o['line-break']
: '');
if ($type === 'js') {
foreach (array('nomunge', 'preserve-semi', 'disable-optimizations') as $opt) {
$cmd .= $o[$opt]
? " --{$opt}"
: '';
}
}
return $cmd . ' ' . escapeshellarg($tmpFile);
}
private static function _prepare()
{
if (! is_file(self::$jarFile)) {
throw new Exception('Minify_YUICompressor : $jarFile('.self::$jarFile.') is not a valid file.');
}
if (! is_readable(self::$jarFile)) {
throw new Exception('Minify_YUICompressor : $jarFile('.self::$jarFile.') is not readable.');
}
if (! is_dir(self::$tempDir)) {
throw new Exception('Minify_YUICompressor : $tempDir('.self::$tempDir.') is not a valid direcotry.');
}
if (! is_writable(self::$tempDir)) {
throw new Exception('Minify_YUICompressor : $tempDir('.self::$tempDir.') is not writable.');
}
}
}
PK ^GMC:! :! ! min/lib/Minify/CSS/Compressor.phpnu W+A
* @author http://code.google.com/u/1stvamp/ (Issue 64 patch)
*/
class Minify_CSS_Compressor {
/**
* Minify a CSS string
*
* @param string $css
*
* @param array $options (currently ignored)
*
* @return string
*/
public static function process($css, $options = array())
{
$obj = new Minify_CSS_Compressor($options);
return $obj->_process($css);
}
/**
* @var array
*/
protected $_options = null;
/**
* Are we "in" a hack? I.e. are some browsers targetted until the next comment?
*
* @var bool
*/
protected $_inHack = false;
/**
* Constructor
*
* @param array $options (currently ignored)
*/
private function __construct($options) {
$this->_options = $options;
}
/**
* Minify a CSS string
*
* @param string $css
*
* @return string
*/
protected function _process($css)
{
$css = str_replace("\r\n", "\n", $css);
// preserve empty comment after '>'
// http://www.webdevout.net/css-hacks#in_css-selectors
$css = preg_replace('@>/\\*\\s*\\*/@', '>/*keep*/', $css);
// preserve empty comment between property and value
// http://css-discuss.incutio.com/?page=BoxModelHack
$css = preg_replace('@/\\*\\s*\\*/\\s*:@', '/*keep*/:', $css);
$css = preg_replace('@:\\s*/\\*\\s*\\*/@', ':/*keep*/', $css);
// apply callback to all valid comments (and strip out surrounding ws
$css = preg_replace_callback('@\\s*/\\*([\\s\\S]*?)\\*/\\s*@'
,array($this, '_commentCB'), $css);
// remove ws around { } and last semicolon in declaration block
$css = preg_replace('/\\s*{\\s*/', '{', $css);
$css = preg_replace('/;?\\s*}\\s*/', '}', $css);
// remove ws surrounding semicolons
$css = preg_replace('/\\s*;\\s*/', ';', $css);
// remove ws around urls
$css = preg_replace('/
url\\( # url(
\\s*
([^\\)]+?) # 1 = the URL (really just a bunch of non right parenthesis)
\\s*
\\) # )
/x', 'url($1)', $css);
// remove ws between rules and colons
$css = preg_replace('/
\\s*
([{;]) # 1 = beginning of block or rule separator
\\s*
([\\*_]?[\\w\\-]+) # 2 = property (and maybe IE filter)
\\s*
:
\\s*
(\\b|[#\'"-]) # 3 = first character of a value
/x', '$1$2:$3', $css);
// remove ws in selectors
$css = preg_replace_callback('/
(?: # non-capture
\\s*
[^~>+,\\s]+ # selector part
\\s*
[,>+~] # combinators
)+
\\s*
[^~>+,\\s]+ # selector part
{ # open declaration block
/x'
,array($this, '_selectorsCB'), $css);
// minimize hex colors
$css = preg_replace('/([^=])#([a-f\\d])\\2([a-f\\d])\\3([a-f\\d])\\4([\\s;\\}])/i'
, '$1#$2$3$4$5', $css);
// remove spaces between font families
$css = preg_replace_callback('/font-family:([^;}]+)([;}])/'
,array($this, '_fontFamilyCB'), $css);
$css = preg_replace('/@import\\s+url/', '@import url', $css);
// replace any ws involving newlines with a single newline
$css = preg_replace('/[ \\t]*\\n+\\s*/', "\n", $css);
// separate common descendent selectors w/ newlines (to limit line lengths)
$css = preg_replace('/([\\w#\\.\\*]+)\\s+([\\w#\\.\\*]+){/', "$1\n$2{", $css);
// Use newline after 1st numeric value (to limit line lengths).
$css = preg_replace('/
((?:padding|margin|border|outline):\\d+(?:px|em)?) # 1 = prop : 1st numeric value
\\s+
/x'
,"$1\n", $css);
// prevent triggering IE6 bug: http://www.crankygeek.com/ie6pebug/
$css = preg_replace('/:first-l(etter|ine)\\{/', ':first-l$1 {', $css);
return trim($css);
}
/**
* Replace what looks like a set of selectors
*
* @param array $m regex matches
*
* @return string
*/
protected function _selectorsCB($m)
{
// remove ws around the combinators
return preg_replace('/\\s*([,>+~])\\s*/', '$1', $m[0]);
}
/**
* Process a comment and return a replacement
*
* @param array $m regex matches
*
* @return string
*/
protected function _commentCB($m)
{
$hasSurroundingWs = (trim($m[0]) !== $m[1]);
$m = $m[1];
// $m is the comment content w/o the surrounding tokens,
// but the return value will replace the entire comment.
if ($m === 'keep') {
return '/**/';
}
if ($m === '" "') {
// component of http://tantek.com/CSS/Examples/midpass.html
return '/*" "*/';
}
if (preg_match('@";\\}\\s*\\}/\\*\\s+@', $m)) {
// component of http://tantek.com/CSS/Examples/midpass.html
return '/*";}}/* */';
}
if ($this->_inHack) {
// inversion: feeding only to one browser
if (preg_match('@
^/ # comment started like /*/
\\s*
(\\S[\\s\\S]+?) # has at least some non-ws content
\\s*
/\\* # ends like /*/ or /**/
@x', $m, $n)) {
// end hack mode after this comment, but preserve the hack and comment content
$this->_inHack = false;
return "/*/{$n[1]}/**/";
}
}
if (substr($m, -1) === '\\') { // comment ends like \*/
// begin hack mode and preserve hack
$this->_inHack = true;
return '/*\\*/';
}
if ($m !== '' && $m[0] === '/') { // comment looks like /*/ foo */
// begin hack mode and preserve hack
$this->_inHack = true;
return '/*/*/';
}
if ($this->_inHack) {
// a regular comment ends hack mode but should be preserved
$this->_inHack = false;
return '/**/';
}
// Issue 107: if there's any surrounding whitespace, it may be important, so
// replace the comment with a single space
return $hasSurroundingWs // remove all other comments
? ' '
: '';
}
/**
* Process a font-family listing and return a replacement
*
* @param array $m regex matches
*
* @return string
*/
protected function _fontFamilyCB($m)
{
// Issue 210: must not eliminate WS between words in unquoted families
$pieces = preg_split('/(\'[^\']+\'|"[^"]+")/', $m[1], null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$out = 'font-family:';
while (null !== ($piece = array_shift($pieces))) {
if ($piece[0] !== '"' && $piece[0] !== "'") {
$piece = preg_replace('/\\s+/', ' ', $piece);
$piece = preg_replace('/\\s?,\\s?/', ',', $piece);
}
$out .= $piece;
}
return $out . $m[2];
}
}
PK ^GM&|&