-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathAutoCache.php
More file actions
377 lines (332 loc) · 14.1 KB
/
AutoCache.php
File metadata and controls
377 lines (332 loc) · 14.1 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
<?php
/*[pro exclude-file-from="lite"]*/
/*[pro strip-from="lite"]*/
namespace WebSharks\CometCache\Pro\Classes;
/**
* Auto-Cache Engine.
*
* @since 150422 Rewrite.
*/
class AutoCache extends AbsBase
{
/**
* Working a child blog?
*
* @since 150422 Rewrite.
*
* @type bool|null
*/
protected $is_child_blog;
/**
* Class constructor.
*
* @since 150422 Rewrite.
*/
public function __construct()
{
parent::__construct();
$this->run();
}
/**
* Public runner; attach to WP-Cron.
*
* @since 150422 Rewrite.
*/
protected function run()
{
if (!$this->plugin->options['enable']) {
return; // Nothing to do.
}
if (!$this->plugin->options['auto_cache_enable']) {
return; // Nothing to do.
}
if (!$this->plugin->options['auto_cache_sitemap_url']) {
if (!$this->plugin->options['auto_cache_other_urls']) {
return; // Nothing to do.
}
}
$cache_dir = $this->plugin->cacheDir();
if (!is_dir($cache_dir) || !is_writable($cache_dir)) {
return; // Not possible in this case.
}
$max_time = (integer) $this->plugin->options['auto_cache_max_time'];
$max_time = $max_time > 60 ? $max_time : 900;
@set_time_limit($max_time); // @TODO Display a warning.
ignore_user_abort(true); // Keep running.
$micro_start_time = microtime(true);
$start_time = time(); // Initialize.
$total_urls = $total_time = 0; // Initialize.
$delay = (integer) $this->plugin->options['auto_cache_delay']; // In milliseconds.
$delay = $delay > 0 ? $delay * 1000 : 0; // Convert delay to microseconds for `usleep()`.
$other_urls = $this->plugin->options['auto_cache_other_urls'];
$other_urls = preg_split('/\s+/', $other_urls, -1, PREG_SPLIT_NO_EMPTY);
$blogs = [(object) ['ID' => null, 'other' => $other_urls]];
$is_multisite = is_multisite(); // Multisite network?
$can_consider_domain_mapping = $is_multisite && $this->plugin->canConsiderDomainMapping();
if ($is_multisite && $this->plugin->options['auto_cache_ms_children_too']) {
$wpdb = $this->plugin->wpdb(); // WordPress DB object instance.
if (($_child_blogs = $wpdb->get_results('SELECT `blog_id` AS `ID` FROM `'.esc_sql($wpdb->blogs).'` WHERE `deleted` <= \'0\''))) {
$blogs = array_merge($blogs, $_child_blogs);
}
unset($_child_blogs); // Housekeeping.
}
shuffle($blogs); // Randomize; i.e. don't always start from the top.
foreach ($blogs as $_blog) {
$_blog_sitemap_urls = $_blog_other_urls = $_blog_urls = [];
if (!isset($_blog->ID)) { // `home_url()` fallback.
$_blog_url = rtrim($this->plugin->getHomeUrlWithHomeScheme(), '/');
$this->is_child_blog = false; // Simple flag.
} else { // This calls upon `switch_to_blog()` to acquire.
$_blog_url = rtrim($this->plugin->getHomeUrlWithHomeScheme($_blog->ID), '/');
$this->is_child_blog = true; // Simple flag; yes it is!
}
if ($is_multisite && $can_consider_domain_mapping) {
$_blog_url = $this->plugin->domainMappingUrlFilter($_blog_url);
}
if ($_blog_url && ($_blog_sitemap_path = ltrim($this->plugin->options['auto_cache_sitemap_url'], '/'))) {
$_blog_sitemap_urls = $this->getSitemapUrlsDeep($_blog_url.'/'.$_blog_sitemap_path);
}
if (!empty($_blog->other)) {
$_blog_other_urls = array_merge($_blog_urls, $_blog->other);
}
$_blog_urls = array_merge($_blog_sitemap_urls, $_blog_other_urls);
$_blog_urls = array_unique($_blog_urls); // Unique URLs only.
shuffle($_blog_urls); // Randomize the order.
foreach ($_blog_urls as $_url) {
++$total_urls; // Counter.
$this->autoCacheUrl($_url);
if ((time() - $start_time) > ($max_time - 30)) {
break 2; // Stop now.
}
if ($delay) {
usleep($delay);
}
}
unset($_url); // A little housekeeping.
}
unset($_blog, $_blog_url, $_blog_sitemap_path, $_blog_sitemap_urls, $_blog_other_urls, $_blog_urls);
$total_time = number_format(microtime(true) - $micro_start_time, 5, '.', '').' seconds';
$this->logAutoCacheRun($total_urls, $total_time);
}
/**
* Auto-cache a specific URL.
*
* @since 150422 Rewrite.
*
* @param string $url The URL to auto-cache.
*/
protected function autoCacheUrl($url)
{
if (!($url = trim((string) $url))) {
return; // Nothing to do.
}
if (!$this->plugin->options['get_requests'] && mb_strpos($url, '?') !== false) {
return; // We're NOT caching URLs with a query string.
}
$cache_path = $this->plugin->buildCachePath($url);
$cache_file_path = $this->plugin->cacheDir($cache_path);
if (is_file($cache_file_path)) {
if (filemtime($cache_file_path) >= strtotime('-'.$this->plugin->options['cache_max_age'])) {
return; // Cached already.
}
}
$this->logAutoCacheUrl(
$url,
wp_remote_get(
$url,
[
'blocking' => false,
'user-agent' => $this->plugin->options['auto_cache_user_agent'].
'; '.GLOBAL_NS.' '.VERSION,
]
)
);
}
/**
* Logs an attempt to auto-cache a specific URL.
*
* @since 150422 Rewrite.
*
* @param string $url The URL we attempted to auto-cache.
* @param \WP_Error $wp_remote_get_response For IDEs.
*
* @throws \Exception If log file exists already; but is NOT writable.
*/
protected function logAutoCacheUrl($url, $wp_remote_get_response)
{
$cache_dir = $this->plugin->cacheDir();
$cache_lock = $this->plugin->cacheLock();
$auto_cache_log_file = $cache_dir.'/'.mb_strtolower(SHORT_NAME).'-auto-cache.log';
if (is_file($auto_cache_log_file) && !is_writable($auto_cache_log_file)) {
throw new \Exception(sprintf(__('Auto-cache log file is NOT writable: `%1$s`. Please set permissions to `644` (or higher). `666` might be needed in some cases.', SLUG_TD), $auto_cache_log_file));
}
if (is_wp_error($wp_remote_get_response)) {
$log_entry =
'Time: '.date(DATE_RFC822)."\n".
'URL: '.$url."\n".
'Error: '.$wp_remote_get_response->get_error_message()."\n\n";
} else {
$log_entry =
'Time: '.date(DATE_RFC822)."\n".
'URL: '.$url."\n\n";
}
file_put_contents($auto_cache_log_file, $log_entry, FILE_APPEND);
if (filesize($auto_cache_log_file) > 2097152) {
rename($auto_cache_log_file, mb_substr($auto_cache_log_file, 0, -4).'-archived-'.time().'.log');
}
$this->plugin->cacheUnlock($cache_lock); // Release.
}
/**
* Logs auto-cache run totals.
*
* @since 150422 Rewrite.
*
* @param int $total_urls Total URLs processed by the run.
* @param string $total_time Total time it took to complete processing.
*
* @throws \Exception If log file exists already; but is NOT writable.
*/
protected function logAutoCacheRun($total_urls, $total_time)
{
$cache_dir = $this->plugin->cacheDir();
$cache_lock = $this->plugin->cacheLock();
$auto_cache_log_file = $cache_dir.'/'.mb_strtolower(SHORT_NAME).'-auto-cache.log';
if (is_file($auto_cache_log_file) && !is_writable($auto_cache_log_file)) {
throw new \Exception(sprintf(__('Auto-cache log file is NOT writable: `%1$s`. Please set permissions to `644` (or higher). `666` might be needed in some cases.', SLUG_TD), $auto_cache_log_file));
}
$log_entry =
'Run Completed: '.date(DATE_RFC822)."\n".
'Total URLs: '.$total_urls."\n".
'Total Time: '.$total_time."\n\n";
file_put_contents($auto_cache_log_file, $log_entry, FILE_APPEND);
if (filesize($auto_cache_log_file) > 2097152) {
rename($auto_cache_log_file, mb_substr($auto_cache_log_file, 0, -4).'-archived-'.time().'.log');
}
$this->plugin->cacheUnlock($cache_lock); // Release.
}
/**
* Collects all URLs from an XML sitemap deeply.
*
* @since 150422 Rewrite.
*
* @param string $sitemap A URL to an XML sitemap file.
* This supports nested XML sitemap index files too; i.e. `<sitemapindex>`.
* Note that GZIP files are NOT supported at this time.
* @param bool $___recursive For internal use only.
*
* @throws \Exception If `$sitemap` is NOT actually a sitemap.
*
* @return array URLs from an XML sitemap deeply.
*
* @note The XMLReader class reads the input XML from a stream, but if the PHP config has `allow_fopen_url=0`
* we need to download the XML Sitemap and read it from a local file. We use the WP HTTP API as a fallback.
*/
protected function getSitemapUrlsDeep($sitemap, $___recursive = false)
{
$urls = [];
$xml_reader = new \XMLReader();
$allow_url_fopen = filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN);
if (!($sitemap = trim((string) $sitemap))) {
goto finale; // Nothing we can do.
}
if (!$this->plugin->autoCacheCheckXmlSitemap($sitemap, $___recursive, $this->is_child_blog)) {
goto finale; // Nothing we can do.
}
if (!$allow_url_fopen || apply_filters(GLOBAL_NS.'_auto_cache_sitemap_force_wp_http_api', false)) { // Try the WP HTTP API instead.
$sitemap = $this->plugin->autoCacheWpRemoteGetXmlSitemap($sitemap);
}
if ($xml_reader->open($sitemap)) {
while ($xml_reader->read()) {
if ($xml_reader->nodeType === $xml_reader::ELEMENT) {
switch ($xml_reader->name) {
case 'sitemapindex':
// e.g. <http://www.smashingmagazine.com/sitemap_index.xml>
if (($_sitemapindex_urls = $this->xmlGetSitemapIndexUrlsDeep($xml_reader))) {
$urls = array_merge($urls, $_sitemapindex_urls);
}
break; // Break switch handler.
case 'urlset':
// e.g. <http://www.smashingmagazine.com/category-sitemap.xml>
if (($_urlset_urls = $this->xmlGetUrlsetUrls($xml_reader))) {
$urls = array_merge($urls, $_urlset_urls);
}
break; // Break switch handler.
}
}
}
unset($_sitemapindex_urls, $_urlset_urls);
}
if (!$allow_url_fopen || apply_filters(GLOBAL_NS.'_auto_cache_sitemap_force_wp_http_api', false)) {
unlink($sitemap); // Delete temp file downloaded by cURL
}
finale: // Target point; grand finale.
return $urls; // A full set of all sitemap URLs; i.e. `<loc>` tags.
}
/**
* For internal use only.
*
* @since 150422 Rewrite.
*
* @param \XMLReader $xml_reader
*
* @return array All sitemap URLs from this `<sitemapindex>` node; deeply.
*/
protected function xmlGetSitemapIndexUrlsDeep(\XMLReader $xml_reader)
{
$urls = []; // Initialize.
if ($xml_reader->name === 'sitemapindex') {
while ($xml_reader->read()) {
if ($xml_reader->nodeType === $xml_reader::ELEMENT) {
switch ($xml_reader->name) {
case 'sitemap':
$is_sitemap_node = true;
break; // Break switch handler.
case 'loc':
if (!empty($is_sitemap_node) && $xml_reader->read() && ($_loc = trim($xml_reader->value))) {
$urls = array_merge($urls, $this->getSitemapUrlsDeep($_loc, true));
}
break;
default:
$is_sitemap_node = false;
break;
}
}
}
return $urls; // All sitemap URLs from this `<sitemapindex>` node; deeply.
}
}
/**
* For internal use only.
*
* @since 150422 Rewrite.
*
* @param \XMLReader $xml_reader
*
* @return array All sitemap URLs from this `<urlset>` node.
*/
protected function xmlGetUrlsetUrls(\XMLReader $xml_reader)
{
$urls = []; // Initialize.
if ($xml_reader->name === 'urlset') {
while ($xml_reader->read()) {
if ($xml_reader->nodeType === $xml_reader::ELEMENT) {
switch ($xml_reader->name) {
case 'url':
$is_url_node = true;
break;
case 'loc':
if (!empty($is_url_node) && $xml_reader->read() && ($_loc = trim($xml_reader->value))) {
$urls[] = $_loc; // Add this URL to the list :-)
}
break;
default:
$is_url_node = false;
break;
}
}
}
return $urls; // All sitemap URLs from this `<urlset>` node.
}
}
}
/*[/pro]*/