Ask your WordPress questions! Pay money and get answers fast! (more info)

Problem signing into admin area after woocommerce upgrade WordPress

  • SOLVED

I am having an issue signing into my Admin area of Wordpress. I receive this error. I believe we just updated Wordpress recently. I have tried uploading a previous version of wordpress via ftp and renaming files but this just gives even more error codes

here is the site http://stormyweatherwine.com/


Fatal error: Call to undefined method CSSMin::minify() in /home/content/45/9778945/html/wp-content/plugins/woocommerce/includes/admin/wc-admin-functions.php on line 186

This is line 186 from the wc-admin-functions.php

$compiled_css = CssMin::minify( $compiled_css );


Any thoughts?

Answers (4)

2014-08-18

Navjot Singh answers:

Can you paste your theme's function.php file?


movino4me comments:

<?php
/**
* Main WordPress API
*
* @package WordPress
*/

require( ABSPATH . WPINC . '/option.php' );

/**
* Converts given date string into a different format.
*
* $format should be either a PHP date format string, e.g. 'U' for a Unix
* timestamp, or 'G' for a Unix timestamp assuming that $date is GMT.
*
* If $translate is true then the given date and format string will
* be passed to date_i18n() for translation.
*
* @since 0.71
*
* @param string $format Format of the date to return.
* @param string $date Date string to convert.
* @param bool $translate Whether the return date should be translated. Default is true.
* @return string|int Formatted date string, or Unix timestamp.
*/
function mysql2date( $format, $date, $translate = true ) {
if ( empty( $date ) )
return false;

if ( 'G' == $format )
return strtotime( $date . ' +0000' );

$i = strtotime( $date );

if ( 'U' == $format )
return $i;

if ( $translate )
return date_i18n( $format, $i );
else
return date( $format, $i );
}

/**
* Retrieve the current time based on specified type.
*
* The 'mysql' type will return the time in the format for MySQL DATETIME field.
* The 'timestamp' type will return the current timestamp.
* Other strings will be interpreted as PHP date formats (e.g. 'Y-m-d').
*
* If $gmt is set to either '1' or 'true', then both types will use GMT time.
* if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
*
* @since 1.0.0
*
* @param string $type 'mysql', 'timestamp', or PHP date format string (e.g. 'Y-m-d').
* @param int|bool $gmt Optional. Whether to use GMT timezone. Default is false.
* @return int|string String if $type is 'gmt', int if $type is 'timestamp'.
*/
function current_time( $type, $gmt = 0 ) {
switch ( $type ) {
case 'mysql':
return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) ) );
break;
case 'timestamp':
return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
break;
default:
return ( $gmt ) ? date( $type ) : date( $type, time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) );
break;
}
}

/**
* Retrieve the date in localized format, based on timestamp.
*
* If the locale specifies the locale month and weekday, then the locale will
* take over the format for the date. If it isn't, then the date format string
* will be used instead.
*
* @since 0.71
*
* @param string $dateformatstring Format to display the date.
* @param int $unixtimestamp Optional. Unix timestamp.
* @param bool $gmt Optional, default is false. Whether to convert to GMT for time.
* @return string The date, translated if locale specifies it.
*/
function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
global $wp_locale;
$i = $unixtimestamp;

if ( false === $i ) {
if ( ! $gmt )
$i = current_time( 'timestamp' );
else
$i = time();
// we should not let date() interfere with our
// specially computed timestamp
$gmt = true;
}

// store original value for language with untypical grammars
// see http://core.trac.wordpress.org/ticket/9396
$req_format = $dateformatstring;

$datefunc = $gmt? 'gmdate' : 'date';

if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
$datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
$datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
$dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
$dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
$datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
$datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
$dateformatstring = ' '.$dateformatstring;
$dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
$dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
$dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
$dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
$dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
$dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );

$dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
}
$timezone_formats = array( 'P', 'I', 'O', 'T', 'Z', 'e' );
$timezone_formats_re = implode( '|', $timezone_formats );
if ( preg_match( "/$timezone_formats_re/", $dateformatstring ) ) {
$timezone_string = get_option( 'timezone_string' );
if ( $timezone_string ) {
$timezone_object = timezone_open( $timezone_string );
$date_object = date_create( null, $timezone_object );
foreach( $timezone_formats as $timezone_format ) {
if ( false !== strpos( $dateformatstring, $timezone_format ) ) {
$formatted = date_format( $date_object, $timezone_format );
$dateformatstring = ' '.$dateformatstring;
$dateformatstring = preg_replace( "/([^\\\])$timezone_format/", "\\1" . backslashit( $formatted ), $dateformatstring );
$dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
}
}
}
}
$j = @$datefunc( $dateformatstring, $i );

/**
* Filter the date formatted based on the locale.
*
* @since 2.8.0
*
* @param string $j Formatted date string.
* @param string $req_format Format to display the date.
* @param int $i Unix timestamp.
* @param bool $gmt Whether to convert to GMT for time. Default false.
*/
$j = apply_filters( 'date_i18n', $j, $req_format, $i, $gmt );
return $j;
}

/**
* Convert integer number to format based on the locale.
*
* @since 2.3.0
*
* @param int $number The number to convert based on locale.
* @param int $decimals Precision of the number of decimal places.
* @return string Converted number in string format.
*/
function number_format_i18n( $number, $decimals = 0 ) {
global $wp_locale;
$formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );

/**
* Filter the number formatted based on the locale.
*
* @since 2.8.0
*
* @param string $formatted Converted number in string format.
*/
return apply_filters( 'number_format_i18n', $formatted );
}

/**
* Convert number of bytes largest unit bytes will fit into.
*
* It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
* number of bytes to human readable number by taking the number of that unit
* that the bytes will go into it. Supports TB value.
*
* Please note that integers in PHP are limited to 32 bits, unless they are on
* 64 bit architecture, then they have 64 bit size. If you need to place the
* larger size then what PHP integer type will hold, then use a string. It will
* be converted to a double, which should always have 64 bit length.
*
* Technically the correct unit names for powers of 1024 are KiB, MiB etc.
* @link http://en.wikipedia.org/wiki/Byte
*
* @since 2.3.0
*
* @param int|string $bytes Number of bytes. Note max integer size for integers.
* @param int $decimals Precision of number of decimal places. Deprecated.
* @return bool|string False on failure. Number string on success.
*/
function size_format( $bytes, $decimals = 0 ) {
$quant = array(
// ========================= Origin ====
'TB' => 1099511627776, // pow( 1024, 4)
'GB' => 1073741824, // pow( 1024, 3)
'MB' => 1048576, // pow( 1024, 2)
'kB' => 1024, // pow( 1024, 1)
'B ' => 1, // pow( 1024, 0)
);
foreach ( $quant as $unit => $mag )
if ( doubleval($bytes) >= $mag )
return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;

return false;
}

/**
* Get the week start and end from the datetime or date string from mysql.
*
* @since 0.71
*
* @param string $mysqlstring Date or datetime field type from mysql.
* @param int $start_of_week Optional. Start of the week as an integer.
* @return array Keys are 'start' and 'end'.
*/
function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
$my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
$mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
$md = substr( $mysqlstring, 5, 2 ); // Mysql string day
$day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day.
$weekday = date( 'w', $day ); // The day of the week from the timestamp
if ( !is_numeric($start_of_week) )
$start_of_week = get_option( 'start_of_week' );

if ( $weekday < $start_of_week )
$weekday += 7;

$start = $day - DAY_IN_SECONDS * ( $weekday - $start_of_week ); // The most recent week start day on or before $day
$end = $start + 7 * DAY_IN_SECONDS - 1; // $start + 7 days - 1 second
return compact( 'start', 'end' );
}

/**
* Unserialize value only if it was serialized.
*
* @since 2.0.0
*
* @param string $original Maybe unserialized original, if is needed.
* @return mixed Unserialized data can be any type.
*/
function maybe_unserialize( $original ) {
if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
return @unserialize( $original );
return $original;
}

/**
* Check value to find if it was serialized.
*
* If $data is not an string, then returned value will always be false.
* Serialized data is always a string.
*
* @since 2.0.5
*
* @param mixed $data Value to check to see if was serialized.
* @param bool $strict Optional. Whether to be strict about the end of the string. Defaults true.
* @return bool False if not serialized and true if it was.
*/
function is_serialized( $data, $strict = true ) {
// if it isn't a string, it isn't serialized
if ( ! is_string( $data ) ) {
return false;
}
$data = trim( $data );
if ( 'N;' == $data ) {
return true;
}
if ( strlen( $data ) < 4 ) {
return false;
}
if ( ':' !== $data[1] ) {
return false;
}
if ( $strict ) {
$lastc = substr( $data, -1 );
if ( ';' !== $lastc && '}' !== $lastc ) {
return false;
}
} else {
$semicolon = strpos( $data, ';' );
$brace = strpos( $data, '}' );
// Either ; or } must exist.
if ( false === $semicolon && false === $brace )
return false;
// But neither must be in the first X characters.
if ( false !== $semicolon && $semicolon < 3 )
return false;
if ( false !== $brace && $brace < 4 )
return false;
}
$token = $data[0];
switch ( $token ) {
case 's' :
if ( $strict ) {
if ( '"' !== substr( $data, -2, 1 ) ) {
return false;
}
} elseif ( false === strpos( $data, '"' ) ) {
return false;
}
// or else fall through
case 'a' :
case 'O' :
return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
case 'b' :
case 'i' :
case 'd' :
$end = $strict ? '$' : '';
return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data );
}
return false;
}

/**
* Check whether serialized data is of string type.
*
* @since 2.0.5
*
* @param mixed $data Serialized data
* @return bool False if not a serialized string, true if it is.
*/
function is_serialized_string( $data ) {
// if it isn't a string, it isn't a serialized string
if ( ! is_string( $data ) ) {
return false;
}
$data = trim( $data );
if ( strlen( $data ) < 4 ) {
return false;
} elseif ( ':' !== $data[1] ) {
return false;
} elseif ( ';' !== substr( $data, -1 ) ) {
return false;
} elseif ( $data[0] !== 's' ) {
return false;
} elseif ( '"' !== substr( $data, -2, 1 ) ) {
return false;
} else {
return true;
}
}

/**
* Serialize data, if needed.
*
* @since 2.0.5
*
* @param mixed $data Data that might be serialized.
* @return mixed A scalar data
*/
function maybe_serialize( $data ) {
if ( is_array( $data ) || is_object( $data ) )
return serialize( $data );

// Double serialization is required for backward compatibility.
// See http://core.trac.wordpress.org/ticket/12930
if ( is_serialized( $data, false ) )
return serialize( $data );

return $data;
}

/**
* Retrieve post title from XMLRPC XML.
*
* If the title element is not part of the XML, then the default post title from
* the $post_default_title will be used instead.
*
* @since 0.71
*
* @global string $post_default_title Default XMLRPC post title.
*
* @param string $content XMLRPC XML Request content
* @return string Post title
*/
function xmlrpc_getposttitle( $content ) {
global $post_default_title;
if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
$post_title = $matchtitle[1];
} else {
$post_title = $post_default_title;
}
return $post_title;
}

/**
* Retrieve the post category or categories from XMLRPC XML.
*
* If the category element is not found, then the default post category will be
* used. The return type then would be what $post_default_category. If the
* category is found, then it will always be an array.
*
* @since 0.71
*
* @global string $post_default_category Default XMLRPC post category.
*
* @param string $content XMLRPC XML Request content
* @return string|array List of categories or category name.
*/
function xmlrpc_getpostcategory( $content ) {
global $post_default_category;
if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
$post_category = trim( $matchcat[1], ',' );
$post_category = explode( ',', $post_category );
} else {
$post_category = $post_default_category;
}
return $post_category;
}

/**
* XMLRPC XML content without title and category elements.
*
* @since 0.71
*
* @param string $content XMLRPC XML Request content
* @return string XMLRPC XML Request content without title and category elements.
*/
function xmlrpc_removepostdata( $content ) {
$content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
$content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
$content = trim( $content );
return $content;
}

/**
* Use RegEx to extract URLs from arbitrary content
*
* @since 3.7.0
*
* @param string $content
* @return array URLs found in passed string
*/
function wp_extract_urls( $content ) {
preg_match_all(
"#((?:[\w-]+://?|[\w\d]+[.])[^\s()<>]+[.](?:\([\w\d]+\)|(?:[^`!()\[\]{};:'\".,<>?«»“”‘’\s]|(?:[:]\d+)?/?)+))#",
$content,
$post_links
);

$post_links = array_unique( array_map( 'html_entity_decode', $post_links[0] ) );

return array_values( $post_links );
}

/**
* Check content for video and audio links to add as enclosures.
*
* Will not add enclosures that have already been added and will
* remove enclosures that are no longer in the post. This is called as
* pingbacks and trackbacks.
*
* @since 1.5.0
*
* @uses $wpdb
*
* @param string $content Post Content
* @param int $post_ID Post ID
*/
function do_enclose( $content, $post_ID ) {
global $wpdb;

//TODO: Tidy this ghetto code up and make the debug code optional
include_once( ABSPATH . WPINC . '/class-IXR.php' );

$post_links = array();

$pung = get_enclosed( $post_ID );

$post_links_temp = wp_extract_urls( $content );

foreach ( $pung as $link_test ) {
if ( ! in_array( $link_test, $post_links_temp ) ) { // link no longer in post
$mids = $wpdb->get_col( $wpdb->prepare("SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $link_test ) . '%') );
foreach ( $mids as $mid )
delete_metadata_by_mid( 'post', $mid );
}
}

foreach ( (array) $post_links_temp as $link_test ) {
if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
$test = @parse_url( $link_test );
if ( false === $test )
continue;
if ( isset( $test['query'] ) )
$post_links[] = $link_test;
elseif ( isset($test['path']) && ( $test['path'] != '/' ) && ($test['path'] != '' ) )
$post_links[] = $link_test;
}
}

foreach ( (array) $post_links as $url ) {
if ( $url != '' && !$wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $url ) . '%' ) ) ) {

if ( $headers = wp_get_http_headers( $url) ) {
$len = isset( $headers['content-length'] ) ? (int) $headers['content-length'] : 0;
$type = isset( $headers['content-type'] ) ? $headers['content-type'] : '';
$allowed_types = array( 'video', 'audio' );

// Check to see if we can figure out the mime type from
// the extension
$url_parts = @parse_url( $url );
if ( false !== $url_parts ) {
$extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION );
if ( !empty( $extension ) ) {
foreach ( wp_get_mime_types() as $exts => $mime ) {
if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
$type = $mime;
break;
}
}
}
}

