PluginProbe
Surge / 1.0.3
Surge v1.0.3
trunk 0.1.0 1.0.0 1.0.2 1.0.3 1.0.5 1.1.0 1.2.0 1.2.1
surge / include / cache.php

cache.php in Surge 1.0.3, at include/cache.php

118 lines 2.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Cache Content
4 *
5 * This file is loaded when there's a chance the request content should be
6 * saved to cache.
7 *
8 * @package Surge
9 */
10
11 namespace Surge;
12
13 include_once( __DIR__ . '/common.php' );
14
15 /**
16 * The main output buffer callback.
17 *
18 * @param string $contents The buffer contents.
19 *
20 * @return string Contents.
21 */
22 $ob_callback = function( $contents ) {
23 $ttl = config( 'ttl' );
24
25 if ( $ttl < 1 ) {
26 return $contents;
27 }
28
29 $skip = false;
30
31 foreach ( headers_list() as $header ) {
32 list( $name, $value ) = array_map( 'trim', explode( ':', $header, 2 ) );
33
34 // Do not store or vary on these headers.
35 if ( in_array( strtolower( $name ), ['x-cache', 'x-powered-by'] ) ) {
36 continue;
37 }
38
39 $headers[ $name ][] = $value;
40
41 if ( strtolower( $name ) == 'set-cookie' ) {
42 $skip = true;
43 break;
44 }
45
46 if ( strtolower( $name ) == 'cache-control' ) {
47 if ( stripos( $value, 'no-cache' ) !== false || stripos( $value, 'max-age=0' ) !== false ) {
48 $skip = true;
49 break;
50 }
51 }
52 }
53
54 if ( ! empty( $_SERVER['HTTP_AUTHORIZATION'] ) ) {
55 $skip = true;
56 }
57
58 if ( ! in_array( strtoupper( $_SERVER['REQUEST_METHOD'] ), [ 'GET', 'HEAD' ] ) ) {
59 $skip = true;
60 }
61
62 if ( ! in_array( http_response_code(), [ 200, 301, 302, 404 ] ) ) {
63 $skip = true;
64 }
65
66 if ( $skip ) {
67 return $contents;
68 }
69
70 $key = key();
71
72 $meta = [
73 'code' => http_response_code(),
74 'headers' => $headers,
75 'created' => time(),
76 'expires' => time() + $ttl,
77 'flags' => array_unique( flag() ),
78 'path' => $key['path'],
79 ];
80
81 $meta = json_encode( $meta );
82 $cache_key = md5( json_encode( $key ) );
83 $level = substr( $cache_key, -2 );
84
85 if ( ! wp_mkdir_p( CACHE_DIR . "/{$level}/" ) ) {
86 return $contents;
87 }
88
89 // Open a new cache file.
90 $hash = wp_generate_password( 6, false );
91 $f = fopen( CACHE_DIR . "/{$level}/{$cache_key}.{$hash}.php", 'xb' );
92
93 // Could not create file.
94 if ( false === $f ) {
95 return $contents;
96 }
97
98 fwrite( $f, '<?php exit; ?>' );
99 fwrite( $f, pack( 'L', strlen( $meta ) ) );
100 fwrite( $f, $meta );
101 fwrite( $f, $contents );
102
103 // Close the file.
104 fclose( $f );
105
106 // Atomic (hopefully) rename.
107 if ( ! rename( CACHE_DIR . "/{$level}/{$cache_key}.{$hash}.php",
108 CACHE_DIR . "/{$level}/{$cache_key}.php" )
109 ) {
110 unlink( CACHE_DIR . "/{$level}/{$cache_key}.{$hash}.php" );
111 }
112
113 return $contents;
114 };
115
116 // Attach to main output buffer.
117 ob_start( $ob_callback );
118