Skip to content

Commit

Permalink
Add hostsToRewrite option and advanced-options page.
Browse files Browse the repository at this point in the history
  • Loading branch information
john-shaffer committed Sep 19, 2021
1 parent b3cd0d7 commit 62ed042
Show file tree
Hide file tree
Showing 9 changed files with 225 additions and 19 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
- accept self-signed certs during sitemap crawling @john-shaffer
- detect dead jobs and mark as failed @john-shaffer
- mark duplicated waiting jobs as skipped on jobs page @john-shaffer
- add an option to process the queue immediately #794 @john-shaffer
- add ability to rewrite hosts specified on a new advanced options page @john-shaffer
- as part of this, changed the host replacement function to use strtr instead of str_replace to avoid replacing things that we just replaced

## WP2Static 7.1.7

Expand Down
2 changes: 1 addition & 1 deletion phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ parameters:
count: 5
- message: '#^In method "WP2Static\\\S+::\S+", you should not use the \$_(GET|POST) superglobal#'
path: src/CoreOptions.php
count: 19
count: 20
- message: '#^In method "WP2Static\\\S+::\S+", you should not use the \$_(GET|POST) superglobal#'
path: src/ViewRenderer.php
count: 32
Expand Down
12 changes: 12 additions & 0 deletions src/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ public static function registerOptionsPage() : void {
'diagnostics' => [ ViewRenderer::class, 'renderDiagnosticsPage' ],
'logs' => [ ViewRenderer::class, 'renderLogsPage' ],
'addons' => [ ViewRenderer::class, 'renderAddonsPage' ],
'advanced' => [ ViewRenderer::class, 'renderAdvancedOptionsPage' ],
];

foreach ( $submenu_pages as $slug => $method ) {
Expand Down Expand Up @@ -471,6 +472,17 @@ public static function wp2staticTrashedPostHandler() : void {
}
}

public static function wp2staticUISaveAdvancedOptions() : void {
CoreOptions::savePosted( 'advanced' );

do_action( 'wp2static_addon_ui_save_advanced_options' );

check_admin_referer( 'wp2static-ui-advanced-options' );

wp_safe_redirect( admin_url( 'admin.php?page=wp2static-advanced' ) );
exit;
}