if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
add_post_meta( $post_ID, 'enclosure', "$url\n$len\n$mime\n" );
}
}
}
}
}

/**
* Perform a HTTP HEAD or GET request.
*
* If $file_path is a writable filename, this will do a GET request and write
* the file to that path.
*
* @since 2.5.0
*
* @param string $url URL to fetch.
* @param string|bool $file_path Optional. File path to write request to.
* @param int $red (private) The number of Redirects followed, Upon 5 being hit, returns false.
* @return bool|string False on failure and string of headers if HEAD request.
*/
function wp_get_http( $url, $file_path = false, $red = 1 ) {
@set_time_limit( 60 );

if ( $red > 5 )
return false;

$options = array();
$options['redirection'] = 5;

if ( false == $file_path )
$options['method'] = 'HEAD';
else
$options['method'] = 'GET';

$response = wp_safe_remote_request( $url, $options );

if ( is_wp_error( $response ) )
return false;

$headers = wp_remote_retrieve_headers( $response );
$headers['response'] = wp_remote_retrieve_response_code( $response );

// WP_HTTP no longer follows redirects for HEAD requests.
if ( 'HEAD' == $options['method'] && in_array($headers['response'], array(301, 302)) && isset( $headers['location'] ) ) {
return wp_get_http( $headers['location'], $file_path, ++$red );
}

if ( false == $file_path )
return $headers;

// GET request - write it to the supplied filename
$out_fp = fopen($file_path, 'w');
if ( !$out_fp )
return $headers;

fwrite( $out_fp, wp_remote_retrieve_body( $response ) );
fclose($out_fp);
clearstatcache();

return $headers;
}

/**
* Retrieve HTTP Headers from URL.
*
* @since 1.5.1
*
* @param string $url
* @param bool $deprecated Not Used.
* @return bool|string False on failure, headers on success.
*/
function wp_get_http_headers( $url, $deprecated = false ) {
if ( !empty( $deprecated ) )
_deprecated_argument( __FUNCTION__, '2.7' );

$response = wp_safe_remote_head( $url );

if ( is_wp_error( $response ) )
return false;

return wp_remote_retrieve_headers( $response );
}

/**
* Whether today is a new day.
*
* @since 0.71
* @uses $day Today
* @uses $previousday Previous day
*
* @return int 1 when new day, 0 if not a new day.
*/
function is_new_day() {
global $currentday, $previousday;
if ( $currentday != $previousday )
return 1;
else
return 0;
}

/**
* Build URL query based on an associative and, or indexed array.
*
* This is a convenient function for easily building url queries. It sets the
* separator to '&' and uses _http_build_query() function.
*
* @see _http_build_query() Used to build the query
* @link http://us2.php.net/manual/en/function.http-build-query.php more on what
* http_build_query() does.
*
* @since 2.3.0
*
* @param array $data URL-encode key/value pairs.
* @return string URL encoded string
*/
function build_query( $data ) {
return _http_build_query( $data, null, '&', '', false );
}

// from php.net (modified by Mark Jaquith to behave like the native PHP5 function)
function _http_build_query($data, $prefix=null, $sep=null, $key='', $urlencode=true) {
$ret = array();

foreach ( (array) $data as $k => $v ) {
if ( $urlencode)
$k = urlencode($k);
if ( is_int($k) && $prefix != null )
$k = $prefix.$k;
if ( !empty($key) )
$k = $key . '%5B' . $k . '%5D';
if ( $v === null )
continue;
elseif ( $v === FALSE )
$v = '0';

if ( is_array($v) || is_object($v) )
array_push($ret,_http_build_query($v, '', $sep, $k, $urlencode));
elseif ( $urlencode )
array_push($ret, $k.'='.urlencode($v));
else
array_push($ret, $k.'='.$v);
}

if ( null === $sep )
$sep = ini_get('arg_separator.output');

return implode($sep, $ret);
}

/**
* Retrieve a modified URL query string.
*
* You can rebuild the URL and append a new query variable to the URL query by
* using this function. You can also retrieve the full URL with query data.
*
* Adding a single key & value or an associative array. Setting a key value to
* an empty string removes the key. Omitting oldquery_or_uri uses the $_SERVER
* value. Additional values provided are expected to be encoded appropriately
* with urlencode() or rawurlencode().
*
* @since 1.5.0
*
* @param mixed $param1 Either newkey or an associative_array
* @param mixed $param2 Either newvalue or oldquery or uri
* @param mixed $param3 Optional. Old query or uri
* @return string New URL query string.
*/
function add_query_arg() {
$ret = '';
$args = func_get_args();
if ( is_array( $args[0] ) ) {
if ( count( $args ) < 2 || false === $args[1] )
$uri = $_SERVER['REQUEST_URI'];
else
$uri = $args[1];
} else {
if ( count( $args ) < 3 || false === $args[2] )
$uri = $_SERVER['REQUEST_URI'];
else
$uri = $args[2];
}

if ( $frag = strstr( $uri, '#' ) )
$uri = substr( $uri, 0, -strlen( $frag ) );
else
$frag = '';

if ( 0 === stripos( $uri, 'http://' ) ) {
$protocol = 'http://';
$uri = substr( $uri, 7 );
} elseif ( 0 === stripos( $uri, 'https://' ) ) {
$protocol = 'https://';
$uri = substr( $uri, 8 );
} else {
$protocol = '';
}

if ( strpos( $uri, '?' ) !== false ) {
list( $base, $query ) = explode( '?', $uri, 2 );
$base .= '?';
} elseif ( $protocol || strpos( $uri, '=' ) === false ) {
$base = $uri . '?';
$query = '';
} else {
$base = '';
$query = $uri;
}

wp_parse_str( $query, $qs );
$qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
if ( is_array( $args[0] ) ) {
$kayvees = $args[0];
$qs = array_merge( $qs, $kayvees );
} else {
$qs[ $args[0] ] = $args[1];
}

foreach ( $qs as $k => $v ) {
if ( $v === false )
unset( $qs[$k] );
}

$ret = build_query( $qs );
$ret = trim( $ret, '?' );
$ret = preg_replace( '#=(&|$)#', '$1', $ret );
$ret = $protocol . $base . $ret . $frag;
$ret = rtrim( $ret, '?' );
return $ret;
}

/**
* Removes an item or list from the query string.
*
* @since 1.5.0
*
* @param string|array $key Query key or keys to remove.
* @param bool $query When false uses the $_SERVER value.
* @return string New URL query string.
*/
function remove_query_arg( $key, $query=false ) {
if ( is_array( $key ) ) { // removing multiple keys
foreach ( $key as $k )
$query = add_query_arg( $k, false, $query );
return $query;
}
return add_query_arg( $key, false, $query );
}

/**
* Walks the array while sanitizing the contents.
*
* @since 0.71
*
* @param array $array Array to walk while sanitizing contents.
* @return array Sanitized $array.
*/
function add_magic_quotes( $array ) {
foreach ( (array) $array as $k => $v ) {
if ( is_array( $v ) ) {
$array[$k] = add_magic_quotes( $v );
} else {
$array[$k] = addslashes( $v );
}
}
return $array;
}

/**
* HTTP request for URI to retrieve content.
*
* @since 1.5.1
* @uses wp_remote_get()
*
* @param string $uri URI/URL of web page to retrieve.
* @return bool|string HTTP content. False on failure.
*/
function wp_remote_fopen( $uri ) {
$parsed_url = @parse_url( $uri );

if ( !$parsed_url || !is_array( $parsed_url ) )
return false;

$options = array();
$options['timeout'] = 10;

$response = wp_safe_remote_get( $uri, $options );

if ( is_wp_error( $response ) )
return false;

return wp_remote_retrieve_body( $response );
}

/**
* Set up the WordPress query.
*
* @since 2.0.0
*
* @param string $query_vars Default WP_Query arguments.
*/
function wp( $query_vars = '' ) {
global $wp, $wp_query, $wp_the_query;
$wp->main( $query_vars );

if ( !isset($wp_the_query) )
$wp_the_query = $wp_query;
}

/**
* Retrieve the description for the HTTP status.
*
* @since 2.3.0
*
* @param int $code HTTP status code.
* @return string Empty string if not found, or description if found.
*/
function get_status_header_desc( $code ) {
global $wp_header_to_desc;

$code = absint( $code );

if ( !isset( $wp_header_to_desc ) ) {
$wp_header_to_desc = array(
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',

200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
226 => 'IM Used',

300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => 'Reserved',
307 => 'Temporary Redirect',

400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
418 => 'I\'m a teapot',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
428 => 'Precondition Required',
429 => 'Too Many Requests',
431 => 'Request Header Fields Too Large',

500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
510 => 'Not Extended',
511 => 'Network Authentication Required',
);
}

if ( isset( $wp_header_to_desc[$code] ) )
return $wp_header_to_desc[$code];
else
return '';
}

/**
* Set HTTP status header.
*
* @since 2.0.0
* @see get_status_header_desc()
*
* @param int $code HTTP status code.
*/
function status_header( $code ) {
$description = get_status_header_desc( $code );

if ( empty( $description ) )
return;

$protocol = $_SERVER['SERVER_PROTOCOL'];
if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
$protocol = 'HTTP/1.0';
$status_header = "$protocol $code $description";
if ( function_exists( 'apply_filters' ) )

/**
* Filter an HTTP status header.
*
* @since 2.2.0
*
* @param string $status_header HTTP status header.
* @param int $code HTTP status code.
* @param string $description Description for the status code.
* @param string $protocol Server protocol.
*/
$status_header = apply_filters( 'status_header', $status_header, $code, $description, $protocol );

@header( $status_header, true, $code );
}

/**
* Gets the header information to prevent caching.
*
* The several different headers cover the different ways cache prevention is handled
* by different browsers
*
* @since 2.8.0
*
* @return array The associative array of header names and field values.
*/
function wp_get_nocache_headers() {
$headers = array(
'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
'Pragma' => 'no-cache',
);

if ( function_exists('apply_filters') ) {
/**
* Filter the cache-controlling headers.
*
* @since 2.8.0
*
* @param array $headers {
* Header names and field values.
*
* @type string $Expires Expires header.
* @type string $Cache-Control Cache-Control header.
* @type string $Pragma Pragma header.
* }
*/
$headers = (array) apply_filters( 'nocache_headers', $headers );
}
$headers['Last-Modified'] = false;
return $headers;
}

/**
* Sets the headers to prevent caching for the different browsers.
*
* Different browsers support different nocache headers, so several headers must
* be sent so that all of them get the point that no caching should occur.
*
* @since 2.0.0
* @see wp_get_nocache_headers()
*/
function nocache_headers() {
$headers = wp_get_nocache_headers();

unset( $headers['Last-Modified'] );

// In PHP 5.3+, make sure we are not sending a Last-Modified header.
if ( function_exists( 'header_remove' ) ) {
@header_remove( 'Last-Modified' );
} else {
// In PHP 5.2, send an empty Last-Modified header, but only as a
// last resort to override a header already sent. #WP23021
foreach ( headers_list() as $header ) {
if ( 0 === stripos( $header, 'Last-Modified' ) ) {
$headers['Last-Modified'] = '';
break;
}
}
}

foreach( $headers as $name => $field_value )
@header("{$name}: {$field_value}");
}

/**
* Set the headers for caching for 10 days with JavaScript content type.
*
* @since 2.1.0
*/
function cache_javascript_headers() {
$expiresOffset = 10 * DAY_IN_SECONDS;
header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
header( "Vary: Accept-Encoding" ); // Handle proxies
header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
}

/**
* Retrieve the number of database queries during the WordPress execution.
*
* @since 2.0.0
*
* @return int Number of database queries
*/
function get_num_queries() {
global $wpdb;
return $wpdb->num_queries;
}

/**
* Whether input is yes or no. Must be 'y' to be true.
*
* @since 1.0.0
*
* @param string $yn Character string containing either 'y' or 'n'
* @return bool True if yes, false on anything else
*/
function bool_from_yn( $yn ) {
return ( strtolower( $yn ) == 'y' );
}

/**
* Loads the feed template from the use of an action hook.
*
* If the feed action does not have a hook, then the function will die with a
* message telling the visitor that the feed is not valid.
*
* It is better to only have one hook for each feed.
*
* @since 2.1.0
*
* @uses $wp_query Used to tell if the use a comment feed.
*/
function do_feed() {
global $wp_query;

$feed = get_query_var( 'feed' );

// Remove the pad, if present.
$feed = preg_replace( '/^_+/', '', $feed );

if ( $feed == '' || $feed == 'feed' )
$feed = get_default_feed();

$hook = 'do_feed_' . $feed;
if ( ! has_action( $hook ) )
wp_die( __( 'ERROR: This is not a valid feed template.' ), '', array( 'response' => 404 ) );

/**
* Fires once the given feed is loaded.
*
* The dynamic hook name, $hook, refers to the feed name.
*
* @since 2.1.0
*
* @param bool $is_comment_feed Whether the feed is a comment feed.
*/
do_action( $hook, $wp_query->is_comment_feed );
}

