forked from FiftyNine/scpper-crawler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWikidotCrawler.php
1527 lines (1410 loc) · 51.8 KB
/
WikidotCrawler.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
/**
* This is a core module for SCP Crawler project, which is a part of larger SCPper project.
* This file contains classes and functions neccessary to extract information about particular
* pages, users, etc. Effectively this is a homemade API for accessing WIKIDOT information.
*
**/
require_once 'HTTP/Request2.php';
require_once 'phpQuery/phpQuery.php';
/******************************************************/
/************ Classes for logging *********************/
/******************************************************/
if (defined('SCP_THREADS')) {
abstract class WikidotLoggerBase extends Threaded
{
}
} else {
abstract class WikidotLoggerBase
{
}
}
// Base class for loggers
abstract class WikidotLogger extends WikidotLoggerBase
{
/*** Fields ***/
private $timeZone = null;
/*** Private ***/
// Adds timestamp and linebreak to a message
private function timestampMessage($message)
{
$now = new DateTime(null, $this->timeZone);
return sprintf(
"[%s] %s\n",
$now->format('d/m/Y H:i:s'),
$message
);
}
// Adds timestamp and outputs message
private function logSimpleInternal($message)
{
$timeMessage = $this->timestampMessage($message);
$this->logInternal($timeMessage);
}
// Formats message with args using vsprintf and outputs it
private function logFormatInternal($format, $args)
{
$message = vsprintf($format, $args);
$this->logSimpleInternal($message);
}
/*** Protected ***/
// Actual method for outputting messages. Must be overridden in descendants
abstract protected function logInternal($message);
/*** Public ***/
// Set timezone
public function setTimeZone($name)
{
if (!$this->timeZone = timezone_open($name)) {
$this->timeZone = null;
}
}
// Static method that checks if logger is null and calls logSimpleInternal
public static function log($logger, $message)
{
if ($logger) {
$logger->logSimpleInternal($message);
}
}
// Static method that checks if logger is null and calls logFormatInternal
public static function logFormat($logger, $format, $args)
{
if ($logger) {
$logger->logFormatInternal($format, $args);
}
}
}
// Logger class that writes messages to a log file
class WikidotFileLogger extends WikidotLogger
{
/*** Fields ***/
// Path to the log file
private $fileName;
/*** Protected ***/
// Write message to log file
protected function logInternal($message)
{
file_put_contents($this->fileName, $message, FILE_APPEND);
}
/*** Public ***/
public function __construct ($fileName, $append)
{
$this->fileName = $fileName;
file_put_contents($this->fileName, "\n", $append?FILE_APPEND:0);
}
}
// Logger class that prints messages to screen
class WikidotDebugLogger extends WikidotLogger
{
/*** Protected ***/
// Write message to standard output
protected function logInternal($message)
{
print($message);
}
}
/******************************************************/
/******* Classes for retrieving wikidot data **********/
/******************************************************/
class WikidotStatus
{
const OK = 0;
const NOT_FOUND = 1;
const REDIRECT = 2;
const FAILED = 3;
const UNKNOWN = 4;
}
// Utility class with functions to retrieve pages and modules
class WikidotUtils
{
/*** Fields ***/
// Max connection time, sec
public static $connectionTimeout = 10;
// Max request time, sec
public static $requestTimeout = 30;
// Max number of attempts for a single page
public static $maxAttempts = 3;
/*** Private ***/
// Create and setup a new request
private static function createRequest($url)
{
$request = new HTTP_Request2($url, HTTP_Request2::METHOD_GET);
$request->setConfig('follow_redirects', true);
$request->setConfig('max_redirects', 2);
$request->setConfig('strict_redirects', true);
$request->setConfig('connect_timeout', self::$connectionTimeout);
$request->setConfig('timeout', self::$requestTimeout);
return $request;
}
// Sends request at most $maxAttempts times, returns response object
private static function sendRequest($request, WikidotLogger $logger = null)
{
$response = null;
try {
$i = 0;
while ($i < self::$maxAttempts) {
try {
$response = $request->send();
} catch (HTTP_Request2_Exception $e) {
$i++;
if ($i >= self::$maxAttempts) {
throw $e;
} else {
continue;
}
}
$status = $response->getStatus();
if ($status < 400) {
break;
}
$i++;
}
} catch (HTTP_Request2_Exception $e) {
WikidotLogger::logFormat($logger, "Failed to retrieve {%s}\nUnexpected error: \"%s\"", array($request->getURL(), $e->getMessage()));
return null;
}
return $response;
}
/*** Public ***/
// Searches for a pager in html and returns number of pages in it. 1 if pager is not found
public static function extractPageCount($html)
{
$res = 1;
$doc = phpQuery::newDocument($html);
if ($pager = pq('div.pager', $doc)) {
foreach (pq('span.target, span.current', $pager) as $pageNo) {
$text = trim(pq($pageNo)->text());
if (filter_var($text, FILTER_VALIDATE_INT)) {
$res = max($res, (int)$text);
}
}
}
$doc->unloadDocument();
return $res;
}
// Extracts a DateTime object from a DOM element if it has the right class. Returns null otherwise
public static function extractDateTime(phpQueryObject $elem)
{
$classes = explode(' ', $elem->attr('class'));
foreach ($classes as $class) {
if (preg_match('/time_(?P<Timestamp>\d+)$/', $class, $matches)) {
return (date_create()->setTimestamp((int)$matches['Timestamp']));
}
}
}
// Extract SiteId from page html
public static function extractSiteId($html)
{
if (preg_match('/WIKIREQUEST.info.siteId = (?P<SiteId>\d+);/', $html, $matches)) {
if (filter_var($matches['SiteId'], FILTER_VALIDATE_INT)) {
return (int)$matches['SiteId'];
}
}
}
// Extract CategoryId from page html
public static function extractCategoryId($html)
{
if (preg_match('/WIKIREQUEST.info.categoryId = (?P<CategoryId>\d+);/', $html, $matches)) {
if (filter_var($matches['CategoryId'], FILTER_VALIDATE_INT)) {
return (int)$matches['CategoryId'];
}
}
}
// Extract PageId from page html
public static function extractPageId($html)
{
if (preg_match('/WIKIREQUEST.info.pageId = (?P<PageId>\d+);/', $html, $matches)) {
if (filter_var($matches['PageId'], FILTER_VALIDATE_INT)) {
return (int)$matches['PageId'];
}
}
}
// Extract PageName from page html
public static function extractPageName($html)
{
if (preg_match('/WIKIREQUEST.info.pageUnixName = "(?P<PageName>[\w\-:]+)";/', $html, $matches)) {
return $matches['PageName'];
}
}
// Iterate through all pages of a paged module, yielding html of each page
public static function iteratePagedModule($siteName, $moduleName, $pageId, $args, $pageNumbers = null, WikidotLogger $logger = null)
{
$changedArgs = array();
if (!is_array($pageNumbers) || count($pageNumbers) == 0) {
$pageNumbers = array();
$args['page'] = 1;
$firstPage = null;
self::requestModule($siteName, $moduleName, $pageId, $args, $firstPage, $logger);
if ($firstPage) {
$changedArgs = (yield $firstPage);
$pageCount = self::extractPageCount($firstPage);
if ($pageCount > 1) {
$pageNumbers = range(2, $pageCount);
}
}
}
foreach ($pageNumbers as $i) {
if (is_array($changedArgs)) {
$args = array_merge($args, $changedArgs);
}
if (is_int($i) && $i > 0) {
$args['page'] = $i;
$modulePage = null;
self::requestModule($siteName, $moduleName, $pageId, $args, $modulePage, $logger);
$changedArgs = (yield $modulePage);
}
}
}
// Request a specified module from wikidot. Returns HTML string.
public static function requestModule($siteName, $moduleName, $pageId, $args, &$html, WikidotLogger $logger = null)
{
$html = null;
$status = WikidotStatus::FAILED;
$fullUrl = sprintf('http://%s.wikidot.com/ajax-module-connector.php', $siteName);
$request = self::createRequest($fullUrl);
$request->setMethod(HTTP_Request2::METHOD_POST);
if (!is_array($args)) {
$args = array();
}
$args['moduleName'] = $moduleName;
$args['pageId'] = $pageId;
$args['page_id'] = $pageId;
$args['wikidot_token7'] = 'ayylmao';
$request->addPostParameter($args);
$request->addCookie('wikidot_token7', 'ayylmao');
if ($response = self::sendRequest($request, $logger)) {
$httpStatus = $response->getStatus();
if ($httpStatus >= 200 && $httpStatus < 300) {
$body = json_decode($response->getBody());
if ($body && $body->status == 'ok' && isset($body->body)) {
$status = WikidotStatus::OK;
$html = $body->body;
} elseif ($body->status == 'not_ok') {
WikidotLogger::logFormat(
$logger,
"Failed to retrieve module {%s/%s}\nWikidot error: \"%s\"\nArguments: %s",
array($siteName, $moduleName, $body->message, var_export($args, true))
);
} else {
WikidotLogger::logFormat(
$logger,
"Failed to retrieve module {%s/%s}\nUnknown error\nArguments: %s",
array($siteName, $moduleName, var_export($args, true))
);
}
} elseif ($httpStatus >= 300 && $httpStatus < 400) {
$status = WikidotStatus::REDIRECT;
WikidotLogger::logFormat(
$logger,
"Failed to retrieve module {%s/%s}\nRedirect detected. HTTP status: %d\nArguments: %s",
array($siteName, $moduleName, $status, var_export($args, true))
);
} else {
if ($httpStatus == 404) {
$status = WikidotStatus::NOT_FOUND;
}
WikidotLogger::logFormat(
$logger,
"Failed to retrieve module {%s %s}\nHTTP status: %d. Error message: \"%s\"\nArguments: %s",
array($siteName, $moduleName, $response->getStatus(), $response->getReasonPhrase(), var_export($args, true))
);
}
}
return $status;
}
// Request a specified page from wikidot. Returns HTML string in $source and status as return value
public static function requestPage($siteName, $pageName, &$source, WikidotLogger $logger = null)
{
$source = null;
$fullUrl = sprintf('http://%s.wikidot.com/%s', $siteName, $pageName);
$request = self::createRequest($fullUrl);
$request->setConfig('use_brackets', true);
$status = WikidotStatus::FAILED;
if ($response = self::sendRequest($request, $logger)) {
$httpStatus = $response->getStatus();
if ($httpStatus >= 200 && $httpStatus < 300) {
$source = $response->getBody();
$status = WikidotStatus::OK;
} elseif ($httpStatus >= 300 && $httpStatus < 400) {
WikidotLogger::logFormat(
$logger,
"Failed to retrieve page {%s}. HTTP status: %d. Redirect detected",
array($request->getURL(), $httpStatus)
);
$status = WikidotStatus::REDIRECT;
} else {
WikidotLogger::logFormat(
$logger,
"Failed to retrieve {%s}. HTTP status: %d\nError message: \"%s\"",
array($request->getURL(), $httpStatus, $response->getReasonPhrase())
);
if ($httpStatus === 404) {
$status = WikidotStatus::NOT_FOUND;
} else {
$status = WikidotStatus::FAILED;
}
}
}
return $status;
}
}
/******************************************************/
/************* Wikidot entity classes *****************/
/******************************************************/
// Class with properties of a single revision
class WikidotRevision
{
/*** Fields ***/
// Wikidot revision id
protected $revisionId;
// Wikidot page id
protected $pageId;
// Zero-based index in the list of revisions of the page
protected $index;
// WikidotUser object - author of the revision
protected $user;
// Date and time revision was submitted
protected $dateTime;
// Comments
protected $comments;
/*** Protected ***/
// Name of class for user object for overriding in descendants
protected function getUserClass()
{
return 'WikidotUser';
}
/*** Public ***/
public function __construct($pageId)
{
$this->pageId = $pageId;
}
// Extract information about revision from a html element
public function extractFrom(phpQueryObject $rev)
{
preg_match('/\d+/', $rev->attr('id'), $ids);
$this->revisionId = (int)$ids[0];
$this->index = (int)substr(trim(pq('td:first', $rev)->text()), 0, -1);
$userClass = $this->getUserClass();
$this->user = new $userClass();
$this->user->extractFrom(pq('span.printuser', $rev));
$this->dateTime = WikidotUtils::extractDateTime(pq('span.odate', $rev));
$this->comments = trim(pq('td:last', $rev)->text());
}
/*** Access methods ***/
// Wikidot revision id
public function getId()
{
return $this->revisionId;
}
// Wikidot page id
public function getPageId()
{
return $this->pageId;
}
// Zero-based index in the list of revisions of the page
public function getIndex()
{
return $this->index;
}
// WikidotUser object - author of the revision
public function getUser()
{
return $this->user;
}
// Id of the author
public function getUserId()
{
if ($this->user) {
return $this->user->getId();
}
}
// Date and time revision was submitted
public function getDateTime()
{
return $this->dateTime;
}
// Comments
public function getComments()
{
return $this->comments;
}
}
// Class with properties of a single wikidot page
class WikidotPage
{
/*** Fields ***/
// Wikidot site name, e.g. 'scp-wiki'
private $siteName;
// Wikidot page name (url), e.g. 'scp-307', 'the-czar-cometh'
private $pageName;
// Retrieval status (according to WikidotStatus class)
private $status = WikidotStatus::UNKNOWN;
// Wikidot inner site id
private $siteId;
// Wikidot inner page id
private $pageId;
// Wikidot page category id
private $categoryId;
// Page title ('SCP-307', 'The Czar Cometh', etc)
private $title;
// Wikidot source text of the page
private $source;
// Array of tags
private $tags;
// Associative array of votes on the page (userId => vote), where vote is either 1 or -1.
private $votes;
// Full list of revisions
private $revisions;
// Latest revision number
protected $lastRevision = -1;
// List of users who edited, voted or otherwise influenced the page (retrieved with history and voting modules)
// (UserId => WikidotUser)
protected $retrievedUsers;
/*** Private ***/
// Extract all properties from a loaded page HTML (not including info from modules)
private function extractPageInfo($html, WikidotLogger $logger = null)
{
if (!$html)
return;
$doc = phpQuery::newDocument($html);
$this->setProperty('siteId', WikidotUtils::extractSiteId($html));
if (!$this->getSiteId()) {
WikidotLogger::logFormat(
$logger,
"Failed to extract SiteId for page {http://%s.wikidot.com/%s}",
array($this->getSiteName(), $this->getPageName())
);
return;
}
$this->setProperty('categoryId', WikidotUtils::extractCategoryId($html));
if (!$this->getCategoryId()) {
WikidotLogger::logFormat(
$logger,
"Failed to extract CategoryId for page {http://%s.wikidot.com/%s}",
array($this->getSiteName(), $this->getPageName())
);
return;
}
$this->setProperty('pageId', WikidotUtils::extractPageId($html));
if (!$this->getId()) {
WikidotLogger::logFormat(
$logger,
"Failed to extract PageId for page {http://%s.wikidot.com/%s}",
array($this->getSiteName(), $this->getPageName())
);
return;
}
// Extract page name in case we were redirected
$newName = WikidotUtils::extractPageName($html);
if ($newName != $this->getPageName()) {
WikidotLogger::logFormat($logger, 'Redirect detected: "%s" -> "%s"', array($this->getPageName(), $newName));
$this->setProperty('pageName', $newName);
}
// Extract last revision number
$pageInfo = pq('div#page-info', $doc);
if ($pageInfo && preg_match('/\d+/', $pageInfo->text(), $matches)) {
$this->lastRevision = (int)$matches[0];
} /*else {
WikidotLogger::logFormat(
$logger,
"Failed to extract latest revision for page {http://%s.wikidot.com/%s}",
array($this->siteName, $this->pageName)
);
}*/
// Extract page title
$titleElem = pq('div#page-title', $doc);
if ($titleElem) {
$this->setProperty('title', trim($titleElem->text()));
} else {
WikidotLogger::logFormat(
$logger,
"Failed to extract title for page {http://%s.wikidot.com/%s}",
array($this->getSiteName(), $this->getPageName())
);
return;
}
// Extract page tags
$tags = array();
$tagsElem = pq('div.page-tags', $doc);
if ($tagsElem) {
foreach (pq('a', $tagsElem) as $tagElem) {
$tags[] = pq($tagElem)->text();
}
$this->setProperty('tags', $tags);
} else {
WikidotLogger::logFormat(
$logger,
"Failed to extract tags for page {http://%s.wikidot.com/%s}",
array($this->getSiteName(), $this->getPageName())
);
return;
}
$doc->unloadDocument();
return true;
}
/*** Protected ***/
// Name of class for revision object
protected function getRevisionClass()
{
return 'WikidotRevision';
}
// Name of class for user object
protected function getUserClass()
{
return 'WikidotUser';
}
// Informs the object that it was changed
protected function changed($message = null)
{
// Do nothing
}
// Add revision to the list
protected function addRevision(WikidotRevision $revision)
{
$this->revisions[$revision->getIndex()] = $revision;
$this->changed();
}
// Set value by property name
protected function setProperty($name, $value)
{
if ($name == "siteId" && is_int($value) && $this->siteId !== $value) {
$this->siteId = $value;
$this->changed();
} elseif ($name == "pageId" && is_int($value) && $this->pageId !== $value) {
$this->pageId = $value;
$this->changed($name);
} elseif ($name == "categoryId" && is_int($value) && $this->categoryId !== $value) {
$this->categoryId = $value;
$this->changed($name);
} elseif ($name == "siteName" && is_string($value) && $this->siteName !== $value) {
$this->siteName = $value;
$this->changed($name);
} elseif ($name == "pageName" && is_string($value) && $this->pageName !== $value) {
$this->pageName = $value;
$this->changed($name);
} elseif ($name == "title" && is_string($value) && $this->title !== $value) {
$this->title = $value;
$this->changed($name);
} elseif ($name == "source" && (is_string($value) || $value == null) && $this->source !== $value) {
$this->source = $value;
$this->changed($name);
} elseif ($name == "tags" && is_array($value)) {
asort($value);
if (!is_array($this->tags)) {
$this->tags = array();
}
if (array_diff($this->tags, $value) || array_diff($value, $this->tags)) {
$this->tags = $value;
$this->changed($name);
}
} elseif ($name == "votes" && is_array($value) && $this->votes != $value) {
$this->votes = $value;
$this->changed($name);
} elseif ($name == "revisions" && is_array($value) && $this->revisions != $value) {
$this->revisions = $value;
$this->changed($name);
}
}
/*** Public ***/
public function __construct ($siteName, $pageName)
{
if (!preg_match('/^[\w\-]+$/', $siteName)) {
throw new Exception('Invalid wikidot site name');
}
if (!preg_match('/^[\w\-:]+$/', $pageName)) {
throw new Exception('Invalid wikidot page name');
}
$this->siteName = $siteName;
$this->pageName = $pageName;
$this->retrievedUsers = array();
}
// Request a source module from wikidot and extract source text from it
public function retrievePageSource(WikidotLogger $logger = null)
{
$res = false;
$html = null;
WikidotUtils::requestModule($this->getSiteName(), 'viewsource/ViewSourceModule', $this->getId(), array(), $html, $logger);
if ($html) {
$doc = phpQuery::newDocument($html);
$elem = pq('div.page-source', $doc);
if ($elem) {
$this->setProperty('source', $elem->text());
$res = true;
}
$doc->unloadDocument();
}
if (!$res) {
WikidotLogger::logFormat(
$logger,
"Failed to retrieve source for page {http://%s.wikidot.com/%s}",
array($this->getSiteName(), $this->getPageName())
);
}
return $res;
}
// Request a whoRated module from wikidot and extract votes from it
public function retrievePageVotes(WikidotLogger $logger = null)
{
$res = false;
$html = null;
WikidotUtils::requestModule($this->getSiteName(), 'pagerate/WhoRatedPageModule', $this->getId(), array(), $html, $logger);
if ($html) {
$doc = phpQuery::newDocument($html);
$votes = array();
foreach (pq('span.printuser', $doc) as $userElem) {
$userClass = $this->getUserClass();
$user = new $userClass();
if ($user->extractFrom(pq($userElem))) {
$this->retrievedUsers[$user->getId()] = $user;
$voteElem = pq($userElem)->next();
$voteText = trim(pq($voteElem)->text());
if ($voteText === '+') {
$vote = 1;
} else if ($voteText === '-') {
$vote = -1;
} else {
continue;
}
$key = (string)$user->getId();
// In the unlikely (but somehow possible) case where
// there are two different votes from the same user
// on the same page at the same time, we will
// count only the positive vote to avoid votes leapfrogging
// each other every other update
if (array_key_exists($key, $votes)) {
$vote = 1;
}
$votes[$key] = $vote;
}
}
$this->setProperty('votes', $votes);
$doc->unloadDocument();
$res = true;
}
if (!$res) {
WikidotLogger::logFormat(
$logger,
"Failed to retrieve votes for page {http://%s.wikidot.com/%s}",
array($this->getSiteName(), $this->getPageName())
);
}
return $res;
}
// Request a history module for the page and extract information from it (posterId, creation date and last revision info)
public function retrievePageHistory(WikidotLogger $logger = null)
{
$revisions = array();
$res = false;
$args = array(
// Here's hoping nobody has that many revisions on a single page
'perpage' => 1000000,
'options' => '{"all":true}'
);
$pageIterator = WikidotUtils::iteratePagedModule($this->getSiteName(), 'history/PageRevisionListModule', $this->getId(), $args, null, $logger);
foreach ($pageIterator as $html) {
$doc = phpQuery::newDocument($html);
foreach (pq('tr[id^=\'revision-row\']', $doc) as $revElem) {
$revClass = $this->getRevisionClass();
$rev = new $revClass($this->getId());
$rev->extractFrom(pq($revElem));
$revisions[$rev->getIndex()] = $rev;
$this->retrievedUsers[$rev->getUserId()] = $rev->getUser();
$res = true;
}
$doc->unloadDocument();
}
if ($res) {
$this->setProperty("revisions", array_reverse($revisions));
$this->lastRevision = $revisions[0]->getIndex();
} else {
WikidotLogger::logFormat(
$logger,
"Failed to retrieve votes for page {http://%s.wikidot.com/%s}",
array($this->getSiteName(), $this->getPageName())
);
}
return $res;
}
// Retrieve only html of the page itself and extract information from it
public function retrievePageInfo(WikidotLogger $logger = null)
{
$html = null;
try {
$this->status = WikidotUtils::requestPage($this->getSiteName(), $this->getPageName(), $html, $logger);
if ($this->status != WikidotStatus::OK || !$html) {
return false;
}
if (!$this->extractPageInfo($html, $logger)) {
return false;
} else {
unset($html);
}
} catch (Exception $e) {
WikidotLogger::logFormat(
$logger,
"Failed to retrieve page info {%s/%s}\nError message: \"%s\"",
array($this->getSiteName(), $this->getPageName(), $e->getMessage())
);
return false;
}
return true;
}
// Retrieve modules for page (votes, source, history) and extract data from them
public function retrievePageModules(WikidotLogger $logger = null)
{
try {
if (!$this->retrievePageSource($logger))
return false;
if (!$this->retrievePageVotes($logger))
return false;
if (!$this->retrievePageHistory($logger))
return false;
} catch (Exception $e) {
WikidotLogger::logFormat(
$logger,
"Failed to retrieve page modules {%s/%s}\nError message: \"%s\"",
array($this->getSiteName(), $this->getPageName(), $e->getMessage())
);
return false;
}
return true;
}
// Open page by http using siteName and pageName and retrieve all information about it,making additional calls to modules
public function retrieveAll(WikidotLogger $logger = null)
{
return $this->retrievePageInfo($logger) && $this->retrievePageModules($logger);
}
// Update info fomr other object of the same id
public function updateFrom(WikidotPage $page)
{
if (!$page || $page->getId() != $this->getId())
return;
$this->setProperty('pageName', $page->pageName);
$this->setProperty('title', $page->title);
$this->setProperty('categoryId', $page->categoryId);
$this->setProperty('source', $page->source);
$this->setProperty('tags', $page->tags);
$this->setProperty('votes', $page->votes);
$this->setProperty('revisions', $page->revisions);
if (isset($page->retrievedUsers)) {
if (isset($this->retrievedUsers)) {
$this->retrievedUsers = $this->retrievedUsers + $page->retrievedUsers;
} else {
$this->retrievedUsers = $page->retrievedUsers;
}
}
}
/*** Access methods ***/
// Wikidot id
public function getId()
{
return $this->pageId;
}
// Wikidot site id
public function getSiteId()
{
return $this->siteId;
}
// Wikidot category id
public function getCategoryId()
{
return $this->categoryId;
}
// Wikidot site name
public function getSiteName()
{
return $this->siteName;
}
// Wikidot page name
public function getPageName()
{
return $this->pageName;
}
// Title of the page
public function getTitle()
{
return $this->title;
}
// Wikidot source text of the page
public function getSource()
{
return $this->source;
}
// Tags
public function getTags()
{
return $this->tags;
}
// Votes
public function getVotes()
{
return $this->votes;
}
// Revisions
public function getRevisions()
{
return $this->revisions;
}
// Last revision number
public function getLastRevision()
{
if ($this->revisions) {
return end($this->revisions)->getIndex();
} else {
return $this->lastRevision;
}
}
// Users retrieved along with modules (UserId => WikidotUser)
public function getRetrievedUsers() {
if (!is_array($this->retrievedUsers)) {
$this->retrievedUsers = array();
}
return $this->retrievedUsers;
}
// Retrieval status
public function getStatus() {
return $this->status;
}
}
// Class containing a list of pages of a single wikidot website
class WikidotPageList
{
/*** Fields ***/
// Wikidot name of the site
private $siteName;
// Array of (CategoryId => Name)
private $categories;
// Array of (PageId => WikidotPage)
protected $pages;
// Array of (PageName)
protected $failedPages;
/*** Protected ***/
// Returns class of pages
protected function getPageClass()
{
return 'WikidotPage';
}
/*** Public ***/
public function __construct($siteName)
{
if (!preg_match('/^[\w\-]+$/', $siteName)) {
throw new Exception('Invalid wikidot site name');
}
$this->siteName = $siteName;
$this->pages = array();
$this->failedPages = array();
$this->categories = array();
}
// Add page to the list or update existing page
public function addPage(WikidotPage $page)
{
if (!$page || !is_a($page, $this->getPageClass()) || $page->getSiteName() !== $this->siteName)
return;
$pageId = $page->getId();
if (isset($this->pages[$pageId])) {
$this->pages[$pageId]->updateFrom($page);
} else {
$this->pages[$pageId] = $page;
}
}
// Remove a page from the list
public function removePage($pageId)
{
unset($this->pages[$pageId]);
}
// Retrieves list of categories and stores in the respective field
public function retrieveCategories(WikidotLogger $logger = null)
{