PluginProbe
LWS Tools / 2.6
LWS Tools v2.6
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, at lws-tools.php

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