/**
* Load the RDF RSS 0.91 Feed template.
*
* @since 2.1.0
*/
function do_feed_rdf() {
load_template( ABSPATH . WPINC . '/feed-rdf.php' );
}

/**
* Load the RSS 1.0 Feed Template.
*
* @since 2.1.0
*/
function do_feed_rss() {
load_template( ABSPATH . WPINC . '/feed-rss.php' );
}

/**
* Load either the RSS2 comment feed or the RSS2 posts feed.
*
* @since 2.1.0
*
* @param bool $for_comments True for the comment feed, false for normal feed.
*/
function do_feed_rss2( $for_comments ) {
if ( $for_comments )
load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
else
load_template( ABSPATH . WPINC . '/feed-rss2.php' );
}

/**
* Load either Atom comment feed or Atom posts feed.
*
* @since 2.1.0
*
* @param bool $for_comments True for the comment feed, false for normal feed.
*/
function do_feed_atom( $for_comments ) {
if ($for_comments)
load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
else
load_template( ABSPATH . WPINC . '/feed-atom.php' );
}

/**
* Display the robots.txt file content.
*
* The echo content should be with usage of the permalinks or for creating the
* robots.txt file.
*
* @since 2.1.0
*/
function do_robots() {
header( 'Content-Type: text/plain; charset=utf-8' );

/**
* Fires when displaying the robots.txt file.
*
* @since 2.1.0
*/
do_action( 'do_robotstxt' );

$output = "User-agent: *\n";
$public = get_option( 'blog_public' );
if ( '0' == $public ) {
$output .= "Disallow: /\n";
} else {
$site_url = parse_url( site_url() );
$path = ( !empty( $site_url['path'] ) ) ? $site_url['path'] : '';
$output .= "Disallow: $path/wp-admin/\n";
$output .= "Disallow: $path/wp-includes/\n";
}

/**
* Filter the robots.txt output.
*
* @since 3.0.0
*
* @param string $output Robots.txt output.
* @param bool $public Whether the site is considered "public".
*/
echo apply_filters( 'robots_txt', $output, $public );
}

/**
* Test whether blog is already installed.
*
* The cache will be checked first. If you have a cache plugin, which saves the
* cache values, then this will work. If you use the default WordPress cache,
* and the database goes away, then you might have problems.
*
* Checks for the option siteurl for whether WordPress is installed.
*
* @since 2.1.0
* @uses $wpdb
*
* @return bool Whether blog is already installed.
*/
function is_blog_installed() {
global $wpdb;

// Check cache first. If options table goes away and we have true cached, oh well.
if ( wp_cache_get( 'is_blog_installed' ) )
return true;

$suppress = $wpdb->suppress_errors();
if ( ! defined( 'WP_INSTALLING' ) ) {
$alloptions = wp_load_alloptions();
}
// If siteurl is not set to autoload, check it specifically
if ( !isset( $alloptions['siteurl'] ) )
$installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
else
$installed = $alloptions['siteurl'];
$wpdb->suppress_errors( $suppress );

$installed = !empty( $installed );
wp_cache_set( 'is_blog_installed', $installed );

if ( $installed )
return true;

// If visiting repair.php, return true and let it take over.
if ( defined( 'WP_REPAIRING' ) )
return true;

$suppress = $wpdb->suppress_errors();

// Loop over the WP tables. If none exist, then scratch install is allowed.
// If one or more exist, suggest table repair since we got here because the options
// table could not be accessed.
$wp_tables = $wpdb->tables();
foreach ( $wp_tables as $table ) {
// The existence of custom user tables shouldn't suggest an insane state or prevent a clean install.
if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table )
continue;
if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table )
continue;

if ( ! $wpdb->get_results( "DESCRIBE $table;" ) )
continue;

// One or more tables exist. We are insane.

wp_load_translations_early();

// Die with a DB error.
$wpdb->error = sprintf( __( 'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.' ), 'maint/repair.php?referrer=is_blog_installed' );
dead_db();
}

$wpdb->suppress_errors( $suppress );

wp_cache_set( 'is_blog_installed', false );

return false;
}

/**
* Retrieve URL with nonce added to URL query.
*
* @since 2.0.4
*
* @param string $actionurl URL to add nonce action.
* @param string $action Optional. Nonce action name.
* @param string $name Optional. Nonce name.
* @return string Escaped URL with nonce action added.
*/
function wp_nonce_url( $actionurl, $action = -1, $name = '_wpnonce' ) {
$actionurl = str_replace( '&amp;', '&', $actionurl );
return esc_html( add_query_arg( $name, wp_create_nonce( $action ), $actionurl ) );
}

/**
* Retrieve or display nonce hidden field for forms.
*
* The nonce field is used to validate that the contents of the form came from
* the location on the current site and not somewhere else. The nonce does not
* offer absolute protection, but should protect against most cases. It is very
* important to use nonce field in forms.
*
* The $action and $name are optional, but if you want to have better security,
* it is strongly suggested to set those two parameters. It is easier to just
* call the function without any parameters, because validation of the nonce
* doesn't require any parameters, but since crackers know what the default is
* it won't be difficult for them to find a way around your nonce and cause
* damage.
*
* The input name will be whatever $name value you gave. The input value will be
* the nonce creation value.
*
* @since 2.0.4
*
* @param string $action Optional. Action name.
* @param string $name Optional. Nonce name.
* @param bool $referer Optional, default true. Whether to set the referer field for validation.
* @param bool $echo Optional, default true. Whether to display or return hidden form field.
* @return string Nonce field.
*/
function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
$name = esc_attr( $name );
$nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';

if ( $referer )
$nonce_field .= wp_referer_field( false );

if ( $echo )
echo $nonce_field;

return $nonce_field;
}

/**
* Retrieve or display referer hidden field for forms.
*
* The referer link is the current Request URI from the server super global. The
* input name is '_wp_http_referer', in case you wanted to check manually.
*
* @since 2.0.4
*
* @param bool $echo Whether to echo or return the referer field.
* @return string Referer field.
*/
function wp_referer_field( $echo = true ) {
$referer_field = '<input type="hidden" name="_wp_http_referer" value="'. esc_attr( wp_unslash( $_SERVER['REQUEST_URI'] ) ) . '" />';

if ( $echo )
echo $referer_field;
return $referer_field;
}

/**
* Retrieve or display original referer hidden field for forms.
*
* The input name is '_wp_original_http_referer' and will be either the same
* value of {@link wp_referer_field()}, if that was posted already or it will
* be the current page, if it doesn't exist.
*
* @since 2.0.4
*
* @param bool $echo Whether to echo the original http referer
* @param string $jump_back_to Optional, default is 'current'. Can be 'previous' or page you want to jump back to.
* @return string Original referer field.
*/
function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
if ( ! $ref = wp_get_original_referer() ) {
$ref = 'previous' == $jump_back_to ? wp_get_referer() : wp_unslash( $_SERVER['REQUEST_URI'] );
}
$orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( $ref ) . '" />';
if ( $echo )
echo $orig_referer_field;
return $orig_referer_field;
}

/**
* Retrieve referer from '_wp_http_referer' or HTTP referer. If it's the same
* as the current request URL, will return false.
*
* @since 2.0.4
*
* @return string|bool False on failure. Referer URL on success.
*/
function wp_get_referer() {
if ( ! function_exists( 'wp_validate_redirect' ) )
return false;
$ref = false;
if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
$ref = wp_unslash( $_REQUEST['_wp_http_referer'] );
else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
$ref = wp_unslash( $_SERVER['HTTP_REFERER'] );

if ( $ref && $ref !== wp_unslash( $_SERVER['REQUEST_URI'] ) )
return wp_validate_redirect( $ref, false );
return false;
}

/**
* Retrieve original referer that was posted, if it exists.
*
* @since 2.0.4
*
* @return string|bool False if no original referer or original referer if set.
*/
function wp_get_original_referer() {
if ( ! empty( $_REQUEST['_wp_original_http_referer'] ) && function_exists( 'wp_validate_redirect' ) )
return wp_validate_redirect( wp_unslash( $_REQUEST['_wp_original_http_referer'] ), false );
return false;
}

/**
* Recursive directory creation based on full path.
*
* Will attempt to set permissions on folders.
*
* @since 2.0.1
*
* @param string $target Full path to attempt to create.
* @return bool Whether the path was created. True if path already exists.
*/
function wp_mkdir_p( $target ) {
$wrapper = null;

// strip the protocol
if( wp_is_stream( $target ) ) {
list( $wrapper, $target ) = explode( '://', $target, 2 );
}

// from php.net/mkdir user contributed notes
$target = str_replace( '//', '/', $target );

// put the wrapper back on the target
if( $wrapper !== null ) {
$target = $wrapper . '://' . $target;
}

// safe mode fails with a trailing slash under certain PHP versions.
$target = rtrim($target, '/'); // Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
if ( empty($target) )
$target = '/';

if ( file_exists( $target ) )
return @is_dir( $target );

// We need to find the permissions of the parent folder that exists and inherit that.
$target_parent = dirname( $target );
while ( '.' != $target_parent && ! is_dir( $target_parent ) ) {
$target_parent = dirname( $target_parent );
}

// Get the permission bits.
$dir_perms = false;
if ( $stat = @stat( $target_parent ) ) {
$dir_perms = $stat['mode'] & 0007777;
} else {
$dir_perms = 0777;
}

if ( @mkdir( $target, $dir_perms, true ) ) {

// If a umask is set that modifies $dir_perms, we'll have to re-set the $dir_perms correctly with chmod()
if ( $dir_perms != ( $dir_perms & ~umask() ) ) {
$folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) );
for ( $i = 1; $i <= count( $folder_parts ); $i++ ) {
@chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms );
}
}

return true;
}

return false;
}

/**
* Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows').
*
* @since 2.5.0
*
* @param string $path File path
* @return bool True if path is absolute, false is not absolute.
*/
function path_is_absolute( $path ) {
// this is definitive if true but fails if $path does not exist or contains a symbolic link
if ( realpath($path) == $path )
return true;

if ( strlen($path) == 0 || $path[0] == '.' )
return false;

// windows allows absolute paths like this
if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
return true;

// a path starting with / or \ is absolute; anything else is relative
return ( $path[0] == '/' || $path[0] == '\\' );
}

/**
* Join two filesystem paths together (e.g. 'give me $path relative to $base').
*
* If the $path is absolute, then it the full path is returned.
*
* @since 2.5.0
*
* @param string $base
* @param string $path
* @return string The path with the base or absolute path.
*/
function path_join( $base, $path ) {
if ( path_is_absolute($path) )
return $path;

return rtrim($base, '/') . '/' . ltrim($path, '/');
}

/**
* Normalize a filesystem path.
*
* Replaces backslashes with forward slashes for Windows systems,
* and ensures no duplicate slashes exist.
*
* @since 3.9.0
*
* @param string $path Path to normalize.
* @return string Normalized path.
*/
function wp_normalize_path( $path ) {
$path = str_replace( '\\', '/', $path );
$path = preg_replace( '|/+|','/', $path );
return $path;
}

/**
* Determines a writable directory for temporary files.
* Function's preference is the return value of sys_get_temp_dir(),
* followed by your PHP temporary upload directory, followed by WP_CONTENT_DIR,
* before finally defaulting to /tmp/
*
* In the event that this function does not find a writable location,
* It may be overridden by the WP_TEMP_DIR constant in
* your wp-config.php file.
*
* @since 2.5.0
*
* @return string Writable temporary directory
*/
function get_temp_dir() {
static $temp;
if ( defined('WP_TEMP_DIR') )
return trailingslashit(WP_TEMP_DIR);

if ( $temp )
return trailingslashit( $temp );

if ( function_exists('sys_get_temp_dir') ) {
$temp = sys_get_temp_dir();
if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
return trailingslashit( $temp );
}

$temp = ini_get('upload_tmp_dir');
if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
return trailingslashit( $temp );

$temp = WP_CONTENT_DIR . '/';
if ( is_dir( $temp ) && wp_is_writable( $temp ) )
return $temp;

$temp = '/tmp/';
return $temp;
}

/**
* Determine if a directory is writable.
*
* This function is used to work around certain ACL issues
* in PHP primarily affecting Windows Servers.
*
* @see win_is_writable()
*
* @since 3.6.0
*
* @param string $path
* @return bool
*/
function wp_is_writable( $path ) {
if ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) )
return win_is_writable( $path );
else
return @is_writable( $path );
}

/**
* Workaround for Windows bug in is_writable() function
*
* PHP has issues with Windows ACL's for determine if a
* directory is writable or not, this works around them by
* checking the ability to open files rather than relying
* upon PHP to interprate the OS ACL.
*
* @link http://bugs.php.net/bug.php?id=27609
* @link http://bugs.php.net/bug.php?id=30931
*
* @since 2.8.0
*
* @param string $path
* @return bool
*/
function win_is_writable( $path ) {

if ( $path[strlen( $path ) - 1] == '/' ) // if it looks like a directory, check a random file within the directory
return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp');
else if ( is_dir( $path ) ) // If it's a directory (and not a file) check a random file within the directory
return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' );

// check tmp file for read/write capabilities
$should_delete_tmp_file = !file_exists( $path );
$f = @fopen( $path, 'a' );
if ( $f === false )
return false;
fclose( $f );
if ( $should_delete_tmp_file )
unlink( $path );
return true;
}

