-
Notifications
You must be signed in to change notification settings - Fork 0
/
camelbot
executable file
·5016 lines (4730 loc) · 166 KB
/
camelbot
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
# author: seth
# description: a wikibot
use strict;
use warnings;
BEGIN{
# used to check whether this script is running on a labs server or somewhere else
# on labs e.g. Tk is disabled.
our $_running_on_labs = (-e '/data/project/camelbot/perl/lib');
}
our $_running_on_labs;
use if $_running_on_labs, lib => qw(/data/project/camelbot/perl/lib);
use Carp; # better output on errors for debugging purposes
use Data::Dumper; # for debugging purposes
use File::Path qw(make_path); # create directories
use File::Slurp qw(slurp write_file); # read/write files
use Getopt::Long qw(:config bundling); # cli params
use Pod::Usage; # cli params help
use POSIX qw/strftime/; # format timestamp
# packages: CamelBot, CamelBotRC, CamelBotIRC
#
# functions
# =========
# global functions
# -------------------
# sub syntaxCheck
# parse cli params
#
# CamelBot: mediawiki functions
# -------------------
# sub new
# constructor
#
# sub api_cont
# use MediaWiki::API using 'continue' for a loop
#
# sub api_simple
# use MediaWiki::API and catch errors
#
# sub archive_ext_links
# find all links in given text ref and call saving procedure on archive.org
#
# sub cat_add
# adds a given bunch of pages to a given category by adding [[category:new]] at
# the end
#
# sub cat_rename
# moves a category and replaces all [[category:old]] by [[category:new]]
#
# sub check_external_link
# given two successive parts $a1, $a2 of a string $a this function checks,
# whether second part of string $a2 is an url with http status 200. the first
# part of the string $a1 is used to detect the end of url in part two $a2.
#
# sub cleanup_wiki_page
# standard cleaning up
#
# sub convert_ns
# converts namespace id to its name or vice versa
#
# sub _db_init
# init db connection
#
# sub _db_query
# send query to db
#
# sub _db_simplequery
# wrapper for simple db queries
#
# sub db_cat_of_dead_monitoring
# use db to monitor added categories of dead people in an endless loop
#
# sub db_extlinks_monitoring
# use db to monitor external links in an endless loop
#
# sub db_fetch_externallinks
# use db to get external links for a given range of el_ids of el-table
#
# sub db_fetch_pages_of_categories_of_the_dead
# use db to get pages that are contained in a category concerning dead people
#
# sub db_fetch_recentchanges
# use db to get recent changes for a given time period
#
# sub db_fetch_sbl_log
# use db to get all entries of the sbl log of blocked edits; optional
# (but recommended) given a regexp for a searched url
#
# sub db_rc_monitoring
# use db to monitor recent changes in an endless loop
#
# sub db_table2array_of_hash
# converts a db_table (fetchall_arrayref) to a array where each element is a
# hashref with {'rowname0'=>'content', 'rowname1'=>'content', ...}
#
# sub delete_marked_pages
# delete pages that are in a special category
#
# sub delete_wiki_page
# deletes a wiki page
#
# sub download_css
# download a css file (not implemented yet: and all files loaded inside css)
#
# sub download_files
# downloads files from the wiki
#
# sub download_pages_by_prefix
# downloads all pages with the same prefix
#
# sub get_abuse_filter_info
# return some info on abuse filter rules
#
# sub get_all_pages
# return all pages that match a given pattern
#
# sub get_diff
# a more detailed version of MediaWiki::Bot::diff
#
# sub get_extlinks_via_db
# get ref to an array of hashes, where each hash represents an external link and
# one page where it's used
#
# sub get_page_info
# get information about a given page (or given pages)
#
# sub get_pages
# get page titles by search or explicitely
#
# sub get_pages_content
# get content of wikipages
#
# sub get_pages_by_prefix
# get all pages and their latest content by prefix
#
# sub get_pages_of_cat_of_dead_via_db
# get ref to an array of hashes, where each hash represents a category and
# one page where it's used
#
# sub get_rc_via_db
# get ref to an array of hashes, where each hash represents a recent change
#
# sub get_namespace_id
# return namespace id of a given page
#
# sub get_sbl_entries
# get all sbl entries of a given wiki
#
# sub get_tables_from_wikitext
# tries to return all tables from a given wikitext. (this will fail on tables in
# tables!)
#
# sub get_date_iso
# get date as formatted string "%Y-%m-%d" from given (or current) unix timestamp
#
# sub get_time_iso
# get date and time as formatted string "%Y-%m-%d%H:%M:%S" from given (or current)
# unix timestamp
#
# sub get_time_iso_
# get date and time as formatted string "%Y-%m-%d %H:%M:%S" from given
# (or current) unix timestamp
#
# sub get_user_contribs
# get list of pages edited by user
#
# sub get_wikitable_ascii_col_widths
# get col widths defined by ascii art
#
# sub handle_cat_dead
# given a bunch of categories of dead people, this function updates a maintenance
# list
#
# sub handle_extlinks
# given a bunch of external links, this function calls functions like
# archive_ext_links
#
# sub handle_rc_pages
# major function for handling of recent changes of short-term and mid-term
#
# sub _handle_api_error
# just a centralized short version of mw api error handling
#
# sub is_allowed
# checks whether bot-template is placed on a page and forbids editing
#
# sub link_replacement
# replaces links in wiki pages
#
# sub login
# logs a bot in to some wiki
#
# sub newest_post_info
# \return hash ref with thread, author and date of newest post
# \param[in] $wikitext content of a talk page
#
# sub notifier
# notify on user or pre-defined wiki pages, if particular edits occur
#
# sub parse_wikitext
# use mediawiki-api of a wiki to parse wikitext
#
# sub parse_page
# use mediawiki-api of a wiki to get a parsed wikipage
#
# sub parse_irc_rc
# parse recent changes told by bot via irc. return ref to hash with content.
#
# sub php_code_unused
# searches for all links in a given piece of wikitext
#
# sub post_process_html
# clean up html that was generated by parsing wikitext
#
# sub rebuild_table
# builds a table and pastes it to a section (overwriting the section)
#
# sub save_wiki_page
# \brief saves a wiki page
# \param[in] $bot a logged in MediaWiki::Bot
# \param[in] $page_utf8 page name in utf8
# \param[in] $summary an edit summary (without 'Bot: ') that will be used when
# saving
# \param[in] $text a ref to the new wikitext
# \param[in] $orig_text a ref to the old wikitext
# \param[in] $time_stack a ref to an array that is used for low frequency editing
# \param[in] $user_answer a ref to a string containing '' (nothing) or 'y' to
# save the last user's answer
#
# sub search_sbl_blocked_log
# search the list of blocked edits (blocked by sbl) for a given url-regexp
#
# sub search_sbl_attempts
# search list(s) of blocked edits (blocked by sbl)
#
# sub table2wikitext
# converts a special table hash ref to wikitext
#
# sub table_body2array
# convert wiki table body to perl ref to 2d array
#
# sub test_and_replace
# tests whether a regexp matches and replaces it. give some verbose output.
# checks urls, breaks if http status != 200
# returns number of replacements
#
# sub text_replacement
# replaces text in wiki pages
#
# sub time_management
# forces that only x edits per minute are done
#
# sub title2filename
# converts a page title to a filename
#
# sub title2url
# convert article name to url
#
# sub title2url_part
# convert article name to part of url with article name
# 'w t f' => 'w_t_f'
#
# sub update_edit_filter_index
# update page with index of present threads about edit filters
#
# sub update_maintenance_lists_build_table
# build a table for update_maintenance_lists
#
# sub update_maintenance_lists
# update some maintenance lists on given edit
#
# sub upload_file
# uploads a file to the wiki
#
# sub url2title
# convert url to article name
#
# sub wikitableHeader2array
# convert wiki table header to perl ref to 1d array
#
# sub wikitable2array
# convert wiki table to perl ref to hash, containing a header and a body
# containing a 2d array
#
# CamelBot: other functions
# ---------------
# sub decode_html_entities
# decode >, <, and & in-place
#
# sub get_http_content
# return content of a given url
#
# sub get_http_status
# return http status code of a given url
#
# sub msg
# print message to stdout
#
# sub num_unique_elem
# return number of elements, without counting double entries
#
# sub read_file_binary
# read a file binary
#
# sub show_diff
# shows a diff via Tk
#
# sub write_csv
# write a 2d-array (= ref to array of refs to arrays) to a csv file
# global vars
$main::VERSION = '1.54.0'; # 2017-05-08
# avoid 'wide character' warning
binmode STDOUT, ":encoding(UTF-8)";
# Carp::Always
sub _die {
die @_ if ref($_[0]);
if($_[-1] =~ /\n$/s){ # $_ is a read-only value
my $arg = pop @_;
$arg =~ s/.*\K at .*? line .*?\n$//s;
push @_, $arg;
}
unshift @_, strftime("%Y-%m-%d %H:%M:%S ", gmtime());
die &Carp::longmess;
}
sub _warn {
if($_[-1] =~ /\n$/s){ # $_ is a read-only value
my $arg = pop @_;
$arg =~ s/.*\K at .*? line .*?\n$//s;
push @_, $arg;
}
unshift @_, strftime("%Y-%m-%d %H:%M:%S ", gmtime());
warn &Carp::longmess;
}
$SIG{__DIE__} = \&_die;
$SIG{__WARN__} = \&_warn;
sub syntaxCheck{
my %params = ( # default cli params
'archive-ext-links' => undef, # save external links from id till id, using db
'cat-add' => 0, # add pages to a category
'cat-change' => 0, # cat change
'cat-dead' => 0, # cat of the dead
'clean-up' => undef, # clean-up
'db-access' => 'replica.my.cnf', # filename with database access data
'diff-from' => undef, # page or revision id to get a diff from
'diff-to' => undef, # version to diff to
'delete' => 0, # delete pages
'download-by-prefix' => undef, # download pages by prefix
'file' => undef, # a file for text-replacement
'get-page' => undef, # get a page
'http-status' => undef, # check reachability of url
'link-replacement' => 0, # link replacing
'minor' => 1, # mark as minor
'parse' => undef, # wikitext-file to parse
'search-pattern' => undef, # text replacing regexp pattern
'rc-monitoring' => undef, # start rc monitoring via irc or db
'use-eval' => 0, # use eval on text-replacement
'save-as-html' => undef, # download pages and save as html pages
'search' => undef, # search via api
'search-sbl-attempts' => undef, # search the sbl log of blocked edits
'section' => undef, # section in wikipage
'text-replacement' => undef, # text replacing
'dest' => undef, # destination filename
'update-editfilter-index' => 0,# update edit filter index in w:de
'upload' => 0, # upload a file
'usercontribs' => 0, # fetch user contributions
'username' => $ENV{'USER'}, # user name
'source' => undef, # source filename
'summary' => undef, # summary/description
'wikipage' => undef, # wikipage (single page)
'wikipages' => undef, # wikipages (regexp)
'test' => 0, # show result only (without renaming)
'verbose' => 1, # trace; grade of verbosity
'version' => 0, # diplay version and exit
);
pod2usage(-exitval => 2) if @ARGV == 0;
GetOptions(\%params,
'archive-ext-links=s',
'cat-add',
'cat-change|c',
'cat-dead',
'clean-up',
'db-access=s',
'diff-from=s',
'diff-to=s',
'delete',
'download-by-prefix=s',
'file=s',
'get-page|g',
'http-status=s',
'irc' => sub { $params{'rc-monitoring'} = 'irc';},
'link-replacement|l',
'minor!',
'parse=s',
'rc-monitoring=s',
'use-eval',
'save-as-html=s',
'search=s',
'search-pattern=s',
'search-sbl-attempts=s',
'section=s',
'text-replacement',
'dest|udest=s',
'update-editfilter-index',
'upload',
'usercontribs|usercontributions',
'username=s',
'source|usource=s',
'summary|usummary=s',
'wikipage=s',
'wikipages=s',
'test|t',
'silent|quiet|q' => sub { $params{'verbose'} = 0;},
'very-verbose' => sub { $params{'verbose'} = 2;},
'verbose|v:+',
# auto_version will not auto make use of 'V'
'version|V' => sub { Getopt::Long::VersionMessage();},
# auto_help will not auto make use of 'h'
'help|?|h' => sub { Getopt::Long::HelpMessage(
-verbose => 99,
-sections => 'NAME|SYNOPSIS|EXAMPLES'
);
},
'man' => sub { pod2usage(-exitval => 0, -verbose => 2);},
) or pod2usage(-exitval => 2);
$params{'verbose'} = 1 unless exists $params{'verbose'};
my @additional_params = (0, 0); # number of additional params (min, max);
if(@ARGV < $additional_params[0] or
($additional_params[1] != -1 and @ARGV > $additional_params[1])
){
if($additional_params[0] == $additional_params[1]){
print "error: number of arguments must be exactly $additional_params[0]," .
" but is " . (0 + @ARGV) . ".\n";
}else{
print "error: number of arguments must be at least $additional_params[0]" .
" and at most " .
($additional_params[1] == -1 ? 'inf' : $additional_params[1]) .
", but is " . (0 + @ARGV) . ".\n";
}
print "please use -h for help\n";
exit 2;
}
return \%params;
}
{
package CamelBot;
use if $_running_on_labs, lib => qw(/data/project/camelbot/perl/lib);
use Data::Dumper; # for debugging purposes
use DBI; # db connection
use File::Slurp qw(write_file); # read/write files
use IPC::Run; # used for tidy
use LWP::UserAgent; # fast, small web browser
use MediaWiki::Bot; # bot for mediawiki, uses mediawiki-api-interface
use POSIX qw/strftime/; # format timestamp
my %_loaded_mod;
$_loaded_mod{'Term::ReadKey'} = eval{
require Term::ReadKey; # used for user input
Term::ReadKey->import();
1;
};
$_loaded_mod{'Text::Diff'} = eval{
require Text::Diff; # diff
Text::Diff->import();
1;
};
$_loaded_mod{'Tk::DiffText'} = eval{
require Tk::DiffText; # graphical diff tool
Tk::DiffText->import();
1;
};
use Time::Local; # timegm
$_loaded_mod{'URI::Escape'} = eval{
require URI::Escape; # uri_escape, uri_unescape
URI::Escape->import();
1;
};
sub new{
my $class = shift;
my $params = shift;
my $self = bless {
# 0 = don't ask user; 1 = ask user for every action
'ask_user' => $params->{'ask_user'} // 0,
'db' => {'file' => $params->{'db_access'}},
'host' => $params->{'host'} // 'de.wikipedia.org',
'rel_url_path' => $params->{'rel_url_path'} // 'w',
# maximum number of edits per minute (-1 = inf)
'max_edits_per_min' => $params->{'max_edits_per_min'} // 5,
'minor' => $params->{'minor'} // 1, # 0 = non-minor; 1 = minor
'mw_api' => undef, # instance of MediaWiki::API
'mw_apiurl' => undef, # url of mw_api
'mw_bot' => undef, # instance of MediaWiki::Bot
#'mw_password' => $mw_password, # not needed permanently
'mw_username' => $params->{'mw_username'},
're_editfilter' => qr/^Wikipedia:Bearbeitungsfilter\/
(?:\d+|Antr\xe4ge$|Fehlerkennungen$|(?:Regelp|P)r\xfcfung$)/x,
're_url_class' => qr/[^\]\[<>"'\x00-\x20\x7F)]|\)(?!\s)/,
're_url_rear' => qr/ # no trailing points
(?:[^\]\[<>"'\x00-\x20\x7F)]|\)(?!\s))*
(?:[^\]\[<>"'\x00-\x20\x7F).]|\)(?!\s))/x,
'maintenance' => {}, # will be set in separate function
# 0 = don't show diff; 1 = show a diff, 2 = gui
'showdiff' => $params->{'showdiff'} // 0,
# 0 = do real edits; 1 = simulate only
'simulation' => $params->{'simulation'} // 0,
'time_stack' => [], # needed for edit/min constraint
# user answer initially is "no"
'user_answer' => $params->{'user_answer'} // '',
'verbosity' => $params->{'verbosity'} // 1,
'wm_proj_type' => undef, # e.g. wikipedia
'wm_proj' => undef, # e.g. dewiki
'wm_lang' => undef, # e.g. de
'cliparams' => $params->{'cliparams'},
}, $class;
$self->refresh_maintenance_params();
$self->login($params->{'mw_password'}); # may change mw_username!
return $self;
}
sub DESTROY{
my $self = shift;
$self->{'db'}->{'handle'}->disconnect if defined $self->{'db'}->{'handle'};
}
sub api_cont{
my $self = shift;
my $query = shift; # may be modified in this function
my $mw_options = shift;
my $die_on_error = shift // 1;
my $finished = 0;
$query->{'continue'} = '' unless exists $query->{'continue'};
my $api_result = $self->api_simple($query, $mw_options, $die_on_error);
if(defined $api_result->{'continue'}){
while(my ($k, $v) = each(%{$api_result->{'continue'}})){
$query->{$k} = $v;
}
}else{
$finished = 1;
}
#if(defined $api_result->{'batchcomplete'}){
# print Dumper $api_result->{'batchcomplete'};
#}
return ($api_result, $finished);
}
sub api_simple{
my $self = shift;
my $query = shift;
my $mw_options = shift;
my $die_on_error = shift // 1;
$self->msg(3, Dumper($query));
my $api_result = $self->{'mw_api'}->api($query, $mw_options);
unless(defined $api_result){
my $caller_increment = 1;
$self->_handle_api_error($caller_increment);
die if $die_on_error;
}
$self->msg(3, Dumper($api_result)) if defined $api_result;
return $api_result;
}
sub archive_ext_links{
my $self = shift;
my $urls = shift;
my $wp_page = shift // '';
my $wp_page_url = $self->title2url($wp_page);
# TODO: 1. fill in params; 2. test
my $email_address = '';
map {
my $encoded_url = $self->uri_escaper($_);
my $url = 'https://web.archive.org/save/' . $_;
#$self->msg(2, $url);
$self->check_external_link(\'', \$url);
#$url = "http://www.webcitation.org/archive?email=$email_address&source=$wp_page_url&url=$encoded_url";
#$self->msg(2, $url);
#$self->check_external_link(\'', \$url);
} grep {!/^https?:\/\/(?:[a-z]+\.)?(?:archive|webcitation)\.org/} @$urls;
return 1;
}
sub cat_add{
my $self = shift;
my $pages = shift;
my $cat = shift;
utf8::decode($cat);
my $summary = '+cat';
my $cat_first = lc substr($cat, 0, 1);
my $cat_tail = substr($cat, 1);
$self->msg(1, "start cat adding...");
for my $page (@$pages){
$self->msg(1, "page = $page");
my $page_utf8 = $page;
utf8::decode($page_utf8);
my $text = $self->{'mw_bot'}->get_text($page_utf8);
next unless $self->is_allowed(\$text, $page);
# page is already in cat
next if $text =~ /\[\[[Cc]ategory:(?i:\Q$cat_first\E)\Q$cat_tail\E\]\]/;
$self->msg(1, "add page to cat.");
# add page to cat
my $text_bak = $text;
if($text =~ /\[\[[cC]ategory:/){
$text =~ s/.*\K(?=\[\[[cC]ategory:)/[[category:$cat]]\n/g;
}else{
$text =~ s/\s*$/\n\n[[category:$cat]]/g;
}
$self->time_management();
$self->save_wiki_page($page_utf8, $summary, \$text, \$text_bak);
}
return 1;
}
sub cat_rename{
my $self = shift;
my $old_cat = shift;
my $new_cat = shift;
utf8::decode($old_cat);
utf8::decode($new_cat);
my $summary = 'cat change';
my $old_cat_first = lc substr($old_cat, 0, 1);
my $old_cat_tail = substr($old_cat, 1);
$self->msg(1, "start cat renaming...");
# get pages in (old) category
my @pages = $self->{'mw_bot'}->get_pages_in_category("Category:$old_cat");
$self->msg(1, 'found '.@pages." pages:");
# for all pages in category change category
for my $page (@pages){
$self->msg(1, "page = $page");
my $text = $self->{'mw_bot'}->get_text($page);
next unless $self->is_allowed(\$text, $page);
my $text_bak = $text;
$text =~ s/
\[\[[cC]ategory:((?i:\Q$old_cat_first\E)\Q$old_cat_tail\E)\]\]
/[[category:$new_cat]]/gx;
if($text ne $text_bak){
$self->msg(1, "changing cat: $1 -> $new_cat");
$self->time_management();
$self->save_wiki_page($page, $summary, \$text, \$text_bak);
}
}
}
sub check_external_link{
my $self = shift;
my $pretext = shift;
my $urlstring = shift;
my $ok = 1;
if($$urlstring =~ /^https?:\/\//){
my $url = $$urlstring; #for vim: { {
if($$pretext =~ /url\s*=\s*$/ and $$urlstring =~ /^([^|}]+)[|}]/){
$url = $1;
}
my $response_code = $self->get_http_status($url);
$self->msg(1, " status of '$url': $response_code");
$ok = 0 if $response_code != 200;
}
return $ok;
}
sub cleanup_wiki_page{
my $self = shift;
my $text = shift; # ref to string
my $page = shift;
my $changes = {};
my $use_eval_in_repl = 1;
if(defined $text and ref $text eq 'SCALAR' and defined $$text){
# == link fixes ==
# === double protocol ===
$changes->{'double protocol'} = $self->test_and_replace($text,
qr/(?:(?:http:|(?<=\[))\/\/)+(https?):?\/\/($self->{'re_url_rear'})/m,
'"$1:\/\/$2"', $use_eval_in_repl);
# === missing/too much brackets ===
# <ref>[http://www.example.org</ref>
# was '"$1\x5b$2]$3"' until 2015-07-18, but deleting of such brackets seems more convenient
$changes->{'wrong left bracket'} = $self->test_and_replace($text,
qr/(<ref>)\s*\[\s*(https?:\/\/$self->{'re_url_rear'})[\s.]*+(<\/ref>)/m,
'"$1$2$3"', $use_eval_in_repl);
# <ref>http://www.example.org]</ref>
$changes->{'wrong right bracket'} = $self->test_and_replace($text,
qr/(<ref>)\s*(https?:\/\/$self->{'re_url_rear'})\s*+]\s*(<\/ref>)/m,
'"$1$2$3"', $use_eval_in_repl); # see above
# === checking of spelling/typography ===
$changes->{'abk..'} = $self->test_and_replace($text,
qr/ (?:Chr|e\.(?: | )?V|ff|Jh|usw)\.\K\. /m,
' ', !$use_eval_in_repl);
$changes->{'abk.. in links'} = $self->test_and_replace($text,
qr/\.\]\]\K\./m,
'', !$use_eval_in_repl);
$changes->{'%ig'} = $self->test_and_replace($text,
qr/[0-9]\K(?: | )?%-ig/m,
'%ig', !$use_eval_in_repl);
$changes->{'komma vor "sondern"'} = $self->test_and_replace($text,
qr/mehr sondern/m,
'mehr, sondern', !$use_eval_in_repl);
$changes->{'°C ([[WP:SVZ]])'} = $self->test_and_replace($text,
qr/°\K(?: | | )C/m,
'C', !$use_eval_in_repl);
#$changes->{"whitespace nach gestorben-symbol"} = $self->test_and_replace($text,
# qr/\x{2020}\K(?! | )/m,
# '" "');
$changes->{"whitespace vor ref-tag"} = $self->test_and_replace($text,
qr/(?<![|=°])(?<!<\/sup>)(?<!\}\})(?: |&(?:nbsp|thinsp);)(?=<ref\b)/m,
'', !$use_eval_in_repl); # \n will lead to false positives # vim: {{
# + }} because of false positive: //de.wikipedia.org/w/index.php?title=Griechische_Staatsschuldenkrise&diff=143759791&oldid=143757358
# === specific domains ===
# see [https://de.wikipedia.org/w/index.php?title=MediaWiki_Diskussion:
# Spam-blacklist&oldid=136131974#
# www.denkmalschutz.de_.22.26cHash.3D.5B0-9a-f.5D.2B.22_entfernen]
$changes->{'lf denkmalschutz.de'} = $self->test_and_replace($text,
qr/http:\/\/www.denkmalschutz.de\/$self->{'re_url_class'}+?\K
&cHash=[0-9a-f]+/mx,
'', !$use_eval_in_repl);
# == optional fixes==
if(scalar(grep {$_ > 0} values %$changes) > 0){
# === unicode character 0x200e before categories ===
$changes->{'u200e'} = $self->test_and_replace($text,
qr/\x{200e}(?=\]\]|\}\}|\|)/m,
'', !$use_eval_in_repl);
# === superfluous space in cats ===
$changes->{'superfluous space in cats'} = $self->test_and_replace($text,
qr/\[\[Kategorie:\K +/m,
'', !$use_eval_in_repl);
# === superfluous declaration as tamplate via keyword ===
$changes->{'superfluous "template"'} = $self->test_and_replace($text,
qr/\{\{\K[Vv]orlage:/m,
'', !$use_eval_in_repl);
# === wrong html br-tag ===
$changes->{'wrong br-tag'} = $self->test_and_replace($text,
qr/<(?:[\/\\]br\s*|br[.\\])>/m,
'<br />', !$use_eval_in_repl);
# === superfluous br-tag ===
$changes->{'superfluous br-tag'} = $self->test_and_replace($text,
qr/^\*.*\K<(?:[\/\\]br\s*|br ?[.\\\/])> *$/m,
'', !$use_eval_in_repl);
# === wrong white space before '%' ===
$changes->{'white space before %; see [[WP:SVZ]]'} = $self->test_and_replace($text,
qr/&(?:nbsp|thinsp|#x202f|#8239);%/m,
' %', !$use_eval_in_repl);
# === technically superfluous external links ===
if($page ne 'Hypertext Transfer Protocol Secure' and
$page ne 'Hypertext_Transfer_Protocol_Secure'){
$changes->{'lf pseudo-external links'} = $self->test_and_replace($text,
qr/(?<!<ref>)\[{1,2}
(https?:\/\/$self->{'wm_lang'}\.$self->{'wm_proj_type'}\.org\/wiki\/
[^\]|\x20\x23?]++
(?:\x23(?!mediaviewer)[^\]|\x20?]+)?)\s
([^\]]+)
\]{1,2}/mx,
'"[[".$self->url2title($1).($self->url2title($1) eq $2 ? "" : "|$2")."]]"',
$use_eval_in_repl
);
}
# === redundant internal link description ===
$changes->{'redundant link description'} = $self->test_and_replace($text,
qr/\[\[\s*+([^|\]\[]+\S)\s*\|\s*+\1\s*+\]\]/m,
'"[[$1]]"', $use_eval_in_repl);
# === zeros ===
$changes->{'zeros'} = $self->test_and_replace($text,
qr/((?:\{\{0\}\}){2,})/m,
'"{{0|" . ("0"x(length($1)/5)) . "}}"', $use_eval_in_repl);
}
# === tests ===
#$self->test_and_replace($text,
# qr/seth sagt: hallo camelbot!/m,
# 'camelbot sagt: hallo seth!', !$use_eval_in_repl);
}else{
$self->msg(0, '$$text is not defined', 'warning');
return $changes;
}
my $summary = (keys %$changes > 0) ? 'kleinere korrekturen (' .
(join ', ', grep {$changes->{$_} > 0} keys %$changes) .
'), siehe [[user:CamelBot]].' : '';
return ($changes, $summary);
}
sub convert_ns{
my $self = shift;
my $ns = shift;
my $converted;
unless(defined $self->{'namespaces'}){
# get namespaces
$self->{'namespaces'} = {$self->{'mw_bot'}->get_namespace_names()};
my $res = $self->api_simple({
'action' => 'query',
'meta' => 'siteinfo',
'siprop' => 'namespacealiases',
});
$self->{'namespacealiases'} = {
map {
($_->{'*'} => $_->{'id'});
} @{$res->{'query'}->{'namespacealiases'}}
};
}
if($ns =~ /^[0-9]+$/){
$converted = $self->{'namespaces'}->{$ns};
}else{
my %rev_ns = reverse(%{$self->{'namespaces'}});
$converted = $rev_ns{$ns} // $self->{'namespacealiases'}->{$ns};
}
$converted = 0 unless defined $converted;
return $converted;
}
sub _db_init{
my $self = shift;
my $proj = shift // $self->{'wm_proj'};
unless(defined $proj){
$self->msg(0, '$proj is not defined', 'error');
return 0;
}
if(defined $self->{'db'}->{'handle'} and
defined $self->{'db'}->{'proj'} and
$self->{'db'}->{'proj'} eq $proj){
# don't re-read db_file or reconnect, if still connected
return 2;
}else{
# check db conn file
unless(-e $self->{'db'}->{'file'}){
$self->msg(1, " db conn file: '$self->{'db'}->{'file'}' does not seem to exist.", 'warning');
if(substr($self->{'db'}->{'file'}, 0, 1) ne '/'){
$self->{'db'}->{'file'} = $ENV{'HOME'} . '/' . $self->{'db'}->{'file'};
if(-e $self->{'db'}->{'file'}){
$self->msg(1, " using db conn file: '$self->{'db'}->{'file'}'.");
}else{
# warning will appear soon
# $self->msg(0, " db conn file does not seem to exist.", 'error');
}
}
}
# db connection parameters
$self->{'db'}->{'host'} = $proj . '.labsdb';
#$self->{'db'}->{'host'} = 's1.labsdb';
$self->{'db'}->{'name'} = $proj . '_p';
$self->{'db'}->{'port'} = '3306';
$self->{'db'}->{'user'} = '';
$self->{'db'}->{'pw'} = '';
my $opened = open(my $INFILE, '<', $self->{'db'}->{'file'});
unless($opened){
$self->msg(0, "could not read db conn file: $!", 'error');
return 0;
}
while(my $line = <$INFILE>){
$self->{'db'}->{'user'} = $1 if $line =~ /^\s*user='(.*)'/;
$self->{'db'}->{'pw'} = $1 if $line =~ /^\s*password='(.*)'/;
$self->{'db'}->{'port'} = $1 if $line =~ /^\s*port='?(.*?)'?\s*(?:#.*)?\n/;
$self->{'db'}->{'host'} = $1 if $line =~ /^\s*host='?(.*?)'?\s*(?:#.*)?\n/;
}
close($INFILE);
$self->msg(2, 'connect to db: ' . Dumper($self->{'db'}));
$self->{'db'}->{'handle'} = DBI->connect( # db connect
'DBI:mysql:' .
'database=' . $self->{'db'}->{'name'} .
';host=' . $self->{'db'}->{'host'} .
';port=' . $self->{'db'}->{'port'} .
';mysql_client_found_rows=0',
$self->{'db'}->{'user'},
$self->{'db'}->{'pw'},
{ 'RaiseError' => 1,
'AutoCommit' => 1,
'mysql_enable_utf8' => 1
}
) or $self->msg(0, 'cannot connect to db: '.$DBI::errstr);
$self->{'db'}->{'proj'} = $proj;
}
return 1;
}
sub _db_query{
my $self = shift;
my $query = shift;
my $return_header = shift // 1;
unless(defined $self->{'db'}->{'handle'}){
$self->msg(0, 'no databae handle', 'error');
return 0;
}
my $sth = $self->{'db'}->{'handle'}->prepare($query)
or $self->msg(0, $self->{'db'}->{'handle'}->errstr.' query = \''.$query.'\'');
return 0 unless $sth;
$sth->execute;
my $names = $sth->{'NAME'}; # or NAME_lc if needed
my $rows_ref = $sth->fetchall_arrayref();
#$sth->finish;
unshift @$rows_ref, $names if $return_header;
return $rows_ref;
}
sub _db_simplequery{
my $self = shift;
my $db_query = shift;
my $return_header = shift // 1;
my $proj = shift // $self->{'wm_proj'};
if(defined $proj){
$self->msg(3, "proj = $proj");
}else{
$self->msg(0, '$proj is not defined.', 'error');
}
$self->_db_init($proj) or return undef;
#print Dumper $db_query;
if(ref(\$db_query) ne 'SCALAR'){
#$db_query->[0] =~ s/\s+/ /g;
$db_query->[0] =~ s/^\s+|\s+\z//g;
$db_query = sprintf $db_query->[0], map {
(defined $_ and /^-?(?:\d*\.\d+|\d+\.?)\z/) ? $_ :
$self->{'db'}->{'handle'}->quote($_); #(not defined $_) ? 'NULL' (will be done by quote, so ensure, using '%s' even on numbers)
} @$db_query[1..@$db_query-1];
}
$self->msg(2, $db_query);
my $db_table = $self->_db_query($db_query, $return_header);
return $db_table;
}
#sub db_fetch_recentchanges_detailed{
# my $self = shift;
# my $last_seconds = shift // 60*60*12; # default = last 12 hours
# my $timestamp = $self->get_time_iso($time()-$last_seconds);
# # check whether token exists:
# my $db_table = db_simplequery([
# 'SELECT `rc_timestamp`, `rc_user_text`, `rc_namespace`, `rc_title`, `rc_comment`, `rc_minor`, `rc_bot`, `rc_new`, `rc_cur_id`, `rc_this_oldid`, `rc_last_oldid`, `rc_type`, `rc_source`, `rc_patrolled`, `rc_old_len`, `rc_new_len`, `rc_deleted` FROM `recentchanges` WHERE `rc_timestamp`>%s', $timestamp],
# !$_return_header);
# if(defined $db_table->[0]){
# my $email = lc $db_table->[0][0];
# my $user_id = $db_table->[0][1];
# }
#}
sub db_fetch_pages_of_categories_of_the_dead{
my $self = shift;
my $since = shift;
if(defined $since and
$since !~ /^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\z/)
{
$self->msg(0, 'param $since is not valid, see source code', 'warning');
return [];
}
my $return_header = 1;
my $sql_query = '
SELECT
`page`.`page_title` AS `page`,
`page`.`page_namespace` AS `namespace`,
`cl_to` AS `category`,
`cl_timestamp`
FROM `categorylinks`
LEFT JOIN `page`
ON `page`.`page_id`=`cl_from`
WHERE `cl_to` LIKE \'Gestorben_2%%\'
AND `page_namespace` = \'0\'
AND `cl_timestamp` >= ' . (defined $since ? '%s' : 'date_sub(now(), interval 2 day)') .
' LIMIT 10000';
my $db_table = defined $since ?
$self->_db_simplequery([$sql_query, $since], $return_header)
: $self->_db_simplequery([$sql_query], $return_header);
for my $row(@$db_table[1..(@$db_table-1)]){
utf8::decode($row->[0]); # page
}
return $self->db_table2array_of_hash($db_table);
}
sub db_fetch_externallinks{
my $self = shift;
my $from_id = shift // 1;
my $to_id = shift;
if($from_id !~ /^[0-9]+\z/){
$self->msg(0, 'param $from_id is not valid, see source code', 'warning');
return [];
}elsif(defined $to_id and $to_id !~ /^[0-9]+\z/){
$self->msg(0, 'param $to_id is not valid, see source code', 'warning');
return [];
}
my $return_header = 1;
my $db_table;
my $sql_max_id = defined $to_id ? 'AND `el_id`<=%s' : '';
$db_table = $self->_db_simplequery(['
SELECT `el_id`, `el_from`, `el_to`, `p`.`page_title` AS `page`
FROM `externallinks`
LEFT JOIN `page` AS `p`
ON (`p`.`page_id`=`externallinks`.`el_from`)
WHERE `el_id`>=%s ' . $sql_max_id . '
ORDER BY `el_id`
LIMIT 1000
', $from_id, $to_id], $return_header);
return $self->db_table2array_of_hash($db_table);
}
sub db_fetch_recentchanges{
my $self = shift;
my $timestamp_begin = shift; # format yyyymmddhhmmss
my $timestamp_end = shift; # format yyyymmddhhmmss
unless(defined $timestamp_begin){
# default = last 12 hours
$timestamp_begin = $self->get_time_iso(time()-60*60*12);
}
my $sql_max_ts = defined $timestamp_end ? 'AND `rc_timestamp`<=%s' : '';
my $return_header = 1;