PluginProbe ʕ •ᴥ•ʔ
NitroPack – Performance, Page Speed & Cache Plugin for Core Web Vitals, CDN & Image Optimization / 1.11.0
NitroPack – Performance, Page Speed & Cache Plugin for Core Web Vitals, CDN & Image Optimization v1.11.0
1.19.8 1.19.7 1.19.6 1.19.5 trunk 1.10.0 1.10.1 1.10.2 1.10.3 1.10.4 1.11.0 1.12.0 1.13.0 1.14.0 1.15.0 1.15.1 1.15.2 1.15.3 1.16.0 1.16.1 1.16.2 1.16.3 1.16.4 1.16.5 1.16.6 1.16.7 1.16.8 1.17.0 1.17.6 1.17.7 1.17.8 1.17.9 1.18.0 1.18.1 1.18.2 1.18.3 1.18.4 1.18.5 1.18.6 1.18.7 1.18.8 1.18.9 1.19.0 1.19.1 1.19.2 1.19.3 1.19.4 1.3.19 1.3.20 1.4.0 1.4.1 1.5.0 1.5.1 1.5.10 1.5.11 1.5.12 1.5.13 1.5.14 1.5.15 1.5.16 1.5.17 1.5.18 1.5.19 1.5.2 1.5.3 1.5.4 1.5.5 1.5.6 1.5.7 1.5.8 1.5.9 1.6.0 1.6.1 1.7.0 1.7.1 1.8.0 1.8.1 1.8.3 1.9.0 1.9.1 1.9.2
nitropack / classes / WordPress / NitroPack.php
nitropack / classes / WordPress Last commit date
Config.php 3 years ago NitroPack.php 2 years ago Notifications.php 3 years ago
NitroPack.php
423 lines
1 <?php
2 namespace NitroPack\WordPress;
3
4 use \NitroPack\SDK\Filesystem;
5
6 class NitroPack {
7 private static $instance = NULL;
8 public static $nitroDirMigrated = false;
9 public static $preUpdatePosts = array();
10 public static $preUpdateTaxonomies = array();
11 public static $preUpdateMeta = array();
12 public static $ignoreUpdatePostIDs = array();
13 public static $np_loggedWarmups = array();
14 public static $optionsToCache = [
15 'cache_handler_cache_handler',
16 'woocommerce_default_customer_address',
17 [ "wc_aelia_currency_switcher" => "ipgeolocation_enabled"]
18 ];
19
20 public static function getInstance() {
21 if (!self::$instance) {
22 self::$instance = new NitroPack();
23 }
24
25 return self::$instance;
26 }
27
28 public static function getDataDir() {
29 $isRaidBoxes = \NitroPack\Integration\Hosting\Raidboxes::detect();
30 $isPantheon = \NitroPack\Integration\Hosting\Pantheon::detect();
31 $isWpe = \NitroPack\Integration\Hosting\WPEngine::detect();
32 $currentFilePath = __FILE__;
33
34 if ($isWpe) {
35 $currentFilePath = preg_replace("@^/sites/@", "/nas/content/live/", $currentFilePath);
36 }
37
38 $oldNitroDirs = [
39 nitropack_trailingslashit(WP_CONTENT_DIR) . 'nitropack',
40 nitropack_trailingslashit(WP_CONTENT_DIR) . 'cache/' . substr(md5($currentFilePath), 0, 7) . "-nitropack",
41 ];
42 $newNitroDir = nitropack_trailingslashit(WP_CONTENT_DIR) . 'cache/' . NITROPACK_CACHE_DIR_NAME;
43 $nitroDir = $newNitroDir;
44
45 if ($isRaidBoxes) {
46 $nitroDir = $oldNitroDirs[0];
47 } else if ($isPantheon) {
48 $nitroDir = nitropack_trailingslashit(WP_CONTENT_DIR) . 'uploads/' . NITROPACK_CACHE_DIR_NAME;
49 }
50
51 $possibleDirs = array_unique(array_merge($oldNitroDirs, [$newNitroDir]));
52 $existingDirs = [];
53
54 foreach ($possibleDirs as $possibleDir) {
55 if (Filesystem::fileExists($possibleDir)) {
56 $existingDirs[] = $possibleDir;
57 }
58 }
59
60 if (count($existingDirs) == 1) {
61 $existingDir = array_shift($existingDirs);
62 if (is_link($existingDir)) {
63 $existingDir = readlink($existingDir);
64 }
65
66 if ($existingDir != $nitroDir) {
67 if (!Filesystem::fileExists($nitroDir) && !NITROPACK_USE_REDIS) {
68 // Existing installation, move to the new location
69
70 if (Filesystem::createDir(dirname($nitroDir)) && Filesystem::rename($existingDir, $nitroDir)) {
71 self::$nitroDirMigrated = true;
72 } else {
73 define('NITROPACK_DATA_DIR_WARNING', 'Unable to initialize cache dir because the PHP user does not have permission to create/rename directories under wp-content/. Running in legacy mode. Please contact support for help.');
74 $nitroDir = $existingDir;
75 }
76 }
77 }
78 }
79
80 return $nitroDir;
81 }
82
83 private $sdkObjects;
84 private $disabledReason;
85 private $pageType;
86
87 public $Config;
88 public $Notifications;
89
90 public function __construct() {
91 $this->Config = new Config($this);
92 $this->Notifications = new Notifications($this);
93 $this->sdkObjects = array();
94 $this->disabledReason = NULL;
95 $this->pageType = NULL;
96 }
97
98 public function getDistribution() {
99 $dist = "regular";
100 $dbDist = NULL;
101
102 try {
103 if (function_exists("get_option")) {
104 $dbDist = get_option("nitropack-distribution", NULL);
105 }
106
107 if ($this->isConnected()) {
108 $sdk = $this->getSdk();
109 if (!$sdk) return $dbDist ? $dbDist : $dist;
110
111 $config = $sdk->getConfig();
112 if ($config) {
113 $dist = $config->Distribution;
114 }
115 } else if ($dbDist !== NULL) {
116 $dist = $dbDist;
117 }
118
119 if ($dbDist != $dist && function_exists("update_option")) {
120 update_option("nitropack-distribution", $dist);
121 }
122
123 return $dist;
124 } catch (Exception $e) {
125 return $dist;
126 }
127 }
128
129 public function getSiteConfig() {
130 $siteConfig = null;
131 $npConfig = $this->Config->get();
132 $currentUrl = $this -> getCurrentUrl();
133
134 $matchLength = 0;
135
136 foreach ($npConfig as $siteUrl => $config) {
137 if (stripos($siteUrl, "www.") === 0) {
138 $siteUrl = substr($siteUrl, 4);
139 }
140
141 if (stripos($currentUrl, $siteUrl) === 0 && strlen($siteUrl) > $matchLength) {
142 $siteConfig = $config;
143 $matchLength = strlen($siteUrl);
144 }
145 }
146
147 if (!$siteConfig) {
148 $matchLength = 0;
149 foreach ($npConfig as $siteUrl => $config) {
150 if (isset($config['additional_domains'])) {
151 foreach ($config['additional_domains'] as $additionalDomain) {
152 if (stripos($additionalDomain, "www.") === 0) {
153 $additionalDomain = substr($additionalDomain, 4);
154 }
155
156 if (stripos($currentUrl, $additionalDomain) === 0 && strlen($additionalDomain) > $matchLength) {
157 $siteConfig = $config;
158 $matchLength = strlen($additionalDomain);
159 }
160 }
161 }
162 }
163 }
164
165 return $siteConfig;
166 }
167
168 public function getSiteId() {
169 $siteConfig = $this->getSiteConfig();
170 return $siteConfig ? $siteConfig["siteId"] : NULL;
171 }
172
173 public function getSiteSecret() {
174 $siteConfig = $this->getSiteConfig();
175 return $siteConfig ? $siteConfig["siteSecret"] : NULL;
176 }
177
178 /**
179 * Bear in mind that get_home_url() is not defined in the context of advanced_cache.php
180 * so this will throw a fatal error if you call it at that point!
181 */
182 public static function getConfigKey() {
183 return preg_replace("/^https?:\/\/(.*)/", "$1", get_home_url());
184 }
185
186 public function getAdditionalDomains($siteId, $siteSecret) {
187 if (null !== $nitro = $this->getSdk($siteId, $siteSecret)) {
188 $config = $nitro->getConfig();
189 if (!property_exists($config->AdditionalDomains, 'Domains')) {
190 $nitro->fetchConfig();
191 }
192 return $config->AdditionalDomains->Domains;
193 }
194
195 return [];
196 }
197
198 public function isConnected() {
199 return !empty($this->getSiteId()) && !empty($this->getSiteSecret());
200 }
201
202 public function updateCurrentBlogConfig($siteId, $siteSecret, $blogId, $enableCompression = null) {
203 if ($enableCompression === null) {
204 $enableCompression = (get_option('nitropack-enableCompression') == 1);
205 }
206
207 $webhookToken = get_option('nitropack-webhookToken');
208 $hosting = nitropack_detect_hosting();
209
210 $home_url = get_home_url();
211 $admin_url = admin_url();
212 $alwaysBuffer = defined("NITROPACK_ALWAYS_BUFFER") ? NITROPACK_ALWAYS_BUFFER : true;
213 $configKey = self::getConfigKey();
214 $staticConfig = $this->Config->get();
215 $staticConfig[$configKey] = array(
216 "siteId" => $siteId,
217 "siteSecret" => $siteSecret,
218 "blogId" => $blogId,
219 "compression" => $enableCompression,
220 "webhookToken" => $webhookToken,
221 "home_url" => $home_url,
222 "admin_url" => $admin_url,
223 "hosting" => $hosting,
224 "alwaysBuffer" => $alwaysBuffer,
225 "isEzoicActive" => \NitroPack\Integration\Plugin\Ezoic::isActive(),
226 "isApoActive" => \NitroPack\Integration\Plugin\Cloudflare::isApoActive(),
227 "isNginxHelperActive" => \NitroPack\Integration\Plugin\NginxHelper::isActive(),
228 "isLateIntegrationInitRequired" => nitropack_is_late_integration_init_required(),
229 "isDlmActive" => \NitroPack\Integration\Plugin\DownloadManager::isActive(),
230 "isWoocommerceCacheHandlerActive" => \NitroPack\Integration\Plugin\WoocommerceCacheHandler::isActive(),
231 "isWoocommerceActive" => \NitroPack\Integration\Plugin\Woocommerce::isActive(),
232 "isAeliaCurrencySwitcherActive" => \NitroPack\Integration\Plugin\AeliaCurrencySwitcher::isActive(),
233 "isGeoTargetingWPActive" => \NitroPack\Integration\Plugin\GeoTargetingWP::isActive(),
234 "dlm_downloading_url" => \NitroPack\Integration\Plugin\DownloadManager::isActive() ? \NitroPack\Integration\Plugin\DownloadManager::downloadingUrl() : NULL,
235 "dlm_download_endpoint" => \NitroPack\Integration\Plugin\DownloadManager::isActive() ? \NitroPack\Integration\Plugin\DownloadManager::downloadEndpoint() : NULL,
236 "pluginVersion" => NITROPACK_VERSION,
237 "options_cache" => [],
238 "additional_domains" => $this->getAdditionalDomains($siteId, $siteSecret),
239 );
240 foreach (self::$optionsToCache as $opt) {
241 if (is_array($opt)) {
242 foreach($opt as $option => $suboption) {
243 if (empty($staticConfig[$configKey]["options_cache"][$option])) {
244 $staticConfig[$configKey]["options_cache"][$option] = [];
245 }
246 $optionValue = get_option($option);
247 if (!empty($optionValue)) {
248 $staticConfig[$configKey]["options_cache"][$option][$suboption] = $optionValue[$suboption];
249 } else {
250 $staticConfig[$configKey]["options_cache"][$option][$suboption] = null;
251 }
252 }
253 } else {
254 $staticConfig[$configKey]["options_cache"][$opt] = get_option($opt);
255 }
256 }
257 $configSetResult = $this->Config->set($staticConfig);
258
259 if (\NitroPack\Integration\Plugin\AeliaCurrencySwitcher::isActive()) {
260 try {
261 \NitroPack\Integration\Plugin\AeliaCurrencySwitcher::configureVariationCookies();
262 } catch (\Exception $e) {
263 // TODO: Log this error
264 }
265 }
266 if (\NitroPack\Integration\Plugin\GeoTargetingWP::isActive()) {
267 try {
268 \NitroPack\Integration\Plugin\GeoTargetingWP::configureVariationCookies();
269 } catch (\Exception $e) {
270 // TODO: Log this error
271 }
272 }
273
274 return $configSetResult;
275 }
276
277 public function unsetCurrentBlogConfig() {
278 $configKey = self::getConfigKey();
279 $staticConfig = $this->Config->get();
280 if (!empty($staticConfig[$configKey])) {
281 unset($staticConfig[$configKey]);
282 return $this->Config->set($staticConfig);
283 }
284
285 return true;
286 }
287
288 public function resetSdkInstances() {
289 $this->sdkObjects = [];
290 }
291
292 public function getSdk($siteId = null, $siteSecret = null, $urlOverride = NULL, $forwardExceptions = false) {
293 $siteConfig = $this->getSiteConfig();
294
295 $siteId = $siteId ?: (!empty($siteConfig) ? $siteConfig['siteId'] : NULL);
296 $siteSecret = $siteSecret ?: (!empty($siteConfig) ? $siteConfig['siteSecret'] : NULL);
297
298 if ($siteId && $siteSecret) {
299 try {
300 $userAgent = NULL; // It will be automatically detected by the SDK
301 $dataDir = nitropack_trailingslashit(NITROPACK_DATA_DIR) . $siteId; // dir without a trailing slash, because this is how the SDK expects it
302 $cacheKey = "{$siteId}:{$siteSecret}:{$dataDir}";
303
304 if ($urlOverride) {
305 $cacheKey .= ":{$urlOverride}";
306 }
307
308 if (!empty($this->sdkObjects[$cacheKey])) {
309 $nitro = $this->sdkObjects[$cacheKey];
310 } else {
311 if (!defined("NP_COOKIE_FILTER")) {
312 \NitroPack\SDK\NitroPack::addCookieFilter("nitropack_filter_non_original_cookies");
313 define("NP_COOKIE_FILTER", true);
314 do_action('np_set_cookie_filter');
315 }
316 if (!defined("NP_STORAGE_CONFIGURED")) {
317 if (defined("NITROPACK_USE_REDIS") && NITROPACK_USE_REDIS) {
318 \NitroPack\SDK\Filesystem::setStorageDriver(new \NitroPack\SDK\StorageDriver\Redis(
319 NITROPACK_REDIS_HOST,
320 NITROPACK_REDIS_PORT,
321 NITROPACK_REDIS_PASS,
322 NITROPACK_REDIS_DB
323 ));
324 }
325 define("NP_STORAGE_CONFIGURED", true);
326 }
327
328 if (!defined('NP_GEOLOCATION_PREFIX_DEFINED')) {
329 do_action('set_nitropack_geo_cache_prefix');
330 define('NP_GEOLOCATION_PREFIX_DEFINED', true);
331 }
332
333 if (defined("NITROPACK_CUSTOM_CACHE_PREFIX") && !defined('NP_CUSTOM_CACHE_PREFIX_SET')) {
334 \NitroPack\SDK\NitroPack::addCustomCachePrefix(NITROPACK_CUSTOM_CACHE_PREFIX);
335 define('NP_CUSTOM_CACHE_PREFIX_SET', true);
336 }
337
338 $nitro = new \NitroPack\SDK\NitroPack($siteId, $siteSecret, $userAgent, $urlOverride, $dataDir);
339 $this->sdkObjects[$cacheKey] = $nitro;
340 }
341 } catch (\Exception $e) {
342 if ($forwardExceptions) {
343 throw $e;
344 }
345 return NULL;
346 }
347
348 return $nitro;
349 }
350
351 return NULL;
352 }
353
354 public function dataDirExists() {
355 return defined("NITROPACK_DATA_DIR") && is_dir(NITROPACK_DATA_DIR); // TODO: Convert this to use the Filesystem abstraction for better Redis support
356 }
357
358 public function initDataDir() {
359 return $this->dataDirExists() || @mkdir(NITROPACK_DATA_DIR, 0755, true); // TODO: Convert this to use the Filesystem abstraction for better Redis support
360 }
361
362 public function setDisabledReason($reason) {
363 $this->disabledReason = $reason;
364 nitropack_header("X-Nitro-Disabled-Reason: $reason");
365 }
366
367 public function getDisabledReason() {
368 return $this->disabledReason;
369 }
370
371 public function setPageType($type) {
372 $this->pageType = $type;
373 }
374
375 public function getPageType() {
376 return $this->pageType;
377 }
378
379 /**
380 * Get current url
381 *
382 * @return string The current url
383 */
384 public function getCurrentUrl() {
385
386 if ( defined('NITROPACK_HOST') ) {
387
388 return NITROPACK_HOST;
389 }
390
391 if (! empty( $_SERVER['HTTP_X_FORWARDED_HOST'] )) {
392 $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
393 } else {
394 $host = !empty($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : "";
395 }
396
397 $uri = !empty($_SERVER["REQUEST_URI"]) ? $_SERVER["REQUEST_URI"] : "";
398 $currentUrl = $host . $uri;
399
400 if (empty($currentUrl) || (defined( 'WP_CLI' ) && WP_CLI && trim($currentUrl) == "localhost")) {
401
402 if (function_exists('get_site_url')) {
403 $host = apply_filters('nitropack_current_host', get_site_url());
404 } elseif (function_exists('get_option')) {
405 $host = apply_filters('nitropack_current_host', get_option('siteurl'));
406 }
407
408 if ($host != '') {
409 $site_url = parse_url($host);
410 if (is_array($site_url) && isset($site_url["host"]) && !empty($site_url["host"])) {
411 $currentUrl = $site_url["host"];
412 }
413 }
414 }
415
416 if (stripos($currentUrl, "www.") === 0) {
417 $currentUrl = substr($currentUrl, 4);
418 }
419
420 return $currentUrl;
421 }
422 }
423