Completed
Push — master ( f1978f...ebc34c )
by Daniel
16s queued 12s
created

FilesystemPublisher::publishPage()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 7
eloc 12
c 3
b 0
f 0
nc 10
nop 2
dl 0
loc 19
rs 8.8333
1
<?php
2
3
namespace SilverStripe\StaticPublishQueue\Publisher;
4
5
use SilverStripe\Assets\Filesystem;
6
use SilverStripe\Control\HTTPResponse;
7
use SilverStripe\Core\Config\Config;
8
use SilverStripe\Security\SecurityToken;
9
use SilverStripe\StaticPublishQueue\Publisher;
10
use function SilverStripe\StaticPublishQueue\PathToURL;
11
use function SilverStripe\StaticPublishQueue\URLtoPath;
12
13
class FilesystemPublisher extends Publisher
14
{
15
    /**
16
     * @var string
17
     */
18
    protected $destFolder = 'cache';
19
20
    /**
21
     * @var string
22
     */
23
    protected $fileExtension = 'php';
24
25
    /**
26
     * @return string
27
     */
28
    public function getDestPath()
29
    {
30
        $base = defined('PUBLIC_PATH') ? PUBLIC_PATH : BASE_PATH;
31
        return $base . DIRECTORY_SEPARATOR . $this->getDestFolder();
32
    }
33
34
    public function setDestFolder($destFolder)
35
    {
36
        $this->destFolder = $destFolder;
37
        return $this;
38
    }
39
40
    public function getDestFolder()
41
    {
42
        return $this->destFolder;
43
    }
44
45
    public function setFileExtension($fileExtension)
46
    {
47
        $fileExtension = strtolower($fileExtension);
48
        if (!in_array($fileExtension, ['html', 'php'], true)) {
49
            throw new \InvalidArgumentException(
50
                sprintf(
51
                    'Bad file extension "%s" passed to %s::%s',
52
                    $fileExtension,
53
                    static::class,
54
                    __FUNCTION__
55
                )
56
            );
57
        }
58
        $this->fileExtension = $fileExtension;
59
        return $this;
60
    }
61
62
    public function getFileExtension()
63
    {
64
        return $this->fileExtension;
65
    }
66
67
    public function purgeURL($url)
68
    {
69
        if (!$url) {
70
            user_error('Bad url:' . var_export($url, true), E_USER_WARNING);
71
            return;
72
        }
73
        if ($path = $this->URLtoPath($url)) {
74
            $success = $this->deleteFromPath($path . '.html') && $this->deleteFromPath($path . '.php');
75
            return [
76
                'success' => $success,
77
                'url' => $url,
78
                'path' => $this->getDestPath() . DIRECTORY_SEPARATOR . $path,
79
            ];
80
        }
81
        return [
82
            'success' => false,
83
            'url' => $url,
84
            'path' => false,
85
        ];
86
    }
87
88
    public function purgeAll()
89
    {
90
        Filesystem::removeFolder($this->getDestPath());
91
92
        return file_exists($this->getDestPath()) ? false : true;
93
    }
94
95
    /**
96
     * @param string $url
97
     * @param bool $forcePublish
98
     * @return array A result array
99
     */
100
    public function publishURL($url, $forcePublish = false)
101
    {
102
        if (!$url) {
103
            user_error('Bad url:' . var_export($url, true), E_USER_WARNING);
104
            return;
105
        }
106
        $success = false;
107
        $response = $this->generatePageResponse($url);
108
        $statusCode = $response->getStatusCode();
109
        $doPublish = ($forcePublish && $this->getFileExtension() === 'php') || $statusCode < 400;
110
111
        if ($statusCode >= 300 && $statusCode < 400) {
112
            // publish redirect response
113
            $success = $this->publishRedirect($response, $url);
114
        } elseif ($doPublish) {
115
            $success = $this->publishPage($response, $url);
116
        }
117
        return [
118
            'published' => $doPublish,
119
            'success' => $success,
120
            'responsecode' => $statusCode,
121
            'url' => $url,
122
        ];
123
    }
124
125
    /**
126
     * @param HTTPResponse $response
127
     * @param string       $url
128
     * @return bool
129
     */
130
    protected function publishRedirect($response, $url)
131
    {
132
        $success = true;
133
        if ($path = $this->URLtoPath($url)) {
134
            $location = $response->getHeader('Location');
135
            if ($this->getFileExtension() === 'php') {
136
                $phpContent = $this->generatePHPCacheFile($response);
137
                $success = $this->saveToPath($phpContent, $path . '.php');
138
            }
139
            return $this->saveToPath($this->generateHTMLCacheRedirection($location), $path . '.html') && $success;
140
        }
141
        return false;
142
    }
143
144
    /**
145
     * @param HTTPResponse $response
146
     * @param string       $url
147
     * @return bool
148
     */
149
    protected function publishPage($response, $url)
150
    {
151
        $success = true;
152
        if ($path = $this->URLtoPath($url)) {
153
            $body = $response->getBody();
154
            if ($this->config()->get('lazy_form_recognition')) {
155
                $id = Config::inst()->get(SecurityToken::class, 'default_name') ?: 'SecurityID';
156
                // little hack to make sure we do not include pages with live forms.
157
                if (stripos($body, '<input type="hidden" name="' . $id . '"') !== false) {
158
                    return false;
159
                }
160
            }
161
            if ($this->getFileExtension() === 'php') {
162
                $phpContent = $this->generatePHPCacheFile($response);
163
                $success = $this->saveToPath($phpContent, $path . '.php');
164
            }
165
            return $this->saveToPath($body, $path . '.html') && $success;
166
        }
167
        return false;
168
    }
169
170
    /**
171
     * returns true on success and false on failure
172
     *
173
     * @param string $content
174
     * @param string $filePath
175
     * @return bool
176
     */
177
    protected function saveToPath($content, $filePath)
178
    {
179
        if (empty($content)) {
180
            return false;
181
        }
182
183
        // Write to a temporary file first
184
        $temporaryPath = tempnam(TEMP_PATH, 'filesystempublisher_');
185
        if (file_put_contents($temporaryPath, $content) === false) {
186
            return false;
187
        }
188
189
        // Move the temporary file to the desired location (prevents unlocked files from being read during write)
190
        $publishPath = $this->getDestPath() . DIRECTORY_SEPARATOR . $filePath;
191
        Filesystem::makeFolder(dirname($publishPath));
192
193
        return rename($temporaryPath, $publishPath);
194
    }
195
196
    protected function deleteFromPath($filePath)
197
    {
198
        $deletePath = $this->getDestPath() . DIRECTORY_SEPARATOR . $filePath;
199
        if (file_exists($deletePath)) {
200
            $success = unlink($deletePath);
201
        } else {
202
            $success = true;
203
        }
204
205
        return $success;
206
    }
207
208
    protected function URLtoPath($url)
209
    {
210
        return URLtoPath($url, BASE_URL, FilesystemPublisher::config()->get('domain_based_caching'));
211
    }
212
213
    protected function pathToURL($path)
214
    {
215
        return PathToURL($path, $this->getDestPath(), FilesystemPublisher::config()->get('domain_based_caching'));
216
    }
217
218
    public function getPublishedURLs($dir = null, &$result = [])
219
    {
220
        if ($dir === null) {
221
            $dir = $this->getDestPath();
222
        }
223
224
        $root = scandir($dir);
225
        foreach ($root as $fileOrDir) {
226
            if (strpos($fileOrDir, '.') === 0) {
227
                continue;
228
            }
229
            $fullPath = $dir . DIRECTORY_SEPARATOR . $fileOrDir;
230
            // we know html will always be generated, this prevents double ups
231
            if (is_file($fullPath) && pathinfo($fullPath, PATHINFO_EXTENSION) === 'html') {
232
                $result[] = $this->pathToURL($fullPath);
233
                continue;
234
            }
235
236
            if (is_dir($fullPath)) {
237
                $this->getPublishedURLs($fullPath, $result);
238
            }
239
        }
240
        return $result;
241
    }
242
}
243