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