compressor

Gesponsorde koppelingen

PHP script bestanden

  1. compressor

« Lees de omschrijving en reacties

.htaccess

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# Default options. Allways available in apache2.
Options +FollowSymLinks
AddDefaultCharset utf-8
LimitRequestBody 10240000
#@todo: ETag Not-Modified implementeren
FileETag none

#ErrorDocument 400 400.php
#ErrorDocument 401 401.php
#ErrorDocument 402 402.php
#ErrorDocument 403 403.php
#ErrorDocument 404 404.php

#mod specific improvements.
<IfModule mod_rewrite.c>
    RewriteEngine On
    
    #SEO: altijd www gebruiken.
    RewriteCond %{HTTP_HOST} ^jedomein.nl [NC]
    RewriteRule ^(.*)$ http://www.jedomein.nl/$1 [L,R=301]
    
    #css/js compressing
    RewriteRule _css/(.+).css$ compress.php?type=css&file=$1.css
    RewriteRule _js/(.+).js$ compress.php?type=js&file=$1.js
    
    #ales naar index.php, op 'echte' bestanden na - zelf implementeren.
    #RewriteCond %{REQUEST_FILENAME} !-f
    #RewriteCond %{REQUEST_FILENAME} !-d
    #RewriteRule . index.php [L]
</IfModule>

<IfModule mod_deflate.c>
    #gzip compressie
    SetOutputFilter DEFLATE
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
    SetEnvIfNoCase Request_URI \
        \.(?:gif|jpe?g|png|swf|pdf|zip|flv)$ no-gzip dont-vary
</IfModule>

<IfModule mod_gzip.c>
    mod_gzip_on Yes

    mod_gzip_item_include mime ^application/x-javascript$
    mod_gzip_item_include mime ^application/json$
    mod_gzip_item_include mime ^text/.*$

    mod_gzip_item_include file \.html$
    mod_gzip_item_include file \.php$
    mod_gzip_item_include file \.js$
    mod_gzip_item_include file \.css$
    mod_gzip_item_include file \.txt$
    mod_gzip_item_include file \.xml$
    mod_gzip_item_include file \.json$
    <IfModule mod_header.c>
        Header append Vary Accept-Encoding
    </IfModule>
</IfModule>

<IfModule mod_expires.c>
    #cache rules to decrease data traffic
    ExpiresActive On
    ExpiresDefault A0
    <FilesMatch "\.(gif|jpg|jpeg|png|swf)$">
      ExpiresDefault A604800
    </FilesMatch>
</IfModule>

<IfModule mod_header.c>
    #cache rules to decrease data traffic
    Header append Vary User-Agent env=!dont-vary
        
    <FilesMatch "\.(php|html|htm)$">
       Header set imagetoolbar "no"
    </FilesMatch>
</IfModule>


compressor.php
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

/**
 * Compressing/caching can take some time.
 */

ini_set( "max_time_limit", 120 );
ini_set( "memory_limit", "32M" );

require_once "_lib/Minifier.php";

$types = array(
    "js" => "JSMinifier",
    "css" => "CSSMinifier"
);

if( isset( $_GET['type'] ) && array_key_exists( $_GET['type'], $types ) && !empty( $_GET['file'] ) ) {
    $compress = new $types[$_GET['type']]( $_GET['file'] );
    echo $compress->getOutput();
}


?>


_lib/Minifier.php
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
<?php
/**
 * Minifier for CSS and JS files. For file combining use this notation: _js/file1.js:file2.js:file3.js
 *
 */

abstract class Minifier {

    /**
     * Output buffer.
     *
     * @var string
     */

    private $output = "";

    /**
     * Absolute path.
     *
     * @var string
     */

    private $cwd;
    
    /**
     * Default expire time for browser.
     *
     * @var integer
     */

    private $expire = 180000;

    /**
     * Allowed file types.
     */

    const TYPE_JS = "js";
    const TYPE_CSS = "css";
    
