PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 2.2.0
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v2.2.0
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.0, at wp-optimize.php

1,161 lines 39.7 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.0
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.0');
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';
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 wp_localize_script('wp-optimize-admin-js', 'wpoptimize', $this->wpo_js_translations());
415
416 do_action('wpo_premium_scripts_styles', $min_or_not, $enqueue_version);
417
418 $options = $this->get_options();
419
420 $tabs = $this->get_tabs();
421
422 $default_tab = apply_filters('wp_optimize_admin_default_tab', 'optimize');
423
424 $active_tab = isset($_GET['tab']) ? substr($_GET['tab'], 12) : $default_tab;
425
426 if (!in_array($active_tab, array_keys($tabs))) $active_tab = $default_tab;
427
428 $nonce_passed = (!empty($_REQUEST['_wpnonce']) && wp_verify_nonce($_REQUEST['_wpnonce'], 'wpo_optimization')) ? true : false;
429
430 if ('optimize' == $active_tab && $nonce_passed && isset($_POST['wp-optimize'])) $options->save_sent_manual_run_optimization_options($_POST, true);
431
432 echo '<div id="wp-optimize-wrap" class="wrap">';
433
434 do_action('wp_optimize_admin_header');
435
436 $this->include_template('admin-page-header.php', false, array('active_tab' => $active_tab, 'tabs' => $tabs));
437
438 $optimize_db = ($nonce_passed && isset($_POST["optimize-db"])) ? true : false;
439
440 $optimizer = $this->get_optimizer();
441
442 foreach ($tabs as $tab_id => $tab_description) {
443 echo '<div class="wp-optimize-nav-tab-contents" id="wp-optimize-nav-tab-contents-'.$tab_id.'" '.(($tab_id == $active_tab) ? '' : 'style="display:none;"').'>';
444
445 do_action('wp_optimize_admin_tab_render_begin', $tab_id, $active_tab);
446
447 switch ($tab_id) {
448 case 'optimize':
449 $optimization_results = (($nonce_passed) ? $optimizer->do_optimizations($_POST) : false);
450
451 if (!empty($optimization_results)) {
452 echo '<div id="message" class="updated"><strong>';
453 foreach ($optimization_results as $optimization_result) {
454 if (!empty($optimization_result->output)) {
455 foreach ($optimization_result->output as $line) {
456 echo $line."<br>";
457 }
458 }
459 }
460 echo '</strong></div>';
461 }
462
463 $this->include_template('optimize-table.php', false, array('optimize_db' => $optimize_db));
464 break;
465
466 case 'tables':
467 $this->include_template('tables.php', false, array('optimize_db' => $optimize_db));
468 break;
469
470 case 'settings':
471 if ('POST' == $_SERVER['REQUEST_METHOD']) {
472 // Nonce check.
473 check_admin_referer('wpo_settings');
474
475 $output = $options->save_settings($_POST);
476
477 if (isset($_POST['wp-optimize-settings'])) {
478 // save settings request sent.
479 $output = $options->save_settings($_POST);
480 }
481
482 $this->wpo_render_output_messages($output);
483 }
484 $this->include_template('admin-settings-general.php');
485 $this->include_template('admin-settings-auto-cleanup.php');
486 $this->include_template('admin-settings-logging.php');
487 $this->include_template('admin-settings-sidebar.php');
488 break;
489
490 case 'may_also':
491 $this->include_template('may-also-like.php');
492 break;
493 }
494
495 do_action('wp_optimize_admin_tab_render_end', $tab_id, $active_tab);
496
497 echo '</div>';
498 }
499
500 echo '</div>';
501
502 }
503
504 /**
505 * Returns array of translations used in javascript code.
506 *
507 * @return array
508 */
509 public function wpo_js_translations() {
510 return apply_filters('wpo_js_translations', array(
511 'automatic_backup_before_optimizations' => __('Automatic backup before optimizations', 'wp-optimize'),
512 'error_unexpected_response' => __('An unexpected response was received.', 'wp-optimize'),
513 'optimization_complete' => __('Optimization complete', 'wp-optimize'),
514 'run_optimizations' => __('Run optimizations', 'wp-optimize'),
515 'cancel' => __('Cancel', 'wp-optimize'),
516 'please_select_settings_file' => __('Please, select settings file.', 'wp-optimize')
517 ));
518 }
519
520 public function wpo_admin_bar() {
521 $wp_admin_bar = $GLOBALS['wp_admin_bar'];
522
523 if (defined('WPOPTIMIZE_ADMINBAR_DISABLE') && WPOPTIMIZE_ADMINBAR_DISABLE) return;
524
525 // Show menu item in top bar only for super admins.
526 if (is_multisite() & !is_super_admin(get_current_user_id())) return;
527
528 // Add a link called at the top admin bar.
529 $args = array(
530 'id' => 'wp-optimize-node',
531 'title' => apply_filters('wpoptimize_admin_node_title', 'WP-Optimize')
532 );
533 $wp_admin_bar->add_node($args);
534
535 $tabs = $this->get_tabs();
536
537 foreach ($tabs as $tab_id => $tab_title) {
538 $menu_page_url = menu_page_url('WP-Optimize', false). '&tab=wp_optimize_'.$tab_id;
539
540 if (is_multisite()) {
541 $menu_page_url = network_admin_url('admin.php?page=WP-Optimize&tab=wp_optimize_'.$tab_id);
542 }
543
544 $args = array(
545 'id' => 'wpoptimize_admin_node_'.$tab_id,
546 'title' => ('optimize' == $tab_id) ? __('Optimize', 'wp-optimize') : $tab_title,
547 'parent' => 'wp-optimize-node',
548 'href' => $menu_page_url
549 );
550 $wp_admin_bar->add_node($args);
551 }
552
553 }
554
555 /**
556 * Add settings link on plugin page
557 *
558 * @param string $links Passing through the URL to be used within the HREF.
559 * @return string Returns the Links.
560 */
561 public function plugin_settings_link($links) {
562
563 $admin_page_url = $this->get_options()->admin_page_url();
564
565 $settings_link = '<a href="' . esc_url($admin_page_url) . '">' . __('Settings', 'wp-optimize') . '</a>';
566 array_unshift($links, $settings_link);
567
568 $optimize_link = '<a href="' . esc_url($admin_page_url) . '">' . __('Optimizer', 'wp-optimize') . '</a>';
569 array_unshift($links, $optimize_link);
570 return $links;
571 }
572
573 /**
574 * Schedules cron event based on selected schedule type
575 *
576 * @return void
577 */
578 public function cron_activate() {
579 $gmtoffset = (int) (3600 * ((double) get_option('gmt_offset')));
580
581 $options = $this->get_options();
582
583 if ($options->get_option('schedule') === false) {
584 $options->set_default_options();
585 } else {
586 if ('true' == $options->get_option('schedule')) {
587 if (!wp_next_scheduled('wpo_cron_event2')) {
588 $schedule_type = $options->get_option('schedule-type', 'wpo_weekly');
589
590 $this_time = (86400 * 7);
591
592 switch ($schedule_type) {
593 case "wpo_daily":
594 $this_time = 86400;
595 break;
596
597 case "wpo_weekly":
598 $this_time = (86400 * 7);
599 break;
600
601 case "wpo_otherweekly":
602 $this_time = (86400 * 14);
603 break;
604
605 case "wpo_monthly":
606 $this_time = (86400 * 30);
607 break;
608 }
609
610 add_action('wpo_cron_event2', array($this, 'cron_action'));
611 wp_schedule_event((current_time("timestamp", 0) + $this_time), $schedule_type, 'wpo_cron_event2');
612 WP_Optimize()->log('running wp_schedule_event()');
613 }
614 }
615 }
616 }
617
618 /**
619 * Clears all cron events
620 *
621 * @return void
622 */
623 public function wpo_cron_deactivate() {
624 wp_clear_scheduled_hook('wpo_cron_event2');
625 }
626
627 /**
628 * Scheduler public functions to update schedulers
629 *
630 * @param array $schedules An array of schedules being passed.
631 * @return array An array of schedules being returned.
632 */
633 public function cron_schedules($schedules) {
634 $schedules['wpo_daily'] = array('interval' => 86400, 'display' => 'Once Daily');
635 $schedules['wpo_weekly'] = array('interval' => 86400 * 7, 'display' => 'Once Weekly');
636 $schedules['wpo_fortnightly'] = array('interval' => 86400 * 14, 'display' => 'Once Every Fortnight');
637 $schedules['wpo_monthly'] = array('interval' => 86400 * 30, 'display' => 'Once Every Month');
638 return $schedules;
639 }
640
641 /**
642 * Returns count of overdue cron jobs.
643 *
644 * @return integer
645 */
646 public function howmany_overdue_crons() {
647 $how_many_overdue = 0;
648 if (function_exists('_get_cron_array') || (is_file(ABSPATH.WPINC.'/cron.php') && include_once(ABSPATH.WPINC.'/cron.php') && function_exists('_get_cron_array'))) {
649 $crons = _get_cron_array();
650 if (is_array($crons)) {
651 $timenow = time();
652 foreach ($crons as $jt => $job) {
653 if ($jt < $timenow) {
654 $how_many_overdue++;
655 }
656 }
657 }
658 }
659 return $how_many_overdue;
660 }
661
662 /**
663 * Returns warning about overdue crons.
664 *
665 * @param int $howmany count of overdue crons
666 * @return string
667 */
668 public function show_admin_warning_overdue_crons($howmany) {
669 $ret = '<div class="updated"><p>';
670 // todo: update link to wp-optimize
671 $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>';
672 $ret .= '</p></div>';
673 return $ret;
674 }
675
676 public function admin_menu() {
677
678 $capability_required = $this->capability_required();
679
680 if (!current_user_can($capability_required)) return;
681
682 $icon_svg = 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgdmlld0JveD0iMCAwIDE2IDE2IgogICB2ZXJzaW9uPSIxLjEiCiAgIGlkPSJzdmc0MzE2IgogICBoZWlnaHQ9IjE2IgogICB3aWR0aD0iMTYiPgogIDxkZWZzCiAgICAgaWQ9ImRlZnM0MzE4IiAvPgogIDxtZXRhZGF0YQogICAgIGlkPSJtZXRhZGF0YTQzMjEiPgogICAgPHJkZjpSREY+CiAgICAgIDxjYzpXb3JrCiAgICAgICAgIHJkZjphYm91dD0iIj4KICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4KICAgICAgICA8ZGM6dHlwZQogICAgICAgICAgIHJkZjpyZXNvdXJjZT0iaHR0cDovL3B1cmwub3JnL2RjL2RjbWl0eXBlL1N0aWxsSW1hZ2UiIC8+CiAgICAgICAgPGRjOnRpdGxlPjwvZGM6dGl0bGU+CiAgICAgIDwvY2M6V29yaz4KICAgIDwvcmRmOlJERj4KICA8L21ldGFkYXRhPgogIDxnCiAgICAgaWQ9ImxheWVyMSI+CiAgICA8cGF0aAogICAgICAgc3R5bGU9ImZpbGw6I2EwYTVhYTtmaWxsLW9wYWNpdHk6MSIKICAgICAgIGlkPSJwYXRoNTciCiAgICAgICBkPSJtIDEwLjc2ODgwOSw2Ljc2MTYwNTEgMCwwIGMgLTAuMDE2ODgsLTAuMDE2ODc4IC0wLjAyNTMxLC0wLjA0MjE4MSAtMC4wMzM3NCwtMC4wNjc0OTkgLTAuMDA4NCwtMC4wMDgzOSAtMC4wMDg0LC0wLjAxNjg3OCAtMC4wMTY4OCwtMC4wMzM3NDMgQyA5Ljk5MjYxMTIsNS4xOTIzMzY2IDguMjIwODU1Nyw0LjU4NDg3ODEgNi43NDQzOTEyLDUuMjkzNTc5NyA1LjY3MjkwMDUsNS44MDgyMzI4IDUuMDU3MDA0Myw2Ljg4ODE2MTMgNS4wNjU0NDIsOC4wMDE4MzY1IDQuNDU3OTgyMiw3LjMxMDAwNzYgMy42OTg2NTg0LDYuNzk1MzU0NSAyLjg1NDk2NDIsNi40OTE2MjUzIDMuMjY4Mzc0Myw1LjA2NTc4MzEgNC4yNTU0OTYsMy44MTcxMTY2IDUuNjg5Nzc0NiwzLjEyNTI4NzggOC4zNjQyODMyLDEuODM0NDM2OCAxMS41NzAzMTksMi45Mzk2NzQ0IDEyLjg4NjQ4MSw1LjU4ODg3MjYgMTMuNDUxNzU1LDYuNzI3ODU5NiAxNC42NDk4MDEsNy4zNTIxOTIxIDE1Ljg0Nzg0Niw3LjIzNDA3NSAxNS43NjM0ODIsNi4zMzk3NiAxNS41MTg4MDUsNS40MzcwMDg2IDE1LjEwNTM5Niw0LjU3NjQ0MDQgMTMuMjE1NTIxLDAuNjg3MDEzNCA4LjUzMzAyMjYsLTAuOTQxMzE2MjcgNC42NDM1OTQzLDAuOTQwMTIxNzkgMi4zMjM0MzcsMi4wNjIyMzM0IDAuODA0Nzg4MTQsNC4xNzk5MDQ0IDAuMzU3NjMxMzIsNi41MzM4MDk4IDIuNDE2MjQzOCw2LjQyNDEyOSA0LjQzMjY3MTcsNy41MDQwNTc0IDUuNDM2NjY2Miw5LjQzNjExNjcgbCAwLjAwODM5LDAgYyAwLjc1OTMxOTIsMS4zNzUyMjAzIDIuNDcyMDE3OCwxLjk0MDQ5NTMgMy45MDYyOTYsMS4yNDg2NjczIDEuMDQ2MTc5OCwtMC41MDYyMTggMS42NTM2NDA4LC0xLjUzNTUyMzggMS42Nzg5NTA4LC0yLjYxNTQ1MTIgMC41ODIxNDgsMC43MDg3MDE4IDEuMzMzMDM1LDEuMjQ4NjY2OCAyLjE1OTg1NiwxLjU3NzcwNjQgLTAuNDM4NzIxLDEuMzU4MzQ3OCAtMS40MDA1MzMsMi41NDc5NTQ4IC0yLjc5MjYyNywzLjIxNDQ3ODggLTIuNTkwMTM4NywxLjI0ODY1OCAtNS42NzgwNTc0LDAuMjUzMTA0IC03LjA2MTcxNTEsLTIuMjI3MzU3IGwgMCwwIEMgMi43NjIxMDQ4LDkuNDUyOTg5NCAxLjUxMzQzODMsOC44MjAyMTkxIDAuMjgxNjQ1OTIsOC45NzIwODQ0IDAuMzgyODg3NjUsOS43OTg5MDQ2IDAuNjE5MTIzMzEsMTAuNjE3Mjg3IDAuOTk4Nzg1MiwxMS40MDE5MjIgYyAxLjg4MTQzNjgsMy44OTc4NjQgNi41NjM5MzcsNS41MjYxOTggMTAuNDYxODAwOCwzLjY0NDc2IDIuMjQ0MjI2LC0xLjA4ODM2OSAzLjczNzU2MiwtMy4xMDQ3OTYgNC4yMzUzNDIsLTUuMzc0MzMyMyAtMS45OTk1NTQsMC4wNDIxODEgLTMuOTQ4NDg2LC0xLjAyOTMwNjMgLTQuOTI3MTcsLTIuOTEwNzQzMyB6IgogICAgICAgY2xhc3M9InN0MTciIC8+CiAgPC9nPgo8L3N2Zz4K';
683
684 // Removes the admin menu items on the left WP bar.
685 if (!is_multisite() || (is_multisite() && is_network_admin())) {
686 add_menu_page("WP-Optimize", "WP-Optimize", $capability_required, "WP-Optimize", array($this, "wp_optimize_menu"), $icon_svg);
687 }
688
689 $options = $this->get_options();
690
691 if ($options->get_option('enable-admin-menu', 'false') == 'true') {
692 add_action('wp_before_admin_bar_render', array($this, 'wpo_admin_bar'));
693 }
694
695 }
696
697 private function wp_normalize_path($path) {
698 // Wp_normalize_path is not present before WP 3.9.
699 if (function_exists('wp_normalize_path')) return wp_normalize_path($path);
700 // Taken from WP 4.6.
701 $path = str_replace('\\', '/', $path);
702 $path = preg_replace('|(?<=.)/+|', '/', $path);
703 if (':' === substr($path, 1, 1)) {
704 $path = ucfirst($path);
705 }
706 return $path;
707 }
708
709 public function get_templates_dir() {
710 return apply_filters('wp_optimize_templates_dir', $this->wp_normalize_path(WPO_PLUGIN_MAIN_PATH.'/templates'));
711 }
712
713 public function get_templates_url() {
714 return apply_filters('wp_optimize_templates_url', WPO_PLUGIN_URL.'/templates');
715 }
716
717 public function include_template($path, $return_instead_of_echo = false, $extract_these = array()) {
718 if ($return_instead_of_echo) ob_start();
719
720 if (preg_match('#^([^/]+)/(.*)$#', $path, $matches)) {
721 $prefix = $matches[1];
722 $suffix = $matches[2];
723 if (isset($this->template_directories[$prefix])) {
724 $template_file = $this->template_directories[$prefix].'/'.$suffix;
725 }
726 }
727
728 if (!isset($template_file)) {
729 $template_file = WPO_PLUGIN_MAIN_PATH.'/templates/'.$path;
730 }
731
732 $template_file = apply_filters('wp_optimize_template', $template_file, $path);
733
734 do_action('wp_optimize_before_template', $path, $template_file, $return_instead_of_echo, $extract_these);
735
736 if (!file_exists($template_file)) {
737 error_log("WP Optimize: template not found: ".$template_file);
738 echo __('Error:', 'wp-optimize').' '.__('template not found', 'wp-optimize')." (".$path.")";
739 } else {
740 extract($extract_these);
741 $wpdb = $GLOBALS['wpdb'];
742 $wp_optimize = $this;
743 $optimizer = $this->get_optimizer();
744 $options = $this->get_options();
745 $wp_optimize_notices = $this->get_notices();
746 include $template_file;
747 }
748
749 do_action('wp_optimize_after_template', $path, $template_file, $return_instead_of_echo, $extract_these);
750
751 if ($return_instead_of_echo) return ob_get_clean();
752 }
753
754 /**
755 * Build a list of template directories (stored in self::$template_directories)
756 */
757 private function register_template_directories() {
758
759 $template_directories = array();
760
761 $templates_dir = $this->get_templates_dir();
762
763 if ($dh = opendir($templates_dir)) {
764 while (($file = readdir($dh)) !== false) {
765 if ('.' == $file || '..' == $file) continue;
766 if (is_dir($templates_dir.'/'.$file)) {
767 $template_directories[$file] = $templates_dir.'/'.$file;
768 }
769 }
770 closedir($dh);
771 }
772
773 // Optimal hook for most extensions to hook into.
774 $this->template_directories = apply_filters('wp_optimize_template_directories', $template_directories);
775
776 }
777
778 /**
779 * Not currently used; needs looking at.
780 * N.B. The description does not match the actual function
781 *
782 * @param integer $date Date of when the optimization was executed.
783 */
784 public function send_email($date) {
785 ob_start();
786 // This need to work on - currently not using the parameter values.
787 $my_time = current_time("timestamp", 0);
788 $my_date = gmdate(get_option('date_format') . ' ' . get_option('time_format'), $my_time);
789 $sendto = (!$options->get_option('email-address') ? get_bloginfo('admin_email') : $options->get_option('email-address'));
790 $subject = get_bloginfo('name').": ".__("Automatic Operation Completed", "wp-optimize")." ".$my_date;
791
792 $msg = __("Scheduled optimization was executed at", "wp-optimize")." ".$my_date."\r\n"."\r\n";
793 $msg .= __("You can safely delete this email.", "wp-optimize")."\r\n";
794 $msg .= "\r\n";
795 $msg .= __("Regards,", "wp-optimize")."\r\n";
796 $msg .= __("WP-Optimize Plugin", "wp-optimize");
797 ob_end_clean();
798 }
799
800 /**
801 * Message to debug
802 *
803 * @param string $message Message to insert into the log.
804 * @param array $context Context of the log.
805 */
806 public function log($message, $context = array()) {
807 $this->get_logger()->debug($message, $context);
808 }
809
810 /**
811 * Format Bytes Into KB/MB
812 *
813 * @param mixed $bytes Number of bytes to be converted.
814 * @return integer return the correct format size.
815 */
816 public function format_size($bytes) {
817 if ($bytes > 1073741824) {
818 return number_format_i18n(($bytes / 1073741824), 2) . ' '.__('GB', 'wp-optimize');
819 } elseif ($bytes > 1048576) {
820 return number_format_i18n(($bytes / 1048576), 1) . ' '.__('MB', 'wp-optimize');
821 } elseif ($bytes > 1024) {
822 return number_format_i18n(($bytes / 1024), 1) . ' '.__('KB', 'wp-optimize');
823 } else {
824 return number_format_i18n($bytes, 0) . ' '.__('bytes', 'wp-optimize');
825 }
826 }
827
828 /**
829 * Executed this function on cron event.
830 */
831 public function cron_action() {
832
833 $optimizer = $this->get_optimizer();
834 $options = $this->get_options();
835
836 $this->log('WPO: Starting cron_action()');
837
838 if ('true' == $options->get_option('schedule')) {
839 $this_options = $options->get_option('auto');
840
841 $optimizations = $optimizer->get_optimizations();
842
843 // Currently the output of the optimizations is not saved/used/logged.
844 $results = $optimizer->do_optimizations($this_options, 'auto');
845 }
846
847 }
848
849 /**
850 * This will customize a URL with a correct Affiliate link
851 * This function can be update to suit any URL as longs as the URL is passed
852 *
853 * @param String $url - URL to be check to see if it an updraftplus match.
854 * @param String $text - Text to be entered within the href a tags.
855 * @param String $html - Any specific HTML to be added.
856 * @param String $class - Specify a class for the href (including the attribute label)
857 * @param Boolean $return_instead_of_echo - if set, then the result will be returned, not echo-ed.
858 *
859 * @return String|void
860 */
861 public function wp_optimize_url($url, $text, $html = '', $class = '', $return_instead_of_echo = false) {
862 // Check if the URL is UpdraftPlus.
863 if (false !== strpos($url, '//updraftplus.com')) {
864 // Set URL with Affiliate ID.
865 $url = $url.'?afref='.$this->get_notices()->get_affiliate_id();
866
867 // Apply filters.
868 $url = apply_filters('wpoptimize_updraftplus_com_link', $url);
869 }
870 // Return URL - check if there is HTML such as images.
871 if ('' != $html) {
872 $result = '<a '.$class.' href="'.esc_attr($url).'">'.$html.'</a>';
873 } else {
874 $result = '<a '.$class.' href="'.esc_attr($url).'">'.htmlspecialchars($text).'</a>';
875 }
876 if ($return_instead_of_echo) return $result;
877 echo $result;
878 }
879
880 /**
881 * Setup WPO logger(s)
882 */
883 public function setup_loggers() {
884
885 $logger = $this->get_logger();
886 $loggers = $this->wpo_loggers();
887
888 if (!empty($loggers)) {
889 foreach ($loggers as $_logger) {
890 $logger->add_logger($_logger);
891 }
892 }
893
894 add_action('wp_optimize_after_optimizations', array($this, 'after_optimizations_logger_action'));
895 add_filter('additional_options_updraft_ring_logger', array($this, 'additional_options_updraft_ring_logger'), 20, 4);
896 }
897
898 /**
899 * Run logger actions after all optimizations done
900 */
901 public function after_optimizations_logger_action() {
902 $loggers = $this->get_logger()->get_loggers();
903 if (!empty($loggers)) {
904 foreach ($loggers as $logger) {
905 if (is_a($logger, 'Updraft_Email_Logger')) {
906 $logger->flush_log();
907 }
908 }
909 }
910 }
911
912 /**
913 * Additional options fo ring logger.
914 *
915 * @param string $additional_options_html The HTML to output.
916 * @param string $logger_form_name The prefix being used in the options form for this logger.
917 * @param array $logger_additional_options Any saved options.
918 * @param Updraft_Logger_Interface $logger_class The logger that the additional options are for.
919 * @return string
920 */
921 public function additional_options_updraft_ring_logger($additional_options_html, $logger_form_name, $logger_additional_options, $logger_class) {
922
923 $ring_logger_limit = ((!empty($logger_additional_options['ring_logger_limit']) && is_numeric($logger_additional_options['ring_logger_limit'])) ? $logger_additional_options['ring_logger_limit'] : '50');
924
925 return $additional_options_html.
926 sprintf(__('Store the last %s entries', 'wp-optimize'), '<input type="number" min="10" step="1" size="4" name="'.$logger_form_name.'[ring_logger_limit]" value="'.esc_attr($ring_logger_limit).'" placeholder="'.esc_attr__('Ring logger limit', 'wp-optimize').'">');
927 }
928
929
930 /**
931 * Returns list of WPO loggers instances
932 * Apply filter wp_optimize_loggers
933 *
934 * @return array|mixed|void
935 */
936 public function wpo_loggers() {
937
938 $loggers = array();
939
940 $loggers_classes = array(
941 'Updraft_PHP_Logger' => WPO_PLUGIN_MAIN_PATH . 'includes/class-updraft-php-logger.php',
942 'Updraft_Email_Logger' => WPO_PLUGIN_MAIN_PATH . 'includes/class-updraft-email-logger.php',
943 'Updraft_Ring_Logger' => WPO_PLUGIN_MAIN_PATH . 'includes/class-updraft-ring-logger.php'
944 );
945
946 $loggers_classes = apply_filters('wp_optimize_loggers_classes', $loggers_classes);
947
948 if (!empty($loggers_classes)) {
949 foreach ($loggers_classes as $logger_class => $logger_file) {
950 if (!class_exists($logger_class)) {
951 if (is_file($logger_file)) {
952 include_once($logger_file);
953 }
954 }
955
956 if (class_exists($logger_class)) {
957 $loggers[] = new $logger_class();
958 }
959 }
960 }
961
962 $loggers = apply_filters('wp_optimize_loggers', $loggers);
963
964 if (empty($loggers)) return array();
965
966 $logger_options = $this->get_options()->get_option('logging');
967 $logger_additional_options = $this->get_options()->get_option('logging-additional');
968
969 foreach ($loggers as $logger) {
970 $logger_class_name = get_class($logger);
971 $logger_id = strtolower($logger_class_name);
972 if (empty($logger_options[$logger_id])) {
973 $logger->disable();
974 }
975
976 if (!empty($logger_additional_options) && array_key_exists($logger_id, $logger_additional_options)) {
977 $logger->set_option($logger_additional_options[$logger_id]);
978 }
979 }
980
981 return $loggers;
982 }
983
984 /**
985 * Returns true if optimization works in multisite mode
986 *
987 * @return boolean
988 */
989 public function is_multisite_mode() {
990 return (is_multisite() && WP_Optimize()->is_premium());
991 }
992
993 /**
994 * Returns list of all sites in multisite
995 *
996 * @return array
997 */
998 public function get_sites() {
999 $sites = array();
1000 // check if function get_sites exists (since 4.6.0) else use wp_get_sites.
1001 if (function_exists('get_sites')) {
1002 $sites = get_sites(array('network_id' => null));
1003 } elseif (function_exists('wp_get_sites')) {
1004 // @codingStandardsIgnoreLine
1005 $sites = wp_get_sites(array('network_id' => null));
1006 }
1007 return $sites;
1008 }
1009
1010 /**
1011 * Output success/error messages from $output array.
1012 *
1013 * @param array $output ['messages' => success messages, 'errors' => error messages]
1014 */
1015 private function wpo_render_output_messages($output) {
1016 foreach ($output['messages'] as $item) {
1017 echo '<div class="updated fade"><strong>'.$item.'</strong></div>';
1018 }
1019
1020 foreach ($output['errors'] as $item) {
1021 echo '<div class="error fade"><strong>'.$item.'</strong></div>';
1022 }
1023 }
1024
1025 /**
1026 * Returns script memory limit in megabytes.
1027 *
1028 * @param bool $memory_limit
1029 * @return int
1030 */
1031 public function get_memory_limit($memory_limit = false) {
1032 // Returns in megabytes
1033 if (false == $memory_limit) $memory_limit = ini_get('memory_limit');
1034 $memory_limit = rtrim($memory_limit);
1035
1036 return $this->return_bytes($memory_limit);
1037 }
1038
1039 /**
1040 * Returns free memory in bytes.
1041 *
1042 * @return int
1043 */
1044 public function get_free_memory() {
1045 return $this->get_memory_limit() - memory_get_usage();
1046 }
1047
1048 /**
1049 * Checks PHP memory_limit and WP_MAX_MEMORY_LIMIT values and return minimal.
1050 *
1051 * @return int memory limit in bytes.
1052 */
1053 public function get_script_memory_limit() {
1054 $memory_limit = $this->get_memory_limit();
1055
1056 if (defined('WP_MAX_MEMORY_LIMIT')) {
1057 $wp_memory_limit = $this->get_memory_limit(WP_MAX_MEMORY_LIMIT);
1058
1059 if ($wp_memory_limit > 0 && $wp_memory_limit < $memory_limit) {
1060 $memory_limit = $wp_memory_limit;
1061 }
1062 }
1063
1064 return $memory_limit;
1065 }
1066
1067 /**
1068 * Returns max packet size for database.
1069 *
1070 * @return int|string
1071 */
1072 public function get_max_packet_size() {
1073 global $wpdb;
1074 static $mp = 0;
1075
1076 if ($mp > 0) return $mp;
1077
1078 $mp = (int) $wpdb->get_var("SELECT @@session.max_allowed_packet");
1079 // Default to 1MB
1080 $mp = (is_numeric($mp) && $mp > 0) ? $mp : 1048576;
1081 // 32MB
1082 if ($mp < 33554432) {
1083 $save = $wpdb->show_errors(false);
1084 // @codingStandardsIgnoreLine
1085 $req = @$wpdb->query("SET GLOBAL max_allowed_packet=33554432");
1086 $wpdb->show_errors($save);
1087
1088 $mp = (int) $wpdb->get_var("SELECT @@session.max_allowed_packet");
1089 // Default to 1MB
1090 $mp = (is_numeric($mp) && $mp > 0) ? $mp : 1048576;
1091 }
1092
1093 return $mp;
1094 }
1095
1096 /**
1097 * Converts shorthand memory notation value to bytes.
1098 * From http://php.net/manual/en/function.ini-get.php
1099 *
1100 * @param string $val shorthand memory notation value.
1101 */
1102 public function return_bytes($val) {
1103 $val = trim($val);
1104 $last = strtolower($val[strlen($val)-1]);
1105 $val = (int) $val;
1106 switch ($last) {
1107 case 'g':
1108 $val *= 1024;
1109 // no break
1110 case 'm':
1111 $val *= 1024;
1112 // no break
1113 case 'k':
1114 $val *= 1024;
1115 }
1116
1117 return $val;
1118 }
1119 }
1120
1121 /**
1122 * Plugin activation actions.
1123 */
1124 function wpo_activation_actions() {
1125 // If plugin activated by not a Network Administrator then deactivate plugin and show message.
1126 if (is_multisite() && !is_network_admin()) {
1127 deactivate_plugins(plugin_basename(__FILE__));
1128 wp_die(__('Only Network Administrator can activate WP-Optimize plugin.', 'wp-optimize').
1129 ' <a href="'.admin_url('plugins.php').'">'.__('go back', 'wp-optimize').'</a>');
1130 }
1131
1132 WP_Optimize()->get_options()->set_default_options();
1133 }
1134
1135 /**
1136 * Plugin deactivation actions.
1137 */
1138 function wpo_deactivation_actions() {
1139 WP_Optimize()->wpo_cron_deactivate();
1140 }
1141
1142 function wpo_cron_deactivate() {
1143 WP_Optimize()->log('running wpo_cron_deactivate()');
1144 wp_clear_scheduled_hook('wpo_cron_event2');
1145 }
1146
1147 /**
1148 * Plugin uninstall actions.
1149 */
1150 function wpo_uninstall_actions() {
1151 WP_Optimize()->get_options()->delete_all_options();
1152 }
1153
1154 function WP_Optimize() {
1155 return WP_Optimize::instance();
1156 }
1157
1158 endif;
1159
1160 $GLOBALS['wp_optimize'] = WP_Optimize();
1161