-
Notifications
You must be signed in to change notification settings - Fork 5
/
OAuth.php
1453 lines (1195 loc) · 41.7 KB
/
OAuth.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
namespace Toolforge ;
require_once( __DIR__ . '/../public_html/php/WbstackMagnusOauth.php' );
class OAuth {
var $use_tag_parameter = true ;
var $tag_parameter_whitelist = ['distributed-game'];
var $use_cookies = true ;
var $testing = false ;
var $tool ;
var $debugging = false ;
var $language , $project ;
var $ini_file , $params ;
var $mwOAuthUrl = 'https://www.mediawiki.org/w/index.php?title=Special:OAuth';
var $publicMwOAuthUrl; //if the mediawiki url given to the user is different from how this
//script may see it (e.g. if behind a proxy) set the user url here.
var $mwOAuthIW = 'mw'; // Set this to the interwiki prefix for the OAuth central wiki.
var $userinfo ;
var $auto_detect_lag = false ;
var $delay_after_create_s = 2 ;
var $delay_after_edit_s = 1 ;
var $delay_after_upload_s = 1 ;
function __construct ( $t , $l = '' , $p = '' , $oauth_url = '' ) {
if ( is_array($t) ) { // Bespoke override for third-party sites
foreach ( $t AS $k => $v ) {
$this->$k = $v ;
}
} else {
$this->tool = $t ;
$this->language = $l ;
$this->project = $p ;
$this->ini_file = "/data/project/$t/oauth.ini" ;
if ( $l == 'wikidata' ) $this->apiUrl = 'https://www.wikidata.org/w/api.php' ;
elseif ( $l == 'commons' ) $this->apiUrl = 'https://commons.wikimedia.org/w/api.php' ;
elseif ( $p == 'mediawiki' ) $this->apiUrl = 'https://www.mediawiki.org/w/api.php' ;
else $this->apiUrl = "https://$l.$p.org/w/api.php" ;
}
if ( !isset( $this->publicMwOAuthUrl )) {
$this->publicMwOAuthUrl = $this->mwOAuthUrl;
}
if ( $oauth_url != '' ) $this->publicMwOAuthUrl = $oauth_url ;
$this->loadIniFile() ;
$this->setupSession() ;
$this->loadToken() ;
if ( isset( $_GET['oauth_verifier'] ) && $_GET['oauth_verifier'] ) {
$this->fetchAccessToken();
}
}
function sleepAfterEdit ( $type ) {
if ( $this->auto_detect_lag ) { // Try to auto-detect lag
$url = $this->apiUrl . '?action=query&meta=siteinfo&format=json&maxlag=-1' ;
$t = @file_get_contents ( $url ) ;
if ( $t !== false ) {
$j = @json_decode ( $t ) ;
if ( isset($j->error->lag) ) {
$lag = $j->error->lag ;
if ( $lag > 1 ) sleep ( $lag * 3 ) ;
return ;
}
}
}
if ( $type == 'create' ) sleep ( $this->delay_after_create_s ) ;
if ( $type == 'edit' ) sleep ( $this->delay_after_edit_s ) ;
if ( $type == 'upload' ) sleep ( $this->delay_after_upload_s ) ;
}
function logout () {
$this->setupSession() ;
session_start();
setcookie ( 'tokenKey' , '' , 1 , '/'.$this->tool.'/' ) ;
setcookie ( 'tokenSecret' , '' , 1 , '/'.$this->tool.'/' ) ;
$_SESSION['tokenKey'] = '' ;
$_SESSION['tokenSecret'] = '' ;
session_write_close();
}
function setupSession() {
// Setup the session cookie
session_name( $this->tool );
$params = session_get_cookie_params();
session_set_cookie_params(
$params['lifetime'],
dirname( $_SERVER['SCRIPT_NAME'] )
);
}
function loadIniFile () {
//$this->params = parse_ini_file ( $this->ini_file ) ;
$this->params = \WbstackMagnusOauth::parse_ini_file( $this->ini_file );
$this->gUserAgent = $this->params['agent'];
if ( !isset($this->gUserAgent) or $this->gUserAgent == '' ) throw new \Exception ( "Cannot get user agent from ini file '{$this->ini_file}'" ) ;
$this->gConsumerKey = $this->params['consumerKey'];
if ( !isset($this->gConsumerKey) or $this->gConsumerKey == '' ) throw new \Exception ( "Cannot get consumer key from ini file '{$this->ini_file}'" ) ;
$this->gConsumerSecret = $this->params['consumerSecret'];
if ( !isset($this->gConsumerSecret) or $this->gConsumerSecret == '' ) throw new \Exception ( "Cannot get consumer secret from ini file '{$this->ini_file}'" ) ;
}
// Load the user token (request or access) from the session
function loadToken() {
$this->gTokenKey = '';
$this->gTokenSecret = '';
session_start();
if ( isset( $_SESSION['tokenKey'] ) ) {
$this->gTokenKey = $_SESSION['tokenKey'];
$this->gTokenSecret = $_SESSION['tokenSecret'];
} elseif ( $this->use_cookies and isset( $_COOKIE['tokenKey'] ) ) {
$this->gTokenKey = $_COOKIE['tokenKey'];
$this->gTokenSecret = $_COOKIE['tokenSecret'];
}
session_write_close();
}
/**
* Handle a callback to fetch the access token
* @return void
*/
function fetchAccessToken() {
$url = $this->mwOAuthUrl . '/token';
$url .= strpos( $url, '?' ) ? '&' : '?';
$url .= http_build_query( [
'format' => 'json',
'oauth_verifier' => $_GET['oauth_verifier'],
// OAuth information
'oauth_consumer_key' => $this->gConsumerKey,
'oauth_token' => $this->gTokenKey,
'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',
] );
$this->signature = $this->sign_request( 'GET', $url );
$url .= "&oauth_signature=" . urlencode( $this->signature );
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
//curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_USERAGENT, $this->gUserAgent );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
$data = curl_exec( $ch );
if ( isset ( $_REQUEST['test'] ) ) {
print "<h1>LOGIN</h1><pre>" ; print_r ( $data ) ; print "</pre></hr>" ;
}
if ( !$data ) {
// header( "HTTP/1.1 500 Internal Server Error" );
throw new \Exception ( 'Curl error: ' . htmlspecialchars( curl_error( $ch ) ) ) ;
}
curl_close( $ch );
$token = json_decode( $data );
if ( is_object( $token ) && isset( $token->error ) ) {
// header( "HTTP/1.1 500 Internal Server Error" );
throw new \Exception ( 'Error retrieving token2: ' . htmlspecialchars( json_encode($token) ) ) ;
}
if ( !is_object( $token ) || !isset( $token->key ) || !isset( $token->secret ) ) {
// header( "HTTP/1.1 500 Internal Server Error" );
throw new \Exception ( 'Invalid response from token request' ) ;
}
// Save the access token
session_start();
$_SESSION['tokenKey'] = $this->gTokenKey = $token->key;
$_SESSION['tokenSecret'] = $this->gTokenSecret = $token->secret;
if ( $this->use_cookies ) {
$t = time()+60*60*24*30*3 ; // expires in three months
setcookie ( 'tokenKey' , $_SESSION['tokenKey'] , $t , '/'.$this->tool.'/' ) ;
setcookie ( 'tokenSecret' , $_SESSION['tokenSecret'] , $t , '/'.$this->tool.'/' ) ;
}
session_write_close();
}
/**
* Utility function to sign a request
*
* Note this doesn't properly handle the case where a parameter is set both in
* the query string in $url and in $params, or non-scalar values in $params.
*
* @param string $method Generally "GET" or "POST"
* @param string $url URL string
* @param array $params Extra parameters for the Authorization header or post
* data (if application/x-www-form-urlencoded).
* @return string Signature
*/
function sign_request( $method, $url, $params = [] ) {
// global $gConsumerSecret, $gTokenSecret;
$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 ) );
$key = rawurlencode( $this->gConsumerSecret ) . '&' . rawurlencode( $this->gTokenSecret );
return base64_encode( hash_hmac( 'sha1', $toSign, $key, true ) );
}
/**
* Request authorization
* @return void
*/
function doAuthorizationRedirect($callback='') {
// First, we need to fetch a request token.
// The request is signed with an empty token secret and no token key.
$this->gTokenSecret = '';
$url = $this->mwOAuthUrl . '/initiate';
$url .= strpos( $url, '?' ) ? '&' : '?';
$query = [
'format' => 'json',
// OAuth information
'oauth_callback' => 'oob', // Must be "oob" for MWOAuth
'oauth_consumer_key' => $this->gConsumerKey,
'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',
] ;
if ( $callback!='' ) $query['oauth_callback'] = $callback ;
$url .= http_build_query( $query );
$signature = $this->sign_request( 'GET', $url );
$url .= "&oauth_signature=" . urlencode( $signature );
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
//curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_USERAGENT, $this->gUserAgent );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
$data = curl_exec( $ch );
if ( !$data ) {
header( "HTTP/1.1 500 Internal Server Error" );
throw new \Exception ( 'Curl error: ' . htmlspecialchars( curl_error( $ch ) ) ) ;
}
curl_close( $ch );
$token = json_decode( $data );
if ( $token === NULL ) {
throw new \Exception ( $data ) ;
}
if ( is_object( $token ) && isset( $token->error ) ) {
header( "HTTP/1.1 500 Internal Server Error" );
$token->callback = $callback ;
throw new \Exception ( 'Error retrieving token1: ' . htmlspecialchars( json_encode($token) ) ) ;
}
if ( !is_object( $token ) || !isset( $token->key ) || !isset( $token->secret ) ) {
header( "HTTP/1.1 500 Internal Server Error" );
throw new \Exception ( 'Invalid response from token request' ) ;
}
// Now we have the request token, we need to save it for later.
session_start();
$_SESSION['tokenKey'] = $token->key;
$_SESSION['tokenSecret'] = $token->secret;
if ( $this->use_cookies ) {
$t = time()+60*60*24*30 ; // expires in one month
setcookie ( 'tokenKey' , $_SESSION['tokenKey'] , $t , '/'.$this->tool.'/' ) ;
setcookie ( 'tokenSecret' , $_SESSION['tokenSecret'] , $t , '/'.$this->tool.'/' ) ;
}
session_write_close();
// Then we send the user off to authorize
$url = $this->publicMwOAuthUrl . '/authorize';
$url .= strpos( $url, '?' ) ? '&' : '?';
$arr = [
'oauth_token' => $token->key,
'oauth_consumer_key' => $this->gConsumerKey,
] ;
if ( $callback != '' ) $arr['callback'] = $callback ;
$url .= http_build_query( $arr );
header( "Location: $url" );
echo 'Please see <a href="' . htmlspecialchars( $url ) . '">' . htmlspecialchars( $url ) . '</a>';
}
function doIdentify() {
$url = $this->mwOAuthUrl . '/identify';
$headerArr = [
// OAuth information
'oauth_consumer_key' => $this->gConsumerKey,
'oauth_token' => $this->gTokenKey,
'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 = $this->sign_request( 'GET', $url, $headerArr );
$headerArr['oauth_signature'] = $signature;
$header = [];
foreach ( $headerArr as $k => $v ) {
$header[] = rawurlencode( $k ) . '="' . rawurlencode( $v ) . '"';
}
$header = 'Authorization: OAuth ' . join( ', ', $header );
if ( $this->testing ) print "HEADER: {$header}\n" ;
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, [ $header ] );
//curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_USERAGENT, $this->gUserAgent );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
$data = curl_exec( $ch );
if ( !$data ) {
header( "HTTP/1.1 $errorCode Internal Server Error" );
throw new \Exception ( 'Curl error: ' . htmlspecialchars( curl_error( $ch ) ) ) ;
}
$err = json_decode( $data );
if ( is_object( $err ) && isset( $err->error ) && $err->error === 'mwoauthdatastore-access-token-not-found' ) {
// We're not authorized!
# echo 'You haven\'t authorized this application yet! Go <a href="' . htmlspecialchars( $_SERVER['SCRIPT_NAME'] ) . '?action=authorize">here</a> to do that.';
# echo '<hr>';
return (object) ['is_authorized'=>false] ;
}
// There are three fields in the response
$fields = explode( '.', $data );
if ( count( $fields ) !== 3 ) {
header( "HTTP/1.1 $errorCode Internal Server Error" );
throw new \Exception ( 'Invalid identify response: ' . htmlspecialchars( $data ) ) ;
}
// 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' ) {
header( "HTTP/1.1 $errorCode Internal Server Error" );
throw new \Exception ( 'Invalid header in identify response: ' . htmlspecialchars( $data ) ) ;
}
// Verify the signature
$sig = base64_decode( strtr( $fields[2], '-_', '+/' ), true );
$check = hash_hmac( 'sha256', $fields[0] . '.' . $fields[1], $this->gConsumerSecret, true );
if ( $sig !== $check ) {
header( "HTTP/1.1 $errorCode Internal Server Error" );
$out = 'JWT signature validation failed: ' . htmlspecialchars( $data );
$out .= '<pre>'; var_dump( base64_encode($sig), base64_encode($check) ); echo '</pre>';
throw new \Exception ( $out ) ;
}
// Decode the payload
$payload = base64_decode( strtr( $fields[1], '-_', '+/' ), true );
if ( $payload !== false ) {
$payload = json_decode( $payload );
}
if ( !is_object( $payload ) ) {
header( "HTTP/1.1 $errorCode Internal Server Error" );
throw new \Exception ( 'Invalid payload in identify response: ' . htmlspecialchars( $data ) ) ;
}
$payload->is_authorized = true ;
return $payload ;
}
/**
* Send an API query with OAuth authorization
*
* @param array $post Post data
* @param object $ch Curl handle
* @return array API results
*/
function doApiQuery( $post, &$ch = null , $mode = '' , $iterations_left = 5 , $last_maxlag = -1 ) {
if ( $iterations_left <= 0 ) return ; // Avoid infinite recursion when Wikidata Is Too Damn Slow Again
global $maxlag ;
if ( !isset($maxlag) ) $maxlag = 5 ;
$maxlag *= 1 ;
$last_maxlag *= 1 ;
$give_maxlag = $maxlag ;
if ( $last_maxlag != -1 ) $give_maxlag = $last_maxlag ;
$give_maxlag *= 1 ;
// Not an edit, high maxlag allowed
if ( isset($post['action']) and $post['action']=='query' and isset($post['meta']) and $post['meta']=='userinfo' ) {
$give_maxlag = 99999 ;
}
$post['maxlag'] = round ( $give_maxlag * 1 ) ;
if ( isset ( $_REQUEST['test'] ) ) print "<pre>GIVEN MAXLAG:{$give_maxlag}</pre>" ;
$headerArr = [
// OAuth information
'oauth_consumer_key' => $this->gConsumerKey,
'oauth_token' => $this->gTokenKey,
'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',
];
if ( isset ( $_REQUEST['test'] ) ) {
print "<pre>" ;
print "!!\n" ;
// print_r ( $headerArr ) ;
print "</pre>" ;
}
$to_sign = '' ;
if ( $mode == 'upload' ) {
$to_sign = $headerArr ;
} else {
$to_sign = $post + $headerArr ;
}
$url = $this->apiUrl ;
if ( $mode == 'identify' ) $url .= '/identify' ;
$signature = $this->sign_request( 'POST', $url, $to_sign );
$headerArr['oauth_signature'] = $signature;
$header = [];
foreach ( $headerArr as $k => $v ) {
$header[] = rawurlencode( $k ) . '="' . rawurlencode( $v ) . '"';
}
$header = 'Authorization: OAuth ' . join( ', ', $header );
if ( !$ch ) {
$ch = curl_init();
}
$post_fields = '' ;
if ( $mode == 'upload' ) {
$post_fields = $post ;
$post_fields['file'] = new CurlFile($post['file'], 'application/octet-stream', $post['filename']);
} else {
$post_fields = http_build_query( $post ) ;
}
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_fields );
curl_setopt( $ch, CURLOPT_HTTPHEADER, [ $header ] );
//curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_USERAGENT, $this->gUserAgent );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
$data = curl_exec( $ch );
if ( isset ( $_REQUEST['test'] ) ) {
print "<hr/><h3>API query</h3>" ;
// print "URL:<pre>$url</pre>" ;
// print "Header:<pre>" ; print_r ( $header ) ; print "</pre>" ;
print "Payload:<pre>" ; print_r ( $post ) ; print "</pre>" ;
print "Result:<pre>" ; print_r ( $data ) ; print "</pre>" ;
print "<hr/>" ;
}
if ( !$data ) return ;
$ret = json_decode( $data );
if ( $ret == null ) return ;
# maxlag
if ( isset($ret->error) and isset($ret->error->code) and $ret->error->code == 'maxlag' ) {
$lag = $maxlag * 1 ;
if ( isset($ret->error->lag) ) $last_maxlag = $ret->error->lag*1 + $maxlag*1 ;
sleep ( $lag ) ;
$ch = null ;
$ret = $this->doApiQuery( $post, $ch , '' , $iterations_left-1 , $last_maxlag*1 ) ;
}
return $ret ;
}
// Wikidata-specific methods
function doesClaimExist ( $claim ) {
$q = 'Q' . str_replace('Q','',$claim['q'].'') ;
$p = 'P' . str_replace('P','',$claim['prop'].'') ;
$url = 'https://www.wikidata.org/w/api.php?action=wbgetentities&format=json&props=claims&ids=' . $q ;
$j = json_decode ( file_get_contents ( $url ) ) ;
if ( !isset ( $j->entities ) ) return false ;
if ( !isset ( $j->entities->$q ) ) return false ;
if ( !isset ( $j->entities->$q->claims ) ) return false ;
if ( !isset ( $j->entities->$q->claims->$p ) ) return false ;
$nid = 'numeric-id' ;
$does_exist = false ;
$cp = $j->entities->$q->claims->$p ; // Claims for this property
foreach ( $cp AS $k => $v ) {
if ( $claim['type'] == 'item' ) {
if ( !isset($v->mainsnak) ) continue ;
if ( !isset($v->mainsnak->datavalue) ) continue ;
if ( !isset($v->mainsnak->datavalue->value) ) continue ;
if ( $v->mainsnak->datavalue->value->$nid != str_replace('Q','',$claim['target'].'') ) continue ;
$does_exist = true ;
} elseif ( $claim['type'] == 'string' ) {
if ( !isset($v->mainsnak) ) continue ;
if ( !isset($v->mainsnak->datavalue) ) continue ;
if ( !isset($v->mainsnak->datavalue->value) ) continue ;
if ( $v->mainsnak->datavalue->value != $claim['text'] ) continue ;
$does_exist = true ;
} elseif ( $claim['type'] == 'date' ) {
if ( !isset($v->mainsnak) ) continue ;
if ( !isset($v->mainsnak->datavalue) ) continue ;
if ( !isset($v->mainsnak->datavalue->value) ) continue ;
if ( !isset($v->mainsnak->datavalue->value->time) ) continue ;
if ( $v->mainsnak->datavalue->value->time != $claim['date'] ) continue ;
if ( $v->mainsnak->datavalue->value->precision != $claim['prec'] ) continue ;
$does_exist = true ;
} else if ( $claim['type'] == 'monolingualtext' ) {
if ( !isset($v->mainsnak) ) continue ;
if ( !isset($v->mainsnak->datavalue) ) continue ;
if ( !isset($v->mainsnak->datavalue->value) ) continue ;
if ( !isset($v->mainsnak->datavalue->value->text) ) continue ;
if ( $v->mainsnak->datavalue->value->text != $claim['text'] ) continue ;
if ( $v->mainsnak->datavalue->value->language != $claim['language'] ) continue ;
$does_exist = true ;
} else if ( $claim['type'] == 'quantity' ) {
if ( !isset($v->mainsnak) ) continue ;
if ( !isset($v->mainsnak->datavalue) ) continue ;
if ( !isset($v->mainsnak->datavalue->value) ) continue ;
if ( !isset($v->mainsnak->datavalue->value->amount) ) continue ;
if ( $v->mainsnak->datavalue->value->amount != $claim['amount'] ) continue ;
if ( $v->mainsnak->datavalue->value->unit != $claim['unit'] ) continue ;
$does_exist = true ;
}
}
return $does_exist ;
}
function getConsumerRights () {
$ch = null;
$res = $this->doApiQuery( [
'format' => 'json',
'action' => 'query',
'meta' => 'userinfo',
'uiprop' => 'blockinfo|groups|rights'
], $ch );
// $url = $this->apiUrl . "?action=query&meta=userinfo&uiprop=blockinfo|groups|rights&format=json" ;
// $ret = json_decode ( file_get_content ( $url ) ) ;
return $res ;
}
function setToolTag ( &$params , $summary = '' ) {
global $tool_hashtag ;
if ( $this->use_tag_parameter and isset($tool_hashtag) and $tool_hashtag!='undefined' and in_array($tool_hashtag,$this->tag_parameter_whitelist) ) {
if ( isset($tool_hashtag) and $tool_hashtag != '' ) {
if (isset($params['tags'])) $params['tags'] .= "|{$tool_hashtag}";
else $params['tags'] = $tool_hashtag ;
}
} else {
if ( isset($tool_hashtag) and $tool_hashtag != '' and $tool_hashtag!='undefined' ) {
if ( $summary == '' ) $summary = "#{$tool_hashtag}" ;
else $summary .= " #{$tool_hashtag}" ;
}
}
if ( $summary != '' ) $params['summary'] = $summary ;
}
function setLabel ( $q , $text , $language , $summary = '' ) {
// Fetch the edit token
$ch = null;
$res = $this->doApiQuery( [
'format' => 'json',
'action' => 'query' ,
'meta' => 'tokens'
], $ch );
if ( !isset( $res->query->tokens->csrftoken ) ) {
$this->error = 'Bad API response [setLabel]: <pre>' . htmlspecialchars( var_export( $res, 1 ) ) . '</pre>';
return false ;
}
$token = $res->query->tokens->csrftoken;
$params = [
'format' => 'json',
'action' => 'wbsetlabel',
'id' => $q,
'language' => $language ,
'value' => $text ,
'token' => $token,
'bot' => 1
] ;
$this->setToolTag($params,$summary);
// Now do that!
$res = $this->doApiQuery( $params , $ch );
if ( isset ( $res->error ) ) {
$this->error = $res->error->info ;
return false ;
}
$this->sleepAfterEdit ( 'edit' ) ;
return true ;
}
function setSitelink ( $q , $site , $title ) {
// Fetch the edit token
$ch = null;
$res = $this->doApiQuery( [
'format' => 'json',
'action' => 'query' ,
'meta' => 'tokens'
], $ch );
if ( !isset( $res->query->tokens->csrftoken ) ) {
$this->error = 'Bad API response [setLabel]: <pre>' . htmlspecialchars( var_export( $res, 1 ) ) . '</pre>';
return false ;
}
$token = $res->query->tokens->csrftoken;
$params = [
'format' => 'json',
'action' => 'wbsetsitelink',
'id' => $q,
'linksite' => $site,
'linktitle' => $title,
'token' => $token,
'bot' => 1
] ;
$this->setToolTag($params,$summary);
// Now do that!
$res = $this->doApiQuery( $params , $ch );
$this->last_res = $res ;
if ( isset ( $res->error ) ) {
$this->error = $res->error->info ;
return false ;
}
$this->sleepAfterEdit ( 'edit' ) ;
return true ;
}
function setDesc ( $q , $text , $language ) {
// Fetch the edit token
$ch = null;
$res = $this->doApiQuery( [
'format' => 'json',
'action' => 'query' ,
'meta' => 'tokens'
], $ch );
if ( !isset( $res->query->tokens->csrftoken ) ) {
$this->error = 'Bad API response [setLabel]: <pre>' . htmlspecialchars( var_export( $res, 1 ) ) . '</pre>';
return false ;
}
$token = $res->query->tokens->csrftoken;
$params = [
'format' => 'json',
'action' => 'wbsetdescription',
'id' => $q,
'language' => $language ,
'value' => $text ,
'token' => $token,
'bot' => 1
] ;
$this->setToolTag($params,$summary);
// Now do that!
$res = $this->doApiQuery( $params , $ch );
if ( isset ( $res->error ) ) {
$this->error = $res->error->info ;
return false ;
}
$this->sleepAfterEdit ( 'edit' ) ;
return true ;
}
function set_Alias ( $q , $text , $language , $mode ) {
// Fetch the edit token
$ch = null;
$res = $this->doApiQuery( [
'format' => 'json',
'action' => 'query' ,
'meta' => 'tokens'
], $ch );
if ( !isset( $res->query->tokens->csrftoken ) ) {
$this->error = 'Bad API response [setLabel]: <pre>' . htmlspecialchars( var_export( $res, 1 ) ) . '</pre>';
return false ;
}
$token = $res->query->tokens->csrftoken;
$params = [
'format' => 'json',
'action' => 'wbsetaliases',
$mode => $text ,
'id' => $q,
'language' => $language ,
// 'value' => $text ,
'token' => $token,
'bot' => 1
] ;
$this->setToolTag($params,$summary);
// Now do that!
$res = $this->doApiQuery( $params , $ch );
if ( isset ( $res->error ) ) {
$this->error = $res->error->info ;
return false ;
}
$this->sleepAfterEdit ( 'edit' ) ;
return true ;
}
function setPageText ( $page , $text ) {
// Fetch the edit token
$ch = null;
$res = $this->doApiQuery( [
'format' => 'json',
'action' => 'query' ,
'meta' => 'tokens'
], $ch );
if ( !isset( $res->query->tokens->csrftoken ) ) {
$this->error = 'Bad API response [setPageText]: <pre>' . htmlspecialchars( var_export( $res, 1 ) ) . '</pre>';
return false ;
}
$token = $res->query->tokens->csrftoken;
$params = [
'format' => 'json',
'action' => 'edit',
'title' => $page,
'text' => $text ,
'minor' => '' ,
'token' => $token,
] ;
$this->setToolTag($params,$summary);
// Now do that!
$res = $this->doApiQuery( $params, $ch );
if ( isset ( $res->error ) ) {
$this->error = $res->error->info ;
return false ;
}
$this->sleepAfterEdit ( 'edit' ) ;
return true ;
}
function addPageText ( $page , $text , $header , $summary , $section ) {
// Fetch the edit token
$ch = null;
$res = $this->doApiQuery( [
'format' => 'json',
'action' => 'query' ,
'meta' => 'tokens'
], $ch );
if ( !isset( $res->query->tokens->csrftoken ) ) {
$this->error = 'Bad API response [setPageText]: <pre>' . htmlspecialchars( var_export( $res, 1 ) ) . '</pre>';
return false ;
}
$token = $res->query->tokens->csrftoken;
$params = [
'format' => 'json',
'action' => 'edit',
'title' => $page,
'appendtext' => $text ,
'sectiontitle' => $header ,
'minor' => '' ,
'token' => $token,
] ;
$this->setToolTag($params,$summary);
if ( isset ( $section ) and $section != '' ) $params['section'] = $section ;
// Now do that!
$res = $this->doApiQuery( $params , $ch );
if ( isset ( $res->error ) ) {
$this->error = $res->error->info ;
return false ;
}
$this->sleepAfterEdit ( 'edit' ) ;
return true ;
}
function createItem ( $data = '' ) {
if ( $data == '' ) $data = (object) [] ;
// Next fetch the edit token
$ch = null;
$res = $this->doApiQuery( [
'format' => 'json',
'action' => 'query' ,
'meta' => 'tokens'
], $ch );
if ( !isset( $res->query->tokens->csrftoken ) ) {
$this->error = 'Bad API response [createItem]: <pre>' . htmlspecialchars( var_export( $res, 1 ) ) . '</pre>';
return false ;
}
$token = $res->query->tokens->csrftoken;
$params = [
'format' => 'json',
'action' => 'wbeditentity',
'new' => 'item' ,
'data' => json_encode ( $data ) ,
'token' => $token,
'bot' => 1
] ;
$this->setToolTag($params,$summary);
$res = $this->doApiQuery( $params , $ch );
if ( isset ( $_REQUEST['test'] ) ) {
print "<pre>" ; print_r ( $res ) ; print "</pre>" ;
}
$this->last_res = $res ;
if ( isset ( $res->error ) ) return false ;
$this->sleepAfterEdit ( 'create' ) ;
return true ;
}
function createItemFromPage ( $site , $page ) {
$page = str_replace ( ' ' , '_' , $page ) ;
// Next fetch the edit token
$ch = null;
$res = $this->doApiQuery( [
'format' => 'json',
'action' => 'query' ,
'meta' => 'tokens'
], $ch );
if ( !isset( $res->query->tokens->csrftoken ) ) {
$this->error = 'Bad API response [createItemFromPage]: <pre>' . htmlspecialchars( var_export( $res, 1 ) ) . '</pre>';
return false ;
}
$token = $res->query->tokens->csrftoken;
$data = [ 'sitelinks' => [ $site => [ "site" => $site ,"title" => $page ] ] ] ;
$m = [] ;
if ( preg_match ( '/^(.+)wiki(|quote)$/' , $site , $m ) ) {
$nice_title = preg_replace ( '/\s+\(.+\)$/' , '' , str_replace ( '_' , ' ' , $page ) ) ;
$lang = $m[1] ;
$lang_map = [
'als' => 'gsw',
'bat_smg' => 'sgs',
'be_x_old' => 'be-tarask',
'bh' => 'bho',
'commons' => 'en',
'fiu_vro' => 'vro',
'mediawiki' => 'en',
'meta' => 'en',
'no' => 'nb',
'roa_rup' => 'rup',
'simple' => 'en',
'species' => 'en',
'wikidata' => 'en',
'zh_classical' => 'lzh',
'zh_min_nan' => 'nan',
'zh_yue' => 'yue',
] ;
if ( isset( $lang_map[ $lang ] ) ) $lang = $lang_map[ $lang ] ;
$data['labels'] = [ $lang => [ 'language' => $lang , 'value' => $nice_title ] ] ;
}
// print "<pre>" ; print_r ( json_encode ( $data ) ) ; print " </pre>" ; return true ;
$params = [
'format' => 'json',
'action' => 'wbeditentity',
'new' => 'item' ,
'data' => json_encode ( $data ) ,
'token' => $token,
'bot' => 1
] ;
$this->setToolTag($params,$summary);
if ( isset ( $_REQUEST['test'] ) ) {
print "<pre>" ; print_r ( $params ) ; print "</pre>" ;
}
$res = $this->doApiQuery( $params , $ch );
if ( isset ( $_REQUEST['test'] ) ) {
print "<pre>" ; print_r ( $res ) ; print "</pre>" ;
}
$this->last_res = $res ;
if ( isset ( $res->error ) ) return false ;
$this->sleepAfterEdit ( 'create' ) ;
return true ;
}
function removeClaim ( $id , $baserev ) {
// Fetch the edit token
$ch = null;
$res = $this->doApiQuery( [
'format' => 'json',
'action' => 'query' ,
'meta' => 'tokens'
], $ch );
if ( !isset( $res->query->tokens->csrftoken ) ) {
$this->error = 'Bad API response [removeClaim]: <pre>' . htmlspecialchars( var_export( $res, 1 ) ) . '</pre>';
return false ;
}
$token = $res->query->tokens->csrftoken;
// Now do that!
$params = [
'format' => 'json',
'action' => 'wbremoveclaims',
'claim' => $id ,
'token' => $token,
'bot' => 1
] ;
$this->setToolTag($params,$summary);
if ( isset ( $baserev ) and $baserev != '' ) $params['baserevid'] = $baserev ;
$res = $this->doApiQuery( $params , $ch );