    /**
     * Use compression?
     *
     */

    const USE_COMPRESSION = true;

    /**
     * Content types for header() usage.
     *
     * @var array
     */

    private $contentTypes = array(
        self::TYPE_JS => "javascript",
        self::TYPE_CSS => "css"
    );
    
    /**
     * Files to combine compress.
     *
     * @var array
     */

    private $files = array();

    /**
     * Compressor initializer
     *
     */

    public function __construct( $file ) {
        $this->cwd = getcwd() . DIRECTORY_SEPARATOR;
        $this->files = $this->setFiles( $file );
    }

    
    /**
     * Find files to parse
     *
     * @param string $file
     * @return array
     */

    private function setFiles( $file ) {
        if( strpos( $file, ":" ) > 1 ) {
            $files = explode( ":", $file );
        }

        else {
            $files = array( $file );
        }

        return $files;
    }

    
    /**
     *    Check if the cache file still exists.
     *
     * @return bool
     */

    private function fileChanged( $file ) {
        return !is_file( $this->cacheName( $file ) );
    }

    
    /**
     *    Returns the name of the cache file
     *
     * @param bool $wildcard
     * @return string
     */

    private function cacheName($file, $wildcard = false) {
        if( !is_dir( $this->cwd . '.cache/' ) ) {
            mkdir( $this->cwd . '.cache' );
        }

        $stat = stat( $this->cwd . "_" . $this->getType() . "/" . $file );
        return $this->cwd . '.cache/' . $file . '.' . ( $wildcard ? '*' : ( $stat['size'] . '-' . $stat['mtime'] ) ) . '.cache';
    }


    /**
     * Load files and check if it has to be re-cached or the old cache file can be used.
     *
     */

    private function processFile( $file ) {
        if( file_exists( $this->cwd . "_" . $this->getType() . "/" . $file ) ) {
            if( self::USE_COMPRESSION == true ) {
                if( $this->fileChanged( $file ) ) {
                    $this->expire = -72000;
                }


                $currentCache = $this->cacheName( $file );

                // the cache exists. show it
                if( !$this->fileChanged( $file ) ) {
                    $this->output .= file_get_contents( $currentCache );
                }

                else {
                    // remove old cache files for this file
                    if ( $deadFiles = glob( $this->cacheName( $file, true ), GLOB_NOESCAPE ) ) {
                        foreach( $deadFiles as $deadFile ) {
                            unlink( $deadFile );
                        }
                    }


                    $file_content = file_get_contents( $this->cwd . "_" . $this->getType() . "/" . $file );

                    $compressed = $this->compress( $file_content );
                    file_put_contents( $currentCache, $compressed );

                    $this->output .= $compressed;
                }
            }

            else {
                $this->output .= file_get_contents( $this->cwd . "_" . $this->getType() . "/" . $file );
            }
        }

        else {
            $this->output .= "/*404 - File not found( $file )*/";
        }

        $this->output .= PHP_EOL;
    }

    
    /**
     * Method for view purposes.
     *
     */

    private function renderOutput() {
        foreach( $this->files as $file ) {
            $this->processFile( $file );
        }
    }

    
    /**
     * Send content-type header and expires header.
     *
     */

    private function sendHeaders() {
        header( 'Content-Type: text/' . $this->contentTypes[$this->getType()] . '; charset=utf-8' );
        header( 'Expires: ' . gmdate('D, d M Y H:i:s', time() + $this->expire) . ' GMT' );
    }

    
    /**
     * Parse files, send headers and return output.
     *
     * @return unknown
     */

    public function getOutput() {
        $this->renderOutput();
        $this->sendHeaders();
        return $this->output;
    }

    
    /**
     * Compress the file and return as string.
     *
     * @param string $output
     */

    abstract protected function compress( $output );

    /**
     * Returns the directory where the file must be read from.
     */

    abstract protected function getType();
}


