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