PluginProbe
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript / 4.0.17
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript v4.0.17
4.1.16 4.1.15 4.1.14 4.1.13 4.1.12 4.1.11 4.1.10 4.0.30 4.0.29 4.0.28 4.0.27 4.0.26 4.0.24 4.0.25 4.0.23 4.0.22 4.0.21 4.0.19 4.0.18 4.0.17 4.0.16 1.9.3 1.9.4 1.9.5 1.9.6 All 170 releases
searchpro / inc / class-berqwp.php

class-berqwp.php in BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript 4.0.17, at inc/class-berqwp.php

1,568 lines 50.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 if (!defined('ABSPATH'))
3 exit;
4
5 use BerqWP\BerqWP as BerqWPCloud;
6 use BerqWP\RateLimiter;
7
8 if (!class_exists('berqWP')) {
9 class berqWP
10 {
11
12 public $is_key_verified = false;
13 public $key_response = false;
14 public static $instance = null;
15
16 public $conflicting_plugins = [
17 'autoptimize/autoptimize.php', // Autoptimize
18 'wp-super-cache/wp-cache.php', // WP Super Cache
19 'w3-total-cache/w3-total-cache.php', // W3 Total Cache
20 'wp-fastest-cache/wpFastestCache.php', // WP Fastest Cache
21 'litespeed-cache/litespeed-cache.php', // LiteSpeed Cache
22 'cache-enabler/cache-enabler.php', // Cache Enabler
23 'hummingbird-performance/wp-hummingbird.php', // Hummingbird – Speed up, Cache, Optimize Your CSS and JS
24 'sg-cachepress/sg-cachepress.php', // SiteGround Optimizer (for those hosted on SiteGround)
25 'wp-rocket/wp-rocket.php', // WP Rocket
26 'breeze/breeze.php', // Breeze (Cloudways)
27 'comet-cache/comet-cache.php', // Comet Cache
28 'hyper-cache/plugin.php', // Hyper Cache
29 'simple-cache/simple-cache.php', // Simple Cache
30 'wp-optimize/wp-optimize.php', // WP-Optimize
31 'swift-performance-lite/performance.php', // Swift Performance Lite
32 'nitropack/nitropack.php', // NitroPack
33 'nitropack/main.php', // NitroPack
34 'jetpack-boost/jetpack-boost.php', // Jetpack Boost
35 'tenweb-speed-optimizer/tenweb_speed_optimizer.php', // 10Web Booster
36 'speed-booster-pack/speed-booster-pack.php', // Speed booster pack
37 'wp-speed-of-light/wp-speed-of-light.php', // WP speed of light
38 'speedycache/speedycache.php', // Speedy cache
39 'powered-cache/powered-cache.php', // Powered cache
40 'clearfy/clearfy.php', // Clearfy
41 'rabbit-loader/rabbit-loader.php',
42 'psn-pagespeed-ninja/pagespeedninja.php',
43 'jch-optimize/jch-optimize.php',
44 'cache-enabler/cache-enabler.php',
45 'core-web-vitals-pagespeed-booster/core-web-vitals-pagespeed-booster.php',
46 'surge/surge.php',
47 'speedien/speedien.php',
48 'wpspeed/wpspeed.php',
49 'debloat/debloat.php',
50 'perfmatters/perfmatters.php',
51 'phastpress/phastpress.php',
52 'wp-meteor/wp-meteor.php',
53 ];
54
55 function __construct()
56 {
57
58 add_action('init', [$this, 'initialize']);
59
60 // Save settings
61 add_action('admin_init', [$this, 'save_settings']);
62
63 // Sitemap for cache warmup
64 // add_action('wp', 'bwp_get_sitemap');
65 add_action('wp_loaded', 'bwp_get_sitemap', 999);
66
67 // BerqWP display logs
68 add_action('init', 'bwp_display_logs');
69
70 require_once optifer_PATH . '/api/register_apis.php';
71
72 add_action('admin_menu', [$this, 'register_menu']);
73 // add_action('init', [$this, 'berq_post_types'], 20);
74 add_action('berqwp_notices', [$this, 'notices']);
75
76 add_filter('plugin_action_links_searchpro/berqwp.php', [$this, 'plugin_settings_links']);
77
78 // add_action('wp_ajax_berqwp_fetch_remote_html', [$this, 'fetch_remote_html']);
79
80 add_action('wp_ajax_berqwp_refresh_cache_stats', [$this, 'refresh_cache_stats']);
81
82 add_action('wp_ajax_berqwp_get_optimized_pages', [$this, 'berqwp_get_optimized_pages']);
83
84 add_action('admin_enqueue_scripts', [$this, 'admin_scripts']);
85
86 // add_filter( 'action_scheduler_queue_runner_concurrent_batches', [$this, 'ashp_increase_concurrent_batches'] );
87
88 // add_filter('action_scheduler_retention_period', function ($period) {
89 // return DAY_IN_SECONDS;
90 // });
91
92 // add_filter('action_scheduler_default_cleaner_statuses', function ($statuses) {
93 // $statuses[] = 'failed';
94 // return $statuses;
95 // });
96
97 // add_filter('action_scheduler_cleanup_batch_size', function ($batch_size) {
98 // return 100;
99 // });
100
101 // Refresh license key
102 add_action('admin_post_bwp_refresh_license', [$this, 'handle_refresh_license_action']);
103
104 add_action('admin_post_switch_optimization_method_local', [$this, 'switch_optimization_method']);
105 add_action('admin_post_switch_optimization_method_cloud', [$this, 'switch_optimization_method']);
106
107 add_action('in_admin_header', [$this, 'remove_admin_notices']);
108
109 // Increase nonce life
110 add_filter('nonce_life', [$this, 'increase_nonce_life']);
111
112 // Page compression test
113 add_action('wp_ajax_berqwp_enable_page_compression', [$this, 'enable_page_compression']);
114 add_action('template_redirect', [$this, 'page_compression_test']);
115
116 // Run daily maintenance tasks
117 // add_action('init', [$this, 'schedule_daily_maintenance']);
118 // add_action('berqwp_daily_maintenance_hook', [$this, 'daily_maintenance']);
119
120 // Revoke License
121 add_action('init', [$this, 'revoke_license']);
122
123 // Create dropin plugin file
124 add_action('init', 'berqwp_setup_dropin');
125
126 // Update settings via API
127 add_action('init', 'bwp_update_configs_webhook');
128
129 // Active-status check from optimization server
130 add_action('init', 'bwp_check_status_webhook');
131
132 // Sync addons from cloud
133 add_action('init', [$this, 'sync_addons']);
134
135 // Multisite support
136 if (function_exists('is_multisite') && is_multisite()) {
137 add_action('network_admin_menu', [$this, 'register_network_menu']);
138 add_action('network_admin_edit_berqwp_network_save', [$this, 'save_network_settings']);
139 add_action('wp_initialize_site', [$this, 'on_new_site_created'], 10, 1);
140 add_action('wp_delete_site', [$this, 'regenerate_blog_map']);
141 add_action('berqwp_activate_plugin', [$this, 'regenerate_blog_map']);
142 }
143 }
144
145 static function getInstance() {
146
147 if (self::$instance === null) {
148 $instance = new berqWP();
149 self::$instance = $instance;
150 return $instance;
151 }
152
153 return self::$instance;
154 }
155
156 function switch_optimization_method() {
157 // Check if the user has the necessary nonce and the action matches
158 if (isset($_GET['action']) && $_GET['action'] === 'switch_optimization_method_local' && wp_verify_nonce($_GET['_wpnonce'], 'switch_optimization_method_local_action')) {
159
160
161 $berqconfigs = berqConfigs::getInstance();
162 $berqconfigs->update_configs(['optimization_method' => 'local']);
163
164 $redirect_url = wp_get_referer();
165
166 // Redirect back to the referring page after clearing the cache
167 wp_safe_redirect($redirect_url);
168 exit;
169 }
170
171 if (isset($_GET['action']) && $_GET['action'] === 'switch_optimization_method_cloud' && wp_verify_nonce($_GET['_wpnonce'], 'switch_optimization_method_cloud_action')) {
172
173 $berqconfigs = berqConfigs::getInstance();
174 $configs = $berqconfigs->get_configs();
175
176 if (empty($configs['secret'])) {
177 $berqconfigs->update_configs(['optimization_method' => '']);
178 } else {
179 $berqconfigs->update_configs(['optimization_method' => 'cloud']);
180 }
181
182
183 $redirect_url = wp_get_referer();
184
185 // Redirect back to the referring page after clearing the cache
186 wp_safe_redirect($redirect_url);
187 exit;
188 }
189 }
190
191 function sync_addons()
192 {
193 $license_key = berqwp_get_license_key();
194 if (get_option('berqwp_sync_addons') && !empty($this->key_response->product_ref) && $this->key_response->product_ref == 'AppSumo Deal' && !empty($license_key)) {
195 berqwp_sync_addons($license_key, home_url());
196 delete_option('berqwp_sync_addons');
197 }
198 }
199
200 function revoke_license()
201 {
202 if (isset($_GET['berqwp_revoke_license']) && !empty($_POST['key_hash'])) {
203 $hash = sanitize_text_field($_POST['key_hash']);
204
205 if ($hash == md5(berqwp_get_license_key())) {
206 berqwp_delete_license_key();
207 echo json_encode(['success' => true]);
208 exit;
209 }
210 }
211 }
212
213 function daily_maintenance()
214 {
215
216 // Perform connection test
217 bwp_check_connection(true);
218
219 $log_file = optifer_cache . 'berqwp.log';
220 if (file_exists($log_file)) {
221 @unlink($log_file);
222 }
223
224 $log_dir = optifer_cache . 'logs/';
225
226 // Check if directory exists
227 if (is_dir($log_dir)) {
228 // Get all files in the directory
229 $files = glob($log_dir . '*');
230
231 // Check if there are more than 10 files
232 if (count($files) > 10) {
233 // Sort files by modified time, newest first
234 usort($files, function ($a, $b) {
235 return filemtime($b) - filemtime($a);
236 });
237
238 // Get files beyond the first 10
239 $files_to_delete = array_slice($files, 10);
240
241 // Delete the extra files
242 foreach ($files_to_delete as $file) {
243 if (is_file($file)) {
244 @unlink($file);
245 }
246 }
247 }
248 }
249 }
250
251 function schedule_daily_maintenance()
252 {
253 if (!as_next_scheduled_action('berqwp_daily_maintenance_hook')) {
254 as_schedule_recurring_action(time(), DAY_IN_SECONDS, 'berqwp_daily_maintenance_hook');
255 }
256 }
257
258 function page_compression_test()
259 {
260 if (isset($_GET['berqwp_compression_test'])) {
261 $test_file_path = optifer_cache . 'gzip-compression-test.gz';
262 $accept_encoding = $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '';
263 $supports_gzip = strpos($accept_encoding, 'gzip') !== false;
264
265 // if ($supports_gzip) {
266 header('Content-Type: text/html; charset=utf-8');
267 // header_remove('Content-Encoding');
268 // header('Content-Encoding: gzip');
269 // readgzfile($test_file_path);
270
271 header('Vary: Accept-Encoding');
272 header('Content-Encoding: gzip', true);
273 header('Content-Length: ' . filesize($test_file_path), true);
274 readfile($test_file_path);
275 // }
276 // header('Content-Type: text/html');
277 // header('Content-Encoding: gzip');
278 // readfile($test_file_path);
279 exit;
280 }
281 }
282
283 function enable_page_compression()
284 {
285
286 check_ajax_referer('wp_rest', 'nonce');
287
288 $url = home_url('/?berqwp_compression_test=' . time());
289 $berqconfigs = berqConfigs::getInstance();
290 $testfile = optifer_cache . 'gzip-compression-test.gz';
291 $html = gzencode('Hello World!');
292 @file_put_contents($testfile, $html);
293
294 sleep(5);
295
296 $response = wp_remote_get($url);
297
298 if (!empty($response) && !is_wp_error($response)) {
299 $html = wp_remote_retrieve_body($response);
300
301 if ($html == 'Hello World!') {
302 $berqconfigs->update_configs(['page_compression' => true]);
303 wp_send_json_success('Compression test passed.');
304 }
305 }
306
307 $berqconfigs->update_configs(['page_compression' => false]);
308 wp_send_json_error('Compression test failed.');
309
310 die(); // Always exit in AJAX functions
311 }
312
313 function increase_nonce_life($default_life)
314 {
315
316 // if (!is_user_logged_in() && bwp_pass_account_requirement()) {
317 if (!is_user_logged_in()) {
318 return 30 * DAY_IN_SECONDS;
319 }
320
321 return $default_life;
322 }
323
324 function remove_admin_notices()
325 {
326
327 if (current_user_can('manage_options')) {
328 $screen = get_current_screen();
329 if ($screen->id === 'toplevel_page_berqwp') {
330 remove_all_actions('user_admin_notices');
331 remove_all_actions('admin_notices');
332 remove_all_actions('all_admin_notices');
333 } else {
334 add_action('admin_notices', function () {
335 do_action('berqwp_notices');
336 }, 10);
337 }
338 }
339 }
340
341 function admin_scripts()
342 {
343
344 // settings page specific assets
345 if ( isset($_GET['page']) && $_GET['page'] == 'berqwp' ) {
346
347 wp_enqueue_style(
348 'bwp-google-fonts',
349 "https://fonts.googleapis.com/css2?family=Lato:wght@400;700&display=swap",
350 [],
351 BERQWP_VERSION
352 );
353
354 wp_enqueue_style(
355 'bwp-jquery-datatable',
356 optifer_URL . '/admin/css/dataTables.dataTables.min.css',
357 [],
358 BERQWP_VERSION
359 );
360
361 wp_enqueue_style(
362 'bwp-settings-style',
363 optifer_URL . '/admin/css/style.css',
364 [],
365 BERQWP_VERSION
366 );
367
368 }
369
370 wp_enqueue_style(
371 'bwp-global-styles', // Handle for the style
372 optifer_URL . 'admin/css/global.css', // URL to the CSS file
373 [], // Dependencies (array of handles)
374 BERQWP_VERSION // Version number
375 );
376 }
377
378 function handle_refresh_license_action()
379 {
380 // Check if the user has the necessary nonce and the action matches
381 if (isset($_GET['action']) && $_GET['action'] === 'bwp_refresh_license' && wp_verify_nonce($_GET['_wpnonce'], 'bwp_refresh_license_action')) {
382
383 // $transient_key = 'berq_lic_response_cache';
384 // $expire_transient_key = 'berq_lic_cache_expire';
385
386 // berqwp_delete_network_option($transient_key);
387 // berqwp_delete_network_option($expire_transient_key);
388
389 berqwp_delete_network_option('berqwp_license_cache');
390
391 // clear cache from cloud
392 bwp_request_purge_license_key_cache();
393
394 global $berqNotifications;
395 $berqNotifications->success('License key successfully refreshed.');
396
397 $redirect_url = add_query_arg('berq_refresh_license', '', wp_get_referer());
398
399 // Redirect back to the referring page after clearing the cache
400 wp_safe_redirect($redirect_url);
401 exit;
402 }
403 }
404
405 function berqwp_get_optimized_pages()
406 {
407 if (!isset($_POST['start']) || !isset($_POST['length'])) {
408 wp_send_json_error('Invalid parameters');
409 return;
410 }
411
412 $start = intval($_POST['start']); // Offset for the query
413 $length = intval($_POST['length']); // Number of records to fetch per request
414 $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : ''; // Search term if present
415
416 $post_types = get_option('berqwp_optimize_post_types');
417 $optimized_pages = [];
418
419 // Build the query arguments
420 $args = array(
421 'post_type' => $post_types,
422 'posts_per_page' => $length, // Limit the number of posts per request
423 'offset' => $start, // Set the offset for pagination
424 'post_status' => array('publish'), // Only published pages
425 );
426
427 // Add search filtering, if applicable
428 if (!empty($search)) {
429 $args['s'] = $search; // Add the search parameter to the query
430 }
431
432 if ($start === 0 && empty($search)) {
433 $url = bwp_admin_home_url('/');
434
435 if (strpos($url, bwp_admin_home_url()) === false) {
436 $url = str_replace(home_url(), bwp_admin_home_url(), $url);
437 }
438
439 $slug = bwp_url_into_path($url);
440
441 $cache_directory = bwp_get_cache_dir();
442 $cache_key = md5($url);
443 // $cache_key = md5($slug);
444 $cache_file = $cache_directory . $cache_key . '.gz';
445
446 if (is_file($cache_file)) {
447 $status = '<span class="bwp-cache-tag completed">Completed</span>';
448
449 // if (bwp_is_partial_cache($url) === true) {
450 // $status = '<span class="bwp-cache-tag part-completed">Partial cache</span>';
451 // }
452 } else {
453 $status = '<span class="bwp-cache-tag">Pending</span>';
454 }
455
456 $parsed_url = parse_url($url);
457 $decoded_path = isset($parsed_url['path']) ? urldecode($parsed_url['path']) : '';
458 $decoded_query = isset($parsed_url['query']) ? urldecode($parsed_url['query']) : '';
459
460 $decoded_url = $parsed_url['scheme'] . '://' . $parsed_url['host'];
461 if (isset($parsed_url['port'])) {
462 $decoded_url .= ':' . $parsed_url['port'];
463 }
464 $decoded_url .= $decoded_path;
465 if ($decoded_query) {
466 $decoded_url .= '?' . $decoded_query;
467 }
468 if (isset($parsed_url['fragment'])) {
469 $decoded_url .= '#' . $parsed_url['fragment'];
470 }
471
472 $page_arr = [
473 'url' => $decoded_url,
474 'status' => $status,
475 'last_modified' => file_exists($cache_file) ? date('Y-m-d H:i:s', filemtime($cache_file)) : ''
476 ];
477
478 array_push($optimized_pages, $page_arr);
479 }
480
481 $query = new WP_Query($args);
482 $total_posts = $query->found_posts; // Get the total number of records
483
484 $valid_posts_query = new WP_Query([
485 'post_type' => $post_types,
486 'posts_per_page' => -1,
487 'fields' => 'ids',
488 'post_status' => ['publish'],
489 ]);
490 $valid_posts = array_filter($valid_posts_query->posts, function ($post_id) {
491 $url = get_permalink($post_id);
492 return bwp_can_optimize_page_url($url);
493 });
494 $total_posts = count($valid_posts);
495
496 if ($query->have_posts()) {
497 while ($query->have_posts()) {
498 $query->the_post();
499
500 $url = get_permalink();
501
502 if (strpos($url, bwp_admin_home_url()) === false) {
503 $url = str_replace(home_url(), bwp_admin_home_url(), $url);
504 }
505
506 if (bwp_admin_home_url('/') == $url) {
507 continue;
508 }
509
510 $slug = bwp_url_into_path($url);
511
512 if (!bwp_can_optimize_page_url($url)) {
513 continue;
514 }
515
516 $cache_directory = bwp_get_cache_dir();
517 $cache_key = md5($url);
518 // $cache_key = md5($slug);
519 $cache_file = $cache_directory . $cache_key . '.gz';
520
521 if (is_file($cache_file)) {
522 $status = '<span class="bwp-cache-tag completed">Completed</span>';
523
524 // if (bwp_is_partial_cache($url) === true) {
525 // $status = '<span class="bwp-cache-tag part-completed">Partial cache</span>';
526 // }
527 } else {
528 $status = '<span class="bwp-cache-tag">Pending</span>';
529 }
530
531 $parsed_url = parse_url($url);
532 $decoded_path = isset($parsed_url['path']) ? urldecode($parsed_url['path']) : '';
533 $decoded_query = isset($parsed_url['query']) ? urldecode($parsed_url['query']) : '';
534
535 $decoded_url = $parsed_url['scheme'] . '://' . $parsed_url['host'];
536 if (isset($parsed_url['port'])) {
537 $decoded_url .= ':' . $parsed_url['port'];
538 }
539 $decoded_url .= $decoded_path;
540 if ($decoded_query) {
541 $decoded_url .= '?' . $decoded_query;
542 }
543 if (isset($parsed_url['fragment'])) {
544 $decoded_url .= '#' . $parsed_url['fragment'];
545 }
546
547 $page_arr = [
548 'url' => $decoded_url,
549 'status' => $status,
550 'last_modified' => file_exists($cache_file) ? date('Y-m-d H:i:s', filemtime($cache_file)) : ''
551 ];
552
553 array_push($optimized_pages, $page_arr);
554 }
555 }
556
557 wp_reset_postdata();
558
559 // Send the response with the optimized pages and total entries
560 wp_send_json_success([
561 'optimized_pages' => $optimized_pages,
562 'total_entries' => $total_posts, // Total number of posts (unfiltered)
563 'records_filtered' => $total_posts // Adjust if filtered by search
564 ]);
565 }
566
567
568
569 function ashp_increase_concurrent_batches($concurrent_batches)
570 {
571 return $concurrent_batches * 2;
572 }
573
574 function refresh_cache_stats()
575 {
576
577 check_ajax_referer('wp_rest', 'nonce');
578
579 $post_types = get_option('berqwp_optimize_post_types');
580 $args = array(
581 'post_type' => $post_types,
582 'posts_per_page' => -1,
583 'fields' => 'ids',
584 'post_status' => 'publish'
585 );
586 $query = new WP_Query($args);
587 $pages_to_exclude = get_option('berq_exclude_urls', []);
588 $total_pages = (int) $query->found_posts - count($pages_to_exclude);
589 $optimized_pages = bwp_cached_pages_count();
590
591 if (get_option('show_on_front') !== 'page') {
592 $total_pages++;
593 }
594
595 if (empty($total_pages) || $total_pages <= 0) {
596 $cached_percentage = 0;
597 } else {
598 $cached_percentage = round(($optimized_pages / $total_pages) * 100, 2);
599 }
600 if ($cached_percentage > 100) {
601 $cached_percentage = 100;
602 }
603
604 if ($cached_percentage < 0) {
605 $cached_percentage = 0;
606 }
607
608 $server_queue = get_option('berqwp_server_queue', []);
609
610 wp_send_json_success(['cache_count' => $optimized_pages, 'cache_percentage' => $cached_percentage, 'total' => $total_pages, 'server_queue' => count($server_queue)]);
611
612 die(); // Always exit in AJAX functions
613 }
614
615 function fetch_remote_html()
616 {
617
618 check_ajax_referer('wp_rest', 'nonce');
619
620 $url = get_option('berqwp_enable_sandbox') ? bwp_admin_home_url('/?berqwp') : bwp_admin_home_url('/');
621
622 $response = wp_remote_get($url);
623 // $response = bwp_wp_remote_get($url);
624
625 if (is_array($response) && !is_wp_error($response)) {
626 $html = wp_remote_retrieve_body($response);
627 echo $html;
628 } else {
629 echo 'Error fetching HTML.';
630 }
631
632 die(); // Always exit in AJAX functions
633 }
634
635 function activate_license_from_multi_site()
636 {
637 if (berq_is_localhost()) {
638 return;
639 }
640
641 $berqwp_license_key_from_parent = constant('BERQWP_LICENSE_KEY');
642
643 if (!empty($berqwp_license_key_from_parent) && empty(berqwp_get_license_key())) {
644 $key = sanitize_text_field($berqwp_license_key_from_parent);
645 $key_response = $this->verify_license_key($key, 'slm_activate');
646
647
648 if (!empty($key_response) && $key_response->result == 'success') {
649 berqwp_update_license_key($key);
650
651 if (is_admin()) {
652 ?>
653 <div class="notice notice-success is-dismissible">
654 <?php esc_html_e('The BerqWP license has been activated for your parent multisite.', 'searchpro'); ?>
655 </div>
656 <?php
657 }
658 } elseif ($key_response->result == 'error') {
659 $error = $key_response->message;
660
661 if (is_admin()) {
662 ?>
663 <div class="notice notice-error is-dismissible">
664 <?php echo esc_html($error); ?>
665 </div>
666 <?php
667
668 }
669 }
670 }
671 }
672
673 function handle_upgrade() {
674
675 $berqconfigs = berqConfigs::getInstance();
676 $configs = $berqconfigs->get_configs();
677 $site_id = $configs['site_id'];
678 $license_key = berqwp_get_license_key();
679 global $berq_log;
680
681 if (!empty($configs['optimization_method']) && $configs['optimization_method'] == 'cloud' && empty($license_key)) {
682
683 $berqconfigs->update_configs([
684 'secret' => '',
685 'optimization_method' => 'local'
686 ]);
687 return;
688 }
689
690 $license_check_only = false;
691
692 if ( !empty($configs['secret']) && !empty($configs['optimization_method']) && $configs['optimization_method'] == 'cloud' && !empty($license_key) && empty(berqwp_get_network_option('berqwp_license_cache')) ) {
693 $license_check_only = true;
694 }
695
696 // user first time upgrades to v4
697 $first_upgrade = empty($configs['optimization_method']) && !empty($license_key);
698 $missing_secret = empty($configs['secret']) && !empty($configs['optimization_method']) && $configs['optimization_method'] == 'cloud' && !empty($license_key);
699
700 if ($first_upgrade || $missing_secret || !empty($license_check_only)) {
701
702 // $berq_log->info("Authenticating secret");
703
704 // $lic_response = wp_remote_post(BerqWPCloud::$endpoint."authenticate", [
705 // 'timeout' => 30,
706 // 'body' => $request_body
707 // ]);
708
709 // if (is_wp_error($lic_response)) {
710 // $berq_log->info("Couldn't reach BerqWP server.");
711 // return;
712 // }
713
714 // $lic_body = wp_remote_retrieve_body($lic_response);
715 // $lic_json = json_decode($lic_body);
716
717 // if (empty($lic_json)) {
718 // $berq_log->info("Authenticate secret invalid response");
719 // return;
720 // }
721
722 $lic_json = $this->authenticate_license($license_key, $license_check_only);
723
724 if (!empty($lic_json->lic) && $lic_json->lic->result == 'success' && ($lic_json->lic->message == 'License key activated' || $lic_json->lic->status == 'active')) {
725
726 if (!empty($lic_json->secret)) {
727 $berqconfigs->update_configs([
728 'secret' => $lic_json->secret,
729 'optimization_method' => 'cloud'
730 ]);
731 }
732
733 berqwp_update_network_option('berqwp_license_cache', $lic_json->lic);
734
735 $berq_log->info("Authentication success.");
736
737 // Fresh installation
738 if (get_option('berqwp_can_use_fluid_images') === false) {
739
740 if ($lic_json->lic->product_ref !== 'AppSumo Deal') {
741 update_option('berqwp_can_use_fluid_images', 1);
742 } else {
743 update_option('berqwp_can_use_fluid_images', 0);
744 update_option('berqwp_sync_addons', true);
745 }
746 }
747
748 } else {
749
750 $berq_log->info("Authentication failed.");
751 berqwp_remove_license_key();
752
753 $berqconfigs->update_configs([
754 'secret' => '',
755 'optimization_method' => 'local'
756 ]);
757
758 berqwp_delete_network_option('berqwp_license_cache');
759 }
760
761 }
762
763 if (!empty(berqwp_get_network_option('berqwp_license_cache'))) {
764 $this->is_key_verified = true;
765 $this->key_response = berqwp_get_network_option('berqwp_license_cache');
766 }
767
768 }
769
770 function initialize()
771 {
772
773 if (defined('DOING_CRON') && DOING_CRON) {
774 return;
775 }
776
777 if (defined('DOING_AJAX') && DOING_AJAX) {
778 return;
779 }
780
781 // Set default settings
782 require_once optifer_PATH . '/inc/initialize.php';
783
784 $this->handle_upgrade();
785
786 if (berqwp_can_use_cloud()) {
787 $license_key = berqwp_get_license_key();
788 $lic_json = $this->authenticate_license($license_key, true);
789
790 if (!empty($lic_json->lic) && $lic_json->lic->result == 'success' && ($lic_json->lic->message == 'License key activated' || $lic_json->lic->status == 'active')) {
791 berqwp_update_network_option('berqwp_license_cache', $lic_json->lic);
792 }
793 }
794
795 // Activate the license from parent site
796 // if (defined('BERQWP_LICENSE_KEY')) {
797 // $this->activate_license_from_multi_site();
798 // }
799
800 if (is_admin()) {
801 $this->berq_post_types();
802 }
803
804 // if (is_admin() && isset($_GET['bwp_get_ip'])) {
805 // $ip = file_get_contents('https://api.ipify.org');
806 // echo 'Server Public IP Address: ' . $ip;
807 // exit;
808 // }
809
810 // if (is_admin() && !empty(berqwp_get_license_key())) {
811 // $license_key = berqwp_get_license_key();
812
813 // global $berq_log;
814 // // $berq_log->info("License key check from initialize function.");
815
816 // $key_response = $this->verify_license_key($license_key);
817
818 // if (!empty($key_response) && $key_response->result == 'success' && $key_response->status == 'active') {
819 // $this->is_key_verified = true;
820 // $this->key_response = $key_response;
821
822 // // Fresh installation
823 // if (get_option('berqwp_can_use_fluid_images') === false) {
824
825 // if ($key_response->product_ref !== 'AppSumo Deal') {
826 // update_option('berqwp_can_use_fluid_images', 1);
827 // } else {
828 // update_option('berqwp_can_use_fluid_images', 0);
829 // update_option('berqwp_sync_addons', true);
830 // }
831 // }
832
833 // } else {
834 // $this->is_key_verified = false;
835
836 // if (!empty($key_response) && $key_response->result == 'error') {
837 // berqwp_delete_license_key();
838 // }
839 // }
840 // }
841
842 // redirect to berqwp admin page
843 if (get_transient('berqwp_redirect')) {
844 delete_transient('berqwp_redirect');
845 // Set the URL to redirect to after activation
846 $redirect_url = admin_url('admin.php?page=berqwp');
847
848 // Redirect after activation
849 wp_redirect($redirect_url);
850
851 // Make sure to exit after the redirect
852 exit;
853 }
854
855 // Deactivate conflicting plugins
856 if (is_admin() && isset($_POST['berqwp_plugins_deactivate']) && wp_verify_nonce($_POST['berqwp_plugins_deactivate'], 'berqwp_plugins_deactivate')) {
857 foreach ($this->conflicting_plugins as $plugin) {
858 // Deactivate each conflicting plugin
859 if (is_plugin_active($plugin)) {
860 deactivate_plugins($plugin);
861 }
862 }
863 header('location: ' . esc_url(get_site_url() . add_query_arg($_GET)));
864 exit;
865 }
866 }
867
868 function save_settings()
869 {
870 require_once optifer_PATH . '/admin/save-settings.php';
871 }
872
873 function notices()
874 {
875
876 $plugin_name = defined('BERQWP_PLUGIN_NAME') ? BERQWP_PLUGIN_NAME : 'BerqWP';
877
878 if (isset($_GET['berqwp_page_compression_enabled'])) {
879 bwp_notice('success', 'Page Compression Enabled', "<p>Page compression has been successfully enabled on your website.</p>");
880 }
881
882 if (isset($_GET['dismiss_feedback'])) {
883 set_transient('bqwp_hide_feedback_notice', true, DAY_IN_SECONDS * 14);
884 }
885
886 if (isset($_GET['bwp_quit_feedback'])) {
887 update_option('bwp_quit_feedback', true);
888 }
889
890
891 if (!empty($this->key_response) && $this->key_response->result == 'success' && $this->key_response->status == 'expired') {
892 ?>
893 <div class="notice notice-error">
894 <p><strong>Error:</strong> <?php echo $plugin_name; ?> license key has expired. Please renew your subscription.</p>
895 </div>
896 <?php
897 }
898
899 // Check connection
900 // $check_rest = bwp_check_connection(false, !empty($_GET['bwp_connection_test']) === true);
901 // if ($check_rest['status'] == 'error') {
902 // bwp_notice('error', 'Website Unreachable: Connection Blocked', "<p>$plugin_name server is unable to access this website, please whitelist our server IP address. <a href='https://berqwp.com/help-center/get-started-with-berqwp/' target='_blank'>Find our server IP address here.</a></p>", [
903 // [
904 // 'href' => esc_attr(add_query_arg(['bwp_connection_test' => true], get_admin_url())),
905 // 'text' => 'Check again',
906 // 'classes' => '',
907 // ]
908 // ]);
909 // }
910
911 // Check Permissions
912 $cache_directory = WP_CONTENT_DIR . '/cache/berqwp/';
913 $wp_config_file = defined('BERQWP_WP_CONFIG') ? BERQWP_WP_CONFIG : ABSPATH . 'wp-config.php';
914
915 if (!is_writable($cache_directory)) {
916 bwp_notice('error', 'Cache directory is not writable', "<p>The $plugin_name cache directory at /wp-content/cache/berqwp/ is not writable. Please update the directory permissions to allow the plugin to store cached files.</p>", []);
917 }
918
919 if (!defined('WP_CACHE') && !is_writable($wp_config_file)) {
920 bwp_notice('warning', 'wp-config.php is not writable', "<p>The wp-config.php file is not writable. $plugin_name needs to write configuration settings to this file. Please adjust the file permissions or manually add the WP_CACHE constant and set it to true.</p>", []);
921 }
922
923 if (defined('BERQWP_ADVANCED_CACHE_PATH')) {
924 $adv_cache_path = BERQWP_ADVANCED_CACHE_PATH;
925 } else {
926 $adv_cache_path = WP_CONTENT_DIR . '/advanced-cache.php';
927 }
928
929 // if (file_exists($adv_cache_path) && !is_writable($adv_cache_path)) {
930 // bwp_notice('warning', 'advanced-cache.php is not writable', "<p>$plugin_name can't write to wp-content/advanced-cache.php — please check file permissions or re-save settings to regenerate it.</p>", []);
931 // }
932
933 if (isset($_GET['page']) && $_GET['page'] == 'berqwp' && !get_transient('bqwp_hide_feedback_notice') && !get_option('bwp_quit_feedback') && $this->is_key_verified && bwp_show_account()) {
934 bwp_notice('info bwp_feedback', 'Loving BerqWP\'s performance?', '<p>Show some love and help us grow 👉 - <a href="https://wordpress.org/support/plugin/searchpro/reviews/#new-post" target="_blank">Rate BerqWP Plugin</a>. Your insights shape our journey.</p>', [
935 [
936 'href' => 'https://wordpress.org/support/plugin/searchpro/reviews/#new-post',
937 'text' => '❤️ You deserve it',
938 'classes' => '',
939 'target' => '_blank',
940 ],
941 [
942 'href' => get_admin_url() . 'admin.php?page=berqwp&bwp_quit_feedback',
943 'text' => '👍 Already did',
944 'classes' => '',
945 'target' => '',
946 ],
947 [
948 'href' => get_admin_url() . 'admin.php?page=berqwp&dismiss_feedback',
949 'text' => 'Not Now',
950 'classes' => '',
951 'target' => '',
952 ]
953 ]);
954
955 // $notice = '<div class="bwp-notice bwp_feedback">';
956 // $notice .= '<p>';
957 // $notice .= __('🎉 <b>Loving BerqWP\'s performance? 🚀</b> Show some love and help us grow 👉 - <a href="https://wordpress.org/support/plugin/searchpro/reviews/#new-post" target="_blank">Rate BerqWP Plugin</a>. Your insights shape our journey.', 'searchpro');
958 // $notice .= '<a href="'.get_admin_url().'admin.php?page=berqwp&dismiss_feedback" style="display: table;margin-left: 50px;color: #969595;display: table;">Dismiss</a>';
959 // $notice .= '</p>';
960 // $notice .= '</div>';
961 // echo wp_kses_post($notice);
962 }
963
964 // purge single page notice
965 if (get_transient('berq_purge_page_notice')) {
966 $flushed_page = esc_url(get_transient('berq_purge_page_notice'));
967 delete_transient('berq_purge_page_notice');
968 bwp_notice('success', '', "<p>Page cache has been flushed for $flushed_page.</p>", []);
969 }
970
971 // purge all cache notice
972 if (get_transient('berq_cache_cleared_notice')) {
973 delete_transient('berq_cache_cleared_notice');
974 bwp_notice('success', '', '<p>The cache has been cleared. Our automatic cache warm-up system will generate the cache. Alternatively, you can
975 visit any page to create its cache immediately.</p>', []);
976 }
977
978 // purge cdn cache notice
979 if (get_transient('berq_purge_cdn_notice')) {
980 delete_transient('berq_purge_cdn_notice');
981 bwp_notice('success', '', '<p>The CDN and page cache have been flushed.</p>', []);
982 }
983
984 // purge critical css cache notice
985 if (get_transient('berq_purge_criticalcss_notice')) {
986 delete_transient('berq_purge_criticalcss_notice');
987 bwp_notice('success', '', '<p>Critical CSS cache has been flushed from the cloud.</p>', []);
988 }
989
990 // cache warmup notice
991 if (get_transient('berq_cache_warmup_notice')) {
992 delete_transient('berq_cache_warmup_notice');
993 bwp_notice('success', 'Cache Warmup Queued', '<p>The cache warmup has been added to the queue. Your website pages will be optimized in the background and ready soon.</p>', []);
994 }
995
996 // force page cache notice
997 if (get_transient('berq_force_cache_notice')) {
998 $forced_page = esc_url(get_transient('berq_force_cache_notice'));
999 delete_transient('berq_force_cache_notice');
1000 bwp_notice('success', '', "<p>The cache for page ($forced_page) has been queued with high priority and will be generated soon.</p>", []);
1001 }
1002
1003 if (get_option('bwp_require_flush_cache', false)) {
1004 bwp_notice('warning', 'Cache Flush Required', '<p>To apply the changes, please flush the cache.</p>', [
1005 [
1006 'href' => esc_attr(wp_nonce_url(admin_url('admin-post.php?action=clear_cache'), 'clear_cache_action')),
1007 'text' => 'Flush cache',
1008 'classes' => '',
1009 ]
1010 ]);
1011 }
1012
1013 if (berq_is_localhost() && berqwp_can_use_cloud()) {
1014 bwp_notice('warning', 'Localhost environment detected:', "<p>$plugin_name requires a live, publicly accessible website to function.</p>", []);
1015 }
1016
1017 $plugins_to_deactivate = '';
1018
1019 foreach ($this->conflicting_plugins as $plugin) {
1020 if (is_plugin_active($plugin)) {
1021 $plugins_to_deactivate .= '<li><b>' . basename(dirname($plugin)) . '</b></li>';
1022 }
1023 }
1024
1025 if (!empty($plugins_to_deactivate)) {
1026 echo "<style>.berqwp-plugin-conflict ul {
1027 list-style: disc;
1028 margin-left: 20px;
1029 }.berqwp-plugin-conflict form {
1030 padding: 10px;
1031 }
1032 .berqwp-plugin-conflict {
1033 display: grid;
1034 grid-template-columns: auto min-content;
1035 }</style>";
1036 echo '<div class="bwp-notice notice notice-error berqwp-plugin-conflict">';
1037 echo wp_kses_post(__('<p><strong>BerqWP Plugin Conflict:</strong> The following plugins have a same nature as BerqWP plugin. Having multiple plugins of the same type can cause unexpected results.</p>', 'searchpro'));
1038 ?>
1039 <form action="<?php echo esc_url(get_site_url() . add_query_arg($_GET)); ?>" method="post">
1040
1041 <?php
1042 $my_nonce = wp_create_nonce('berqwp_plugins_deactivate');
1043 echo '<input type="hidden" name="berqwp_plugins_deactivate" value="' . esc_attr($my_nonce) . '" />';
1044 ?>
1045
1046 <input type="submit" class="button-secondary alignright" value="Deactivate Conflicting Plugins">
1047 </form>
1048 <?php
1049 echo wp_kses_post("<ul>$plugins_to_deactivate</ul>");
1050 echo '</div>';
1051 }
1052 }
1053
1054 function berq_post_types()
1055 {
1056 // Get post type names
1057 $post_type_names = get_post_types(['public' => true, 'exclude_from_search' => false], 'names');
1058 unset($post_type_names['attachment']);
1059
1060 // var_dump($post_type_names);
1061
1062 // Modify which post types to optimize
1063 $post_type_names = apply_filters('berqwp_post_types', $post_type_names);
1064
1065 // Save the names in a WordPress option
1066 update_option('berqwp_post_type_names', $post_type_names);
1067 }
1068
1069 function plugin_settings_links($links)
1070 {
1071 $mylinks = array(
1072 '<a target="_blank" href="https://berqwp.com/help-center/">' . __('Help Center', 'searchpro') . '</a>',
1073 '<a href="' . admin_url('admin.php?page=berqwp') . '">' . __('Settings', 'searchpro') . '</a>',
1074 );
1075
1076 return array_merge($links, $mylinks);
1077 }
1078
1079 function authenticate_license($license_key, $check_only = false) {
1080
1081 $berqconfigs = berqConfigs::getInstance();
1082 $berqwp_configs = $berqconfigs->get_configs();
1083 $site_id = $berqwp_configs['site_id'];
1084
1085 if (empty($site_id)) {
1086 $blog_id = get_current_blog_id();
1087 $network_id = function_exists('get_current_network_id') ? get_current_network_id() : 1;
1088 $siteurl = get_option('siteurl');
1089 $site_id = md5("berqwp|$network_id|$blog_id|$siteurl");
1090
1091 $berqconfigs->update_configs(['site_id' => $site_id]);
1092 }
1093
1094 global $berq_log;
1095 $transient_key = 'berqwp_lic_response_cache'; // Set a unique key for the transient
1096 $expire_transient_key = 'berqwp_lic_cache_expire'; // Set a unique key for the transient
1097
1098 if (!$check_only) {
1099 berqwp_delete_network_option($transient_key);
1100 }
1101
1102 // Check if the response is already cached
1103 $lic_json = berqwp_get_network_option($transient_key);
1104 $cache_expire_time = (int) berqwp_get_network_option($expire_transient_key);
1105
1106 if (false === $lic_json || $cache_expire_time < time()) {
1107
1108 $berq_log->info("Authenticating license key");
1109
1110 $body = [
1111 'license_key' => $license_key,
1112 'site_id' => $site_id,
1113 'site_url' => home_url(),
1114 ];
1115
1116 if ($check_only) {
1117 $body['check'] = true;
1118 }
1119
1120 $lic_response = wp_remote_post(BerqWPCloud::$endpoint."authenticate", [
1121 'timeout' => 30,
1122 'body' => $body
1123 ]);
1124
1125 if (is_wp_error($lic_response)) {
1126 $berq_log->info("Couldn't reach BerqWP server.");
1127 return;
1128 }
1129
1130 $lic_body = wp_remote_retrieve_body($lic_response);
1131 $lic_json = json_decode($lic_body);
1132
1133 if (!empty($lic_json)) {
1134 berqwp_update_network_option($transient_key, $lic_json);
1135 berqwp_update_network_option($expire_transient_key, time() + DAY_IN_SECONDS);
1136 }
1137
1138 }
1139
1140
1141 return $lic_json;
1142
1143 }
1144
1145 function verify_license_key($license_key, $action = 'slm_check')
1146 {
1147 if ($action !== 'slm_deactivate') {
1148 return;
1149 }
1150
1151 // Action
1152 // slm_activate
1153 // slm_deactivate
1154 // slm_check
1155
1156 if (empty($license_key)) {
1157 return;
1158 }
1159
1160 if (defined('BERQWP_DOING_LICENSE_CHECK')) {
1161 // sleep(1);
1162 return;
1163 }
1164
1165 /**
1166 * Replaced transients with options
1167 */
1168
1169 global $berq_log;
1170 $transient_key = 'berq_lic_response_cache'; // Set a unique key for the transient
1171 $expire_transient_key = 'berq_lic_cache_expire'; // Set a unique key for the transient
1172
1173 if ($action !== 'slm_check') {
1174 // delete_transient( $transient_key );
1175 berqwp_delete_network_option($transient_key);
1176 }
1177
1178 // Check if the response is already cached
1179 // $cached_response = get_transient($transient_key);
1180 $cached_response = berqwp_get_network_option($transient_key);
1181 $cache_expire_time = (int) berqwp_get_network_option($expire_transient_key);
1182
1183
1184 if (false === $cached_response || $cache_expire_time < time()) {
1185 // If not cached, perform the API request
1186
1187 $rateLimiter = new RateLimiter(5, 60, optifer_cache . 'ratelimit/');
1188 $clientIdentifier = gethostname();
1189 if (function_exists('is_multisite') && is_multisite()) {
1190 $clientIdentifier .= '-site-' . get_current_blog_id();
1191 }
1192
1193 if ($rateLimiter->isRateLimited($clientIdentifier)) {
1194 return false;
1195 }
1196
1197 define('BERQWP_DOING_LICENSE_CHECK', true);
1198
1199 $berq_log->info('Checking the license key.');
1200
1201 $parsed_url = parse_url(home_url());
1202 $domain = $parsed_url['host'];
1203
1204 $api_params = array(
1205 'registered_domain' => $domain,
1206 'slm_action' => $action,
1207 'secret_key' => BERQ_SECRET,
1208 'license_key' => $license_key,
1209 'version' => BERQWP_VERSION,
1210 't' => '',
1211 );
1212
1213 $endpoint_url = esc_url(add_query_arg($api_params, BERQ_SERVER));
1214
1215 $args = array(
1216 'method' => 'POST', // Only POST works for unknown reason
1217 'timeout' => 20,
1218 'redirection' => 5,
1219 'blocking' => true,
1220 'headers' => array(
1221 'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
1222 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
1223 'Accept-Encoding' => 'gzip, deflate, br',
1224 'Accept-Language' => 'en-US,en;q=0.9',
1225 'Connection' => 'keep-alive',
1226 'Referer' => 'https://berqwp.com/', // Adjust based on actual referer
1227 ),
1228 'cookies' => array(),
1229 'sslverify' => false, // Disable SSL verification (for debugging purposes)
1230 );
1231
1232 // $request = wp_remote_request( $endpoint_url, $args );
1233
1234
1235 $berq_log->info('Making request 1');
1236
1237 $query_string = http_build_query($api_params);
1238 // $client = new HttpClient(BERQ_SERVER);
1239 // $client->setUserAgent('BerqWP');
1240 // $client->post('?' . $query_string, $api_params);
1241 // $client->setTimeout(30);
1242
1243 $client = new \GuzzleHttp\Client([
1244 'timeout' => 60,
1245 'http_errors' => false,
1246 'verify' => false,
1247 ]);
1248
1249 $response = $client->post(BERQ_SERVER . '?' . $query_string, [
1250 'form_params' => $api_params,
1251 ]);
1252 $statusCode = $response->getStatusCode();
1253 $response = $response->getBody()->getContents();
1254
1255 // var_dump($client->getContent(), $client->getError(), $api_params);
1256
1257 // $berq_log->info(print_r($client->getContent(), true).'---'.$client->ok());
1258
1259 if ($statusCode >= 200 && $statusCode < 300) {
1260 // $response = $client->getContent();
1261 $JSON = json_decode($response);
1262
1263 if ($action == 'slm_activate' && isset($JSON->error_code) && $JSON->message !== 'Invalid license key') {
1264 sleep(1);
1265 $api_params = array(
1266 'registered_domain' => $domain,
1267 'slm_action' => 'slm_check',
1268 'secret_key' => BERQ_SECRET,
1269 'license_key' => $license_key,
1270 't' => '',
1271 );
1272
1273 $berq_log->info('Making request 2');
1274
1275 $query_string = http_build_query($api_params);
1276 // $client = new HttpClient(BERQ_SERVER);
1277 // $client->setUserAgent('BerqWP');
1278 // $client->post('?' . $query_string, $api_params);
1279
1280
1281 // if ($client->ok()) {
1282 // $response = $client->getContent();
1283 // }
1284
1285 $response = $client->post(BERQ_SERVER . '?' . $query_string, [
1286 'form_params' => $api_params,
1287 ]);
1288
1289 $response = $response->getBody()->getContents();
1290 }
1291 }
1292
1293 if ($action !== 'slm_check') {
1294 $api_params = array(
1295 'registered_domain' => $domain,
1296 'slm_action' => 'slm_check',
1297 'secret_key' => BERQ_SECRET,
1298 'license_key' => $license_key,
1299 'version' => BERQWP_VERSION,
1300 't' => '',
1301 );
1302
1303 $berq_log->info('Making request 3');
1304
1305 $query_string = http_build_query($api_params);
1306 // $client = new HttpClient(BERQ_SERVER);
1307 // $client->setUserAgent('BerqWP');
1308 // $client->post('?' . $query_string, $api_params);
1309
1310
1311 // if ($client->ok()) {
1312 // $response = $client->getContent();
1313 // }
1314
1315 $response = $client->post(BERQ_SERVER . '?' . $query_string, [
1316 'form_params' => $api_params,
1317 ]);
1318
1319 $response = $response->getBody()->getContents();
1320 }
1321
1322 if (empty($response)) {
1323 return;
1324 }
1325
1326 $cached_response = json_decode($response);
1327
1328
1329 if ($action == 'slm_check' && !empty($cached_response) && !empty($cached_response->result)) {
1330 $domain_found = false;
1331
1332 foreach ($cached_response->registered_domains as $reg_domain) {
1333 $domain_name = str_replace('www.', '', $domain);
1334 $domain_name_www = 'www.' . $domain;
1335
1336 if ($reg_domain->registered_domain == $domain_name || $reg_domain->registered_domain == $domain_name_www || $reg_domain->registered_domain == $domain) {
1337 $domain_found = true;
1338 break;
1339 }
1340 }
1341
1342 if ($domain_found) {
1343 // Cache the response for 24 hours
1344 // set_transient($transient_key, $cached_response, 24 * HOUR_IN_SECONDS);
1345 berqwp_update_network_option($transient_key, $cached_response);
1346 berqwp_update_network_option($expire_transient_key, time() + MONTH_IN_SECONDS);
1347 } else {
1348
1349 berqwp_delete_network_option($transient_key);
1350 berqwp_delete_network_option($expire_transient_key);
1351 berqwp_delete_license_key();
1352
1353 return false;
1354 }
1355 }
1356
1357 // if ($action == 'slm_check' && !empty($cached_response) && $cached_response->result == 'success' && $cached_response->status == 'active') {
1358 // // Cache the response for 24 hours
1359 // set_transient($transient_key, $cached_response, 24 * HOUR_IN_SECONDS);
1360 // }
1361
1362 // if ($action == 'slm_check' && !empty($cached_response) && $cached_response->result == 'error') {
1363 // // Key verification failed, cache the response for 14 hours
1364 // // preventing unnecessary verification requests
1365 // set_transient($transient_key, $cached_response, 14 * HOUR_IN_SECONDS);
1366 // }
1367
1368 } else {
1369 // $berq_log->info('Delivering license key object from the transient cache.');
1370 }
1371
1372 // Return the cached response
1373 return $cached_response;
1374 }
1375
1376 // Disable emoji functionality
1377 function disable_emoji()
1378 {
1379 // Remove emoji-related actions and filters
1380 remove_action('wp_head', 'print_emoji_detection_script', 7);
1381 remove_action('admin_print_scripts', 'print_emoji_detection_script');
1382 remove_action('wp_print_styles', 'print_emoji_styles');
1383 remove_action('admin_print_styles', 'print_emoji_styles');
1384 remove_filter('the_content_feed', 'wp_staticize_emoji');
1385 remove_filter('comment_text_rss', 'wp_staticize_emoji');
1386 remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
1387
1388 // Remove emoji-related TinyMCE plugins
1389 add_filter('tiny_mce_plugins', [$this, 'disable_emoji_tinymce']);
1390 }
1391
1392 // Filter function to disable emoji-related TinyMCE plugins
1393 function disable_emoji_tinymce($plugins)
1394 {
1395 if (is_array($plugins)) {
1396 return array_diff($plugins, array('wpemoji'));
1397 } else {
1398 return array();
1399 }
1400 }
1401
1402 // function clear_cache(WP_REST_Request $request)
1403 // {
1404 // require_once optifer_PATH . 'api/clear_cache.php';
1405 // }
1406
1407 // function warmup_cache(WP_REST_Request $request)
1408 // {
1409 // require_once optifer_PATH . 'api/warmup_cache.php';
1410 // }
1411
1412 // function store_cache(WP_REST_Request $request)
1413 // {
1414 // require_once optifer_PATH . 'api/store_cache.php';
1415 // }
1416
1417 // function store_javascript_cache(WP_REST_Request $request)
1418 // {
1419 // require_once optifer_PATH . 'api/store_javascript_cache.php';
1420 // }
1421
1422 // ==========================================
1423 // Multisite Network Support
1424 // ==========================================
1425
1426 function register_network_menu()
1427 {
1428 $svg = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
1429 <path fill-rule="evenodd" clip-rule="evenodd" d="M6.43896 0H17.561C21.1172 0 24 2.88287 24 6.43903V17.561C24 21.1171 21.1172 24 17.561 24H6.43896C2.88281 24 0 21.1171 0 17.561V6.43903C0 2.88287 2.88281 0 6.43896 0ZM15.7888 4.09753L8.59961 12.7534H12.3517L7.02441 20.4878L16.3903 11.0222L12.7814 10.3799L15.7888 4.09753Z" fill="#a7aaad"/>
1430 </svg>';
1431
1432 $plugin_name = defined('BERQWP_PLUGIN_NAME') ? BERQWP_PLUGIN_NAME : 'BerqWP';
1433
1434 add_menu_page(
1435 $plugin_name . ' Network',
1436 $plugin_name,
1437 'manage_network_options',
1438 'berqwp-network',
1439 [$this, 'network_admin_page'],
1440 'data:image/svg+xml;base64,' . base64_encode($svg),
1441 10
1442 );
1443 }
1444
1445 function network_admin_page()
1446 {
1447 require_once optifer_PATH . 'admin/network-admin-page.php';
1448 }
1449
1450 function save_network_settings()
1451 {
1452 check_admin_referer('berqwp_network_save');
1453
1454 if (!current_user_can('manage_network_options')) {
1455 wp_die('Unauthorized');
1456 }
1457
1458 // License activation
1459 if (!empty($_POST['berqwp_license_key'])) {
1460 $key = sanitize_text_field($_POST['berqwp_license_key']);
1461 // $key_response = $this->verify_license_key($key, 'slm_activate');
1462 $key_response = $this->authenticate_license($key);
1463 if (!empty($key_response) && isset($key_response->result) && $key_response->result == 'success') {
1464 berqwp_update_license_key($key);
1465 }
1466 }
1467
1468 // License deactivation
1469 if (!empty($_POST['berq_deactivate_key'])) {
1470 $existing_key = berqwp_get_license_key();
1471 if (!empty($existing_key)) {
1472 $this->verify_license_key($existing_key, 'slm_deactivate');
1473 }
1474 berqwp_delete_license_key();
1475 berqwp_delete_network_option('berq_lic_response_cache');
1476 berqwp_delete_network_option('berq_lic_cache_expire');
1477 berqwp_delete_network_option('berqwp_lic_response_cache');
1478 berqwp_delete_network_option('berqwp_lic_cache_expire');
1479 }
1480
1481 // Flush all sites cache
1482 if (!empty($_POST['berqwp_flush_all_cache'])) {
1483 $cache_directory = WP_CONTENT_DIR . '/cache/berqwp/html/';
1484 if (is_dir($cache_directory)) {
1485 berqwp_unlink_recursive($cache_directory);
1486 }
1487 }
1488
1489 wp_safe_redirect(network_admin_url('admin.php?page=berqwp-network&updated=true'));
1490 exit;
1491 }
1492
1493 function regenerate_blog_map()
1494 {
1495 if (!function_exists('is_multisite') || !is_multisite()) {
1496 return;
1497 }
1498
1499 $sites = get_sites(['fields' => 'ids', 'number' => 0]);
1500 $map = [
1501 'subdomains' => [],
1502 'subdirs' => [],
1503 ];
1504
1505 $is_subdomain = defined('SUBDOMAIN_INSTALL') && SUBDOMAIN_INSTALL;
1506
1507 foreach ($sites as $site_id) {
1508 $site = get_site($site_id);
1509 if (!$site) continue;
1510
1511 if ($is_subdomain) {
1512 $map['subdomains'][strtolower($site->domain)] = (int) $site_id;
1513 } else {
1514 $path = rtrim($site->path, '/') . '/';
1515 if ($path !== '/') {
1516 $map['subdirs'][$path] = (int) $site_id;
1517 }
1518 }
1519 }
1520
1521 $map_file = WP_CONTENT_DIR . '/cache/berqwp/blog-map.json';
1522 $map_dir = dirname($map_file);
1523 if (!is_dir($map_dir)) {
1524 wp_mkdir_p($map_dir);
1525 }
1526 file_put_contents($map_file, json_encode($map, JSON_PRETTY_PRINT));
1527 }
1528
1529 function on_new_site_created($new_site)
1530 {
1531 if (function_exists('is_plugin_active_for_network') && is_plugin_active_for_network('searchpro/berqwp.php')) {
1532 switch_to_blog($new_site->blog_id);
1533 berqwp_activate_single_site();
1534 restore_current_blog();
1535 }
1536 $this->regenerate_blog_map();
1537 }
1538
1539 function register_menu()
1540 {
1541 $svg = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
1542 <path fill-rule="evenodd" clip-rule="evenodd" d="M6.43896 0H17.561C21.1172 0 24 2.88287 24 6.43903V17.561C24 21.1171 21.1172 24 17.561 24H6.43896C2.88281 24 0 21.1171 0 17.561V6.43903C0 2.88287 2.88281 0 6.43896 0ZM15.7888 4.09753L8.59961 12.7534H12.3517L7.02441 20.4878L16.3903 11.0222L12.7814 10.3799L15.7888 4.09753Z" fill="#a7aaad"/>
1543 </svg>';
1544
1545 $plugin_name = defined('BERQWP_PLUGIN_NAME') ? BERQWP_PLUGIN_NAME : 'BerqWP';
1546
1547 add_menu_page($plugin_name, $plugin_name, 'manage_options', 'berqwp', [$this, 'admin_page'], 'data:image/svg+xml;base64,' . base64_encode($svg), 10);
1548 }
1549
1550 function admin_page()
1551 {
1552
1553 $berqconfigs = berqConfigs::getInstance();
1554 $configs = $berqconfigs->get_configs();
1555
1556 if (!empty($configs['optimization_method'])) {
1557 require_once optifer_PATH . 'admin/admin-page.php';
1558 } else {
1559 require_once optifer_PATH . 'admin/intro-page.php';
1560 }
1561 }
1562 }
1563
1564 berqWP::getInstance();
1565 // global $berqWP;
1566 // $berqWP = new berqWP();
1567 }
1568