/**
 * Class which compresses the given CSS file, and caches it.
 * The file will be cached each time it changes.
 *
 */

class CSSMinifier extends Minifier {

    protected function compress( $output ) {
        require_once "CSSMin.php";
        return CSSMin::minify( $output );
    }


    protected function getType() {
        return self::TYPE_CSS;
    }
}


/**
 * Class which compresses the given CSS file, and caches it.
 * The file will be chached each time it changes.
 *
 */

class JSMinifier extends Minifier {

    protected function compress( $output ) {
        require_once "JSMin.php";
        return JSMin::minify( $output );
    }


    protected function getType() {
        return self::TYPE_JS;
    }
}


?>


_lib/CSSMin.php
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php

/**
 * @author Martijn!
 * @url http://www.phphulp.nl/php/scripts/1/1145/
 *
 */

class CSSMin {

    public static function minify( $css ) {
        $css = preg_replace('/\/\*.*?\*\//s', '', $css);
        $css = str_replace(array("\r", "\n", "\t"), '', $css);
        $css = preg_replace('/\s*({|}|;|:|,)\s*/', '$1', $css);

        $aMatch = array();
        
        if( preg_match_all('/{.*?}/s', $css, $aMatch) ) {
            $aMatch[0] = array_unique($aMatch[0]);

            foreach( $aMatch[0] as $k => $v ) {
                $l = strlen($v);
                if( $v[$l-2] == ';' ) {
                    $v = substr($v, 0, $l-2) . '}';
                }

                $css = str_replace($aMatch[0][$k], $v, $css);
            }
        }


        return $css;
    }
}


?>


_lib/JSMin.php
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
<?php
/**
 * jsmin.php - PHP implementation of Douglas Crockford's JSMin.
 *
 * This is pretty much a direct port of jsmin.c to PHP with just a few
 * PHP-specific performance tweaks. Also, whereas jsmin.c reads from stdin and
 * outputs to stdout, this library accepts a string as input and returns another
 * string as output.
 *
 * PHP 5 or higher is required.
 *
 * Permission is hereby granted to use this version of the library under the
 * same terms as jsmin.c, which has the following license:
 *
 * --
 * Copyright (c) 2002 Douglas Crockford  (www.crockford.com)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * The Software shall be used for Good, not Evil.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * --
 *
 * @package JSMin
 * @author Ryan Grove <[email protected]>
 * @copyright 2002 Douglas Crockford <[email protected]> (jsmin.c)
 * @copyright 2007 Ryan Grove <[email protected]> (PHP port)
 * @license http://opensource.org/licenses/mit-license.php MIT License
 * @version 1.1.0 (2007-06-01)
 * @link http://code.google.com/p/jsmin-php/
 */


class JSMin {
  const ORD_LF    = 10;
  const ORD_SPACE = 32;

  protected $a           = '';
  protected $b           = '';
  protected $input       = '';
  protected $inputIndex  = 0;
  protected $inputLength = 0;
  protected $lookAhead   = null;
  protected $output      = array();

  // -- Public Static Methods --------------------------------------------------

  public static function minify($js) {
    $jsmin = new JSMin($js);
    return $jsmin->min();
  }


  // -- Public Instance Methods ------------------------------------------------

  public function __construct($input) {
    $this->input       = str_replace("\r\n", "\n", $input);
    $this->inputLength = strlen($this->input);
  }


  // -- Protected Instance Methods ---------------------------------------------

