forked from hamstar/Wikimate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWikimate.php
669 lines (559 loc) · 16.8 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
<?php
/**
* Provides an interface over wiki API objects such as pages.
*
* @author Robert McLeod
* @since December 2010
* @version 0.10.0
*/
class Wikimate {
const SECTIONLIST_BY_NAME = 1;
const SECTIONLIST_BY_INDEX = 2;
/**
* @var string The current version number (conforms to http://semver.org/).
*/
const VERSION = '0.10.0';
private $api;
private $username;
private $password;
/** @var Requests_Session */
private $session;
private $error = array();
private $debugMode = false;
/**
* Create a new Wikimate object.
*
* @return Wikimate
*/
function __construct( $api ) {
$this->api = $api;
$this->initRequests();
}
/**
* Set up a Requests_Session with appropriate user agent.
*
* @todo Pull version number from elsewhere.
*
* @return void
*/
private function initRequests() {
$this->session = new Requests_Session($this->api);
$this->useragent = "Wikimate ".self::VERSION." (https://github.com/hamstar/Wikimate)";
}
/**
* Logs in to the wiki
* @return boolean true if logged in
*/
public function login( $username, $password ) {
//Logger::log("Logging in");
$details = array(
'action' => 'login',
'lgname' => $username,
'lgpassword' => $password,
'format' => 'json'
);
// Send the login request
$response = $this->session->post($this->api, array(), $details);
// Check if we got an API result or the API doc page (invalid request)
if ( strstr( $response->body, "This is an auto-generated MediaWiki API documentation page" ) ) {
$this->error['login'] = "The API could not understand the first login request";
return false;
}
$loginResult = json_decode( $response->body );
if ( $this->debugMode ) {
echo "Login request:\n";
print_r( $details );
echo "Login request response:\n";
print_r( $loginResult );
}
if ( $loginResult->login->result == "NeedToken" ) {
//Logger::log("Sending token {$loginResult->login->token}");
$details['lgtoken'] = strtolower( trim( $loginResult->login->token ) );
// Send the confirm token request
$loginResult = $this->session->post($this->api, array(), $details)->body;
// Check if we got an API result or the API doc page (invalid request)
if ( strstr( $loginResult, "This is an auto-generated MediaWiki API documentation page" ) ) {
$this->error['login'] = "The API could not understand the confirm token request";
return false;
}
$loginResult = json_decode( $loginResult );
if ( $this->debugMode ) {
echo "Confirm token request:\n";
print_r( $details );
echo "Confirm token response:\n";
print_r( $loginResult );
}
if ( $loginResult->login->result != "Success" ) {
// Some more comprehensive error checking
switch ( $loginResult->login->result ) {
case 'NotExists':
$this->error['login'] = 'The username does not exist';
break;
default:
$this->error['login'] = 'The API result was: ' . $loginResult->login->result;
break;
}
return false;
}
}
//Logger::log("Logged in");
return true;
}
/**
* Sets the debug mode
*
* @param boolean $debugMode true to turn debugging on
* @return Wikimate this object
*/
public function setDebugMode( $b ) {
$this->debugMode = $b;
return $this;
}
/**
* Used to return or print the curl settings, but now prints an error and
* returns Wikimate::getRequestsConfig()
*
* @deprecated since version 0.10.0
* @param boolean $echo True to echo the configuration
* @return mixed Array of config if $echo is false, (boolean)true if echo is true
*/
public function debugCurlConfig( $echo = false ) {
if ( $echo ) {
echo "ERROR: Curl is no longer used by Wikimate.\n";
}
return $this->getRequestsConfig();
}
/**
* Get or print the Requests configuration.
*
* @param boolean $echo Whether to echo the options
* @return array Options if $echo is FALSE
* @return TRUE If options 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 );
}
/**
* 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 unserialized php output from the wiki
*/
public function query( $array ) {
$array['action'] = 'query';
$array['format'] = 'php';
$apiResult = $this->session->get( $this->api.'?'.http_build_query($array) );
return unserialize( $apiResult->body );
}
/**
* Performs a parse query to the wiki API.
* @param array $array array of details to be passed in the query.
* @return array unserialized php output from the wiki API.
*/
public function parse( $array ) {
$array['action'] = 'parse';
$array['format'] = 'php';
$apiResult = $this->session->get( $this->api.'?'.http_build_query($array));
return unserialize( $apiResult->body );
}
/**
* Perfoms an edit query to the wiki api
* @param array $array array of details to be passed in the query
* @return array unserialized php output from the wiki
*/
public function edit( $array ) {
$headers = array(
'Content-Type' => "application/x-www-form-urlencoded"
);
$array['action'] = 'edit';
$array['format'] = 'php';
$apiResult = $this->session->post( $this->api, $headers, $array );
return unserialize( $apiResult->body );
}
/**
* Perfoms a delete query to the wiki api
* @param array $array array of details to be passed in the query
* @return array unserialized php output from the wiki
*/
public function delete( $array ) {
$headers = array(
'Content-Type' => "application/x-www-form-urlencoded"
);
$array['action'] = 'delete';
$array['format'] = 'php';
$apiResult = $this->session->post( $this->api, $headers, $array );
return unserialize( $apiResult );
}
public function getError() {
return $this->error;
}
}
/**
* Models a wiki article page that can have its text altered and retrieved.
* @author Robert McLeod
* @since December 2010
* @version 0.5
*/
class WikiPage {
const SECTIONLIST_BY_INDEX = 1;
const SECTIONLIST_BY_NAME = 2;
const SECTIONLIST_BY_NUMBER = 3;
private $title = null;
private $exists = false;
private $text = null;
private $edittoken = null;
private $starttimestamp = null;
private $wikimate = null;
private $error = null;
private $invalid = false;
private $sections = null;
/*
*
* Magic methods
*
*/
/**
* Constructs a WikiPage object from the title given and adds
* a wikibot object
* @param string $title name of the wiki article
* @param WikiBot $wikibot WikiBot object
*/
function __construct( $title, $wikimate ) {
$this->wikimate = $wikimate;
$this->title = $title;
$this->text = $this->getText( true );
if ( $this->invalid ) {
echo "Invalid page title - cannot create WikiPage";
return null;
}
}
/**
*
* @return <type> Destructor
*/
function __destruct() {
$this->title = null;
$this->exists = false;
$this->text = null;
$this->edittoken = null;
$this->starttimestamp = null;
$this->wikimate = null;
$this->error = null;
$this->invalid = false;
return null;
}
/**
* Returns the wikicode of the page
* @return string of wikicode
*/
function __toString() {
return $this->text;
}
/**
* Returns an array sections with the section name as the key and the text
* as the element e.g.
*
* array(
* 'intro' => 'this text is the introduction',
* 'History' => 'this is text under the history section'
* )
*
* @return array of sections
*/
function __invoke() {
return $this->getAllSections( false, self::SECTIONLIST_BY_NAME );
}
/**
* Returns the page existance status
* @return boolean true if page exists
*/
function exists() {
return $this->exists;
}
/**
* Alias of self::__destruct()
*/
function destroy() {
$this->__destruct();
}
/*
*
* Page meta functions
*
*/
/**
* Returns an error if there is one, null shows no error
* @return mixed null for no errors or an error array object
*/
function getError() {
return $this->error;
}
/**
* Returns the title of this page
* @return string the title of this page
*/
function getTitle() {
return $this->title;
}
/**
* Returns the number of sections in this page
* @return integer the number of sections in this page
*/
function getNumSections() {
return count( $this->sections->byIndex );
}
/**
* Returns the sections offsets and lengths
* @return StdClass section class
*/
function getSectionOffsets() {
return $this->sections;
}
/*
*
* Getting functions
*
*/
/**
* Gets the text of the page. If refesh is true then this method will
* query the wiki api again for the page details
* @param boolean $refresh true to query the wiki api again
* @return string the text of the page
*/
function getText( $refresh = false ) {
if ( $refresh ) { // we want to query the api
$data = array(
'prop' => 'info|revisions',
'intoken' => 'edit',
'titles' => $this->title,
'rvprop' => 'content' // need to get page text
);
$r = $this->wikimate->query( $data ); // run the query
// Check for errors
if ( isset( $r['error'] ) ) {
$this->error = $r; // set the error if there was one
} else {
$this->error = null; // reset the error status
}
$page = array_pop( $r['query']['pages'] ); // get the page (there should only be one)
unset( $r, $data );
if ( isset( $page['invalid'] ) ) {
$this->invalid = true;
}
$this->edittoken = $page['edittoken'];
$this->starttimestamp = $page['starttimestamp'];
if ( !isset( $page['missing'] ) ) {
$this->exists = true; // update the existance if the page is there
$this->text = $page['revisions'][0]['*']; // put the content into text
}
unset( $page );
// Now we need to get the section information
preg_match_all( '/={1,6}.*={1,6}\n/', $this->text, $m ); // TODO: improve regexp if possible
// Set the intro section (between title and first section)
$this->sections->byIndex[0]['offset'] = 0;
$this->sections->byName['intro']['offset'] = 0;
if ( !empty( $m[0] ) ) {
// Array of section names
$sections = $m[0];
// Setup the current section
$currIndex = 0;
$currName = 'intro';
foreach ( $sections as $i => $section ) {
// Get the current offset
$currOffset = strpos( $this->text, $section );
// Are we still on the first section?
if ( $currIndex == 0 ) {
$this->sections->byIndex[$currIndex]['length'] = $currOffset;
$this->sections->byName[$currName]['length'] = $currOffset;
}
// Get the current name and index
$currName = trim( str_replace( '=', '', $section ) );
$currIndex++;
// Set the offset for the current section
$this->sections->byIndex[$currIndex]['offset'] = $currOffset;
$this->sections->byName[$currName]['offset'] = $currOffset;
// If there is a section after this, set the length of this one
if ( isset( $sections[$currIndex] ) ) {
$nextOffset = strpos( $this->text, $sections[$currIndex] ); // get the offset of the next section
$length = $nextOffset - $currOffset; // calculate the length of this one
// Set the length of this section
$this->sections->byIndex[$currIndex]['length'] = $length;
$this->sections->byName[$currName]['length'] = $length;
}
}
}
}
return $this->text; // return the text in any case
}
/**
* Returns the section requested, section can be the following:
* - section name (string:"History")
* - section index (int:3)
*
* @param mixed $section the section to get
* @param boolan $includeHeading false to get section text only
* @return string wikitext of the section on the page
*/
function getSection( $section, $includeHeading = false ) {
// Check if we have a section name or index
if ( is_int( $section ) ) {
$coords = $this->sections->byIndex[$section];
} else if ( is_string( $section ) ) {
$coords = $this->sections->byName[$section];
}
// Extract the text
@extract( $coords );
if ( isset( $length ) ) {
$text = substr( $this->text, $offset, $length );
} else {
$text = substr( $this->text, $offset );
}
// Whack of the heading if need be
if ( !$includeHeading && $offset > 0 ) {
$text = substr( $text, strpos( trim( $text ), "\n" ) ); // chop off the first line
}
return $text;
}
/**
* Return all the sections of the page in an array - the key names can be
* set to name or index by using the following for the second param
* - self::SECTIONLIST_BY_NAME
* - self::SECTIONLIST_BY_INDEX
*
* @param boolean $includeHeading false to get section text only
* @param integer $keyNames modifier for the array key names
* @return array of sections
*/
function getAllSections( $includeHeading = false, $keyNames = self::SECTIONLIST_BY_INDEX ) {
$sections = array();
switch ( $keyNames ) {
case self::SECTIONLIST_BY_INDEX:
$array = array_keys( $this->sections->byIndex );
break;
case self::SECTIONLIST_BY_NAME:
$array = array_keys( $this->sections->byName );
break;
default:
throw new Exception( 'Unexpected parameter $keyNames given to WikiPage::getAllSections()' );
break;
}
foreach ( $array as $key ) {
$sections[$key] = $this->getSection( $key, $includeHeading );
}
return $sections;
}
/*
*
* Setting functions
*
*/
/**
* Sets the text in the page. Updates the starttimestamp to the timestamp
* after the page edit (if the edit is successful)
* @param string $text the article text
* @param string $section the section to edit (null for whole page)
* @return boolean true if page was edited successfully
*/
function setText( $text, $section = null, $minor = false, $summary = null ) {
$data = array(
'title' => $this->title,
'text' => $text,
'md5' => md5( $text ),
'bot' => "true",
'token' => $this->edittoken,
'starttimestamp' => $this->starttimestamp
);
// set options from arguments
if ( !is_null( $section ) )
$data['section'] = $section;
if ( $minor )
$data['minor'] = $minor;
if ( !is_null( $summary ) )
$data['summary'] = $summary;
// Make sure we don't create a page by accident or overwrite another one
if ( !$this->exists ) {
$data['createonly'] = "true"; // createonly if not exists
} else {
$data['nocreate'] = "true"; // don't create, it should exist
}
$r = $this->wikimate->edit( $data ); // the edit query
// Check if it worked
if ( $r['edit']['result'] == "Success" ) {
$this->exists = true;
if ( is_null( $section ) ) {
$this->text = $text;
} else {
}
// Get the new starttimestamp
$data = array(
'prop' => 'info',
'intoken' => 'edit',
'titles' => $this->title
);
$r = $this->wikimate->query( $data );
$page = array_pop( $r['query']['pages'] ); // get the page
$this->starttimestamp = $page['starttimestamp']; // update the starttimestamp
$this->error = null; // reset the error
return true;
}
$this->error = $r;
return false;
}
/**
* Sets the text of the given section.
* Essentially an alias of WikiPage:setText() with the summary and minor
* parameters switched.
*
* @param string $text The text of the section
* @param mixed $section section index, new by default
* @param string $summary summary text
* @param boolean $minor true for minor edit
* @return boolean true if the section was saved
*/
function setSection( $text, $section = 0, $summary = null, $minor = false ) {
$this->setText( $text, $section, $minor, $summary );
}
/**
* Alias of WikiPage::setSection() specifically for creating new sections
*
* @param string $name the heading name for the new section
* @param string $text The text of the new section
* @return boolean true if the section was saved
*/
function newSection( $name, $text ) {
return $this->setSection( $text, $section = 'new', $summary = $name, $minor = false );
}
function delete( $reason ) {
$data = array(
'title' => $this->title,
'token' => $this->edittoken
);
// set options from arguments
if ( !is_null( $reason ) )
$data['reason'] = $reason;
$r = $this->wikimate->delete( $data ); // the delete query
// Check if it worked
if ( $r['delete'] ) {
$this->exists = false; // the page was deleted
$this->error = null; // reset the error
return true;
}
$this->error = $r;
return false;
}
}