public static function wp2staticEnqueueJobs() : void {
// check each of these in order we want to enqueue
$job_types = [
Expand Down
72 changes: 71 additions & 1 deletion src/CoreOptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public static function createTable() : void {
id mediumint(9) NOT NULL AUTO_INCREMENT,
name VARCHAR(191) NOT NULL,
value VARCHAR(249) NOT NULL,
blob_value BLOB,
label VARCHAR(249) NULL,
description VARCHAR(249) NULL,
PRIMARY KEY (id)
Expand Down Expand Up @@ -59,6 +60,10 @@ public static function seedOptions() : void {
"INSERT IGNORE INTO $table_name (name, value, label, description)
VALUES (%s, %s, %s, %s);";

$blob_query_string =
"INSERT IGNORE INTO $table_name (name, value, label, description, blob_value)
VALUES (%s, %s, %s, %s, %s);";

$queries[] = $wpdb->prepare(
$query_string,
'detectCustomPostTypes',
Expand Down Expand Up @@ -203,6 +208,17 @@ public static function seedOptions() : void {
'How to send completion webhook payload (GET|POST).'
);

// Advanced options

$queries[] = $wpdb->prepare(
$blob_query_string,
'hostsToRewrite',
'1',
'Hosts to Rewrite',
'Hosts to rewrite to the deployment URL.',
'localhost'
);

foreach ( $queries as $query ) {
$wpdb->query( $query );
}
Expand Down Expand Up @@ -246,6 +262,47 @@ public static function getValue( string $name ) : string {
return $option_value;
}

/**
* Get option BLOB value
*
* @throws WP2StaticException
* @return string option BLOB value
*/
public static function getBlobValue( string $name ) : string {
global $wpdb;

$table_name = $wpdb->prefix . self::$table_name;

$sql = $wpdb->prepare(
"SELECT blob_value FROM $table_name WHERE" . ' name = %s LIMIT 1',
$name
);

$option_value = $wpdb->get_var( $sql );

if ( ! is_string( $option_value ) ) {
return '';
}

return $option_value;
}

/**
* @return array<string>
*/
public static function getLineDelimitedBlobValue( string $name ) : array {
$vals = preg_split(
'/\r\n|\r|\n/',
self::getBlobValue( $name )
);

if ( ! $vals ) {
return [];
}

return $vals;
}

/**
* Get option (value, description, label, etc)
*
Expand All @@ -257,7 +314,8 @@ public static function get( string $name ) {
$table_name = $wpdb->prefix . self::$table_name;

$sql = $wpdb->prepare(
"SELECT name, value, label, description FROM $table_name WHERE" . ' name = %s LIMIT 1',
"SELECT name, value, label, description, blob_value
FROM $table_name WHERE" . ' name = %s LIMIT 1',
$name
);

Expand Down Expand Up @@ -477,6 +535,18 @@ public static function savePosted( string $screen = 'core' ) : void {
[ 'name' => 'autoJobQueueDeployment' ]
);

break;
case 'advanced':
$hosts_to_rewrite = preg_replace(
'/^\s+|\s+$/m',
'',
$_POST['hostsToRewrite']
);
$wpdb->update(
$table_name,
[ 'blob_value' => $hosts_to_rewrite ],
[ 'name' => 'hostsToRewrite' ]
);
break;
}
}
Expand Down
37 changes: 24 additions & 13 deletions src/SimpleRewriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,22 +53,33 @@ public static function rewriteFileContents( string $file_contents ) : string

$wordpress_site_url = untrailingslashit( $wordpress_site_url );
$destination_url = untrailingslashit( $destination_url );
$destination_url_rel = URLHelper::getProtocolRelativeURL( $destination_url );
$destination_url_rel_cslashes = addcslashes( $destination_url_rel, '/' );

$search_patterns = [
$wordpress_site_url,
URLHelper::getProtocolRelativeURL( $wordpress_site_url ),
addcslashes( URLHelper::getProtocolRelativeURL( $wordpress_site_url ), '/' ),
];
$replace_patterns = [
$destination_url,
URLHelper::getProtocolRelativeURL( $destination_url ),
addcslashes( URLHelper::getProtocolRelativeURL( $destination_url ), '/' ),
$replace_pairs = [
$wordpress_site_url => $destination_url,
URLHelper::getProtocolRelativeURL( $wordpress_site_url ) =>
URLHelper::getProtocolRelativeURL( $destination_url ),
addcslashes( URLHelper::getProtocolRelativeURL( $wordpress_site_url ), '/' ) =>
addcslashes( URLHelper::getProtocolRelativeURL( $destination_url ), '/' ),
];

$rewritten_contents = str_replace(
$search_patterns,
$replace_patterns,
$file_contents
$hosts = CoreOptions::getLineDelimitedBlobValue( 'hostsToRewrite' );

foreach ( $hosts as $host ) {
if ( $host ) {
$host_rel = URLHelper::getProtocolRelativeURL( 'http://' . $host );

$replace_pairs[ 'http:' . $host_rel ] = $destination_url;
$replace_pairs[ 'https:' . $host_rel ] = $destination_url;
$replace_pairs[ $host_rel ] = $destination_url_rel;
$replace_pairs[ addcslashes( $host_rel, '/' ) ] = $destination_url_rel_cslashes;
}
}

$rewritten_contents = strtr(
$file_contents,
$replace_pairs
);

return $rewritten_contents;
Expand Down
13 changes: 13 additions & 0 deletions src/ViewRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,19 @@ public static function renderOptionsPage() : void {
require_once WP2STATIC_PATH . 'views/options-page.php';
}

public static function renderAdvancedOptionsPage() : void {
CoreOptions::init();

$view = [];
$view['nonce_action'] = 'wp2static-ui-advanced-options';

$view['coreOptions'] = [
'hostsToRewrite' => CoreOptions::get( 'hostsToRewrite' ),
];

require_once WP2STATIC_PATH . 'views/advanced-options-page.php';
}

public static function renderDiagnosticsPage() : void {
$view = [];
$view['memoryLimit'] = ini_get( 'memory_limit' );
Expand Down
7 changes: 7 additions & 0 deletions src/WordPressAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,13 @@ public static function registerHooks( string $bootstrap_file ) : void {
0
);

add_action(
'admin_post_wp2static_ui_save_advanced_options',
[ Controller::class, 'wp2staticUISaveAdvancedOptions' ],
10,
0
);

add_action(
'admin_post_wp2static_manually_enqueue_jobs',
[ Controller::class, 'wp2staticManuallyEnqueueJobs' ],
Expand Down
48 changes: 44 additions & 4 deletions tests/unit/SimpleRewriterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ public function testRewrite() {
Mockery::mock( 'overload:\WP2Static\CoreOptions' )
->shouldreceive( 'getValue' )
->withArgs( [ 'deploymentURL' ] )
->andReturn( 'https://bar.com' );
->andReturn( 'https://bar.com' )
->shouldreceive( 'getLineDelimitedBlobValue' )
->withArgs( [ 'hostsToRewrite' ] )
->andReturn( [ 'localhost' ] );
Mockery::mock( 'overload:\WP2Static\SiteInfo' )
->shouldreceive( 'getUrl' )
->withArgs( [ 'site' ] )
Expand Down Expand Up @@ -104,7 +107,10 @@ public function testRewriteFileContents( $raw_html, $expected ) {
Mockery::mock( 'overload:\WP2Static\CoreOptions' )
->shouldreceive( 'getValue' )
->withArgs( [ 'deploymentURL' ] )
->andReturn( 'https://bar.com' );
->andReturn( 'https://bar.com' )
->shouldreceive( 'getLineDelimitedBlobValue' )
->withArgs( [ 'hostsToRewrite' ] )
->andReturn( [ 'localhost' ] );
Mockery::mock( 'overload:\WP2Static\SiteInfo' )
->shouldreceive( 'getUrl' )
->withArgs( [ 'site' ] )
Expand All @@ -124,6 +130,9 @@ public function testRewriteFileContentsHttpToHttps() {
->shouldreceive( 'getValue' )
->withArgs( [ 'deploymentURL' ] )
->andReturn( 'https://bar.com' )
->shouldreceive( 'getLineDelimitedBlobValue' )
->withArgs( [ 'hostsToRewrite' ] )
->andReturn( [ 'localhost' ] )
->getMock();
Mockery::mock( 'overload:\WP2Static\SiteInfo' )
->shouldreceive( 'getUrl' )
Expand All @@ -143,6 +152,9 @@ public function testRewriteFileContentsHttpsToHttp() {
->shouldreceive( 'getValue' )
->withArgs( [ 'deploymentURL' ] )
->andReturn( 'http://bar.com' )
->shouldreceive( 'getLineDelimitedBlobValue' )
->withArgs( [ 'hostsToRewrite' ] )
->andReturn( [ 'localhost' ] )
->getMock();
Mockery::mock( 'overload:\WP2Static\SiteInfo' )
->shouldreceive( 'getUrl' )
Expand All @@ -156,6 +168,28 @@ public function testRewriteFileContentsHttpsToHttp() {
$this->assertEquals( $expected, $actual );
}

public function testRewriteFileContentsHostsToRewrite() {
// Mock the methods and functions used by SimpleRewriter
Mockery::mock( 'overload:\WP2Static\CoreOptions' )
->shouldreceive( 'getValue' )
->withArgs( [ 'deploymentURL' ] )
->andReturn( 'http://bar.com' )
->shouldreceive( 'getLineDelimitedBlobValue' )
->withArgs( [ 'hostsToRewrite' ] )
->andReturn( [ 'localhost' ] )
->getMock();
Mockery::mock( 'overload:\WP2Static\SiteInfo' )
->shouldreceive( 'getUrl' )
->withArgs( [ 'site' ] )
->andReturn( 'https://foo.com/' )
->getMock();

// localhost -> bar.com
$expected = 'http://bar.com/somepath';
$actual = SimpleRewriter::rewriteFileContents( 'https://localhost/somepath' );
$this->assertEquals( $expected, $actual );
}

/**
* @dataProvider rewriteFileContentsProvider
*/
Expand All @@ -164,7 +198,10 @@ public function testRewriteFileContentsDestinationUrlFilter( $raw_html, $expecte
Mockery::mock( 'overload:\WP2Static\CoreOptions' )
->shouldreceive( 'getValue' )
->withArgs( [ 'deploymentURL' ] )
->andReturn( 'https://bar.com' );
->andReturn( 'https://bar.com' )
->shouldreceive( 'getLineDelimitedBlobValue' )
->withArgs( [ 'hostsToRewrite' ] )
->andReturn( [ 'localhost' ] );
Mockery::mock( 'overload:\WP2Static\SiteInfo' )
->shouldreceive( 'getUrl' )
->withArgs( [ 'site' ] )
Expand Down Expand Up @@ -193,7 +230,10 @@ public function testRewriteFileContentsSiteUrlFilter( $raw_html, $expected ) {
Mockery::mock( 'overload:\WP2Static\CoreOptions' )
->shouldreceive( 'getValue' )
->withArgs( [ 'deploymentURL' ] )
->andReturn( 'https://bar.com' );
->andReturn( 'https://bar.com' )
->shouldreceive( 'getLineDelimitedBlobValue' )
->withArgs( [ 'hostsToRewrite' ] )
->andReturn( [ 'localhost' ] );
Mockery::mock( 'overload:\WP2Static\SiteInfo' )
->shouldreceive( 'getUrl' )
->withArgs( [ 'site' ] )
Expand Down
50 changes: 50 additions & 0 deletions views/advanced-options-page.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php
// phpcs:disable Generic.Files.LineLength.MaxExceeded
// phpcs:disable Generic.Files.LineLength.TooLong
/**
* @var mixed[] $view
*/

?>

<div class="wrap">
<form
name="wp2static-ui-advanced-options"
method="POST"
action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">

<h1>Advanced Options<h1>

<h2>Post-processing Options</h2>

<table class="widefat striped">
<tbody>
<tr>
<td style="width:50%;">
<label
for="<?php echo $view['coreOptions']['hostsToRewrite']->name; ?>"
><b><?php echo $view['coreOptions']['hostsToRewrite']->label; ?></b></label>
<br/><?php echo $view['coreOptions']['hostsToRewrite']->description; ?>
</td>
<td>
<textarea
class="widefat"
cols=30 rows=10
id="<?php echo $view['coreOptions']['hostsToRewrite']->name; ?>"
name="<?php echo $view['coreOptions']['hostsToRewrite']->name; ?>"
type="text"
><?php echo $view['coreOptions']['hostsToRewrite']->blob_value; ?></textarea>
</td>
</tr>
</tbody>
</table>

<p>

<?php wp_nonce_field( $view['nonce_action'] ); ?>
<input name="action" type="hidden" value="wp2static_ui_save_advanced_options" />

<button class="button btn-primary" type="submit">Save options</button>

</form>
</div>

0 comments on commit 62ed042

Please sign in to comment.