  protected function action($d) {
    switch($d) {
      case
1:
        $this->output[] = $this->a;

      case
2:
        $this->a = $this->b;

        if ($this->a === "'" || $this->a === '"') {
          for (;;) {
            $this->output[] = $this->a;
            $this->a        = $this->get();

            if ($this->a === $this->b) {
              break;
            }


            if (ord($this->a) <= self::ORD_LF) {
              throw new JSMinException('Unterminated string literal.');
            }


            if ($this->a === '\\') {
              $this->output[] = $this->a;
              $this->a        = $this->get();
            }
          }
        }

      case
3:
        $this->b = $this->next();

        if ($this->b === '/' && (
            $this->a === '(' || $this->a === ',' || $this->a === '=' ||
            $this->a === ':' || $this->a === '[' || $this->a === '!' ||
            $this->a === '&' || $this->a === '|' || $this->a === '?')) {

          $this->output[] = $this->a;
          $this->output[] = $this->b;

          for (;;) {
            $this->a = $this->get();

            if ($this->a === '/') {
              break;
            }

            elseif ($this->a === '\\') {
              $this->output[] = $this->a;
              $this->a        = $this->get();
            }

            elseif (ord($this->a) <= self::ORD_LF) {
              throw new JSMinException('Unterminated regular expression '.
                  'literal.');
            }


            $this->output[] = $this->a;
          }


          $this->b = $this->next();
        }
    }
  }


  protected function get() {
    $c = $this->lookAhead;
    $this->lookAhead = null;

    if ($c === null) {
      if ($this->inputIndex < $this->inputLength) {
        $c = $this->input[$this->inputIndex];
        $this->inputIndex += 1;
      }

      else {
        $c = null;
      }
    }


    if ($c === "\r") {
      return "\n";
    }


    if ($c === null || $c === "\n" || ord($c) >= self::ORD_SPACE) {
      return $c;
    }


    return ' ';
  }


  protected function isAlphaNum($c) {
    return ord($c) > 126 || $c === '\\' || preg_match('/^[\w\$]$/', $c) === 1;
  }


  protected function min() {
    $this->a = "\n";
    $this->action(3);

    while ($this->a !== null) {
      switch ($this->a) {
        case
' ':
          if ($this->isAlphaNum($this->b)) {
            $this->action(1);
          }

          else {
            $this->action(2);
          }

          break;

        case
"\n":
          switch ($this->b) {
            case
'{':
            case
'[':
            case
'(':
            case
'+':
            case
'-':
              $this->action(1);
              break;

            case
' ':
              $this->action(3);
              break;

            default:

              if ($this->isAlphaNum($this->b)) {
                $this->action(1);
              }

              else {
                $this->action(2);
              }
          }

          break;

        default:

          switch ($this->b) {
            case
' ':
              if ($this->isAlphaNum($this->a)) {
                $this->action(1);
                break;
              }


              $this->action(3);
              break;

            case
"\n":
              switch ($this->a) {
                case
'}':
                case
']':
                case
')':
                case
'+':
                case
'-':
                case
'"':
                case
"'":
                  $this->action(1);
                  break;

                default:

                  if ($this->isAlphaNum($this->a)) {
                    $this->action(1);
                  }

                  else {
                    $this->action(3);
                  }
              }

              break;

            default:

              $this->action(1);
              break;
          }
      }
    }


    return implode('', $this->output);
  }


  protected function next() {
    $c = $this->get();

    if ($c === '/') {
      switch($this->peek()) {
        case
'/':
          for (;;) {
            $c = $this->get();

            if (ord($c) <= self::ORD_LF) {
              return $c;
            }
          }

        case
'*':
          $this->get();

          for (;;) {
            switch($this->get()) {
              case
'*':
                if ($this->peek() === '/') {
                  $this->get();
                  return ' ';
                }

                break;

              case
null:
                throw new JSMinException('Unterminated comment.');
            }
          }

        default:

          return $c;
      }
    }


    return $c;
  }


  protected function peek() {
    $this->lookAhead = $this->get();
    return $this->lookAhead;
  }
}


// -- Exceptions ---------------------------------------------------------------
class JSMinException extends Exception {}
?>

 
 

Om de gebruiksvriendelijkheid van onze website en diensten te optimaliseren maken wij gebruik van cookies. Deze cookies gebruiken wij voor functionaliteiten, analytische gegevens en marketing doeleinden. U vindt meer informatie in onze privacy statement.