-
Notifications
You must be signed in to change notification settings - Fork 14
/
wiki_parser.php
2887 lines (2180 loc) · 124 KB
/
wiki_parser.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__ ."/utils.php");
/**
* Jungle Wikipedia Syntax Parser
*
* @link https://github.com/donwilson/PHP-Wikipedia-Syntax-Parser
*
* @author Don Wilson <donwilson@gmail.com>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @package Jungle
* @subpackage Wikipedia Syntax Parser
*
* @todo cleaning from $this->clean_wiki_text(xxx) isn't cleaning out inline wiki links [see sections->Presidency->Domestic Policy->Economic Policy: http://jungledb.dev/dev/wiki.php?e=3414021]
* @todo articles without only 1 section: http://jungledb.dev/dev/wiki.php?e=2307763
*/
class Jungle_WikiSyntax_Parser {
private $raw_text;
private $text = "";
private $title = "";
private $cargo = array(
'title' => "",
'title_hash' => "",
'page_attributes' => array(),
'sections' => array(),
'tables' => array(),
'quotes' => array(),
'meta_boxes' => array(),
'external_links' => array(),
'categories' => array(),
'portals' => array(),
);
private $options = array(
'page_attributes' => array(),
'wikipedia_meta' => array(),
// regex rules to ignore/remove specific wiki templates
'ignore_template_matches' => array(
"#^(?:\'|\-|Wikiquote|Use dmy dates|Use mdy dates|nowrap|clear)#si", // functions on words
"#^(?:Expand section|Sister project links|Wikipedia books link|Wikiatlas|Link (?:FL|GL|FA|GA)|good article|anchor|commons|reflist|refimprove|refbegin|refend|Unreferenced|Citation needed|Primary sources|Citation style|medref|no footnotes|more footnotes|cleanup\-|Sources|Verification|Verify)#si",
"#^(?:\-|X mark|Check mark|Tick|hmmm|n\.b\.|bang|(N|Y)\&|Ya|Y|aye|Check mark\-n|X mark\-n|X mark big|Cross((?:\s*)\|(?:[0-9]+?)(?:\s*?)))$#si",
"#^(?:Empty section|Wikinews|link recovered via|expandsect|sortname|see also|sfn|also|Subscription required|Fact|Full|Page needed|Season needed|Volume needed|Clarify|Examples|List fact|Nonspecific)#si",
"#^(?:Featured article|lead too short|inadequate lead|Lead too long|Lead rewrite|Lead missing|distinguish|redirect|fact|pp\-|permanently protected|temporarily protected)#si",
"#^(?:infobox|taxobox|navbox|cite|citation|awards|won|nom|end|Persondata)#si",
"#^(?:Nihongo|Details|Essay|double image|Multiple image|Hatnote|Please check|Inline citations|Indrefs|Citations|No citations|In\-text citations|Nofootnote|Nocitations|Inline refs needed|Inline\-citations|Inline|Nofootnotes|Needs footnotes|Nofn|No inline citations|Noinline|Inlinerefs|Inline\-sources|In line citation|In\-line citations|Inline|Citations|uw\-biog1|uw\-biog2|uw\-biog3|uw\-biog4)#si",
"#^(?:s\-|Col\-begin|Col\-start|Col\-begin\-small|Col\-break|Col\-2|Col\-1\-of\-2|Col\-2\-of\-2|Col\-3|Col\-1\-of\-3|Col\-2\-of\-3|Col\-3\-of\-3|Col\-4|Col\-1\-of\-4|Col\-2\-of\-4|Col\-3\-of\-4|Col\-4\-of\-4|Col\-5|Col\-1\-of\-5|Col\-2\-of\-5|Col\-3\-of\-5|Col\-4\-of\-5|Col\-5\-of\-5|Col\-end|End|Top|Mid|Bottom|Columns\-start|start box|end box|Column|Columns\-end|Multicol|Multicol\-break|Multicol\-end|Div col|Div col end|col\-float|col\-float\-break|col\-float\-end)#si",
"#^(?:NASDAQ|NASDAQ was|NASDAQ link|New York Stock Exchange|NYSE|NYSE was|NYSE link|TSX|TSX was|TSX link)#si",
// http://en.wikipedia.org/wiki/Category:Inline_dispute_templates
"#^(?:Chronology citation needed|Contradict\-inline|Copyvio link|Discuss|Irrelevant citation|Neologism inline|POV\-statement|Slang|Spam link|Speculation\-inline|Talkfact|Tone\-inline|Under discussion\-inline|Undue\-inline)#si",
// specific regex rules
"#^(?:cn|Oc|Hin|Inc\-video|TOCright|TOCleft|Rp|bgcolor\-(?:[A-Za-z0-9\-\_]+))$#si",
"#^(?:BLP|Copy to )#si",
"#^(?:[A-Za-z0-9\-\_\s]+?)(BLP)#si",
// {{xxx|...}} -- cutoff with | for exact template finding
"#^((?:[A-Za-z0-9\-]+)\-stub|dn|dts|Needdab|hidden begin|hidden end|Italic title|unref|Gallery|confusing|Wiktionary|Wikify|Wikt|Wiktionary pipe|Wiktionary category|Wiktionary\-inline|Wiktionary redirect|Copy to Wiktionary|Italic title prefixed|flag|r|Other uses|Otheruses|Multiple issues|as of|Not a typo|Wikisource|es|es icon|legend|\#tag\:(?:.+?)|fb|Advert|lang\-(?:[A-Za-z]{2,4})|pt icon|explain|Context|Bk|rp|nr|notability|cleanup|Tone|Video game cleanup|Plot|link\-interwiki|Issue|Update|For|CI|Cat improve|Improve categories|Catimprove|Cleanup\-cat|Cleanup cat|Few categories|Few cats|Fewcategories|Fewcats|Improve\-categories|Improve\-cats|Improve categories|Improve cats|Improvecategories|Improvecats|More categories|More category|Morecat|Morecategories|Morecats|Cat\-improve|Category\-improve|Categories\-improve|Category improve|Categories improve)\s*\|?#si",
// article messages/wiki cleanup
"#^(?:\.\.\.|Abbreviations|Advert|All plot|Almanac|Alternative text missing|Anachronism|Autobiography|Bad summary|Biblio|Booster|Broken|Buzzword|Category unsourced|Check category|CIA|Clarify timeframe|Clarify\-section|Cleanup|Cleanup AfD|Cleanup Congress Bio|Cleanup red links|Cleanup\-articletitle|Cleanup\-astrology|Cleanup\-biography|Cleanup\-book|Cleanup\-colors|Cleanup\-combine|Cleanup\-comics|Cleanup\-gallery|Cleanup\-GM|Cleanup\-HTML|Cleanup\-ICHD|Cleanup\-images|Cleanup\-infobox|Cleanup\-IPA|Cleanup\-lang|Cleanup\-link rot|Cleanup\-remainder|Cleanup\-reorganize|Cleanup\-rewrite|Cleanup\-school|Cleanup\-spam|Cleanup\-statistics|Cleanup\-tense|Cleanup\-translation|Cleanup\-university|Cleanup\-weighted|Close paraphrasing|Colloquial|Condense|Confusing|Confusing section|Context needed|Contradict|Contradict section|Contradict\-other|Contradict\-other\-multiple|Convert template|Coord missing|Copied howto|Copied section to Wikisource|Copied to Wikibooks|Copied to Wikibooks Cookbook|Copy edit|Copy edit\-section|Criticism section|Criticism title|Dablinks|Dead end|Dead link header|Debate|Dicdef|Directory|Duplication|Editorial|Empty section|Essay\-like|Example farm|Expand article|Expand section|Expert\-maths|Expert\-subject|Expert\-subject\-multiple|External links|Famous|Fanpov|Fiction|Fiction trivia|Format footnotes|Further reading cleanup|Game guide|Generalize|Howto|Ibid|Icon\-issues|Improve categories|In popular culture|In\-universe|Inappropriate person|Incomplete)\s*\|?#si",
"#^(?:Incomplete table|ISBN|Jagged 85 shortened|Like resume|Local|Manual|Misleading|Missing fields|Missing information|More plot|More\-specific\-links|MOS|MOSLOW|NCBI taxonomy|New infobox|News release|News release section|NFimageoveruse|No plot|Nonfiction|NPOV language|Obituary|Off\-topic|ORList|Out of date|Outdated as of|Over\-quotation|Overcolored|Overcoloured|Overlinked|Overly detailed|Peacock|Plot|Prune|Puffery|Recategorize|Refactor|Religion primary|Repair coord|Repetition|Repetition section|Repetition\-inline|Review|Rewrite section|RJL|Schedule|Section\-diffuse|Sections|Too many see alsos|Specific|Story|Strawman|Sub\-sections|Summarize|Summarize section|Summary style|Sync|Tagged|Technical|Term paper|Textbook|ToLCleanup|Tone|Too abstract|Too many photos|Too\-many\-boxes|Travel guide|Trivia|Uncategorized|Unclear date|Underlinked|Undue|Undue precision|Update|Update after|Update section|Very long|Very long section|Video game cleanup|Wikify|Wikify section|Ambox|1911 POV|Abbreviations|Advert|Aero\-table|Afd\-merge required|Afd\-merge to|Afdnotice2|All plot|Almanac|Alphabetize|Alumni|Anachronism|Animals cleanup|Arabic script needed|Armenian script needed|Article for deletion|Autobiography|Bad summary|Being translated)\s*\|?#si",
"#^(?:Video game cleanup|Gamecleanup|Bengali script needed|Berber script needed|Biblio|BLP IMDb refimprove|BLP IMDb\-only refimprove|BLP primary sources|BLP selfpublished|BLP sources|BLP sources section|BLP unsourced|BLP unsourced section|Booster|Broken|Burmese script needed|Buzzword|Category unsourced|Catholic\-cleanup|Caution|Check category|Chemical\-importance|Cherokee script needed|Cherry picked|Chinese script needed|CIA|CIA\-Sect|Citation style|Citations broken|Cite check|Cite plot points|Clarify\-section|Cleanup AfD|Cleanup Congress Bio|Cleanup FJ biography|Cleanup red links|Cleanup split|Cleanup\-articletitle|Cleanup\-astrology|Cleanup\-biography|Cleanup\-book|Cleanup\-colors|Cleanup\-combine|Cleanup\-comics|Cleanup\-gallery|Cleanup\-GM|Cleanup\-HTML|Cleanup\-ICHD|Cleanup\-images|Cleanup\-IPA|Cleanup\-lang|Cleanup\-link rot|Cleanup\-list|Cleanup\-list\-sort|Cleanup\-reorganize|Cleanup\-rewrite|Cleanup\-school|Cleanup\-spam|Cleanup\-statistics|Cleanup\-tense|Cleanup\-translation|Cleanup\-university|Cleanup\-weighted|Close paraphrasing|Coat rack|COI|Colloquial|Comparison|Condense|Confusing|Content|Context|Contradict|Contradict\-other|Contradict\-other\-multiple|Converted|Copied section to Wikisource|Copied to Wikibooks|Copied to Wikibooks Cookbook|Copy edit\-section|Copy section to Wikisource|Copy to gaming wiki|Copy to Wikibooks|Copy to Wikibooks Cookbook|Copy to Wikimedia Commons|Copy to Wikiquote|Copy to Wikisource|Copy to Wikiversity|Copy to Wikivoyage|Copy to Wiktionary|Copypaste|Copyvio\-revdel|Copyvioel|Corrupt (organization)|Coverage|Create\-list|Criticism section|Criticism title|Crystal|Csb\-pageincluded|Csb\-pageincludes|Csb\-wikipage|Current)\s*\|?#si",
"#^(?:Current Australian COTF|Current disaster|Current person|Current related|Current severe outbreak|Current spaceflight|Current sport|Current sport\-related|Current sports transaction|Current tornado outbreak|Current\-anytext|Dabconcept|Dablinks|Db\-revise|Dead end|Dead link header|Debate|Devanagari script needed|Dicdef|Directory|Dispute about|Disputed|Disputed title|Disputed\-category|Disputed\-list|Duplication|DYKissues|Editorial|Egyptian hieroglyphic script needed|Election results missing|Empty section|End of season|Essay\-like|Example farm|Exit list|Expand article|Expand section|Expand Spanish|Expert\-maths|Expert\-subject|Expert\-subject\-multiple|External links|Famous|Famous players|Famous players generic|Fanpov|Few references exist|Fiction|Fiction trivia|Film IMDb refimprove|Footballer\-unknown\-status|Format footnotes|Formula missing descriptions|Fringe theories|Further reading cleanup|Game guide|Gameplay|Generalize|Geographic refimprove|Geographical imbalance|Georgian script needed|Globalize|GOCEinuse|GOCEuc|Greek script needed|Hasty|Hebrew script needed|Historical congressional article|Historical information needed|Historicize|Hoax|Howto|Hypothesis|Ibid|Icon\-issues|Importance\-section|Improve categories|In popular culture|In translation|In\-universe|Inadequate lead|Inappropriate person|Inappropriate title|Inclusion|Incoherent|Incoming links|Incomplete|Incomplete disambiguation|Indian cinema under construction|Indian pop cat|IndicL|Infobox problem|Integrate\-section|InterTransWiki|Invalid references|ISBN|ISSN\-disclaimer|Jagged 85 cleanup|Japanese script needed|Khmer script needed|Kmposts)\s*\|?#si",
"#^(?:Korean script needed|Lacking overview|Lao script needed|Launching|Lead missing|Lead rewrite|Lead too long|Lead too short|Like resume|Link up|Linkage|List dispute|List missing criteria|List to table|List years|Listcopy|Listmaybe|Local|Manual|ManualTranswiki|Math2english|ME\-importance|Mediated|Medref|Memorial|Merge FJC|Merge school|Merging from|Metricate|Meyers|Mileposts|Wikicite|Misleading|Missing|Missing information|Missing information non\-contentious|Missing\-taxobox|Mission|More footnotes|More plot|More\-specific\-links|MOS|MOSLOW|MRfD|Multiple issues|Music\-examples|Nationalhistory|NCBI taxonomy|Need consensus|Needhanja|Needhiragana|Needkanji|Needs table|Neologism|New unreviewed article|New user article|New user article LSU|News release|News release section|NFaudiooveruse|NFimageoveruse|No Copy to Wikibooks|No footnotes|No plot|No prose|Noleak|Noleander shortened|Non\-free|Non\-free\-lists|Non\-free\-overuse|Non\-free\-vio|Nonfiction|Nonnotable content|Not English|Notability|Nothaweng|Notice|Notvio|NovelsWikiProject Collaboration|Now project|NPOV language|Obituary|ODM\-List\-Country|Off\-topic|One source|Only\-two\-dabs|Original research|ORList|Orphan|Out of date|Over coverage|Over\-quotation|Overcoloured|Overlinked|Overly detailed|Page numbers improve|Page numbers needed|Pageinprogress|More information|Partisan sources|Patronymic|Peacock|Persian script needed|Please check ISSN)\s*\|?#si",
"#^(?:Plot hook|Plot notice|POV|POV\-check|POV\-title|POV\-title\-section|POV\:KS|Pp\-create|Pp\-dispute|Pp\-meta|Primary sources|Pro and con list|Proofreader needed|Proposed deletion endorsed|Prose|Prune|Pruned|Pseudo|Puffery|R mentioned in hatnote|Rank order|Recategorize|Recent death|Recent death presumed|Recent unreviewed edits|Recentism|Recently revised|Ref expand|Refimprove|Refimprove section|Regional units|Religion primary|Religious text primary|Repair coord|Repetition|Repetition section|Review|Review wikification|Rewrite section|Rewriting|RJL|Rough translation|Samoan script needed|Schedule|Science review|Section images needed|Section\-diffuse|Section\-sort|Sections|Self\-published|Self\-reference|Spacing|Spam\-request|Specific|Speculation|Split|Split dab|Split2|Splitsectionto|Sports venue to be demolished|Spotlight working|Story|Strawman|Substituted template|Summarize|Summarize section|Summary style|Sync|Synthesis|Syriac script needed|Systemic bias|Tamil script needed|Tech Issue|Technical|Term paper|Textbook|Thai script needed|Third\-party|Tibetan script needed|Time references needed|Time\-context|Tok Pisin script needed|ToLCleanup|Tone|Too abstract|Too few opinions|Too many photos|Too Many Revisions|Too many see alsos|Too\-many\-boxes|TrainingPage|TranslatePassage|Translation WIP|Travel guide|Trivia|TWCleanup|TWCleanup2|Unbalanced|Unbalanced section|Uncategorized stub|Unchronological|Unclear date)\s*\|?#si",
"#^(?:Underlinked|Undue|Undue\-section|Units attention|Unlinked references|Unreferenced|Unreferenced Kent|Unreferenced section|Unreferenced small|Unreferenced top icon|Unreferenced\-Fs|Unreferenced\-law|UnreferencedMED|Unreliable sources|Unsorted|Upcoming contests|Update|Update\-EB|USgovtPOV|USRD\-wrongdir|Verifiability|Verify sources|Very long|Very long section|Video game cleanup|Vietnamese script needed|Vital construction|WA botmark|Weasel|WH\-transwiki\-from|WH\-transwiki\-to|Wikify|Wikify section|WPJournalsCotW\-Article|WWFinuse|Yiddish script needed)\s*\|?#si",
"#^(?:BLP IMDb refimprove|BLP IMDb\-only refimprove|BLP primary sources|BLP selfpublished|BLP sources|BLP sources section|BLP unsourced|BLP unsourced section|Broken ref|Chronology citation needed|Circular|Citation style|Citations broken|Cite check|Cite plot points|Cleanup\-link rot|Disputed|Disputed\-section|Expert\-talk|Geodata\-check|Hoax|Ibid|Include\-eb|Irrelevant citation|ISSN\-needed|Issue|Medref|More footnotes|Neologism|Neologism inline|No footnotes|Nonspecific|One source|Original research|Page numbers improve|Page numbers needed|Peacock term|Primary sources|Refimprove|Refimprove section|Reflist\-talk|Religious text primary|Science review|Section OR|Self\-published|Self\-reference|Specific time|Specify|Speculation|Speculation\-inline|Synthesis|Synthesis\-inline|Tertiary|Time references needed|Tone\-inline|Unlinked references|Unreferenced|Unreferenced section|Unreferenced\-law|Unreferenced\-law section|Unreferenced2|Unreliable sources|Verify sources|Volume needed|Weasel\-inline)\s*\|?#si",
"#^(?:Language|Aa|Ab|Ace|Ae|Af|Ak|Am|An|Ar|Arn|Arz|As|Ast|Av|Ay|Az|Ba|Bi|Be|Ber|Bg|Bla|Bm|Bn|Bo|Br|Bs|Bxr|Byq|Ca|Cbv|Cdo|Ce|Ceb|Ch|Chm|Ckb|Ckv|Ssf|Co|Cr|Crh|Cz|Cu|Cv|Cy|Da|De|Dsb|Dv|Dz|Ee|El|En|Eo|Es|Et|Eu|Ext|Fa|Ff|Fi|Fj|Fo|Fr|Frp|Fur|Fy|Ga|Gd|Gl|Gn|Grc|Gsw|Gu|Gv|Ha|He|Hi|Hif|Ho|Hr|Hsb|Ht|Hu|Hy|Hz|Ia|Id|Ie|Ig|Ii|Ik|Ilo|Io|Is|It|Iu|Ja|Jac|Jv|Ka|Kab|Kar|Kg|Ki|Kj|Kk|Kl|Km|Kn|Knn|Ko|Kr|Ks|Ksh|Ku|Kv|Kw|Ky|Kz|La|Lb|Lg|Li|Lij|Liv|Ln|Lo|Lou|Lt|Lu|Lv|Mam|Me|Mh|Mi|Mk|Ml|Mn|Mo|Mr|Ms|Mt|Mwl|My|Myn|Na|Nah|Nan|Nap|Nd|Nds|Ne|New|Ng|Nl|Nn|No|Non|Nr|Nso|Nv|Ny|Oc|Oe|Oj|Om|Or|Os|Oto|Pa|Ph|Pi|Pl|Pms|Ps|Pt|Qu|Quc|Rm|Rmy|Rn|Ro|Roa\-rup|Ru|Rw|Sa|Sah|Sc|Scn|Sco|Sd|Sdc|Sdn) icon\s*$#si",
"#^(?:DABcheck|DGA\-icon|DYK user topicon|FA number|FA pass|FA user topicon|FAC|FAC welcome|FAC withdrawn|FAC2|FACClosed|FACfailed|FAClink|FAR|FAR\-icon|FARClosed|FARMessage|FARpass|FARpassed|FARpasswith|FC withdrawn|Featured animation|Featured article|Featured article candidates|Featured article review|Featured article tools|Featured list|Featured list candidates|Featured list removal candidates|Featured picture|Featured picture set|Featured portal|Featured sound|FFA number|FFL number|FL number|FL pass|FL user topicon|FLC|FLC withdrawn|FLCClosed|FLCfailed|FLRC|Former featured picture|Former featured sound|FormerFA2|FP number|FP user topicon|FPcandidates|FPCold|FPCresult|FPlowres|FPO number|FPO user topicon|FPOC|FPOCClosed|FPR|FPRMessage|FS number|FSC|FT number|FT pass|ITN user topicon|Link FA|Link FL|OFAN|PI featured article|QOTD|QuoteText|TFA|Today's featured article request|WP FAC|WP FC|WP FL|WP FLC)\s*\|?#si",
"#^(?:Alphabetize|Complete|Dynamic list|Expand list|Expand list section|Inc\-film|Inc\-lit|Inc\-musong|Inc\-personnel|Inc\-results|Inc\-sport|Inc\-transport|Inc\-tv|Inc\-up|Inc\-vg|Inc\-video|List dispute|List missing criteria|Main list|Dyoh|LastMonth|Lmonth|NextMonth|Nmonth|RD Archive header|RD Archive header monthly|RD medadvice|RD medremoval|RD removal|RD\-deleted|RefDesk|Refdesk|Refdeskchatty|Searchanswer|TodayRD|Tomor|Tomorr|WPRDAC attention|Yest|Yester|AFCHD|Help desk templates|Help me IRC|Help me\-na|Help me\-nq|Help me\-ns|Helpme\-unblock|Helpme\-unblock2|Sofixit|Solookitup|Dyoh|Cleanup\-spam|No more links|NoMoreCruft|NoMoreLinksTrackback|Prone to spam|Spam link|Spam note|Welcomespam|Dispute templates|3O|3Odec|3OR|3ORshort|Accessibility dispute|BLPVio|Cleanup\-articletitle|Content|Controversial|Dispute about|Dispute progress|Dispute\-resolution|Disputed|Disputed chem|Disputed tag|Disputed title|Disputed\-category|Disputed\-list|Disputed\-section|Gdansk\-Vote\-Notice|Hidden content dispute|Jew\-MJ dispute|List dispute|List missing criteria|Out of date|Pbneutral|Rfc|RFCheader|Speculation|Third opinion|Under discussion|DR case status|DRN|DRN archive bottom|DRN archive top|DRN case status|Drn filing editor|DRN status|DRN\-notice)\s*\|?#si",
"#^(?:User DRN|Chronology citation needed|Contradict\-inline|Copyvio link|Discuss|Irrelevant citation|Neologism inline|POV\-statement|Slang|Spam link|Speculation\-inline|Talkfact|Tone\-inline|Under discussion\-inline|Undue\-inline|Dispute templates|1911 POV|According to whom|Advert|Autobiography|By whom|Catholic\-cleanup|Cherry picked|Circular\-ref|Coat rack|COI|Compared to?|Fringe theories|Like resume|Lopsided|Manual|Memorial|NPOV disputes progress|NPOV language|Obituary|Partisan sources|Pbneutral|Peacock|POV|POV\-check|POV\-lead|POV\-map|POV\-section|POV\-statement|POV\-title|Pp\-reset|Pseudo|Puffery|Recentism|Self\-published|Self\-published inline|Self\-published source|Story|Systemic bias|Tone|Too few opinions|Unbalanced|Unbalanced section|Undue|Undue\-inline|USgovtPOV|Weasel|Which|Who|Refdeskchatty|R template index|Redirect template|This is a redirect|R from code|Redirect for convenience|Deprecated stub|Deprecated template|R from title without diacritics|R from incomplete disambiguation|R from incorrect disambiguation|R from incorrect name|R from misspelling|Redirect from modification|R from name and country|No redirect|R from other disambiguation|Redirect from plural|R from postal abbreviation|R from alternative punctuation|R from ambiguous page|R from merge|R from other capitalisation|R from printworthy plural|R from tzid|R restricted|R to disambiguation page|R from railroad name with ampersand|Redirect from case citation|Redirect to circumvent Special\:RELC|Redirect to related topic|R from related word|R from shortcut|Redirect to plural|R from alternative spacing|R from UK postcode|R from unnecessary disambiguation|R from US postal abbreviation|R from year)\s*\|?#si",
// http://en.wikipedia.org/wiki/Template:Citation_needed/doc#Inline_templates
"#^(?:Attribution needed|Which|Citation needed|Primary source\-inline|Retracted|Third\-party\-inline|Author missing|Author incomplete|Date missing|ISBN missing|Publisher missing|Title incomplete|Year missing|Contradict\-inline|Contradiction\-inline|Examples|Inconsistent|List fact|Lopsided|Clarify timeframe|Update\-small|Where|Year needed|Disambiguation needed|Pronunciation needed|Ambiguous|Awkward|Buzz|Elucidate|Expand acronym|Why|Cite quote|Clarify|Examples|List fact|Nonspecific|Page needed|Citation needed span|Cn\-span|Fact span|Reference necessary|Full|Season needed|Volume needed|Better source|Dead link|Failed verification|Request quotation|Self\-published inline|Source need translation|Verify credibility|Verify source|Definition|Dubious|Technical\-statement|Or|Peacock term|POV\-statement|Quantify|Time fact|Chronology citation needed|Undue\-inline|Vague|Weasel\-inline|When|Who|Whom|By whom|Update after|Cite check|Refimprove|Unreferenced|Citation style|No footnotes)#si",
// http://en.wikipedia.org/wiki/Template:Use_Australian_English
"#^(?:Use Australian English|Use American English|Use British English|Use British \(Oxford\) English|Use Canadian English|Use Indian English|Use New Zealand English|Use Pakistani English|Use South African English)#si",
// other wikis
"#^(?:en|de|fr|nl|it|pl|es|ru|ja|pt|zh|sv|vi|uk|ca|no|fi|cs|hu|fa|ko|ro|id|tr|ar|sk|eo|da|sr|lt|kk|ms|he|eu|bg|sl|vo|hr|war|hi|et|az|gl|nn|simple|la|el|th|new|sh|roa\-rup|oc|mk|ka|tl|ht|pms|te|ta|be\-x\-old|be|br|lv|ceb|sq|jv|mg|cy|mr|lb|is|bs|my|uz|yo|an|lmo|hy|ml|fy|bpy|pnb|sw|bn|io|af|gu|zh\-yue|ne|nds|ur|ku|ast|scn|su|qu|diq|ba|tt|ga|cv|ie|nap|bat\-smg|map\-bms|wa|als|am|kn|gd|bug|tg|zh\-min\-nan|sco|mzn|yi|yec|hif|roa\-tara|ky|arz|os|nah|sah|mn|ckb|sa|pam|hsb|li|mi|si|co|gan|glk|bar|bo|fo|bcl|ilo|mrj|se|nds\-nl|fiu\-vro|tk|vls|ps|gv|rue|dv|nrm|pag|pa|koi|xmf|rm|km|kv|csb|udm|zea|mhr|fur|mt|wuu|lad|lij|ug|pi|sc|or|zh\-classical|bh|nov|ksh|frr|ang|so|kw|stq|nv|hak|ay|frp|ext|szl|pcd|gag|ie|ln|haw|xal|vep|rw|pdc|pfl|eml|gn|krc|crh|ace|to|ce|kl|arc|myv|dsb|as|bjn|pap|tpi|lbe|mdf|wo|jbo|sn|kab|av|cbk\-zam|ty|srn|lez|kbd|lo|ab|tet|mwl|ltg|na|ig|kg|za|kaa|nso|zu|rmy|cu|tn|chy|chr|got|sm|bi|mo|iu|bm|ik|pih|ss|sd|pnt|cdo|ee|ha|ti|bxr|ts|om|ks|ki|ve|sg|rn|cr|lg|dz|ak|ff|tum|fj|st|tw|xh|ny|ch|ng|ii|cho|mh|aa|kj|ho|mus|kr|hz)(?:\s*?)\:#si",
),
);
// list of subdomains that WikiPedia uses for foreign wikis
private $foreign_wiki_regex = "(en|de|fr|nl|it|pl|es|ru|ja|pt|zh|sv|vi|uk|ca|no|fi|cs|hu|fa|ko|ro|id|tr|ar|sk|eo|da|sr|lt|kk|ms|he|eu|bg|sl|vo|hr|war|hi|et|az|gl|nn|simple|la|el|th|new|sh|roa\-rup|oc|mk|ka|tl|ht|pms|te|ta|be\-x\-old|be|br|lv|ceb|sq|jv|mg|cy|mr|lb|is|bs|my|uz|yo|an|lmo|hy|ml|fy|bpy|pnb|sw|bn|io|af|gu|zh\-yue|ne|nds|ur|ku|ast|scn|su|qu|diq|ba|tt|ga|cv|ie|nap|bat\-smg|map\-bms|wa|als|am|kn|gd|bug|tg|zh\-min\-nan|sco|mzn|yi|yec|hif|roa\-tara|ky|arz|os|nah|sah|mn|ckb|sa|pam|hsb|li|mi|si|co|gan|glk|bar|bo|fo|bcl|ilo|mrj|se|nds\-nl|fiu\-vro|tk|vls|ps|gv|rue|dv|nrm|pag|pa|koi|xmf|rm|km|kv|csb|udm|zea|mhr|fur|mt|wuu|lad|lij|ug|pi|sc|or|zh\-classical|bh|nov|ksh|frr|ang|so|kw|stq|nv|hak|ay|frp|ext|szl|pcd|gag|ie|ln|haw|xal|vep|rw|pdc|pfl|eml|gn|krc|crh|ace|to|ce|kl|arc|myv|dsb|as|bjn|pap|tpi|lbe|mdf|wo|jbo|sn|kab|av|cbk\-zam|ty|srn|lez|kbd|lo|ab|tet|mwl|ltg|na|ig|kg|za|kaa|nso|zu|rmy|cu|tn|chy|chr|got|sm|bi|mo|iu|bm|ik|pih|ss|sd|pnt|cdo|ee|ha|ti|bxr|ts|om|ks|ki|ve|sg|rn|cr|lg|dz|ak|ff|tum|fj|st|tw|xh|ny|ch|ng|ii|cho|mh|aa|kj|ho|mus|kr|hz)";
private $inner_bypass; // rigged to pass messages between two private classes
public function __construct($text, $title="", $user_options=false) {
$this->title = $title;
// remove comments
$text = preg_replace("#". preg_quote("<!--", "#") ."(.*?)". preg_quote("-->", "#") ."#si", "", $text);
$this->text = $text;
$this->raw_text = $text;
if(!empty($user_options) && is_array($user_options)) {
$this->options = $user_options + $this->options;
}
}
public function __destruct() {
$this->text = "";
$this->title = "";
$this->cargo = "";
}
public function parse($sections_to_ignore=array()) {
$this->citations();
$this->initial_clean();
$this->templates();
$this->page_attributes();
if(!in_array("sections", $sections_to_ignore)) {
$this->sections();
}
if(!in_array("external_links", $sections_to_ignore)) {
$this->external_links();
}
if(!in_array("categories", $sections_to_ignore)) {
$this->categories();
}
if(!in_array("portals", $sections_to_ignore)) {
$this->portals();
}
if(!in_array("meta_boxes", $sections_to_ignore)) {
$this->meta_boxes();
}
if(!in_array("foreign_wikis", $sections_to_ignore)) {
$this->foreign_wikis();
}
if(!in_array("attachments", $sections_to_ignore)) {
$this->attachments();
}
//if(!in_array("guess", $sections_to_ignore)) {
// $this->make_logical_guesses_on_content();
//}
$this->pack_cargo();
$this->cargo = $this->finalize_internal_links($this->cargo);
if(!empty($sections_to_ignore)) {
foreach($sections_to_ignore as $section_to_ignore) {
if(isset($this->cargo[ $section_to_ignore ])) {
unset($this->cargo[ $section_to_ignore ]);
}
}
}
// move citations down
if(isset($this->cargo['citations'])) {
$citations = $this->cargo['citations'];
unset($this->cargo['citations']);
$this->cargo['citations'] = $citations;
unset($citations);
}
foreach(array_keys($this->cargo) as $cargo_key) {
if(empty($this->cargo[$cargo_key])) {
unset($this->cargo[$cargo_key]);
}
}
$this->cargo['debug']['peak_memory_usage'] = memory_get_peak_usage();
return $this->cargo;
}
private function tables($section_header_key, $section_syntax) {
$section_syntax_offset_cursor_position = 0;
if(preg_match_all("#(\{{2}col\-begin\}{2})(.+)(\{{2}col\-end\}{2})#si", $section_syntax, $col_matches, PREG_OFFSET_CAPTURE)) {
foreach(array_keys($col_matches[0]) as $col_key) {
$cols = preg_split("#\s*\{{2}\-\}{2}\s*#s", $col_matches[2][ $col_key ][0], -1, PREG_SPLIT_NO_EMPTY);
if(!empty($cols)) {
foreach($cols as $col) {
// column cleanup
$col = preg_replace("#^\|([^\|]+)\|#si", "", $col);
$col = preg_replace("#(\s*)\|([^\|]+)\|\s*$#si", "\\1", $col);
$col = trim($col, " |");
// process any inner tables
$section_syntax = $this->tables($section_header_key, $col);
}
}
}
}
while(preg_match("#\{\|(?:.+?)\|\}#s", $section_syntax, $matches, PREG_OFFSET_CAPTURE)) {
$bits = preg_split("#\|\}\s*#s", $matches[0][0], -1, PREG_SPLIT_DELIM_CAPTURE);
$new = array_shift($bits) ."|}";
$new .= array_shift($bits);
$offset = $matches[0][1];
if(strtoupper(mb_detect_encoding($section_syntax)) == "UTF-8") {
$offset = mb_strlen(mb_strcut($section_syntax, 0, $matches[0][1]));
}
$section_syntax = $this->table_process($new, $offset, $section_syntax, $section_header_key);
}
return $section_syntax;
}
private function table_process($table, $raw_table_full_offset, $section_syntax, $section_header_key) {
// Generate unique table key
$table_key = substr(md5(microtime(true) ."_". rand(0, 9999) ."_". (__LINE__ * rand(1, 100))), 0, 8);
$raw_table_full_length = mb_strlen($table);
$wiki_table_shortcode = "[wiki_table=". $table_key ."]";
$section_syntax_before = $section_syntax;
$section_syntax = mb_substr($section_syntax, 0, $raw_table_full_offset) . $wiki_table_shortcode . mb_substr($section_syntax, ($raw_table_full_offset + $raw_table_full_length));
$table_before = $table;
$table = preg_replace("#\|\-([^\n]*)\n#si", "|-\n", $table);
$table = preg_replace("#^\{\|([^\n]*?)\n\|\-#si", "{|", $table);
$table_data = array();
$table = trim(str_replace("\r", "", $table));
$table = preg_replace(array("#^\s*\{\s*\|\s*(?:\|\-\s*)?#si", "#(?:\s*\|\-)?\s*\|\s*\}\s*$#si"), "", $table);
$table = preg_replace("#(width|height)=([0-9\"\'\s]*)#si", " ", $table);
$table = preg_replace("#\s*(?:width|height|border|style|class|cellpadding|cellspacing|align|id)=(\"|\')?(?:[^\\1]*?)\\1#si", "", $table);
$table = preg_replace("#\s*(?:width|height|border|style|class|cellpadding|cellspacing|align|id)=(?:[^\s]*?)#si", "", $table);
$table = preg_replace("#". preg_quote(PHP_EOL, "#") ."\|{2,}#si", "\n|", $table);
$table = preg_replace("#". preg_quote(PHP_EOL, "#") ."\!{2,}#si", "\n!", $table);
$table = preg_replace(array("#^\s*\|\-\s*#si", "#\s*\|\-\s*$#si"), "", $table);
$table = trim($table);
//new dBug(array(
// 'table_key' => $table_key,
// 'raw_table_full_length' => $raw_table_full_length,
// 'raw_table_full_offset' => $raw_table_full_offset,
// 'wiki_table_shortcode' => $wiki_table_shortcode,
// 'wiki_table_shortcode_length' => mb_strlen($wiki_table_shortcode),
// 'table' => $table_before,
// 'table_len' => strlen($table_before),
// 'table_len_mb' => mb_strlen($table_before),
// 'section_syntax_before' => $section_syntax_before,
// 'section_syntax' => $section_syntax,
//));
//$rows = preg_split("#\s*". preg_quote("|-", "#") ."\s*#", $table, -1, PREG_SPLIT_NO_EMPTY);
$rows = preg_split("#\s". preg_quote("|-", "#") ."\s#", $table);
if(empty($rows)) {
return $section_syntax;
}
$num_header_rows = 0;
$row_i = 1;
$rowspan_bucket = array(); // store rowspan="" data while going through rows
foreach($rows as $row) {
if($num_header_rows === 0 && preg_match("#\s*\|\+\s*#si", $row)) {
//print "continue... ". __LINE__ ."<br />\n";
continue;
}
$row = $this->insert_jungledb_helpers($row);
$row = str_replace("!!", "\n!", $row);
$row = str_replace("||", "\n|", $row);
$row = preg_replace("#^\s*\|". preg_quote(PHP_EOL, "#") ."#si", "", $row);
$row_type = false;
if($row_type === false && preg_match("#scope=\"\s*(row|col)\s*\"#si", $row, $match)) {
if(strtolower(trim($match[1])) == "row") {
$row_type = "data";
} elseif(strtolower(trim($match[1])) == "col") {
$row_type = "header";
}
}
if($row_type === false && preg_match("#\n\s*!#si", $row)) {
$row_type = "header";
}
//$columns = preg_split("#\s*(\![^\|]*)?\|\s*#si", $row, -1, PREG_SPLIT_DELIM_CAPTURE ^ PREG_SPLIT_NO_EMPTY);
//$columns = explode("\n", $row);
$columns = preg_split("#\s*". preg_quote(PHP_EOL, "#") ."(\||\!)#si", $row);
//array_shift($columns);
if(empty($columns)) {
//print "continue... ". __LINE__ ."<br />\n";
//print htmlentities($row) ."<br />\n";
//print "<hr />\n";
continue;
}
if(empty($num_header_rows)) {
$num_header_rows = 1;
$_num_header_rows = 1;
}
if($row_type === false && ($row_i <= $num_header_rows)) {
$row_type = "header";
}
// default to row_type = row
if($row_type === false) {
$row_type = "data";
}
$table_data[ $row_i ]['type'] = $row_type;
// save column data
$max_rowspan = 1;
$col_i = 1; // column id
foreach($columns as $column) {
$column_before = $column;
if($row_type === "header") {
while(!empty($rowspan_bucket[ $col_i ])) {
$rowspan_bucket[ $col_i ]--;
$col_i++;
}
}
$col_x = 1; // number of columns to fill
$col_y = 1; // number of rows to fill
if(preg_match_all("#\s*(row|col)span=([0-9\"\']+)#si", $column, $spanmatches)) {
foreach(array_keys($spanmatches['0']) as $mkey) {
$span_type = strtolower(trim($spanmatches['1'][$mkey]));
$span_length = trim(preg_replace("#[^0-9]+#si", "", $spanmatches['2'][$mkey]));
//if($span_length <= 1) {
// continue;
//}
if($span_type == "row") {
$col_y = max(1, $span_length);
if($row_type === "header") {
$rowspan_bucket[ $col_i ] = ($span_length - 1);
}
} elseif($span_type == "col") {
$col_x = max(1, $span_length);
}
}
}
// leading spaces + ! + spaces
$column = preg_replace("#^\s*\!\s*#si", "", $column);
// leading spaces + | + spaces
$column = preg_replace("#^\s*\|\s*#si", "", $column);
// leading "xxx="""
$column = preg_replace("#^\s*([A-Za-z0-9\-\_]+)=\"(.+?)\"#si", "", $column);
$column = preg_replace("#^\s*([A-Za-z0-9\-\_]+)=(.*)\s*(?:\||\!)#si", "", $column);
// leading spaces + | + spaces
$column = preg_replace("#^\s*\|{1,}\s*#si", "", $column);
$column = trim($column);
$column = $this->clean_jungledb_helpers($column);
$column = $this->clean_wiki_text($column, true);
$column = trim($column, " |");
if($row_type === "header") {
$column = ltrim($column, " |!");
}
$column_data = array(
'text' => $column,
);
// process and save basic row data columns
if($row_type === "data") {
for($y = $row_i; $y <= ($row_i + ($col_y - 1)); $y++) {
$table_data[ $y ]['type'] = "data";
for($i = $col_i; $i <= ($col_i + ($col_x - 1)); $i++) {
if(isset($table_data[ $y ]['columns'][ $i ])) {
$col_i++;
continue;
}
$table_data[ $y ]['columns'][ $i ] = $column_data;
}
}
}
// process header data
if($row_type === "header") {
if($col_x > 1) {
$column_data['colspan'] = $col_x;
}
if($col_y > 1) {
$column_data['rowspan'] = $col_y;
$max_rowspan = max($max_rowspan, $col_y);
}
$table_data[ $row_i ]['columns'][ $col_i ] = $column_data;
}
if($col_x > 1) {
$col_i = ($col_i + ($col_x - 1));
}
$col_i++;
}
$num_header_rows = ($num_header_rows + ($max_rowspan - 1));
// remove completely empty rows -- stop on first non-strlen=0 column, else remove and go on
$check_continue = true;
foreach($table_data[ $row_i ]['columns'] as $column) {
if(strlen( trim($column['text']) ) > 0) {
$check_continue = false;
break;
}
}
if($check_continue === true) {
// didn't pass check, remove this data and go on without updating increaser
unset($table_data[ $row_i ]);
continue;
}
$row_i++;
}
if(!empty($table_data)) {
// clean columns
$num_cols = 0;
foreach($table_data as $table_row_id => $table_row) {
if(empty($num_cols) && $table_row['type'] == "header") {
foreach($table_row['columns'] as $column) {
if(!empty($column['colspan'])) {
$num_cols += $column['colspan'];
} else {
$num_cols++;
}
}
continue;
}
if(!empty($num_cols) && $table_row['type'] === "data") {
ksort($table_data[$table_row_id]['columns']);
foreach(array_keys($table_row['columns']) as $column_id) {
if($column_id > $num_cols) {
unset($table_data[$table_row_id]['columns'][$column_id]);
}
}
}
}
if(!isset($this->cargo['tables'])) {
$this->cargo['tables'] = array();
}
$this->cargo['tables'][ $table_key ] = array(
'key' => $table_key,
'section' => $section_header_key,
'num_columns' => $num_cols,
'num_rows' => ($row_i - 1 - $num_header_rows),
'data' => $table_data,
);
}
return $section_syntax;
}
private function quotes($section_header_key, $section_syntax) {
// http://en.wikipedia.org/wiki/Category:Quotation_templates
// specific: http://en.wikipedia.org/wiki/Template:Cquote
// TODO
$this->inner_bypass = $section_header_key;
$section_syntax = preg_replace_callback("#\{{2}\s*(bq|Block quote|Bquote|cquote|cquote2|quote|blockquote|quote box|rquote|Quotation)\s*\|(.+?)\}{2}#si", array($this, "quote_parser"), $section_syntax);
return $section_syntax;
}
private function quote_parser($match) {
$section_header_key = $this->inner_bypass;
$template = strtolower(trim($match[1]));
$contents = explode("|", trim($this->insert_jungledb_helpers($match[2]), " |"));
// stylized text only
if(in_array($template, array("bq"))) {
return trim($match[2], " |");
}
$quote = array(
'key' => substr(md5($section_header_key ."_". rand(1, 9999) ."_". rand(300, 5099)), 0, 8),
'section' => $section_header_key,
'text' => false,
);
// complex template
if(in_array($template, array("quote box"))) {
foreach($contents as $content) {
if(preg_match("#^\s*title\s*=\s*(.+?)$#si", $content, $content_match)) {
$quote['title'] = trim($content_match[1]);
continue;
}
if(preg_match("#^\s*quote\s*=\s*(.+?)$#si", $content, $content_match)) {
$quote['text'] = trim($content_match[1]);
continue;
}
if(preg_match("#^\s*source\s*=\s*(.+?)$#si", $content, $content_match)) {
$quote['source'] = trim($content_match[1]);
continue;
}
}
} else {
// general template
$quote['text'] = array_shift($contents);
if(!empty($contents) && in_array($template, array("block quote", "bquote", "quotation"))) {
array_shift($contents);
array_shift($contents);
}
if(!empty($contents)) {
$quote['author'] = array_shift($contents);
}
if(!empty($contents)) {
$quote['source'] = array_shift($contents);
}
if(!empty($contents)) {
$quote['publication'] = array_shift($contents);
}
}
// prep text
if($quote['text'] === false) {
return "";
}
$quote['text'] = trim(preg_replace("#^(?:quotetext|\d|text)\s*=\s*#si", "", trim($quote['text'])));
if(strlen($quote['text']) < 1) {
return "";
}
if(isset($quote['author'])) {
$quote['author'] = trim(preg_replace("#^(?:personquoted|\d|sign)\s*=\s*#si", "", trim($quote['author'])));
if(strlen($quote['author']) < 1) {
unset($quote['author']);
}
}
if(isset($quote['source'])) {
$quote['source'] = trim(preg_replace("#^(?:quotesource|\d|source)\s*=\s*#si", "", trim($quote['source'])));
if(strlen($quote['source']) < 1) {
unset($quote['source']);
}
}
$quote = array_map(array($this, "clean_jungledb_helpers"), $quote);
$this->cargo['quotes'][ $quote['key'] ] = $quote;
return "[wiki_quote=". $quote['key'] ."]";
}
private function templates() {
$templates = array();
//preg_match_all("#(". preg_quote("{{", "#") .")(.*?)(". preg_quote("}}", "#") .")#si", $this->text, $matches);
$text_templates = $this->_find_sub_templates($this->text);
foreach($text_templates[0] as $text_template) {
if(!preg_match("#^\{\{([^\|\:]+)(.*?)\}\}$#si", $text_template, $match)) {
continue;
}
$template_name = trim($match[1]); // wikisyntax is very case sensitive, so don't use strtolower or similar
if(!empty($this->options['ignore_template_matches'])) {
foreach($this->options['ignore_template_matches'] as $ignore_template_match_regex) {
if(preg_match($ignore_template_match_regex, $template_name)) {
continue 2;
}
}
}
//$template_attributes = trim(ltrim(trim($match[2]), "|")); // remove trailing spaces and starting pipe
$template_attributes = trim(preg_replace("#^(?:[\s|\||\:]*?)#si", "", $match[2]));
$template = array(
':template' => $this->compact_to_slug($template_name),
'template' => $template_name,
);
if(strlen($template_attributes) > 0) {
$template_attributes = $this->insert_jungledb_helpers($template_attributes);
//$template_attributes = preg_replace("#\[\[\s*([^\|]+?)\|(.+?)\]\]#si", "[[\\1###JNGLDBDEL###\\2]]", $template_attributes);
if((strstr($template_attributes, "=") !== false) || (strstr($template_attributes,"|") !== false)) {
$template_attributes_array = explode("|", $template_attributes);
$template_attributes = array();
foreach($template_attributes_array as $taa_attr) {
$taa_attr = trim($taa_attr);
if(preg_match("#^([A-Za-z0-9\_]+?)\=(.+)$#si", $taa_attr, $taa_attr_match)) {
$template_attributes[ $this->compact_to_slug($taa_attr_match[1]) ] = trim($taa_attr_match[2]);
} else {
$template_attributes[] = trim($taa_attr);
}
}
}
$template_attributes = $this->clean_jungledb_helpers($template_attributes);
$template['attributes'] = $this->explodeString_byBreak($template_attributes);
}
//$sub_templates = $this->_find_sub_templates($template['original']); // eventually...
$templates[] = $template;
}
if(!empty($templates)) {
$this->cargo['wikipedia_meta']['templates'] = $templates;
}
}
private function page_attributes() {
$page_attributes = array(
'type' => false
);
if($page_attributes['type'] === false && (preg_match("#^(Template|Wikipedia|Portal|User|File|MediaWiki|Template|Category|Book|Help|Course|Institution)\:#si", $this->title, $match))) {
// special wikipedia pages
$page_attributes['type'] = strtolower($match['1']);
}
if($page_attributes['type'] === false && (preg_match("#\#REDIRECT\s*\[\[([^\]]+?)\]\]#si", $this->text, $match))) {
// redirection
$page_attributes['type'] = "redirect";
$page_attributes['child_of'] = $match[1];
}
if($page_attributes['type'] === false && (preg_match("#\{\{(disambig|hndis|disamb|hospitaldis|geodis|disambiguation|mountainindex|roadindex|school disambiguation|hospital disambiguation|mathdab|math disambiguation)((\|[^\}]+?)?)\}\}#si", $this->text, $match))) {
// disambiguation file
$page_attributes['type'] = "disambiguation";
$page_attributes['disambiguation_key'] = $this->compact_to_slug($match[1]);
if(strlen(trim($match[2])) > 0) {
$page_attributes['disambiguation_value'] = trim($match[2]);
}
}
if($page_attributes['type'] === false) {
// just a normal page
$page_attributes['type'] = "main";
}
if(preg_match("#\{\{\s*Use\s+([ymdhs]{3,5})\s+date#si", $this->text, $match)) {
$page_attributes['date_format'] = $match[1];
}
if(!empty($page_attributes)) {
$this->cargo['page_attributes'] = $page_attributes;
}
}
private function meta_boxes() {
// Todo: Some pages use {{MLB infobox ... }} instead of {{Infobox MLB ... }} [ex: http://en.wikipedia.org/wiki/Texas_Rangers_(baseball)]. I think {{MLB ...}} is an actual Wikipedia template and not distinctly an Infobox template
//////// TODO /////////////////
$meta_box_templates = array(
"USCensusPop",
"NASDAQ",
"NASDAQ was",
"NASDAQ link",
"New York Stock Exchange",
"NYSE",
"NYSE was",
"NYSE link",
"TSX",
"TSX was",
"TSX link",
"(?:[A-Za-z0-9\s\-\_]+?) (?:infobox|taxobox)",
"Automatic taxobox",
"Football kit",
"Cladogram",
"tracklist",
"Track listing",
"Starbox\s+([A-Za-z0-9\-\_]+?)",
"drugbox",
"Historical populations",
"Demography",
"Coords?\s*\|",
"Location map",
"Weather box",
"Album ratings",
"Film ratings",
"Song ratings",
"Video game reviews",
"Chembox",
"Convention list",
"Pedigree",
"DYS",
"NCAA Division I baseball rankings",
"NCAA Division I FBS football ranking movements",
"CFB Conference Schedule Entry",
"CFB passer rating",
"CFB Schedule End",
"CFB Schedule Entry",
"CFB Standings End",
"CFB Standings Entry",
"CFB Standings Start",
"CFB Team Depth Chart",
"CFB Yearly Record End",
"CFB Yearly Record Entry",
"CFB Yearly Record Start",
"CFB Yearly Record Subhead",
"CFB Yearly Record Subtotal",
"College athlete recruit end",
"College athlete recruit entry",
"Tomatobox",
"Sourcetext",
"Singlechart",
"Singles discography",
"USFL team",
"V8 supercar race",
"Video game multiple console reviews",
"Video game titles",
"rocketspecs",
"Rfam box",
"VG Reviews",
"Episode list",
"Independent baseball team",
"Infobox independent baseball team",
// Generic ones at the bottom
"Infobox",
"Geobox",
"Persondata",
"Succession box",
"Taxobox",
);
preg_match_all("/\{{2}((?>[^\{\}]+)|(?R))*\}{2}/x", $this->text, $matches);
if(empty($matches[0])) {
return false;
}
$skipped_templates = array("main", "main list", "cat main", "mainarticle", "see also2", "see also", "see", "further", "about", "rellink", "portal", "portalbox", "portal box", "portal bar", "portal-inline", "bq", "block quote", "bquote", "cquote", "cquote2", "quote", "blockquote", "quote box", "rquote", "quotation");
$meta_boxes = array();
//$meta_boxes['_debug'] = $matches;
$_meta_boxes_multiples = array();
foreach($matches[0] as $key => $raw_template_syntax) {
$raw_template_syntax = trim($raw_template_syntax);
// skip over those that we already remove/process
if(!preg_match("#\{{2}\s*(". implode("|", $meta_box_templates) .")(.+?)\}{2}$#si", $raw_template_syntax, $template_type_match)) {
if(!preg_match("#\{{2}\s*([^\|]+)(?:\|(.*?))?\}{2}$#si", $raw_template_syntax, $skip_match)) {
continue;
}
$skip_match[1] = strtolower(trim($skip_match[1], " |"));
// show it if we don't manually process it
if(in_array($skip_match[1], $skipped_templates)) {
continue;
}
if(!empty($this->options['ignore_template_matches'])) {
foreach($this->options['ignore_template_matches'] as $ignore_template_match_regex) {
if(preg_match($ignore_template_match_regex, $skip_match[1])) {
continue 2;
}
}
}
//print "raw_template_syntax = <pre>". preg_replace("#\{{2}\s*([^\|\}\:]+)(\|)?#si", "{{<a href=\"http://en.wikipedia.org/wiki/Template:\\1\">\\1</a>\\2", $raw_template_syntax, 1) ."</pre>\n\n";
continue;
}
$infobox_values = array();
// pull actual data out
if(!preg_match("#^\{{2}\s*([^\|]+)\|(.*)\s*\}{2}$#si", $raw_template_syntax, $template_type_match)) {
// something went wrong
continue;
}
$infobox_tmp = $this->insert_jungledb_helpers($template_type_match[2]);
// {{url|xxx}} -> [http://[www.]]xxx
$infobox_tmp = preg_replace_callback("#\{{2}\s*url\s*\|\s*([^\}]+?)\s*\}{2}#si", function($match) {
return JungleDB_Utils::prepare_url_string($match[1]);
}, $infobox_tmp);
// get rid of all template calls
$infobox_tmp = preg_replace("/\{{2}((?>[^\{\}]+)|(?R))*\}{2}/x", "", $infobox_tmp);
//$meta_boxes['_debug_after'][] = $infobox_tmp;
$_meta_box_type = $this->compact_to_slug($template_type_match[1]);
//$meta_boxes['_debug_types'][] = $_meta_box_type;
$infobox_tmp = trim($infobox_tmp, " \r\t\n|");
if(in_array($_meta_box_type, array("coord", "coords"))) {
$_infobox_values = preg_split("#\s*\|\s*#s", $infobox_tmp);
if(!empty($_infobox_values)) {
foreach(array_keys($_infobox_values) as $iv_key) {
if(!preg_match("#^\s*(.+)\s*(?:\:|=)\s*(.*)\s*$#si", $_infobox_values[$iv_key], $line_type)) {
continue;
}
if(preg_match("#^\s*([A-Za-z0-9\-\_]+)\s*\:#si", $_infobox_values[$iv_key])) {
unset($_infobox_values[$iv_key]);
continue;
}
$line_type[2] = trim($line_type[2], " =|");
if("" !== $line_type[2]) {
$infobox_values[ $this->compact_to_slug($line_type[1]) ] = $line_type[2];
}
unset($_infobox_values[$iv_key]);
}
// wiki styling, unneeded
if(isset($infobox_values['display'])) {
unset($infobox_values['display']);
}
if(isset($infobox_values['format'])) {
unset($infobox_values['format']);
}
if(isset($infobox_values['notes'])) {
unset($infobox_values['notes']);
}
if(isset($infobox_values['dim'])) {
$infobox_values['diameter'] = $infobox_values['dim'];
unset($infobox_values['dim']);
}
$infobox_values['coords'] = implode("|", $_infobox_values);
$coords = array_map('trim', array_values($_infobox_values)); // reset keys
if(count($coords) == 2) {
// decimal [without |N|W]
// North or South?
$coord = ltrim($coords[0], " -") . (substr($coords[0], 0, 1) == "-"?"S":"N");
$coord .= " ";
$coord .= ltrim($coords[1], " -") . (substr($coords[1], 0, 1) == "-"?"W":"E");
$infobox_values['coord'] = $coord;
unset($coord);
unset($infobox_values['coords']);
} elseif(count($coords) == 4) {
// decimal
$infobox_values['coord'] = $coords[0] . $coords[1] ." ". $coords[2] . $coords[3];
unset($coord);
unset($infobox_values['coords']);
} elseif(count($coords) == 6) {
// degrees
$coord = $coords[0] ."°". $coords[1] ."'". strtoupper($coords[2]);
$coord .= " ";
$coord .= $coords[3] ."°". $coords[4] ."'". strtoupper($coords[5]);
$infobox_values['coord'] = $coord;
unset($coord);
unset($infobox_values['coords']);
} elseif(count($coords) == 8) {
// degrees
$coord = $coords[0] ."°". $coords[1] ."'". $coords[2] ."\"". strtoupper($coords[3]);
$coord .= " ";
$coord .= $coords[4] ."°". $coords[5] ."'". $coords[6] ."\"". strtoupper($coords[7]);
$infobox_values['coord'] = $coord;
unset($coord);
unset($infobox_values['coords']);
}
unset($coords);
}
} elseif("historical_populations" === $_meta_box_type) {
$infobox_values['dates'] = array();
$_infobox_values = preg_split("#\s*\|\s*#s", trim($infobox_tmp, " \n\t\r|"));
$dated = false;
foreach($_infobox_values as $_infobox_value) {
if(preg_match("#^\s*([A-Za-z]+)\s*=\s*(.+?)\s*$#si", $_infobox_value, $tmp__match)) {
$slug = $this->compact_to_slug($tmp__match[1]);
if(in_array($slug, array("align"))) {
continue;
}
$infobox_values[ $slug ] = $this->clean_wiki_text( trim($tmp__match[2]) );
continue;
}