/**
* Get an array containing the current upload directory's path and url.
*
* Checks the 'upload_path' option, which should be from the web root folder,
* and if it isn't empty it will be used. If it is empty, then the path will be
* 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
* override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
*
* The upload URL path is set either by the 'upload_url_path' option or by using
* the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
*
* If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
* the administration settings panel), then the time will be used. The format
* will be year first and then month.
*
* If the path couldn't be created, then an error will be returned with the key
* 'error' containing the error message. The error suggests that the parent
* directory is not writable by the server.
*
* On success, the returned array will have many indices:
* 'path' - base directory and sub directory or full path to upload directory.
* 'url' - base url and sub directory or absolute URL to upload directory.
* 'subdir' - sub directory if uploads use year/month folders option is on.
* 'basedir' - path without subdir.
* 'baseurl' - URL path without subdir.
* 'error' - set to false.
*
* @since 2.0.0
*
* @param string $time Optional. Time formatted in 'yyyy/mm'.
* @return array See above for description.
*/
function wp_upload_dir( $time = null ) {
$siteurl = get_option( 'siteurl' );
$upload_path = trim( get_option( 'upload_path' ) );

if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
$dir = WP_CONTENT_DIR . '/uploads';
} elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
// $dir is absolute, $upload_path is (maybe) relative to ABSPATH
$dir = path_join( ABSPATH, $upload_path );
} else {
$dir = $upload_path;
}

if ( !$url = get_option( 'upload_url_path' ) ) {
if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
$url = WP_CONTENT_URL . '/uploads';
else
$url = trailingslashit( $siteurl ) . $upload_path;
}

// Obey the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
// We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
$dir = ABSPATH . UPLOADS;
$url = trailingslashit( $siteurl ) . UPLOADS;
}

// If multisite (and if not the main site in a post-MU network)
if ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) {

if ( ! get_site_option( 'ms_files_rewriting' ) ) {
// If ms-files rewriting is disabled (networks created post-3.5), it is fairly straightforward:
// Append sites/%d if we're not on the main site (for post-MU networks). (The extra directory
// prevents a four-digit ID from conflicting with a year-based directory for the main site.
// But if a MU-era network has disabled ms-files rewriting manually, they don't need the extra
// directory, as they never had wp-content/uploads for the main site.)

if ( defined( 'MULTISITE' ) )
$ms_dir = '/sites/' . get_current_blog_id();
else
$ms_dir = '/' . get_current_blog_id();

$dir .= $ms_dir;
$url .= $ms_dir;

} elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
// Handle the old-form ms-files.php rewriting if the network still has that enabled.
// When ms-files rewriting is enabled, then we only listen to UPLOADS when:
// 1) we are not on the main site in a post-MU network,
// as wp-content/uploads is used there, and
// 2) we are not switched, as ms_upload_constants() hardcodes
// these constants to reflect the original blog ID.
//
// Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute.
// (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as
// as it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files
// rewriting in multisite, the resulting URL is /files. (#WP22702 for background.)

if ( defined( 'BLOGUPLOADDIR' ) )
$dir = untrailingslashit( BLOGUPLOADDIR );
else
$dir = ABSPATH . UPLOADS;
$url = trailingslashit( $siteurl ) . 'files';
}
}

$basedir = $dir;
$baseurl = $url;

$subdir = '';
if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
// Generate the yearly and monthly dirs
if ( !$time )
$time = current_time( 'mysql' );
$y = substr( $time, 0, 4 );
$m = substr( $time, 5, 2 );
$subdir = "/$y/$m";
}

$dir .= $subdir;
$url .= $subdir;

/**
* Filter the uploads directory data.
*
* @since 2.0.0
*
* @param array $uploads Array of upload directory data with keys of 'path',
* 'url', 'subdir, 'basedir', and 'error'.
*/
$uploads = apply_filters( 'upload_dir',
array(
'path' => $dir,
'url' => $url,
'subdir' => $subdir,
'basedir' => $basedir,
'baseurl' => $baseurl,
'error' => false,
) );

// Make sure we have an uploads dir
if ( ! wp_mkdir_p( $uploads['path'] ) ) {
if ( 0 === strpos( $uploads['basedir'], ABSPATH ) )
$error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
else
$error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];

$message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $error_path );
$uploads['error'] = $message;
}

return $uploads;
}

/**
* Get a filename that is sanitized and unique for the given directory.
*
* If the filename is not unique, then a number will be added to the filename
* before the extension, and will continue adding numbers until the filename is
* unique.
*
* The callback is passed three parameters, the first one is the directory, the
* second is the filename, and the third is the extension.
*
* @since 2.5.0
*
* @param string $dir
* @param string $filename
* @param mixed $unique_filename_callback Callback.
* @return string New filename, if given wasn't unique.
*/
function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
// sanitize the file name before we begin processing
$filename = sanitize_file_name($filename);

// separate the filename into a name and extension
$info = pathinfo($filename);
$ext = !empty($info['extension']) ? '.' . $info['extension'] : '';
$name = basename($filename, $ext);

// edge case: if file is named '.ext', treat as an empty name
if ( $name === $ext )
$name = '';

// Increment the file number until we have a unique file to save in $dir. Use callback if supplied.
if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
$filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
} else {
$number = '';

// change '.ext' to lower case
if ( $ext && strtolower($ext) != $ext ) {
$ext2 = strtolower($ext);
$filename2 = preg_replace( '|' . preg_quote($ext) . '$|', $ext2, $filename );

// check for both lower and upper case extension or image sub-sizes may be overwritten
while ( file_exists($dir . "/$filename") || file_exists($dir . "/$filename2") ) {
$new_number = $number + 1;
$filename = str_replace( "$number$ext", "$new_number$ext", $filename );
$filename2 = str_replace( "$number$ext2", "$new_number$ext2", $filename2 );
$number = $new_number;
}
return $filename2;
}

while ( file_exists( $dir . "/$filename" ) ) {
if ( '' == "$number$ext" )
$filename = $filename . ++$number . $ext;
else
$filename = str_replace( "$number$ext", ++$number . $ext, $filename );
}
}

return $filename;
}

/**
* Create a file in the upload folder with given content.
*
* If there is an error, then the key 'error' will exist with the error message.
* If success, then the key 'file' will have the unique file path, the 'url' key
* will have the link to the new file. and the 'error' key will be set to false.
*
* This function will not move an uploaded file to the upload folder. It will
* create a new file with the content in $bits parameter. If you move the upload
* file, read the content of the uploaded file, and then you can give the
* filename and content to this function, which will add it to the upload
* folder.
*
* The permissions will be set on the new file automatically by this function.
*
* @since 2.0.0
*
* @param string $name
* @param null $deprecated Never used. Set to null.
* @param mixed $bits File content
* @param string $time Optional. Time formatted in 'yyyy/mm'.
* @return array
*/
function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
if ( !empty( $deprecated ) )
_deprecated_argument( __FUNCTION__, '2.0' );

if ( empty( $name ) )
return array( 'error' => __( 'Empty filename' ) );

$wp_filetype = wp_check_filetype( $name );
if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) )
return array( 'error' => __( 'Invalid file type' ) );

$upload = wp_upload_dir( $time );

if ( $upload['error'] !== false )
return $upload;

/**
* Filter whether to treat the upload bits as an error.
*
* Passing a non-array to the filter will effectively short-circuit preparing
* the upload bits, returning that value instead.
*
* @since 3.0.0
*
* @param mixed $upload_bits_error An array of upload bits data, or a non-array error to return.
*/
$upload_bits_error = apply_filters( 'wp_upload_bits', array( 'name' => $name, 'bits' => $bits, 'time' => $time ) );
if ( !is_array( $upload_bits_error ) ) {
$upload[ 'error' ] = $upload_bits_error;
return $upload;
}

$filename = wp_unique_filename( $upload['path'], $name );

$new_file = $upload['path'] . "/$filename";
if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
if ( 0 === strpos( $upload['basedir'], ABSPATH ) )
$error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir'];
else
$error_path = basename( $upload['basedir'] ) . $upload['subdir'];

$message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $error_path );
return array( 'error' => $message );
}

$ifp = @ fopen( $new_file, 'wb' );
if ( ! $ifp )
return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );

@fwrite( $ifp, $bits );
fclose( $ifp );
clearstatcache();

// Set correct file permissions
$stat = @ stat( dirname( $new_file ) );
$perms = $stat['mode'] & 0007777;
$perms = $perms & 0000666;
@ chmod( $new_file, $perms );
clearstatcache();

// Compute the URL
$url = $upload['url'] . "/$filename";

return array( 'file' => $new_file, 'url' => $url, 'error' => false );
}

/**
* Retrieve the file type based on the extension name.
*
* @since 2.5.0
*
* @param string $ext The extension to search.
* @return string|null The file type, example: audio, video, document, spreadsheet, etc.
* Null if not found.
*/
function wp_ext2type( $ext ) {
$ext = strtolower( $ext );

/**
* Filter file type based on the extension name.
*
* @since 2.5.0
*
* @see wp_ext2type()
*
* @param array $ext2type Multi-dimensional array with extensions for a default set
* of file types.
*/
$ext2type = apply_filters( 'ext2type', array(
'image' => array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp', 'tif', 'tiff', 'ico' ),
'audio' => array( 'aac', 'ac3', 'aif', 'aiff', 'm3a', 'm4a', 'm4b', 'mka', 'mp1', 'mp2', 'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
'video' => array( 'asf', 'avi', 'divx', 'dv', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt', 'rm', 'vob', 'wmv' ),
'document' => array( 'doc', 'docx', 'docm', 'dotm', 'odt', 'pages', 'pdf', 'rtf', 'wp', 'wpd' ),
'spreadsheet' => array( 'numbers', 'ods', 'xls', 'xlsx', 'xlsm', 'xlsb' ),
'interactive' => array( 'swf', 'key', 'ppt', 'pptx', 'pptm', 'pps', 'ppsx', 'ppsm', 'sldx', 'sldm', 'odp' ),
'text' => array( 'asc', 'csv', 'tsv', 'txt' ),
'archive' => array( 'bz2', 'cab', 'dmg', 'gz', 'rar', 'sea', 'sit', 'sqx', 'tar', 'tgz', 'zip', '7z' ),
'code' => array( 'css', 'htm', 'html', 'php', 'js' ),
) );

foreach ( $ext2type as $type => $exts )
if ( in_array( $ext, $exts ) )
return $type;

return null;
}

/**
* Retrieve the file type from the file name.
*
* You can optionally define the mime array, if needed.
*
* @since 2.0.4
*
* @param string $filename File name or path.
* @param array $mimes Optional. Key is the file extension with value as the mime type.
* @return array Values with extension first and mime type.
*/
function wp_check_filetype( $filename, $mimes = null ) {
if ( empty($mimes) )
$mimes = get_allowed_mime_types();
$type = false;
$ext = false;

foreach ( $mimes as $ext_preg => $mime_match ) {
$ext_preg = '!\.(' . $ext_preg . ')$!i';
if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
$type = $mime_match;
$ext = $ext_matches[1];
break;
}
}

return compact( 'ext', 'type' );
}

/**
* Attempt to determine the real file type of a file.
* If unable to, the file name extension will be used to determine type.
*
* If it's determined that the extension does not match the file's real type,
* then the "proper_filename" value will be set with a proper filename and extension.
*
* Currently this function only supports validating images known to getimagesize().
*
* @since 3.0.0
*
* @param string $file Full path to the file.
* @param string $filename The name of the file (may differ from $file due to $file being in a tmp directory)
* @param array $mimes Optional. Key is the file extension with value as the mime type.
* @return array Values for the extension, MIME, and either a corrected filename or false if original $filename is valid
*/
function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {

$proper_filename = false;

// Do basic extension validation and MIME mapping
$wp_filetype = wp_check_filetype( $filename, $mimes );
extract( $wp_filetype );

// We can't do any further validation without a file to work with
if ( ! file_exists( $file ) )
return compact( 'ext', 'type', 'proper_filename' );

// We're able to validate images using GD
if ( $type && 0 === strpos( $type, 'image/' ) && function_exists('getimagesize') ) {

// Attempt to figure out what type of image it actually is
$imgstats = @getimagesize( $file );

// If getimagesize() knows what kind of image it really is and if the real MIME doesn't match the claimed MIME
if ( !empty($imgstats['mime']) && $imgstats['mime'] != $type ) {
/**
* Filter the list mapping image mime types to their respective extensions.
*
* @since 3.0.0
*
* @param array $mime_to_ext Array of image mime types and their matching extensions.
*/
$mime_to_ext = apply_filters( 'getimagesize_mimes_to_exts', array(
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/bmp' => 'bmp',
'image/tiff' => 'tif',
) );

// Replace whatever is after the last period in the filename with the correct extension
if ( ! empty( $mime_to_ext[ $imgstats['mime'] ] ) ) {
$filename_parts = explode( '.', $filename );
array_pop( $filename_parts );
$filename_parts[] = $mime_to_ext[ $imgstats['mime'] ];
$new_filename = implode( '.', $filename_parts );

if ( $new_filename != $filename )
$proper_filename = $new_filename; // Mark that it changed

// Redefine the extension / MIME
$wp_filetype = wp_check_filetype( $new_filename, $mimes );
extract( $wp_filetype );
}
}
}

/**
* Filter the "real" file type of the given file.
*
* @since 3.0.0
*
* @param array $wp_check_filetype_and_ext File data array containing 'ext', 'type', and
* 'proper_filename' keys.
* @param string $file Full path to the file.
* @param string $filename The name of the file (may differ from $file due to
* $file being in a tmp directory).
* @param array $mimes Key is the file extension with value as the mime type.
*/
return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes );
}

