PluginProbe
LWS Tools / 2.6.2
LWS Tools v2.6.2
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.2, at lws-tools.php

1,410 lines 52.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.2
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 (isset($_POST['data'])) {
188 set_transient('lwstk_remind_me', 2592000);
189 }
190 }
191
192 //AJAX Reminder//
193 add_action("wp_ajax_lws_tk_donotask_ajax", "lws_tk_do_not_ask");
194 function lws_tk_do_not_ask()
195 {
196 check_ajax_referer('donotask_for_tk', '_ajax_nonce');
197 if (isset($_POST['data'])) {
198 update_option('lwstk_do_not_ask_again', true);
199 }
200 }
201
202
203 function lws_tk_convert($size)
204 {
205 $unit = array(__('b', 'lws-cleaner'), __('K', 'lws-cleaner'), __('M', 'lws-cleaner'), __('G', 'lws-cleaner'), __('T', 'lws-cleaner'), __('P', 'lws-cleaner'));
206 if ($size <= 0) {
207 return '0 ' . $unit[1];
208 }
209 return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . '' . $unit[$i];
210 }
211
212
213 /**
214 * Create plugin menu in wp-admin
215 */
216 add_action('admin_menu', 'lws_tk_menu_admin');
217 function lws_tk_menu_admin()
218 {
219 $menu_slug = 'lws-tk-config';
220 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');
221 }
222
223 /**
224 * Generate the setting page in admin
225 */
226 function lws_tk_create_page()
227 {
228 global $wpdb;
229 include_once __DIR__ . '/view/change_htaccess.php';
230
231
232 //NOTIF//
233 $plugins_update = array();
234 $themes_update = array();
235 $unused_plugins = array();
236 $unused_themes = array();
237
238 $actual_version = get_bloginfo('version');
239 $up_to_date = true;
240 $translations_ready = false;
241 $cert_invalid = false;
242
243 $all_plugins = get_plugins();
244 $all_themes = wp_get_themes();
245 $my_theme = wp_get_theme();
246
247
248 //Number of themes/plugins
249 $count_themes = count($all_themes);
250 $count_inactive_themes = $count_themes - 1;
251 $count_plugins = count($all_plugins);
252
253 //SSL Expiration & Issuer @sameer|Reading SSL certificates in PHP
254 if (!$lws_tk_ssl_cert = get_transient('lws_tk_ssl_cert')) {
255 $errno = 0;
256 $errstr = '';
257 $timeout = 30;
258 $ssl_info = stream_context_create(array("ssl" => array("capture_peer_cert" => true)));
259
260 $stream = @stream_socket_client("ssl://" . parse_url(site_url(), PHP_URL_HOST) . ":443", $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $ssl_info);
261
262 if ($stream) {
263 $cert_resource = stream_context_get_params($stream);
264 $certificate = $cert_resource['options']['ssl']['peer_certificate'];
265 $certinfo = openssl_x509_parse($certificate);
266 fclose($stream);
267 $lws_tk_ssl_cert = $certinfo;
268 set_transient('lws_tk_ssl_cert', $certinfo, 24 * HOUR_IN_SECONDS);
269 }
270 }
271
272 if ($lws_tk_ssl_cert['validTo_time_t'] - time() < 0) {
273 $cert_invalid = true;
274 }
275 $expiration_ssl = date("m/j/Y", $lws_tk_ssl_cert['validTo_time_t']);
276 $issued_by = $lws_tk_ssl_cert['issuer']['CN'];
277 $up_to_date = (wp_get_update_data()['counts']['wordpress']);
278
279
280 if (!empty(wp_get_translation_updates())) {
281 $translations_ready = true;
282 }
283
284 //Check if DB prefix is different from default
285 $db_prefix = $wpdb->prefix == "wp_" ? true /* Default */ : false /* Not Default */;
286
287 if (isset($_POST['lws_tk_update_prefix'])) {
288 if (!isset($_POST['nonce_updating_prefix_nonce']) || !wp_verify_nonce($_POST['nonce_updating_prefix_nonce'], 'lws_tk_update_prefix')) {
289 wp_die();
290 }
291 $config = ABSPATH . 'wp-config.php';
292 $lines = file($config); //file in to an array
293 $config_file = '';
294 $new_prefix = 'wp';
295
296 //Create new prefix
297 $characters = array_merge(range('a', 'z'), range('0', '9'));
298 $length = rand(2, 4);
299 for ($i = 0; $i < $length; $i++) {
300 $rand = mt_rand(0, count($characters) - 1);
301 $new_prefix .= $characters[$rand];
302 }
303 $new_prefix .= '_';
304
305 //Modify wp-config to change said prefix
306 foreach ($lines as $line) {
307 if (strpos($line, '$table_prefix') === 0) {
308 $line = '$table_prefix = ' . '"' . $new_prefix . '";' . "\n\r";
309 }
310 $config_file .= $line;
311 }
312
313 //Update each table to reflect new prefix
314 if ($wpdb->get_results("SHOW TABLES LIKE '" . $wpdb->prefix . "%'", ARRAY_N) !== null) {
315 foreach ($wpdb->get_results("SHOW TABLES LIKE '" . $wpdb->prefix . "%'", ARRAY_N) as $table) {
316 $new_name = substr_replace($table[0], $new_prefix, 0, strlen($wpdb->prefix));
317 $wpdb->query("RENAME TABLE `{$table[0]}` TO `{$new_name}`");
318 }
319 }
320
321 //Update specific options with new prefix
322 $wpdb->query("UPDATE {$new_prefix}options SET option_name='{$new_prefix}user_roles' WHERE option_name='{$wpdb->prefix}user_roles';");
323
324 $wpdb->query("UPDATE {$new_prefix}usermeta SET meta_key =
325 CONCAT(
326 REPLACE(LEFT(meta_key, " . strlen($wpdb->prefix) . "), '{$wpdb->prefix}', '{$new_prefix}'),
327 SUBSTR(meta_key, " . (strlen($wpdb->prefix) + 1) . ")
328 ) WHERE
329 meta_key in (
330 '{$wpdb->prefix}capabilities', '{$wpdb->prefix}user_level',
331 '{$wpdb->prefix}user-settings', '{$wpdb->prefix}user-settings-time',
332 '{$wpdb->prefix}dashboard_quick_press_last_post_id'
333 )");
334
335 //Save the new wp-config
336 if (!empty($config_file)) {
337 file_put_contents($config, $config_file);
338 }
339
340 header("Refresh:0;");
341
342 //Check if DB prefix is different from default
343 $db_prefix = $new_prefix == "wp_" ? true /* Default */ : false /* Not Default */;
344 }
345
346
347 //Get every plugins in need of an update
348 if (get_site_transient('update_plugins') && get_site_transient('update_plugins')->response !== null) {
349 foreach (get_site_transient('update_plugins')->response as $plugin) {
350 $plugin_data = get_plugin_data($dir = plugin_dir_path(__DIR__) . "/" . $plugin->plugin);
351 $plugins_update[] = array('name' => $plugin_data['Name'], 'version' => $plugin_data['Version'], 'new_version' => $plugin->new_version, 'package' => $plugin->plugin, 'slug' => $plugin->slug);
352 }
353 }
354
355 //Get every themes in need of an update
356 if (get_site_transient('update_themes') && get_site_transient('update_themes')->response !== null) {
357 foreach (get_site_transient('update_themes')->response as $theme) {
358 $theme_data = wp_get_theme($theme['theme']);
359 $themes_update[] = array('name' => $theme_data['Name'], 'version' => $theme_data['Version'], 'new_version' => $theme['new_version'], 'package' => $theme['package'], 'slug' => $theme['theme']);
360 }
361 }
362
363 //Get every unused plugins and the number of used plugins
364 $active_plugins = 0;
365 $inactive_plugins = 0;
366 foreach ($all_plugins as $slug => $plugin) {
367 if (!is_plugin_active($slug) && !is_plugin_active_for_network($slug)) {
368 $unused_plugins[] = array('name' => $plugin['Name'], 'author' => $plugin['AuthorName'], 'version' => $plugin['Version'], 'slug' => $plugin['TextDomain'], 'package' => $slug);
369 $inactive_plugins += 1;
370 } else {
371 $active_plugins += 1;
372 }
373 }
374
375 //Get every unused themes
376 foreach ($all_themes as $slug => $theme) {
377 if ($theme['Name'] != $my_theme->name) {
378 $unused_themes[] = array('name' => $theme['Name'], 'author' => $theme['Author'], 'version' => $theme['Version'], 'slug' => $slug);
379 }
380 }
381
382 //SERVER
383
384 $environment = sanitize_text_field($_SERVER['SERVER_SOFTWARE']);
385 $user_ip = sanitize_text_field($_SERVER['HTTP_X_REAL_IP']);
386 $server_port = sanitize_text_field($_SERVER['SERVER_PORT']);
387
388 if (sanitize_text_field($_SERVER['HTTPS']) == 'on') {
389 $is_https = __('Yes', 'lws-tools');
390 } else {
391 $is_https = __('No', 'lws-tools');
392 }
393
394 $server_name = sanitize_text_field($_SERVER['SERVER_NAME']);
395 $server_ip = sanitize_text_field($_SERVER['SERVER_ADDR']);
396 $server_protocol = sanitize_text_field($_SERVER['SERVER_PROTOCOL']);
397
398 $php_ver = phpversion();
399 $is_debug = WP_DEBUG;
400 if ($is_debug) {
401 $is_debug = __('Yes', 'lws-tools');
402 } else {
403 $is_debug = __('No', 'lws-tools');
404 }
405
406 $fopen = ini_get("allow_url_fopen");
407 if ($fopen) {
408 $fopen = __('Yes', 'lws-tools');
409 } else {
410 $fopen = __('No', 'lws-tools');
411 }
412
413 $timezone = ini_get("date.timezone");
414 $charset = ini_get("default_charset");
415 $can_file_upload = ini_get("file_uploads");
416
417 if ($can_file_upload) {
418 $can_file_upload = __('Yes', 'lws-tools');
419 } else {
420 $can_file_upload = __('No', 'lws-tools');
421 }
422
423 $max_exec_time = ini_get("max_execution_time");
424 $max_file_upload = ini_get("max_file_uploads");
425 $max_input_vars = ini_get("max_input_vars");
426 $memory_limit = ini_get("memory_limit");
427 $post_max_size = ini_get("post_max_size");
428 $upload_max_filesize = ini_get("upload_max_filesize");
429 $php_memory_usage = lws_tk_convert(memory_get_usage());
430
431 //OPTIMISATION
432 $opti_list = array(
433 'llm_optimisation' =>
434 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),
435 'delete_live_writer' =>
436 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),
437 'less_revision' =>
438 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),
439 'page_author_link' =>
440 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),
441 'no_self_ping' =>
442 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),
443 'no_emote_wp' =>
444 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),
445 'no_h1_mce' =>
446 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),
447 'remove_shortlink' =>
448 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),
449 'medium_large' =>
450 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),
451 'sanitize_media' =>
452 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),
453 'no_rss' =>
454 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),
455 'remove_feeds_links' =>
456 array(__('Remove RSS feeds links', 'lws-tools'), __('Remove URLs to manage RSS feeds', 'lws-tools'), false),
457 'no_comment_rss' =>
458 array(__('Remove comments RSS feeds', 'lws-tools'), __('Remove feeds related to comments', 'lws-tools'), false),
459 );
460
461 $secu_list = array(
462 'err_co' =>
463 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),
464 'hide_gen' =>
465 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),
466 'no_apirest' =>
467 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),
468 'no_user_sitemap' =>
469 array(__('Hide users pages from WordPress sitemap', 'lws-tools'), __('Hide users pages of your WordPress from the plan of your site.', 'lws-tools'), false),
470 'no_user_ep_rest' =>
471 array(__('Hide users endpoints from REST API', 'lws-tools'), __('Deactivate users endpoints, hiding the users list from disconnected users.', 'lws-tools'), false),
472 );
473
474 $wp_manager = array(
475 'autoindex' =>
476 //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.
477 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),
478 'authorid' =>
479 //En cachant votre identifiant, un pirate aura plus de difficulté à se connecter à votre wordpress.
480 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),
481 'comments' =>
482 // 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
483 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),
484 'sqlfiles' =>
485 // 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.
486 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),
487 'readmelicense' =>
488 // Augmentez votre sécurité en bloquant l’accès à vos fichiers situés à la racine de votre site et/ou plugin.
489 //Ces fichiers peuvent contenir des informations exploitables par les pirates pour trouver des failles.
490 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),
491 'xmlrpc' =>
492 // 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.
493 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),
494 'phpuploads' =>
495 // Cette option vous permet d'interdire l'exécution de fichier PHP dans ce dossier, qui n'est pas prévu pour cela.
496 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),
497 );
498
499 if (isset($_POST['lws_tk_optimisations'])) {
500 if (!isset($_POST['nonce_opti_listing_nonce']) || !wp_verify_nonce($_POST['nonce_opti_listing_nonce'], 'lws_tk_optimisations')) {
501 wp_die();
502 }
503 //Sanitize array
504 $checkboxes = isset($_POST['lws_tk_optimisation_list']) ? (array) $_POST['lws_tk_optimisation_list'] : array();
505 $checkboxes = array_map('sanitize_text_field', $checkboxes);
506 //Update checkboxes
507 foreach ($opti_list as $key => $list) {
508 if (in_array($key, $checkboxes)) {
509 update_option('lws_tk_' . $key, 'yes');
510 if ($key == 'less_revision') {
511 $value = sanitize_text_field($_POST['less_revision_revision_number']);
512 update_option('lws_tk_reduce_revisions_number', $value);
513 }
514 } else {
515 delete_option('lws_tk_' . $key);
516 if ($key == 'less_revision') {
517 delete_option('lws_tk_reduce_revisions_number');
518 }
519 }
520 }
521
522 $change_tab = 'nav-optimisation';
523 }
524
525 if (isset($_POST['lws_tk_security'])) {
526 if (!isset($_POST['nonce_security_listing_nonce']) || !wp_verify_nonce($_POST['nonce_security_listing_nonce'], 'lws_tk_security')) {
527 wp_die();
528 }
529 //Sanitize array
530 $checkboxes = isset($_POST['lws_tk_security_list']) ? (array) $_POST['lws_tk_security_list'] : array();
531 $checkboxes = array_map('sanitize_text_field', $checkboxes);
532 //Update checkboxes
533 foreach ($secu_list as $key => $list) {
534 if (in_array($key, $checkboxes)) {
535 update_option('lws_tk_' . $key, 'yes');
536 } else {
537 delete_option('lws_tk_' . $key);
538 }
539 }
540 if (isset($_SERVER['lwsapitoken']) && explode('/', getcwd())[1] == 'htdocs') {
541 $wp_manager_checkboxes = isset($_POST['lws_tk_wpmanager_list']) ? (array) $_POST['lws_tk_wpmanager_list'] : array();
542 $wp_manager_checkboxes = array_map('sanitize_text_field', $wp_manager_checkboxes);
543 foreach ($wp_manager as $key => $list) {
544 if (in_array($key, $wp_manager_checkboxes)) {
545 $opts[$key] = true;
546 } else {
547 $opts[$key] = false;
548 }
549 }
550 include_once __DIR__ . '/view/update_htaccess.php';
551 }
552
553 $change_tab = 'nav-security';
554 }
555
556 $results = $wpdb->get_results("SHOW TABLE STATUS");
557 $db_size = 0;
558 $list_tables = array();
559 foreach ($results as $size) {
560 $db_size += $size->Data_length + $size->Index_length;
561 $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);
562 }
563
564 $table_number = count($list_tables);
565 $db_size = (lws_tk_convert($db_size));
566
567 //TOOLS
568 $revisions_amount = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "posts` WHERE post_type='revision'");
569 $revisions_amount = count($revisions_amount);
570
571 $trashed_comments = count($wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "comments` WHERE comment_approved='trash'"));
572 $spam_comments = count($wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "comments` WHERE comment_approved='spam'"));
573
574 if (isset($_POST['lws_tk_reset_plugin'])) {
575 if (!isset($_POST['nonce_security_reset_nonce']) || !wp_verify_nonce($_POST['nonce_security_reset_nonce'], 'lws_tk_reset_plugin')) {
576 wp_die();
577 }
578 $delete_all = array(
579 'err_co',
580 'sanitize_media',
581 'hide_gen',
582 'delete_live_writer',
583 'less_revision',
584 'no_h1_mce',
585 'no_emote_wp',
586 'no_apirest',
587 'medium_large',
588 'page_author_link',
589 'no_rss',
590 'remove_feeds_links',
591 'no_comment_rss',
592 'no_user_sitemap',
593 'no_user_ep_rest',
594 'no_self_ping',
595 'remove_shortlink'
596 );
597 foreach ($delete_all as $key => $list) {
598 delete_option('lws_tk_' . $list);
599 }
600 }
601 include __DIR__ . '/view/tabs.php';
602 }
603
604 ///OPTIMISATIONS///
605
606 add_action('init', 'lws_tk_optimisations');
607 function lws_tk_optimisations()
608 {
609
610 if (get_option('lws_tk_llm_optimisation')) {
611 generate_llms_file(false);
612 }
613
614 // Automatically regenerate the file whenever one of the follwing hook is triggered
615 $hooks = [
616 'post_updated',
617 'wp_ajax_updatevbview',
618 'deleted_post',
619 'trashed_post',
620 'untrashed_post',
621 'customize_save_after'
622 ];
623
624 foreach($hooks as $hook) {
625 add_action($hook, function() {
626 if (get_option('lws_tk_llm_optimisation')) {
627 generate_llms_file(true);
628 }
629 });
630 }
631
632 // Regenerate llms.txt when WooCommerce is activated or deactivated
633 // as it will add new pages/posts to add to llms.txt
634 add_action('activated_plugin', function($plugin) {
635 if ($plugin === 'woocommerce/woocommerce.php' && get_option('lws_tk_llm_optimisation')) {
636 generate_llms_file(true);
637 }
638 });
639
640 add_action('deactivated_plugin', function($plugin) {
641 if ($plugin === 'woocommerce/woocommerce.php' && get_option('lws_tk_llm_optimisation')) {
642 generate_llms_file(true);
643 }
644 });
645
646 /**
647 * Sanitize more the name of media uploaded
648 */
649 if (get_option('lws_tk_sanitize_media')) {
650 add_filter('sanitize_file_name', 'lws_tk_sanitize_file_name');
651 }
652
653 /**
654 * Deactivate Windows Live Writer Manifest Link
655 */
656 if (get_option('lws_tk_delete_live_writer')) {
657 remove_action('wp_head', 'wlwmanifest_link');
658 }
659
660 /**
661 * Remove any errors shown in the login page
662 */
663 if (get_option('lws_tk_err_co')) {
664 add_filter('login_errors', function ($error) {
665 return $error = esc_html__('Failed to connect', 'lws-tools');
666 });
667 }
668
669 /**
670 * Remove the element indicating the use of WordPress
671 */
672 if (get_option('lws_tk_hide_gen')) {
673 remove_action('wp_head', 'wp_generator');
674 }
675
676 /**
677 * Reduce number of revisions [Based on option _number - 1]
678 */
679 if (get_option('lws_tk_less_revision')) {
680 add_filter('wp_revisions_to_keep', 'lws_tk_reduce_revisions', 10, 2);
681 function lws_tk_reduce_revisions($num, $post)
682 {
683 return $num = get_option('lws_tk_reduce_revisions_number');
684 }
685 }
686
687 /**
688 * Remove heading1 for TMCE
689 */
690 if (get_option('lws_tk_no_h1_mce')) {
691 add_filter('tiny_mce_before_init', 'lws_tk_remove_h1_tmce');
692 function lws_tk_remove_h1_tmce($block)
693 {
694 $block['block_formats'] = "Paragraph=p;Heading 2=h2;Heading 3=h3;Heading 4=h4;Heading 5=h5;Heading 6=h6;Preformatted=pre";
695 return $block;
696 }
697 }
698
699 /**
700 * Disable the emoji's
701 */
702 if (get_option('lws_tk_no_emote_wp')) {
703 remove_action('wp_head', 'print_emoji_detection_script', 7);
704 remove_action('admin_print_scripts', 'print_emoji_detection_script');
705 remove_action('wp_print_styles', 'print_emoji_styles');
706 remove_action('admin_print_styles', 'print_emoji_styles');
707 remove_filter('the_content_feed', 'wp_staticize_emoji');
708 remove_filter('comment_text_rss', 'wp_staticize_emoji');
709 remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
710 add_filter('tiny_mce_plugins', 'lws_tk_disable_emojis_tinymce');
711 add_filter('wp_resource_hints', 'lws_tk_disable_emojis_remove_dns_prefetch', 10, 2);
712 }
713
714 /**
715 * Remove Author Page and its link
716 */
717 if (get_option('lws_tk_page_author_link')) {
718 add_action('template_redirect', function () {
719 if (is_author()) {
720 global $wp_query;
721 $wp_query->set_404();
722 status_header(404);
723 }
724 });
725 add_filter('author_link', function () {
726 return get_option('home');
727 });
728 }
729
730 /**
731 * Add one more size type for images
732 */
733 if (get_option('lws_tk_medium_large')) {
734 add_filter('image_size_names_choose', function ($size_names) {
735 $new_sizes = array(
736 'medium_large' => esc_html__('Medium-Large', 'lws-tools'),
737 );
738 return array_merge($size_names, $new_sizes);
739 });
740 }
741
742 /**
743 * Disable REST API in its entirety
744 */
745 if (get_option('lws_tk_no_apirest')) {
746 add_filter('rest_authentication_errors', function ($access) {
747 return new WP_Error(
748 'rest_disabled',
749 esc_html__('The WordPress REST API has been disabled.', 'lws-tools'),
750 array('status' => rest_authorization_required_code())
751 );
752 });
753 }
754
755 /**
756 * Disable only the endpoints for users and users/id when disconnected
757 */
758 if (get_option('lws_tk_no_user_ep_rest')) {
759 if (!is_user_logged_in()) {
760 add_filter('rest_endpoints', 'lws_tk_disable_custom_rest_endpoints');
761 }
762 }
763
764 /**
765 * Disable all RSS Feeds
766 */
767 if (get_option('lws_tk_no_rss')) {
768 add_action('do_feed', function () {
769 wp_die(esc_html__('No feed available', 'lws-tools'));
770 }, 1);
771 add_action('do_feed_rdf', function () {
772 wp_die(esc_html__('No feed available', 'lws-tools'));
773 }, 1);
774 add_action('do_feed_rss', function () {
775 wp_die(esc_html__('No feed available', 'lws-tools'));
776 }, 1);
777 add_action('do_feed_rss2', function () {
778 wp_die(esc_html__('No feed available', 'lws-tools'));
779 }, 1);
780 add_action('do_feed_atom', function () {
781 wp_die(esc_html__('No feed available', 'lws-tools'));
782 }, 1);
783 add_action('do_feed_rss2_comments', function () {
784 wp_die(esc_html__('No feed available', 'lws-tools'));
785 }, 1);
786 add_action('do_feed_atom_comments', function () {
787 wp_die(esc_html__('No feed available', 'lws-tools'));
788 }, 1);
789 }
790
791 /**
792 * Disable only Comments RSS Feed
793 */
794 if (get_option('lws_tk_no_comment_rss')) {
795 add_action('do_feed', function ($comments) {
796 if ($comments) {
797 wp_die(esc_html__('No feed available', 'lws-tools'));
798 }
799 }, 1);
800 add_action('do_feed_rdf', function ($comments) {
801 if ($comments) {
802 wp_die(esc_html__('No feed available', 'lws-tools'));
803 }
804 }, 1);
805 add_action('do_feed_rss', function ($comments) {
806 if ($comments) {
807 wp_die(esc_html__('No feed available', 'lws-tools'));
808 }
809 }, 1);
810 add_action('do_feed_rss2', function ($comments) {
811 if ($comments) {
812 wp_die(esc_html__('No feed available', 'lws-tools'));
813 }
814 }, 1);
815 add_action('do_feed_atom', function ($comments) {
816 if ($comments) {
817 wp_die(esc_html__('No feed available', 'lws-tools'));
818 }
819 }, 1);
820 add_action('do_feed_rss2_comments', function ($comments) {
821 if ($comments) {
822 wp_die(esc_html__('No feed available', 'lws-tools'));
823 }
824 }, 1);
825 add_action('do_feed_atom_comments', function ($comments) {
826 if ($comments) {
827 wp_die(esc_html__('No feed available', 'lws-tools'));
828 }
829 }, 1);
830 }
831 }
832
833 function generate_llms_file($regenerate = false) {
834 $llms_file = ABSPATH . 'llms.txt';
835
836 // If we must regenerate the file, delete it then recreate it
837 if ($regenerate) {
838 unlink($llms_file);
839 }
840
841 if (!file_exists($llms_file)) {
842 $content = '';
843
844 $title = get_bloginfo() ?: site_url();
845 $content .= "# " . esc_html($title) . "\n\n";
846
847 $description = get_bloginfo('description') ?? '';
848 if (!empty($description)) {
849 $content .= "> " . esc_html($description) . "\n\n";
850 }
851
852 $args = array(
853 'post_type' => "post",
854 'post_status' => 'publish',
855 'fields' => 'ids',
856 'posts_per_page' => -1, // Get all posts
857 );
858 $posts = get_posts($args);
859
860 $args = array(
861 'post_type' => "page",
862 'post_status' => 'publish',
863 'fields' => 'ids',
864 'posts_per_page' => -1, // Get all pages
865 );
866 $pages = get_posts($args);
867
868 $content .= "# Posts\n\n";
869 foreach ($posts as $post) {
870 $content .= "- [" . esc_html(get_the_title($post)) . "] (" . esc_html(get_permalink($post)) . ")\n";
871 }
872
873 $content .= "\n# Pages\n\n";
874 foreach ($pages as $page) {
875 $content .= "- [" . esc_html(get_the_title($page)) . "] (" . esc_html(get_permalink($page)) . ")\n";
876 }
877
878 // Add WooCommerce products if WooCommerce is active
879 if (class_exists('WooCommerce')) {
880 $args = array(
881 'post_type' => "product",
882 'post_status' => 'publish',
883 'fields' => 'ids',
884 'posts_per_page' => -1, // Get all products
885 );
886 $products = get_posts($args);
887
888 if (!empty($products)) {
889 $content .= "\n# Products\n\n";
890 foreach ($products as $product) {
891 $content .= "- [" . esc_html(get_the_title($product)) . "] (" . esc_html(get_permalink($product)) . ")\n";
892 }
893 }
894 }
895
896 file_put_contents($llms_file, $content);
897 }
898 }
899
900 /**
901 * Remove links to users in the sitemap
902 */
903 if (get_option('lws_tk_no_user_sitemap')) {
904 add_filter('wp_sitemaps_add_provider', function ($provider, $name) {
905 return ($name == 'users') ? false : $provider;
906 }, 10, 2);
907 }
908
909 /**
910 * Remove password strength check.
911 */
912 if (get_option('lws_tk_remove_password_strength_meter')) {
913 add_action('admin_enqueue_scripts', 'lws_tk_remove_password_strength_meter');
914 }
915 function lws_tk_remove_password_strength_meter($hook)
916 {
917 if ($hook != "user-new.php") {
918 return;
919 }
920 wp_dequeue_script('wc-password-strength-meter');
921 wp_dequeue_script('user-profile');
922 wp_dequeue_script('password-strength-meter');
923 wp_deregister_script('user-profile');
924 $suffix = SCRIPT_DEBUG ? '' : '.min';
925 $admin = explode('/', admin_url('', 'relative'));
926 end($admin);
927 $admin = prev($admin);
928 wp_enqueue_script('user-profile', '/' . $admin . "/js/user-profile$suffix.js", array('jquery', 'wp-util'), false, 1);
929 }
930
931 /**
932 * Remove self-pingbacks in posts
933 */
934 if (get_option('kws_tk_no_self_ping')) {
935 add_action('pre_ping', 'lws_tk_no_self_ping');
936 }
937 function lws_tk_no_self_ping(&$links)
938 {
939 $home = get_option('home');
940 foreach ($links as $l => $link) {
941 if (0 === strpos($link, $home)) {
942 unset($links[$l]);
943 }
944 }
945 }
946
947 /**
948 * Remove shorlink from head
949 */
950 if (get_option('lws_tk_remove_shortlink')) {
951 add_filter('after_setup_theme', 'lws_tk_remove_shortlink');
952 }
953 function lws_tk_remove_shortlink()
954 {
955 remove_action('wp_head', 'wp_shortlink_wp_head', 10);
956 remove_action('template_redirect', 'wp_shortlink_header', 11);
957 }
958
959 if (get_option('lws_tk_remove_feeds_links')) {
960 remove_action('wp_head', 'feed_links_extra', 3);
961 remove_action('wp_head', 'feed_links', 2);
962 }
963
964
965 /**
966 * Produces cleaner filenames for uploads
967 * @wpartisan
968 */
969 function lws_tk_sanitize_file_name($filename)
970 {
971 $sanitized_filename = remove_accents($filename);
972
973 // Standard replacements
974 $invalid = array(
975 ' ' => '-',
976 '%20' => '-',
977 '_' => '-',
978 );
979
980 //Replace invalid characters defined above in the name by '-'
981 $sanitized_filename = str_replace(array_keys($invalid), array_values($invalid), $sanitized_filename);
982
983 $sanitized_filename = preg_replace('/[^A-Za-z0-9-\. ]/', '', $sanitized_filename); // Remove all non-alphanumeric except '.'
984 $sanitized_filename = preg_replace('/\.(?=.*\.)/', '', $sanitized_filename); // Remove all but last '.'
985 $sanitized_filename = preg_replace('/-+/', '-', $sanitized_filename); // Replace any more than one - in a row
986 $sanitized_filename = str_replace('-.', '.', $sanitized_filename); // Remove last - if at the end
987 $sanitized_filename = strtolower($sanitized_filename); // Lowercase
988
989 return $sanitized_filename;
990 }
991
992 /**
993 * Filter function used to remove the tinymce emoji plugin.
994 */
995 function lws_tk_disable_emojis_tinymce($plugins)
996 {
997 if (is_array($plugins)) {
998 return array_diff($plugins, array('wpemoji'));
999 } else {
1000 return array();
1001 }
1002 }
1003
1004 /**
1005 * Remove emoji CDN hostname from DNS prefetching hints.
1006 */
1007 function lws_tk_disable_emojis_remove_dns_prefetch($urls, $relation_type)
1008 {
1009 if ('dns-prefetch' == $relation_type) {
1010 /** This filter is documented in wp-includes/formatting.php */
1011 $emoji_svg_url = apply_filters('emoji_svg_url', 'https://s.w.org/images/core/emoji/2/svg/');
1012
1013 $urls = array_diff($urls, array($emoji_svg_url));
1014 }
1015
1016 return $urls;
1017 }
1018
1019 /**
1020 * Disable access to the users and users/id endpoints of RESTAPI
1021 */
1022 function lws_tk_disable_custom_rest_endpoints($endpoints)
1023 {
1024 $routes = array('/wp/v2/users', '/wp/v2/users/(?P<id>[\d]+)');
1025 foreach ($routes as $route) {
1026 if (!empty($endpoints[$route])) {
1027 foreach ($endpoints[$route] as $i => $handlers) {
1028 if (
1029 is_array($handlers) && isset($handlers['methods']) &&
1030 'GET' === $handlers['methods']
1031 ) {
1032 unset($endpoints[$route][$i]);
1033 }
1034 }
1035 }
1036 }
1037
1038 return $endpoints;
1039 }
1040
1041 ///END OPTIMISATIONS///
1042
1043 ////AJAX////
1044
1045 add_action('wp_ajax_update_ia_chatbot_state', 'lws_tk_update_ia_chatbot_state');
1046 function lws_tk_update_ia_chatbot_state()
1047 {
1048 check_ajax_referer('ia_chatbot_nonce', '_ajax_nonce');
1049
1050 if (!get_option('lws_tk_ia_chatbot_state')) {
1051 update_option('lws_tk_ia_chatbot_state', true);
1052 } else {
1053 delete_option('lws_tk_ia_chatbot_state');
1054 }
1055
1056 wp_die(json_encode(['code' => "SUCCESS", 'data' => "Chatbot state updated"]));
1057 }
1058
1059 add_action('wp_ajax_lws_tools_on_message_sent', 'lws_tk_lws_tools_on_message_sent');
1060 function lws_tk_lws_tools_on_message_sent()
1061 {
1062 check_ajax_referer('lws_tools_ratelimit', '_ajax_nonce');
1063 $user_ip = isset($_SERVER['HTTP_X_REAL_IP']) ? $_SERVER['HTTP_X_REAL_IP'] : '127.0.0.1';
1064
1065 $chatbot_data = get_option('lws_tools_chatbot_data', []);
1066 isset($chatbot_data[$user_ip]) or $chatbot_data[$user_ip] = ['amount' => 0, 'date' => time()];
1067
1068 // If the last reset happened 30 days ago or more, reset right now
1069 if ($chatbot_data[$user_ip]['date'] < time() - (30 * 24 * 60 * 60)) {
1070 $chatbot_data[$user_ip] = ['amount' => 0, 'date' => time()];
1071 }
1072
1073 if ($chatbot_data[$user_ip]['amount'] >= 100) {
1074 wp_die(json_encode(['code' => "LIMIT", 'data' => "You have reached the maximum number of uses for the AI Chatbot. Please try again next month."]));
1075 }
1076
1077 // Add 1 use of the AI Chatbot
1078 $chatbot_data[$user_ip]['amount']++;
1079
1080 update_option('lws_tools_chatbot_data', $chatbot_data);
1081
1082 if ($chatbot_data[$user_ip]['amount'] > 100) {
1083 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."]));
1084 }
1085
1086 wp_die(json_encode(['code' => "SUCCESS", 'data' => "Chatbot quota updated", 'amount' => $chatbot_data[$user_ip]['amount']]));
1087 }
1088
1089
1090
1091
1092 // AJAX PART FOR THE DOWNLOAD //
1093 /*AJAX DOWNLOAD AND ACTIVATE PLUGINS*/
1094
1095 //AJAX DL Plugin//
1096 add_action("wp_ajax_lws_tk_downloadPlugin", "wp_ajax_install_plugin");
1097 //
1098
1099 //AJAX Activate Plugin//
1100 add_action("wp_ajax_lws_tk_activatePlugin", "lws_tools_activate_plugin");
1101 function lws_tools_activate_plugin()
1102 {
1103 check_ajax_referer('tools_activate_plugin', '_ajax_nonce');
1104
1105 if (isset($_POST['ajax_slug'])) {
1106 switch (sanitize_textarea_field($_POST['ajax_slug'])) {
1107 case 'lws-hide-login':
1108 activate_plugin('lws-hide-login/lws-hide-login.php');
1109 break;
1110 case 'lws-sms':
1111 activate_plugin('lws-sms/lws-sms.php');
1112 break;
1113 case 'lws-tools':
1114 activate_plugin('lws-tools/lws-tools.php');
1115 break;
1116 case 'lws-affiliation':
1117 activate_plugin('lws-affiliation/lws-affiliation.php');
1118 break;
1119 case 'lws-cleaner':
1120 activate_plugin('lws-cleaner/lws-cleaner.php');
1121 break;
1122 case 'lwscache':
1123 activate_plugin('lwscache/lwscache.php');
1124 break;
1125 case 'lws-optimize':
1126 activate_plugin('lws-optimize/lws-optimize.php');
1127 break;
1128 }
1129 }
1130 wp_die();
1131 }
1132 //
1133
1134 /*END AJAX*/
1135
1136 //AJAX Plugins//
1137 add_action("wp_ajax_lwstools_updateAllPlugin", "lws_tk_update_all_plugin");
1138 function lws_tk_update_all_plugin()
1139 {
1140 check_ajax_referer('tools_update_every_plugin', '_ajax_nonce');
1141 $pu = new Plugin_Upgrader();
1142 $update_all = array();
1143 foreach (get_site_transient('update_plugins')->response as $plugin) {
1144 $update_all[] = $plugin->plugin;
1145 }
1146 $pu->bulk_upgrade($update_all);
1147 wp_die();
1148 }
1149
1150 add_action("wp_ajax_lwstools_updatePlugin", "lws_tk_update_plugin");
1151 function lws_tk_update_plugin()
1152 {
1153 check_ajax_referer('tools_update_one_plugin', '_ajax_nonce');
1154 $pu = new Plugin_Upgrader();
1155 $plugin_package = sanitize_text_field($_POST['lws_tk_update_plugin_specific']);
1156 $pu->upgrade($plugin_package);
1157 $pu->plugin_info();
1158 wp_die();
1159 }
1160 //
1161
1162 //AJAX Themes//
1163 add_action("wp_ajax_lwstools_updateAllTheme", "lws_tk_update_all_theme");
1164 function lws_tk_update_all_theme()
1165 {
1166 check_ajax_referer('tools_update_all_theme', '_ajax_nonce');
1167 $tu = new Theme_Upgrader();
1168 $update_all = array();
1169 foreach (get_site_transient('update_themes')->response as $theme) {
1170 $update_all[] = $theme['theme'];
1171 }
1172 $tu->bulk_upgrade($update_all);
1173 wp_die();
1174 }
1175
1176 add_action("wp_ajax_lwstools_updateTheme", "lws_tk_update_theme");
1177 function lws_tk_update_theme()
1178 {
1179 check_ajax_referer('tools_update_one_theme', '_ajax_nonce');
1180 $tu = new Theme_Upgrader();
1181 $theme_package = sanitize_text_field($_POST['lws_tk_update_theme_specific']);
1182 $tu->upgrade($theme_package);
1183 wp_die();
1184 }
1185 //
1186
1187 //AJAX Unused Plugins//
1188 add_action("wp_ajax_lwstools_deleteAllPlugin", "lws_tk_delete_all_plugin");
1189 function lws_tk_delete_all_plugin()
1190 {
1191 check_ajax_referer('tools_delete_all_plugin', '_ajax_nonce');
1192 $to_delete = array();
1193 foreach (get_plugins() as $slug => $plugin) {
1194 if (!is_plugin_active($slug) && !is_plugin_active_for_network($slug)) {
1195 $to_delete[] = $slug;
1196 }
1197 }
1198 delete_plugins($to_delete);
1199 wp_die();
1200 }
1201
1202 add_action("wp_ajax_lwstools_deletePlugin", "lws_tk_delete_plugin");
1203 function lws_tk_delete_plugin()
1204 {
1205 check_ajax_referer('tools_delete_one_plugin', '_ajax_nonce');
1206 $plugin_package = sanitize_text_field($_POST['lws_tk_delete_plugin_specific']);
1207 delete_plugins([$plugin_package]);
1208 wp_die();
1209 }
1210 //
1211
1212 //AJAX Unused Themes//
1213 add_action("wp_ajax_lwstools_deleteAllTheme", "lws_tk_delete_all_theme");
1214 function lws_tk_delete_all_theme()
1215 {
1216 check_ajax_referer('tools_delete_all_theme', '_ajax_nonce');
1217 foreach (wp_get_themes() as $slug => $theme) {
1218 if ($theme['Name'] != wp_get_theme()->name) {
1219 delete_theme($slug);
1220 }
1221 }
1222 wp_die();
1223 }
1224
1225 add_action("wp_ajax_lwstools_deleteTheme", "lws_tk_delete_theme");
1226 function lws_tk_delete_theme()
1227 {
1228 check_ajax_referer('tools_delete_one_theme', '_ajax_nonce');
1229 $theme_package = sanitize_text_field($_POST['lws_tk_delete_theme_specific']);
1230 delete_theme($theme_package);
1231 wp_die();
1232 }
1233 //
1234
1235 //AJAX DL Plugin//
1236 add_action("wp_ajax_lwstools_downloadPlugin", "wp_ajax_install_plugin");
1237 //
1238
1239 //AJAX Update Trads//
1240 add_action("wp_ajax_lwstools_updateTrads", "lws_tk_update_trads");
1241 function lws_tk_update_trads()
1242 {
1243 check_ajax_referer('tools_upgrade_tools_trad', '_ajax_nonce');
1244 $lp = new Language_Pack_Upgrader();
1245 $lp->bulk_upgrade();
1246 wp_die();
1247 }
1248 //
1249
1250 //AJAX Repair DB//
1251 add_action("wp_ajax_lwstools_repairdb", "lws_tk_repairdb");
1252 function lws_tk_repairdb()
1253 {
1254 check_ajax_referer('tools_repair_only_db', '_ajax_nonce');
1255 $config_page = ABSPATH . 'wp-config.php';
1256 $config_page_content = file($config_page);
1257 foreach ($config_page_content as $content) {
1258 if (preg_match('/^define\(\s*\'([A-Z_]+)\',(.*)\)/', $content, $match)) {
1259 if ('WP_ALLOW_REPAIR' === $match[1]) {
1260 echo esc_url(get_site_url() . "/wp-admin/maint/repair.php?repair=1");
1261 wp_die();
1262 }
1263 }
1264 }
1265 array_shift($config_page_content);
1266 array_unshift($config_page_content, "<?php\r\ndefine('WP_ALLOW_REPAIR', true);\r\n");
1267 $file = @fopen($config_page, 'w');
1268 foreach ($config_page_content as $line) {
1269 @fwrite($file, $line);
1270 }
1271 @fclose($file);
1272 echo esc_url(get_site_url() . "/wp-admin/maint/repair.php?repair=1");
1273 wp_die();
1274 /*@exec("wp config set WP_ALLOW_REPAIR true --raw");
1275 echo esc_url(get_site_url() . "/wp-admin/maint/repair.php?repair=1");
1276 wp_die();*/
1277 }
1278 //
1279
1280 //AJAX Opti DB//
1281 add_action("wp_ajax_lwstools_optidb", "lws_tk_optidb");
1282 function lws_tk_optidb()
1283 {
1284 check_ajax_referer('tools_optimize_all_db', '_ajax_nonce');
1285 $config_page = ABSPATH . 'wp-config.php';
1286 $config_page_content = file($config_page);
1287 foreach ($config_page_content as $content) {
1288 if (preg_match('/^define\(\s*\'([A-Z_]+)\',(.*)\)/', $content, $match)) {
1289 if ('WP_ALLOW_REPAIR' === $match[1]) {
1290 echo esc_url(get_site_url() . "/wp-admin/maint/repair.php?repair=2");
1291 wp_die();
1292 }
1293 }
1294 }
1295 array_shift($config_page_content);
1296 array_unshift($config_page_content, "<?php\r\ndefine('WP_ALLOW_REPAIR', true);\r\n");
1297 $file = @fopen($config_page, 'w');
1298 foreach ($config_page_content as $line) {
1299 @fwrite($file, $line);
1300 }
1301 @fclose($file);
1302 echo esc_url(get_site_url() . "/wp-admin/maint/repair.php?repair=2");
1303 wp_die();
1304 /*@exec("wp config set WP_ALLOW_REPAIR true --raw");
1305 echo esc_url(get_site_url() . "/wp-admin/maint/repair.php?repair=2");
1306 wp_die();*/
1307 }
1308 //
1309
1310 //AJAX Deactivate Repair DB//
1311 add_action("wp_ajax_lwstools_deactivate_repair", "lws_tk_deactivate_repairdb");
1312 function lws_tk_deactivate_repairdb()
1313 {
1314 check_ajax_referer('tools_deactivate_repair_option', '_ajax_nonce');
1315 $config_page = ABSPATH . 'wp-config.php';
1316 $config_page_content = file($config_page);
1317 foreach ($config_page_content as $key => $content) {
1318 if (preg_match('/^define\(\s*\'([A-Z_]+)\',(.*)\)/', $content, $match)) {
1319 if ('WP_ALLOW_REPAIR' === $match[1]) {
1320 $config_page_content[$key] = "";
1321 $file = @fopen($config_page, 'w');
1322 foreach ($config_page_content as $line) {
1323 @fwrite($file, $line);
1324 }
1325 @fclose($file);
1326 wp_die();
1327 }
1328 }
1329 }
1330 wp_die();
1331 /*@exec("wp config delete WP_ALLOW_REPAIR");
1332 wp_die();*/
1333 }
1334 //
1335
1336 //AJAX Disconnect everyone but user//
1337 add_action("wp_ajax_lwstools_disconnectall", "lws_tk_disconnect_all");
1338 function lws_tk_disconnect_all()
1339 {
1340 check_ajax_referer('disconnect_all_and_everyone', '_ajax_nonce');
1341 foreach (get_users(array('fields' => array('ID'))) as $user) {
1342 if ($user->ID == get_current_user_id()) {
1343 $sessions = WP_Session_Tokens::get_instance(get_current_user_id());
1344 $sessions->destroy_others(wp_get_session_token());
1345 } else {
1346 $sessions = WP_Session_Tokens::get_instance($user->ID);
1347 $sessions->destroy_all();
1348 }
1349 }
1350 wp_die();
1351 }
1352 //
1353
1354 //AJAX Delete revisions older than $days//
1355 add_action("wp_ajax_lwstools_delete_revisions", "lws_tk_delete_revision");
1356 function lws_tk_delete_revision()
1357 {
1358 check_ajax_referer('delete_all_revisions', '_ajax_nonce');
1359 global $wpdb;
1360 $days = sanitize_text_field($_POST['lws_tk_days_revisions']);
1361 $wpdb->get_results("DELETE FROM `" . $wpdb->prefix . "posts` WHERE post_type='revision' AND post_modified < '" . date("Y-m-d H:i:s", time() - (24 * 60 * 60 * $days)) . "';");
1362 wp_die();
1363 }
1364 //
1365
1366 //AJAX Delete Trashed comments//
1367 add_action("wp_ajax_lwstools_delete_trash_comments", "lws_tk_delete_trash_comments");
1368 function lws_tk_delete_trash_comments()
1369 {
1370 check_ajax_referer('delete_all_trash_comments', '_ajax_nonce');
1371 global $wpdb;
1372 $wpdb->get_results("DELETE FROM `" . $wpdb->prefix . "comments` WHERE comment_approved='trash'");
1373 wp_die();
1374 }
1375 //
1376
1377 //AJAX Delete Trashed comments//
1378 add_action("wp_ajax_lwstools_delete_spam_comments", "lws_tk_delete_spam_comments");
1379 function lws_tk_delete_spam_comments()
1380 {
1381 check_ajax_referer('delete_all_spam_comms', '_ajax_nonce');
1382 global $wpdb;
1383 $wpdb->get_results("DELETE FROM `" . $wpdb->prefix . "comments` WHERE comment_approved='spam'");
1384 wp_die();
1385 }
1386 //
1387
1388 //AJAX Delete old transients//
1389 add_action("wp_ajax_lwstools_delete_transients", "lws_tk_delete_old_transients");
1390 function lws_tk_delete_old_transients()
1391 {
1392 check_ajax_referer('delete_all_transients', '_ajax_nonce');
1393 delete_expired_transients();
1394 wp_die();
1395 }
1396 //
1397
1398 //AJAX Keep Config even after delete//
1399 add_action("wp_ajax_lwstools_keep_changes", "lws_tk_keep_changes");
1400 function lws_tk_keep_changes()
1401 {
1402 check_ajax_referer('keep_on_delete_change', '_ajax_nonce');
1403 $is_checked = sanitize_text_field($_POST['state']);
1404 $is_checked == 'true' ? update_option('lws_tk_keep_data_on_delete', true) : delete_option('lws_tk_keep_data_on_delete');
1405 wp_die();
1406 }
1407 //
1408
1409 ///END AJAX///
1410