-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwp-mega-cleaner.php
More file actions
641 lines (567 loc) · 23.8 KB
/
wp-mega-cleaner.php
File metadata and controls
641 lines (567 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
<?php
/*
Plugin Name: Mega Cleaner
Plugin URI: https://github.com/Megabre/WpMegaCleaner
Description: Professional WordPress database cleaning and optimization tool. Clean unnecessary data, optimize tables, and maintain your WordPress database performance with ease.
Version: 1.2
Author: Megabre
Author URI: https://www.megabre.com
Text Domain: mega-cleaner
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
if ( ! defined( 'ABSPATH' ) ){
exit; // Exit if accessed this file directly
}
function wp_mega_cleaner_admin_menu() {
add_menu_page( "Mega Cleaner", "Mega Cleaner", "manage_options", "wp-mega-cleaner", "wp_mega_cleaner_admin", "dashicons-database" );
}
add_action( 'admin_menu', 'wp_mega_cleaner_admin_menu' );
// Add custom cron schedules
add_filter('cron_schedules', function($schedules) {
if (!isset($schedules['weekly'])) {
$schedules['weekly'] = array(
'interval' => 7 * DAY_IN_SECONDS,
'display' => __('Once Weekly', 'mega-cleaner')
);
}
if (!isset($schedules['monthly'])) {
$schedules['monthly'] = array(
'interval' => 30 * DAY_IN_SECONDS,
'display' => __('Once Monthly', 'mega-cleaner')
);
}
return $schedules;
});
function wp_mega_cleaner_enqueue_assets($hook) {
if ($hook != 'toplevel_page_wp-mega-cleaner') {
return;
}
// Using WordPress admin styles instead of external CDN
wp_enqueue_style('wp-mega-cleaner-admin', plugin_dir_url(__FILE__) . 'admin-style.css', array(), '1.2');
}
add_action('admin_enqueue_scripts', 'wp_mega_cleaner_enqueue_assets');
// Schedule automatic cleanup
add_action('wp_mega_cleaner_auto_cleanup', 'wp_mega_cleaner_run_scheduled_cleanup');
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
function easy_wp_cleaner($type){
global $wpdb;
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
switch($type){
case "revision":
$ewc_sql = "DELETE FROM $wpdb->posts WHERE post_type = 'revision'";
$wpdb->query($ewc_sql);
break;
case "draft":
$ewc_sql = "DELETE FROM $wpdb->posts WHERE post_status = 'draft'";
$wpdb->query($ewc_sql);
break;
case "autodraft":
$ewc_sql = "DELETE FROM $wpdb->posts WHERE post_status = 'auto-draft'";
$wpdb->query($ewc_sql);
break;
case "trashed_posts":
$ewc_sql = "DELETE FROM $wpdb->posts WHERE post_status = 'trash'";
$wpdb->query($ewc_sql);
break;
case "moderated":
$ewc_sql = "DELETE FROM $wpdb->comments WHERE comment_approved = '0'";
$wpdb->query($ewc_sql);
break;
case "spam":
$ewc_sql = "DELETE FROM $wpdb->comments WHERE comment_approved = 'spam'";
$wpdb->query($ewc_sql);
break;
case "trash":
$ewc_sql = "DELETE FROM $wpdb->comments WHERE comment_approved = 'trash'";
$wpdb->query($ewc_sql);
break;
case "pingbacks":
$ewc_sql = "DELETE FROM $wpdb->comments WHERE comment_type = 'pingback'";
$wpdb->query($ewc_sql);
break;
case "trackbacks":
$ewc_sql = "DELETE FROM $wpdb->comments WHERE comment_type = 'trackback'";
$wpdb->query($ewc_sql);
break;
case "postmeta":
$ewc_sql = "DELETE pm FROM $wpdb->postmeta pm LEFT JOIN $wpdb->posts wp ON wp.ID = pm.post_id WHERE wp.ID IS NULL";
$wpdb->query($ewc_sql);
break;
case "commentmeta":
$ewc_sql = "DELETE FROM $wpdb->commentmeta WHERE comment_id NOT IN (SELECT comment_id FROM $wpdb->comments)";
$wpdb->query($ewc_sql);
break;
case "usermeta":
$ewc_sql = "DELETE um FROM $wpdb->usermeta um LEFT JOIN $wpdb->users u ON u.ID = um.user_id WHERE u.ID IS NULL";
$wpdb->query($ewc_sql);
break;
case "relationships":
$ewc_sql = "DELETE FROM $wpdb->term_relationships WHERE term_taxonomy_id=1 AND object_id NOT IN (SELECT id FROM $wpdb->posts)";
$wpdb->query($ewc_sql);
break;
case "orphan_terms":
$ewc_sql = "DELETE t FROM $wpdb->terms t INNER JOIN $wpdb->term_taxonomy tt ON t.term_id = tt.term_id WHERE tt.taxonomy NOT IN ('category', 'post_tag') AND tt.count = 0";
$wpdb->query($ewc_sql);
break;
case "feed":
$ewc_sql = "DELETE FROM $wpdb->options WHERE option_name LIKE '_site_transient_browser_%' OR option_name LIKE '_site_transient_timeout_browser_%' OR option_name LIKE '_transient_feed_%' OR option_name LIKE '_transient_timeout_feed_%'";
$wpdb->query($ewc_sql);
break;
case "expired_transients":
$ewc_sql = "DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_timeout_%' AND option_value < UNIX_TIMESTAMP()";
$wpdb->query($ewc_sql);
$ewc_sql = "DELETE FROM $wpdb->options WHERE option_name LIKE '_site_transient_timeout_%' AND option_value < UNIX_TIMESTAMP()";
$wpdb->query($ewc_sql);
break;
case "all_transients":
$ewc_sql = "DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_%' OR option_name LIKE '_site_transient_%'";
$wpdb->query($ewc_sql);
break;
case "orphan_options":
$ewc_sql = "DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_%' OR option_name LIKE '_site_transient_%' OR option_name LIKE 'widget_%' OR option_name LIKE '_wc_session_%'";
$wpdb->query($ewc_sql);
break;
}
// phpcs:enable
}
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
function easy_wp_cleaner_count($type){
global $wpdb;
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
switch($type){
case "revision":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'revision'";
$count = $wpdb->get_var($ewc_sql);
break;
case "draft":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'draft'";
$count = $wpdb->get_var($ewc_sql);
break;
case "autodraft":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'auto-draft'";
$count = $wpdb->get_var($ewc_sql);
break;
case "trashed_posts":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'trash'";
$count = $wpdb->get_var($ewc_sql);
break;
case "moderated":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '0'";
$count = $wpdb->get_var($ewc_sql);
break;
case "spam":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = 'spam'";
$count = $wpdb->get_var($ewc_sql);
break;
case "trash":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = 'trash'";
$count = $wpdb->get_var($ewc_sql);
break;
case "pingbacks":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_type = 'pingback'";
$count = $wpdb->get_var($ewc_sql);
break;
case "trackbacks":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_type = 'trackback'";
$count = $wpdb->get_var($ewc_sql);
break;
case "postmeta":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->postmeta pm LEFT JOIN $wpdb->posts wp ON wp.ID = pm.post_id WHERE wp.ID IS NULL";
$count = $wpdb->get_var($ewc_sql);
break;
case "commentmeta":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->commentmeta WHERE comment_id NOT IN (SELECT comment_id FROM $wpdb->comments)";
$count = $wpdb->get_var($ewc_sql);
break;
case "usermeta":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->usermeta um LEFT JOIN $wpdb->users u ON u.ID = um.user_id WHERE u.ID IS NULL";
$count = $wpdb->get_var($ewc_sql);
break;
case "relationships":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id=1 AND object_id NOT IN (SELECT id FROM $wpdb->posts)";
$count = $wpdb->get_var($ewc_sql);
break;
case "orphan_terms":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->terms t INNER JOIN $wpdb->term_taxonomy tt ON t.term_id = tt.term_id WHERE tt.taxonomy NOT IN ('category', 'post_tag') AND tt.count = 0";
$count = $wpdb->get_var($ewc_sql);
break;
case "feed":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->options WHERE option_name LIKE '_site_transient_browser_%' OR option_name LIKE '_site_transient_timeout_browser_%' OR option_name LIKE '_transient_feed_%' OR option_name LIKE '_transient_timeout_feed_%'";
$count = $wpdb->get_var($ewc_sql);
break;
case "expired_transients":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->options WHERE option_name LIKE '_transient_timeout_%' AND option_value < UNIX_TIMESTAMP()";
$count = $wpdb->get_var($ewc_sql);
break;
case "all_transients":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->options WHERE option_name LIKE '_transient_%' OR option_name LIKE '_site_transient_%'";
$count = $wpdb->get_var($ewc_sql);
break;
case "orphan_options":
$ewc_sql = "SELECT COUNT(*) FROM $wpdb->options WHERE option_name LIKE '_transient_%' OR option_name LIKE '_site_transient_%' OR option_name LIKE 'widget_%' OR option_name LIKE '_wc_session_%'";
$count = $wpdb->get_var($ewc_sql);
break;
default:
$count = 0;
break;
}
return $count;
}
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
function easy_wp_cleaner_optimize(){
global $wpdb;
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
$ewc_sql = 'SHOW TABLE STATUS FROM `' . esc_sql(DB_NAME) . '`';
$result = $wpdb->get_results($ewc_sql);
// phpcs:enable
foreach($result as $row){
$table_name = esc_sql($row->Name);
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
$ewc_sql = 'OPTIMIZE TABLE `' . $table_name . '`';
$wpdb->query($ewc_sql);
// phpcs:enable
}
}
function wp_mega_cleaner_backup_database() {
global $wpdb;
// Safety check - only run in admin context
if (!is_admin()) {
return array('success' => false, 'message' => 'Not in admin context');
}
$backup_dir = WP_CONTENT_DIR . '/wp-mega-cleaner-backups/';
if (!file_exists($backup_dir)) {
$created = wp_mkdir_p($backup_dir);
if (!$created) {
return array('success' => false, 'message' => 'Could not create backup directory');
}
// Create .htaccess to protect directory
@file_put_contents($backup_dir . '.htaccess', "Options -Indexes\n<Files *.sql>\nOrder allow,deny\nAllow from all\n</Files>");
// Create index.php to prevent directory listing
@file_put_contents($backup_dir . 'index.php', '<?php // Silence is golden');
}
$filename = 'backup_' . DB_NAME . '_' . gmdate('Y-m-d_H-i-s') . '.sql';
$filepath = $backup_dir . $filename;
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
$tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
// phpcs:enable
$output = '';
$output .= "-- WordPress Database Backup\n";
$output .= "-- Generated by Mega Cleaner\n";
$output .= "-- Date: " . gmdate('Y-m-d H:i:s') . "\n\n";
$output .= "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\n";
$output .= "SET time_zone = \"+00:00\";\n\n";
foreach ($tables as $table) {
$table_name = $table[0];
$table_name_escaped = esc_sql($table_name);
// Get table structure
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared
$create_table = $wpdb->get_row("SHOW CREATE TABLE `$table_name_escaped`", ARRAY_N);
// phpcs:enable
$output .= "\n-- Table structure for `$table_name`\n";
$output .= "DROP TABLE IF EXISTS `$table_name`;\n";
$output .= $create_table[1] . ";\n\n";
// Get table data
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
$rows = $wpdb->get_results("SELECT * FROM `$table_name_escaped`", ARRAY_A);
// phpcs:enable
if (count($rows) > 0) {
$output .= "-- Data for table `$table_name`\n";
foreach ($rows as $row) {
$values = array();
foreach ($row as $value) {
if (is_null($value)) {
$values[] = 'NULL';
} else {
$values[] = "'" . esc_sql($value) . "'";
}
}
$output .= "INSERT INTO `$table_name` VALUES (" . implode(', ', $values) . ");\n";
}
}
}
file_put_contents($filepath, $output);
return array(
'success' => true,
'filename' => $filename,
'filepath' => $filepath,
'url' => content_url('wp-mega-cleaner-backups/' . $filename)
);
}
function wp_mega_cleaner_get_all_tables() {
global $wpdb;
// Safety check - only run in admin context
if (!is_admin()) {
return array();
}
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
$tables = $wpdb->get_results('SHOW TABLE STATUS', ARRAY_A);
// phpcs:enable
$result = array();
foreach ($tables as $table) {
$table_name = $table['Name'];
$size = ($table['Data_length'] + $table['Index_length']) / 1024;
$rows = $table['Rows'];
$result[] = array(
'name' => $table_name,
'size' => $size,
'rows' => $rows,
'engine' => isset($table['Engine']) ? $table['Engine'] : 'N/A'
);
}
return $result;
}
function wp_mega_cleaner_delete_table($table_name) {
global $wpdb;
$table_name_escaped = esc_sql($table_name);
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared
$wpdb->query("DROP TABLE IF EXISTS `$table_name_escaped`");
// phpcs:enable
return true;
}
function wp_mega_cleaner_truncate_table($table_name) {
global $wpdb;
$table_name_escaped = esc_sql($table_name);
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared
$wpdb->query("TRUNCATE TABLE `$table_name_escaped`");
// phpcs:enable
return true;
}
function wp_mega_cleaner_execute_sql($sql) {
global $wpdb;
// Security: Only allow SELECT, DELETE, UPDATE, INSERT, TRUNCATE, DROP, OPTIMIZE
$allowed_keywords = array('SELECT', 'DELETE', 'UPDATE', 'INSERT', 'TRUNCATE', 'DROP', 'OPTIMIZE', 'SHOW', 'DESCRIBE', 'EXPLAIN');
$sql_upper = strtoupper(trim($sql));
$is_allowed = false;
foreach ($allowed_keywords as $keyword) {
if (strpos($sql_upper, $keyword) === 0) {
$is_allowed = true;
break;
}
}
if (!$is_allowed) {
return array('success' => false, 'error' => 'Only SELECT, DELETE, UPDATE, INSERT, TRUNCATE, DROP, OPTIMIZE, SHOW, DESCRIBE, EXPLAIN queries are allowed.');
}
// Prevent dangerous operations on core tables
$core_tables = array($wpdb->posts, $wpdb->users, $wpdb->options, $wpdb->comments);
foreach ($core_tables as $core_table) {
if ( stripos( $sql_upper, $core_table ) !== false
&& ( stripos( $sql_upper, 'DROP' ) !== false || stripos( $sql_upper, 'TRUNCATE' ) !== false ) ) {
return array(
'success' => false,
'error' => 'Cannot DROP or TRUNCATE core WordPress tables.'
);
}
}
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
if (stripos($sql_upper, 'SELECT') === 0 || stripos($sql_upper, 'SHOW') === 0 || stripos($sql_upper, 'DESCRIBE') === 0 || stripos($sql_upper, 'EXPLAIN') === 0) {
$results = $wpdb->get_results($sql, ARRAY_A);
return array('success' => true, 'results' => $results, 'count' => count($results));
} else {
$affected = $wpdb->query($sql);
return array('success' => true, 'affected' => $affected);
}
// phpcs:enable
}
// Database Health Score Calculation
function wp_mega_cleaner_calculate_health_score() {
global $wpdb;
$score = 100;
$details = array();
// Count unnecessary data
$revisions = easy_wp_cleaner_count('revision');
$drafts = easy_wp_cleaner_count('draft');
$autodrafts = easy_wp_cleaner_count('autodraft');
$trashed_posts = easy_wp_cleaner_count('trashed_posts');
$spam = easy_wp_cleaner_count('spam');
$trash_comments = easy_wp_cleaner_count('trash');
$orphan_postmeta = easy_wp_cleaner_count('postmeta');
$orphan_commentmeta = easy_wp_cleaner_count('commentmeta');
$orphan_usermeta = easy_wp_cleaner_count('usermeta');
$expired_transients = easy_wp_cleaner_count('expired_transients');
$total_unnecessary = $revisions + $drafts + $autodrafts + $trashed_posts + $spam + $trash_comments +
$orphan_postmeta + $orphan_commentmeta + $orphan_usermeta + $expired_transients;
// Calculate score (penalty for unnecessary data)
$penalty = min(50, ($total_unnecessary / 1000) * 5); // Max 50 point penalty
$score -= $penalty;
// Check database size
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
$tables = $wpdb->get_results('SHOW TABLE STATUS', ARRAY_A);
// phpcs:enable
$total_size = 0;
foreach ($tables as $table) {
$total_size += ($table['Data_length'] + $table['Index_length']) / 1024 / 1024; // MB
}
// Large database penalty (over 500MB)
if ($total_size > 500) {
$size_penalty = min(20, (($total_size - 500) / 100) * 2);
$score -= $size_penalty;
}
$score = max(0, min(100, round($score)));
$details = array(
'score' => $score,
'total_unnecessary' => $total_unnecessary,
'database_size_mb' => round($total_size, 2),
'breakdown' => array(
'revisions' => $revisions,
'drafts' => $drafts,
'autodrafts' => $autodrafts,
'trashed_posts' => $trashed_posts,
'spam' => $spam,
'trash_comments' => $trash_comments,
'orphan_postmeta' => $orphan_postmeta,
'orphan_commentmeta' => $orphan_commentmeta,
'orphan_usermeta' => $orphan_usermeta,
'expired_transients' => $expired_transients
)
);
return $details;
}
// Get preview data before cleaning
function wp_mega_cleaner_get_preview($type) {
global $wpdb;
$preview = array();
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
switch($type) {
case 'revision':
$preview = $wpdb->get_results("SELECT ID, post_title, post_date FROM $wpdb->posts WHERE post_type = 'revision' ORDER BY post_date DESC LIMIT 20", ARRAY_A);
break;
case 'draft':
$preview = $wpdb->get_results("SELECT ID, post_title, post_date FROM $wpdb->posts WHERE post_status = 'draft' ORDER BY post_date DESC LIMIT 20", ARRAY_A);
break;
case 'spam':
$preview = $wpdb->get_results("SELECT comment_ID, comment_author, comment_date FROM $wpdb->comments WHERE comment_approved = 'spam' ORDER BY comment_date DESC LIMIT 20", ARRAY_A);
break;
}
// phpcs:enable
return $preview;
}
// Log cleaning operation
function wp_mega_cleaner_log_operation($operation, $count, $details = '') {
$log_entry = array(
'timestamp' => current_time('mysql'),
'operation' => $operation,
'count' => $count,
'details' => $details
);
$logs = get_option('wp_mega_cleaner_logs', array());
$logs[] = $log_entry;
// Keep only last 100 logs
if (count($logs) > 100) {
$logs = array_slice($logs, -100);
}
update_option('wp_mega_cleaner_logs', $logs);
}
// Get cleaning reports
function wp_mega_cleaner_get_reports($limit = 20) {
$logs = get_option('wp_mega_cleaner_logs', array());
return array_slice(array_reverse($logs), 0, $limit);
}
// Schedule automatic cleanup
function wp_mega_cleaner_schedule_cleanup($frequency, $operations = array()) {
$schedules = get_option('wp_mega_cleaner_schedules', array());
$schedule_id = uniqid();
$schedules[$schedule_id] = array(
'frequency' => $frequency, // daily, weekly, monthly
'operations' => $operations,
'created' => current_time('mysql'),
'next_run' => wp_mega_cleaner_calculate_next_run($frequency)
);
update_option('wp_mega_cleaner_schedules', $schedules);
// Schedule WordPress cron
if (!wp_next_scheduled('wp_mega_cleaner_auto_cleanup')) {
wp_schedule_event(time(), $frequency, 'wp_mega_cleaner_auto_cleanup');
}
return $schedule_id;
}
// Calculate next run time
function wp_mega_cleaner_calculate_next_run($frequency) {
switch($frequency) {
case 'daily':
return gmdate('Y-m-d H:i:s', strtotime('+1 day'));
case 'weekly':
return gmdate('Y-m-d H:i:s', strtotime('+1 week'));
case 'monthly':
return gmdate('Y-m-d H:i:s', strtotime('+1 month'));
default:
return gmdate('Y-m-d H:i:s', strtotime('+1 day'));
}
}
// Auto cleanup cron handler
function wp_mega_cleaner_run_scheduled_cleanup() {
$schedules = get_option('wp_mega_cleaner_schedules', array());
foreach ($schedules as $schedule_id => $schedule) {
if (strtotime($schedule['next_run']) <= time()) {
// Run scheduled operations
foreach ($schedule['operations'] as $operation) {
$count_before = easy_wp_cleaner_count($operation);
easy_wp_cleaner($operation);
$count_after = easy_wp_cleaner_count($operation);
wp_mega_cleaner_log_operation(
$operation . ' (scheduled)',
$count_before - $count_after,
'Scheduled cleanup: ' . $schedule['frequency']
);
}
// Update next run time
$schedules[$schedule_id]['next_run'] = wp_mega_cleaner_calculate_next_run($schedule['frequency']);
$schedules[$schedule_id]['last_run'] = current_time('mysql');
}
}
update_option('wp_mega_cleaner_schedules', $schedules);
}
// WooCommerce specific cleaning
function wp_mega_cleaner_woocommerce_cleanup() {
global $wpdb;
$cleaned = array();
// Clean expired sessions
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
$sessions = $wpdb->get_results("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '_wc_session_%'", ARRAY_A);
// phpcs:enable
$session_count = count($sessions);
if ($session_count > 0) {
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
$wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_wc_session_%'");
// phpcs:enable
$cleaned['sessions'] = $session_count;
}
// Clean orphaned order meta (orphaned postmeta for non-existent posts)
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
$order_meta = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->postmeta pm
LEFT JOIN $wpdb->posts p ON p.ID = pm.post_id
WHERE p.ID IS NULL");
if ($order_meta > 0) {
$wpdb->query("DELETE pm FROM $wpdb->postmeta pm
LEFT JOIN $wpdb->posts p ON p.ID = pm.post_id
WHERE p.ID IS NULL");
$cleaned['order_meta'] = $order_meta;
}
// phpcs:enable
return $cleaned;
}
function wp_mega_cleaner_admin() {
// Check permissions
if (!current_user_can('manage_options')) {
wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'mega-cleaner'));
}
// Only include admin file when actually on the admin page
// Multiple checks to prevent execution during plugin activation
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is not form processing, just a page check
if ( ! isset( $_GET['page'] ) || sanitize_text_field( wp_unslash( $_GET['page'] ) ) !== 'wp-mega-cleaner' ) {
return;
}
// Additional safety: ensure we're in admin context
if (!is_admin()) {
return;
}
$admin_file = plugin_dir_path(__FILE__) . 'wp-mega-cleaner-admin.php';
if (file_exists($admin_file)) {
include($admin_file);
} else {
echo '<div class="wrap"><h1>Mega Cleaner</h1><p>Admin file not found.</p></div>';
}
}