/**
* Retrieve list of mime types and file extensions.
*
* @since 3.5.0
*
* @return array Array of mime types keyed by the file extension regex corresponding to those types.
*/
function wp_get_mime_types() {
/**
* Filter the list of mime types and file extensions.
*
* This filter should be used to add, not remove, mime types. To remove
* mime types, use the 'upload_mimes' filter.
*
* @since 3.5.0
*
* @param array $wp_get_mime_types Mime types keyed by the file extension regex
* co


Navjot Singh comments:

THis isn't the full file. Can you upload it to dropbox or pastebin.com something and paste the url here?


movino4me comments:

https://dl.dropboxusercontent.com/u/16717719/functions.php


Navjot Singh comments:

Can you PM me your FTP details?


movino4me comments:

Great job Navjot we are up and running!

cheers

2014-08-18

Kyle answers:

Do you have a plugin called Quick Cache or any other caching plugins?


movino4me comments:

no cache plugins

2014-08-18

Arnav Joy answers:

can you show me file

class-cssmin.php at \woocommerce\includes\libraries


movino4me comments:

Hey Arnav good to see you!
here is the contents of the file

<?php
/**
* CssMin - A (simple) css minifier with benefits
*
* --
* Copyright (c) 2011 Joe Scylla <[email protected]>
*
* 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 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 CssMin
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
* Abstract definition of a CSS token class.
*
* Every token has to extend this class.
*
* @package CssMin/Tokens
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
abstract class aCssToken
{
/**
* Returns the token as string.
*
* @return string
*/
abstract public function __toString();
}

/**
* Abstract definition of a for a ruleset start token.
*
* @package CssMin/Tokens
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
abstract class aCssRulesetStartToken extends aCssToken
{

}

/**
* Abstract definition of a for ruleset end token.
*
* @package CssMin/Tokens
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
abstract class aCssRulesetEndToken extends aCssToken
{
/**
* Implements {@link aCssToken::__toString()}.
*
* @return string
*/
public function __toString()
{
return "}";
}
}

/**
* Abstract definition of a parser plugin.
*
* Every parser plugin have to extend this class. A parser plugin contains the logic to parse one or aspects of a
* stylesheet.
*
* @package CssMin/Parser/Plugins
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
abstract class aCssParserPlugin
{
/**
* Plugin configuration.
*
* @var array
*/
protected $configuration = array();
/**
* The CssParser of the plugin.
*
* @var CssParser
*/
protected $parser = null;
/**
* Plugin buffer.
*
* @var string
*/
protected $buffer = "";
/**
* Constructor.
*
* @param CssParser $parser The CssParser object of this plugin.
* @param array $configuration Plugin configuration [optional]
* @return void
*/
public function __construct(CssParser $parser, array $configuration = null)
{
$this->configuration = $configuration;
$this->parser = $parser;
}
/**
* Returns the array of chars triggering the parser plugin.
*
* @return array
*/
abstract public function getTriggerChars();
/**
* Returns the array of states triggering the parser plugin or FALSE if every state will trigger the parser plugin.
*
* @return array
*/
abstract public function getTriggerStates();
/**
* Parser routine of the plugin.
*
* @param integer $index Current index
* @param string $char Current char
* @param string $previousChar Previous char
* @return mixed TRUE will break the processing; FALSE continue with the next plugin; integer set a new index and break the processing
*/
abstract public function parse($index, $char, $previousChar, $state);
}

/**
* Abstract definition of a minifier plugin class.
*
* Minifier plugin process the parsed tokens one by one to apply changes to the token. Every minifier plugin has to
* extend this class.
*
* @package CssMin/Minifier/Plugins
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
abstract class aCssMinifierPlugin
{
/**
* Plugin configuration.
*
* @var array
*/
protected $configuration = array();
/**
* The CssMinifier of the plugin.
*
* @var CssMinifier
*/
protected $minifier = null;
/**
* Constructor.
*
* @param CssMinifier $minifier The CssMinifier object of this plugin.
* @param array $configuration Plugin configuration [optional]
* @return void
*/
public function __construct(CssMinifier $minifier, array $configuration = array())
{
$this->configuration = $configuration;
$this->minifier = $minifier;
}
/**
* Apply the plugin to the token.
*
* @param aCssToken $token Token to process
* @return boolean Return TRUE to break the processing of this token; FALSE to continue
*/
abstract public function apply(aCssToken &$token);
/**
* --
*
* @return array
*/
abstract public function getTriggerTokens();
}

/**
* Abstract definition of a minifier filter class.
*
* Minifier filters allows a pre-processing of the parsed token to add, edit or delete tokens. Every minifier filter
* has to extend this class.
*
* @package CssMin/Minifier/Filters
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
abstract class aCssMinifierFilter
{
/**
* Filter configuration.
*
* @var array
*/
protected $configuration = array();
/**
* The CssMinifier of the filter.
*
* @var CssMinifier
*/
protected $minifier = null;
/**
* Constructor.
*
* @param CssMinifier $minifier The CssMinifier object of this plugin.
* @param array $configuration Filter configuration [optional]
* @return void
*/
public function __construct(CssMinifier $minifier, array $configuration = array())
{
$this->configuration = $configuration;
$this->minifier = $minifier;
}
/**
* Filter the tokens.
*
* @param array $tokens Array of objects of type aCssToken
* @return integer Count of added, changed or removed tokens; a return value large than 0 will rebuild the array
*/
abstract public function apply(array &$tokens);
}

/**
* Abstract formatter definition.
*
* Every formatter have to extend this class.
*
* @package CssMin/Formatter
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
abstract class aCssFormatter
{
/**
* Indent string.
*
* @var string
*/
protected $indent = " ";
/**
* Declaration padding.
*
* @var integer
*/
protected $padding = 0;
/**
* Tokens.
*
* @var array
*/
protected $tokens = array();
/**
* Constructor.
*
* @param array $tokens Array of CssToken
* @param string $indent Indent string [optional]
* @param integer $padding Declaration value padding [optional]
*/
public function __construct(array $tokens, $indent = null, $padding = null)
{
$this->tokens = $tokens;
$this->indent = !is_null($indent) ? $indent : $this->indent;
$this->padding = !is_null($padding) ? $padding : $this->padding;
}
/**
* Returns the array of aCssToken as formatted string.
*
* @return string
*/
abstract public function __toString();
}

/**
* Abstract definition of a ruleset declaration token.
*
* @package CssMin/Tokens
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
abstract class aCssDeclarationToken extends aCssToken
{
/**
* Is the declaration flagged as important?
*
* @var boolean
*/
public $IsImportant = false;
/**
* Is the declaration flagged as last one of the ruleset?
*
* @var boolean
*/
public $IsLast = false;
/**
* Property name of the declaration.
*
* @var string
*/
public $Property = "";
/**
* Value of the declaration.
*
* @var string
*/
public $Value = "";
/**
* Set the properties of the @font-face declaration.
*
* @param string $property Property of the declaration
* @param string $value Value of the declaration
* @param boolean $isImportant Is the !important flag is set?
* @param boolean $IsLast Is the declaration the last one of the block?
* @return void
*/
public function __construct($property, $value, $isImportant = false, $isLast = false)
{
$this->Property = $property;
$this->Value = $value;
$this->IsImportant = $isImportant;
$this->IsLast = $isLast;
}
/**
* Implements {@link aCssToken::__toString()}.
*
* @return string
*/
public function __toString()
{
return $this->Property . ":" . $this->Value . ($this->IsImportant ? " !important" : "") . ($this->IsLast ? "" : ";");
}
}

/**
* Abstract definition of a for at-rule block start token.
*
* @package CssMin/Tokens
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
abstract class aCssAtBlockStartToken extends aCssToken
{

}

/**
* Abstract definition of a for at-rule block end token.
*
* @package CssMin/Tokens
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
abstract class aCssAtBlockEndToken extends aCssToken
{
/**
* Implements {@link aCssToken::__toString()}.
*
* @return string
*/
public function __toString()
{
return "}";
}
}

/**
* {@link aCssFromatter Formatter} returning the CSS source in {@link http://goo.gl/etzLs Whitesmiths indent style}.
*
* @package CssMin/Formatter
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssWhitesmithsFormatter extends aCssFormatter
{
/**
* Implements {@link aCssFormatter::__toString()}.
*
* @return string
*/
public function __toString()
{
$r = array();
$level = 0;
for ($i = 0, $l = count($this->tokens); $i < $l; $i++)
{
$token = $this->tokens[$i];
$class = get_class($token);
$indent = str_repeat($this->indent, $level);
if ($class === "CssCommentToken")
{
$lines = array_map("trim", explode("\n", $token->Comment));
for ($ii = 0, $ll = count($lines); $ii < $ll; $ii++)
{
$r[] = $indent . (substr($lines[$ii], 0, 1) == "*" ? " " : "") . $lines[$ii];
}
}
elseif ($class === "CssAtCharsetToken")
{
$r[] = $indent . "@charset " . $token->Charset . ";";
}
elseif ($class === "CssAtFontFaceStartToken")
{
$r[] = $indent . "@font-face";
$r[] = $this->indent . $indent . "{";
$level++;
}
elseif ($class === "CssAtImportToken")
{
$r[] = $indent . "@import " . $token->Import . " " . implode(", ", $token->MediaTypes) . ";";
}
elseif ($class === "CssAtKeyframesStartToken")
{
$r[] = $indent . "@keyframes \"" . $token->Name . "\"";
$r[] = $this->indent . $indent . "{";
$level++;
}
elseif ($class === "CssAtMediaStartToken")
{
$r[] = $indent . "@media " . implode(", ", $token->MediaTypes);
$r[] = $this->indent . $indent . "{";
$level++;
}
elseif ($class === "CssAtPageStartToken")
{
$r[] = $indent . "@page";
$r[] = $this->indent . $indent . "{";
$level++;
}
elseif ($class === "CssAtVariablesStartToken")
{
$r[] = $indent . "@variables " . implode(", ", $token->MediaTypes);
$r[] = $this->indent . $indent . "{";
$level++;
}
elseif ($class === "CssRulesetStartToken" || $class === "CssAtKeyframesRulesetStartToken")
{
$r[] = $indent . implode(", ", $token->Selectors);
$r[] = $this->indent . $indent . "{";
$level++;
}
elseif ($class == "CssAtFontFaceDeclarationToken"
|| $class === "CssAtKeyframesRulesetDeclarationToken"
|| $class === "CssAtPageDeclarationToken"
|| $class == "CssAtVariablesDeclarationToken"
|| $class === "CssRulesetDeclarationToken"
)
{
$declaration = $indent . $token->Property . ": ";
if ($this->padding)
{
$declaration = str_pad($declaration, $this->padding, " ", STR_PAD_RIGHT);
}
$r[] = $declaration . $token->Value . ($token->IsImportant ? " !important" : "") . ";";
}
elseif ($class === "CssAtFontFaceEndToken"
|| $class === "CssAtMediaEndToken"
|| $class === "CssAtKeyframesEndToken"
|| $class === "CssAtKeyframesRulesetEndToken"
|| $class === "CssAtPageEndToken"
|| $class === "CssAtVariablesEndToken"
|| $class === "CssRulesetEndToken"
)
{
$r[] = $indent . "}";
$level--;
}
}
return implode("\n", $r);
}
}

/**
* This {@link aCssMinifierPlugin} will process var-statement and sets the declaration value to the variable value.
*
* This plugin only apply the variable values. The variable values itself will get parsed by the
* {@link CssVariablesMinifierFilter}.
*
* Example:
*
* @variables
* {
* defaultColor: black;
* }
* color: var(defaultColor);
*

*
* Will get converted to:
*
* color:black;
*

*
* @package CssMin/Minifier/Plugins
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssVariablesMinifierPlugin extends aCssMinifierPlugin
{
/**
* Regular expression matching a value.
*
* @var string
*/
private $reMatch = "/var\((.+)\)/iSU";
/**
* Parsed variables.
*
* @var array
*/
private $variables = null;
/**
* Returns the variables.
*
* @return array
*/
public function getVariables()
{
return $this->variables;
}
/**
* Implements {@link aCssMinifierPlugin::minify()}.
*
* @param aCssToken $token Token to process
* @return boolean Return TRUE to break the processing of this token; FALSE to continue
*/
public function apply(aCssToken &$token)
{
if (stripos($token->Value, "var") !== false && preg_match_all($this->reMatch, $token->Value, $m))
{
$mediaTypes = $token->MediaTypes;
if (!in_array("all", $mediaTypes))
{
$mediaTypes[] = "all";
}
for ($i = 0, $l = count($m[0]); $i < $l; $i++)
{
$variable = trim($m[1][$i]);
foreach ($mediaTypes as $mediaType)
{
if (isset($this->variables[$mediaType], $this->variables[$mediaType][$variable]))
{
// Variable value found => set the declaration value to the variable value and return
$token->Value = str_replace($m[0][$i], $this->variables[$mediaType][$variable], $token->Value);
continue 2;
}
}
// If no value was found trigger an error and replace the token with a CssNullToken
CssMin::triggerError(new CssError(__FILE__, __LINE__, __METHOD__ . ": No value found for variable " . $variable . " in media types " . implode(", ", $mediaTypes) . "", (string) $token));
$token = new CssNullToken();
return true;
}
}
return false;
}
/**
* Implements {@link aMinifierPlugin::getTriggerTokens()}
*
* @return array
*/
public function getTriggerTokens()
{
return array
(
"CssAtFontFaceDeclarationToken",
"CssAtPageDeclarationToken",
"CssRulesetDeclarationToken"
);
}
/**
* Sets the variables.
*
* @param array $variables Variables to set
* @return void
*/
public function setVariables(array $variables)
{
$this->variables = $variables;
}
}

