     1: <?php
     2: /**
     3:  * Designed to allow caching
     4:  *
     5:  * @author Mike Schinkel <mike@newclarity.net>
     6:  *
     7:  */
     8: /**
     9:  * @param string $css_dir
    10:  */
    11: function output_css( $css_dir ) {
    12:   $files = headers( array(
    13:     'css_dir' => $css_dir,
    14:     'color_scheme' => filter_input( INPUT_GET, 'color', FILTER_SANITIZE_STRING ),
    15:     'cache_seconds' =>  filter_input( INPUT_GET, 'cache', FILTER_SANITIZE_NUMBER_INT ),
    16:    ));
    17:   body( $files );
    18: }
    19: /**
    20:  * @param array $args
    21:  *
    22:  * @return array Files
    23:  */
    24: function headers( $args ) {
    25:   header( "Content-type: text/css" );
    26:
    27:   if ( empty( $args['color_scheme'] ) )
    28:     $args['color_scheme'] = 'grey';
    29:   if ( empty( $args['cache_seconds'] ) )
    30:     $args['cache_seconds'] = 3600;
    31:
    32:   $files = array();
    33:   $files[0] = "{$args['css_dir']}/styles.css";
    34:   $files[1] = "{$args['css_dir']}/styles-{$args['color_scheme']}.css";
    35:
    36:   $file_time = filemtime( __FILE__ );
    37:   foreach( $files as $file )
    38:     if ( $file_time < ( $new_file_time = filemtime( $file ) ) )
    39:       $file_time = $new_file_time;
    40:
    41:   $time_string = format_gmt_string( $file_time );
    42:   $timeout = format_gmt_string( time() + (int)$args['cache_seconds'] );
    43:   $etag = (string)$file_time;
    44:
    45:   $modified = true;
    46:   $matched = false;
    47:
    48:   if ( ! empty( $_SERVER['HTTP_IF_NONE_MATCH'] ) )
    49:     $matched = $etag == trim( $_SERVER['HTTP_IF_NONE_MATCH'], '"' );
    50:
    51:   if ( ! empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) )
    52:     $modified = $time_string != $_SERVER['HTTP_IF_MODIFIED_SINCE'];
    53:
    54:   if ( $matched || ! $modified ) {
    55:     header('HTTP/1.1 304 Not Modified');
    56:     exit();
    57:   } else {
    58:     header( "Cache-Control: public, max-age={$args['cache_seconds']}" );
    59:     header( "Last-Modified: {$time_string}" );
    60:     header( "ETag: \"{$file_time}\"" );
    61:     header( "Expires: {$timeout}" );
    62:     header( "Connection: close" );
    63:   }
    64:   return $files;
    65: }
    66: /**
    67:  * Loads contents of CSS files and then echos them out.
    68:  *
    69:  * @param array $files
    70:  */
    71: function body( $files ) {
    72:   foreach( $files as $file ) {
    73:     if ( file_exists( $file ) ) {
    74:       echo file_get_contents( $file );
    75:     }
    76:   }
    77: }
    78: /**
    79:  * @param datetime $datetime
    80:  * @return string
    81:  */
    82: function format_gmt_string( $datetime ) {
    83:   return gmdate( 'D, d M Y H:i:s ', $datetime ) . 'GMT';
    84: }
    85:
    86: