-
Notifications
You must be signed in to change notification settings - Fork 58
/
Wiki.java
8980 lines (8388 loc) · 363 KB
/
Wiki.java
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
/**
* @(#)Wiki.java 0.39 12/08/2023
* Copyright (C) 2007 - 2023 MER-C and contributors
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version. Additionally
* this file is subject to the "Classpath" exception.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.wikipedia;
import java.io.*;
import java.net.*;
import java.net.http.*;
import java.nio.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.text.Normalizer;
import java.time.*;
import java.time.format.*;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.logging.*;
import java.util.stream.*;
import java.util.zip.GZIPInputStream;
import javax.security.auth.login.*;
/**
* This is a somewhat sketchy bot framework for editing MediaWiki wikis.
* Requires JDK 21 or greater. Uses the <a
* href="https://mediawiki.org/wiki/API:Main_page">MediaWiki API</a> for most
* operations. It is recommended that the server runs the latest version
* of MediaWiki (1.39), otherwise some functions may not work. This framework
* requires no dependencies outside the core JDK and does not implement any
* functionality added by MediaWiki extensions.
* <p>
* Extended documentation is available
* <a href="https://github.com/MER-C/wiki-java/wiki/Extended-documentation">here</a>.
* All wikilinks are relative to the English Wikipedia and all timestamps are in
* your wiki's time zone.
* <p>
* Please file bug reports <a href="https://en.wikipedia.org/wiki/User_talk:MER-C">here</a>
* or at the <a href="https://github.com/MER-C/wiki-java/issues">Github issue
* tracker</a>.
*
* <h2>Configuration variables</h2>
* <p>
* Some configuration is available through <code>java.util.Properties</code>.
* Set the system property <code>wiki-java.properties</code> to a file path
* where a configuration file is located. The available variables are:
* <ul>
* <li><b>maxretries</b>: (default 2) the number of attempts to retry a network
* request before stopping
* <li><b>connecttimeout</b>: (default 30000) maximum allowed time for a HTTP(s)
* connection to be established in milliseconds
* <li><b>readtimeout</b>: (default 180000) maximum allowed time for the read
* to take place in milliseconds (needs to be longer, some connections are
* slow and the data volume is large!).
* <li><b>loguploadsize</b>: (default 22, equivalent to 2^22 = 4 MB) controls
* the log2(size) of each chunk in chunked uploads. Disable chunked uploads
* by setting a large value here (50, equivalent to 2^50 = 1 PB will do).
* Stuff you actually upload must be no larger than 4 GB.
* .</ul>
*
* @author MER-C and contributors
* @version 0.39
*/
public class Wiki implements Comparable<Wiki>
{
// NAMESPACES
/**
* Denotes the namespace of images and media, such that there is no
* description page. Uses the "Media:" prefix.
* @see #FILE_NAMESPACE
* @since 0.03
*/
public static final int MEDIA_NAMESPACE = -2;
/**
* Denotes the namespace of pages with the "Special:" prefix. Note
* that many methods dealing with special pages may spew due to
* raw content not being available.
* @since 0.03
*/
public static final int SPECIAL_NAMESPACE = -1;
/**
* Denotes the main namespace, with no prefix.
* @since 0.03
*/
public static final int MAIN_NAMESPACE = 0;
/**
* Denotes the namespace for talk pages relating to the main
* namespace, denoted by the prefix "Talk:".
* @since 0.03
*/
public static final int TALK_NAMESPACE = 1;
/**
* Denotes the namespace for user pages, given the prefix "User:".
* @since 0.03
*/
public static final int USER_NAMESPACE = 2;
/**
* Denotes the namespace for user talk pages, given the prefix
* "User talk:".
* @since 0.03
*/
public static final int USER_TALK_NAMESPACE = 3;
/**
* Denotes the namespace for pages relating to the project,
* with prefix "Project:". It also goes by the name of whatever
* the project name was.
* @since 0.03
*/
public static final int PROJECT_NAMESPACE = 4;
/**
* Denotes the namespace for talk pages relating to project
* pages, with prefix "Project talk:". It also goes by the name
* of whatever the project name was, + "talk:".
* @since 0.03
*/
public static final int PROJECT_TALK_NAMESPACE = 5;
/**
* Denotes the namespace for file description pages. Has the prefix
* "File:". Do not create these directly, use upload() instead.
* @see #MEDIA_NAMESPACE
* @since 0.25
*/
public static final int FILE_NAMESPACE = 6;
/**
* Denotes talk pages for file description pages. Has the prefix
* "File talk:".
* @since 0.25
*/
public static final int FILE_TALK_NAMESPACE = 7;
/**
* Denotes the namespace for (wiki) system messages, given the prefix
* "MediaWiki:".
* @since 0.03
*/
public static final int MEDIAWIKI_NAMESPACE = 8;
/**
* Denotes the namespace for talk pages relating to system messages,
* given the prefix "MediaWiki talk:".
* @since 0.03
*/
public static final int MEDIAWIKI_TALK_NAMESPACE = 9;
/**
* Denotes the namespace for templates, given the prefix "Template:".
* @since 0.03
*/
public static final int TEMPLATE_NAMESPACE = 10;
/**
* Denotes the namespace for talk pages regarding templates, given
* the prefix "Template talk:".
* @since 0.03
*/
public static final int TEMPLATE_TALK_NAMESPACE = 11;
/**
* Denotes the namespace for help pages, given the prefix "Help:".
* @since 0.03
*/
public static final int HELP_NAMESPACE = 12;
/**
* Denotes the namespace for talk pages regarding help pages, given
* the prefix "Help talk:".
* @since 0.03
*/
public static final int HELP_TALK_NAMESPACE = 13;
/**
* Denotes the namespace for category description pages. Has the
* prefix "Category:".
* @since 0.03
*/
public static final int CATEGORY_NAMESPACE = 14;
/**
* Denotes the namespace for talk pages regarding categories. Has the
* prefix "Category talk:".
* @since 0.03
*/
public static final int CATEGORY_TALK_NAMESPACE = 15;
/**
* Denotes all namespaces.
* @since 0.03
*/
public static final int ALL_NAMESPACES = 0x09f91102;
// LOG TYPES
/**
* Denotes all logs.
* @since 0.06
*/
public static final String ALL_LOGS = "";
/**
* Denotes the user creation log.
* @since 0.06
*/
public static final String USER_CREATION_LOG = "newusers";
/**
* Denotes the upload log.
* @since 0.06
*/
public static final String UPLOAD_LOG = "upload";
/**
* Denotes the deletion log.
* @since 0.06
*/
public static final String DELETION_LOG = "delete";
/**
* Denotes the move log.
* @since 0.06
*/
public static final String MOVE_LOG = "move";
/**
* Denotes the block log.
* @since 0.06
*/
public static final String BLOCK_LOG = "block";
/**
* Denotes the protection log.
* @since 0.06
*/
public static final String PROTECTION_LOG = "protect";
/**
* Denotes the user rights log.
* @since 0.06
*/
public static final String USER_RIGHTS_LOG = "rights";
/**
* Denotes the user renaming log.
* @since 0.06
*/
public static final String USER_RENAME_LOG = "renameuser";
/**
* Denotes the page importation log.
* @since 0.08
*/
public static final String IMPORT_LOG = "import";
/**
* Denotes the edit patrol log.
* @since 0.08
*/
public static final String PATROL_LOG = "patrol";
/**
* Denotes the page creation log.
* @since 0.36
*/
public static final String PAGE_CREATION_LOG = "create";
// PROTECTION LEVELS
/**
* Denotes a non-protected page.
* @since 0.09
*/
public static final String NO_PROTECTION = "all";
/**
* Denotes semi-protection (only autoconfirmed users can perform a
* action).
* @since 0.09
*/
public static final String SEMI_PROTECTION = "autoconfirmed";
/**
* Denotes full protection (only admins can perform a particular action).
* @since 0.09
*/
public static final String FULL_PROTECTION = "sysop";
// ASSERTION MODES
/**
* Use no assertions.
* @see #setAssertionMode
* @since 0.11
*/
public static final int ASSERT_NONE = 0;
/**
* Assert that we are logged in. This is checked every action.
* @see #setAssertionMode
* @since 0.30
*/
public static final int ASSERT_USER = 1;
/**
* Assert that we have a bot flag. This is checked every action.
* @see #setAssertionMode
* @since 0.11
*/
public static final int ASSERT_BOT = 2;
/**
* Assert that we have no new messages. Not defined officially, but
* some bots have this. This is checked intermittently.
* @see #setAssertionMode
* @since 0.11
*/
public static final int ASSERT_NO_MESSAGES = 4;
/**
* Assert that we have a sysop flag. This is checked intermittently.
* @see #setAssertionMode
* @since 0.30
*/
public static final int ASSERT_SYSOP = 8;
// REVISION OPTIONS
/**
* In {@link org.wikipedia.Wiki.Revision#diff(long, String) Revision.diff()},
* denotes the next revision.
* @see org.wikipedia.Wiki.Revision#diff(long, String)
* @since 0.21
*/
public static final long NEXT_REVISION = -1L;
/**
* In {@link org.wikipedia.Wiki.Revision#diff(long, String) Revision.diff()},
* denotes the current revision.
* @see org.wikipedia.Wiki.Revision#diff(long, String)
* @since 0.21
*/
public static final long CURRENT_REVISION = -2L;
/**
* In {@link org.wikipedia.Wiki.Revision#diff(long, String) Revision.diff()},
* denotes the previous revision.
* @see org.wikipedia.Wiki.Revision#diff(long, String)
* @since 0.21
*/
public static final long PREVIOUS_REVISION = -3L;
/**
* The list of options the user can specify for his/her gender.
* @see User#getGender()
* @since 0.24
*/
public enum Gender
{
// These names come from the MW API so we can use valueOf() and
// toString() without any fidgets whatsoever. Java naming conventions
// aren't worth another 20 lines of code.
/**
* The user self-identifies as a male.
* @since 0.24
*/
male,
/**
* The user self-identifies as a female.
* @since 0.24
*/
female,
/**
* The user has not specified a gender in preferences.
* @since 0.24
*/
unknown;
}
private static final String version = "0.39";
// fundamental URL strings
private final String protocol, domain, articlePath, scriptPath;
private String base, articleUrl;
/**
* Stores default HTTP parameters for API calls. Contains {@linkplain
* #setMaxLag(int) maxlag}, {@linkplain #setResolveRedirects(boolean) redirect
* resolution} and {@linkplain #setAssertionMode(int) user and bot assertions}
* when wanted by default. Add stuff to this map if you want to add parameters
* to every API call.
* @see #makeApiCall(Map, Map, String)
*/
protected ConcurrentHashMap<String, String> defaultApiParams;
/**
* URL entrypoint for the MediaWiki API. (Needs to be accessible to
* subclasses.)
* @see #initVars()
* @see #getApiUrl()
* @see <a href="https://mediawiki.org/wiki/Manual:Api.php">MediaWiki
* documentation</a>
*/
protected String apiUrl;
// wiki properties
private boolean siteinfofetched = false;
private boolean wgCapitalLinks = true;
private String dbname;
private String mwVersion;
private ZoneId timezone = ZoneOffset.UTC;
private Locale locale = Locale.ENGLISH;
private List<String> extensions = Collections.emptyList();
private LinkedHashMap<String, Integer> namespaces = null;
private ArrayList<Integer> ns_subpages = null;
private LinkedHashMap<String, String> iwmap = new LinkedHashMap<>();
// user management
private HttpClient client;
private final CookieManager cookies;
private User user;
private int statuscounter = 0;
// watchlist cache
private List<String> watchlist = null;
// preferences
private int max = 500;
private int slowmax = 50;
private int throttle = 10000;
private int maxlag = 5;
private int assertion = ASSERT_NONE; // assertion mode
private int statusinterval = 100; // status check
private int querylimit = Integer.MAX_VALUE;
private String useragent = "Wiki.java/" + version + " (https://github.com/MER-C/wiki-java/)";
private boolean markminor = false, markbot = false;
private boolean resolveredirect = false;
private Level loglevel = Level.ALL;
private static final Logger logger = Logger.getLogger("wiki");
// Store time when the last throttled action was executed
private long lastThrottleActionTime = 0;
// config via properties
private final int maxtries;
private final int read_timeout_msec;
private final int log2_upload_size;
// CONSTRUCTORS AND CONFIGURATION
/**
* Creates a new MediaWiki API client for the given wiki with <a
* href="https://mediawiki.org/wiki/Manual:$wgScriptPath"><var>
* $wgScriptPath</var></a> set to <var>scriptPath</var> and via the
* specified protocol.
*
* @param domain the wiki domain name
* @param articlePath the article path
* @param scriptPath the script path
* @param protocol a protocol e.g. "http://", "https://" or "file:///"
* @since 0.39
*/
protected Wiki(String domain, String articlePath, String scriptPath, String protocol)
{
this.domain = Objects.requireNonNull(domain);
this.articlePath = Objects.requireNonNull(articlePath);
this.scriptPath = Objects.requireNonNull(scriptPath);
this.protocol = Objects.requireNonNull(protocol);
defaultApiParams = new ConcurrentHashMap<>();
defaultApiParams.put("format", "xml");
defaultApiParams.put("maxlag", String.valueOf(maxlag));
logger.setLevel(loglevel);
logger.log(Level.CONFIG, "[{0}] Using Wiki.java {1}", new Object[] { domain, version });
// read in config
Properties props = new Properties();
String filename = System.getProperty("wiki-java.properties");
if (filename != null)
{
try
{
InputStream in = new FileInputStream(new File(filename));
props.load(in);
}
catch (IOException ex)
{
logger.log(Level.WARNING, "Unable to load properties file " + filename);
}
}
maxtries = Integer.parseInt(props.getProperty("maxretries", "2"));
log2_upload_size = Integer.parseInt(props.getProperty("loguploadsize", "22")); // 4 MB
read_timeout_msec = Integer.parseInt(props.getProperty("readtimeout", "180000")); // 180 seconds
cookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(30))
.cookieHandler(cookies)
.build();
}
/**
* Creates a new MediaWiki API client for the given wiki with <a
* href="https://mediawiki.org/wiki/Manual:$wgScriptPath"><var>
* $wgScriptPath</var></a> set to <var>scriptPath</var> and via the
* specified protocol.
*
* @param domain the wiki domain name
* @param scriptPath the script path
* @param protocol a protocol e.g. "http://", "https://" or "file:///"
* @since 0.31
*/
protected Wiki(String domain, String scriptPath, String protocol)
{
this(domain, "/wiki/", scriptPath, protocol);
}
/**
* Creates a new MediaWiki API client for the given wiki using HTTPS.
* Depending on the settings of the wiki, you may need to call {@link
* Wiki#getSiteInfo()} on the returned object after this in order for some
* functionality to work correctly.
*
* @param domain the wiki domain name e.g. en.wikipedia.org (defaults to
* en.wikipedia.org)
* @return the constructed API client object
* @since 0.34
*/
public static Wiki newSession(String domain)
{
return newSession(domain, "/w", "https://");
}
/**
* Creates a new MediaWiki API client for the given wiki with <a
* href="https://mediawiki.org/wiki/Manual:$wgScriptPath"><var>
* $wgScriptPath</var></a> set to <var>scriptPath</var> and <a
* href="https://www.mediawiki.org/wiki/Manual:$wgArticlePath">
* <var>$wgArticlePath</var></a> set to <var>articlePath</var> via the
* specified protocol. Depending on the settings of the wiki, you may need
* to call {@link Wiki#getSiteInfo()} on the returned object after this in
* order for some functionality to work correctly.
*
* <p>All factory methods in subclasses must call {@link #initVars()}.
*
* @param domain the wiki domain name
* @param articlePath the article path
* @param scriptPath the script path
* @param protocol a protocol e.g. "http://", "https://" or "file:///"
* @return the constructed API client object
* @since 0.39
*/
public static Wiki newSession(String domain, String articlePath, String scriptPath, String protocol)
{
// Don't put network requests here. Servlets cannot afford to make
// unnecessary network requests in initialization.
Wiki wiki = new Wiki(domain, articlePath, scriptPath, protocol);
wiki.initVars();
return wiki;
}
/**
* Creates a new MediaWiki API client for the given wiki with <a
* href="https://mediawiki.org/wiki/Manual:$wgScriptPath"><var>
* $wgScriptPath</var></a> set to <var>scriptPath</var> and via the
* specified protocol. Depending on the settings of the wiki, you may need
* to call {@link Wiki#getSiteInfo()} on the returned object after this in
* order for some functionality to work correctly.
*
* <p>All factory methods in subclasses must call {@link #initVars()}.
*
* @param domain the wiki domain name
* @param scriptPath the script path
* @param protocol a protocol e.g. "http://", "https://" or "file:///"
* @return the constructed API client object
* @since 0.34
*/
public static Wiki newSession(String domain, String scriptPath, String protocol)
{
return newSession(domain, "/wiki/", scriptPath, protocol);
}
/**
* Edit this if you need to change the API and human interface url
* configuration of the wiki. One example use is to change the port number.
*
* <p>Contributed by Tedder
* @since 0.24
*/
protected void initVars()
{
try {
base = new URI(protocol + domain + scriptPath + "/index.php").normalize().toString();
apiUrl = new URI(protocol + domain + scriptPath + "/api.php").normalize().toString();
articleUrl = new URI(protocol + domain + articlePath).normalize().toString();
} catch(URISyntaxException e) {
// Log and throw exception
log(Level.SEVERE, "initVars", "Provided URI is invalid: " + e.getMessage());
throw new IllegalArgumentException("Invalid URI schema provided.");
}
}
/**
* Gets the domain of the wiki as supplied on construction.
* @return the domain of the wiki
* @since 0.06
*/
public final String getDomain()
{
return domain;
}
/**
* Gets the <a href="https://mediawiki.org/wiki/Manual:$wgArticlePath"><var>
* $wgArticlePath</var></a> variable as supplied on construction.
* @return the article path of the wiki
* @since 0.39
*/
public final String getArticlePath()
{
return articlePath;
}
/**
* Gets the <a href="https://mediawiki.org/wiki/Manual:$wgScriptPath"><var>
* $wgScriptPath</var></a> variable as supplied on construction.
* @return the script path of the wiki
* @since 0.14
*/
public final String getScriptPath()
{
return scriptPath;
}
/**
* Gets the protocol used to access this MediaWiki instance, as supplied
* on construction.
* @return (see above)
* @since 0.35
*/
public final String getProtocol()
{
return protocol;
}
/**
* Determines whether this wiki is equal to another object based on the
* protocol (not case sensitive), domain (not case sensitive) and
* scriptPath (case sensitive). A return value of {@code true} means two
* Wiki objects point to the same instance of MediaWiki.
* @param obj the object to compare
* @return whether the wikis point to the same instance of MediaWiki
*/
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof Wiki))
return false;
Wiki other = (Wiki)obj;
return domain.equalsIgnoreCase(other.domain)
&& scriptPath.equals(other.scriptPath)
&& protocol.equalsIgnoreCase(other.protocol);
}
/**
* Returns a hash code of this object based on the protocol, domain and
* scriptpath.
* @return a hash code
*/
@Override
public int hashCode()
{
// English locale used here for reproducability and so network requests
// are not required
int hc = domain.toLowerCase(Locale.ENGLISH).hashCode();
hc = 127 * hc + scriptPath.hashCode();
hc = 127 * hc + protocol.toLowerCase(Locale.ENGLISH).hashCode();
return hc;
}
/**
* Allows wikis to be sorted based on their domain (case insensitive), then
* their script path (case sensitive). If 0 is returned, it is reasonable
* both Wikis point to the same instance of MediaWiki.
* @param other the wiki to compare to
* @return -1 if this wiki is alphabetically before the other, 1 if after
* and 0 if they are likely to be the same instance of MediaWiki
* @since 0.35
*/
@Override
public int compareTo(Wiki other)
{
int result = domain.compareToIgnoreCase(other.domain);
if (result == 0)
result = scriptPath.compareTo(other.scriptPath);
return result;
}
/**
* Gets the URL of index.php.
* @return (see above)
* @see <a href="https://mediawiki.org/wiki/Manual:Parameters_to_index.php">
* MediaWiki documentation</a>
* @since 0.35
*/
public String getIndexPhpUrl()
{
return base;
}
/**
* Gets the URL of api.php.
* @return (see above)
* @see <a href="https://mediawiki.org/wiki/Manual:Api.php">MediaWiki
* documentation</a>
* @since 0.36
*/
public String getApiUrl()
{
return apiUrl;
}
/**
* Gets the editing throttle.
* @return the throttle value in milliseconds
* @see #setThrottle
* @since 0.09
*/
public int getThrottle()
{
return throttle;
}
/**
* Sets the throttle, which limits most write requests to no more than one
* per wiki instance in the given time across all threads. (As a
* consequence, all throttled methods are thread safe.) Read requests are
* not throttled or restricted in any way. Default is 10 seconds.
*
* @param throttle the new throttle value in milliseconds
* @see #getThrottle
* @since 0.09
*/
public void setThrottle(int throttle)
{
this.throttle = throttle;
log(Level.CONFIG, "setThrottle", "Throttle set to " + throttle + " milliseconds");
}
/**
* Gets various properties of the wiki and sets the bot framework up to use
* them. The return value is cached. This method is thread safe. Returns:
* <ul>
* <li><b>usingcapitallinks</b>: (Boolean) whether a wiki forces upper case
* for the title. Example: en.wikipedia = true, en.wiktionary = false.
* Default = true. See <a href="https://mediawiki.org/wiki/Manual:$wgCapitalLinks">
* <var>$wgCapitalLinks</var></a>
* <li><b>scriptpath</b>: (String) the <a
* href="https://mediawiki.org/wiki/Manual:$wgScriptPath"><var>
* $wgScriptPath</var> wiki variable</a>. Default = {@code /w}.
* <li><b>version</b>: (String) the MediaWiki version used for this wiki
* <li><b>timezone</b>: (ZoneId) the timezone the wiki is in, default = UTC
* <li><b>locale</b>: (Locale) the locale of the wiki
* <li><b>dbname</b>: (String) the internal name of the database
* </ul>
*
* @return (see above)
* @since 0.30
* @throws IOException if a network error occurs
* @deprecated This method is likely going to get renamed with the return
* type changed to void once I finish cleaning up the site info caching
* mechanism. Use the specialized methods instead.
*/
@Deprecated
public synchronized Map<String, Object> getSiteInfo() throws IOException
{
Map<String, Object> siteinfo = new HashMap<>();
if (!siteinfofetched)
{
Map<String, String> getparams = new HashMap<>();
getparams.put("action", "query");
getparams.put("meta", "siteinfo");
getparams.put("siprop", "namespaces|namespacealiases|general|extensions|interwikimap");
String line = makeApiCall(getparams, null, "getSiteInfo");
detectUncheckedErrors(line, null, null);
// general site info
String bits = line.substring(line.indexOf("<general "), line.indexOf("</general>"));
wgCapitalLinks = parseAttribute(bits, "case", 0).equals("first-letter");
timezone = ZoneId.of(parseAttribute(bits, "timezone", 0));
mwVersion = parseAttribute(bits, "generator", 0);
locale = new Locale(parseAttribute(bits, "lang", 0));
dbname = parseAttribute(bits, "wikiid", 0);
// parse extensions
bits = line.substring(line.indexOf("<extensions>"), line.indexOf("</extensions>"));
extensions = new ArrayList<>();
String[] unparsed = bits.split("<ext ");
for (int i = 1; i < unparsed.length; i++)
extensions.add(parseAttribute(unparsed[i], "name", 0));
// populate namespace cache
namespaces = new LinkedHashMap<>(30);
ns_subpages = new ArrayList<>(30);
// xml form: <ns id="-2" canonical="Media" ... >Media</ns> or <ns id="0" ... />
String[] items = line.split("<ns ");
for (int i = 1; i < items.length; i++)
{
int ns = Integer.parseInt(parseAttribute(items[i], "id", 0));
// parse localized namespace name
// must be before parsing canonical namespace so that
// namespaceIdentifier always returns the localized name
int b = items[i].indexOf('>') + 1;
int c = items[i].indexOf("</ns>");
if (c < 0)
namespaces.put("", ns);
else
namespaces.put(normalize(decode(items[i].substring(b, c))), ns);
String canonicalnamespace = parseAttribute(items[i], "canonical", 0);
if (canonicalnamespace != null)
namespaces.put(canonicalnamespace, ns);
// does this namespace support subpages?
if (items[i].contains("subpages=\"\""))
ns_subpages.add(ns);
}
// interwiki map
bits = line.substring(line.indexOf("<interwikimap>"), line.indexOf("</interwikimap>"));
unparsed = bits.split("<iw ");
for (int i = 1; i < unparsed.length; i++)
iwmap.put(parseAttribute(unparsed[i], "prefix", 0), parseAttribute(unparsed[i], "url", 0));
siteinfofetched = true;
log(Level.INFO, "getSiteInfo", "Successfully retrieved site info for " + getDomain());
}
siteinfo.put("usingcapitallinks", wgCapitalLinks);
siteinfo.put("scriptpath", scriptPath);
siteinfo.put("timezone", timezone);
siteinfo.put("version", mwVersion);
siteinfo.put("locale", locale);
siteinfo.put("extensions", extensions);
siteinfo.put("dbname", dbname);
return siteinfo;
}
/**
* Gets the version of MediaWiki this wiki runs e.g. 1.20wmf5 (54b4fcb).
* See [[Special:Version]] on your wiki.
* @return (see above)
* @throws UncheckedIOException if the site info cache has not been
* populated and a network error occurred when populating it
* @since 0.14
* @see <a href="https://gerrit.wikimedia.org/">MediaWiki Git</a>
*/
public String version()
{
ensureNamespaceCache();
return mwVersion;
}
/**
* Detects whether a wiki forces upper case for the first character in a
* title. Example: en.wikipedia = true, en.wiktionary = false.
* @return (see above)
* @throws UncheckedIOException if the site info cache has not been
* populated and a network error occurred when populating it
* @see <a href="https://mediawiki.org/wiki/Manual:$wgCapitalLinks">MediaWiki
* documentation</a>
* @since 0.30
*/
public boolean usesCapitalLinks()
{
ensureNamespaceCache();
return wgCapitalLinks;
}
/**
* Returns the list of extensions installed on this wiki.
* @return (see above)
* @throws UncheckedIOException if the site info cache has not been
* populated and a network error occurred when populating it
* @see <a href="https://www.mediawiki.org/wiki/Manual:Extensions">MediaWiki
* documentation</a>
* @since 0.35
*/
public List<String> installedExtensions()
{
ensureNamespaceCache();
return new ArrayList<>(extensions);
}
/**
* Gets the timezone of this wiki
* @return (see above)
* @throws UncheckedIOException if the site info cache has not been
* populated and a network error occurred when populating it
* @since 0.35
*/
public ZoneId timezone()
{
ensureNamespaceCache();
return timezone;
}
/**
* Gets the locale of this wiki.
* @return (see above)
* @throws UncheckedIOException if the site info cache has not been
* populated and a network error occurred when populating it
* @since 0.35
*/
public Locale locale()
{
ensureNamespaceCache();
return locale;
}
/**
* Gets the interwiki map of this wiki. The return type is a many to one
* map between interwiki link prefixes (e.g. "m" for meta.wikimedia.org)
* and the target URL with placeholders (e.g. https://meta.wikimedia.org/wiki/$1 ).
* @return a Map prefix → URL with placeholders
* @throws UncheckedIOException if the site info cache has not been
* populated and a network error occurred when populating it
* @since 0.39
*/
public Map<String, String> interWikiMap()
{
ensureNamespaceCache();
return iwmap;
}
/**
* Sets the user agent HTTP header to be used for requests. Default is
* <samp>"Wiki.java " + version</samp>.
* @param useragent the new user agent
* @since 0.22
*/
public void setUserAgent(String useragent)
{
this.useragent = useragent;
}
/**
* Gets the user agent HTTP header to be used for requests. Default is
* <samp>"Wiki.java " + version</samp>.
* @return useragent the user agent
* @since 0.22
*/
public String getUserAgent()
{
return useragent;
}
/**
* Checks whether API action=query dependencies automatically resolve
* redirects (default = false).
* @return (see above)
* @since 0.27
*/
public boolean isResolvingRedirects()
{
return resolveredirect;
}
/**
* Sets whether API action=query dependencies automatically resolve
* redirects (default = false).
* @param b (see above)
* @since 0.27