| 1 |
<?php |
| 2 |
/** |
| 3 |
* Surge Installer |
| 4 |
* |
| 5 |
* This file runs when Surge needs to be installed. Its main purpose is to copy |
| 6 |
* the advanced-cache.php loader and add the WP_CACHE constant to wp-config.php. |
| 7 |
* |
| 8 |
* @package Surge |
| 9 |
*/ |
| 10 |
|
| 11 |
namespace Surge; |
| 12 |
|
| 13 |
include_once( __DIR__ . '/common.php' ); |
| 14 |
|
| 15 |
// Remove old advanced-cache.php. |
| 16 |
if ( file_exists( WP_CONTENT_DIR . '/advanced-cache.php' ) ) { |
| 17 |
unlink( WP_CONTENT_DIR . '/advanced-cache.php' ); |
| 18 |
} |
| 19 |
|
| 20 |
// Copy our own advanced-cache.php. |
| 21 |
$ret = copy( __DIR__ . '/advanced-cache.php', WP_CONTENT_DIR . '/advanced-cache.php' ); |
| 22 |
if ( ! $ret ) { |
| 23 |
update_option( 'surge_installed', 3 ); |
| 24 |
return; |
| 25 |
} |
| 26 |
|
| 27 |
// Create the cache directory |
| 28 |
wp_mkdir_p( CACHE_DIR ); |
| 29 |
|
| 30 |
// Nothing to do if WP_CACHE is already on or forced skip. |
| 31 |
if ( defined( 'WP_CACHE' ) && WP_CACHE || apply_filters( 'surge_skip_config_update', false ) ) { |
| 32 |
update_option( 'surge_installed', 1 ); |
| 33 |
return; |
| 34 |
} |
| 35 |
|
| 36 |
// Fetch wp-config.php contents. |
| 37 |
$config_path = ABSPATH . 'wp-config.php'; |
| 38 |
if ( ! file_exists( ABSPATH . 'wp-config.php' ) |
| 39 |
&& @file_exists( dirname( ABSPATH ) . '/wp-config.php' ) |
| 40 |
&& ! @file_exists( dirname( ABSPATH ) . '/wp-settings.php' ) |
| 41 |
) { |
| 42 |
$config_path = dirname( ABSPATH ) . '/wp-config.php'; |
| 43 |
} |
| 44 |
|
| 45 |
$config = file_get_contents( $config_path ); |
| 46 |
|
| 47 |
// Remove existing WP_CACHE definitions. |
| 48 |
// Some regex inherited from https://github.com/wp-cli/wp-config-transformer/ |
| 49 |
$pattern = '#(?<=^|;|<\?php\s|<\?\s)(\s*?)(\h*define\s*\(\s*[\'"](WP_CACHE)[\'"]\s*)' |
| 50 |
. '(,\s*([\'"].*?[\'"]|.*?)\s*)((?:,\s*(?:true|false)\s*)?\)\s*;\s)#ms'; |
| 51 |
|
| 52 |
$config = preg_replace( $pattern, '', $config ); |
| 53 |
|
| 54 |
// Add a WP_CACHE to wp-config.php. |
| 55 |
$anchor = "/* That's all, stop editing!"; |
| 56 |
if ( false !== strpos( $config, $anchor ) ) { |
| 57 |
$config = str_replace( $anchor, "define( 'WP_CACHE', true );\n\n" . $anchor, $config ); |
| 58 |
} elseif ( false !== strpos( $config, '<?php' ) ) { |
| 59 |
$config = preg_replace( '#^<\?php\s.*#', "$0\ndefine( 'WP_CACHE', true );\n", $config ); |
| 60 |
} |
| 61 |
|
| 62 |
// Write modified wp-config.php. |
| 63 |
$bytes = file_put_contents( $config_path, $config ); |
| 64 |
update_option( 'surge_installed', $bytes ? 1 : 2 ); |
| 65 |
|