/**
* This {@link aCssMinifierFilter minifier filter} will parse the variable declarations out of @variables at-rule
* blocks. The variables will get store in the {@link CssVariablesMinifierPlugin} that will apply the variables to
* declaration.
*
* @package CssMin/Minifier/Filters
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssVariablesMinifierFilter extends aCssMinifierFilter
{
/**
* Implements {@link aCssMinifierFilter::filter()}.
*
* @param array $tokens Array of objects of type aCssToken
* @return integer Count of added, changed or removed tokens; a return value large than 0 will rebuild the array
*/
public function apply(array &$tokens)
{
$variables = array();
$defaultMediaTypes = array("all");
$mediaTypes = array();
$remove = array();
for($i = 0, $l = count($tokens); $i < $l; $i++)
{
// @variables at-rule block found
if (get_class($tokens[$i]) === "CssAtVariablesStartToken")
{
$remove[] = $i;
$mediaTypes = (count($tokens[$i]->MediaTypes) == 0 ? $defaultMediaTypes : $tokens[$i]->MediaTypes);
foreach ($mediaTypes as $mediaType)
{
if (!isset($variables[$mediaType]))
{
$variables[$mediaType] = array();
}
}
// Read the variable declaration tokens
for($i = $i; $i < $l; $i++)
{
// Found a variable declaration => read the variable values
if (get_class($tokens[$i]) === "CssAtVariablesDeclarationToken")
{
foreach ($mediaTypes as $mediaType)
{
$variables[$mediaType][$tokens[$i]->Property] = $tokens[$i]->Value;
}
$remove[] = $i;
}
// Found the variables end token => break;
elseif (get_class($tokens[$i]) === "CssAtVariablesEndToken")
{
$remove[] = $i;
break;
}
}
}
}
// Variables in @variables at-rule blocks
foreach($variables as $mediaType => $null)
{
foreach($variables[$mediaType] as $variable => $value)
{
// If a var() statement in a variable value found...
if (stripos($value, "var") !== false && preg_match_all("/var\((.+)\)/iSU", $value, $m))
{
// ... then replace the var() statement with the variable values.
for ($i = 0, $l = count($m[0]); $i < $l; $i++)
{
$variables[$mediaType][$variable] = str_replace($m[0][$i], (isset($variables[$mediaType][$m[1][$i]]) ? $variables[$mediaType][$m[1][$i]] : ""), $variables[$mediaType][$variable]);
}
}
}
}
// Remove the complete @variables at-rule block
foreach ($remove as $i)
{
$tokens[$i] = null;
}
if (!($plugin = $this->minifier->getPlugin("CssVariablesMinifierPlugin")))
{
CssMin::triggerError(new CssError(__FILE__, __LINE__, __METHOD__ . ": The plugin CssVariablesMinifierPlugin was not found but is required for " . __CLASS__ . ""));
}
else
{
$plugin->setVariables($variables);
}
return count($remove);
}
}

/**
* {@link aCssParserPlugin Parser plugin} for preserve parsing url() values.
*
* This plugin return no {@link aCssToken CssToken} but ensures that url() values will get parsed properly.
*
* @package CssMin/Parser/Plugins
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssUrlParserPlugin extends aCssParserPlugin
{
/**
* Implements {@link aCssParserPlugin::getTriggerChars()}.
*
* @return array
*/
public function getTriggerChars()
{
return array("(", ")");
}
/**
* Implements {@link aCssParserPlugin::getTriggerStates()}.
*
* @return array
*/
public function getTriggerStates()
{
return false;
}
/**
* Implements {@link aCssParserPlugin::parse()}.
*
* @param integer $index Current index
* @param string $char Current char
* @param string $previousChar Previous char
* @return mixed TRUE will break the processing; FALSE continue with the next plugin; integer set a new index and break the processing
*/
public function parse($index, $char, $previousChar, $state)
{
// Start of string
if ($char === "(" && strtolower(substr($this->parser->getSource(), $index - 3, 4)) === "url(" && $state !== "T_URL")
{
$this->parser->pushState("T_URL");
$this->parser->setExclusive(__CLASS__);
}
// Escaped LF in url => remove escape backslash and LF
elseif ($char === "\n" && $previousChar === "\\" && $state === "T_URL")
{
$this->parser->setBuffer(substr($this->parser->getBuffer(), 0, -2));
}
// Parse error: Unescaped LF in string literal
elseif ($char === "\n" && $previousChar !== "\\" && $state === "T_URL")
{
$line = $this->parser->getBuffer();
$this->parser->setBuffer(substr($this->parser->getBuffer(), 0, -1) . ")"); // Replace the LF with the url string delimiter
$this->parser->popState();
$this->parser->unsetExclusive();
CssMin::triggerError(new CssError(__FILE__, __LINE__, __METHOD__ . ": Unterminated string literal", $line . "_"));
}
// End of string
elseif ($char === ")" && $state === "T_URL")
{
$this->parser->popState();
$this->parser->unsetExclusive();
}
else
{
return false;
}
return true;
}
}

/**
* {@link aCssParserPlugin Parser plugin} for preserve parsing string values.
*
* This plugin return no {@link aCssToken CssToken} but ensures that string values will get parsed properly.
*
* @package CssMin/Parser/Plugins
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssStringParserPlugin extends aCssParserPlugin
{
/**
* Current string delimiter char.
*
* @var string
*/
private $delimiterChar = null;
/**
* Implements {@link aCssParserPlugin::getTriggerChars()}.
*
* @return array
*/
public function getTriggerChars()
{
return array("\"", "'", "\n");
}
/**
* Implements {@link aCssParserPlugin::getTriggerStates()}.
*
* @return array
*/
public function getTriggerStates()
{
return false;
}
/**
* Implements {@link aCssParserPlugin::parse()}.
*
* @param integer $index Current index
* @param string $char Current char
* @param string $previousChar Previous char
* @return mixed TRUE will break the processing; FALSE continue with the next plugin; integer set a new index and break the processing
*/
public function parse($index, $char, $previousChar, $state)
{
// Start of string
if (($char === "\"" || $char === "'") && $state !== "T_STRING")
{
$this->delimiterChar = $char;
$this->parser->pushState("T_STRING");
$this->parser->setExclusive(__CLASS__);
}
// Escaped LF in string => remove escape backslash and LF
elseif ($char === "\n" && $previousChar === "\\" && $state === "T_STRING")
{
$this->parser->setBuffer(substr($this->parser->getBuffer(), 0, -2));
}
// Parse error: Unescaped LF in string literal
elseif ($char === "\n" && $previousChar !== "\\" && $state === "T_STRING")
{
$line = $this->parser->getBuffer();
$this->parser->popState();
$this->parser->unsetExclusive();
$this->parser->setBuffer(substr($this->parser->getBuffer(), 0, -1) . $this->delimiterChar); // Replace the LF with the current string char
CssMin::triggerError(new CssError(__FILE__, __LINE__, __METHOD__ . ": Unterminated string literal", $line . "_"));
$this->delimiterChar = null;
}
// End of string
elseif ($char === $this->delimiterChar && $state === "T_STRING")
{
// If the Previous char is a escape char count the amount of the previous escape chars. If the amount of
// escape chars is uneven do not end the string
if ($previousChar == "\\")
{
$source = $this->parser->getSource();
$c = 1;
$i = $index - 2;
while (substr($source, $i, 1) === "\\")
{
$c++; $i--;
}
if ($c % 2)
{
return false;
}
}
$this->parser->popState();
$this->parser->unsetExclusive();
$this->delimiterChar = null;
}
else
{
return false;
}
return true;
}
}

/**
* This {@link aCssMinifierFilter minifier filter} sorts the ruleset declarations of a ruleset by name.
*
* @package CssMin/Minifier/Filters
* @link http://code.google.com/p/cssmin/
* @author Rowan Beentje <http://assanka.net>
* @copyright Rowan Beentje <http://assanka.net>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssSortRulesetPropertiesMinifierFilter extends aCssMinifierFilter
{
/**
* Implements {@link aCssMinifierFilter::filter()}.
*
* @param array $tokens Array of objects of type aCssToken
* @return integer Count of added, changed or removed tokens; a return value larger than 0 will rebuild the array
*/
public function apply(array &$tokens)
{
$r = 0;
for ($i = 0, $l = count($tokens); $i < $l; $i++)
{
// Only look for ruleset start rules
if (get_class($tokens[$i]) !== "CssRulesetStartToken") { continue; }
// Look for the corresponding ruleset end
$endIndex = false;
for ($ii = $i + 1; $ii < $l; $ii++)
{
if (get_class($tokens[$ii]) !== "CssRulesetEndToken") { continue; }
$endIndex = $ii;
break;
}
if (!$endIndex) { break; }
$startIndex = $i;
$i = $endIndex;
// Skip if there's only one token in this ruleset
if ($endIndex - $startIndex <= 2) { continue; }
// Ensure that everything between the start and end is a declaration token, for safety
for ($ii = $startIndex + 1; $ii < $endIndex; $ii++)
{
if (get_class($tokens[$ii]) !== "CssRulesetDeclarationToken") { continue(2); }
}
$declarations = array_slice($tokens, $startIndex + 1, $endIndex - $startIndex - 1);
// Check whether a sort is required
$sortRequired = $lastPropertyName = false;
foreach ($declarations as $declaration)
{
if ($lastPropertyName)
{
if (strcmp($lastPropertyName, $declaration->Property) > 0)
{
$sortRequired = true;
break;
}
}
$lastPropertyName = $declaration->Property;
}
if (!$sortRequired) { continue; }
// Arrange the declarations alphabetically by name
usort($declarations, array(__CLASS__, "userDefinedSort1"));
// Update "IsLast" property
for ($ii = 0, $ll = count($declarations) - 1; $ii <= $ll; $ii++)
{
if ($ii == $ll)
{
$declarations[$ii]->IsLast = true;
}
else
{
$declarations[$ii]->IsLast = false;
}
}
// Splice back into the array.
array_splice($tokens, $startIndex + 1, $endIndex - $startIndex - 1, $declarations);
$r += $endIndex - $startIndex - 1;
}
return $r;
}
/**
* User defined sort function.
*
* @return integer
*/
public static function userDefinedSort1($a, $b)
{
return strcmp($a->Property, $b->Property);
}
}

/**
* This {@link aCssToken CSS token} represents the start of a ruleset.
*
* @package CssMin/Tokens
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssRulesetStartToken extends aCssRulesetStartToken
{
/**
* Array of selectors.
*
* @var array
*/
public $Selectors = array();
/**
* Set the properties of a ruleset token.
*
* @param array $selectors Selectors of the ruleset
* @return void
*/
public function __construct(array $selectors = array())
{
$this->Selectors = $selectors;
}
/**
* Implements {@link aCssToken::__toString()}.
*
* @return string
*/
public function __toString()
{
return implode(",", $this->Selectors) . "{";
}
}

/**
* {@link aCssParserPlugin Parser plugin} for parsing ruleset block with including declarations.
*
* Found rulesets will add a {@link CssRulesetStartToken} and {@link CssRulesetEndToken} to the
* parser; including declarations as {@link CssRulesetDeclarationToken}.
*
* @package CssMin/Parser/Plugins
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssRulesetParserPlugin extends aCssParserPlugin
{
/**
* Implements {@link aCssParserPlugin::getTriggerChars()}.
*
* @return array
*/
public function getTriggerChars()
{
return array(",", "{", "}", ":", ";");
}
/**
* Implements {@link aCssParserPlugin::getTriggerStates()}.
*
* @return array
*/
public function getTriggerStates()
{
return array("T_DOCUMENT", "T_AT_MEDIA", "T_RULESET::SELECTORS", "T_RULESET", "T_RULESET_DECLARATION");
}
/**
* Selectors.
*
* @var array
*/
private $selectors = array();
/**
* Implements {@link aCssParserPlugin::parse()}.
*
* @param integer $index Current index
* @param string $char Current char
* @param string $previousChar Previous char
* @return mixed TRUE will break the processing; FALSE continue with the next plugin; integer set a new index and break the processing
*/
public function parse($index, $char, $previousChar, $state)
{
// Start of Ruleset and selectors
if ($char === "," && ($state === "T_DOCUMENT" || $state === "T_AT_MEDIA" || $state === "T_RULESET::SELECTORS"))
{
if ($state !== "T_RULESET::SELECTORS")
{
$this->parser->pushState("T_RULESET::SELECTORS");
}
$this->selectors[] = $this->parser->getAndClearBuffer(",{");
}
// End of selectors and start of declarations
elseif ($char === "{" && ($state === "T_DOCUMENT" || $state === "T_AT_MEDIA" || $state === "T_RULESET::SELECTORS"))
{
if ($this->parser->getBuffer() !== "")
{
$this->selectors[] = $this->parser->getAndClearBuffer(",{");
if ($state == "T_RULESET::SELECTORS")
{
$this->parser->popState();
}
$this->parser->pushState("T_RULESET");
$this->parser->appendToken(new CssRulesetStartToken($this->selectors));
$this->selectors = array();
}
}
// Start of declaration
elseif ($char === ":" && $state === "T_RULESET")
{
$this->parser->pushState("T_RULESET_DECLARATION");
$this->buffer = $this->parser->getAndClearBuffer(":;", true);
}
// Unterminated ruleset declaration
elseif ($char === ":" && $state === "T_RULESET_DECLARATION")
{
// Ignore Internet Explorer filter declarations
if ($this->buffer === "filter")
{
return false;
}
CssMin::triggerError(new CssError(__FILE__, __LINE__, __METHOD__ . ": Unterminated declaration", $this->buffer . ":" . $this->parser->getBuffer() . "_"));
}
// End of declaration
elseif (($char === ";" || $char === "}") && $state === "T_RULESET_DECLARATION")
{
$value = $this->parser->getAndClearBuffer(";}");
if (strtolower(substr($value, -10, 10)) === "!important")
{
$value = trim(substr($value, 0, -10));
$isImportant = true;
}
else
{
$isImportant = false;
}
$this->parser->popState();
$this->parser->appendToken(new CssRulesetDeclarationToken($this->buffer, $value, $this->parser->getMediaTypes(), $isImportant));
// Declaration ends with a right curly brace; so we have to end the ruleset
if ($char === "}")
{
$this->parser->appendToken(new CssRulesetEndToken());
$this->parser->popState();
}
$this->buffer = "";
}
// End of ruleset
elseif ($char === "}" && $state === "T_RULESET")
{
$this->parser->popState();
$this->parser->clearBuffer();
$this->parser->appendToken(new CssRulesetEndToken());
$this->buffer = "";
$this->selectors = array();
}
else
{
return false;
}
return true;
}
}

