PluginProbe
LWS Tools / 2.6.3
LWS Tools v2.6.3
trunk 1.0 1.0.1 2.0 2.1 2.1.5 2.2 2.2.1 2.3 2.3.1 2.4 2.4.1 2.4.2 2.4.5 2.4.6 2.4.7 2.4.8 2.4.9 2.5 2.6 2.6.1 2.6.1.5 2.6.2 2.6.3 2.6.4
lws-tools / lws-tools.php

lws-tools.php in LWS Tools 2.6.3, at lws-tools.php

1,491 lines 54.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * Plugin Name: LWS Tools
5 * Plugin URI: https://www.lws.fr/
6 * Description: Optimize and modify your website's parameters
7 * Version: 2.6.3
8 * Author: LWS
9 * Author URI: https://www.lws.fr
10 * Tested up to: 6.9
11 * Domain Path: /languages
12 * Requires PHP : 7.3
13 *
14
15 * @since 1.0
16 * @package lwstools
17 */
18
19 if (!defined('ABSPATH')) {
20 exit;
21 }
22
23 if (!function_exists('wp_get_wp_version')) {
24 function wp_get_wp_version() {
25 static $wp_version;
26
27 if ( ! isset( $wp_version ) ) {
28 require ABSPATH . WPINC . '/version.php';
29 }
30
31 return $wp_version;
32 }
33 }
34
35
36 define('LWS_TK_URL', plugin_dir_url(__FILE__));
37 define('LWS_TK_DIR', plugin_dir_path(__FILE__));
38 require_once(ABSPATH . '/wp-admin/includes/class-wp-upgrader.php');
39 require_once(ABSPATH . '/wp-admin/includes/class-core-upgrader.php');
40 require_once(ABSPATH . '/wp-admin/includes/class-theme-upgrader.php');
41 require_once(ABSPATH . '/wp-admin/includes/class-plugin-upgrader.php');
42 require_once(ABSPATH . '/wp-admin/includes/class-language-pack-upgrader.php');
43
44 if (!function_exists('get_plugin_data')) {
45 require_once(ABSPATH . 'wp-admin/includes/plugin.php');
46 }
47
48 if (!class_exists('IaSupport')) {
49 require_once 'ia/ia_support.php';
50 }
51
52 // Remove all notices and popup while on the config page
53 add_action('admin_notices', function () {
54 if (substr(get_current_screen()->id, 0, 29) == "toplevel_page_lws-tk-config") {
55 remove_all_actions('admin_notices');
56 }
57 }, 0);
58
59 /**
60 * Load translations
61 */
62 add_action('init', 'lws_tk_traduction');
63 function lws_tk_traduction()
64 {
65 $ia = new IaSupport();
66 load_plugin_textdomain('lws-tools', false, dirname(plugin_basename(__FILE__)) . '/languages');
67 }
68
69 register_activation_hook(__FILE__, 'lws_tk_on_activation');
70 function lws_tk_on_activation()
71 {
72 set_transient('lwstk_remind_me', 2592000);
73 }
74
75 register_uninstall_hook(__FILE__, 'lws_tk_uninstalling_plugin');
76 function lws_tk_uninstalling_plugin()
77 {
78 if (!get_option('lws_tk_keep_data_on_delete')) {
79 $delete_all = array(
80 'err_co',
81 'sanitize_media',
82 'hide_gen',
83 'delete_live_writer',
84 'less_revision',
85 'no_h1_mce',
86 'no_emote_wp',
87 'no_apirest',
88 'medium_large',
89 'page_author_link',
90 'no_rss',
91 'remove_feeds_links',
92 'no_comment_rss',
93 'no_user_sitemap',
94 'no_user_ep_rest',
95 'no_self_ping',
96 'remove_shortlink'
97 );
98 foreach ($delete_all as $list) {
99 delete_option('lws_tk_' . $list);
100 }
101 delete_option('lws_tk_keep_data_on_delete');
102 delete_option('lws_tk_reduce_revisions_number');
103 }
104 }
105
106 /**
107 * Enqueue any CSS or JS script needed
108 */
109 add_action('admin_enqueue_scripts', 'lws_tk_scripts');
110 function lws_tk_scripts()
111 {
112 // Get plugin version for cache busting
113 $plugin_data = get_plugin_data(__FILE__);
114 $version = $plugin_data['Version'];
115
116 wp_enqueue_style('lws_tools_support_css', LWS_TK_URL . "css/lws_tools_support_css.css", array(), $version);
117
118 if (get_current_screen()->base == ('toplevel_page_lws-tk-config') || get_current_screen()->base == ('lws-tools_page_lws-tk-config-ia')) {
119 wp_enqueue_style('lws_tk-css', LWS_TK_URL . "css/lws_tk_style.css", array(), $version);
120 wp_enqueue_style('lws_tk-dt-css', LWS_TK_URL . "DataTables/datatables.min.css", array(), $version);
121 wp_enqueue_script('lws_tk-dt', LWS_TK_URL . "DataTables/datatables.min.js", array(), $version);
122 wp_enqueue_style('lws_sms-Poppins', 'https://fonts.googleapis.com/css?family=Poppins');
123 wp_enqueue_style('lwsop_bootstrap_css', LWS_TK_URL . "css/bootstrap.css", array(), $version);
124 wp_enqueue_script('lwsop_bootstrap_js', LWS_TK_URL . "js/bootstrap.min.js", array(), $version);
125 } else {
126 wp_enqueue_style('lws_tk_css_out', LWS_TK_URL . "css/lws_tk_style_out.css", array(), $version);
127 if (!get_transient('lwstk_remind_me') && !get_option('lwstk_do_not_ask_again')) {
128 add_action('admin_notices', 'lwstk_review_ad_plugin');
129 }
130 }
131 }
132
133 function lwstk_review_ad_plugin()
134 {
135 ?>
136 <script>
137 function lwstk_remind_me() {
138 var data = {
139 _ajax_nonce: '<?php echo esc_attr(wp_create_nonce('reminder_for_tk')); ?>',
140 action: "lws_tk_reminder_ajax",
141 data: true,
142 };
143 jQuery.post(ajaxurl, data, function(response) {
144 jQuery("#lwstk_review_notice").addClass("animationFadeOut");
145 setTimeout(() => {
146 jQuery("#lwstk_review_notice").addClass("lws_hidden");
147 }, 800);
148 });
149
150 }
151
152 function lwstk_do_not_bother_me() {
153 var data = {
154 _ajax_nonce: '<?php echo esc_attr(wp_create_nonce('donotask_for_tk')); ?>',
155 action: "lws_tk_donotask_ajax",
156 data: true,
157 };
158 jQuery.post(ajaxurl, data, function(response) {
159 jQuery("#lwstk_review_notice").addClass("animationFadeOut");
160 setTimeout(() => {
161 jQuery("#lwstk_review_notice").addClass("lws_hidden");
162 }, 800);
163 });
164 }
165 </script>
166
167 <div class="notice notice-info is-dismissible lwstk_review_block_general" id="lwstk_review_notice">
168 <div class="lwstk_circle">
169 <img class="lwstk_review_block_image" src="<?php echo esc_url(plugins_url('images/plugin_lws-tools.svg', __FILE__)) ?>" width="40px" height="40px">
170 </div>
171 <div style="padding:16px">
172 <h1 class="lwstk_review_block_title"> <?php esc_html_e('Thank you for using LWS Tools!', 'lws-tools'); ?></h1>
173 <p class="lwstk_review_block_desc"><?php _e('Evaluate our plugin to help others optimise and secure their WordPress website!', 'lws-tools'); ?></p>
174 <a class="lwstk_button_rate_plugin" href="https://wordpress.org/support/plugin/lws-tools/reviews/" target="_blank"><img style="margin-right: 8px;" src="<?php echo esc_url(plugins_url('images/noter.svg', __FILE__)) ?>" width="15px" height="15px"><?php esc_html_e('Rate', 'lws-tools'); ?></a>
175 <a class="lwstk_review_button_secondary" onclick="lwstk_remind_me()"><?php esc_html_e('Remind me later', 'lws-tools'); ?></a>
176 <a class="lwstk_review_button_secondary" onclick="lwstk_do_not_bother_me()"><?php esc_html_e('Do not ask again', 'lws-tools'); ?></a>
177 </div>
178 </div>
179 <?php
180 }
181
182 //AJAX Reminder//
183 add_action("wp_ajax_lws_tk_reminder_ajax", "lws_tk_remind_me_later");
184 function lws_tk_remind_me_later()
185 {
186 check_ajax_referer('reminder_for_tk', '_ajax_nonce');
187 if (!current_user_can('manage_options')) {
188 wp_die(-1);
189 }
190 if (isset($_POST['data'])) {
191 set_transient('lwstk_remind_me', 2592000);
192 }
193 }
194
195 //AJAX Reminder//
196 add_action("wp_ajax_lws_tk_donotask_ajax", "lws_tk_do_not_ask");
197 function lws_tk_do_not_ask()
198 {
199 check_ajax_referer('donotask_for_tk', '_ajax_nonce');
200 if (!current_user_can('manage_options')) {
201 wp_die(-1);
202 }
203 if (isset($_POST['data'])) {
204 update_option('lwstk_do_not_ask_again', true);
205 }
206 }
207
208
209 function lws_tk_convert($size)
210 {
211 $unit = array(__('b', 'lws-cleaner'), __('K', 'lws-cleaner'), __('M', 'lws-cleaner'), __('G', 'lws-cleaner'), __('T', 'lws-cleaner'), __('P', 'lws-cleaner'));
212 if ($size <= 0) {
213 return '0 ' . $unit[1];
214 }
215 return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . '' . $unit[$i];
216 }
217
218
219 /**
220 * Create plugin menu in wp-admin
221 */
222 add_action('admin_menu', 'lws_tk_menu_admin');
223 function lws_tk_menu_admin()
224 {
225 $menu_slug = 'lws-tk-config';
226 add_menu_page(__('LWS Tools - Overview', 'lws-tools'), 'LWS Tools', 'manage_options', $menu_slug, 'lws_tk_create_page', LWS_TK_URL . 'images/plugin_lws_tools.svg');
227 }
228
229 /**
230 * Generate the setting page in admin
231 */
232 function lws_tk_create_page()
233 {
234 global $wpdb;
235 include_once __DIR__ . '/view/change_htaccess.php';
236
237
238 //NOTIF//
239 $plugins_update = array();
240 $themes_update = array();
241 $unused_plugins = array();
242 $unused_themes = array();
243
244 $actual_version = get_bloginfo('version');
245 $up_to_date = true;
246 $translations_ready = false;
247 $cert_invalid = false;
248
249 $all_plugins = get_plugins();
250 $all_themes = wp_get_themes();
251 $my_theme = wp_get_theme();
252
253
254 //Number of themes/plugins
255 $count_themes = count($all_themes);
256 $count_inactive_themes = $count_themes - 1;
257 $count_plugins = count($all_plugins);
258
259 //SSL Expiration & Issuer @sameer|Reading SSL certificates in PHP
260 if (!$lws_tk_ssl_cert = get_transient('lws_tk_ssl_cert')) {
261 $errno = 0;
262 $errstr = '';
263 $timeout = 30;
264 $ssl_info = stream_context_create(array("ssl" => array("capture_peer_cert" => true)));
265
266 $stream = @stream_socket_client("ssl://" . parse_url(site_url(), PHP_URL_HOST) . ":443", $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $ssl_info);
267
268 if ($stream) {
269 $cert_resource = stream_context_get_params($stream);
270 $certificate = $cert_resource['options']['ssl']['peer_certificate'];
271 $certinfo = openssl_x509_parse($certificate);
272 fclose($stream);
273 $lws_tk_ssl_cert = $certinfo;
274 set_transient('lws_tk_ssl_cert', $certinfo, 24 * HOUR_IN_SECONDS);
275 }
276 }
277
278 if ($lws_tk_ssl_cert['validTo_time_t'] - time() < 0) {
279 $cert_invalid = true;
280 }
281 $expiration_ssl = date("m/j/Y", $lws_tk_ssl_cert['validTo_time_t']);
282 $issued_by = $lws_tk_ssl_cert['issuer']['CN'];
283 $up_to_date = (wp_get_update_data()['counts']['wordpress']);
284
285
286 if (!empty(wp_get_translation_updates())) {
287 $translations_ready = true;
288 }
289
290 //Check if DB prefix is different from default
291 $db_prefix = $wpdb->prefix == "wp_" ? true /* Default */ : false /* Not Default */;
292
293 if (isset($_POST['lws_tk_update_prefix'])) {
294 if (!isset($_POST['nonce_updating_prefix_nonce']) || !wp_verify_nonce($_POST['nonce_updating_prefix_nonce'], 'lws_tk_update_prefix')) {
295 wp_die();
296 }
297 $config = ABSPATH . 'wp-config.php';
298 $lines = file($config); //file in to an array
299 $config_file = '';
300 $new_prefix = 'wp';
301
302 //Create new prefix
303 $characters = array_merge(range('a', 'z'), range('0', '9'));
304 $length = rand(2, 4);
305 for ($i = 0; $i < $length; $i++) {
306 $rand = mt_rand(0, count($characters) - 1);
307 $new_prefix .= $characters[$rand];
308 }
309 $new_prefix .= '_';
310
311 //Modify wp-config to change said prefix
312 foreach ($lines as $line) {
313 if (strpos($line, '$table_prefix') === 0) {
314 $line = '$table_prefix = ' . '"' . $new_prefix . '";' . "\n\r";
315 }
316 $config_file .= $line;
317 }
318
319 //Update each table to reflect new prefix
320 if ($wpdb->get_results("SHOW TABLES LIKE '" . $wpdb->prefix . "%'", ARRAY_N) !== null) {
321 foreach ($wpdb->get_results("SHOW TABLES LIKE '" . $wpdb->prefix . "%'", ARRAY_N) as $table) {
322 $new_name = substr_replace($table[0], $new_prefix, 0, strlen($wpdb->prefix));
323 $wpdb->query("RENAME TABLE `{$table[0]}` TO `{$new_name}`");
324 }
325 }
326
327 //Update specific options with new prefix
328 $wpdb->query("UPDATE {$new_prefix}options SET option_name='{$new_prefix}user_roles' WHERE option_name='{$wpdb->prefix}user_roles';");
329
330 $wpdb->query("UPDATE {$new_prefix}usermeta SET meta_key =
331 CONCAT(
332 REPLACE(LEFT(meta_key, " . strlen($wpdb->prefix) . "), '{$wpdb->prefix}', '{$new_prefix}'),
333 SUBSTR(meta_key, " . (strlen($wpdb->prefix) + 1) . ")
334 ) WHERE
335 meta_key in (
336 '{$wpdb->prefix}capabilities', '{$wpdb->prefix}user_level',
337 '{$wpdb->prefix}user-settings', '{$wpdb->prefix}user-settings-time',
338 '{$wpdb->prefix}dashboard_quick_press_last_post_id'
339 )");
340
341 //Save the new wp-config
342 if (!empty($config_file)) {
343 file_put_contents($config, $config_file);
344 }
345
346 header("Refresh:0;");
347
348 //Check if DB prefix is different from default
349 $db_prefix = $new_prefix == "wp_" ? true /* Default */ : false /* Not Default */;
350 }
351
352
353 //Get every plugins in need of an update
354 if (get_site_transient('update_plugins') && get_site_transient('update_plugins')->response !== null) {
355 foreach (get_site_transient('update_plugins')->response as $plugin) {
356 $plugin_data = get_plugin_data($dir = plugin_dir_path(__DIR__) . "/" . $plugin->plugin);
357 $plugins_update[] = array('name' => $plugin_data['Name'], 'version' => $plugin_data['Version'], 'new_version' => $plugin->new_version, 'package' => $plugin->plugin, 'slug' => $plugin->slug);
358 }
359 }
360
361 //Get every themes in need of an update
362 if (get_site_transient('update_themes') && get_site_transient('update_themes')->response !== null) {
363 foreach (get_site_transient('update_themes')->response as $theme) {
364 $theme_data = wp_get_theme($theme['theme']);
365 $themes_update[] = array('name' => $theme_data['Name'], 'version' => $theme_data['Version'], 'new_version' => $theme['new_version'], 'package' => $theme['package'], 'slug' => $theme['theme']);
366 }
367 }
368
369 //Get every unused plugins and the number of used plugins
370 $active_plugins = 0;
371 $inactive_plugins = 0;
372 foreach ($all_plugins as $slug => $plugin) {
373 if (!is_plugin_active($slug) && !is_plugin_active_for_network($slug)) {
374 $unused_plugins[] = array('name' => $plugin['Name'], 'author' => $plugin['AuthorName'], 'version' => $plugin['Version'], 'slug' => $plugin['TextDomain'], 'package' => $slug);
375 $inactive_plugins += 1;
376 } else {
377 $active_plugins += 1;
378 }
379 }
380
381 //Get every unused themes
382 foreach ($all_themes as $slug => $theme) {
383 if ($theme['Name'] != $my_theme->name) {
384 $unused_themes[] = array('name' => $theme['Name'], 'author' => $theme['Author'], 'version' => $theme['Version'], 'slug' => $slug);
385 }
386 }
387
388 //SERVER
389
390 $environment = sanitize_text_field($_SERVER['SERVER_SOFTWARE']);
391 $user_ip = sanitize_text_field($_SERVER['HTTP_X_REAL_IP']);
392 $server_port = sanitize_text_field($_SERVER['SERVER_PORT']);
393
394 if (sanitize_text_field($_SERVER['HTTPS']) == 'on') {
395 $is_https = __('Yes', 'lws-tools');
396 } else {
397 $is_https = __('No', 'lws-tools');
398 }
399
400 $server_name = sanitize_text_field($_SERVER['SERVER_NAME']);
401 $server_ip = sanitize_text_field($_SERVER['SERVER_ADDR']);
402 $server_protocol = sanitize_text_field($_SERVER['SERVER_PROTOCOL']);
403
404 $php_ver = phpversion();
405 $is_debug = WP_DEBUG;
406 if ($is_debug) {
407 $is_debug = __('Yes', 'lws-tools');
408 } else {
409 $is_debug = __('No', 'lws-tools');
410 }
411
412 $fopen = ini_get("allow_url_fopen");
413 if ($fopen) {
414 $fopen = __('Yes', 'lws-tools');
415 } else {
416 $fopen = __('No', 'lws-tools');
417 }
418
419 $timezone = ini_get("date.timezone");
420 $charset = ini_get("default_charset");
421 $can_file_upload = ini_get("file_uploads");
422
423 if ($can_file_upload) {
424 $can_file_upload = __('Yes', 'lws-tools');
425 } else {
426 $can_file_upload = __('No', 'lws-tools');
427 }
428
429 $max_exec_time = ini_get("max_execution_time");
430 $max_file_upload = ini_get("max_file_uploads");
431 $max_input_vars = ini_get("max_input_vars");
432 $memory_limit = ini_get("memory_limit");
433 $post_max_size = ini_get("post_max_size");
434 $upload_max_filesize = ini_get("upload_max_filesize");
435 $php_memory_usage = lws_tk_convert(memory_get_usage());
436
437 //OPTIMISATION
438 $opti_list = array(
439 'llm_optimisation' =>
440 array(__('LLM Optimization', 'lws-tools'), __('Create an llms.txt file in your WordPress root directory to control AI crawler access and behavior. This helps manage how large language models (LLMs) like GPT and Claude index your content.', 'lws-tools'), true),
441 'delete_live_writer' =>
442 array(__('Delete Windows Live Writer manifest', 'lws-tools'), __('Delete the line WordPress add in the header of your website. Useless if you do not use Windows Live Writer.', 'lws-tools'), true),
443 'less_revision' =>
444 array(__('Reduce the amount of available revisions to ', 'lws-tools'), __('WordPress automatically save posts and pages every 2 minutes. Do not completely deactivate those, you should reduce the maximum amount of revisions so as to not obstruct the database uselessly.', 'lws-tools'), true),
445 'page_author_link' =>
446 array(__('Remove author\'s pages and their links', 'lws-tools'), __('If you do not wish to possess individual pages for authors, delete those here. It also help hiding their login informations.', 'lws-tools'), true),
447 'no_self_ping' =>
448 array(__('Prevent WordPress from pingbacking yourself in your posts', 'lws-tools'), __('A Pingback is a link created automatically between two contents. It generally helps with SEO but also generate for contents on the same website, which can be bothersome.', 'lws-tools'), false),
449 'no_emote_wp' =>
450 array(__('Use visitor\'s emotes instead of WordPress', 'lws-tools'), __('Once activated, emotes in your posts and pages will use the vistor\'s emote instead of loading WordPress, helping with performances.', 'lws-tools'), false),
451 'no_h1_mce' =>
452 array(__('Remove Heading 1 from TinyMCE', 'lws-tools'), __('By deactivating H1 tags, you remove the possibility for content creators on your website to put multiple Main Title on your website. You must only have one for good SEO.', 'lws-tools'), true),
453 'remove_shortlink' =>
454 array(__('Remove shortlinks from the page', 'lws-tools'), __('A shortlink is a shortened link of your post or page. It then exists in the source code of your page. you can gain a small performance boost by deactivating that option if you do not use it.', 'lws-tools'), true),
455 'medium_large' =>
456 array(__('Add back hidden \'Medium Large\' image size ', 'lws-tools'), __('Add a new size for images (768 pixels), already existing but hidden, when inserting medias in a post', 'lws-tools'), false),
457 'sanitize_media' =>
458 array(__('Provide a new way of sanitizing uploaded media name', 'lws-tools'), __('Medias names are cleaned even more thoroughly than normal for better names', 'lws-tools'), false),
459 'no_rss' =>
460 array(__('Remove RSS feeds', 'lws-tools'), __('RSS feeds allows visitors to subscribe to your posts and power some apps. Remove RSS if you do not use the blogging part of WordPress or do not want to manage it.', 'lws-tools'), false),
461 'remove_feeds_links' =>
462 array(__('Remove RSS feeds links', 'lws-tools'), __('Remove URLs to manage RSS feeds', 'lws-tools'), false),
463 'no_comment_rss' =>
464 array(__('Remove comments RSS feeds', 'lws-tools'), __('Remove feeds related to comments', 'lws-tools'), false),
465 );
466
467 $secu_list = array(
468 'err_co' =>
469 array(__('Hide connexion errors on wp-login', 'lws-tools'), __('Hide errors when a person try to connect to your WordPress (notably, hide your username)', 'lws-tools'), true),
470 'hide_gen' =>
471 array(__('Hide "WordPress Version" meta on pages', 'lws-tools'), __('WordPress version is shown in multiple places. Security breachs from older versions can be used by hackers to hack your website. You should hide your version.', 'lws-tools'), true),
472 'no_apirest' =>
473 array(__('Deactivate REST API', 'lws-tools'), __('WordPress latest breachs focus on REST API, deactivate-it if you have no use for it.', 'lws-tools'), false),
474 'no_user_sitemap' =>
475 array(__('Hide users pages from WordPress sitemap', 'lws-tools'), __('Hide users pages of your WordPress from the plan of your site.', 'lws-tools'), false),
476 'no_user_ep_rest' =>
477 array(__('Hide users endpoints from REST API', 'lws-tools'), __('Deactivate users endpoints, hiding the users list from disconnected users.', 'lws-tools'), false),
478 );
479
480 $wp_manager = array(
481 'autoindex' =>
482 //Vous pouvez activer cette option pour sécuriser vos données sensibles (fichiers personnels, listing d'adresses mail, mots de passe, sauvegarde de bases de données,...). Cela empêchera l'accès à vos fichiers dans un dossier sans fichier index.
483 array(__('Deactivate files listing for directories with no index', 'lws-tools'), __('You can activate this option to secure your sensible datas (personnal files, email addresses listing, password, database backups,...). It will prevent acces to files in a directory with no index file.', 'lws-tools'), true),
484 'authorid' =>
485 //En cachant votre identifiant, un pirate aura plus de difficulté à se connecter à votre wordpress.
486 array(__('Hide author\'s username', 'lws-tools'), __('By hiding your login, a hacker will have a harder time connection to your WordPress.', 'lws-tools'), true),
487 'comments' =>
488 // En activant cette option, vous bloquerez les tentatives de spams et les abus de commentaires envoyés par les robots et les mauvaises requêtes
489 array(__('Block access to comment pages to browser without UserAgent or Referer', 'lws-tools'), __('By activating this option, you will block spam attempts and comments abuse sent by bots and bad requests', 'lws-tools'), false),
490 'sqlfiles' =>
491 // Il est nécessaire de bloquer le téléchargement de vos fichiers .sql pour éviter toute attaque malveillante. Vos fichiers peuvent contenir des informations sensibles.
492 array(__('Block downloading of SQL files', 'lws-tools'), __('It is necessary to block downloading of your SQL files to prevent all malicious attacks. Your files can contains sensible informations.', 'lws-tools'), false),
493 'readmelicense' =>
494 // Augmentez votre sécurité en bloquant l’accès à vos fichiers situés à la racine de votre site et/ou plugin.
495 //Ces fichiers peuvent contenir des informations exploitables par les pirates pour trouver des failles.
496 array(__('Block access to readme and license files', 'lws-tools'), __('Improve security by blocking access to files situate at the root of your website/plugin. Those files can contains informations usable by hackers to find breaches.', 'lws-tools'), false),
497 'xmlrpc' =>
498 // Il est nécessaire de bloquer l’accès au fichier xml-rpc s’il n’est pas utilisé car celui-ci permet de se connecter à distance à Wordpress et peut être utilisé à des fins malveillantes.
499 array(__('Block access to xmlrpc.php', 'lws-tools'), __('It is necessary to block access to xmlrpc if it is not used as it allows to connect remotely to WordPress and could be used for malicious intent.', 'lws-tools'), false),
500 'phpuploads' =>
501 // Cette option vous permet d'interdire l'exécution de fichier PHP dans ce dossier, qui n'est pas prévu pour cela.
502 array(__('Forbid PHP execution in the uploads directory', 'lws-tools'), __('This option lets you forbid execution of PHP in files in this directory, which is not made for that.', 'lws-tools'), false),
503 );
504
505 if (isset($_POST['lws_tk_optimisations'])) {
506 if (!isset($_POST['nonce_opti_listing_nonce']) || !wp_verify_nonce($_POST['nonce_opti_listing_nonce'], 'lws_tk_optimisations')) {
507 wp_die();
508 }
509 //Sanitize array
510 $checkboxes = isset($_POST['lws_tk_optimisation_list']) ? (array) $_POST['lws_tk_optimisation_list'] : array();
511 $checkboxes = array_map('sanitize_text_field', $checkboxes);
512 //Update checkboxes
513 foreach ($opti_list as $key => $list) {
514 if (in_array($key, $checkboxes)) {
515 update_option('lws_tk_' . $key, 'yes');
516 if ($key == 'less_revision') {
517 $value = sanitize_text_field($_POST['less_revision_revision_number']);
518 update_option('lws_tk_reduce_revisions_number', $value);
519 }
520 } else {
521 delete_option('lws_tk_' . $key);
522 if ($key == 'less_revision') {
523 delete_option('lws_tk_reduce_revisions_number');
524 }
525 }
526 }
527
528 $change_tab = 'nav-optimisation';
529 }
530
531 if (isset($_POST['lws_tk_security'])) {
532 if (!isset($_POST['nonce_security_listing_nonce']) || !wp_verify_nonce($_POST['nonce_security_listing_nonce'], 'lws_tk_security')) {
533 wp_die();
534 }
535 //Sanitize array
536 $checkboxes = isset($_POST['lws_tk_security_list']) ? (array) $_POST['lws_tk_security_list'] : array();
537 $checkboxes = array_map('sanitize_text_field', $checkboxes);
538 //Update checkboxes
539 foreach ($secu_list as $key => $list) {
540 if (in_array($key, $checkboxes)) {
541 update_option('lws_tk_' . $key, 'yes');
542 } else {
543 delete_option('lws_tk_' . $key);
544 }
545 }
546 if (isset($_SERVER['lwsapitoken']) && explode('/', getcwd())[1] == 'htdocs') {
547 $wp_manager_checkboxes = isset($_POST['lws_tk_wpmanager_list']) ? (array) $_POST['lws_tk_wpmanager_list'] : array();
548 $wp_manager_checkboxes = array_map('sanitize_text_field', $wp_manager_checkboxes);
549 foreach ($wp_manager as $key => $list) {
550 if (in_array($key, $wp_manager_checkboxes)) {
551 $opts[$key] = true;
552 } else {
553 $opts[$key] = false;
554 }
555 }
556 include_once __DIR__ . '/view/update_htaccess.php';
557 }
558
559 $change_tab = 'nav-security';
560 }
561
562 $results = $wpdb->get_results("SHOW TABLE STATUS");
563 $db_size = 0;
564 $list_tables = array();
565 foreach ($results as $size) {
566 $db_size += $size->Data_length + $size->Index_length;
567 $list_tables[] = array('name' => $size->Name, 'size' => lws_tk_convert($size->Data_length + $size->Index_length), 'charset' => $size->Collation, 'created' => $size->Create_time, 'engine' => $size->Engine);
568 }
569
570 $table_number = count($list_tables);
571 $db_size = (lws_tk_convert($db_size));
572
573 //TOOLS
574 $revisions_amount = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "posts` WHERE post_type='revision'");
575 $revisions_amount = count($revisions_amount);
576
577 $trashed_comments = count($wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "comments` WHERE comment_approved='trash'"));
578 $spam_comments = count($wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "comments` WHERE comment_approved='spam'"));
579
580 if (isset($_POST['lws_tk_reset_plugin'])) {
581 if (!isset($_POST['nonce_security_reset_nonce']) || !wp_verify_nonce($_POST['nonce_security_reset_nonce'], 'lws_tk_reset_plugin')) {
582 wp_die();
583 }
584 $delete_all = array(
585 'err_co',
586 'sanitize_media',
587 'hide_gen',
588 'delete_live_writer',
589 'less_revision',
590 'no_h1_mce',
591 'no_emote_wp',
592 'no_apirest',
593 'medium_large',
594 'page_author_link',
595 'no_rss',
596 'remove_feeds_links',
597 'no_comment_rss',
598 'no_user_sitemap',
599 'no_user_ep_rest',
600 'no_self_ping',
601 'remove_shortlink'
602 );
603 foreach ($delete_all as $key => $list) {
604 delete_option('lws_tk_' . $list);
605 }
606 }
607 include __DIR__ . '/view/tabs.php';
608 }
609
610 ///OPTIMISATIONS///
611
612 add_action('init', 'lws_tk_optimisations');
613 function lws_tk_optimisations()
614 {
615
616 if (get_option('lws_tk_llm_optimisation')) {
617 generate_llms_file(false);
618 }
619
620 // Automatically regenerate the file whenever one of the follwing hook is triggered
621 $hooks = [
622 'post_updated',
623 'wp_ajax_updatevbview',
624 'deleted_post',
625 'trashed_post',
626 'untrashed_post',
627 'customize_save_after'
628 ];
629
630 foreach($hooks as $hook) {
631 add_action($hook, function() {
632 if (get_option('lws_tk_llm_optimisation')) {
633 generate_llms_file(true);
634 }
635 });
636 }
637
638 // Regenerate llms.txt when WooCommerce is activated or deactivated
639 // as it will add new pages/posts to add to llms.txt
640 add_action('activated_plugin', function($plugin) {
641 if ($plugin === 'woocommerce/woocommerce.php' && get_option('lws_tk_llm_optimisation')) {
642 generate_llms_file(true);
643 }
644 });
645
646 add_action('deactivated_plugin', function($plugin) {
647 if ($plugin === 'woocommerce/woocommerce.php' && get_option('lws_tk_llm_optimisation')) {
648 generate_llms_file(true);
649 }
650 });
651
652 /**
653 * Sanitize more the name of media uploaded
654 */
655 if (get_option('lws_tk_sanitize_media')) {
656 add_filter('sanitize_file_name', 'lws_tk_sanitize_file_name');
657 }
658
659 /**
660 * Deactivate Windows Live Writer Manifest Link
661 */
662 if (get_option('lws_tk_delete_live_writer')) {
663 remove_action('wp_head', 'wlwmanifest_link');
664 }
665
666 /**
667 * Remove any errors shown in the login page
668 */
669 if (get_option('lws_tk_err_co')) {
670 add_filter('login_errors', function ($error) {
671 return $error = esc_html__('Failed to connect', 'lws-tools');
672 });
673 }
674
675 /**
676 * Remove the element indicating the use of WordPress
677 */
678 if (get_option('lws_tk_hide_gen')) {
679 remove_action('wp_head', 'wp_generator');
680 }
681
682 /**
683 * Reduce number of revisions [Based on option _number - 1]
684 */
685 if (get_option('lws_tk_less_revision')) {
686 add_filter('wp_revisions_to_keep', 'lws_tk_reduce_revisions', 10, 2);
687 function lws_tk_reduce_revisions($num, $post)
688 {
689 return $num = get_option('lws_tk_reduce_revisions_number');
690 }
691 }
692
693 /**
694 * Remove heading1 for TMCE
695 */
696 if (get_option('lws_tk_no_h1_mce')) {
697 add_filter('tiny_mce_before_init', 'lws_tk_remove_h1_tmce');
698 function lws_tk_remove_h1_tmce($block)
699 {
700 $block['block_formats'] = "Paragraph=p;Heading 2=h2;Heading 3=h3;Heading 4=h4;Heading 5=h5;Heading 6=h6;Preformatted=pre";
701 return $block;
702 }
703 }
704
705 /**
706 * Disable the emoji's
707 */
708 if (get_option('lws_tk_no_emote_wp')) {
709 remove_action('wp_head', 'print_emoji_detection_script', 7);
710 remove_action('admin_print_scripts', 'print_emoji_detection_script');
711 remove_action('wp_print_styles', 'print_emoji_styles');
712 remove_action('admin_print_styles', 'print_emoji_styles');
713 remove_filter('the_content_feed', 'wp_staticize_emoji');
714 remove_filter('comment_text_rss', 'wp_staticize_emoji');
715 remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
716 add_filter('tiny_mce_plugins', 'lws_tk_disable_emojis_tinymce');
717 add_filter('wp_resource_hints', 'lws_tk_disable_emojis_remove_dns_prefetch', 10, 2);
718 }
719
720 /**
721 * Remove Author Page and its link
722 */
723 if (get_option('lws_tk_page_author_link')) {
724 add_action('template_redirect', function () {
725 if (is_author()) {
726 global $wp_query;
727 $wp_query->set_404();
728 status_header(404);
729 }
730 });
731 add_filter('author_link', function () {
732 return get_option('home');
733 });
734 }
735
736 /**
737 * Add one more size type for images
738 */
739 if (get_option('lws_tk_medium_large')) {
740 add_filter('image_size_names_choose', function ($size_names) {
741 $new_sizes = array(
742 'medium_large' => esc_html__('Medium-Large', 'lws-tools'),
743 );
744 return array_merge($size_names, $new_sizes);
745 });
746 }
747
748 /**
749 * Disable REST API in its entirety
750 */
751 if (get_option('lws_tk_no_apirest')) {
752 add_filter('rest_authentication_errors', function ($access) {
753 return new WP_Error(
754 'rest_disabled',
755 esc_html__('The WordPress REST API has been disabled.', 'lws-tools'),
756 array('status' => rest_authorization_required_code())
757 );
758 });
759 }
760
761 /**
762 * Disable only the endpoints for users and users/id when disconnected
763 */
764 if (get_option('lws_tk_no_user_ep_rest')) {
765 if (!is_user_logged_in()) {
766 add_filter('rest_endpoints', 'lws_tk_disable_custom_rest_endpoints');
767 }
768 }
769
770 /**
771 * Disable all RSS Feeds
772 */
773 if (get_option('lws_tk_no_rss')) {
774 add_action('do_feed', function () {
775 wp_die(esc_html__('No feed available', 'lws-tools'));
776 }, 1);
777 add_action('do_feed_rdf', function () {
778 wp_die(esc_html__('No feed available', 'lws-tools'));
779 }, 1);
780 add_action('do_feed_rss', function () {
781 wp_die(esc_html__('No feed available', 'lws-tools'));
782 }, 1);
783 add_action('do_feed_rss2', function () {
784 wp_die(esc_html__('No feed available', 'lws-tools'));
785 }, 1);
786 add_action('do_feed_atom', function () {
787 wp_die(esc_html__('No feed available', 'lws-tools'));
788 }, 1);
789 add_action('do_feed_rss2_comments', function () {
790 wp_die(esc_html__('No feed available', 'lws-tools'));
791 }, 1);
792 add_action('do_feed_atom_comments', function () {
793 wp_die(esc_html__('No feed available', 'lws-tools'));
794 }, 1);
795 }
796
797 /**
798 * Disable only Comments RSS Feed
799 */
800 if (get_option('lws_tk_no_comment_rss')) {
801 add_action('do_feed', function ($comments) {
802 if ($comments) {
803 wp_die(esc_html__('No feed available', 'lws-tools'));
804 }
805 }, 1);
806 add_action('do_feed_rdf', function ($comments) {
807 if ($comments) {
808 wp_die(esc_html__('No feed available', 'lws-tools'));
809 }
810 }, 1);
811 add_action('do_feed_rss', function ($comments) {
812 if ($comments) {
813 wp_die(esc_html__('No feed available', 'lws-tools'));
814 }
815 }, 1);
816 add_action('do_feed_rss2', function ($comments) {
817 if ($comments) {
818 wp_die(esc_html__('No feed available', 'lws-tools'));
819 }
820 }, 1);
821 add_action('do_feed_atom', function ($comments) {
822 if ($comments) {
823 wp_die(esc_html__('No feed available', 'lws-tools'));
824 }
825 }, 1);
826 add_action('do_feed_rss2_comments', function ($comments) {
827 if ($comments) {
828 wp_die(esc_html__('No feed available', 'lws-tools'));
829 }
830 }, 1);
831 add_action('do_feed_atom_comments', function ($comments) {
832 if ($comments) {
833 wp_die(esc_html__('No feed available', 'lws-tools'));
834 }
835 }, 1);
836 }
837 }
838
839 function generate_llms_file($regenerate = false) {
840 $llms_file = ABSPATH . 'llms.txt';
841
842 // If we must regenerate the file, delete it then recreate it
843 if ($regenerate) {
844 unlink($llms_file);
845 }
846
847 if (!file_exists($llms_file)) {
848 $content = '';
849
850 $title = get_bloginfo() ?: site_url();
851 $content .= "# " . esc_html($title) . "\n\n";
852
853 $description = get_bloginfo('description') ?? '';
854 if (!empty($description)) {
855 $content .= "> " . esc_html($description) . "\n\n";
856 }
857
858 $args = array(
859 'post_type' => "post",
860 'post_status' => 'publish',
861 'fields' => 'ids',
862 'posts_per_page' => -1, // Get all posts
863 );
864 $posts = get_posts($args);
865
866 $args = array(
867 'post_type' => "page",
868 'post_status' => 'publish',
869 'fields' => 'ids',
870 'posts_per_page' => -1, // Get all pages
871 );
872 $pages = get_posts($args);
873
874 $content .= "# Posts\n\n";
875 foreach ($posts as $post) {
876 $content .= "- [" . esc_html(get_the_title($post)) . "] (" . esc_html(get_permalink($post)) . ")\n";
877 }
878
879 $content .= "\n# Pages\n\n";
880 foreach ($pages as $page) {
881 $content .= "- [" . esc_html(get_the_title($page)) . "] (" . esc_html(get_permalink($page)) . ")\n";
882 }
883
884 // Add WooCommerce products if WooCommerce is active
885 if (class_exists('WooCommerce')) {
886 $args = array(
887 'post_type' => "product",
888 'post_status' => 'publish',
889 'fields' => 'ids',
890 'posts_per_page' => -1, // Get all products
891 );
892 $products = get_posts($args);
893
894 if (!empty($products)) {
895 $content .= "\n# Products\n\n";
896 foreach ($products as $product) {
897 $content .= "- [" . esc_html(get_the_title($product)) . "] (" . esc_html(get_permalink($product)) . ")\n";
898 }
899 }
900 }
901
902 file_put_contents($llms_file, $content);
903 }
904 }
905
906 /**
907 * Remove links to users in the sitemap
908 */
909 if (get_option('lws_tk_no_user_sitemap')) {
910 add_filter('wp_sitemaps_add_provider', function ($provider, $name) {
911 return ($name == 'users') ? false : $provider;
912 }, 10, 2);
913 }
914
915 /**
916 * Remove password strength check.
917 */
918 if (get_option('lws_tk_remove_password_strength_meter')) {
919 add_action('admin_enqueue_scripts', 'lws_tk_remove_password_strength_meter');
920 }
921 function lws_tk_remove_password_strength_meter($hook)
922 {
923 if ($hook != "user-new.php") {
924 return;
925 }
926 wp_dequeue_script('wc-password-strength-meter');
927 wp_dequeue_script('user-profile');
928 wp_dequeue_script('password-strength-meter');
929 wp_deregister_script('user-profile');
930 $suffix = SCRIPT_DEBUG ? '' : '.min';
931 $admin = explode('/', admin_url('', 'relative'));
932 end($admin);
933 $admin = prev($admin);
934 wp_enqueue_script('user-profile', '/' . $admin . "/js/user-profile$suffix.js", array('jquery', 'wp-util'), false, 1);
935 }
936
937 /**
938 * Remove self-pingbacks in posts
939 */
940 if (get_option('lws_tk_no_self_ping')) {
941 add_action('pre_ping', 'lws_tk_no_self_ping');
942 }
943 function lws_tk_no_self_ping(&$links)
944 {
945 $home = get_option('home');
946 foreach ($links as $l => $link) {
947 if (0 === strpos($link, $home)) {
948 unset($links[$l]);
949 }
950 }
951 }
952
953 /**
954 * Remove shorlink from head
955 */
956 if (get_option('lws_tk_remove_shortlink')) {
957 add_filter('after_setup_theme', 'lws_tk_remove_shortlink');
958 }
959 function lws_tk_remove_shortlink()
960 {
961 remove_action('wp_head', 'wp_shortlink_wp_head', 10);
962 remove_action('template_redirect', 'wp_shortlink_header', 11);
963 }
964
965 if (get_option('lws_tk_remove_feeds_links')) {
966 remove_action('wp_head', 'feed_links_extra', 3);
967 remove_action('wp_head', 'feed_links', 2);
968 }
969
970
971 /**
972 * Produces cleaner filenames for uploads
973 * @wpartisan
974 */
975 function lws_tk_sanitize_file_name($filename)
976 {
977 $sanitized_filename = remove_accents($filename);
978
979 // Standard replacements
980 $invalid = array(
981 ' ' => '-',
982 '%20' => '-',
983 '_' => '-',
984 );
985
986 //Replace invalid characters defined above in the name by '-'
987 $sanitized_filename = str_replace(array_keys($invalid), array_values($invalid), $sanitized_filename);
988
989 $sanitized_filename = preg_replace('/[^A-Za-z0-9-\. ]/', '', $sanitized_filename); // Remove all non-alphanumeric except '.'
990 $sanitized_filename = preg_replace('/\.(?=.*\.)/', '', $sanitized_filename); // Remove all but last '.'
991 $sanitized_filename = preg_replace('/-+/', '-', $sanitized_filename); // Replace any more than one - in a row
992 $sanitized_filename = str_replace('-.', '.', $sanitized_filename); // Remove last - if at the end
993 $sanitized_filename = strtolower($sanitized_filename); // Lowercase
994
995 return $sanitized_filename;
996 }
997
998 /**
999 * Filter function used to remove the tinymce emoji plugin.
1000 */
1001 function lws_tk_disable_emojis_tinymce($plugins)
1002 {
1003 if (is_array($plugins)) {
1004 return array_diff($plugins, array('wpemoji'));
1005 } else {
1006 return array();
1007 }
1008 }
1009
1010 /**
1011 * Remove emoji CDN hostname from DNS prefetching hints.
1012 */
1013 function lws_tk_disable_emojis_remove_dns_prefetch($urls, $relation_type)
1014 {
1015 if ('dns-prefetch' == $relation_type) {
1016 /** This filter is documented in wp-includes/formatting.php */
1017 $emoji_svg_url = apply_filters('emoji_svg_url', 'https://s.w.org/images/core/emoji/2/svg/');
1018
1019 $urls = array_diff($urls, array($emoji_svg_url));
1020 }
1021
1022 return $urls;
1023 }
1024
1025 /**
1026 * Disable access to the users and users/id endpoints of RESTAPI
1027 */
1028 function lws_tk_disable_custom_rest_endpoints($endpoints)
1029 {
1030 $routes = array('/wp/v2/users', '/wp/v2/users/(?P<id>[\d]+)');
1031 foreach ($routes as $route) {
1032 if (!empty($endpoints[$route])) {
1033 foreach ($endpoints[$route] as $i => $handlers) {
1034 if (
1035 is_array($handlers) && isset($handlers['methods']) &&
1036 'GET' === $handlers['methods']
1037 ) {
1038 unset($endpoints[$route][$i]);
1039 }
1040 }
1041 }
1042 }
1043
1044 return $endpoints;
1045 }
1046
1047 ///END OPTIMISATIONS///
1048
1049 ////AJAX////
1050
1051 add_action('wp_ajax_update_ia_chatbot_state', 'lws_tk_update_ia_chatbot_state');
1052 function lws_tk_update_ia_chatbot_state()
1053 {
1054 check_ajax_referer('ia_chatbot_nonce', '_ajax_nonce');
1055 if (!current_user_can('manage_options')) {
1056 wp_die(-1);
1057 }
1058
1059 if (!get_option('lws_tk_ia_chatbot_state')) {
1060 update_option('lws_tk_ia_chatbot_state', true);
1061 } else {
1062 delete_option('lws_tk_ia_chatbot_state');
1063 }
1064
1065 wp_die(json_encode(['code' => "SUCCESS", 'data' => "Chatbot state updated"]));
1066 }
1067
1068 add_action('wp_ajax_lws_tools_on_message_sent', 'lws_tk_lws_tools_on_message_sent');
1069 function lws_tk_lws_tools_on_message_sent()
1070 {
1071 check_ajax_referer('lws_tools_ratelimit', '_ajax_nonce');
1072 if (!current_user_can('manage_options')) {
1073 wp_die(-1);
1074 }
1075 $raw_ip = isset($_SERVER['HTTP_X_REAL_IP']) ? $_SERVER['HTTP_X_REAL_IP'] : '127.0.0.1';
1076 $user_ip = filter_var($raw_ip, FILTER_VALIDATE_IP) ? $raw_ip : '127.0.0.1';
1077 $ip_key = hash('sha256', $user_ip);
1078
1079 $chatbot_data = get_option('lws_tools_chatbot_data', []);
1080 isset($chatbot_data[$ip_key]) or $chatbot_data[$ip_key] = ['amount' => 0, 'date' => time()];
1081
1082 // If the last reset happened 30 days ago or more, reset right now
1083 if ($chatbot_data[$ip_key]['date'] < time() - (30 * 24 * 60 * 60)) {
1084 $chatbot_data[$ip_key] = ['amount' => 0, 'date' => time()];
1085 }
1086
1087 if ($chatbot_data[$ip_key]['amount'] >= 100) {
1088 wp_die(json_encode(['code' => "LIMIT", 'data' => "You have reached the maximum number of uses for the AI Chatbot. Please try again next month."]));
1089 }
1090
1091 // Add 1 use of the AI Chatbot
1092 $chatbot_data[$ip_key]['amount']++;
1093
1094 update_option('lws_tools_chatbot_data', $chatbot_data);
1095
1096 if ($chatbot_data[$ip_key]['amount'] > 100) {
1097 wp_die(json_encode(['code' => "LIMIT_JUST_REACHED", 'data' => "You have reached the maximum number of uses for the AI Chatbot. Please try again next month."]));
1098 }
1099
1100 wp_die(json_encode(['code' => "SUCCESS", 'data' => "Chatbot quota updated", 'amount' => $chatbot_data[$ip_key]['amount']]));
1101 }
1102
1103
1104
1105
1106 // AJAX PART FOR THE DOWNLOAD //
1107 /*AJAX DOWNLOAD AND ACTIVATE PLUGINS*/
1108
1109 //AJAX DL Plugin//
1110 add_action("wp_ajax_lws_tk_downloadPlugin", "wp_ajax_install_plugin");
1111 //
1112
1113 //AJAX Activate Plugin//
1114 add_action("wp_ajax_lws_tk_activatePlugin", "lws_tools_activate_plugin");
1115 function lws_tools_activate_plugin()
1116 {
1117 check_ajax_referer('tools_activate_plugin', '_ajax_nonce');
1118 if (!current_user_can('manage_options')) {
1119 wp_die(-1);
1120 }
1121
1122 if (isset($_POST['ajax_slug'])) {
1123 switch (sanitize_textarea_field($_POST['ajax_slug'])) {
1124 case 'lws-hide-login':
1125 activate_plugin('lws-hide-login/lws-hide-login.php');
1126 break;
1127 case 'lws-sms':
1128 activate_plugin('lws-sms/lws-sms.php');
1129 break;
1130 case 'lws-tools':
1131 activate_plugin('lws-tools/lws-tools.php');
1132 break;
1133 case 'lws-affiliation':
1134 activate_plugin('lws-affiliation/lws-affiliation.php');
1135 break;
1136 case 'lws-cleaner':
1137 activate_plugin('lws-cleaner/lws-cleaner.php');
1138 break;
1139 case 'lwscache':
1140 activate_plugin('lwscache/lwscache.php');
1141 break;
1142 case 'lws-optimize':
1143 activate_plugin('lws-optimize/lws-optimize.php');
1144 break;
1145 }
1146 }
1147 wp_die();
1148 }
1149 //
1150
1151 /*END AJAX*/
1152
1153 //AJAX Plugins//
1154 add_action("wp_ajax_lwstools_updateAllPlugin", "lws_tk_update_all_plugin");
1155 function lws_tk_update_all_plugin()
1156 {
1157 check_ajax_referer('tools_update_every_plugin', '_ajax_nonce');
1158 if (!current_user_can('manage_options')) {
1159 wp_die(-1);
1160 }
1161 $pu = new Plugin_Upgrader();
1162 $update_all = array();
1163 foreach (get_site_transient('update_plugins')->response as $plugin) {
1164 $update_all[] = $plugin->plugin;
1165 }
1166 $pu->bulk_upgrade($update_all);
1167 wp_die();
1168 }
1169
1170 add_action("wp_ajax_lwstools_updatePlugin", "lws_tk_update_plugin");
1171 function lws_tk_update_plugin()
1172 {
1173 check_ajax_referer('tools_update_one_plugin', '_ajax_nonce');
1174 if (!current_user_can('manage_options')) {
1175 wp_die(-1);
1176 }
1177 $pu = new Plugin_Upgrader();
1178 $plugin_package = sanitize_text_field($_POST['lws_tk_update_plugin_specific']);
1179 $pu->upgrade($plugin_package);
1180 $pu->plugin_info();
1181 wp_die();
1182 }
1183 //
1184
1185 //AJAX Themes//
1186 add_action("wp_ajax_lwstools_updateAllTheme", "lws_tk_update_all_theme");
1187 function lws_tk_update_all_theme()
1188 {
1189 check_ajax_referer('tools_update_all_theme', '_ajax_nonce');
1190 if (!current_user_can('manage_options')) {
1191 wp_die(-1);
1192 }
1193 $tu = new Theme_Upgrader();
1194 $update_all = array();
1195 foreach (get_site_transient('update_themes')->response as $theme) {
1196 $update_all[] = $theme['theme'];
1197 }
1198 $tu->bulk_upgrade($update_all);
1199 wp_die();
1200 }
1201
1202 add_action("wp_ajax_lwstools_updateTheme", "lws_tk_update_theme");
1203 function lws_tk_update_theme()
1204 {
1205 check_ajax_referer('tools_update_one_theme', '_ajax_nonce');
1206 if (!current_user_can('manage_options')) {
1207 wp_die(-1);
1208 }
1209 $tu = new Theme_Upgrader();
1210 $theme_package = sanitize_text_field($_POST['lws_tk_update_theme_specific']);
1211 $tu->upgrade($theme_package);
1212 wp_die();
1213 }
1214 //
1215
1216 //AJAX Unused Plugins//
1217 add_action("wp_ajax_lwstools_deleteAllPlugin", "lws_tk_delete_all_plugin");
1218 function lws_tk_delete_all_plugin()
1219 {
1220 check_ajax_referer('tools_delete_all_plugin', '_ajax_nonce');
1221 if (!current_user_can('manage_options')) {
1222 wp_die(-1);
1223 }
1224 $to_delete = array();
1225 foreach (get_plugins() as $slug => $plugin) {
1226 if (!is_plugin_active($slug) && !is_plugin_active_for_network($slug)) {
1227 $to_delete[] = $slug;
1228 }
1229 }
1230 delete_plugins($to_delete);
1231 wp_die();
1232 }
1233
1234 add_action("wp_ajax_lwstools_deletePlugin", "lws_tk_delete_plugin");
1235 function lws_tk_delete_plugin()
1236 {
1237 check_ajax_referer('tools_delete_one_plugin', '_ajax_nonce');
1238 if (!current_user_can('manage_options')) {
1239 wp_die(-1);
1240 }
1241 $plugin_package = sanitize_text_field($_POST['lws_tk_delete_plugin_specific']);
1242 delete_plugins([$plugin_package]);
1243 wp_die();
1244 }
1245 //
1246
1247 //AJAX Unused Themes//
1248 add_action("wp_ajax_lwstools_deleteAllTheme", "lws_tk_delete_all_theme");
1249 function lws_tk_delete_all_theme()
1250 {
1251 check_ajax_referer('tools_delete_all_theme', '_ajax_nonce');
1252 if (!current_user_can('manage_options')) {
1253 wp_die(-1);
1254 }
1255 foreach (wp_get_themes() as $slug => $theme) {
1256 if ($theme['Name'] != wp_get_theme()->name) {
1257 delete_theme($slug);
1258 }
1259 }
1260 wp_die();
1261 }
1262
1263 add_action("wp_ajax_lwstools_deleteTheme", "lws_tk_delete_theme");
1264 function lws_tk_delete_theme()
1265 {
1266 check_ajax_referer('tools_delete_one_theme', '_ajax_nonce');
1267 if (!current_user_can('manage_options')) {
1268 wp_die(-1);
1269 }
1270 $theme_package = sanitize_text_field($_POST['lws_tk_delete_theme_specific']);
1271 delete_theme($theme_package);
1272 wp_die();
1273 }
1274 //
1275
1276 //AJAX DL Plugin//
1277 add_action("wp_ajax_lwstools_downloadPlugin", "wp_ajax_install_plugin");
1278 //
1279
1280 //AJAX Update Trads//
1281 add_action("wp_ajax_lwstools_updateTrads", "lws_tk_update_trads");
1282 function lws_tk_update_trads()
1283 {
1284 check_ajax_referer('tools_upgrade_tools_trad', '_ajax_nonce');
1285 if (!current_user_can('manage_options')) {
1286 wp_die(-1);
1287 }
1288 $lp = new Language_Pack_Upgrader();
1289 $lp->bulk_upgrade();
1290 wp_die();
1291 }
1292 //
1293
1294 //AJAX Repair DB//
1295 add_action("wp_ajax_lwstools_repairdb", "lws_tk_repairdb");
1296 function lws_tk_repairdb()
1297 {
1298 check_ajax_referer('tools_repair_only_db', '_ajax_nonce');
1299 if (!current_user_can('manage_options')) {
1300 wp_die(-1);
1301 }
1302 $config_page = ABSPATH . 'wp-config.php';
1303 $config_page_content = file($config_page);
1304 foreach ($config_page_content as $content) {
1305 if (preg_match('/^define\(\s*\'([A-Z_]+)\',(.*)\)/', $content, $match)) {
1306 if ('WP_ALLOW_REPAIR' === $match[1]) {
1307 echo esc_url(get_site_url() . "/wp-admin/maint/repair.php?repair=1");
1308 wp_die();
1309 }
1310 }
1311 }
1312 array_shift($config_page_content);
1313 array_unshift($config_page_content, "<?php\r\ndefine('WP_ALLOW_REPAIR', true);\r\n");
1314 $file = fopen($config_page, 'w');
1315 if ($file === false) {
1316 wp_die(-1);
1317 }
1318 foreach ($config_page_content as $line) {
1319 fwrite($file, $line);
1320 }
1321 fclose($file);
1322 echo esc_url(get_site_url() . "/wp-admin/maint/repair.php?repair=1");
1323 wp_die();
1324 /*@exec("wp config set WP_ALLOW_REPAIR true --raw");
1325 echo esc_url(get_site_url() . "/wp-admin/maint/repair.php?repair=1");
1326 wp_die();*/
1327 }
1328 //
1329
1330 //AJAX Opti DB//
1331 add_action("wp_ajax_lwstools_optidb", "lws_tk_optidb");
1332 function lws_tk_optidb()
1333 {
1334 check_ajax_referer('tools_optimize_all_db', '_ajax_nonce');
1335 if (!current_user_can('manage_options')) {
1336 wp_die(-1);
1337 }
1338 $config_page = ABSPATH . 'wp-config.php';
1339 $config_page_content = file($config_page);
1340 foreach ($config_page_content as $content) {
1341 if (preg_match('/^define\(\s*\'([A-Z_]+)\',(.*)\)/', $content, $match)) {
1342 if ('WP_ALLOW_REPAIR' === $match[1]) {
1343 echo esc_url(get_site_url() . "/wp-admin/maint/repair.php?repair=2");
1344 wp_die();
1345 }
1346 }
1347 }
1348 array_shift($config_page_content);
1349 array_unshift($config_page_content, "<?php\r\ndefine('WP_ALLOW_REPAIR', true);\r\n");
1350 $file = fopen($config_page, 'w');
1351 if ($file === false) {
1352 wp_die(-1);
1353 }
1354 foreach ($config_page_content as $line) {
1355 fwrite($file, $line);
1356 }
1357 fclose($file);
1358 echo esc_url(get_site_url() . "/wp-admin/maint/repair.php?repair=2");
1359 wp_die();
1360 /*@exec("wp config set WP_ALLOW_REPAIR true --raw");
1361 echo esc_url(get_site_url() . "/wp-admin/maint/repair.php?repair=2");
1362 wp_die();*/
1363 }
1364 //
1365
1366 //AJAX Deactivate Repair DB//
1367 add_action("wp_ajax_lwstools_deactivate_repair", "lws_tk_deactivate_repairdb");
1368 function lws_tk_deactivate_repairdb()
1369 {
1370 check_ajax_referer('tools_deactivate_repair_option', '_ajax_nonce');
1371 if (!current_user_can('manage_options')) {
1372 wp_die(-1);
1373 }
1374 $config_page = ABSPATH . 'wp-config.php';
1375 $config_page_content = file($config_page);
1376 foreach ($config_page_content as $key => $content) {
1377 if (preg_match('/^define\(\s*\'([A-Z_]+)\',(.*)\)/', $content, $match)) {
1378 if ('WP_ALLOW_REPAIR' === $match[1]) {
1379 $config_page_content[$key] = "";
1380 $file = fopen($config_page, 'w');
1381 if ($file === false) {
1382 wp_die(-1);
1383 }
1384 foreach ($config_page_content as $line) {
1385 fwrite($file, $line);
1386 }
1387 fclose($file);
1388 wp_die();
1389 }
1390 }
1391 }
1392 wp_die();
1393 /*@exec("wp config delete WP_ALLOW_REPAIR");
1394 wp_die();*/
1395 }
1396 //
1397
1398 //AJAX Disconnect everyone but user//
1399 add_action("wp_ajax_lwstools_disconnectall", "lws_tk_disconnect_all");
1400 function lws_tk_disconnect_all()
1401 {
1402 check_ajax_referer('disconnect_all_and_everyone', '_ajax_nonce');
1403 if (!current_user_can('manage_options')) {
1404 wp_die(-1);
1405 }
1406 foreach (get_users(array('fields' => array('ID'))) as $user) {
1407 if ($user->ID == get_current_user_id()) {
1408 $sessions = WP_Session_Tokens::get_instance(get_current_user_id());
1409 $sessions->destroy_others(wp_get_session_token());
1410 } else {
1411 $sessions = WP_Session_Tokens::get_instance($user->ID);
1412 $sessions->destroy_all();
1413 }
1414 }
1415 wp_die();
1416 }
1417 //
1418
1419 //AJAX Delete revisions older than $days//
1420 add_action("wp_ajax_lwstools_delete_revisions", "lws_tk_delete_revision");
1421 function lws_tk_delete_revision()
1422 {
1423 check_ajax_referer('delete_all_revisions', '_ajax_nonce');
1424 if (!current_user_can('manage_options')) {
1425 wp_die(-1);
1426 }
1427 global $wpdb;
1428 $days = absint($_POST['lws_tk_days_revisions']);
1429 $cutoff = date("Y-m-d H:i:s", time() - (24 * 60 * 60 * $days));
1430 $wpdb->query($wpdb->prepare("DELETE FROM `" . $wpdb->prefix . "posts` WHERE post_type='revision' AND post_modified < %s", $cutoff));
1431 wp_die();
1432 }
1433 //
1434
1435 //AJAX Delete Trashed comments//
1436 add_action("wp_ajax_lwstools_delete_trash_comments", "lws_tk_delete_trash_comments");
1437 function lws_tk_delete_trash_comments()
1438 {
1439 check_ajax_referer('delete_all_trash_comments', '_ajax_nonce');
1440 if (!current_user_can('manage_options')) {
1441 wp_die(-1);
1442 }
1443 global $wpdb;
1444 $wpdb->get_results("DELETE FROM `" . $wpdb->prefix . "comments` WHERE comment_approved='trash'");
1445 wp_die();
1446 }
1447 //
1448
1449 //AJAX Delete Trashed comments//
1450 add_action("wp_ajax_lwstools_delete_spam_comments", "lws_tk_delete_spam_comments");
1451 function lws_tk_delete_spam_comments()
1452 {
1453 check_ajax_referer('delete_all_spam_comms', '_ajax_nonce');
1454 if (!current_user_can('manage_options')) {
1455 wp_die(-1);
1456 }
1457 global $wpdb;
1458 $wpdb->get_results("DELETE FROM `" . $wpdb->prefix . "comments` WHERE comment_approved='spam'");
1459 wp_die();
1460 }
1461 //
1462
1463 //AJAX Delete old transients//
1464 add_action("wp_ajax_lwstools_delete_transients", "lws_tk_delete_old_transients");
1465 function lws_tk_delete_old_transients()
1466 {
1467 check_ajax_referer('delete_all_transients', '_ajax_nonce');
1468 if (!current_user_can('manage_options')) {
1469 wp_die(-1);
1470 }
1471 delete_expired_transients();
1472 wp_die();
1473 }
1474 //
1475
1476 //AJAX Keep Config even after delete//
1477 add_action("wp_ajax_lwstools_keep_changes", "lws_tk_keep_changes");
1478 function lws_tk_keep_changes()
1479 {
1480 check_ajax_referer('keep_on_delete_change', '_ajax_nonce');
1481 if (!current_user_can('manage_options')) {
1482 wp_die(-1);
1483 }
1484 $is_checked = sanitize_text_field($_POST['state']);
1485 $is_checked == 'true' ? update_option('lws_tk_keep_data_on_delete', true) : delete_option('lws_tk_keep_data_on_delete');
1486 wp_die();
1487 }
1488 //
1489
1490 ///END AJAX///
1491