forked from hamstar/Wikimate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Wikimate.php
2603 lines (2304 loc) · 80.9 KB
/
Wikimate.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
/**
* Wikimate is a wrapper for the MediaWiki API that aims to be very easy to use.
*
* @package Wikimate
* @version 1.1.0
* @copyright SPDX-License-Identifier: MIT
*/
/**
* Provides an interface over wiki API objects such as pages and files.
*
* All requests to the API can throw WikimateException if the server is lagged
* and a finite number of retries is exhausted. By default requests are
* retried indefinitely. See {@see Wikimate::request()} for more information.
*
* @author Robert McLeod & Frans P. de Vries
* @since 0.2 December 2010
*/
class Wikimate
{
/**
* The current version number (conforms to Semantic Versioning)
*
* @var string
* @link https://semver.org/
*/
const VERSION = '1.1.0';
/**
* Identifier for CSRF token
*
* @var string
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Tokens
*/
const TOKEN_DEFAULT = 'csrf';
/**
* Identifier for Login token
*
* @var string
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Tokens
*/
const TOKEN_LOGIN = 'login';
/**
* Default lag value in seconds
*
* @var integer
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Maxlag_parameter
*/
const MAXLAG_DEFAULT = 5;
/**
* Base URL for API requests
*
* @var string
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Main_page#Endpoint
*/
protected $api;
/**
* Default headers for Requests_Session
*
* @var array
*/
protected $headers;
/**
* Default data for Requests_Session
*
* @var array
*/
protected $data;
/**
* Default options for Requests_Session
*
* @var array
*/
protected $options;
/**
* Username for API requests
*
* @var string
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Login#Method_1._login
*/
protected $username;
/**
* Password for API requests
*
* @var string
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Login#Method_1._login
*/
protected $password;
/**
* Session object for HTTP requests
*
* @var Requests_Session
* @link https://requests.ryanmccue.info/
*/
protected $session;
/**
* User agent string for Requests_Session
*
* @var string
* @link https://requests.ryanmccue.info/docs/usage-advanced.html#session-handling
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Etiquette#The_User-Agent_header
*/
protected $useragent;
/**
* Error array with API and Wikimate errors
*
* @var array|null
*/
protected $error = null;
/**
* Whether to output debug logging
*
* @var boolean
*/
protected $debugMode = false;
/**
* Maximum lag in seconds to accept in requests
*
* @var integer
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Maxlag_parameter
*/
protected $maxlag = self::MAXLAG_DEFAULT;
/**
* Maximum number of retries for lagged requests (-1 = retry indefinitely)
*
* @var integer
*/
protected $maxretries = -1;
/**
* Stored CSRF token for API requests
*
* @var string|null
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Tokens
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Edit#Additional_notes
*/
private $csrfToken = null;
/**
* Stored parameter lists for API modules
*
* @var array
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Parameter_information
*/
private $moduleParams = array();
/**
* Creates a new Wikimate object.
*
* @param string $api Base URL for the API
* @param array $headers Default headers for API requests
* @param array $data Default data for API requests
* @param array $options Default options for API requests
* @return Wikimate
*/
public function __construct($api, $headers = array(), $data = array(), $options = array())
{
$this->api = $api;
$this->headers = $headers;
$this->data = $data;
$this->options = $options;
$this->initRequests();
}
/**
* Sets up a Requests_Session with appropriate user agent.
*
* @return void
* @link https://requests.ryanmccue.info/docs/usage-advanced.html#session-handling
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Etiquette#The_User-Agent_header
*/
protected function initRequests()
{
$this->useragent = 'Wikimate/' . self::VERSION . ' (https://github.com/hamstar/Wikimate)';
$this->session = new WpOrg\Requests\Session($this->api, $this->headers, $this->data, $this->options);
$this->session->useragent = $this->useragent;
}
/**
* Sends a GET or POST request in JSON format to the API.
*
* This method handles maxlag errors as advised at:
* {@see https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Maxlag_parameter}
* The request is sent with the current maxlag value
* (default: 5 seconds, per {@see Wikimate::MAXLAG_DEFAULT}).
* If a lag error is received, the method waits (sleeps) for the
* recommended time (per the Retry-After header), then tries again.
* It will do this indefinitely unless the number of retries is limited,
* in which case WikimateException is thrown once the limit is reached.
*
* The string type for $data is used only for upload POST requests,
* and must contain the complete multipart body, including maxlag.
*
* @param array|string $data Data for the request
* @param array $headers Optional extra headers to send with the request
* @param boolean $post True to send a POST request, otherwise GET
* @return array The API response
* @throw WikimateException If lagged and ran out of retries,
* or got an unexpected API response
*/
private function request($data, $headers = array(), $post = false)
{
$retries = 0;
// Add format & maxlag parameter to request
if (is_array($data)) {
$data['format'] = 'json';
$data['maxlag'] = $this->getMaxlag();
$action = $data['action'];
} else {
$action = 'upload';
}
// Define type of HTTP request for messages
$httptype = $post ? 'POST' : 'GET';
// Send appropriate type of request, once or multiple times
do {
if ($post) {
// Debug logging of POST requests, except for upload string
if ($this->debugMode && is_array($data)) {
echo "$action $httptype parameters:\n";
print_r($data);
}
$response = $this->session->post($this->api, $headers, $data);
} else {
// Debug logging of GET requests as a query string
if ($this->debugMode) {
echo "$action $httptype parameters:\n";
echo http_build_query($data) . "\n";
}
$response = $this->session->get($this->api . '?' . http_build_query($data), $headers);
}
// Check for replication lag error
$serverLagged = ($response->headers->offsetGet('X-Database-Lag') !== null);
if ($serverLagged) {
// Determine recommended or default delay
if ($response->headers->offsetGet('Retry-After') !== null) {
$sleep = (int)$response->headers->offsetGet('Retry-After');
} else {
$sleep = $this->getMaxlag();
}
if ($this->debugMode) {
preg_match('/Waiting for [^ ]*: ([0-9.-]+) seconds? lagged/', $response->body, $match);
echo "Server lagged for {$match[1]} seconds; will retry in {$sleep} seconds\n";
}
sleep($sleep);
// Check retries limit
if ($this->getMaxretries() >= 0) {
$retries++;
} else {
$retries = -1; // continue indefinitely
}
}
} while ($serverLagged && $retries <= $this->getMaxretries());
// Throw exception if we ran out of retries
if ($serverLagged) {
throw new WikimateException("Server lagged ($retries consecutive maxlag responses)");
}
// Check if we got the API doc page (invalid request)
if (strpos($response->body, "This is an auto-generated MediaWiki API documentation page") !== false) {
throw new WikimateException("The API could not understand the $action $httptype request");
}
// Check if we got a JSON result
$result = json_decode($response->body, true);
if ($result === null) {
throw new WikimateException("The API did not return the $action JSON response");
}
if ($this->debugMode) {
echo "$action $httptype response:\n";
print_r($result);
}
return $result;
}
/**
* Obtains a wiki token for logging in or data-modifying actions.
*
* If a CSRF (default) token is requested, it is stored and returned
* upon further such requests, instead of making another API call.
* The stored token is discarded via {@see Wikimate::logout()}.
*
* For now this method, in Wikimate tradition, is kept simple and supports
* only the two token types needed elsewhere in the library. It also
* doesn't support the option to request multiple tokens at once.
* See {@see https://www.mediawiki.org/wiki/Special:MyLanguage/API:Tokens}
* for more information.
*
* @param string $type The token type
* @return mixed The requested token (string), or null if error
*/
protected function token($type = self::TOKEN_DEFAULT)
{
// Check for supported token types
if ($type != self::TOKEN_DEFAULT && $type != self::TOKEN_LOGIN) {
$this->error = array();
$this->error['token'] = 'The API does not support the token type';
return null;
}
// Check for existing CSRF token for this login session
if ($type == self::TOKEN_DEFAULT && $this->csrfToken !== null) {
return $this->csrfToken;
}
$details = array(
'action' => 'query',
'meta' => 'tokens',
'type' => $type,
);
// Send the token request
$tokenResult = $this->request($details, array(), true);
// Check for errors
if (isset($tokenResult['error'])) {
$this->error = $tokenResult['error']; // Set the error if there was one
return null;
} else {
$this->error = null; // Reset the error status
}
if ($type == self::TOKEN_LOGIN) {
return $tokenResult['query']['tokens']['logintoken'];
} else {
// Store CSRF token for this login session
$this->csrfToken = $tokenResult['query']['tokens']['csrftoken'];
return $this->csrfToken;
}
}
/**
* Obtains parameter lists for API modules.
* For specific API modules where supported parameters vary with
* MediaWiki versions, this method is used to fetch and store
* these parameter lists for use by the API calls of those modules.
* Current list of modules for which this mechanism is employed:
* - {@link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Logout logout}
* - {@link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Delete delete}
* - {@link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Undelete undelete}
*
* @return void
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Parameter_information
*/
private function storeModuleParams()
{
// Obtain parameter info for modules
$details = array(
'action' => 'paraminfo',
'modules' => 'logout|delete|undelete',
);
// Send the paraminfo request
$paramResult = $this->request($details);
// Check for errors
if (isset($paramResult['error'])) {
$this->error = $paramResult['error']; // Set the error if there was one
return;
} else {
$this->error = null; // Reset the error status
}
// Store supported parameters for all requested modules
foreach ($paramResult['paraminfo']['modules'] as $module) {
$this->moduleParams[$module['name']] = array();
foreach ($module['parameters'] as $param) {
$this->moduleParams[$module['name']][] = $param['name'];
}
}
}
/**
* Checks API module's parameters for a supported parameter.
*
* @param string $module The module name
* @param string $param The parameter name
* @return boolean True if supported
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Parameter_information
*/
public function supportsModuleParam($module, $param)
{
return in_array($param, $this->moduleParams[$module]);
}
/**
* Logs in to the wiki.
*
* @param string $username The user name
* @param string $password The user password
* @param string $domain The domain (optional)
* @return boolean True if logged in
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Login#Method_1._login
*/
public function login($username, $password, $domain = null)
{
// Obtain login token first
if (($logintoken = $this->token(self::TOKEN_LOGIN)) === null) {
return false;
}
$details = array(
'action' => 'login',
'lgname' => $username,
'lgpassword' => $password,
'lgtoken' => $logintoken,
);
// If $domain is provided, set the corresponding detail in the request information array
if (is_string($domain)) {
$details['lgdomain'] = $domain;
}
// Send the login request
$loginResult = $this->request($details, array(), true);
// Check for errors
if (isset($loginResult['error'])) {
$this->error = $loginResult['error']; // Set the error if there was one
return false;
} else {
$this->error = null; // Reset the error status
}
if (isset($loginResult['login']['result']) && $loginResult['login']['result'] != 'Success') {
// Some more comprehensive error checking
$this->error = array();
switch ($loginResult['login']['result']) {
case 'Failed':
$this->error['auth'] = 'Incorrect username or password';
break;
default:
$this->error['auth'] = 'The API result was: ' . $loginResult['login']['result'];
break;
}
return false;
}
// Obtain parameter lists for API modules
$this->storeModuleParams();
return true;
}
/**
* Logs out of the wiki and discards CSRF token.
*
* @return boolean True if logged out
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Logout
*/
public function logout()
{
$details = array(
'action' => 'logout',
);
// Check if token parameter is required (it is since MediaWiki v1.34)
if ($this->supportsModuleParam('logout', 'token')) {
// Obtain logout token
if (($logouttoken = $this->token()) === null) {
return false;
}
$details['token'] = $logouttoken;
}
// Send the logout request
$logoutResult = $this->request($details, array(), true);
// Check for errors
if (isset($logoutResult['error'])) {
$this->error = $logoutResult['error']; // Set the error if there was one
return false;
} else {
$this->error = null; // Reset the error status
}
// Discard CSRF token for this login session
$this->csrfToken = null;
return true;
}
/**
* Gets the current value of the maxlag parameter.
*
* @return integer The maxlag value in seconds
*/
public function getMaxlag()
{
return $this->maxlag;
}
/**
* Sets the new value of the maxlag parameter.
*
* @param integer $ml The new maxlag value in seconds
* @return Wikimate This object
*/
public function setMaxlag($ml)
{
$this->maxlag = (int)$ml;
return $this;
}
/**
* Gets the current value of the max retries limit.
*
* @return integer The max retries limit
*/
public function getMaxretries()
{
return $this->maxretries;
}
/**
* Sets the new value of the max retries limit.
*
* @param integer $mr The new max retries limit
* @return Wikimate This object
*/
public function setMaxretries($mr)
{
$this->maxretries = (int)$mr;
return $this;
}
/**
* Gets the user agent for API requests.
*
* @return string The default user agent, or the current one defined
* by {@see Wikimate::setUserAgent()}
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Etiquette#The_User-Agent_header
*/
public function getUserAgent()
{
return $this->useragent;
}
/**
* Sets the user agent for API requests.
*
* In order to use a custom user agent for all requests in the session,
* call this method before invoking {@see Wikimate::login()}.
*
* @param string $ua The new user agent
* @return Wikimate This object
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Etiquette#The_User-Agent_header
*/
public function setUserAgent($ua)
{
$this->useragent = (string)$ua;
// Update the session
$this->session->useragent = $this->useragent;
return $this;
}
/**
* Sets the debug mode.
*
* @param boolean $b True to turn debugging on
* @return Wikimate This object
*/
public function setDebugMode($b)
{
$this->debugMode = $b;
return $this;
}
/**
* Gets or prints the Requests configuration.
*
* @param boolean $echo Whether to echo the session options and headers
* @return mixed Options array if $echo is false, or
* True if options/headers have been echoed to STDOUT
*/
public function debugRequestsConfig($echo = false)
{
if ($echo) {
echo "<pre>Requests options:\n";
print_r($this->session->options);
echo "Requests headers:\n";
print_r($this->session->headers);
echo "</pre>";
return true;
}
return $this->session->options;
}
/**
* Returns a WikiPage object populated with the page data.
*
* @param string $title The name of the wiki article
* @return WikiPage The page object
*/
public function getPage($title)
{
return new WikiPage($title, $this);
}
/**
* Returns a WikiFile object populated with the file data.
*
* @param string $filename The name of the wiki file
* @return WikiFile The file object
*/
public function getFile($filename)
{
return new WikiFile($filename, $this);
}
/**
* Performs a query to the wiki API with the given details.
*
* @param array $array Array of details to be passed in the query
* @return array Decoded JSON output from the wiki API
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Query
*/
public function query($array)
{
$array['action'] = 'query';
return $this->request($array);
}
/**
* Performs a parse query to the wiki API.
*
* @param array $array Array of details to be passed in the query
* @return array Decoded JSON output from the wiki API
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Parsing_wikitext
*/
public function parse($array)
{
$array['action'] = 'parse';
return $this->request($array);
}
/**
* Performs an edit query to the wiki API.
*
* @param array $array Array of details to be passed in the query
* @return array|boolean Decoded JSON output from the wiki API
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Edit
*/
public function edit($array)
{
// Obtain default token first
if (($edittoken = $this->token()) === null) {
return false;
}
$headers = array(
'Content-Type' => "application/x-www-form-urlencoded"
);
$array['action'] = 'edit';
$array['token'] = $edittoken;
return $this->request($array, $headers, true);
}
/**
* Performs a delete query to the wiki API.
*
* @param array $array Array of details to be passed in the query
* @return array|boolean Decoded JSON output from the wiki API
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Delete
*/
public function delete($array)
{
// Obtain default token first
if (($deletetoken = $this->token()) === null) {
return false;
}
$headers = array(
'Content-Type' => "application/x-www-form-urlencoded"
);
$array['action'] = 'delete';
$array['token'] = $deletetoken;
return $this->request($array, $headers, true);
}
/**
* Performs an undelete query to the wiki API.
*
* @param string $name The original name of the wiki page or file
* @param string $reason Reason for the restore
* @param boolean $talktoo True to restore talk page, if any;
* false to leave talk page deleted (MW 1.39+)
* @return array|boolean Decoded JSON output from the wiki API
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Undelete
*/
public function undelete($name, $reason = null, $talktoo = true)
{
// Obtain default token first
if (($undeletetoken = $this->token()) === null) {
return false;
}
$headers = array(
'Content-Type' => "application/x-www-form-urlencoded"
);
// Set options from arguments
$array = array(
'action' => 'undelete',
'title' => $name,
'token' => $undeletetoken
);
if (!is_null($reason)) {
$array['reason'] = $reason;
}
// Check if undeletetalk parameter is supported (it is since MediaWiki v1.39)
if ($this->supportsModuleParam('undelete', 'undeletetalk') && $talktoo) {
$array['undeletetalk'] = $talktoo;
}
return $this->request($array, $headers, true);
}
/**
* Downloads data from the given URL.
*
* @param string $url The URL to download from
* @return mixed The downloaded data (string), or null if error
*/
public function download($url)
{
$getResult = $this->session->get($url);
if (!$getResult->success) {
// Debug logging of Requests_Response only on failed download
if ($this->debugMode) {
echo "download GET response:\n";
print_r($getResult);
}
$this->error = array();
$this->error['file'] = 'Download error (HTTP status: ' . $getResult->status_code . ')';
$this->error['http'] = $getResult->status_code;
return null;
}
return $getResult->body;
}
/**
* Uploads a file to the wiki API.
*
* @param array $array Array of details to be used in the upload
* @return array|boolean Decoded JSON output from the wiki API
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Upload
*/
public function upload($array)
{
// Obtain default token first
if (($uploadtoken = $this->token()) === null) {
return false;
}
$array['action'] = 'upload';
$array['format'] = 'json';
$array['maxlag'] = $this->getMaxlag();
$array['token'] = $uploadtoken;
// Construct multipart body:
// https://www.mediawiki.org/w/index.php?title=API:Upload&oldid=2293685#Sample_Raw_Upload
// https://www.mediawiki.org/w/index.php?title=API:Upload&oldid=2339771#Sample_Raw_POST_of_a_single_chunk
$boundary = '---Wikimate-' . md5(microtime());
$body = '';
foreach ($array as $fieldName => $fieldData) {
$body .= "--{$boundary}\r\n";
$body .= 'Content-Disposition: form-data; name="' . $fieldName . '"';
// Process the (binary) file
if ($fieldName == 'file') {
$body .= '; filename="' . $array['filename'] . '"' . "\r\n";
$body .= "Content-Type: application/octet-stream; charset=UTF-8\r\n";
$body .= "Content-Transfer-Encoding: binary\r\n";
// Process text parameters
} else {
$body .= "\r\n";
$body .= "Content-Type: text/plain; charset=UTF-8\r\n";
$body .= "Content-Transfer-Encoding: 8bit\r\n";
}
$body .= "\r\n{$fieldData}\r\n";
}
$body .= "--{$boundary}--\r\n";
// Construct multipart headers
$headers = array(
'Content-Type' => "multipart/form-data; boundary={$boundary}",
'Content-Length' => strlen($body),
);
return $this->request($body, $headers, true);
}
/**
* Performs a file revert query to the wiki API.
*
* @param array $array Array of details to be passed in the query
* @return array|boolean Decoded JSON output from the wiki API
* @link https://www.mediawiki.org/wiki/Special:MyLanguage/API:Filerevert
*/
public function filerevert($array)
{
// Obtain default token first
if (($reverttoken = $this->token()) === null) {
return false;
}
$array['action'] = 'filerevert';
$array['token'] = $reverttoken;
$headers = array(
'Content-Type' => "application/x-www-form-urlencoded"
);
return $this->request($array, $headers, true);
}
/**
* Returns the latest error if there is one.
*
* @return mixed The error array, or null if no error
*/
public function getError()
{
return $this->error;
}
}
/**
* Defines Wikimate's exception for unexpected run-time errors
* while communicating with the API.
* WikimateException can be thrown only from {@see Wikimate::request()},
* and is propagated to callers of this library.
*
* @author Frans P. de Vries
* @since 1.0.0 August 2021
* @link https://www.php.net/manual/en/class.runtimeexception.php
*/
class WikimateException extends RuntimeException
{
}
/**
* Models a wiki article page that can have its text altered and retrieved.
*
* @author Robert McLeod & Frans P. de Vries
* @since 0.2 December 2010
*/
class WikiPage
{
/**
* Identifier for page sections by index.
* Use section indexes as keys in return array
* of {@see WikiPage::getAllSections()}.
*
* @var integer
*/
const SECTIONLIST_BY_INDEX = 1;
/**
* Identifier for page sections by name.
* Use section names as keys in return array
* of {@see WikiPage::getAllSections()}.
*
* @var integer
*/
const SECTIONLIST_BY_NAME = 2;
/**
* The title of the page
*
* @var string|null
*/
protected $title = null;
/**
* Wikimate object for API requests
*
* @var Wikimate|null
*/
protected $wikimate = null;
/**
* Whether the page exists
*
* @var boolean
*/
protected $exists = false;
/**
* Whether the page is invalid
*
* @var boolean
*/
protected $invalid = false;
/**
* Error array with API and WikiPage errors
*
* @var array|null
*/
protected $error = null;
/**
* Stores the timestamp for detection of edit conflicts
*
* @var integer|null
*/
protected $starttimestamp = null;
/**
* The complete text of the page
*
* @var string|null
*/
protected $text = null;
/**
* The sections object for the page
*
* @var stdClass|null
*/
protected $sections = null;
/*
*
* Magic methods
*
*/
/**
* Constructs a WikiPage object from the title given
* and associates it with the passed Wikimate object.
*
* @param string $title Name of the wiki article
* @param Wikimate $wikimate Wikimate object
*/
public function __construct($title, $wikimate)
{
$this->wikimate = $wikimate;
$this->title = $title;
$this->sections = new \stdClass();
$this->text = $this->getText(true);
if ($this->invalid) {
$this->error['page'] = 'Invalid page title - cannot create WikiPage';
}
}
/**
* Forgets all object properties.
*/
public function __destruct()
{
$this->title = null;
$this->wikimate = null;
$this->exists = false;
$this->invalid = false;
$this->error = null;
$this->starttimestamp = null;
$this->text = null;
$this->sections = null;
}
/**
* Returns the wikicode of the page.
*
* @return string String of wikicode