Htaccess.php
2.2 KB
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
<?php
namespace AIOSEO\Plugin\Common\Tools;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class Htaccess {
/**
* The path to the .htaccess file.
*
* @since 4.0.0
*
* @var string
*/
private $path = '';
/**
* Class constructor.
*
* @since 4.0.0
*/
public function __construct() {
$this->path = ABSPATH . '.htaccess';
}
/**
* Get the contents of the .htaccess file.
*
* @since 4.0.0
*
* @return string The contents of the file.
*/
public function getContents() {
$fs = aioseo()->core->fs;
if ( ! $fs->exists( $this->path ) ) {
return false;
}
$contents = $fs->getContents( $this->path );
return aioseo()->helpers->encodeOutputHtml( $contents );
}
/**
* Saves the contents of the .htaccess file.
*
* @since 4.0.0
*
* @param string $contents The contents to write.
* @return boolean True if the file was updated.
*/
public function saveContents( $contents ) {
$fs = aioseo()->core->fs;
if ( ! $fs->isWritable( $this->path ) ) {
return [
'success' => false,
'reason' => 'file-not-writable',
'message' => __( 'We were unable to save the .htaccess file because the file was not writable. Please check the file permissions and try again.', 'all-in-one-seo-pack' )
];
}
$fileExists = $fs->exists( $this->path );
$originalContents = $fileExists ? $fs->getContents( $this->path ) : null;
$fileSaved = $fs->putContents( $this->path, $contents );
if ( false === $fileSaved ) {
return [
'success' => false,
'reason' => 'file-not-saved'
];
}
$response = wp_remote_get( home_url( '?' . time() ) );
$isValidRequest = wp_remote_retrieve_response_code( $response );
if (
// Add an exception for Windows devs since the request fails in Local.
! defined( 'AIOSEO_DEV_WINDOWS' ) &&
( is_wp_error( $response ) || 200 !== $isValidRequest )
) {
$fs->putContents( $this->path, $originalContents );
return [
'success' => false,
'reason' => 'syntax-errors',
'message' => __( 'We were unable to save the .htaccess file due to syntax errors. Please check the code below and try again.', 'all-in-one-seo-pack' )
];
}
return [
'success' => true
];
}
}