/
APII.php
4397 lines (4045 loc) · 148 KB
/
APII.php
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
<?php
/*
Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
This file is part of IABot's Framework.
IABot is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
InternetArchiveBot 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with InternetArchiveBot. If not, see <https://www.gnu.org/licenses/agpl-3.0.html>.
*/
/**
* @file
* API object
* @author Maximilian Doerr (Cyberpower678)
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
*/
use Wikimedia\DeadlinkChecker\CheckIfDead;
/**
* API class
* Manages the core functions of IABot including communication to external APIs
* The API class initialized per page, and destroyed at the end of it's use.
* It also manages the page data for every thread, and handles DB and parser calls.
* @author Maximilian Doerr (Cyberpower678)
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
*/
class API
{
/**
* Stores the global curl handle for the bot.
*
* @var resource
* @access protected
* @static
* @staticvar
*/
protected static $globalCurl_handle = null;
/**
* A flag that determines if the profiler is enabled.
*
* @var resource
* @access protected
* @static
* @staticvar
*/
protected static $profiling_enabled = false;
/**
* Stores cached data on users
*
* @var array
* @access protected
* @static
* @staticvar
*/
protected static $userAPICache = [];
/**
* Stores the the limit on the number titles that can be passed to the API
*
* @var array
* @access protected
* @static
*/
protected static $titlesLimit = false;
/**
* Stores the local name of the namespaces
*
* @var array
* @access protected
* @static
*/
protected static $namespaces = false;
/**
* Stores the page redirects to the final destination
*
* @var array
* @access protected
* @static
*/
protected static $redirects = false;
/**
* Temporarily stores the resolved value of a template. Values remain for 1 hour.
*
* @var array
* @access protected
* @static
*/
protected static $templateURLCache = [];
/**
* Stores the list of Categories to lookup
*
* @access public
* @var DB
*/
protected static $categories = false;
/**
* Stores the last edits made within the edit period, if applicable
*
* @access protected
* @var DB
*/
protected static $lastEdits = [];
/**
* Stores the rate limit
*
* @access protected
* @var mixed
*/
protected static $rateLimit = false;
/**
* Configuration variables as set on Wikipedia, as well as page and page id variables.
*
* @var mixed
* @access public
*/
public $page, $pageid, $config;
/**
* Stores the page content for the page being analyzed
*
* @var string
* @access public
*/
public $content = "";
/**
* Stores the revids of the page's history
*
* @var array
* @access public
*/
public $history = [];
/**
* Stores the bot's DB class
*
* @access public
* @var DB
*/
public $db;
/**
* Constructor function for the API class.
* Initializes the DB class and loads the page
* contents of the page.
*
* @param string $page
* @param int $pageid
* @param array $config associative array of config key/values, as specified in deadlink.php
*
* @access public
* @throws Exception
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
public function __construct( $page, $pageid, $config )
{
$this->page = $page;
$this->pageid = $pageid;
$this->config = $config;
$this->content = self::getPageText( $page );
if( $config['rate_limit'] != 0 ) self::$rateLimit = $config['rate_limit'];
$tmp = DBCLASS;
$this->db = new $tmp( $this );
}
/**
* Retrieve the page content
*
* @param string $page Page title to fetch
* @param bool|string $forceURL URL to force the function to use.
*
* @access public
* @static
* @return string Page content
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
public static function getPageText( $page, $forceURL = false, $revID = false )
{
$params = [
'action' => 'raw',
'title' => $page
];
if( $revID !== false && is_numeric( $revID ) ) $params['oldid'] = $revID;
$get = http_build_query( $params );
if( $forceURL === false ) {
$api = str_replace( "api.php", "index.php", API );
} else $api = $forceURL;
if( IAVERBOSE ) echo "Making query: $api?$get\n";
$data = self::makeHTTPRequest( $api, $params );
$headers = curl_getinfo( self::$globalCurl_handle );
if( IAVERBOSE && $headers['http_code'] >= 400 ) {
echo "ERROR: {$headers['http_code']} while retrieving '$page'\n";
return false;
}
return $data;
}
/**
* Create and setup a global curl handle
*
* @access protected
* @static
* @return void
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
protected static function initGlobalCurlHandle()
{
self::$globalCurl_handle = curl_init();
curl_setopt( self::$globalCurl_handle, CURLOPT_COOKIEFILE, COOKIE );
curl_setopt( self::$globalCurl_handle, CURLOPT_COOKIEJAR, COOKIE );
curl_setopt( self::$globalCurl_handle, CURLOPT_USERAGENT, USERAGENT );
curl_setopt( self::$globalCurl_handle, CURLOPT_MAXCONNECTS, 100 );
curl_setopt( self::$globalCurl_handle, CURLOPT_MAXREDIRS, 20 );
curl_setopt( self::$globalCurl_handle, CURLOPT_ENCODING, 'gzip' );
curl_setopt( self::$globalCurl_handle, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( self::$globalCurl_handle, CURLOPT_TIMEOUT, 100 );
curl_setopt( self::$globalCurl_handle, CURLOPT_CONNECTTIMEOUT, 10 );
curl_setopt( self::$globalCurl_handle, CURLOPT_FOLLOWLOCATION, 0 );
curl_setopt( self::$globalCurl_handle, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( self::$globalCurl_handle, CURLOPT_SAFE_UPLOAD, true );
@curl_setopt( self::$globalCurl_handle, CURLOPT_DNS_USE_GLOBAL_CACHE, true );
curl_setopt( self::$globalCurl_handle, CURLOPT_DNS_CACHE_TIMEOUT, 60 );
curl_setopt( self::$globalCurl_handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
if( PHP_MAJOR_VERSION . "." . PHP_MINOR_VERSION >= 7.3 ) {
curl_setopt( self::$globalCurl_handle,
CURLOPT_SSLVERSION,
CURL_SSLVERSION_TLSv1_3
);
}
}
/**
* Check if a list of pages exist locally
*
* @access private
* @static
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
* @param $url Endpoint to query
* @param array $query Params to send
* @param bool $usePOST How to send those params
* @param bool $useOAuth Authenticate with OAuth
* @param array $keys Optional OAuth keys to pass
* @return bool|string Query results
* @throws Exception
*/
private static function makeHTTPRequest( $url, $query = [], $usePOST = false, $useOAuth = true, $keys = [],
$headers = []
) {
global $accessibleWikis;
if( is_null( self::$globalCurl_handle ) ) self::initGlobalCurlHandle();
if( in_array( $url, [ API, $accessibleWikis[WIKIPEDIA]['i18nsource'] ] ) || strpos( $url, OAUTH ) !== false ) {
curl_setopt( self::$globalCurl_handle, CURLOPT_FOLLOWLOCATION, 0 );
} else {
curl_setopt( self::$globalCurl_handle, CURLOPT_FOLLOWLOCATION, 1 );
}
if( $usePOST ) {
curl_setopt( self::$globalCurl_handle, CURLOPT_URL, $url );
curl_setopt( self::$globalCurl_handle, CURLOPT_HTTPGET, 0 );
curl_setopt( self::$globalCurl_handle, CURLOPT_POST, 1 );
curl_setopt( self::$globalCurl_handle, CURLOPT_POSTFIELDS, $query );
} else {
if( !empty( $query ) ) {
$get = http_build_query( $query );
curl_setopt( self::$globalCurl_handle, CURLOPT_URL, $url . "?$get" );
} else {
curl_setopt( self::$globalCurl_handle, CURLOPT_URL, $url );
}
curl_setopt( self::$globalCurl_handle, CURLOPT_HTTPGET, 1 );
curl_setopt( self::$globalCurl_handle, CURLOPT_POST, 0 );
}
if( $useOAuth ) {
if( $usePOST ) {
curl_setopt( self::$globalCurl_handle, CURLOPT_HTTPHEADER,
[ self::generateOAuthHeader( 'POST', $url, $keys ) ]
);
} else {
if( isset( $get ) ) {
curl_setopt( self::$globalCurl_handle, CURLOPT_HTTPHEADER,
[ self::generateOAuthHeader( 'GET', $url . "?$get", $keys ) ]
);
} else {
curl_setopt( self::$globalCurl_handle, CURLOPT_HTTPHEADER,
[ self::generateOAuthHeader( 'GET', $url, $keys ) ]
);
}
}
}
if( !empty( $headers ) ) {
curl_setopt( self::$globalCurl_handle, CURLOPT_HTTPHEADER, $headers );
}
$data = curl_exec( self::$globalCurl_handle );
$curlData = curl_getinfo( self::$globalCurl_handle );
if( !empty( $curlData['redirect_url'] ) ) {
if( $url == API ) {
echo "Config Error: The API is located elsewhere. Updating configuration and terminating!\n";
$accessibleWikis[WIKIPEDIA]['apiurl'] = $curlData['redirect_url'];
DB::setConfiguration( 'global', 'systemglobals-allwikis', WIKIPEDIA, $accessibleWikis[WIKIPEDIA] );
exit( 1 );
}
if( strpos( $url, OAUTH ) !== false ) {
echo "Config Error: The OAuth module is located elsewhere. Updating configuration and terminating!\n";
$piece = str_replace( OAUTH, '', $url );
$accessibleWikis[WIKIPEDIA]['oauthurl'] = str_replace( $piece, '', $curlData['redirect_url'] );
DB::setConfiguration( 'global', 'systemglobals-allwikis', WIKIPEDIA, $accessibleWikis[WIKIPEDIA] );
exit( 1 );
}
if( $url == $accessibleWikis[WIKIPEDIA]['i18nsource'] ) {
echo "Config Error: The meta wiki is located elsewhere. Updating configuration and terminating!\n";
$accessibleWikis[WIKIPEDIA]['i18nsource'] = $curlData['redirect_url'];
DB::setConfiguration( 'global', 'systemglobals-allwikis', WIKIPEDIA, $accessibleWikis[WIKIPEDIA] );
exit( 1 );
}
}
return $data;
}
/**
* Check if a list of pages exist locally
*
* @access public
* @static
* @param array List of pages to check for
* @return array Whether or not each page exists
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
public static function pagesExist( $pageList )
{
$returnArray = [];
$sliced = true;
$pageLists = array_chunk( $pageList, self::getTitlesLimit() );
do {
if( !$sliced ) $pageLists = [ $pageList ];
foreach( $pageLists as $subList ) {
$params = [
'action' => "query",
'format' => "json",
'titles' => implode( '|', $subList )
];
$out = http_build_query( $params );
if( IAVERBOSE ) echo "Making query: $out\n";
$data = self::makeHTTPRequest( API, $params, true );
$data = json_decode( $data, true );
if( isset( $data['error']['code'] ) && $data['error']['code'] == 'toomanyvalues' ) {
$sliced = true;
$pageLists = array_chunk( $pageList, $data['error']['limit'] );
break;
}
if( !empty( $data['query']['pages'] ) ) {
foreach( $data['query']['pages'] as $pid => $pageInfo ) {
$pageListID = array_search( $pageInfo['title'], $pageList );
if( $pageListID === false ) {
foreach( $data['query']['normalized'] as $normalized ) {
if( $pageInfo['title'] == $normalized['to'] ) break;
}
$pageListID = array_search( $normalized['from'], $pageList );
}
$returnArray[$pageList[$pageListID]] = !isset( $pageInfo['missing'] );
unset( $pageList[$pageListID] );
}
}
$sliced = false;
}
} while( !empty( $pageList ) );
return $returnArray;
}
/**
* Generates a header field to be sent during MW
* API BOT Requests
*
* @param string $method CURL Method being used
* @param string $url URL being CURLed to.
*
* @access public
* @static
* @return string Header field
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
public static function generateOAuthHeader( $method = 'GET', $url, $keys = [] )
{
if( !empty( $keys['consumerkey'] ) && !empty( $keys['consumersecret'] ) && !empty( $keys['accesstoken'] ) &&
!empty( $keys['accesssecret'] ) ) {
$headerArr = [
// OAuth information
'oauth_consumer_key' => $keys['consumerkey'],
'oauth_token' => $keys['accesstoken'],
'oauth_version' => '1.0',
'oauth_nonce' => md5( microtime() . mt_rand() ),
'oauth_timestamp' => time(),
// We're using secret key signatures here.
'oauth_signature_method' => 'HMAC-SHA1',
];
$signature =
@self::generateSignature( $method, $url, $headerArr, $keys['consumersecret'], $keys['accesssecret'] );
} elseif( defined( 'CONSUMERKEY' ) && defined( 'ACCESSTOKEN' ) ) {
$headerArr = [
// OAuth information
'oauth_consumer_key' => CONSUMERKEY,
'oauth_token' => ACCESSTOKEN,
'oauth_version' => '1.0',
'oauth_nonce' => md5( microtime() . mt_rand() ),
'oauth_timestamp' => time(),
// We're using secret key signatures here.
'oauth_signature_method' => 'HMAC-SHA1',
];
$signature = @self::generateSignature( $method, $url, $headerArr );
} else return "";
$headerArr['oauth_signature'] = $signature;
$header = [];
foreach( $headerArr as $k => $v ) {
$header[] = rawurlencode( $k ) . '="' . rawurlencode( $v ) . '"';
}
$header = 'Authorization: OAuth ' . join( ', ', $header );
unset( $headerArr );
return $header;
}
/**
* Signs the OAuth header field
*
* @param string $method CURL method being used
* @param string $url URL being CURLed to
* @param array $params parameters of the OAUTH header and the URL parameters
*
* @access protected
* @static
* @return base64 encoded signature
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
protected static function generateSignature( $method, $url, $params = [], $consumerSecret = false,
$accessSecret = false
) {
$parts = parse_url( $url );
// We need to normalize the endpoint URL
$scheme = isset( $parts['scheme'] ) ? $parts['scheme'] : 'http';
$host = isset( $parts['host'] ) ? $parts['host'] : '';
$port = isset( $parts['port'] ) ? $parts['port'] : ( $scheme == 'https' ? '443' : '80' );
$path = isset( $parts['path'] ) ? $parts['path'] : '';
if( ( $scheme == 'https' && $port != '443' ) ||
( $scheme == 'http' && $port != '80' )
) {
// Only include the port if it's not the default
$host = "$host:$port";
}
// Also the parameters
$pairs = [];
parse_str( isset( $parts['query'] ) ? $parts['query'] : '', $query );
$query += $params;
unset( $query['oauth_signature'] );
if( $query ) {
$query = array_combine(
// rawurlencode follows RFC 3986 since PHP 5.3
array_map( 'rawurlencode', array_keys( $query ) ),
array_map( 'rawurlencode', array_values( $query ) )
);
ksort( $query, SORT_STRING );
foreach( $query as $k => $v ) {
$pairs[] = "$k=$v";
}
}
$toSign = rawurlencode( strtoupper( $method ) ) . '&' .
rawurlencode( "$scheme://$host$path" ) . '&' .
rawurlencode( join( '&', $pairs ) );
if( $accessSecret && $consumerSecret ) {
$key = rawurlencode( $consumerSecret ) . '&' . rawurlencode( $accessSecret );
} else $key = rawurlencode( CONSUMERSECRET ) . '&' . rawurlencode( ACCESSSECRET );
return base64_encode( hash_hmac( 'sha1', $toSign, $key, true ) );
}
/**
* Find out who reverted the text and why
*
* @param int userID The user ID to look up
*
* @access public
* @static
* @return array User information
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
public static function getUser( $userID )
{
if( isset( self::$userAPICache[$userID] ) ) return self::$userAPICache[$userID];
$params = [
'action' => 'query',
'list' => 'users',
'ususerids' => $userID,
'usprop' => 'groups|rights|registration|editcount|blockinfo|centralids',
'format' => 'json'
];
$get = http_build_query( $params );
if( IAVERBOSE ) echo "Making query: $get\n";
$data = self::makeHTTPRequest( API, $params );
$data = json_decode( $data, true );
self::$userAPICache[$userID] = $data['query']['users'][0];
return $data['query']['users'][0];
}
/**
* Verify tokens and keys and authenticate as defined user, USERNAME
* Uses OAuth
* @access public
* @static
* @return bool Successful login
*
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
public static function botLogon()
{
echo "Logging on as " . USERNAME . "...";
$error = "";
$url = OAUTH . '/identify';
if( IAVERBOSE ) echo "Making query: $url\n";
$data = self::makeHTTPRequest( $url, [], true );
if( !$data ) {
$error = 'Curl error: ' . htmlspecialchars( curl_error( self::$globalCurl_handle ) );
goto loginerror;
}
$err = json_decode( $data );
if( is_object( $err ) && isset( $err->error ) && $err->error === 'mwoauthdatastore-access-token-not-found' ) {
// We're not authorized!
$error = "Missing authorization or authorization failed";
goto loginerror;
}
// There are three fields in the response
$fields = explode( '.', $data );
if( count( $fields ) !== 3 ) {
$error = 'Invalid identify response: ' . htmlspecialchars( $data );
goto loginerror;
}
// Validate the header. MWOAuth always returns alg "HS256".
$header = base64_decode( strtr( $fields[0], '-_', '+/' ), true );
if( $header !== false ) {
$header = json_decode( $header );
}
if( !is_object( $header ) || $header->typ !== 'JWT' || $header->alg !== 'HS256' ) {
$error = 'Invalid header in identify response: ' . htmlspecialchars( $data );
goto loginerror;
}
// Verify the signature
$sig = base64_decode( strtr( $fields[2], '-_', '+/' ), true );
$check = hash_hmac( 'sha256', $fields[0] . '.' . $fields[1], CONSUMERSECRET, true );
if( $sig !== $check ) {
$error = 'JWT signature validation failed: ' . htmlspecialchars( $data );
goto loginerror;
}
// Decode the payload
$payload = base64_decode( strtr( $fields[1], '-_', '+/' ), true );
if( $payload !== false ) {
$payload = json_decode( $payload );
}
if( !is_object( $payload ) ) {
$error = 'Invalid payload in identify response: ' . htmlspecialchars( $data );
goto loginerror;
}
if( USERNAME == $payload->username ) {
echo "Success!!\n\n";
return true;
} else {
loginerror:
echo "Failed!!\n";
if( !empty( $error ) ) {
echo "ERROR: $error\n";
} else echo "ERROR: The bot logged into the wrong username.\n";
return false;
}
}
/**
* Fetches the wiki configuration values.
*
* @access Public
* @static
* @return array Loaded configuration from on wiki.
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
public static function fetchConfiguration( &$isDefined = false, $getCiteDefinitions = true, $force = false )
{
$config = [
'link_scan' => 0,
'dead_only' => 2,
'tag_override' => 1,
'page_scan' => 0,
'archive_by_accessdate' => 1,
'touch_archive' => 0,
'notify_on_talk' => 1,
'notify_on_talk_only' => 0,
'notify_error_on_talk' => 1,
'talk_message_header' => "Links modified on main page",
'talk_message' => "Please review the links modified on the main page...",
'talk_message_header_talk_only' => "Links needing modification on main page",
'talk_message_talk_only' => "Please review and fix the links I found needing fixing...",
'talk_error_message' => "There were problems archiving a few links on the page.",
'talk_error_message_header' => "Notification of problematic links",
'talk_message_verbose' => 0,
'deadlink_tags' => [],
'dateformat' => [],
'templatebehavior' => "append",
'ignore_tags' => [ "{{cbignore}}" ],
'talk_only_tags' => [ "{{cbtalkonly}}" ],
'no_talk_tags' => [ "{{cbnotalk}}" ],
'ref_bounds' => [],
'paywall_tags' => [],
'archive_tags' => [],
'sarchive_tags' => [],
'aarchive_tags' => [],
'notify_domains' => [],
'verify_dead' => 1,
'archive_alive' => 1,
'convert_archives' => 1,
'convert_archives_encoding' => 1,
'convert_to_cites' => 1,
'mladdarchivetalkonly' => "{link}->{newarchive}",
'mltaggedtalkonly' => "{link}",
'mltagremovedtalkonly' => "{link}",
'mladdarchive' => "{link}->{newarchive}",
'mlmodifyarchive' => "{link}->{newarchive}<--{oldarchive}",
'mlfix' => "{link}",
'mltagged' => "{link}",
'mltagremoved' => "{link}",
'mldefault' => "{link}",
'plerror' => "{problem}: {error}",
'maineditsummary' => "Fixing dead links",
'errortalkeditsummary' => "Errors encountered during archiving",
'talkeditsummary' => "Links have been altered",
'tag_cites' => 1,
'rate_limit' => false
];
$configDB = DB::getConfiguration( WIKIPEDIA, "wikiconfig" );
$archiveTemplates = CiteMap::getMaps( WIKIPEDIA, $force, 'archive' );
if( $getCiteDefinitions === true ) {
$tmp = CiteMap::getMaps( WIKIPEDIA, $force );
foreach( $tmp as $key => $object ) {
if( is_null( $object ) ) continue;
if( !$object->isDisabled() ) $templateList[] = "{{{$key}}}";
}
unset( $tmp );
}
if( isset( $configDB['deadlink_tags_data'] ) && !( $configDB['deadlink_tags_data'] instanceof CiteMap ) ) {
$configDB['deadlink_tags_data'] = CiteMap::getMaps( WIKIPEDIA, $force, 'dead' );
}
$configDB['archive_tags'] = [];
$configDB['sarchive_tags'] = [];
$configDB['aarchive_tags'] = [];
foreach( $archiveTemplates as $name => $template ) {
$name = str_replace( " ", "_", $name );
$configDB['all_archives'][$name] = $template;
if( isset( $configDB["darchive_$name"] ) ) {
$configDB['using_archives'][] = $name;
$configDB['archive_tags'] = array_merge( $configDB['archive_tags'], $configDB["darchive_$name"] );
if( $template['templatebehavior'] == 'swallow' ) {
$configDB['sarchive_tags'] = array_merge( $configDB['sarchive_tags'], $configDB["darchive_$name"] );
} else {
$configDB['aarchive_tags'] = array_merge( $configDB['aarchive_tags'], $configDB["darchive_$name"] );
}
}
}
if( !isset( $configDB['deprecated_archives'] ) ) {
$configDB['deprecated_archives'] = [];
}
$isDefined = true;
foreach( $config as $name => $defaultValue ) {
if( !isset( $configDB[$name] ) ) {
if( !in_array( $name, [ 'ref_bounds', 'rate_limit' ] ) ) $isDefined = false;
$configDB[$name] = $config[$name];
}
}
$config = $configDB;
self::$rateLimit = $config['rate_limit'];
if( isset( $templateList ) ) {
$config['citation_tags'] = $templateList;
} else $config['citation_tags'] = [];
return $config;
}
/**
* Fetches the final redirect location of a redirecting page.
*
* @param string $pageTitle The title of the page to follow, including the namespace
*
* @access Public
* @static
* @return string Final page destination or false on failure
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
public static function getRedirectRoot( $pageTitle )
{
if( isset( self::$redirects[$pageTitle] ) ) return self::$redirects[$pageTitle];
$params = [
'action' => "query",
'format' => "json",
'redirects' => "1",
'titles' => $pageTitle
];
$get = http_build_query( $params );
if( IAVERBOSE ) echo "Making query: $get\n";
$data = self::makeHTTPRequest( API, $params );
$data = json_decode( $data, true );
$endTarget = $pageTitle;
if( !empty( $data['query']['normalized'] ) ) {
foreach( $data['query']['normalized'] as $redirect ) {
if( $redirect['from'] == $endTarget ) $endTarget = $redirect['to'];
}
}
if( !empty( $data['query']['redirects'] ) ) {
foreach( $data['query']['redirects'] as $redirect ) {
if( $redirect['from'] == $endTarget ) $endTarget = $redirect['to'];
}
}
self::$redirects[$pageTitle] = $endTarget;
return $endTarget;
}
/**
* Fetches the onwiki citoid JSON values.
*
* @access Public
* @static
* @return array Fetched citoid and respective template data from the wiki.
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
public static function retrieveCitoidDefinitions()
{
$returnArray = [];
$citoidMapTypes = self::getPageText( "MediaWiki:Citoid-template-type-map.json" );
if( !empty( $citoidMapTypes ) && ( $citoidMapTypes = json_decode( $citoidMapTypes, true ) ) ) {
$returnArray['mapped_templates'] = $citoidMapTypes;
$returnArray['unique_templates'] = array_unique( $citoidMapTypes, SORT_REGULAR );
foreach( $returnArray['unique_templates'] as $cite ) {
$templateData = self::getTemplateData( $cite );
if( !empty( $templateData ) ) $returnArray['template_data'][$cite] = $templateData;
}
}
return $returnArray;
}
/**
* Fetches the templatedata JSON values.
*
* @access Public
* @static
* @return array Fetched template data from the wiki.
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
public static function getTemplateData( $template )
{
$template = trim( $template, "{}" );
$pageNameTemplate = self::getTemplateNamespaceName() . ":$template";
$params = [
'action' => "templatedata",
'format' => "json",
'titles' => $pageNameTemplate,
'includeMissingTitles' => "1",
'lang' => "en",
'redirects' => "1"
];
$get = http_build_query( $params );
if( IAVERBOSE ) echo "Making query: $get\n";
$data = self::makeHTTPRequest( API, $params );
$data = json_decode( $data, true );
if( !empty( $data['pages'] ) ) {
foreach( $data['pages'] as $pageData ) {
if( isset( $pageData['missing'] ) ) return false;
return $pageData;
}
} else return false;
}
/**
* Get name of a namespace
*
* @access public
* @static
* @return string The name of the Template namespace
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
public static function getNamespaceName( $namespace )
{
if( self::$namespaces === false ) {
$params = [
'action' => 'query',
'meta' => 'siteinfo',
'format' => 'json',
'siprop' => 'namespaces'
];
$get = http_build_query( $params );
if( IAVERBOSE ) echo "Making query: $get\n";
$tried = 0;
do {
$data = self::makeHTTPRequest( API, $params );
$data = json_decode( $data, true );
$tried++;
} while( empty( $data['query']['namespaces'] ) && $tried < 10 );
if( empty( $data['query']['namespaces'] ) ) return false;
self::$namespaces = $data['query']['namespaces'];
}
if( isset( self::$namespaces[$namespace] ) ) {
return self::$namespaces[$namespace]['*'];
} else return false;
}
/**
* Get name of Template namespace
*
* @access public
* @static
* @return string The name of the Template namespace
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
public static function getTemplateNamespaceName()
{
return self::getNamespaceName( 10 );
}
/**
* Get name of Module namespace
*
* @access public
* @static
* @return string The name of the Module namespace
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
public static function getModuleNamespaceName()
{
return self::getNamespaceName( 828 );
}
/**
* Retrieves a batch of articles from Wikipedia
*
* @param int $limit How many articles to return in a batch
* @param array $resume Where to resume in the batch retrieval process
* @param int $namespace Which namespace the bot should operate in
*
* @access public
* @static
* @return array A list of pages with respective page IDs.
* @license https://www.gnu.org/licenses/agpl-3.0.txt
* @copyright Copyright (c) 2015-2021, Maximilian Doerr, Internet Archive
* @author Maximilian Doerr (Cyberpower678)
*/
public static function getAllArticles( $limit, array $resume, $namespace = 0 )
{
$returnArray = [];
while( true ) {
$params = [
'action' => 'query',
'list' => 'allpages',
'format' => 'json',
'apnamespace' => $namespace,
'apfilterredir' => 'nonredirects',
'aplimit' => $limit - count( $returnArray )
];
if( defined( 'APPREFIX' ) ) $params['apprefix'] = APPREFIX;
$params = array_merge( $params, $resume );
$get = http_build_query( $params );
if( IAVERBOSE ) echo "Making query: $get\n";
$data = self::makeHTTPRequest( API, $params );
$data = json_decode( $data, true );
$returnArray = array_merge( $returnArray, $data['query']['allpages'] );
if( isset( $data['continue'] ) ) {
$resume = $data['continue'];
} else {
$resume = [];
break;
}
if( $limit <= count( $returnArray ) ) break;
}