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