/**
* This {@link aCssToken CSS token} represents the end of a ruleset.
*
* @package CssMin/Tokens
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssRulesetEndToken extends aCssRulesetEndToken
{

}

/**
* This {@link aCssToken CSS token} represents a ruleset declaration.
*
* @package CssMin/Tokens
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssRulesetDeclarationToken extends aCssDeclarationToken
{
/**
* Media types of the declaration.
*
* @var array
*/
public $MediaTypes = array("all");
/**
* Set the properties of a ddocument- or at-rule @media level declaration.
*
* @param string $property Property of the declaration
* @param string $value Value of the declaration
* @param mixed $mediaTypes Media types of the declaration
* @param boolean $isImportant Is the !important flag is set
* @param boolean $isLast Is the declaration the last one of the ruleset
* @return void
*/
public function __construct($property, $value, $mediaTypes = null, $isImportant = false, $isLast = false)
{
parent::__construct($property, $value, $isImportant, $isLast);
$this->MediaTypes = $mediaTypes ? $mediaTypes : array("all");
}
}

/**
* This {@link aCssMinifierFilter minifier filter} sets the IsLast property of any last declaration in a ruleset,
* @font-face at-rule or @page at-rule block. If the property IsLast is TRUE the decrations will get stringified
* without tailing semicolon.
*
* @package CssMin/Minifier/Filters
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssRemoveLastDelarationSemiColonMinifierFilter extends aCssMinifierFilter
{
/**
* Implements {@link aCssMinifierFilter::filter()}.
*
* @param array $tokens Array of objects of type aCssToken
* @return integer Count of added, changed or removed tokens; a return value large than 0 will rebuild the array
*/
public function apply(array &$tokens)
{
for ($i = 0, $l = count($tokens); $i < $l; $i++)
{
$current = get_class($tokens[$i]);
$next = isset($tokens[$i+1]) ? get_class($tokens[$i+1]) : false;
if (($current === "CssRulesetDeclarationToken" && $next === "CssRulesetEndToken") ||
($current === "CssAtFontFaceDeclarationToken" && $next === "CssAtFontFaceEndToken") ||
($current === "CssAtPageDeclarationToken" && $next === "CssAtPageEndToken"))
{
$tokens[$i]->IsLast = true;
}
}
return 0;
}
}

/**
* This {@link aCssMinifierFilter minifier filter} will remove any empty rulesets (including @keyframes at-rule block
* rulesets).
*
* @package CssMin/Minifier/Filters
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssRemoveEmptyRulesetsMinifierFilter extends aCssMinifierFilter
{
/**
* Implements {@link aCssMinifierFilter::filter()}.
*
* @param array $tokens Array of objects of type aCssToken
* @return integer Count of added, changed or removed tokens; a return value large than 0 will rebuild the array
*/
public function apply(array &$tokens)
{
$r = 0;
for ($i = 0, $l = count($tokens); $i < $l; $i++)
{
$current = get_class($tokens[$i]);
$next = isset($tokens[$i + 1]) ? get_class($tokens[$i + 1]) : false;
if (($current === "CssRulesetStartToken" && $next === "CssRulesetEndToken") ||
($current === "CssAtKeyframesRulesetStartToken" && $next === "CssAtKeyframesRulesetEndToken" && !array_intersect(array("from", "0%", "to", "100%"), array_map("strtolower", $tokens[$i]->Selectors)))
)
{
$tokens[$i] = null;
$tokens[$i + 1] = null;
$i++;
$r = $r + 2;
}
}
return $r;
}
}

/**
* This {@link aCssMinifierFilter minifier filter} will remove any empty @font-face, @keyframes, @media and @page
* at-rule blocks.
*
* @package CssMin/Minifier/Filters
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssRemoveEmptyAtBlocksMinifierFilter extends aCssMinifierFilter
{
/**
* Implements {@link aCssMinifierFilter::filter()}.
*
* @param array $tokens Array of objects of type aCssToken
* @return integer Count of added, changed or removed tokens; a return value large than 0 will rebuild the array
*/
public function apply(array &$tokens)
{
$r = 0;
for ($i = 0, $l = count($tokens); $i < $l; $i++)
{
$current = get_class($tokens[$i]);
$next = isset($tokens[$i + 1]) ? get_class($tokens[$i + 1]) : false;
if (($current === "CssAtFontFaceStartToken" && $next === "CssAtFontFaceEndToken") ||
($current === "CssAtKeyframesStartToken" && $next === "CssAtKeyframesEndToken") ||
($current === "CssAtPageStartToken" && $next === "CssAtPageEndToken") ||
($current === "CssAtMediaStartToken" && $next === "CssAtMediaEndToken"))
{
$tokens[$i] = null;
$tokens[$i + 1] = null;
$i++;
$r = $r + 2;
}
}
return $r;
}
}

/**
* This {@link aCssMinifierFilter minifier filter} will remove any comments from the array of parsed tokens.
*
* @package CssMin/Minifier/Filters
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssRemoveCommentsMinifierFilter extends aCssMinifierFilter
{
/**
* Implements {@link aCssMinifierFilter::filter()}.
*
* @param array $tokens Array of objects of type aCssToken
* @return integer Count of added, changed or removed tokens; a return value large than 0 will rebuild the array
*/
public function apply(array &$tokens)
{
$r = 0;
for ($i = 0, $l = count($tokens); $i < $l; $i++)
{
if (get_class($tokens[$i]) === "CssCommentToken")
{
$tokens[$i] = null;
$r++;
}
}
return $r;
}
}

/**
* CSS Parser.
*
* @package CssMin/Parser
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssParser
{
/**
* Parse buffer.
*
* @var string
*/
private $buffer = "";
/**
* {@link aCssParserPlugin Plugins}.
*
* @var array
*/
private $plugins = array();
/**
* Source to parse.
*
* @var string
*/
private $source = "";
/**
* Current state.
*
* @var integer
*/
private $state = "T_DOCUMENT";
/**
* Exclusive state.
*
* @var string
*/
private $stateExclusive = false;
/**
* Media types state.
*
* @var mixed
*/
private $stateMediaTypes = false;
/**
* State stack.
*
* @var array
*/
private $states = array("T_DOCUMENT");
/**
* Parsed tokens.
*
* @var array
*/
private $tokens = array();
/**
* Constructer.
*
* Create instances of the used {@link aCssParserPlugin plugins}.
*
* @param string $source CSS source [optional]
* @param array $plugins Plugin configuration [optional]
* @return void
*/
public function __construct($source = null, array $plugins = null)
{
$plugins = array_merge(array
(
"Comment" => true,
"String" => true,
"Url" => true,
"Expression" => true,
"Ruleset" => true,
"AtCharset" => true,
"AtFontFace" => true,
"AtImport" => true,
"AtKeyframes" => true,
"AtMedia" => true,
"AtPage" => true,
"AtVariables" => true
), is_array($plugins) ? $plugins : array());
// Create plugin instances
foreach ($plugins as $name => $config)
{
if ($config !== false)
{
$class = "Css" . $name . "ParserPlugin";
$config = is_array($config) ? $config : array();
if (class_exists($class))
{
$this->plugins[] = new $class($this, $config);
}
else
{
CssMin::triggerError(new CssError(__FILE__, __LINE__, __METHOD__ . ": The plugin " . $name . " with the class name " . $class . " was not found"));
}
}
}
if (!is_null($source))
{
$this->parse($source);
}
}
/**
* Append a token to the array of tokens.
*
* @param aCssToken $token Token to append
* @return void
*/
public function appendToken(aCssToken $token)
{
$this->tokens[] = $token;
}
/**
* Clears the current buffer.
*
* @return void
*/
public function clearBuffer()
{
$this->buffer = "";
}
/**
* Returns and clear the current buffer.
*
* @param string $trim Chars to use to trim the returned buffer
* @param boolean $tolower if TRUE the returned buffer will get converted to lower case
* @return string
*/
public function getAndClearBuffer($trim = "", $tolower = false)
{
$r = $this->getBuffer($trim, $tolower);
$this->buffer = "";
return $r;
}
/**
* Returns the current buffer.
*
* @param string $trim Chars to use to trim the returned buffer
* @param boolean $tolower if TRUE the returned buffer will get converted to lower case
* @return string
*/
public function getBuffer($trim = "", $tolower = false)
{
$r = $this->buffer;
if ($trim)
{
$r = trim($r, " \t\n\r\0\x0B" . $trim);
}
if ($tolower)
{
$r = strtolower($r);
}
return $r;
}
/**
* Returns the current media types state.
*
* @return array
*/
public function getMediaTypes()
{
return $this->stateMediaTypes;
}
/**
* Returns the CSS source.
*
* @return string
*/
public function getSource()
{
return $this->source;
}
/**
* Returns the current state.
*
* @return integer The current state
*/
public function getState()
{
return $this->state;
}
/**
* Returns a plugin by class name.
*
* @param string $name Class name of the plugin
* @return aCssParserPlugin
*/
public function getPlugin($class)
{
static $index = null;
if (is_null($index))
{
$index = array();
for ($i = 0, $l = count($this->plugins); $i < $l; $i++)
{
$index[get_class($this->plugins[$i])] = $i;
}
}
return isset($index[$class]) ? $this->plugins[$index[$class]] : false;
}
/**
* Returns the parsed tokens.
*
* @return array
*/
public function getTokens()
{
return $this->tokens;
}
/**
* Returns if the current state equals the passed state.
*
* @param integer $state State to compare with the current state
* @return boolean TRUE is the state equals to the passed state; FALSE if not
*/
public function isState($state)
{
return ($this->state == $state);
}
/**
* Parse the CSS source and return a array with parsed tokens.
*
* @param string $source CSS source
* @return array Array with tokens
*/
public function parse($source)
{
// Reset
$this->source = "";
$this->tokens = array();
// Create a global and plugin lookup table for trigger chars; set array of plugins as local variable and create
// several helper variables for plugin handling
$globalTriggerChars = "";
$plugins = $this->plugins;
$pluginCount = count($plugins);
$pluginIndex = array();
$pluginTriggerStates = array();
$pluginTriggerChars = array();
for ($i = 0, $l = count($plugins); $i < $l; $i++)
{
$tPluginClassName = get_class($plugins[$i]);
$pluginTriggerChars[$i] = implode("", $plugins[$i]->getTriggerChars());
$tPluginTriggerStates = $plugins[$i]->getTriggerStates();
$pluginTriggerStates[$i] = $tPluginTriggerStates === false ? false : "|" . implode("|", $tPluginTriggerStates) . "|";
$pluginIndex[$tPluginClassName] = $i;
for ($ii = 0, $ll = strlen($pluginTriggerChars[$i]); $ii < $ll; $ii++)
{
$c = substr($pluginTriggerChars[$i], $ii, 1);
if (strpos($globalTriggerChars, $c) === false)
{
$globalTriggerChars .= $c;
}
}
}
// Normalise line endings
$source = str_replace("\r\n", "\n", $source); // Windows to Unix line endings
$source = str_replace("\r", "\n", $source); // Mac to Unix line endings
$this->source = $source;
// Variables
$buffer = &$this->buffer;
$exclusive = &$this->stateExclusive;
$state = &$this->state;
$c = $p = null;
// --
for ($i = 0, $l = strlen($source); $i < $l; $i++)
{
// Set the current Char
$c = $source[$i]; // Is faster than: $c = substr($source, $i, 1);
// Normalize and filter double whitespace characters
if ($exclusive === false)
{
if ($c === "\n" || $c === "\t")
{
$c = " ";
}
if ($c === " " && $p === " ")
{
continue;
}
}
$buffer .= $c;
// Extended processing only if the current char is a global trigger char
if (strpos($globalTriggerChars, $c) !== false)
{
// Exclusive state is set; process with the exclusive plugin
if ($exclusive)
{
$tPluginIndex = $pluginIndex[$exclusive];
if (strpos($pluginTriggerChars[$tPluginIndex], $c) !== false && ($pluginTriggerStates[$tPluginIndex] === false || strpos($pluginTriggerStates[$tPluginIndex], $state) !== false))
{
$r = $plugins[$tPluginIndex]->parse($i, $c, $p, $state);
// Return value is TRUE => continue with next char
if ($r === true)
{
continue;
}
// Return value is numeric => set new index and continue with next char
elseif ($r !== false && $r != $i)
{
$i = $r;
continue;
}
}
}
// Else iterate through the plugins
else
{
$triggerState = "|" . $state . "|";
for ($ii = 0, $ll = $pluginCount; $ii < $ll; $ii++)
{
// Only process if the current char is one of the plugin trigger chars
if (strpos($pluginTriggerChars[$ii], $c) !== false && ($pluginTriggerStates[$ii] === false || strpos($pluginTriggerStates[$ii], $triggerState) !== false))
{
// Process with the plugin
$r = $plugins[$ii]->parse($i, $c, $p, $state);
// Return value is TRUE => break the plugin loop and and continue with next char
if ($r === true)
{
break;
}
// Return value is numeric => set new index, break the plugin loop and and continue with next char
elseif ($r !== false && $r != $i)
{
$i = $r;
break;
}
}
}
}
}
$p = $c; // Set the parent char
}
return $this->tokens;
}
/**
* Remove the last state of the state stack and return the removed stack value.
*
* @return integer Removed state value
*/
public function popState()
{
$r = array_pop($this->states);
$this->state = $this->states[count($this->states) - 1];
return $r;
}
/**
* Adds a new state onto the state stack.
*
* @param integer $state State to add onto the state stack.
* @return integer The index of the added state in the state stacks
*/
public function pushState($state)
{
$r = array_push($this->states, $state);
$this->state = $this->states[count($this->states) - 1];
return $r;
}
/**
* Sets/restores the buffer.
*
* @param string $buffer Buffer to set
* @return void
*/
public function setBuffer($buffer)
{
$this->buffer = $buffer;
}
/**
* Set the exclusive state.
*
* @param string $exclusive Exclusive state
* @return void
*/
public function setExclusive($exclusive)
{
$this->stateExclusive = $exclusive;
}
/**
* Set the media types state.
*
* @param array $mediaTypes Media types state
* @return void
*/
public function setMediaTypes(array $mediaTypes)
{
$this->stateMediaTypes = $mediaTypes;
}
/**
* Sets the current state in the state stack; equals to {@link CssParser::popState()} + {@link CssParser::pushState()}.
*
* @param integer $state State to set
* @return integer
*/
public function setState($state)
{
$r = array_pop($this->states);
array_push($this->states, $state);
$this->state = $this->states[count($this->states) - 1];
return $r;
}
/**
* Removes the exclusive state.
*
* @return void
*/
public function unsetExclusive()
{
$this->stateExclusive = false;
}
/**
* Removes the media types state.
*
* @return void
*/
public function unsetMediaTypes()
{
$this->stateMediaTypes = false;
}
}

