/
BotCore.php
1795 lines (1792 loc) · 66.3 KB
/
BotCore.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
require_once __DIR__ . "/Password.php";
/** BotCore.php
* Central file of the Cygnus-Framework
* Most functions get loaded from this file.
* @author Freddy2001 <freddy2001@wikipedia.de>, Hgzh, Luke081515 <luke081515@tools.wmflabs.org>, MGChecker <hgasuser@gmail.com>
* @requires extensions: JSON
* @version V2.1 alpha
*/
class Core extends Password {
protected $username;
protected $cleanUsername;
protected $password;
protected $curlHandle;
protected $site;
protected $protocol;
protected $job;
protected $assert;
protected $mail;
protected $mailcontent;
private $version = "Cygnus-Framework V2.1 alpha";
private $ua;
private $maxlag;
private $target;
private $debugMode = false;
private $failedLoginCounter = 0;
private $passwordVersion = "2.1.0"; // Should be the same as in Password.php, when you are changing the file.
/** initcurl
* initializes curl
* this function usually should be called first
* creates the connection object
* does the login if the bot isn"t explicitly told not to by $loadSettings
* if that"s not the case, it reads the login data of settings.json and does the login afterwards
* @author Hgzh / MGChecker
* @param $job - name of the job; used for the internal storage of cookies
* @param $account - name of the accounts in settings.json
* @param $assert - [optional: bot] if set to "user" edits can be made without botflag
* @param $loadSettings - [optional: true] if the settings shall be loaded or another way will be used to login
*/
public function initcurl($account, $job, $pUseHTTPS = true, $assert = "bot") {
if ($assert !== "bot" && $assert !== "user") {
throw new Exception("assert has to be 'bot' or 'user'");
}
$this->assert = $assert;
$this->setMaxlag(5);
$this->start($account);
$this->job = $job;
if ($pUseHTTPS === true) {
$this->protocol = "https";
} else {
$this->protocol = "http";
}
// init curl
$curl = curl_init();
if ($curl === false) {
throw new Exception("Curl initialization failed.");
} else {
$this->curlHandle = $curl;
}
$this->login();
$this->createCleanUsername();
$this->echoMsg("***** Starting up....\nVersion: " . $this->version . " *****", "notice");
$this->ua = "User:" . $this->cleanUsername . " - " . $this->job . " - " . $this->version;
$this->echoMsg("Used UserAgent: '" . $this->ua . "'\n", "notice");
if ($this->cleanUsername === $this->username) {
$this->echoMsg("Warning: Main-account login via \"action=login\" is deprecated and may stop working without warning. ", "warning");
$this->echoMsg("To continue login with \"action=login\", see [[Special:BotPasswords]].", "warning");
}
}
/** initcurlArgs
* Use this function instead of initcurl if you want to use args or console to tell the bot the password
* @author Luke081515
* @param $job - name of the job; useful for saving the cookies
* @param $pUseHTTPS - [optional: true] if false, http will be used
* @param $assert - [optional: bot] if set to "user" instead, you can use a bot without flag
*/
public function initcurlArgs($job, $pUseHTTPS = true, $assert = "bot", $supress = false, $debugMode = false) {
if ($debugMode) {
$this->debugMode = true;
}
if ($assert !== "bot" && $assert !== "user") {
exit(1);
}
$this->assert = $assert;
$this->job = $job;
if ($pUseHTTPS === true) {
$this->protocol = "https";
} else {
$this->protocol = "http";
}
// init curl
$curl = curl_init();
if ($curl === false) {
throw new Exception("Curl initialization failed.");
} else {
$this->curlHandle = $curl;
}
$this->createCleanUsername();
$this->ua = "User:" . $this->cleanUsername . " - " . $this->job . " - " . $this->version;
if (!$supress) {
$this->echoMsg("***** Starting up....\nVersion: " . $this->version . " *****", "notice");
$this->echoMsg("Used UserAgent: '" . $this->ua . "'\n", "notice");
}
if ($this->cleanUsername === $this->username) {
$this->echoMsg("Warning: Main-account login via \"action=login\" is deprecated and may stop working without warning. ", "warning");
$this->echoMsg("To continue login with \"action=login\", see [[Special:BotPasswords]].", "warning");
}
// change if you need more, default is 5
$this->setMaxlag(5);
}
public function __construct($account, $job, $pUseHTTPS = true) {}
public function __destruct() {
curl_close($this->curlHandle);
}
/** createCleanUsername
* Looks up the username for a botpassword
* If username is a botpassword, the botpasswordname will get removed
* Otherwise $this->cleanUsername will get set to the same value
* @author Luke081515
*/
private function createCleanUsername() {
$cleanUsername = strstr($this->username, "@", true);
if ($cleanUsername === false) {
$this->cleanUsername = $this->username;
} else {
$this->cleanUsername = $cleanUsername;
}
}
/** httpRequest
* does http(s) requests
* mostly used to communicate with the API
* @param $pArguments - API params you want to exectute (starts normally with action=)
* @param $job - used to find the right cookies. just use $this->job
* @param $pMethod - [optional: POST] Method of the request. For querys, you just use GET
* @param $pTarget - [optional: w/api.php] use this,
if Special:Version shows something different than w/api.php for using the api
* @author Hgzh
* @return answer of the API
*/
protected function httpRequest($arguments, $job, $method = 'POST', $target = '') {
if($target == '') {
// Kept for legacy support
// ToDo: Remove in next major release
$target = $this->target;
} else {
echo ("\nThis way of setting the path has been deprecated. "
. "Please migrate it to Password.php. See release notes for details");
}
$baseURL = $this->protocol . '://' .
$this->site . '/' .
$target;
$method = strtoupper($method);
if ($arguments != "") {
if ($method === "POST") {
$requestURL = $baseURL;
$postFields = $arguments;
} else if ($method === "GET") {
$requestURL = $baseURL . "?" .
$arguments;
} else {
throw new Exception("Unknown http request method.");
}
}
if (!$requestURL) {
throw new Exception("No arguments for http request found.");
}
// set curl options
curl_setopt($this->curlHandle, CURLOPT_USERAGENT, $this->ua);
curl_setopt($this->curlHandle, CURLOPT_URL, $requestURL);
curl_setopt($this->curlHandle, CURLOPT_ENCODING, "UTF-8");
curl_setopt($this->curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->curlHandle, CURLOPT_COOKIEFILE, realpath("Cookies" . $job . ".tmp"));
curl_setopt($this->curlHandle, CURLOPT_COOKIEJAR, realpath("Cookies" . $job . ".tmp"));
// if posted, add post fields
if ($method === "POST" && $postFields != "") {
curl_setopt($this->curlHandle, CURLOPT_POST, 1);
curl_setopt($this->curlHandle, CURLOPT_POSTFIELDS, $postFields);
} else {
curl_setopt($this->curlHandle, CURLOPT_POST, 0);
curl_setopt($this->curlHandle, CURLOPT_POSTFIELDS, "");
}
// perform request
$success = false;
for ($i = 1; $i <= 20; $i++) {
$rqResult = curl_exec($this->curlHandle);
if ($rqResult !== false) {
$success = true;
break 1;
} else {
$this->echoMsg("Curl request with arguments \"" . $arguments . "\" to " . $this->site . " failed ($i/20): " . curl_error($this->curlHandle), "error");
sleep(10);
}
}
if ($success === true) {
if ($this->debugMode) {
$this->echoMsg("Result for '" . $arguments . "':\n'" . $rqResult . "'", "none");
}
return $rqResult;
} else {
throw new Exception("Curl request definitively failed: " . curl_error($this->curlHandle));
}
}
/** requireToken
* query the api for the token
* @author Hgzh / Luke081515 / MGChecker
* @param $type - [optional: csrf] - type of the token (see the api docs for details)
* @return requested token
*/
public function requireToken($type = "csrf") {
if ($type === "login") { // No assert on login
$result = $this->httpRequest("action=query&format=json&maxlag=" . $this->maxlag . "&meta=tokens&type=" . $type, $this->job, "GET");
} else {
$result = $this->httpRequest("action=query&format=json&assert=" . $this->assert . "&maxlag=" . $this->maxlag . "&meta=tokens&type=" . $type, $this->job, "GET");
}
$result = json_decode($result, true);
$tokenname = $type . "token";
try {
$token = $result["query"]["tokens"][$tokenname];
} catch (Exception $e) {
throw new Excpetion("You filed an invalid token request." . $e->getMessage());
}
if ($token === "") {
throw new Exception("Could not receive login token.");
}
return $token;
}
/** login
* used for login
* do not use this function, use initcurl/initcurlArgs instead
* @author Hgzh
*/
protected function login() {
$lgToken = $this->requireToken("login");
// perform login
$result = $this->httpRequest("action=login&maxlag=" . $this->maxlag . "&format=json&lgname=" . urlencode($this->username) .
"&lgpassword=" . urlencode($this->password) .
"&lgtoken=" . urlencode($lgToken), $this->job);
$result = json_decode($result, true);
$lgResult = $result['login']['result'];
// manage result
if ($lgResult == "Success") {
return true;
} else {
if(isset($result['login']['reason'])) {
$lgReason = $result['login']['reason'];
} else {
$lgReason = $lgResult;
}
throw new Exception("Login failed with message: " . $lgReason);
}
}
/** logout
* Does a logout
*/
public function logout() {
$this->httpRequest("action=logout", $this->job);
}
/** DO NOT USE this function
* in case you are not using initcurlArgs
*/
public function setSite($site) {
$this->site = $site;
}
/** DO NOT USE this function
* in case you are not using initcurlArgs
*/
public function setUsername($username) {
$this->username = $username;
$this->createCleanUsername();
}
/** DO NOT USE this function
* in case you are not using initcurlArgs
*/
public function setPassword($password) {
$this->password = $password;
}
/** DO NOT USE this function
* in case you are not using initcurlArgs
*/
public function setTarget($target) {
$this->target = $target;
}
/** start
* Searches for the data from Password.php, does the login after that
* this function is used by initcurl, use initcurl instead
* @author Luke081515
*/
public function start($account) {
$Found = false;
$this->init();
if (method_exists($this, 'getPasswordVersion')) {
$passwordVersion = $this->getPasswordVersion();
} else {
throw new Exception("You are using an old version of Password.php. Please upgrade.");
}
if ($this->passwordVersion !== $passwordVersion) { // Ensuring no old version is used
throw new Exception("You are using an old version of Password.php. Please upgrade.");
}
$LoginName = unserialize($this->getLoginName());
$LoginHost = unserialize($this->getLoginHost());
$LoginAccount = unserialize($this->getLoginAccount());
$LoginPassword = unserialize($this->getLoginPassword());
$Mail = unserialize($this->getMail());
$Target = unserialize($this->getApiPath());
for ($a = 0; isset($LoginName[$a]); $a++) {
if ($LoginName[$a] === $account) {
$this->site = $LoginHost[$a];
$this->username = $LoginAccount[$a];
$this->password = $LoginPassword[$a];
$this->mail = $Mail[$a];
$this->target = $Target[$a];
$Found = true;
}
}
if (!$Found) {
throw new Exception("No matching credentials available.");
}
}
/** checkResult
* this is an internal method
* this method gets called if there is an error in executing an action
* depending on the code, it executes different actions
* @author Luke081515
* @param $result - errorcode of the api
* @return fail - edit failed, a retry would not be useful
* @return retry - try it again, it may work
* @return conflict - there is an edit conflict
*/
private function checkResult($result) {
if ($result === 'maxlag' || $result === 'readonly' || $result === 'unknownerror-nocode' || $result === 'unknownerror' || $result === 'ratelimited') {
$this->echoMsg("Action failed. Reason: " . $result . ". Please try again", "error");
return 'retry';
} else if ($result === 'blocked' || $result === 'confirmemail' || $result === 'autoblocked') {
throw new Exception("You will not be able to execute writing actions soon. Reason: " . $result);
} else if ($result === 'assertuserfailed' || $result === 'assertbotfailed') {
if($this->failedLoginCounter > 5) {
throw new Exception("MaxLoginTrysExceeded"); // ToDo: Find a way to reset this on succesful actions without putting that into every function
}
$this->failedLoginCounter++;
$this->login();
return "retry";
} else if ($result === "editconflict") {
$this->echoMsg("Editconflict detected", "error");
return "conflict";
} else if ($result === "nosuchsection") {
return "nosuchsection";
} else {
$this->echoMsg("Action failed. Error: " . $result, "error");
return "fail";
}
}
/** readPageEngine
* for internal use only, used for readPage/readSection functions
* @param $request - the data for the api to get the content of the page
* @author Luke081515
* @return text of the page
*/
private function readPageEngine($request) {
do {
$page = json_decode($this->httpRequest($request, $this->job, 'GET'), true);
if (isset($page['error'])) {
$errorcode = $this->checkResult($page['error']['code']);
if($errorcode === "fail" || $errorcode === "nosuchsection") {
return false;
}
}
} while (isset($errorcode) && $errorcode === "retry");
$pageID = $page['query']['pageids'][0];
if ($pageID == -1) {
return null;
}
return $page['query']['pages'][$pageID]['revisions'][0]['*'];
}
/** readPage
* Returns the content of a page
* @param $title - name of the page including namespaces
* @author MGChecker
* @return content of the page
** false if there is an unknown error
** null if the page does not exist
*/
public function readPage($title) {
$request = "action=query&prop=revisions&format=json&rvprop=content&rvlimit=1&rvcontentformat=text%2Fx-wiki&titles=" . urlencode($title) .
"&rvdir=older&assert=" . $this->assert . "&maxlag=" . $this->maxlag . "&rawcontinue=&indexpageids=1";
return $this->readPageEngine($request);
}
/** readPageId
* Returns the content of a page
* @param $pageID - ID of the page
* @author MGChecker
* @return content of the page
** false if there is an unknown error
** null if the page does not exist
*/
public function readPageID($pageID) {
$request = "action=query&prop=revisions&format=json&rvprop=content&rvlimit=1&rvcontentformat=text%2Fx-wiki&pageids=" . urlencode($pageID) .
"&rvdir=older&assert=" . $this->assert . "&maxlag=" . $this->maxlag . "&rawcontinue=&indexpageids=1";
return $this->readPageEngine($request);
}
/** readPageJs
* Returns the content of a JS page
* @param $title - title of the page
* @author MGChecker
* @return text of the page
** false if there is an unknown error
** null if the page does not exist
*/
public function readPageJs($title) {
$request = "action=query&prop=revisions&format=json&rvprop=content&rvlimit=1&rvcontentformat=text%2Fjavascript&titles=" . urlencode($title) .
"&rvdir=older&assert=" . $this->assert . "&maxlag=" . $this->maxlag . "&rawcontinue=&indexpageids=1";
return $this->readPageEngine($request);
}
/** readPageCss
* Returns the content of a CSS page
* @param $title - title of the page
* @author MGChecker
* @return text of the page
** false if there is an unknown error
** null if the page does not exist
*/
public function readPageCss($title) {
$request = "action=query&prop=revisions&format=json&rvprop=content&rvlimit=1&rvcontentformat=text%2Fcss&titles=" . urlencode($title) .
"&rvdir=older&assert=" . $this->assert . "&maxlag=" . $this->maxlag . "&rawcontinue=&indexpageids=1";
return $this->readPageEngine($request);
}
/** readSection
* returns the content of a specified section
* @param $title - name of the page
* @param $section - number of the section
* @author MGChecker
* @return text of the section
** false if there is an unknown error
** null if the page does not exist
*/
public function readSection($title, $section) {
$request = "action=query&prop=revisions&format=json&rvprop=content&rvlimit=1&rvcontentformat=text%2Fx-wiki&rvdir=older&indexpageids=1&rvsection=" . urlencode($section) .
"&assert=" . $this->assert . "&maxlag=" . $this->maxlag . "&titles=" . urlencode($title);
return $this->readPageEngine($request);
}
/** getTableOfContents
* returns the Table of Contents of a page
* @param $page - Title of the page
* @author Luke081515
* @return two-dimensional array
* @return first dimension: the section
* @retuns second dimension:
* [0] => level;
* [1] => title of the section
* [2] => section number at the table of contents (e.g. something like 7.5 as well);
* [3] => section number as int;
*/
public function getTableOfContents($title) {
$result = $this->httpRequest("action=parse&format=json&maxlag=" . $this->maxlag . "&assert=" . $this->assert .
"&page=" . urlencode($title) . "&prop=sections", $this->job, "GET");
$result = json_decode($result, true);
for ($a = 0; isset($result["parse"]["sections"][$a]["level"]); $a++) {
$ret[$a][0] = $result["parse"]["sections"][$a]["level"];
$ret[$a][1] = $result["parse"]["sections"][$a]["line"];
$ret[$a][2] = $result["parse"]["sections"][$a]["number"];
$ret[$a][3] = $result["parse"]["sections"][$a]["index"];
}
return $ret;
}
/** getEchoNotifications
* gets Notifications
* requires an installed echo extension in MediaWiki
* @author Freddy2001
* @returns Array with all notifications
*/
public function getEchoNotifications() {
$result = $this->httpRequest("action=query&format=json&meta=notifications", $this->job, 'GET');
$result = json_decode($result, true);
return $result['query']['notifications']['list'];
}
/** editPageEngine
* internal method which does the edit. please use one of the following functions instead
* @param $title - name of the page
* @param $content - new content
* @param $summary - summary
* @param $botflag - if true, the bot will use a botflag
* @param $minorflag - if true the edit will get marked as minor
* @param $noCreate - should the page get recreated in case that this is needed?
* @param $sectionnumber - which section should get edited? (default => the whole page)
* @param $overrideNobots - Should {{NoBots}} gets overriden?
* @author Hgzh / Luke081515 / MGChecker
* @return unserialized answer of the api, if successful
*/
private function editPageEngine($title, $content, $summary, $botflag, $minorflag, $noCreate = 1, $sectionnumber = -1, $overrideNobots = false) {
while (true) {
if ($overrideNobots !== true) {
if ($this->allowBots($this->readPage($title)) === false) {
return "nobots";
}
}
$token = $this->requireToken();
// perform edit
$request = "action=edit&assert=" . $this->assert . "&maxlag=" . $this->maxlag . "&format=json&bot=&title=" . urlencode($title) .
"&text=" . urlencode($content) .
"&token=" . urlencode($token) .
"&summary=" . urlencode($summary);
if ($botflag) {
$request .= "&bot=";
}
if ($minorflag) {
$request .= "&minor=";
}
if ($noCreate) {
$request .= "&nocreate=";
}
if ($sectionnumber !== -1) {
$request .= "§ion=" . urlencode($sectionnumber);
}
$result = $this->httpRequest($request, $this->job);
$result = json_decode($result, true);
$editres = $result["edit"]["result"];
// manage result
if ($editres == "Success") {
if (array_key_exists("nochange", $result["edit"])) {
return array("nochange");
} else {
return array($result["edit"]["oldrevid"], $result["edit"]["newrevid"]);
}
} else {
return array($result["edit"]["oldrevid"], $result["edit"]["newrevid"]);
}
}
}
/** editPage
* edits a page
* @param $title - title of the page
* @param $content - new content
* @param $summary - summary
* @param $noCreate - should the page get recreated? default is no
* @param $overrideNobots - should {{NoBots}} get overriden? default is no
* @author Freddy2001 / Luke081515
* @return unserialized answer of the api, if successful
*/
public function editPage($title, $content, $summary, $noCreate = 1, $overrideNobots = false) {
if ($this->assert == "bot") {
$botflag = true;
} else {
$botflag = false;
}
return $this->editPageEngine($title, $content, $summary, $botflag, false, $noCreate, -1, $overrideNobots);
}
/** editPageMinor
* edits a page and marks the edit as minor
* @param $title - title of the page
* @param $content - new content
* @param $summary - summary
* @param $noCreate - should the page get recreated? default is no
* @param $overrideNobots - should {{NoBots}} get overriden? default is no
* @author Freddy2001 / Luke081515
* @return unserialized answer of the api, if successful
*/
public function editPageMinor($title, $content, $summary, $noCreate = 1, $overrideNobots = false) {
if ($this->assert == "bot") {
$botflag = true;
} else {
$botflag = false;
}
return $this->editPageEngine($title, $content, $summary, $botflag, true, $noCreate, -1, $overrideNobots);
}
/** editPageD
* edits a page
* @param $title - title of the page
* @param $content - new content
* @param $summary - summary
* @param $botflag - if true, the edit will get marked with a botflag
* @param $minorflag - if true, the edit will get marked as minor
* @param $noCreate - should the page get recreated? default is no
* @param $overrideNobots - should {{NoBots}} get overriden? default is no
* @author MGChecker / Luke081515
* @return unserialized answer of the api, if successful
*/
public function editPageD($title, $content, $summary, $botflag, $minorflag, $noCreate = 1, $overrideNobots = false) {
return $this->editPageEngine($title, $content, $summary, $botflag, $minorflag, $noCreate, -1, $overrideNobots);
}
/** editSection
* edits a section
* @param $title - title of the page
* @param $content - new content
* @param $summary - summary
* @param $sectionnumber - number of the section
* @param $noCreate - should the page get recreated? default is no
* @param $overrideNobots - should {{NoBots}} get overriden? default is no
* @author Freddy2001 / MGChecker / Luke081515
* @return unserialized answer of the api, if successful
*/
public function editSection($title, $content, $summary, $sectionnumber, $noCreate = 1, $overrideNobots = false) {
if ($this->assert == "bot") {
$botflag = true;
} else {
$botflag = false;
}
if ($sectionnumber < 0) {
throw new Exception("You selected a invalid section number. To edit a whole page, use editPage().");
}
return $this->editPageEngine($title, $content, $summary, $botflag, false, $noCreate, $sectionnumber, $overrideNobots);
}
/** editSection
* edits a section, marks the edit as minor
* @param $title - title of the page
* @param $content - new content
* @param $summary - summary
* @param $sectionnumber - number of the section
* @param $noCreate - should the page get recreated? default is no
* @param $overrideNobots - should {{NoBots}} get overriden? default is no
* @author Freddy2001 / MGChecker / Luke081515
* @return unserialized answer of the api, if successful
*/
public function editSectionMinor($title, $content, $summary, $sectionnumber, $noCreate = 1, $overrideNobots = false) {
if ($this->assert == "bot") {
$botflag = true;
} else {
$botflag = false;
}
if ($sectionnumber < 0) {
throw new Exception("You selected a invalid section number. To edit a whole page, use editPageMinor().");
}
return $this->editPageEngine($title, $content, $summary, $botflag, true, $noCreate, $sectionnumber, $overrideNobots);
}
/** editPageD
* edits a page
* @param $title - title of the page
* @param $content - new content
* @param $summary - summary
* @param $botflag - if true, the edit will get marked with a botflag
* @param $minorflag - if true, the edit will get marked as minor
* @param $sectionnumber - number of the section
* @param $noCreate - should the page get recreated? default is no
* @param $overrideNobots - should {{NoBots}} get overriden? default is no
* @author MGChecker / Luke081515
* @return unserialized answer of the api, if successful
*/
public function editSectionD($title, $content, $summary, $sectionnumber, $botflag, $minorflag, $noCreate = 1, $overrideNobots = false) {
if ($sectionnumber < 0) {
throw new Exception("You selected a invalid section number. To edit a whole page, use editPageD().");
}
return $this->editPageEngine($title, $content, $summary, $botflag, $minorflag, $noCreate, $sectionnumber, $overrideNobots);
}
/** movePage
* moves a page
* @param $oldTitle - old title of a page
* @param $newTitle - new title of a page
* @param $reason - reason for the action
* @param - $bot (default: 0) - use a botflag?
* @param - $movetalk (default: 1) - move the talk page as well?
* @param - $noredirect - (default: 1) - create a redirect?
* @return serialized answer of the API
*/
public function movePage($oldTitle, $newTitle, $reason, $bot = 0, $movetalk = 1, $noredirect = 1) {
$token = $this->requireToken();
$request = "action=move&format=json&assert=" . $this->assert . "&maxlag=" . $this->maxlag .
"&from=" . urlencode($oldTitle) .
"&to=" . urlencode($newTitle) .
"&reason=" . urlencode($reason) .
"&bot=" . $bot .
"&movetalk=" . $movetalk .
"&noredirect=" . $noredirect .
"&token=" . urlencode($token);
$result = $this->httpRequest($request, $this->job);
return serialize(json_decode($result, true));
}
/** rollback
* rollbacks an edit
* @author Luke081515
* @param $title - name of the page
* @param $user - author of the revision that should get rollbacked
* @param $summary - [optional: Defined summary of mediawiki] custom summary
* @param $markbot - [optional: 0] - if true, the rollbacked edit and the rollback will be marked as bot
* @return true - if rollback was successful
* @return false - if the rollback failed
* @return null - if there was a conflict when doing a rollback
*/
public function rollback($title, $user, $summary = "", $markbot = 0) {
while (true) {
$token = $this->requireToken("rollback");
$request = "action=rollback&format=json&assert=" . $this->assert . "&maxlag=" . $this->maxlag .
"&title=" . urlencode($title) .
"&user=" . urlencode($user) .
"&markbot=" . urlencode($markbot) .
"&watchlist=nochange" .
"&token=" . urlencode($token);
if ($summary !== "") {
$request = $request . "&summary=" . urlencode($summary);
}
$result = $this->httpRequest($request, $this->job);
$result = json_decode($result, true);
if (array_key_exists("error", $result)) {
$code = $this->checkResult($result["error"]["code"]);
if ($code === "fail") {
return false;
} else if ($code === "retry") {
sleep(5);
} else if ($code === "conflict") {
return null;
}
} else {
return true;
}
}
}
/** watch
* Allows to put a page on your watchlist, or remove it
* @param $title - title of the page
* @param $unwatch - default 0 - if 1, the page will get removed from the list
* @return mixed - true if successful, otherwise the API error code
*/
public function watch ($title, $unwatch = 0) {
$token = $this->requireToken("watch");
$request = "action=watch"
. "&format=json"
. "&unwatch=" . $unwatch
. "&titles=" . urlencode($title)
. "&token=" . urlencode($token)
. "&assert=" . $this->assert
. "&maxlag=" . $this->maxlag;
$result = $this->httpRequest($request, $this->job);
$result = json_decode($result, true);
if (array_key_exists("error", $result)) {
return $result["error"]["code"];
}
return true;
}
/** purge
* Allows to put a page on your watchlist, or remove it
* @author Luke081515
* @param $title - title of the page
* @param $forcelinkupdate - default 0 - if 1, updates the links tables.
* @param $forcerecursivelinkupdate - default 0 - if 1, updates the links table,
* @param $forcerecursivelinkupdate - and update the links tables for any page that uses this page as a template.
* @return boolean - true if successful, false if page was not found
*/
public function purge ($title, $forcelinkupdate = 0, $forcerecursivelinkupdate = 0) {
$request = "action=purge"
. "&format=json"
. "&forcelinkupdate=" . $forcelinkupdate
. "&forcerecursivelinkupdate=" . $forcerecursivelinkupdate
. "&titles=" . urlencode($title)
. "&assert=" . $this->assert
. "&maxlag=" . $this->maxlag;
$result = $this->httpRequest($request, $this->job);
$result = json_decode($result, true);
//
if (isset($result['purge'][0]['missing'])) {
return false;
}
return true;
}
/** patrol
* Marks the specified version as reviewed or not reviewed
* @author Luke081515
* @param $id - the revid or rcid to patrol
* @param $revid [optional: true] - if true, you use a revid, otherwise a rcid
* @return string / bool - true if successful, otherwise the API error-code
*/
public function patrol($id, $revid = true) {
$token = $this->requireToken("patrol");
$request = "action=patrol&format=json&assert=" . $this->assert . "&maxlag=" . $this->maxlag .
"&token=" . urlencode($token);
if ($revid) {
$request = $request . "&revid=" . urlencode($id);
} else {
$request = $request . "&rcid=" . urlencode($id);
}
$result = $this->httpRequest($request, $this->job);
$result = json_decode($result, true);
if (array_key_exists("error", $result)) {
if ($result["error"]["code"] === "patroldisabled" || $result["error"]["code"] === "nosuchrcid" || $result["error"]["code"] === "noautopatrol") {
return $result["error"]["code"];
} else {
return $this->checkResult($result["error"]["code"]);
}
} else {
return true;
}
}
/** review
* Marks the specified version as reviewed or not reviewed
* @param $revid - the revid of the revision to approve/unapprove
* @param $comment [optional: ""] - the comment to add for the log
* @param $unapprove [optional: 0] - if 1: mark the rev as unreviewed instead of reviewed
* @return string - success if succesful, otherwise the API error-code
*/
public function review($revid, $comment = "", $unapprove = 0) {
$token = $this->requireToken();
$request = "action=review&format=json&assert=" . $this->assert .
"&maxlag=" . $this->maxlag .
"&revid=" . urlencode($revid) .
"&comment=" . urlencode($comment) .
"&token=" . urlencode($token);
if ($unapprove) {
$request = $request . "&unapprove=1";
}
$result = $this->httpRequest($request, $this->job);
$result = json_decode($result, true);
if (array_key_exists("error", $result)) {
if ($result["error"]["code"] === "notreviewable") {
return $result["error"]["code"];
} else {
return $this->checkResult($result["error"]["code"]);
}
} else {
return "success";
}
}
// User related functions
/** checkUserExistence
* checks if a user exists
* @author Luke081515
* @param $username - The username of the user
* @returs true if the user does exist, false if not
*/
public function checkUserExistence($username) {
$result = $this->httpRequest('action=query&format=json&list=users&usprop=&ususers=' . urlencode($username), $this->job, 'GET');
$result = json_decode($result, true);
if (isset($result['query']['users'][0]['missing'])) {
return false;
}
return true;
}
/** getUserEditcount
* returns the editcount of a user, false if the user does not exist
* @author Luke081515
* @param $username - The username of the user
* @returs editcount as int if the user does exist, false if not
*/
public function getUserEditcount ($username) {
$result = $this->httpRequest("action=query&format=json&list=users&usprop=editcount&ususers=" . urlencode($username), $this->job, "GET");
$result = json_decode($result, true);
if (isset($result['query']['users'][0]['missing'])) {
return false;
}
return $result['query']['users'][0]['editcount'];
}
/** checkUserBlock
* checks if a user is blocked
* @author Luke081515
* @param $username - The username of the user
* @returs true if blocked, false if not
*/
public function checkUserBlock ($username) {
$result = $this->httpRequest("action=query&format=json&list=blocks&bkusers=" . urlencode($username), $this->job, "GET");
if (strpos($result, "reason") !== false) {
return true;
}
return false;
}
/** checkUserMail
* checks if the user has the mail feature active
* @author Luke081515
* @param $username - The username of the user
* @returs false if not or if the user does not exist, true otherwise
*/
public function checkUserMail ($username) {
$result = $this->httpRequest('action=query&format=json&list=users&usprop=emailable&ususers=' . urlencode($username), $this->job, 'GET');
if (strpos($result, "emailable") !== false) {
return true;
}
return false;
}
/** getUserGroups
* returns the groups of a user, false if the user does not exist
* @author Luke081515
* @param $username - The username of the user
* @returs the groups as array if the user does exist, false if not
*/
public function getUserGroups ($username) {
$result = $this->httpRequest('action=query&format=json&list=users&usprop=groups&ususers=' . urlencode($username), $this->job, 'GET');
if (strpos($result, "missing") !== false)
return false;
$result = json_decode($result, true);
return $result['query']['users'][0]['groups'];
}
/** getUserGender
* returns the gender a user has set in the settings
* @author KPFC
* @param $username – The username of the user
* @return the gender as string ('female', 'male' or 'unknown')
*/
public function getUserGender ($username) {
$result = $this->httpRequest('action=query&format=json&list=users&usprop=gender&ususers=' . urlencode($username), $this->job, 'GET');
$result = json_decode($result, true);
if (isset($result['query']['users'][0]['missing'])) {
return false;
}
return $result['query']['users'][0]['gender'];
}
/** checkTemplate
* checks if a template is used at a page (transcluded)
* @author Luke081515
* @param $page - the page to check
* @param $templat - the name of the template, including the prefix (e.g. Template:Test)
* @return true if template is transcluded, false if not, or if the page does not exist
*/
public function checkTemplate($page, $template) {
$page = str_replace(" ", "_", $page);
$data = "action=query&format=json&prop=templates&tllimit=1&assert=" . $this->assert . "&maxlag=" . $this->maxlag
. "&titles=" . urlencode($page)
. "&tltemplates=" . urlencode($template);
$result = $this->httpRequest($data, $this->job, "GET");
if (strpos($result, ",\"templates\":[{\"ns\":") === false) {
return false;
}
return true;
}
/** getCatMembers
* reads out all category members of a category, including subcategories
* works till you have more than 5000 subcategories per category
* @author Luke081515
* @param $kat - category, which should get analyzed
* @param $onlySubCats - [optional: false] if true, only the subcategories will returned, not the pagetitles
* @param $excludeWls - [optional: false] if true, you won"t get categories with redirects
* @return false if the categories has no members, otherwise a serialized array with page titles
*/
public function getCatMembers($kat, $onlySubCats = false, $excludeWls = false) {
$b = 0;
$subCat[0] = $kat;
$result = $this->httpRequest("action=query&list=categorymembers&format=json&cmtitle=" . urlencode($kat) .
"&cmprop=title&cmtype=subcat&cmlimit=max&assert=" . $this->assert . "&maxlag=" . $this->maxlag .
"&cmsort=sortkey&cmdir=ascending&rawcontinue=", $this->job, "GET");
$result = json_decode($result, true);
$a = 0;
if (isset($result["query"]["categorymembers"][$a]["title"])) {
$Sub = true;
while (isset($result["query"]["categorymembers"][$a]["title"])) {
$subCat[$b] = $result["query"]["categorymembers"][$a]["title"];
$b++;
$a++;
}
}
$b = 0;
$c = 0;
if ($onlySubCats === true) {
return $subCat;
}
if ($excludeWls === false) {
while (isset($subCat[$b]))
{
$result = $this->httpRequest("action=query&list=categorymembers&format=json&cmtitle=" . urlencode($subCat[$b]) .
"&cmprop=title&cmtype=page&cmlimit=max&cmsort=sortkey&cmdir=ascending&rawcontinue=", $this->job, "GET");
$result = json_decode($result, true);
$Cont = false;
if (isset($result["query-continue"]["categorymembers"]["cmcontinue"])) {
$Continue = $result["query-continue"]["categorymembers"]["cmcontinue"];
$Cont = true;
}
while ($Cont === true) {
$a = 0;
if (isset($result["query"]["categorymembers"][$a]["title"])) {
while (isset($result["query"]["categorymembers"][$a]["title"])) {
$page[$c] = $result["query"]["categorymembers"][$a]["title"];
$c++;
$a++;
}
}
$result = $this->httpRequest("action=query&list=categorymembers&format=json&cmcontinue=" . $Continue
. "&cmtitle=" . urlencode($subCat[$b])
. "&cmprop=title&cmtype=page&cmlimit=max&cmsort=sortkey&cmdir=ascending&rawcontinue=", $this->job, "GET");
$result = json_decode($result, true);
if (isset($result["query-continue"]["categorymembers"]["cmcontinue"])) {
$Continue = $result["query-continue"]["categorymembers"]["cmcontinue"];
$Cont = true;
} else {
$Cont = false;
}
}
$a = 0;
if (isset($result["query"]["categorymembers"][$a]["title"]) === true) {
while (isset($result["query"]["categorymembers"][$a]["title"])) {
$page[$c] = $result["query"]["categorymembers"][$a]["title"];
$c++;
$a++;
}
}
$b++;
}
} else {
while (isset($subCat[$b])) {
$result = $this->httpRequest("action=query&format=json&generator=categorymembers&gcmtitle=" . urlencode($subCat[$b]) .
"&prop=info&gcmlimit=max&rawcontinue=&redirects", $this->job, "GET");
$result = json_decode($result, true);
$Cont = false;
if (isset($result["query-continue"]["categorymembers"]["gcmcontinue"])) {
$Continue = $result["query-continue"]["categorymembers"]["gcmcontinue"];
$Cont = true;
}
while ($Cont === true) {
$a = 0;
if (isset($result["query"]["pages"][$a]["title"])) {
while (isset($result["query"]["pages"][$a]["title"])) {
$page[$c] = $result["query"]["pages"][$a]["title"];
$c++;
$a++;
}
}
try {
$result = $this->httpRequest("action=query&format=json&generator=categorymembers&gcmtitle=" . urlencode($subCat[$b]) .