PluginProbe
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript / 1.9.5
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript v1.9.5
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 1.9.5, at inc/class-berqwp.php

567 lines 17.2 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 if (!class_exists('berqWP')) {
6 class berqWP
7 {
8
9 public $is_key_verified = false;
10 public $key_response = false;
11
12 public $conflicting_plugins = [
13 'autoptimize/autoptimize.php', // Autoptimize
14 'wp-super-cache/wp-cache.php', // WP Super Cache
15 'w3-total-cache/w3-total-cache.php', // W3 Total Cache
16 'wp-fastest-cache/wpFastestCache.php', // WP Fastest Cache
17 'litespeed-cache/litespeed-cache.php', // LiteSpeed Cache
18 'cache-enabler/cache-enabler.php', // Cache Enabler
19 'hummingbird-performance/wp-hummingbird.php', // Hummingbird – Speed up, Cache, Optimize Your CSS and JS
20 'sg-cachepress/sg-cachepress.php', // SiteGround Optimizer (for those hosted on SiteGround)
21 'wp-rocket/wp-rocket.php', // WP Rocket
22 'breeze/breeze.php', // Breeze (Cloudways)
23 'comet-cache/comet-cache.php', // Comet Cache
24 'hyper-cache/plugin.php', // Hyper Cache
25 'simple-cache/simple-cache.php', // Simple Cache
26 'wp-optimize/wp-optimize.php', // WP-Optimize
27 'swift-performance-lite/performance.php', // Swift Performance Lite
28 'nitropack/nitropack.php', // NitroPack
29 'jetpack-boost/jetpack-boost.php', // Jetpack Boost
30 'tenweb-speed-optimizer/tenweb_speed_optimizer.php', // 10Web Booster
31 'speed-booster-pack/speed-booster-pack.php', // Speed booster pack
32 'wp-speed-of-light/wp-speed-of-light.php', // WP speed of light
33 'speedycache/speedycache.php', // Speedy cache
34 'powered-cache/powered-cache.php', // Powered cache
35 'clearfy/clearfy.php', // Clearfy
36 'rabbit-loader/rabbit-loader.php',
37 'psn-pagespeed-ninja/pagespeedninja.php',
38 'jch-optimize/jch-optimize.php',
39 'cache-enabler/cache-enabler.php',
40 'core-web-vitals-pagespeed-booster/core-web-vitals-pagespeed-booster.php',
41 'surge/surge.php',
42 'speedien/speedien.php',
43 'wpspeed/wpspeed.php',
44 'debloat/debloat.php',
45 'perfmatters/perfmatters.php',
46 'phastpress/phastpress.php',
47 // 'hide-my-wp/index.php',
48 ];
49
50 function __construct()
51 {
52
53 add_action('init', [$this, 'initialize']);
54
55 // Save settings
56 add_action('admin_init', [$this, 'save_settings']);
57
58 require_once optifer_PATH . '/api/register_apis.php';
59
60 add_action('admin_menu', [$this, 'register_menu']);
61 // add_action('init', [$this, 'berq_post_types'], 20);
62 add_action('admin_notices', [$this, 'notices']);
63
64 add_filter('plugin_action_links_searchpro/berqwp.php', [$this, 'plugin_settings_links']);
65
66 add_action('wp_ajax_berqwp_fetch_remote_html', [$this, 'fetch_remote_html']);
67
68 // add_filter( 'action_scheduler_queue_runner_concurrent_batches', [$this, 'ashp_increase_concurrent_batches'] );
69 }
70
71 function ashp_increase_concurrent_batches( $concurrent_batches ) {
72 return $concurrent_batches * 2;
73 }
74
75 function fetch_remote_html() {
76
77 check_ajax_referer('wp_rest', 'nonce');
78
79 $url = get_option('berqwp_enable_sandbox') ? home_url().'/?berqwp' : home_url();
80
81 // $response = wp_remote_get($url);
82 $response = bwp_wp_remote_get($url);
83
84 if (is_array($response) && !is_wp_error($response)) {
85 $html = wp_remote_retrieve_body($response);
86 echo $html;
87 } else {
88 echo 'Error fetching HTML.';
89 }
90
91 die(); // Always exit in AJAX functions
92 }
93
94 function activate_license_from_multi_site()
95 {
96 if (berq_is_localhost()) {
97 return;
98 }
99
100 $berqwp_license_key_from_parent = constant('BERQWP_LICENSE_KEY');
101
102 if (!empty($berqwp_license_key_from_parent) && empty(get_option('berqwp_license_key'))) {
103 $key = sanitize_text_field($berqwp_license_key_from_parent);
104 $key_response = $this->verify_license_key($key, 'slm_activate');
105
106
107 if (!empty($key_response) && $key_response->result == 'success') {
108 update_option('berqwp_license_key', $key);
109
110 if (is_admin()) {
111 ?>
112 <div class="notice notice-success is-dismissible">
113 <?php esc_html_e('The BerqWP license has been activated for your parent multisite.', 'searchpro'); ?>
114 </div>
115 <?php
116 }
117
118 } elseif ($key_response->result == 'error') {
119 $error = $key_response->message;
120
121 if (is_admin()) {
122 ?>
123 <div class="notice notice-error is-dismissible">
124 <?php echo esc_html($error); ?>
125 </div>
126 <?php
127
128 }
129 }
130 }
131 }
132
133 function initialize()
134 {
135
136 // Set default settings
137 require_once optifer_PATH . '/inc/initialize.php';
138
139 // Activate the license from parent site
140 if (defined('BERQWP_LICENSE_KEY')) {
141 $this->activate_license_from_multi_site();
142 }
143
144 if (is_admin()) {
145 $this->berq_post_types();
146 }
147
148 if (get_option('berqwp_disable_emojis') == 1) {
149 $this->disable_emoji();
150 }
151
152 if (is_admin() && !empty(get_option('berqwp_license_key'))) {
153 $license_key = get_option('berqwp_license_key');
154 $key_response = $this->verify_license_key($license_key);
155
156 if (!empty($key_response) && $key_response->result == 'success' && $key_response->status == 'active') {
157 $this->is_key_verified = true;
158 $this->key_response = $key_response;
159
160 } else {
161 $this->is_key_verified = false;
162 }
163 }
164
165 // redirect to berqwp admin page
166 if (get_transient('berqwp_redirect')) {
167 delete_transient('berqwp_redirect');
168 // Set the URL to redirect to after activation
169 $redirect_url = admin_url('admin.php?page=berqwp');
170
171 // Redirect after activation
172 wp_redirect($redirect_url);
173
174 // Make sure to exit after the redirect
175 exit;
176 }
177
178 // Deactivate conflicting plugins
179 if (is_admin() && isset($_POST['berqwp_plugins_deactivate']) && wp_verify_nonce($_POST['berqwp_plugins_deactivate'], 'berqwp_plugins_deactivate')) {
180 foreach ($this->conflicting_plugins as $plugin) {
181 // Deactivate each conflicting plugin
182 if (is_plugin_active($plugin)) {
183 deactivate_plugins($plugin);
184 }
185 }
186 header('location: ' . esc_url(get_site_url() . add_query_arg($_GET)));
187 exit;
188 }
189
190 }
191
192 function save_settings()
193 {
194 require_once optifer_PATH . '/admin/save-settings.php';
195 }
196
197 function berqwp_cleanup_completed_and_failed_tasks()
198 {
199
200 if (!get_transient('berqwp_action_cleanup')) {
201 set_transient('berqwp_action_cleanup', true, 60 * 60 * 10);
202
203 global $berq_log;
204 $berq_log->info("* * * * * * * * *");
205 $berq_log->info("* Task Cleanup");
206 $berq_log->info("* * * * * * * * *");
207
208 global $wpdb;
209
210 // Define the hook name
211 $hook_name = 'warmup_cache_by_slug';
212
213 // Count the number of completed and failed actions for the given hook
214 $count = $wpdb->get_var(
215 $wpdb->prepare(
216 "SELECT COUNT(*) FROM {$wpdb->prefix}actionscheduler_actions WHERE hook = %s AND (status = 'complete' OR status = 'failed')",
217 $hook_name
218 )
219 );
220
221 $berq_log->info("Completed + failed task count: $count");
222
223 // Check if the count exceeds 50
224 if ($count > 50) {
225 $delete_count = $count - 50; // Calculate how many rows to delete
226
227 $berq_log->info("Deleting last $delete_count");
228
229 $wpdb->query(
230 $wpdb->prepare(
231 "DELETE FROM {$wpdb->prefix}actionscheduler_actions WHERE hook = %s AND (status = 'complete' OR status = 'failed') ORDER BY scheduled_date_gmt ASC LIMIT %d",
232 $hook_name,
233 $delete_count
234 )
235 );
236 }
237
238 // clear logs, keep the last 1000
239 if ( class_exists( 'ActionScheduler_QueueRunner' ) ) {
240 global $wpdb;
241 $table_name = $wpdb->prefix . 'actionscheduler_logs';
242
243 // Count the total number of logs
244 $total_logs = $wpdb->get_var( "SELECT COUNT(*) FROM $table_name" );
245
246 // Set the limit to keep the latest 1000 logs
247 $limit = max( 0, $total_logs - 1000 );
248
249 // Delete logs beyond the limit
250 $wpdb->query( "DELETE FROM $table_name WHERE log_date_gmt < (SELECT log_date_gmt FROM $table_name ORDER BY log_date_gmt DESC LIMIT 1 OFFSET $limit)" );
251 }
252
253 $berq_log->info("* * * * * * * * * *");
254 $berq_log->info("* Task Cleanup End");
255 $berq_log->info("* * * * * * * * * *");
256
257 }
258 }
259
260 function notices()
261 {
262
263 if (isset($_GET['dismiss_feedback'])) {
264 set_transient( 'bqwp_hide_feedback_notice', true, DAY_IN_SECONDS * 2 );
265 }
266
267 // Check rest api
268 $check_rest = bwp_check_rest_api();
269 if ( $check_rest['status'] == 'error' ) {
270 ?>
271 <div class="notice notice-error">
272 <p><strong>Error:</strong> The WordPress REST API is disabled. BerqWP plugin will not function correctly without the
273 REST API. Please enable the REST API for full functionality.</p>
274 </div>
275 <?php
276 }
277
278 if (isset($_GET['page']) && $_GET['page'] == 'berqwp' && !get_transient( 'bqwp_hide_feedback_notice' ) && $this->is_key_verified) {
279 $notice = '<div class="notice notice-info bwp_feedback">';
280 $notice .= '<p>';
281 $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');
282 $notice .= '<a href="'.get_admin_url().'admin.php?page=berqwp&dismiss_feedback" style="display: table;margin-left: 50px;color: #969595;display: table;">Dismiss</a>';
283 $notice .= '</p>';
284 $notice .= '</div>';
285 echo wp_kses_post($notice);
286 }
287
288 if (berq_is_localhost()) {
289 ?>
290 <div class="notice notice-warning">
291 <?php
292 echo wp_kses_post(__("<p><b>Localhost Detected:</b> BerqWP doesn't operate in a localhost environment.</p>", 'searchpro'));
293 ?>
294 </div>
295 <?php
296 }
297
298
299 $plugins_to_deactivate = '';
300
301 foreach ($this->conflicting_plugins as $plugin) {
302 if (is_plugin_active($plugin)) {
303 $plugins_to_deactivate .= '<li><b>' . basename(dirname($plugin)) . '</b></li>';
304 }
305 }
306
307 if (!empty($plugins_to_deactivate)) {
308 echo "<style>.berqwp-plugin-conflict ul {
309 list-style: disc;
310 margin-left: 20px;
311 }.berqwp-plugin-conflict form {
312 padding: 10px;
313 }
314 .berqwp-plugin-conflict {
315 display: grid;
316 grid-template-columns: auto min-content;
317 }</style>";
318 echo '<div class="notice notice-error berqwp-plugin-conflict">';
319 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'));
320 ?>
321 <form action="<?php echo esc_url(get_site_url() . add_query_arg($_GET)); ?>" method="post">
322
323 <?php
324 $my_nonce = wp_create_nonce('berqwp_plugins_deactivate');
325 echo '<input type="hidden" name="berqwp_plugins_deactivate" value="' . esc_attr($my_nonce) . '" />';
326 ?>
327
328 <input type="submit" class="button-secondary alignright" value="Deactivate Conflicting Plugins">
329 </form>
330 <?php
331 echo wp_kses_post("<ul>$plugins_to_deactivate</ul>");
332 echo '</div>';
333 }
334 }
335
336 function berq_post_types()
337 {
338 // Get post type names
339 $post_type_names = get_post_types(array(
340 'public' => true,
341 'exclude_from_search' => false,
342 ), 'names');
343 unset($post_type_names['attachment']);
344
345 // var_dump($post_type_names);
346
347 // Modify which post types to optimize
348 $post_type_names = apply_filters( 'berqwp_post_types', $post_type_names );
349
350 // Save the names in a WordPress option
351 update_option('berqwp_post_type_names', $post_type_names);
352
353 // Cleanup actions
354 $this->berqwp_cleanup_completed_and_failed_tasks();
355 }
356
357 function plugin_settings_links($links)
358 {
359 $mylinks = array(
360 '<a target="_blank" href="https://berqwp.com/help-center/">' . __('Help Center', 'searchpro') . '</a>',
361 '<a href="' . admin_url('admin.php?page=berqwp') . '">' . __('Settings', 'searchpro') . '</a>',
362 );
363
364 return array_merge($links, $mylinks);
365 }
366
367 function verify_license_key($license_key, $action = 'slm_check')
368 {
369 // Action
370 // slm_activate
371 // slm_deactivate
372 // slm_check
373
374 if (empty($license_key)) {
375 return;
376 }
377
378 global $berq_log;
379 $transient_key = 'berq_lic_response_cache'; // Set a unique key for the transient
380
381 if ($action !== 'slm_check') {
382 delete_transient( $transient_key );
383 }
384
385 // Check if the response is already cached
386 $cached_response = get_transient($transient_key);
387
388
389 if (false === $cached_response) {
390 // If not cached, perform the API request
391
392 $berq_log->info('Checking the license key.');
393
394 $api_params = array(
395 'registered_domain' => $_SERVER['SERVER_NAME'],
396 'slm_action' => $action,
397 'secret_key' => BERQ_SECRET,
398 'license_key' => $license_key,
399 );
400
401 $endpoint_url = esc_url(add_query_arg($api_params, BERQ_SERVER));
402
403 $args = array(
404 'method' => 'POST', // Only POST works for unknown reason
405 'timeout' => 10,
406 'redirection' => 5,
407 'blocking' => true,
408 'headers' => array(
409 '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',
410 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
411 'Accept-Encoding' => 'gzip, deflate, br',
412 'Accept-Language' => 'en-US,en;q=0.9',
413 'Connection' => 'keep-alive',
414 'Referer' => 'https://berqwp.com/', // Adjust based on actual referer
415 ),
416 'cookies' => array(),
417 'sslverify' => false, // Disable SSL verification (for debugging purposes)
418 );
419
420 $response = wp_remote_request(add_query_arg($api_params, BERQ_SERVER), $args);
421
422 // Send query to the license manager server
423 // $response = (array) wp_remote_post($endpoint_url, array('timeout' => 20, 'sslverify' => false));
424
425 // if wp_remote_get didn't work
426 if (is_array($response) && empty($response['body'])) {
427 // Create context options with headers
428 $context_options = [
429 "ssl" => array(
430 "verify_peer" => false,
431 "verify_peer_name" => false,
432 ),
433 'http' => [
434 'method' => 'GET',
435 'header' => [
436 'Content-Type: application/json',
437 ],
438 ],
439 ];
440
441 // Create a stream context
442 $context = stream_context_create($context_options);
443
444 // Make the GET request
445 $response = json_decode(file_get_contents($endpoint_url, false, $context));
446 }
447
448 if (is_array($response)) {
449 $cached_response = json_decode($response['body']);
450
451 if ($action == 'slm_check' && !empty($cached_response)) {
452 // Cache the response for 24 hours
453 set_transient($transient_key, $cached_response, 24 * HOUR_IN_SECONDS);
454 }
455
456 } else {
457 $cached_response = $response;
458
459 if ($action == 'slm_check' && !empty($cached_response) && $cached_response->result == 'success' && $cached_response->status == 'active') {
460 // Cache the response for 24 hours
461 set_transient($transient_key, $cached_response, 24 * HOUR_IN_SECONDS);
462 }
463
464 }
465 } else {
466 $berq_log->info('Delivering license key object from the transient cache.');
467 }
468
469
470 // Return the cached response
471 return $cached_response;
472
473 }
474
475 // Disable emoji functionality
476 function disable_emoji()
477 {
478 // Remove emoji-related actions and filters
479 remove_action('wp_head', 'print_emoji_detection_script', 7);
480 remove_action('admin_print_scripts', 'print_emoji_detection_script');
481 remove_action('wp_print_styles', 'print_emoji_styles');
482 remove_action('admin_print_styles', 'print_emoji_styles');
483 remove_filter('the_content_feed', 'wp_staticize_emoji');
484 remove_filter('comment_text_rss', 'wp_staticize_emoji');
485 remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
486
487 // Remove emoji-related TinyMCE plugins
488 add_filter('tiny_mce_plugins', [$this, 'disable_emoji_tinymce']);
489 }
490
491 // Filter function to disable emoji-related TinyMCE plugins
492 function disable_emoji_tinymce($plugins)
493 {
494 if (is_array($plugins)) {
495 return array_diff($plugins, array('wpemoji'));
496 } else {
497 return array();
498 }
499 }
500
501 function get_media_ids(WP_REST_Request $request)
502 {
503 require_once optifer_PATH . 'api/get_media_ids.php';
504 }
505
506 function optimize_images(WP_REST_Request $request)
507 {
508 require_once optifer_PATH . 'api/optimize_images.php';
509 }
510
511
512 function delete_images(WP_REST_Request $request)
513 {
514 require_once optifer_PATH . 'api/delete_images.php';
515 }
516
517 function clear_cache(WP_REST_Request $request)
518 {
519 require_once optifer_PATH . 'api/clear_cache.php';
520 }
521
522 function warmup_cache(WP_REST_Request $request)
523 {
524 require_once optifer_PATH . 'api/warmup_cache.php';
525 }
526
527 function store_webp(WP_REST_Request $request)
528 {
529 require_once optifer_PATH . 'api/store_webp.php';
530 }
531
532 function store_cache(WP_REST_Request $request)
533 {
534 require_once optifer_PATH . 'api/store_cache.php';
535 }
536
537 function store_javascript_cache(WP_REST_Request $request)
538 {
539 require_once optifer_PATH . 'api/store_javascript_cache.php';
540 }
541
542 function register_menu()
543 {
544 $svg = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
545 <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="#1F71FF"/>
546 </svg>';
547
548 add_menu_page('BerqWP', 'BerqWP', 'manage_options', 'berqwp', [$this, 'admin_page'], 'data:image/svg+xml;base64,' . base64_encode($svg), 10);
549 }
550
551 function admin_page()
552 {
553 if ($this->is_key_verified) {
554 require_once optifer_PATH . 'admin/admin-page.php';
555 } else {
556 require_once optifer_PATH . 'admin/intro-page.php';
557
558 }
559
560 }
561
562
563 }
564
565 global $berqWP;
566 $berqWP = new berqWP();
567 }