/**
* {@link aCssFromatter Formatter} returning the CSS source in {@link http://goo.gl/j4XdU OTBS indent style} (The One True Brace Style).
*
* @package CssMin/Formatter
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssOtbsFormatter extends aCssFormatter
{
/**
* Implements {@link aCssFormatter::__toString()}.
*
* @return string
*/
public function __toString()
{
$r = array();
$level = 0;
for ($i = 0, $l = count($this->tokens); $i < $l; $i++)
{
$token = $this->tokens[$i];
$class = get_class($token);
$indent = str_repeat($this->indent, $level);
if ($class === "CssCommentToken")
{
$lines = array_map("trim", explode("\n", $token->Comment));
for ($ii = 0, $ll = count($lines); $ii < $ll; $ii++)
{
$r[] = $indent . (substr($lines[$ii], 0, 1) == "*" ? " " : "") . $lines[$ii];
}
}
elseif ($class === "CssAtCharsetToken")
{
$r[] = $indent . "@charset " . $token->Charset . ";";
}
elseif ($class === "CssAtFontFaceStartToken")
{
$r[] = $indent . "@font-face {";
$level++;
}
elseif ($class === "CssAtImportToken")
{
$r[] = $indent . "@import " . $token->Import . " " . implode(", ", $token->MediaTypes) . ";";
}
elseif ($class === "CssAtKeyframesStartToken")
{
$r[] = $indent . "@keyframes \"" . $token->Name . "\" {";
$level++;
}
elseif ($class === "CssAtMediaStartToken")
{
$r[] = $indent . "@media " . implode(", ", $token->MediaTypes) . " {";
$level++;
}
elseif ($class === "CssAtPageStartToken")
{
$r[] = $indent . "@page {";
$level++;
}
elseif ($class === "CssAtVariablesStartToken")
{
$r[] = $indent . "@variables " . implode(", ", $token->MediaTypes) . " {";
$level++;
}
elseif ($class === "CssRulesetStartToken" || $class === "CssAtKeyframesRulesetStartToken")
{
$r[] = $indent . implode(", ", $token->Selectors) . " {";
$level++;
}
elseif ($class == "CssAtFontFaceDeclarationToken"
|| $class === "CssAtKeyframesRulesetDeclarationToken"
|| $class === "CssAtPageDeclarationToken"
|| $class == "CssAtVariablesDeclarationToken"
|| $class === "CssRulesetDeclarationToken"
)
{
$declaration = $indent . $token->Property . ": ";
if ($this->padding)
{
$declaration = str_pad($declaration, $this->padding, " ", STR_PAD_RIGHT);
}
$r[] = $declaration . $token->Value . ($token->IsImportant ? " !important" : "") . ";";
}
elseif ($class === "CssAtFontFaceEndToken"
|| $class === "CssAtMediaEndToken"
|| $class === "CssAtKeyframesEndToken"
|| $class === "CssAtKeyframesRulesetEndToken"
|| $class === "CssAtPageEndToken"
|| $class === "CssAtVariablesEndToken"
|| $class === "CssRulesetEndToken"
)
{
$level--;
$r[] = str_repeat($indent, $level) . "}";
}
}
return implode("\n", $r);
}
}

/**
* This {@link aCssToken CSS token} is a utility token that extends {@link aNullToken} and returns only a empty string.
*
* @package CssMin/Tokens
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssNullToken extends aCssToken
{
/**
* Implements {@link aCssToken::__toString()}.
*
* @return string
*/
public function __toString()
{
return "";
}
}

/**
* CSS Minifier.
*
* @package CssMin/Minifier
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssMinifier
{
/**
* {@link aCssMinifierFilter Filters}.
*
* @var array
*/
private $filters = array();
/**
* {@link aCssMinifierPlugin Plugins}.
*
* @var array
*/
private $plugins = array();
/**
* Minified source.
*
* @var string
*/
private $minified = "";
/**
* Constructer.
*
* Creates instances of {@link aCssMinifierFilter filters} and {@link aCssMinifierPlugin plugins}.
*
* @param string $source CSS source [optional]
* @param array $filters Filter configuration [optional]
* @param array $plugins Plugin configuration [optional]
* @return void
*/
public function __construct($source = null, array $filters = null, array $plugins = null)
{
$filters = array_merge(array
(
"ImportImports" => false,
"RemoveComments" => true,
"RemoveEmptyRulesets" => true,
"RemoveEmptyAtBlocks" => true,
"ConvertLevel3Properties" => false,
"ConvertLevel3AtKeyframes" => false,
"Variables" => true,
"RemoveLastDelarationSemiColon" => true
), is_array($filters) ? $filters : array());
$plugins = array_merge(array
(
"Variables" => true,
"ConvertFontWeight" => false,
"ConvertHslColors" => false,
"ConvertRgbColors" => false,
"ConvertNamedColors" => false,
"CompressColorValues" => false,
"CompressUnitValues" => false,
"CompressExpressionValues" => false
), is_array($plugins) ? $plugins : array());
// Filters
foreach ($filters as $name => $config)
{
if ($config !== false)
{
$class = "Css" . $name . "MinifierFilter";
$config = is_array($config) ? $config : array();
if (class_exists($class))
{
$this->filters[] = new $class($this, $config);
}
else
{
CssMin::triggerError(new CssError(__FILE__, __LINE__, __METHOD__ . ": The filter " . $name . " with the class name " . $class . " was not found"));
}
}
}
// Plugins
foreach ($plugins as $name => $config)
{
if ($config !== false)
{
$class = "Css" . $name . "MinifierPlugin";
$config = is_array($config) ? $config : array();
if (class_exists($class))
{
$this->plugins[] = new $class($this, $config);
}
else
{
CssMin::triggerError(new CssError(__FILE__, __LINE__, __METHOD__ . ": The plugin " . $name . " with the class name " . $class . " was not found"));
}
}
}
// --
if (!is_null($source))
{
$this->minify($source);
}
}
/**
* Returns the minified Source.
*
* @return string
*/
public function getMinified()
{
return $this->minified;
}
/**
* Returns a plugin by class name.
*
* @param string $name Class name of the plugin
* @return aCssMinifierPlugin
*/
public function getPlugin($class)
{
static $index = null;
if (is_null($index))
{
$index = array();
for ($i = 0, $l = count($this->plugins); $i < $l; $i++)
{
$index[get_class($this->plugins[$i])] = $i;
}
}
return isset($index[$class]) ? $this->plugins[$index[$class]] : false;
}
/**
* Minifies the CSS source.
*
* @param string $source CSS source
* @return string
*/
public function minify($source)
{
// Variables
$r = "";
$parser = new CssParser($source);
$tokens = $parser->getTokens();
$filters = $this->filters;
$filterCount = count($this->filters);
$plugins = $this->plugins;
$pluginCount = count($plugins);
$pluginIndex = array();
$pluginTriggerTokens = array();
$globalTriggerTokens = array();
for ($i = 0, $l = count($plugins); $i < $l; $i++)
{
$tPluginClassName = get_class($plugins[$i]);
$pluginTriggerTokens[$i] = $plugins[$i]->getTriggerTokens();
foreach ($pluginTriggerTokens[$i] as $v)
{
if (!in_array($v, $globalTriggerTokens))
{
$globalTriggerTokens[] = $v;
}
}
$pluginTriggerTokens[$i] = "|" . implode("|", $pluginTriggerTokens[$i]) . "|";
$pluginIndex[$tPluginClassName] = $i;
}
$globalTriggerTokens = "|" . implode("|", $globalTriggerTokens) . "|";
/*
* Apply filters
*/
for($i = 0; $i < $filterCount; $i++)
{
// Apply the filter; if the return value is larger than 0...
if ($filters[$i]->apply($tokens) > 0)
{
// ...then filter null values and rebuild the token array
$tokens = array_values(array_filter($tokens));
}
}
$tokenCount = count($tokens);
/*
* Apply plugins
*/
for($i = 0; $i < $tokenCount; $i++)
{
$triggerToken = "|" . get_class($tokens[$i]) . "|";
if (strpos($globalTriggerTokens, $triggerToken) !== false)
{
for($ii = 0; $ii < $pluginCount; $ii++)
{
if (strpos($pluginTriggerTokens[$ii], $triggerToken) !== false || $pluginTriggerTokens[$ii] === false)
{
// Apply the plugin; if the return value is TRUE continue to the next token
if ($plugins[$ii]->apply($tokens[$i]) === true)
{
continue 2;
}
}
}
}
}
// Stringify the tokens
for($i = 0; $i < $tokenCount; $i++)
{
$r .= (string) $tokens[$i];
}
$this->minified = $r;
return $r;
}
}

/**
* CssMin - A (simple) css minifier with benefits
*
* --
* Copyright (c) 2011 Joe Scylla <[email protected]>
*
* 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 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 CssMin
* @link http://code.google.com/p/cssmin/
* @author Joe Scylla <[email protected]>
* @copyright 2008 - 2011 Joe Scylla <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version 3.0.1
*/
class CssMin
{
/**
* Index of classes
*
* @var array
*/
private static $classIndex = array();
/**
* Parse/minify errors
*
* @var array
*/
private static $errors = array();
/**
* Verbose output.
*
* @var boolean
*/
private static $isVerbose = false;
/**
* {@link http://goo.gl/JrW54 Autoload} function of CssMin.
*
* @param string $class Name of the class
* @return void
*/
public static function autoload($class)
{
if (isset(self::$classIndex[$class]))
{
require(self::$classIndex[$class]);
}
}
/**
* Return errors
*
* @return array of {CssError}.
*/
public static function getErrors()
{
return self::$errors;
}
/**
* Returns if there were errors.
*
* @return boolean
*/
public static function hasErrors()
{
return count(self::$errors) > 0;
}
/**
* Initialises CssMin.
*
* @return void
*/
public static function initialise()
{
// Create the class index for autoloading or including
$paths = array(dirname(__FILE__));
while (list($i, $path) = each($paths))
{
$subDirectorys = glob($path . "*", GLOB_MARK | GLOB_ONLYDIR | GLOB_NOSORT);
if (is_array($subDirectorys))
{
foreach ($subDirectorys as $subDirectory)
{
$paths[] = $subDirectory;
}
}
$files = glob($path . "*.php", 0);
if (is_array($files))
{
foreach ($files as $file)
{
$class = substr(basename($file), 0, -4);
self::$classIndex[$class] = $file;
}
}
}
krsort(self::$classIndex);
// Only use autoloading if spl_autoload_register() is available and no __autoload() is defined (because
// __autoload() breaks if spl_autoload_register() is used.
if (function_exists("spl_autoload_register") && !is_callable("__autoload"))
{
spl_autoload_register(array(__CLASS__, "autoload"));
}
// Otherwise include all class files
else
{
foreach (self::$classIndex as $class => $file)
{
if (!class_exists($class))
{
require_once($file);
}
}
}
}
/**
* Minifies CSS source.
*
* @param string $source CSS source
* @param array $filters Filter configuration [optional]
* @param array $plugins Plugin configuration [optional]
* @return


Arnav Joy comments:

are you using any other extension of woocommerce plugin ?
or are you using table rate shipping in your site?

2014-08-18

Bob answers:

can you remove woo commerce and re-install it again(download fresh woocommerce and upload it)?

if that not work

please temporary put comment at line no. 186 in woocommerce/includes/admin/wc-admin-functions.php
the content you should comment is $compiled_css = CssMin::minify( $compiled_css );


movino4me comments:

I have tried installation and posted in my question

<em>
I have tried uploading a previous version of wordpress via ftp and renaming files but this just gives even more error codes</em>

line 186 currently has this
$compiled_css = CssMin::minify( $compiled_css );