PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 2.2.2
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v2.2.2
4.6.1 4.6.0 4.5.5 4.5.4 4.5.3 4.5.2 3.2.20 3.2.21 3.2.22 3.2.3 3.2.5 3.2.6 3.2.7 3.2.9 3.3.0 3.3.1 3.3.2 3.4.0 3.4.1 3.4.2 3.5.0 3.6.0 3.7.0 3.7.1 3.8.0 All 110 releases
wp-optimize / wp-optimize.php

wp-optimize.php in WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance 2.2.2, at wp-optimize.php

1,243 lines 41.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 Plugin Name: WP-Optimize
4 Plugin URI: https://getwpo.com
5 Description: WP-Optimize is WordPress's #1 most installed optimization plugin. With it, you can clean up your database easily and safely, without manual queries.
6 Version: 2.2.2
7 Author: David Anderson, Ruhani Rabin, Team Updraft
8 Author URI: https://updraftplus.com
9 Text Domain: wp-optimize
10 Domain Path: /languages
11 License: GPLv2 or later
12 */
13
14 if (!defined('ABSPATH')) die('No direct access allowed');
15
16 // Check to make sure if WP_Optimize is already call and returns.
17 if (!class_exists('WP_Optimize')) :
18 define('WPO_VERSION', '2.2.2');
19 define('WPO_PLUGIN_URL', plugin_dir_url(__FILE__));
20 define('WPO_PLUGIN_MAIN_PATH', plugin_dir_path(__FILE__));
21 define('WPO_PREMIUM_NOTIFICATION', false);
22
23 class WP_Optimize {
24
25 public $premium_version_link = 'https://getwpo.com/buy/';
26
27 private $template_directories;
28
29 protected static $_instance = null;
30
31 protected static $_optimizer_instance = null;
32
33 protected static $_options_instance = null;
34
35 protected static $_notices_instance = null;
36
37 protected static $_logger_instance = null;
38
39 protected static $_db_info = null;
40
41 public function __construct() {
42
43 // Checks if premium is installed along with plugins needed.
44 add_action('plugins_loaded', array($this, 'plugins_loaded'), 1);
45
46 register_activation_hook(__FILE__, 'wpo_activation_actions');
47 register_deactivation_hook(__FILE__, 'wpo_deactivation_actions');
48 register_uninstall_hook(__FILE__, 'wpo_uninstall_actions');
49
50 add_action('admin_init', array($this, 'admin_init'));
51 add_action('admin_menu', array($this, 'admin_menu'));
52
53 add_filter("plugin_action_links_".plugin_basename(__FILE__), array($this, 'plugin_settings_link'));
54 add_action('wpo_cron_event2', array($this, 'cron_action'));
55 add_filter('cron_schedules', array($this, 'cron_schedules'));
56
57 if (!$this->is_premium()) {
58 add_action('auto_option_settings', array($this->get_options(), 'auto_option_settings'));
59 }
60
61 add_action('wp_ajax_wp_optimize_ajax', array($this, 'wp_optimize_ajax_handler'));
62
63 // Initialize loggers.
64 add_action('plugins_loaded', array($this, 'setup_loggers'));
65
66 // Show update to Premium notice for non-premium multisite.
67 add_action('wpo_additional_options', array($this, 'show_multisite_update_to_premium_notice'));
68
69 include_once(WPO_PLUGIN_MAIN_PATH.'/includes/updraftcentral.php');
70
71 }
72
73 public static function instance() {
74 if (empty(self::$_instance)) {
75 self::$_instance = new self();
76 }
77 return self::$_instance;
78 }
79
80 public static function get_optimizer() {
81 if (empty(self::$_optimizer_instance)) {
82 if (!class_exists('WP_Optimizer')) include_once(WPO_PLUGIN_MAIN_PATH.'/includes/class-wp-optimizer.php');
83 self::$_optimizer_instance = new WP_Optimizer();
84 }
85 return self::$_optimizer_instance;
86 }
87
88 public static function get_options() {
89 if (empty(self::$_options_instance)) {
90 if (!class_exists('WP_Optimize_Options')) include_once(WPO_PLUGIN_MAIN_PATH.'/includes/class-wp-optimize-options.php');
91 self::$_options_instance = new WP_Optimize_Options();
92 }
93 return self::$_options_instance;
94 }
95
96 public static function get_notices() {
97 if (empty(self::$_notices_instance)) {
98 if (!class_exists('WP_Optimize_Notices')) include_once(WPO_PLUGIN_MAIN_PATH.'/includes/wp-optimize-notices.php');
99 self::$_notices_instance = new WP_Optimize_Notices();
100 }
101 return self::$_notices_instance;
102 }
103
104 /**
105 * Returns WP_Optimize_Database_Information instance.
106 *
107 * @return WP_Optimize_Database_Information
108 */
109 public function get_db_info() {
110 if (empty(self::$_db_info)) {
111 if (!class_exists('WP_Optimize_Database_Information')) include_once(WPO_PLUGIN_MAIN_PATH.'/includes/wp-optimize-database-information.php');
112 self::$_db_info = new WP_Optimize_Database_Information();
113 }
114 return self::$_db_info;
115 }
116
117 /**
118 * Return instance of Updraft_Logger
119 *
120 * @return Updraft_Logger
121 */
122 public static function get_logger() {
123 if (empty(self::$_logger_instance)) {
124 include_once(WPO_PLUGIN_MAIN_PATH.'/includes/class-updraft-logger.php');
125 self::$_logger_instance = new Updraft_Logger();
126 }
127 return self::$_logger_instance;
128 }
129
130 public function get_task_manager() {
131 include_once(WPO_PLUGIN_MAIN_PATH.'/includes/class-updraft-tasks-activation.php');
132
133 Updraft_Tasks_Activation::check_updates();
134
135 include_once(WPO_PLUGIN_MAIN_PATH . '/includes/class-updraft-task-meta.php');
136 include_once(WPO_PLUGIN_MAIN_PATH . '/includes/class-updraft-task-options.php');
137 include_once(WPO_PLUGIN_MAIN_PATH . '/includes/class-updraft-task.php');
138
139 // TODO: return here Task Manager instance in future.
140 }
141
142 /**
143 * Indicate whether we have an associated instance of WP-Optimize Premium or not.
144 *
145 * @returns Boolean
146 */
147 public static function is_premium() {
148 if (file_exists(WPO_PLUGIN_MAIN_PATH.'/premium.php') && function_exists('WP_Optimize_Premium')) {
149 $wp_optimize_premium = WP_Optimize_Premium();
150 if (is_a($wp_optimize_premium, 'WP_Optimize_Premium')) return true;
151 }
152 return false;
153 }
154
155 /**
156 * Checks if this is the premium version and loads it. It also ensures that if the free version is installed then it is disabled with an appropriate error message.
157 */
158 public function plugins_loaded() {
159
160 if (is_multisite()) {
161 add_action('network_admin_menu', array($this, 'admin_menu'));
162 }
163
164 // Run Premium loader if it exists
165 if (file_exists(WPO_PLUGIN_MAIN_PATH.'/premium.php') && !class_exists('WP_Optimize_Premium')) {
166 include_once(WPO_PLUGIN_MAIN_PATH.'/premium.php');
167 }
168
169 // load defaults
170 WP_Optimize()->get_options()->set_default_options();
171
172 if ($this->is_active('premium') && false !== ($free_plugin = $this->is_active('free'))) {
173 if (!function_exists('deactivate_plugins')) include_once(ABSPATH.'wp-admin/includes/plugin.php');
174 deactivate_plugins($free_plugin);
175 // Registers the notice letting the user know it cannot be active if premium is active.
176 add_action('admin_notices', array($this, 'show_admin_notice_premium'));
177 return;
178 }
179
180
181 // Loads the language file.
182 load_plugin_textdomain('wp-optimize', false, dirname(plugin_basename(__FILE__)) . '/languages');
183 }
184
185 /**
186 * Check whether one of free/Premium is active (whether it is this instance or not)
187 *
188 * @param String $which - 'free' or 'premium'
189 *
190 * @return String|Boolean - plugin path (if installed) or false if not
191 */
192 private function is_active($which = 'free') {
193 $active_plugins = $this->get_active_plugins();
194 foreach ($active_plugins as $file) {
195 if ('wp-optimize.php' == basename($file)) {
196 $plugin_dir = WP_PLUGIN_DIR.'/'.dirname($file);
197 if (('free' == $which && !file_exists($plugin_dir.'/premium.php')) || ('free' != $which && file_exists($plugin_dir.'/premium.php'))) return $file;
198 }
199 }
200 return false;
201 }
202
203 /**
204 * Gets an array of plugins active on either the current site, or site-wide
205 *
206 * @return Array - a list of plugin paths (relative to the plugin directory)
207 */
208 private function get_active_plugins() {
209
210 // Gets all active plugins on the current site
211 $active_plugins = get_option('active_plugins');
212
213 if (is_multisite()) {
214 $network_active_plugins = get_site_option('active_sitewide_plugins');
215 if (!empty($network_active_plugins)) {
216 $network_active_plugins = array_keys($network_active_plugins);
217 $active_plugins = array_merge($active_plugins, $network_active_plugins);
218 }
219 }
220
221 return $active_plugins;
222 }
223
224 /**
225 * This function checks whether a specific plugin is installed, and returns information about it
226 *
227 * @param string $name Specify "Plugin Name" to return details about it.
228 * @return array Returns an array of details such as if installed, the name of the plugin and if it is active.
229 */
230 public function is_installed($name) {
231
232 // Needed to have the 'get_plugins()' function
233 include_once(ABSPATH.'wp-admin/includes/plugin.php');
234
235 // Gets all plugins available
236 $get_plugins = get_plugins();
237
238 $active_plugins = $this->get_active_plugins();
239
240 $plugin_info['installed'] = false;
241 $plugin_info['active'] = false;
242
243 // Loops around each plugin available.
244 foreach ($get_plugins as $key => $value) {
245 // If the plugin name matches that of the specified name, it will gather details.
246 if ($value['Name'] != $name) continue;
247 $plugin_info['installed'] = true;
248 $plugin_info['name'] = $key;
249 $plugin_info['version'] = $value['Version'];
250 if (in_array($key, $active_plugins)) {
251 $plugin_info['active'] = true;
252 }
253 break;
254 }
255 return $plugin_info;
256 }
257
258 /**
259 * This is a notice to show users that premium is installed
260 */
261 public function show_admin_notice_premium() {
262 echo '<div id="wp-optimize-premium-installed-warning" class="error"><p>'.__('WP-Optimize (Free) has been de-activated, because WP-Optimize Premium is active.', 'wp-optimize').'</p></div>';
263 if (isset($_GET['activate'])) unset($_GET['activate']);
264 }
265
266 /**
267 * Show update to Premium notice for non-premium multisite.
268 */
269 public function show_multisite_update_to_premium_notice() {
270 if (!is_multisite() || self::is_premium()) return;
271
272 echo '<p><a href="'.$this->premium_version_link.'">'.__('New feature: WP-Optimize Premium can now optimize all sites within a multisite install, not just the main one.', 'wp-optimize').'</a></p>';
273 }
274
275 public function admin_init() {
276 $pagenow = $GLOBALS['pagenow'];
277
278 $this->register_template_directories();
279
280 if (('index.php' == $pagenow && current_user_can('update_plugins')) || ('index.php' == $pagenow && defined('WP_OPTIMIZE_FORCE_DASHNOTICE') && WP_OPTIMIZE_FORCE_DASHNOTICE)) {
281 $options = $this->get_options();
282
283 $dismissed_until = $options->get_option('dismiss_dash_notice_until', 0);
284
285 if (file_exists(WPO_PLUGIN_MAIN_PATH . '/index.html')) {
286 $installed = filemtime(WPO_PLUGIN_MAIN_PATH . '/index.html');
287 $installed_for = (time() - $installed);
288 }
289
290 if (($installed && time() > $dismissed_until && $installed_for > (14 * 86400) && !defined('WP_OPTIMIZE_NOADS_B')) || (defined('WP_OPTIMIZE_FORCE_DASHNOTICE') && WP_OPTIMIZE_FORCE_DASHNOTICE)) {
291 add_action('all_admin_notices', array($this, 'show_admin_notice_upgradead'));
292 }
293 }
294 }
295
296 public function show_admin_notice_upgradead() {
297 $this->include_template('notices/thanks-for-using-main-dash.php');
298 }
299
300 public function capability_required() {
301 return apply_filters('wp_optimize_capability_required', 'manage_options');
302 }
303
304 public function wp_optimize_ajax_handler() {
305 $nonce = empty($_POST['nonce']) ? '' : $_POST['nonce'];
306
307 if (!wp_verify_nonce($nonce, 'wp-optimize-ajax-nonce') || empty($_POST['subaction'])) die('Security check');
308
309 $subaction = $_POST['subaction'];
310 $data = isset($_POST['data']) ? $_POST['data'] : null;
311
312 if (!current_user_can($this->capability_required())) die('Security check');
313
314 $wp_optimize = $this;
315 $optimizer = $this->get_optimizer();
316 $options = $this->get_options();
317
318 $results = array();
319
320 // Some commands that are available via AJAX only.
321 if ('dismiss_dash_notice_until' == $subaction) {
322 $options->update_option('dismiss_dash_notice_until', (time() + 366 * 86400));
323 } elseif ('dismiss_page_notice_until' == $subaction) {
324 $options->update_option('dismiss_page_notice_until', (time() + 84 * 86400));
325 } else {
326 // Other commands, available for any remote method.
327 if (!class_exists('WP_Optimize_Commands')) include_once(WPO_PLUGIN_MAIN_PATH . 'includes/class-commands.php');
328
329 $commands = new WP_Optimize_Commands();
330
331 if (!method_exists($commands, $subaction)) {
332 error_log("WP-Optimize: ajax_handler: no such command (".$subaction.")");
333 die('No such command');
334 } else {
335 $results = call_user_func(array($commands, $subaction), $data);
336
337 // clean status box content, it broke json sometimes.
338 if (isset($results['status_box_contents'])) {
339 $results['status_box_contents'] = str_replace(array("\n", "\t"), '', $results['status_box_contents']);
340 }
341
342 if (is_wp_error($results)) {
343 $results = array(
344 'result' => false,
345 'error_code' => $results->get_error_code(),
346 'error_message' => $results->get_error_message(),
347 'error_data' => $results->get_error_data(),
348 );
349 }
350
351 // if nothing was returned for some reason, set as result null.
352 if (empty($results)) {
353 $results = array(
354 'result' => null
355 );
356 }
357 }
358 }
359
360 $result = json_encode($results);
361
362 $json_last_error = json_last_error();
363
364 // if json_encode returned error then return error.
365 if ($json_last_error) {
366 $result = array(
367 'result' => false,
368 'error_code' => $json_last_error,
369 'error_message' => 'json_encode error : '.$json_last_error,
370 'error_data' => '',
371 );
372
373 $result = json_encode($result);
374 }
375
376 echo $result;
377
378 die;
379 }
380
381 /**
382 * Builds the Tabs that should be displayed
383 *
384 * @return String Returns all tabs specified
385 */
386 public function get_tabs() {
387 return apply_filters('wp_optimize_admin_page_tabs', array('optimize' => 'WP-Optimize', 'tables' => __('Table information', 'wp-optimize'), 'settings' => __('Settings', 'wp-optimize'), 'may_also' => __('Premium / Plugin family', 'wp-optimize')));
388 }
389
390 public function wp_optimize_menu() {
391 $capability_required = $this->capability_required();
392
393 if (!current_user_can($capability_required)) {
394 echo "Permission denied.";
395 return;
396 }
397
398 $enqueue_version = (defined('WP_DEBUG') && WP_DEBUG) ? WPO_VERSION.'.'.time() : WPO_VERSION;
399 $min_or_not = (defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) ? '' : '.min';
400
401 wp_enqueue_script('jquery-serialize-json', WPO_PLUGIN_URL.'js/serialize-json/jquery.serializejson'.$min_or_not.'.js', array('jquery'), $enqueue_version);
402
403 wp_register_script('updraft-queue-js', WPO_PLUGIN_URL.'js/queue'.$min_or_not.'.js', array(), $enqueue_version);
404 wp_enqueue_script('wp-optimize-admin-js', WPO_PLUGIN_URL.'js/wpadmin'.$min_or_not.'.js', array('jquery', 'updraft-queue-js'), $enqueue_version);
405 wp_enqueue_style('wp-optimize-admin-css', WPO_PLUGIN_URL.'css/admin'.$min_or_not.'.css', array(), $enqueue_version);
406 // Using tablesorter to help with organising the DB size on Table Information
407 // https://github.com/Mottie/tablesorter
408 wp_enqueue_script('tablesorter-js', WPO_PLUGIN_URL.'js/tablesorter/jquery.tablesorter'.$min_or_not.'.js', array('jquery'), $enqueue_version);
409
410 wp_enqueue_script('tablesorter-widgets-js', WPO_PLUGIN_URL.'js/tablesorter/jquery.tablesorter.widgets'.$min_or_not.'.js', array('jquery'), $enqueue_version);
411
412 wp_enqueue_style('tablesorter-css', WPO_PLUGIN_URL.'css/tablesorter/theme.default.min.css', array(), $enqueue_version);
413
414 $js_variables = $this->wpo_js_translations();
415 $js_variables['loggers_classes_info'] = $this->get_loggers_classes_info();
416
417 wp_localize_script('wp-optimize-admin-js', 'wpoptimize', $js_variables);
418
419 do_action('wpo_premium_scripts_styles', $min_or_not, $enqueue_version);
420
421 do_action('wpo_premium_scripts_styles', $min_or_not, $enqueue_version);
422
423 $options = $this->get_options();
424
425 $tabs = $this->get_tabs();
426
427 $default_tab = apply_filters('wp_optimize_admin_default_tab', 'optimize');
428
429 $active_tab = isset($_GET['tab']) ? substr($_GET['tab'], 12) : $default_tab;
430
431 if (!in_array($active_tab, array_keys($tabs))) $active_tab = $default_tab;
432
433 $nonce_passed = (!empty($_REQUEST['_wpnonce']) && wp_verify_nonce($_REQUEST['_wpnonce'], 'wpo_optimization')) ? true : false;
434
435 if ('optimize' == $active_tab && $nonce_passed && isset($_POST['wp-optimize'])) $options->save_sent_manual_run_optimization_options($_POST, true);
436
437 echo '<div id="wp-optimize-wrap" class="wrap">';
438
439 do_action('wp_optimize_admin_header');
440
441 $this->include_template('admin-page-header.php', false, array('active_tab' => $active_tab, 'tabs' => $tabs));
442
443 $optimize_db = ($nonce_passed && isset($_POST["optimize-db"])) ? true : false;
444
445 $optimizer = $this->get_optimizer();
446
447 foreach ($tabs as $tab_id => $tab_description) {
448 echo '<div class="wp-optimize-nav-tab-contents" id="wp-optimize-nav-tab-contents-'.$tab_id.'" '.(($tab_id == $active_tab) ? '' : 'style="display:none;"').'>';
449
450 do_action('wp_optimize_admin_tab_render_begin', $tab_id, $active_tab);
451
452 switch ($tab_id) {
453 case 'optimize':
454 $optimization_results = (($nonce_passed) ? $optimizer->do_optimizations($_POST) : false);
455
456 if (!empty($optimization_results)) {
457 echo '<div id="message" class="updated"><strong>';
458 foreach ($optimization_results as $optimization_result) {
459 if (!empty($optimization_result->output)) {
460 foreach ($optimization_result->output as $line) {
461 echo $line."<br>";
462 }
463 }
464 }
465 echo '</strong></div>';
466 }
467
468 $this->include_template('optimize-table.php', false, array('optimize_db' => $optimize_db));
469 break;
470
471 case 'tables':
472 $this->include_template('tables.php', false, array('optimize_db' => $optimize_db));
473 break;
474
475 case 'settings':
476 if ('POST' == $_SERVER['REQUEST_METHOD']) {
477 // Nonce check.
478 check_admin_referer('wpo_settings');
479
480 $output = $options->save_settings($_POST);
481
482 if (isset($_POST['wp-optimize-settings'])) {
483 // save settings request sent.
484 $output = $options->save_settings($_POST);
485 }
486
487 $this->wpo_render_output_messages($output);
488 }
489 $this->include_template('admin-settings-general.php');
490 $this->include_template('admin-settings-auto-cleanup.php');
491 $this->include_template('admin-settings-logging.php');
492 $this->include_template('admin-settings-sidebar.php');
493 break;
494
495 case 'may_also':
496 $this->include_template('may-also-like.php');
497 break;
498 }
499
500 do_action('wp_optimize_admin_tab_render_end', $tab_id, $active_tab);
501
502 echo '</div>';
503 }
504
505 echo '</div>';
506
507 }
508
509 /**
510 * Returns array of translations used in javascript code.
511 *
512 * @return array
513 */
514 public function wpo_js_translations() {
515 return apply_filters('wpo_js_translations', array(
516 'automatic_backup_before_optimizations' => __('Automatic backup before optimizations', 'wp-optimize'),
517 'error_unexpected_response' => __('An unexpected response was received.', 'wp-optimize'),
518 'optimization_complete' => __('Optimization complete', 'wp-optimize'),
519 'run_optimizations' => __('Run optimizations', 'wp-optimize'),
520 'cancel' => __('Cancel', 'wp-optimize'),
521 'please_select_settings_file' => __('Please, select settings file.', 'wp-optimize'),
522 'are_you_sure_you_want_to_remove_logging_destination' => __('Are you sure you want to remove this logging destination?', 'wp-optimize'),
523 'fill_all_settings_fields' => __('Before saving, you need to complete the currently incomplete settings (or remove them).', 'wp-optimize'),
524 ));
525 }
526
527 public function wpo_admin_bar() {
528 $wp_admin_bar = $GLOBALS['wp_admin_bar'];
529
530 if (defined('WPOPTIMIZE_ADMINBAR_DISABLE') && WPOPTIMIZE_ADMINBAR_DISABLE) return;
531
532 // Show menu item in top bar only for super admins.
533 if (is_multisite() & !is_super_admin(get_current_user_id())) return;
534
535 // Add a link called at the top admin bar.
536 $args = array(
537 'id' => 'wp-optimize-node',
538 'title' => apply_filters('wpoptimize_admin_node_title', 'WP-Optimize')
539 );
540 $wp_admin_bar->add_node($args);
541
542 $tabs = $this->get_tabs();
543
544 foreach ($tabs as $tab_id => $tab_title) {
545 $menu_page_url = menu_page_url('WP-Optimize', false). '&tab=wp_optimize_'.$tab_id;
546
547 if (is_multisite()) {
548 $menu_page_url = network_admin_url('admin.php?page=WP-Optimize&tab=wp_optimize_'.$tab_id);
549 }
550
551 $args = array(
552 'id' => 'wpoptimize_admin_node_'.$tab_id,
553 'title' => ('optimize' == $tab_id) ? __('Optimize', 'wp-optimize') : $tab_title,
554 'parent' => 'wp-optimize-node',
555 'href' => $menu_page_url
556 );
557 $wp_admin_bar->add_node($args);
558 }
559
560 }
561
562 /**
563 * Add settings link on plugin page
564 *
565 * @param string $links Passing through the URL to be used within the HREF.
566 * @return string Returns the Links.
567 */
568 public function plugin_settings_link($links) {
569
570 $admin_page_url = $this->get_options()->admin_page_url();
571
572 $settings_link = '<a href="' . esc_url($admin_page_url) . '">' . __('Settings', 'wp-optimize') . '</a>';
573 array_unshift($links, $settings_link);
574
575 $optimize_link = '<a href="' . esc_url($admin_page_url) . '">' . __('Optimizer', 'wp-optimize') . '</a>';
576 array_unshift($links, $optimize_link);
577 return $links;
578 }
579
580 /**
581 * Schedules cron event based on selected schedule type
582 *
583 * @return void
584 */
585 public function cron_activate() {
586 $gmtoffset = (int) (3600 * ((double) get_option('gmt_offset')));
587
588 $options = $this->get_options();
589
590 if ($options->get_option('schedule') === false) {
591 $options->set_default_options();
592 } else {
593 if ('true' == $options->get_option('schedule')) {
594 if (!wp_next_scheduled('wpo_cron_event2')) {
595 $schedule_type = $options->get_option('schedule-type', 'wpo_weekly');
596
597 $this_time = (86400 * 7);
598
599 switch ($schedule_type) {
600 case "wpo_daily":
601 $this_time = 86400;
602 break;
603
604 case "wpo_weekly":
605 $this_time = (86400 * 7);
606 break;
607
608 case "wpo_otherweekly":
609 $this_time = (86400 * 14);
610 break;
611
612 case "wpo_monthly":
613 $this_time = (86400 * 30);
614 break;
615 }
616
617 add_action('wpo_cron_event2', array($this, 'cron_action'));
618 wp_schedule_event((current_time("timestamp", 0) + $this_time), $schedule_type, 'wpo_cron_event2');
619 WP_Optimize()->log('running wp_schedule_event()');
620 }
621 }
622 }
623 }
624
625 /**
626 * Clears all cron events
627 *
628 * @return void
629 */
630 public function wpo_cron_deactivate() {
631 wp_clear_scheduled_hook('wpo_cron_event2');
632 }
633
634 /**
635 * Scheduler public functions to update schedulers
636 *
637 * @param array $schedules An array of schedules being passed.
638 * @return array An array of schedules being returned.
639 */
640 public function cron_schedules($schedules) {
641 $schedules['wpo_daily'] = array('interval' => 86400, 'display' => 'Once Daily');
642 $schedules['wpo_weekly'] = array('interval' => 86400 * 7, 'display' => 'Once Weekly');
643 $schedules['wpo_fortnightly'] = array('interval' => 86400 * 14, 'display' => 'Once Every Fortnight');
644 $schedules['wpo_monthly'] = array('interval' => 86400 * 30, 'display' => 'Once Every Month');
645 return $schedules;
646 }
647
648 /**
649 * Returns count of overdue cron jobs.
650 *
651 * @return integer
652 */
653 public function howmany_overdue_crons() {
654 $how_many_overdue = 0;
655 if (function_exists('_get_cron_array') || (is_file(ABSPATH.WPINC.'/cron.php') && include_once(ABSPATH.WPINC.'/cron.php') && function_exists('_get_cron_array'))) {
656 $crons = _get_cron_array();
657 if (is_array($crons)) {
658 $timenow = time();
659 foreach ($crons as $jt => $job) {
660 if ($jt < $timenow) {
661 $how_many_overdue++;
662 }
663 }
664 }
665 }
666 return $how_many_overdue;
667 }
668
669 /**
670 * Returns warning about overdue crons.
671 *
672 * @param int $howmany count of overdue crons
673 * @return string
674 */
675 public function show_admin_warning_overdue_crons($howmany) {
676 $ret = '<div class="updated"><p>';
677 // todo: update link to wp-optimize
678 $ret .= '<strong>'.__('Warning', 'wp-optimize').':</strong> '.sprintf(__('WordPress has a number (%d) of scheduled tasks which are overdue. Unless this is a development site, this probably means that the scheduler in your WordPress install is not working.', 'wp-optimize'), $howmany).' <a href="'.apply_filters('wpoptimize_com_link', "https://updraftplus.com/faqs/scheduler-wordpress-installation-working/").'">'.__('Read this page for a guide to possible causes and how to fix it.', 'wp-optimize').'</a>';
679 $ret .= '</p></div>';
680 return $ret;
681 }
682
683 public function admin_menu() {
684
685 $capability_required = $this->capability_required();
686
687 if (!current_user_can($capability_required)) return;
688
689 $icon_svg = 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgdmlld0JveD0iMCAwIDE2IDE2IgogICB2ZXJzaW9uPSIxLjEiCiAgIGlkPSJzdmc0MzE2IgogICBoZWlnaHQ9IjE2IgogICB3aWR0aD0iMTYiPgogIDxkZWZzCiAgICAgaWQ9ImRlZnM0MzE4IiAvPgogIDxtZXRhZGF0YQogICAgIGlkPSJtZXRhZGF0YTQzMjEiPgogICAgPHJkZjpSREY+CiAgICAgIDxjYzpXb3JrCiAgICAgICAgIHJkZjphYm91dD0iIj4KICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4KICAgICAgICA8ZGM6dHlwZQogICAgICAgICAgIHJkZjpyZXNvdXJjZT0iaHR0cDovL3B1cmwub3JnL2RjL2RjbWl0eXBlL1N0aWxsSW1hZ2UiIC8+CiAgICAgICAgPGRjOnRpdGxlPjwvZGM6dGl0bGU+CiAgICAgIDwvY2M6V29yaz4KICAgIDwvcmRmOlJERj4KICA8L21ldGFkYXRhPgogIDxnCiAgICAgaWQ9ImxheWVyMSI+CiAgICA8cGF0aAogICAgICAgc3R5bGU9ImZpbGw6I2EwYTVhYTtmaWxsLW9wYWNpdHk6MSIKICAgICAgIGlkPSJwYXRoNTciCiAgICAgICBkPSJtIDEwLjc2ODgwOSw2Ljc2MTYwNTEgMCwwIGMgLTAuMDE2ODgsLTAuMDE2ODc4IC0wLjAyNTMxLC0wLjA0MjE4MSAtMC4wMzM3NCwtMC4wNjc0OTkgLTAuMDA4NCwtMC4wMDgzOSAtMC4wMDg0LC0wLjAxNjg3OCAtMC4wMTY4OCwtMC4wMzM3NDMgQyA5Ljk5MjYxMTIsNS4xOTIzMzY2IDguMjIwODU1Nyw0LjU4NDg3ODEgNi43NDQzOTEyLDUuMjkzNTc5NyA1LjY3MjkwMDUsNS44MDgyMzI4IDUuMDU3MDA0Myw2Ljg4ODE2MTMgNS4wNjU0NDIsOC4wMDE4MzY1IDQuNDU3OTgyMiw3LjMxMDAwNzYgMy42OTg2NTg0LDYuNzk1MzU0NSAyLjg1NDk2NDIsNi40OTE2MjUzIDMuMjY4Mzc0Myw1LjA2NTc4MzEgNC4yNTU0OTYsMy44MTcxMTY2IDUuNjg5Nzc0NiwzLjEyNTI4NzggOC4zNjQyODMyLDEuODM0NDM2OCAxMS41NzAzMTksMi45Mzk2NzQ0IDEyLjg4NjQ4MSw1LjU4ODg3MjYgMTMuNDUxNzU1LDYuNzI3ODU5NiAxNC42NDk4MDEsNy4zNTIxOTIxIDE1Ljg0Nzg0Niw3LjIzNDA3NSAxNS43NjM0ODIsNi4zMzk3NiAxNS41MTg4MDUsNS40MzcwMDg2IDE1LjEwNTM5Niw0LjU3NjQ0MDQgMTMuMjE1NTIxLDAuNjg3MDEzNCA4LjUzMzAyMjYsLTAuOTQxMzE2MjcgNC42NDM1OTQzLDAuOTQwMTIxNzkgMi4zMjM0MzcsMi4wNjIyMzM0IDAuODA0Nzg4MTQsNC4xNzk5MDQ0IDAuMzU3NjMxMzIsNi41MzM4MDk4IDIuNDE2MjQzOCw2LjQyNDEyOSA0LjQzMjY3MTcsNy41MDQwNTc0IDUuNDM2NjY2Miw5LjQzNjExNjcgbCAwLjAwODM5LDAgYyAwLjc1OTMxOTIsMS4zNzUyMjAzIDIuNDcyMDE3OCwxLjk0MDQ5NTMgMy45MDYyOTYsMS4yNDg2NjczIDEuMDQ2MTc5OCwtMC41MDYyMTggMS42NTM2NDA4LC0xLjUzNTUyMzggMS42Nzg5NTA4LC0yLjYxNTQ1MTIgMC41ODIxNDgsMC43MDg3MDE4IDEuMzMzMDM1LDEuMjQ4NjY2OCAyLjE1OTg1NiwxLjU3NzcwNjQgLTAuNDM4NzIxLDEuMzU4MzQ3OCAtMS40MDA1MzMsMi41NDc5NTQ4IC0yLjc5MjYyNywzLjIxNDQ3ODggLTIuNTkwMTM4NywxLjI0ODY1OCAtNS42NzgwNTc0LDAuMjUzMTA0IC03LjA2MTcxNTEsLTIuMjI3MzU3IGwgMCwwIEMgMi43NjIxMDQ4LDkuNDUyOTg5NCAxLjUxMzQzODMsOC44MjAyMTkxIDAuMjgxNjQ1OTIsOC45NzIwODQ0IDAuMzgyODg3NjUsOS43OTg5MDQ2IDAuNjE5MTIzMzEsMTAuNjE3Mjg3IDAuOTk4Nzg1MiwxMS40MDE5MjIgYyAxLjg4MTQzNjgsMy44OTc4NjQgNi41NjM5MzcsNS41MjYxOTggMTAuNDYxODAwOCwzLjY0NDc2IDIuMjQ0MjI2LC0xLjA4ODM2OSAzLjczNzU2MiwtMy4xMDQ3OTYgNC4yMzUzNDIsLTUuMzc0MzMyMyAtMS45OTk1NTQsMC4wNDIxODEgLTMuOTQ4NDg2LC0xLjAyOTMwNjMgLTQuOTI3MTcsLTIuOTEwNzQzMyB6IgogICAgICAgY2xhc3M9InN0MTciIC8+CiAgPC9nPgo8L3N2Zz4K';
690
691 // Removes the admin menu items on the left WP bar.
692 if (!is_multisite() || (is_multisite() && is_network_admin())) {
693 add_menu_page("WP-Optimize", "WP-Optimize", $capability_required, "WP-Optimize", array($this, "wp_optimize_menu"), $icon_svg);
694 }
695
696 $options = $this->get_options();
697
698 if ($options->get_option('enable-admin-menu', 'false') == 'true') {
699 add_action('wp_before_admin_bar_render', array($this, 'wpo_admin_bar'));
700 }
701
702 }
703
704 private function wp_normalize_path($path) {
705 // Wp_normalize_path is not present before WP 3.9.
706 if (function_exists('wp_normalize_path')) return wp_normalize_path($path);
707 // Taken from WP 4.6.
708 $path = str_replace('\\', '/', $path);
709 $path = preg_replace('|(?<=.)/+|', '/', $path);
710 if (':' === substr($path, 1, 1)) {
711 $path = ucfirst($path);
712 }
713 return $path;
714 }
715
716 public function get_templates_dir() {
717 return apply_filters('wp_optimize_templates_dir', $this->wp_normalize_path(WPO_PLUGIN_MAIN_PATH.'/templates'));
718 }
719
720 public function get_templates_url() {
721 return apply_filters('wp_optimize_templates_url', WPO_PLUGIN_URL.'/templates');
722 }
723
724 public function include_template($path, $return_instead_of_echo = false, $extract_these = array()) {
725 if ($return_instead_of_echo) ob_start();
726
727 if (preg_match('#^([^/]+)/(.*)$#', $path, $matches)) {
728 $prefix = $matches[1];
729 $suffix = $matches[2];
730 if (isset($this->template_directories[$prefix])) {
731 $template_file = $this->template_directories[$prefix].'/'.$suffix;
732 }
733 }
734
735 if (!isset($template_file)) {
736 $template_file = WPO_PLUGIN_MAIN_PATH.'/templates/'.$path;
737 }
738
739 $template_file = apply_filters('wp_optimize_template', $template_file, $path);
740
741 do_action('wp_optimize_before_template', $path, $template_file, $return_instead_of_echo, $extract_these);
742
743 if (!file_exists($template_file)) {
744 error_log("WP Optimize: template not found: ".$template_file);
745 echo __('Error:', 'wp-optimize').' '.__('template not found', 'wp-optimize')." (".$path.")";
746 } else {
747 extract($extract_these);
748 $wpdb = $GLOBALS['wpdb'];
749 $wp_optimize = $this;
750 $optimizer = $this->get_optimizer();
751 $options = $this->get_options();
752 $wp_optimize_notices = $this->get_notices();
753 include $template_file;
754 }
755
756 do_action('wp_optimize_after_template', $path, $template_file, $return_instead_of_echo, $extract_these);
757
758 if ($return_instead_of_echo) return ob_get_clean();
759 }
760
761 /**
762 * Build a list of template directories (stored in self::$template_directories)
763 */
764 private function register_template_directories() {
765
766 $template_directories = array();
767
768 $templates_dir = $this->get_templates_dir();
769
770 if ($dh = opendir($templates_dir)) {
771 while (($file = readdir($dh)) !== false) {
772 if ('.' == $file || '..' == $file) continue;
773 if (is_dir($templates_dir.'/'.$file)) {
774 $template_directories[$file] = $templates_dir.'/'.$file;
775 }
776 }
777 closedir($dh);
778 }
779
780 // Optimal hook for most extensions to hook into.
781 $this->template_directories = apply_filters('wp_optimize_template_directories', $template_directories);
782
783 }
784
785 /**
786 * Not currently used; needs looking at.
787 * N.B. The description does not match the actual function
788 *
789 * @param integer $date Date of when the optimization was executed.
790 */
791 public function send_email($date) {
792 ob_start();
793 // This need to work on - currently not using the parameter values.
794 $my_time = current_time("timestamp", 0);
795 $my_date = gmdate(get_option('date_format') . ' ' . get_option('time_format'), $my_time);
796 $sendto = (!$options->get_option('email-address') ? get_bloginfo('admin_email') : $options->get_option('email-address'));
797 $subject = get_bloginfo('name').": ".__("Automatic Operation Completed", "wp-optimize")." ".$my_date;
798
799 $msg = __("Scheduled optimization was executed at", "wp-optimize")." ".$my_date."\r\n"."\r\n";
800 $msg .= __("You can safely delete this email.", "wp-optimize")."\r\n";
801 $msg .= "\r\n";
802 $msg .= __("Regards,", "wp-optimize")."\r\n";
803 $msg .= __("WP-Optimize Plugin", "wp-optimize");
804 ob_end_clean();
805 }
806
807 /**
808 * Message to debug
809 *
810 * @param string $message Message to insert into the log.
811 * @param array $context Context of the log.
812 */
813 public function log($message, $context = array()) {
814 $this->get_logger()->debug($message, $context);
815 }
816
817 /**
818 * Format Bytes Into KB/MB
819 *
820 * @param mixed $bytes Number of bytes to be converted.
821 * @return integer return the correct format size.
822 */
823 public function format_size($bytes) {
824 if ($bytes > 1073741824) {
825 return number_format_i18n(($bytes / 1073741824), 2) . ' '.__('GB', 'wp-optimize');
826 } elseif ($bytes > 1048576) {
827 return number_format_i18n(($bytes / 1048576), 1) . ' '.__('MB', 'wp-optimize');
828 } elseif ($bytes > 1024) {
829 return number_format_i18n(($bytes / 1024), 1) . ' '.__('KB', 'wp-optimize');
830 } else {
831 return number_format_i18n($bytes, 0) . ' '.__('bytes', 'wp-optimize');
832 }
833 }
834
835 /**
836 * Executed this function on cron event.
837 */
838 public function cron_action() {
839
840 $optimizer = $this->get_optimizer();
841 $options = $this->get_options();
842
843 $this->log('WPO: Starting cron_action()');
844
845 if ('true' == $options->get_option('schedule')) {
846 $this_options = $options->get_option('auto');
847
848 $optimizations = $optimizer->get_optimizations();
849
850 // Currently the output of the optimizations is not saved/used/logged.
851 $results = $optimizer->do_optimizations($this_options, 'auto');
852 }
853
854 }
855
856 /**
857 * This will customize a URL with a correct Affiliate link
858 * This function can be update to suit any URL as longs as the URL is passed
859 *
860 * @param String $url - URL to be check to see if it an updraftplus match.
861 * @param String $text - Text to be entered within the href a tags.
862 * @param String $html - Any specific HTML to be added.
863 * @param String $class - Specify a class for the href (including the attribute label)
864 * @param Boolean $return_instead_of_echo - if set, then the result will be returned, not echo-ed.
865 *
866 * @return String|void
867 */
868 public function wp_optimize_url($url, $text, $html = '', $class = '', $return_instead_of_echo = false) {
869 // Check if the URL is UpdraftPlus.
870 if (false !== strpos($url, '//updraftplus.com')) {
871 // Set URL with Affiliate ID.
872 $url = $url.'?afref='.$this->get_notices()->get_affiliate_id();
873
874 // Apply filters.
875 $url = apply_filters('wpoptimize_updraftplus_com_link', $url);
876 }
877 // Return URL - check if there is HTML such as images.
878 if ('' != $html) {
879 $result = '<a '.$class.' href="'.esc_attr($url).'">'.$html.'</a>';
880 } else {
881 $result = '<a '.$class.' href="'.esc_attr($url).'">'.htmlspecialchars($text).'</a>';
882 }
883 if ($return_instead_of_echo) return $result;
884 echo $result;
885 }
886
887 /**
888 * Setup WPO logger(s)
889 */
890 public function setup_loggers() {
891
892 $logger = $this->get_logger();
893 $loggers = $this->wpo_loggers();
894
895 if (!empty($loggers)) {
896 foreach ($loggers as $_logger) {
897 $logger->add_logger($_logger);
898 }
899 }
900
901 add_action('wp_optimize_after_optimizations', array($this, 'after_optimizations_logger_action'));
902 }
903
904 /**
905 * Run logger actions after all optimizations done
906 */
907 public function after_optimizations_logger_action() {
908 $loggers = $this->get_logger()->get_loggers();
909 if (!empty($loggers)) {
910 foreach ($loggers as $logger) {
911 if (is_a($logger, 'Updraft_Email_Logger')) {
912 $logger->flush_log();
913 }
914 }
915 }
916 }
917
918 /**
919 * Returns list of WPO loggers instances
920 * Apply filter wp_optimize_loggers
921 *
922 * @return array
923 */
924 public function wpo_loggers() {
925
926 $loggers = array();
927 $loggers_classes_by_id = array();
928 $options_keys = array();
929
930 $loggers_classes = $this->get_loggers_classes();
931
932 foreach ($loggers_classes as $logger_class => $source) {
933 $loggers_classes_by_id[strtolower($logger_class)] = $logger_class;
934 }
935
936 $saved_loggers = $this->get_options()->get_option('logging');
937 $logger_additional_options = $this->get_options()->get_option('logging-additional');
938
939 // create loggers classes instances.
940 if (!empty($saved_loggers)) {
941 // check for previous version options format.
942 $keys = array_keys($saved_loggers);
943
944 // if options stored in old format then reformat it.
945 if (false == is_numeric($keys[0])) {
946 $_saved_loggers = array();
947 foreach ($saved_loggers as $logger_id => $enabled) {
948 if ($enabled) {
949 $_saved_loggers[] = $logger_id;
950 }
951 }
952
953 // fill email with admin.
954 if (array_key_exists('updraft_email_logger', $saved_loggers) && $saved_loggers['updraft_email_logger']) {
955 $logger_additional_options['updraft_email_logger'] = array(
956 get_option('admin_email')
957 );
958 }
959
960 $saved_loggers = $_saved_loggers;
961 }
962
963 foreach ($saved_loggers as $i => $logger_id) {
964
965 if (!array_key_exists($logger_id, $loggers_classes_by_id)) continue;
966
967 $logger_class = $loggers_classes_by_id[$logger_id];
968
969 $logger = new $logger_class();
970
971 $logger_options = $logger->get_options_list();
972
973 if (!empty($logger_options)) {
974 foreach (array_keys($logger_options) as $option_name) {
975 if (array_key_exists($option_name, $options_keys)) {
976 $options_keys[$option_name]++;
977 } else {
978 $options_keys[$option_name] = 0;
979 }
980
981 $option_value = isset($logger_additional_options[$option_name][$options_keys[$option_name]]) ? $logger_additional_options[$option_name][$options_keys[$option_name]] : '';
982
983 // if options in old format then get correct value.
984 if ('' === $option_value && array_key_exists($logger_id, $logger_additional_options)) {
985 $option_value = array_shift($logger_additional_options[$logger_id]);
986 }
987
988 $logger->set_option($option_name, $option_value);
989 }
990 }
991
992 // check if logger is active.
993 $active = (!is_array($logger_additional_options) || (array_key_exists('active', $logger_additional_options) && empty($logger_additional_options['active'][$i]))) ? false : true;
994
995 if ($active) {
996 $logger->enable();
997 } else {
998 $logger->disable();
999 }
1000
1001 $loggers[] = $logger;
1002 }
1003 }
1004
1005 $loggers = apply_filters('wp_optimize_loggers', $loggers);
1006
1007 return $loggers;
1008 }
1009
1010 /**
1011 * Returns associative array with logger class name in a key and path to class file in a value.
1012 *
1013 * @return array
1014 */
1015 public function get_loggers_classes() {
1016 $loggers_classes = array(
1017 'Updraft_PHP_Logger' => WPO_PLUGIN_MAIN_PATH . 'includes/class-updraft-php-logger.php',
1018 'Updraft_Email_Logger' => WPO_PLUGIN_MAIN_PATH . 'includes/class-updraft-email-logger.php',
1019 'Updraft_Ring_Logger' => WPO_PLUGIN_MAIN_PATH . 'includes/class-updraft-ring-logger.php'
1020 );
1021
1022 $loggers_classes = apply_filters('wp_optimize_loggers_classes', $loggers_classes);
1023
1024 if (!empty($loggers_classes)) {
1025 foreach ($loggers_classes as $logger_class => $logger_file) {
1026 if (!class_exists($logger_class)) {
1027 if (is_file($logger_file)) {
1028 include_once($logger_file);
1029 }
1030 }
1031 }
1032 }
1033
1034 return $loggers_classes;
1035 }
1036
1037 /**
1038 * Returns information about all loggers classes.
1039 *
1040 * @return array
1041 */
1042 public function get_loggers_classes_info() {
1043 $loggers_classes = $this->get_loggers_classes();
1044
1045 $loggers_classes_info = array();
1046
1047 if (!empty($loggers_classes)) {
1048 foreach (array_keys($loggers_classes) as $logger_class_name) {
1049
1050 if (!class_exists($logger_class_name)) continue;
1051
1052 $logger_id = strtolower($logger_class_name);
1053 $logger_class = new $logger_class_name();
1054
1055 $loggers_classes_info[$logger_id] = array(
1056 'description' => $logger_class->get_description(),
1057 'allow_multiple' => $logger_class->is_allow_multiple(),
1058 'options' => $logger_class->get_options_list()
1059 );
1060 }
1061 }
1062
1063 return $loggers_classes_info;
1064 }
1065
1066 /**
1067 * Returns true if optimization works in multisite mode
1068 *
1069 * @return boolean
1070 */
1071 public function is_multisite_mode() {
1072 return (is_multisite() && WP_Optimize()->is_premium());
1073 }
1074
1075 /**
1076 * Returns list of all sites in multisite
1077 *
1078 * @return array
1079 */
1080 public function get_sites() {
1081 $sites = array();
1082 // check if function get_sites exists (since 4.6.0) else use wp_get_sites.
1083 if (function_exists('get_sites')) {
1084 $sites = get_sites(array('network_id' => null));
1085 } elseif (function_exists('wp_get_sites')) {
1086 // @codingStandardsIgnoreLine
1087 $sites = wp_get_sites(array('network_id' => null));
1088 }
1089 return $sites;
1090 }
1091
1092 /**
1093 * Output success/error messages from $output array.
1094 *
1095 * @param array $output ['messages' => success messages, 'errors' => error messages]
1096 */
1097 private function wpo_render_output_messages($output) {
1098 foreach ($output['messages'] as $item) {
1099 echo '<div class="updated fade"><strong>'.$item.'</strong></div>';
1100 }
1101
1102 foreach ($output['errors'] as $item) {
1103 echo '<div class="error fade"><strong>'.$item.'</strong></div>';
1104 }
1105 }
1106
1107 /**
1108 * Returns script memory limit in megabytes.
1109 *
1110 * @param bool $memory_limit
1111 * @return int
1112 */
1113 public function get_memory_limit($memory_limit = false) {
1114 // Returns in megabytes
1115 if (false == $memory_limit) $memory_limit = ini_get('memory_limit');
1116 $memory_limit = rtrim($memory_limit);
1117
1118 return $this->return_bytes($memory_limit);
1119 }
1120
1121 /**
1122 * Returns free memory in bytes.
1123 *
1124 * @return int
1125 */
1126 public function get_free_memory() {
1127 return $this->get_memory_limit() - memory_get_usage();
1128 }
1129
1130 /**
1131 * Checks PHP memory_limit and WP_MAX_MEMORY_LIMIT values and return minimal.
1132 *
1133 * @return int memory limit in bytes.
1134 */
1135 public function get_script_memory_limit() {
1136 $memory_limit = $this->get_memory_limit();
1137
1138 if (defined('WP_MAX_MEMORY_LIMIT')) {
1139 $wp_memory_limit = $this->get_memory_limit(WP_MAX_MEMORY_LIMIT);
1140
1141 if ($wp_memory_limit > 0 && $wp_memory_limit < $memory_limit) {
1142 $memory_limit = $wp_memory_limit;
1143 }
1144 }
1145
1146 return $memory_limit;
1147 }
1148
1149 /**
1150 * Returns max packet size for database.
1151 *
1152 * @return int|string
1153 */
1154 public function get_max_packet_size() {
1155 global $wpdb;
1156 static $mp = 0;
1157
1158 if ($mp > 0) return $mp;
1159
1160 $mp = (int) $wpdb->get_var("SELECT @@session.max_allowed_packet");
1161 // Default to 1MB
1162 $mp = (is_numeric($mp) && $mp > 0) ? $mp : 1048576;
1163 // 32MB
1164 if ($mp < 33554432) {
1165 $save = $wpdb->show_errors(false);
1166 // @codingStandardsIgnoreLine
1167 $req = @$wpdb->query("SET GLOBAL max_allowed_packet=33554432");
1168 $wpdb->show_errors($save);
1169
1170 $mp = (int) $wpdb->get_var("SELECT @@session.max_allowed_packet");
1171 // Default to 1MB
1172 $mp = (is_numeric($mp) && $mp > 0) ? $mp : 1048576;
1173 }
1174
1175 return $mp;
1176 }
1177
1178 /**
1179 * Converts shorthand memory notation value to bytes.
1180 * From http://php.net/manual/en/function.ini-get.php
1181 *
1182 * @param string $val shorthand memory notation value.
1183 */
1184 public function return_bytes($val) {
1185 $val = trim($val);
1186 $last = strtolower($val[strlen($val)-1]);
1187 $val = (int) $val;
1188 switch ($last) {
1189 case 'g':
1190 $val *= 1024;
1191 // no break
1192 case 'm':
1193 $val *= 1024;
1194 // no break
1195 case 'k':
1196 $val *= 1024;
1197 }
1198
1199 return $val;
1200 }
1201 }
1202
1203 /**
1204 * Plugin activation actions.
1205 */
1206 function wpo_activation_actions() {
1207 // If plugin activated by not a Network Administrator then deactivate plugin and show message.
1208 if (is_multisite() && !is_network_admin()) {
1209 deactivate_plugins(plugin_basename(__FILE__));
1210 wp_die(__('Only Network Administrator can activate WP-Optimize plugin.', 'wp-optimize').
1211 ' <a href="'.admin_url('plugins.php').'">'.__('go back', 'wp-optimize').'</a>');
1212 }
1213
1214 WP_Optimize()->get_options()->set_default_options();
1215 }
1216
1217 /**
1218 * Plugin deactivation actions.
1219 */
1220 function wpo_deactivation_actions() {
1221 WP_Optimize()->wpo_cron_deactivate();
1222 }
1223
1224 function wpo_cron_deactivate() {
1225 WP_Optimize()->log('running wpo_cron_deactivate()');
1226 wp_clear_scheduled_hook('wpo_cron_event2');
1227 }
1228
1229 /**
1230 * Plugin uninstall actions.
1231 */
1232 function wpo_uninstall_actions() {
1233 WP_Optimize()->get_options()->delete_all_options();
1234 }
1235
1236 function WP_Optimize() {
1237 return WP_Optimize::instance();
1238 }
1239
1240 endif;
1241
1242 $GLOBALS['wp_optimize'] = WP_Optimize();
1243