-
Notifications
You must be signed in to change notification settings - Fork 3
/
wikiget.awk
executable file
·2730 lines (2369 loc) · 92.6 KB
/
wikiget.awk
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/local/bin/awk -bE
#
# Wikiget - command-line access to Wikimedia API read/write functions
# https://github.com/greencardamom/Wikiget
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2025 by User:GreenC (at en.wikipedia.org)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# 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.
# Code Table of Contents
#
# [[ _______ Global system vars ____________________________________________ ]]
# [[ _______ Command line parsing and argument processing __________________ ]]
# [[ _______ Setup _________________________________________________________ ]]
# [[ _______ Core read-only functions ______________________________________ ]]
# ___ Categories (-c)
# ___ External links list (-x)
# ___ Recent changes (-r)
# ___ User Contributions (-u)
# ___ Forward links (-F)
# ___ Backlinks (-b)
# ___ Print wiki text (-w)
# ___ Search list (-a)
# [[ _______ Utilities ______________________________________________________ ]]
# [[ _______ Library ________________________________________________________ ]]
# [[ _______ JSON ___________________________________________________________ ]]
# [[ _______ Edit ___________________________________________________________ ]]
# [[ ________ Global system vars _____________________________________________ ]]
BEGIN { # Program cfg
_defaults = "contact = User:GreenC -> en.wikipedia.org \
program = Wikiget \
version = 1.21 \
copyright = 2016-2025 \
agent = " G["program"] " " G["version"] " " G["contact"] "\
maxlag = 5 \
lang = en \
project = wikipedia"
asplit(G, _defaults, "[ ]*[=][ ]*", "[ ]{9,}")
setup("wget curl lynx") # Use one of wget, curl or lynx - searches PATH in this order
# They do the same, need at least one available in PATH
# For edit (-E) wget is required
Optind = Opterr = 1
# randomnumber() seed
_cliff_seed = "0.00" splitx(sprintf("%f", systime() * 0.000001), ".", 2)
# Optional OAuth consumer keys. See EDITSETUP for more info.
# Create the files below with secure permissions to store your secrets:
# mkdir /home/user/.config/wikiget
# mkdir /home/user/.config/wikiget/secrets
# chmod 700 /home/user/.config/wikiget/secrets
# chmod 600 mybot.consumerkey
# chmod 600 mybot.consumersecret
# chmod 600 mybot.accesskey
# chmod 600 mybot.accesssecret
G["consumerKey"] = strip(readfile("/home/user/.config/wikiget/secrets/mybot.consumerkey"))
G["consumerSecret"] = strip(readfile("/home/user/.config/wikiget/secrets/mybot.consumersecret"))
G["accessKey"] = strip(readfile("/home/user/.config/wikiget/secrets/mybot.accesskey"))
G["accessSecret"] = strip(readfile("/home/user/.config/wikiget/secrets/mybot.accesssecret"))
}
BEGIN { # Program run
parsecommandline()
}
# [[ ________ Command line parsing and argument processing ___________________ ]]
#
# parsecommandline() - parse command-line
#
function parsecommandline(c,opts,Arguments) {
while ((c = getopt(ARGC, ARGV, "yrhVfjpdo:k:a:g:i:s:e:u:m:b:l:n:w:c:t:q:x:z:F:E:S:P:I:R:T:AB:G:")) != -1) {
opts++
if (c == "h") {
usage()
usage_extended()
exit
}
if (c == "b") { # -b <entity> Backlinks for entity ( -b "Template:Project Gutenberg" )
Arguments["main"] = verifyval(Optarg)
Arguments["main_c"] = "b"
}
if (c == "t") # -t <types> Types of backlinks ( -t "ntf" )
Arguments["bltypes"] = verifyval(Optarg)
if (c == "F") { # -F <entity> Forward-links for entity ( -F "Example" )
Arguments["main"] = verifyval(Optarg)
Arguments["main_c"] = "F"
}
if (c == "B") { # -B <entity> Redirects for entity ( -B "Example" )
Arguments["main"] = verifyval(Optarg)
Arguments["main_c"] = "B"
}
if (c == "c") { # -b <entity> List articles in a category ( -c "Category:1900 births" )
Arguments["main"] = verifyval(Optarg)
Arguments["main_c"] = "c"
}
if (c == "q") # -q <types> Types of links in a category ( -t "psf" )
Arguments["cattypes"] = verifyval(Optarg)
if (c == "a") { # -a <search> List articles in search results ( -a "John Smith" )
Arguments["main"] = verifyval(Optarg)
Arguments["main_c"] = "a"
}
if (c == "d") # -d Include search snippet in results (optional with -a )
Arguments["snippet"] = "true"
if (c == "j") # -j Show number of search results (optional with -a)
Arguments["numsearch"] = "true"
if (c == "i") # -i <max> Max number of search results (optional with -a)
Arguments["maxsearch"] = verifyval(Optarg)
if (c == "g") # -g <type> Target search (optional with -a)
Arguments["searchtarget"] = verifyval(Optarg)
if (c == "u") { # -u <username> User contributions ( -u "User:Green Cardamom")
Arguments["main"] = verifyval(Optarg)
Arguments["main_c"] = "u"
}
if (c == "s") # -s <time> Start time for -u (required w/ -u)
Arguments["starttime"] = verifyval(Optarg)
if (c == "e") # -e <time> End time for -u (required w/ -u)
Arguments["endtime"] = verifyval(Optarg)
if (c == "i") # -i <regex> Edit comment must include this regex match
Arguments["inccomments"] = verifyval(Optarg)
if (c == "j") # -j <regex> Edit comment must exclude this regex match
Arguments["exccomments"] = verifyval(Optarg)
if (c == "n") # -n <namespace> Namespace for -u, -a and -x (option)
Arguments["namespace"] = verifyval(Optarg)
if (c == "r") # -r Recent changes
Arguments["main_c"] = "r"
if (c == "o") # -o <username> Username for recent changes
Arguments["username"] = verifyval(Optarg)
if (c == "k") # -k <tag> Tag for recent changes
Arguments["tags"] = verifyval(Optarg)
if (c == "A") { # -A Dump a list of all article titles on Wikipedia (no redirects)
Arguments["main_c"] = "A"
}
if (c == "t") # -t <type> Filter redirects
Arguments["redirtype"] = verifyval(Optarg)
if (c == "k") # -k <#> Number of pages to return
Arguments["maxpages"] = verifyval(Optarg)
if (c == "w") { # -w <article> Print wiki text
Arguments["main"] = verifyval(Optarg)
Arguments["main_c"] = "w"
}
if (c == "f") # -f Don't follow redirect (return source of redirect page)
Arguments["followredirect"] = "false"
if (c == "p") # -p Plain text (strip wiki markup)
Arguments["plaintext"] = "true"
if (c == "x") { # -x <URL> List articles containing an external link
Arguments["main"] = verifyval(Optarg)
Arguments["main_c"] = "x"
}
if (c == "E") { # -E <title> Edit a page with this title. Requires -S and -P
Arguments["main_c"] = "E"
Arguments["title"] = verifyval(Optarg)
}
if (c == "S") # -S <summary> Edit summary
Arguments["summary"] = verifyval(Optarg)
if (c == "P") # -P <filename> Page content filename
Arguments["page"] = verifyval(Optarg)
if (c == "R") { # -R <page> Move from page name
Arguments["main_c"] = "R"
Arguments["movefrom"] = verifyval(Optarg)
}
if (c == "T") # -T <page> Move to page name
Arguments["moveto"] = verifyval(Optarg)
if (c == "G") { # -G <page> Purge page
Arguments["main_c"] = "G"
Arguments["title"] = verifyval(Optarg)
}
if (c == "I") # -I User info
Arguments["main_c"] = "I"
if (c == "m") # -m <maxlag> Maxlag setting when using API, default set in BEGIN{} section
Arguments["maxlag"] = verifyval(Optarg)
if (c == "l") # -l <lang> Language code, default set in BEGIN{} section
Arguments["lang"] = verifyval(Optarg)
if (c == "z") # -z <project> Project name, default set in BEGIN{} section
Arguments["project"] = verifyval(Optarg)
if (c == "y") # -y Show debugging info to stderr
Arguments["debug"] = 1
if (c == "V") { # -V Version and copyright info.
version()
exit
}
}
if (opts < 1)
usage(1)
processarguments(Arguments)
}
#
# processarguments() - process arguments
#
function processarguments(Arguments, c,a,i) {
if (length(Arguments["lang"]) > 0) # Check options, set defaults
G["lang"] = Arguments["lang"]
# default set in BEGIN{}
if (length(Arguments["project"]) > 0) # Check options, set defaults
G["project"] = Arguments["project"]
# default set in BEGIN{}
if (isanumber(Arguments["maxlag"]))
G["maxlag"] = Arguments["maxlag"]
# default set in BEGIN{}
if (isanumber(Arguments["maxpages"]))
G["maxpages"] = Arguments["maxpages"]
else
G["maxpages"] = 10
if (isanumber(Arguments["maxsearch"]))
G["maxsearch"] = Arguments["maxsearch"]
else
G["maxsearch"] = 10000
if (isanumber(Arguments["namespace"]) || Arguments["namespace"] ~ "[|]")
G["namespace"] = Arguments["namespace"]
else
G["namespace"] = "0"
if (Arguments["followredirect"] == "false")
G["followredirect"] = "false"
else
G["followredirect"] = "true"
if (Arguments["plaintext"] == "true")
G["plaintext"] = "true"
else
G["plaintext"] = "false"
if (Arguments["snippet"] == "true")
G["snippet"] = "true"
else
G["snippet"] = "false"
if (Arguments["redirtype"] !~ /1|2|3/)
G["redirtype"] = "2"
else
G["redirtype"] = Arguments["redirtype"]
if (Arguments["numsearch"] == "true")
G["numsearch"] = "true"
else
G["numsearch"] = "false"
if (Arguments["searchtarget"] !~ /^text$|^title$/)
G["searchtarget"] = "text"
else
G["searchtarget"] = Arguments["searchtarget"]
if (length(Arguments["bltypes"]) > 0 && Arguments["main_c"] == "b") {
if (Arguments["bltypes"] !~ /[^ntf]/) { # ie. contains only those letters
c = split(Arguments["bltypes"], a, "")
while (i++ < c)
G["bltypes"] = G["bltypes"] a[i]
}
else {
stdErr("Invalid \"-t\" value(s)")
exit
}
}
else
G["bltypes"] = "ntf"
if (length(Arguments["cattypes"]) > 0) {
if (Arguments["cattypes"] !~ /[^psf]/) {
c = split(Arguments["cattypes"], a, "")
while (i++ < c)
G["cattypes"] = G["cattypes"] a[i]
}
else {
stdErr("Invalid \"-q\" value(s)")
exit
}
}
else
G["cattypes"] = "p"
if(! empty(Arguments["inccomments"]))
G["inccomments"] = Arguments["inccomments"]
if(! empty(Arguments["exccomments"]))
G["exccomments"] = Arguments["exccomments"]
if (Arguments["debug"]) # Enable debugging
G["debug"] = 1
G["apiURL"] = "https://" G["lang"] "." G["project"] ".org/w/api.php?"
# ________________ program entry points _______________________ #
if (Arguments["main_c"] == "E") { # edit page
if (empty(Arguments["summary"]) || empty(Arguments["page"])) {
stdErr("Missing -S and/or -P")
usage(1)
}
editPage(Arguments["title"], Arguments["summary"], Arguments["page"])
}
else if (Arguments["main_c"] == "I") { # OAuth userinfo
userInfo()
}
else if (Arguments["main_c"] == "G") { # purge page
if (empty(Arguments["title"])) {
stdErr("Missing page title")
usage(1)
}
purgePage(Arguments["title"])
}
else if (Arguments["main_c"] == "R") { # move page
if (empty(Arguments["summary"])) {
stdErr("Missing -S (reason for move)")
usage(1)
}
if (empty(Arguments["moveto"]))
usage(1)
movePage(Arguments["movefrom"], Arguments["moveto"], Arguments["summary"])
}
else if (Arguments["main_c"] == "A") {
allPages(G["redirtype"])
}
else if (Arguments["main_c"] == "b") { # backlinks
if ( entity_exists(Arguments["main"]) ) {
if ( ! backlinks(Arguments["main"]) )
stdErr("No backlinks for " Arguments["main"])
}
}
else if (Arguments["main_c"] == "F") { # forward-links
forlinks(Arguments["main"])
}
else if (Arguments["main_c"] == "B") { # redirects
redirects(Arguments["main"])
}
else if (Arguments["main_c"] == "c") { # categories
category(Arguments["main"])
}
else if (Arguments["main_c"] == "x") { # external links
xlinks(Arguments["main"])
}
else if (Arguments["main_c"] == "a") { # search results
search(Arguments["main"])
}
else if (Arguments["main_c"] == "u") { # user contributions
if (! isanumber(Arguments["starttime"]) || ! isanumber(Arguments["endtime"])) {
stdErr("Invalid start time (-s) or end time (-e)\n")
usage(1)
}
Arguments["starttime"] = Arguments["starttime"] "000000"
Arguments["endtime"] = Arguments["endtime"] "235959"
if (! ucontribs(Arguments["main"],Arguments["starttime"],Arguments["endtime"]) )
stdErr("No user and/or edits found.")
}
else if (Arguments["main_c"] == "r") { # recent changes
if ((length(Arguments["username"]) == 0 && length(Arguments["tags"]) == 0) || (length(Arguments["username"]) > 0 && length(Arguments["tags"]) > 0)) {
stdErr("Recent changes requires either -f or -k\n")
usage(1)
}
if (! rechanges(Arguments["username"],Arguments["tags"]) )
stdErr("No recent changes found.")
}
else if (Arguments["main_c"] == "w") { # wiki text
if (entity_exists(Arguments["main"]) ) {
if (G["plaintext"] == "true")
print wikitextplain(Arguments["main"])
else
print wikitext(Arguments["main"])
}
else {
stdErr("Unable to find " Arguments["main"])
exit
}
}
else
usage(1)
}
#
# usage()
#
function usage(die) {
print ""
print G["program"] " - command-line access to some Wikimedia API functions"
print ""
print "Usage:"
print ""
print " Backlinks:"
print " -b <name> Backlinks for article, template, userpage, etc.."
print " -t <types> (option) 1-3 letter string of types of backlinks:"
print " n(ormal)t(ranscluded)f(ile). Default: \"ntf\"."
print " See -h for more info "
print " -n <namespace> (option) Pipe-separated numeric value(s) of namespace(s)"
print " Only list pages in this namespace. Default: 0"
print " See -h for NS codes and examples"
print ""
print " Forward-links:"
print " -F <name> Forward-links for article, template, userpage, etc.."
print ""
print " Redirects:"
print " -B <name> Redirects for article, template, userpage, etc.."
print " -n <namespace> (option) Pipe-separated numeric value(s) of namespace(s)"
print " Only list redirects in this namespace. Default: 0"
print " See -h for NS codes and examples"
print ""
print " User contributions:"
print " -u <username> Username without User: prefix"
print " -s <starttime> Start time in YMD format (-s 20150101). Required with -u"
print " -e <endtime> End time in YMD format (-e 20151231). If same as -s,"
print " does 24hr range. Required with -u"
print " -i <regex> (option) Edit comment must include regex match"
print " -j <regex> (option) Edit comment must exclude regex match"
print " -n <namespace> (option) Pipe-separated numeric value(s) of namespace"
print " Only list pages in this namespace. Default: 0"
print " See -h for NS codes and examples"
print ""
print " Recent changes:"
print " -r Recent changes (past 30 days) aka Special:RecentChanges"
print " Either -o or -t required"
print " -o <username> Only list changes made by this user"
print " -k <tag> Only list changes tagged with this tag"
print " -i <regex> (option) Edit comment must include regex match"
print " -j <regex> (option) Edit comment must exclude regex match"
print " -n <namespace> (option) Pipe-separated numeric value(s) of namespace"
print " Only list pages in this namespace. Default: 0"
print " See -h for NS codes and examples"
print ""
print " Category list:"
print " -c <category> List articles in a category"
print " -q <types> (option) 1-3 letter string of types of links: "
print " p(age)s(ubcat)f(ile). Default: \"p\""
print ""
print " Search-result list:"
print " -a <search> List of articles containing a search string"
print " See docs https://www.mediawiki.org/wiki/Help:CirrusSearch"
print " -d (option) Include search-result snippet in output (def: title)"
print " -g <target> (option) Search in \"title\" or \"text\" (def: \"text\")"
print " -n <namespace> (option) Pipe-separated numeric value(s) of namespace"
print " Only list pages in this namespace. Default: 0"
print " See -h for NS codes and examples"
print " -i <maxsize> (option) Max number of results to return. Default: 10000"
print " 10k max limit imposed by search engine"
print " -j (option) Show number of search results"
print ""
print " External links list:"
print " -x <domain name> List articles containing domain name (Special:Linksearch)"
print " Works with domain-name only. To search for a full URI use"
print " regex. eg. -a \"insource:/http:\\/\\/gq.com\\/home.htm/\""
print " To include subdomains use wildcards: \"-x *.domain.com\""
print " -n <namespace> (option) Pipe-separated numeric value(s) of namespace"
print " Only list pages in this namespace. Default: 0"
print " See -h for NS codes and examples"
print ""
print " Print wiki text:"
print " -w <article> Print wiki text of article"
print " -p (option) Plain-text version (strip wiki markup)"
print " -f (option) Don't follow redirects (print redirect page)"
print ""
print " All pages:"
print " -A Print a list of page titles on the wiki (possibly very large)"
print " -t <# type> 1=All, 2=Skip redirects, 3=Only redirects. Default: 2"
print " -k <#> Number of pages to return. 0 is all. Default: 10"
print " -n <namespace> (option) Pipe-separated numeric value(s) of namespace"
print " Only list pages in this namespace. Default: 0"
print " See -h for NS codes and examples"
print ""
print " Edit page:"
print " -E <title> Edit a page with this title. Requires -S and -P"
print " -S <summary> Edit summary"
print " -P <filename> Page content filename. If \"STDIN\" read from stdin"
print " See EDITSETUP for authentication configuration"
print ""
print " -R <page> Move from page name. Requires -T"
print " -T <page> Move to page name"
print ""
print " -G <page> Purge page"
print " -I Show OAuth userinfo"
print ""
print " Global options:"
print " -l <language> Wiki language code (default: " G["lang"] ")"
print " See https://en.wikipedia.org/wiki/List_of_Wikipedias"
print " -z <project> Wiki project (default: " G["project"] ")"
print " https://en.wikipedia.org/wiki/Wikipedia:Wikimedia_sister_projects"
print " -m <#> API maxlag value (default: " G["maxlag"] ")"
print " See https://www.mediawiki.org/wiki/API:Etiquette#Use_maxlag_parameter"
print " -y Print debugging to stderr (show URLs sent to API)"
print " -V Version and copyright"
print " -h Help with examples"
print ""
if(die) exit
}
function usage_extended() {
print "Examples:"
print ""
print " Backlinks:"
print " for a User: showing all link types (\"ntf\")"
print " wikiget -b \"User:Jimbo Wales\""
print " for a User: showing normal and transcluded links"
print " wikiget -b \"User:Jimbo Wales\" -t nt"
print " for a Template: showing transcluded links"
print " wikiget -b \"Template:Gutenberg author\" -t t"
print " for a File: showing file links"
print " wikiget -b \"File:Justforyoucritter.jpg\" -t f"
print " for article \"Paris (Idaho)\" on the French Wiki"
print " wikiget -b \"Paris (Idaho)\" -l fr"
print ""
print " User contributions:"
print " show all edits from 9/10-9/12 on 2001"
print " wikiget -u \"Jimbo Wales\" -s 20010910 -e 20010912"
print " show all edits during the 24hrs of 9/11"
print " wikiget -u \"Jimbo Wales\" -s 20010911 -e 20010911"
print " show all edits when the edit-comment starts with 'A' "
print " wikiget -u \"Jimbo Wales\" -s 20010911 -e 20010911 -i \"^A\""
print " articles only"
print " wikiget -u \"Jimbo Wales\" -s 20010911 -e 20010930 -n 0"
print " talk pages only"
print " wikiget -u \"Jimbo Wales\" -s 20010911 -e 20010930 -n 1"
print " talk and articles only"
print " wikiget -u \"Jimbo Wales\" -s 20010911 -e 20010930 -n \"0|1\""
print ""
print " -n codes: https://www.mediawiki.org/wiki/Extension_default_namespaces"
print ""
print " Recent changes:"
print " show edits for prior 30 days by IABot made under someone else's name"
print " (ie. OAuth) with an edit summary including this target word"
print " wikiget -k \"OAuth CID: 1804\" -r -i \"Bluelinking\""
print ""
print " CID list: https://en.wikipedia.org/wiki/Special:Tags"
print ""
print " Category list:"
print " pages in a category"
print " wikiget -c \"Category:1900 births\""
print " subcats in a category"
print " wikiget -c \"Category:Dead people\" -q s"
print " subcats and pages in a category"
print " wikiget -c \"Category:Dead people\" -q sp"
print ""
print " Search-result list:"
print " article titles containing a search"
print " wikiget -a \"Jethro Tull\" -g title"
print " first 50 articles containing a search"
print " wikiget -a John -i 50"
print " include snippet of text containing the search string"
print " wikiget -a John -i 50 -d"
print " search talk and articles only"
print " wikiget -a \"Barleycorn\" -n \"0|1\""
print " regex search, include debug output"
print " wikiget -a \"insource:/ia[^.]*[.]us[.]/\" -y"
print " subpages of User:GreenC"
print " wikiget -a \"user: subpageof:GreenC\""
print ""
print " search docs: https://www.mediawiki.org/wiki/Help:CirrusSearch"
print " -n codes: https://www.mediawiki.org/wiki/Extension_default_namespaces"
print ""
print " External link list:"
print " list articles containing a URL with this domain"
print " wikiget -x \"news.yahoo.com\""
print " list articles in NS 1 containing a URL with this domain"
print " wikiget -x \"*.yahoo.com\" -n 1"
print ""
print " All pages:"
print " all page titles excluding redirects w/debug tracking progress"
print " wikiget -A -t 2 -y > list.txt"
print " first 50 page titles including redirects"
print " wikiget -A -t 1 -k 50 > list.txt"
print ""
print " Print wiki text:"
print " wiki text of article \"Paris\" on the English Wiki"
print " wikiget -w \"Paris\""
print " plain text of article \"China\" on the French Wiki"
print " wikiget -w \"China\" -p -l fr"
print " wiki text of article on Wikinews"
print " wikiget -w \"Healthy cloned monkeys born in Shanghai\" -z wikinews"
print ""
print " Edit page:"
print " Edit \"Paris\" by uploading new content from the local file paris.ws"
print " wikiget -E \"Paris\" -S \"Fix spelling\" -P \"/home/paris.ws\""
print " Input via stdin"
print " cat /home/paris.ws | wikiget -E \"Paris\" -S \"Fix spelling\" -P STDIN"
print " Purge page"
print " wikiget -G \"Paris\""
print ""
}
function version() {
print G["program"] " " G["version"]
print "Copyright (C) " G["copyright"] " User:GreenC (en.wikipedia.org)"
print
print "The MIT License (MIT)"
print
print "Permission is hereby granted, free of charge, to any person obtaining a copy"
print "of this software and associated documentation files (the "Software"), to deal"
print "in the Software without restriction, including without limitation the rights"
print "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell"
print "copies of the Software, and to permit persons to whom the Software is"
print "furnished to do so, subject to the following conditions:"
print
print "The above copyright notice and this permission notice shall be included in"
print "all copies or substantial portions of the Software."
print
print "THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR"
print "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,"
print "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE"
print "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER"
print "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,"
print "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN"
print "THE SOFTWARE."
print
}
#
# Verify an argument has a valid value
#
function verifyval(val) {
if (val == "" || substr(val,1,1) ~ /^[-]/) {
stdErr("\nCommand line argument has an empty value when it should have something.\n")
usage(1)
}
return val
}
#
# getopt()
# Credit: GNU awk (/usr/local/share/awk/getopt.awk)
# Pre-define these globaly: Optind = Opterr = 1
#
function getopt(argc, argv, options, thisopt, i) {
if (length(options) == 0) # no options given
return -1
if (argv[Optind] == "--") { # all done
Optind++
_opti = 0
return -1
} else if (argv[Optind] !~ /^-[^:[:space:]]/) {
_opti = 0
return -1
}
if (_opti == 0)
_opti = 2
thisopt = substr(argv[Optind], _opti, 1)
Optopt = thisopt
i = index(options, thisopt)
if (i == 0) {
if (Opterr)
printf("%c -- invalid option\n", thisopt) > "/dev/stderr"
if (_opti >= length(argv[Optind])) {
Optind++
_opti = 0
} else
_opti++
return "?"
}
if (substr(options, i + 1, 1) == ":") {
# get option argument
if (length(substr(argv[Optind], _opti + 1)) > 0) {
Optarg = substr(argv[Optind], _opti + 1)
}
else {
Optarg = argv[++Optind]
}
_opti = 0
} else {
Optarg = ""
}
if (_opti == 0 || _opti >= length(argv[Optind])) {
Optind++
_opti = 0
} else
_opti++
return thisopt
}
# [[ ________ Setup __________________________________________________________ ]]
#
# Check for existence of needed programs and files.
#
function setup(files_system) {
if (! files_verify("ls") ) {
stdErr("Unable to find 'ls' and/or 'command'. PATH problem?\n")
exit
}
if (! files_verify(files_system) )
exit
}
#
# Verify existence of programs in path
# Return 0 if fail.
#
function files_verify(files_system, a, i, missing) {
missing = 0
split(files_system, a, " ")
for ( i in a ) {
if (! sys2var(sprintf("command -v %s",a[i])) ) {
if (a[i] == "wget") G["wget"] = "false"
else if (a[i] == "curl") G["curl"] = "false"
else if (a[i] == "lynx") G["lynx"] = "false"
else {
stdErr("Abort: command not found in PATH: " a[i])
missing++
}
}
else if (a[i] == "wget") G["wget"] = "true"
else if (a[i] == "curl") G["curl"] = "true"
else if (a[i] == "lynx") G["lynx"] = "true"
}
if (G["wget"] == "false" && G["curl"] == "false" && G["lynx"] == "false") {
stdErr("Abort: unable to find wget, curl or lynx in PATH.")
return 0
}
else if (G["wget"] == "true")
G["wta"] = "wget"
else if (G["curl"] == "true")
G["wta"] = "curl"
else if (G["lynx"] == "true")
G["wta"] = "lynx"
if ( missing )
return 0
return 1
}
# [[ ________ Core read-only functions _______________________________________ ]]
# ___ Categories (-c)
#
# MediaWiki API:Categorymembers
# https://www.mediawiki.org/wiki/API:Categorymembers
#
function category(entity, ct, url, results) {
if (entity !~ /^[Cc]ategory[:]/)
entity = "Category:" entity
if (G["cattypes"] ~ /p/)
ct = ct " page"
if (G["cattypes"] ~ /s/)
ct = ct " subcat"
if (G["cattypes"] ~ /f/)
ct = ct " file"
ct = strip(ct)
gsub(/[ ]/,"|",ct)
url = G["apiURL"] "action=query&list=categorymembers&cmtitle=" urlencodeawk(entity) "&cmtype=" urlencodeawk(ct) "&cmprop=title&cmlimit=500&format=json&formatversion=2&maxlag=" G["maxlag"]
results = uniq(getcategory(url, entity) )
if ( length(results) > 0)
print results
return length(results)
}
function getcategory(url, entity, jsonin, jsonout, continuecode) {
jsonin = http2var(url)
if (apierror(jsonin, "json") > 0)
return ""
jsonout = json2var(jsonin)
continuecode = getcontinue(jsonin, "cmcontinue")
while ( continuecode != "-1-1!!-1-1" ) {
url = G["apiURL"] "action=query&list=categorymembers&cmtitle=" urlencodeawk(entity) "&cmtype=page&cmprop=title&cmlimit=500&format=json&formatversion=2&maxlag=" G["maxlag"] "&continue=-||&cmcontinue=" continuecode
jsonin = http2var(url)
jsonout = jsonout "\n" json2var(jsonin)
continuecode = getcontinue(jsonin, "cmcontinue")
}
return jsonout
}
# ___ External links list (-x)
#
# MediaWiki API:Exturlusage
# https://www.mediawiki.org/wiki/API:Exturlusage
#
function xlinks(entity, url,results,a,c,i) {
if (entity ~ /^https?/ )
gsub(/^https?[:]\/\//,"",entity)
else if(entity ~ /^\/\// )
gsub(/^\/\//,"",entity)
if (entity ~ /^[*]$/) {
entity = ""
}
c = split("http|https|ftp|ftps|sftp", a, /[|]/)
# iterate for euprotocol=a[i]
for(i = 1; i <= c; i++) {
url = G["apiURL"] "action=query&list=exturlusage&euprotocol=" urlencodeawk(a[i]) "&euexpandurl=&euquery=" urlencodeawk(entity) "&euprop=title&eulimit=500&eunamespace=" urlencodeawk(G["namespace"]) "&format=json&formatversion=2&maxlag=" G["maxlag"]
results = results "\n" getxlinks(url, entity, "http")
}
results = uniq( results )
if ( length(results) > 0)
print results
return length(results)
}
function getxlinks(url, entity, euprotocol, jsonin, jsonout, continuecode) {
jsonin = http2var(url)
if (apierror(jsonin, "json") > 0)
return ""
jsonout = json2var(jsonin)
continuecode = getcontinue(jsonin,"eucontinue")
while ( continuecode != "-1-1!!-1-1" ) {
url = G["apiURL"] "action=query&list=exturlusage&euprotocol=" urlencodeawk(euprotocol) "&euexpandurl=&euquery=" urlencodeawk(entity) "&euprop=title&eulimit=500&eunamespace=" urlencodeawk(G["namespace"]) "&format=json&formatversion=2&maxlag=" G["maxlag"] "&continue=" urlencodeawk("-||") "&eucontinue=" urlencodeawk(continuecode, "rawphp")
jsonin = http2var(url)
jsonout = jsonout "\n" json2var(jsonin)
continuecode = getcontinue(jsonin,"eucontinue")
}
return jsonout
}
# ___ Recent changes (-r)
#
# MediaWiki API:RecentChanges
# https://www.mediawiki.org/wiki/API:RecentChanges#cite_note-1
#
function rechanges(username, tag, url, results, entity) {
if (length(username) > 0)
entity = "&rcuser=" urlencodeawk(username)
else if (length(tag) > 0)
entity = "&rctag=" urlencodeawk(tag)
else
return 0
url = G["apiURL"] "action=query&list=recentchanges&rcprop=" urlencodeawk("title|parsedcomment") entity "&rclimit=500&rcnamespace=" urlencodeawk(G["namespace"]) "&format=json&formatversion=2&maxlag=" G["maxlag"]
results = uniq( getrechanges(url, entity) )
if ( length(results) > 0)
print results
return length(results)
}
function getrechanges(url, entity, jsonin, jsonout, continuecode) {
jsonin = http2var(url)
if (apierror(jsonin, "json") > 0)
return ""
jsonout = json2varUcontribs(jsonin)
continuecode = getcontinue(jsonin,"rccontinue")
while ( continuecode != "-1-1!!-1-1" ) {
url = G["apiURL"] "action=query&list=recentchanges&rcprop=" urlencodeawk("title|parsedcomment") entity "&rclimit=500&continue=" urlencodeawk("-||") "&rccontinue=" urlencodeawk(continuecode) "&rcnamespace=" urlencodeawk(G["namespace"]) "&format=json&formatversion=2&maxlag=" G["maxlag"]
jsonin = http2var(url)
jsonout = jsonout "\n" json2varUcontribs(jsonin)
continuecode = getcontinue(jsonin,"rccontinue")
}
return jsonout
}
# ___ User Contributions (-u)
#
# MediaWiki API:Usercontribs
# https://www.mediawiki.org/wiki/API:Usercontribs
#
function ucontribs(entity,sdate,edate, url, results) {
# API stopped working with User: prefix sometime in April 2018
sub(/^[Uu]ser[:]/, "", entity)
url = G["apiURL"] "action=query&list=usercontribs&ucuser=" urlencodeawk(entity) "&uclimit=500&ucstart=" urlencodeawk(sdate) "&ucend=" urlencodeawk(edate) "&ucdir=newer&ucnamespace=" urlencodeawk(G["namespace"]) "&ucprop=" urlencodeawk("title|parsedcomment") "&format=json&formatversion=2&maxlag=" G["maxlag"]
results = uniq( getucontribs(url, entity, sdate, edate) )
if ( length(results) > 0)
print results
return length(results)
}
function getucontribs(url, entity, sdate, edate, jsonin, jsonout, continuecode) {
jsonin = http2var(url)
if (apierror(jsonin, "json") > 0)
return ""
jsonout = json2varUcontribs(jsonin)
continuecode = getcontinue(jsonin,"uccontinue")
while ( continuecode != "-1-1!!-1-1" ) {
url = G["apiURL"] "action=query&list=usercontribs&ucuser=" urlencodeawk(entity) "&uclimit=500&continue=" urlencodeawk("-||") "&uccontinue=" urlencodeawk(continuecode) "&ucstart=" urlencodeawk(sdate) "&ucend=" urlencodeawk(edate) "&ucdir=newer&ucnamespace=" urlencodeawk(G["namespace"]) "&ucprop=" urlencodeawk("title|parsedcomment") "&format=json&formatversion=2&maxlag=" G["maxlag"]
jsonin = http2var(url)
jsonout = jsonout "\n" json2varUcontribs(jsonin)
continuecode = getcontinue(jsonin,"uccontinue")
}
return jsonout
}
# ___ Forward links (-F)
#
# MediaWiki API:Parsing_wikitext
# https://www.mediawiki.org/wiki/API:Parsing_wikitext
#
function forlinks(entity,sdate,edate, url,jsonin,jsonout) {
url = G["apiURL"] "action=parse&prop=" urlencodeawk("links") "&page=" urlencodeawk(entity) "&format=json&formatversion=2&maxlag=" G["maxlag"]
jsonin = http2var(url)
if (apierror(jsonin, "json") > 0)
return ""
jsonout = json2var(jsonin)
if ( length(jsonout) > 0)
print jsonout
return length(jsonout)
}
# ___ Redirects (-B)
# Note: Must set namespace - will only return for the given namespace
#
# MediaWiki API:Redirects
# https://www.mediawiki.org/wiki/API:Redirects
#
function redirects(entity, url, results) {
url = G["apiURL"] "action=query&prop=redirects&titles=" urlencodeawk(entity) "&rdprop=title&rdnamespace=" urlencodeawk(G["namespace"]) "&format=json&formatversion=2&rdlimit=500&maxlag=" G["maxlag"]
results = uniq( getrdchanges(url, entity) )
if ( length(results) > 0)
print results
return length(results)
}
function getrdchanges(url, entity, jsonin, jsonout, continuecode) {
jsonin = http2var(url)
if (apierror(jsonin, "json") > 0)
return ""
jsonout = json2varRd(jsonin)
continuecode = getcontinue(jsonin,"rdcontinue")
while ( continuecode != "-1-1!!-1-1" ) {
url = G["apiURL"] "action=query&prop=redirects&rdprop=title&rdcontinue=" urlencodeawk(continuecode) "&titles=" urlencodeawk(entity) "&rdnamespace=" urlencodeawk(G["namespace"]) "&format=json&formatversion=2&rdlimit=500&maxlag=" G["maxlag"]
jsonin = http2var(url)