/
WikimediaPage.php
1298 lines (1185 loc) · 57.2 KB
/
WikimediaPage.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
class WikimediaPage
{
public $xml;
private $simple_xml;
private $data_object_parameters;
private $galleries = array();
/* see http://www.mediawiki.org/wiki/Manual:MIME_type_detection
http://dublincore.org/documents/dcmi-type-vocabulary/#H7
http://dublincore.org/usage/meetings/2004/03/Relator-codes.html */
private static $default_role = 'creator';
private static $mediatypes = array(
'BITMAP' => array('dcmitype'=>'http://purl.org/dc/dcmitype/StillImage', 'role'=>'photographer'),
'DRAWING' => array('dcmitype'=>'http://purl.org/dc/dcmitype/StillImage', 'role'=>'illustrator'),
'AUDIO' => array('dcmitype'=>'http://purl.org/dc/dcmitype/Sound', 'role'=>'recorder'),
'VIDEO' => array('dcmitype'=>'http://purl.org/dc/dcmitype/MovingImage','role'=>'creator'),
// 'MULTIMEDIA' => '',
'TEXT' => array('dcmitype'=>'http://purl.org/dc/dcmitype/Text', 'role'=>'author'));
// see http://commons.wikimedia.org/wiki/Help:Namespaces for relevant numbers
public static $NS = array('Gallery' => 0, 'Media' => 6, 'Template' => 10, 'Category' => 14);
private static $GALLERIES_UNRELATED_TO_TAXON = array('Related species');
// For details see http://commons.wikimedia.org/w/api.php
public static $API_URL = 'http://commons.wikimedia.org/w/api.php';
public static $max_titles_per_lookup = 50;
public static $max_categories_per_lookup = 500;
// Maximum URL length ~ 8100 chars (https://www.mediawiki.org/wiki/API:FAQ#do_really_long_API_urls_not_work)
public static $max_http_chars = 8100;
// For allowed length of titles string, allow an extra 300 chars for ?action=query&..blah.blah.<TITLES>.continue=blah,blah
// declare this as a function because static variables can't be initialized using e.g. strlen()
public static function max_encoded_characters_in_titles() {return self::$max_http_chars - strlen(self::$API_URL) - 300;}
function __construct($xml)
{
$this->xml = $xml;
$this->simple_xml = @simplexml_load_string($this->xml);
// Oddly, wikimedia dumps occasionally have random newlines within tags.
if(!is_object($this->simple_xml))
{
// Hence simplexml_load_string() sometimes fails (this is rare, though).
echo "ERROR, malformed xml";
if(preg_match("/<title>([^<]+)/u", $this->xml, $arr)) echo " for page titled <".$arr[1].">\n";
else echo ":\n".$this->xml."\n";
$this->text = $this->title = $this->ns = $this->contributor = $this->timestamp = "";
}else
{
if(preg_match("/^<\?xml version=\"1\.0\"\?><api><query>/", $xml))
{
$this->text = (string) $this->simple_xml->query->pages->page->revisions->rev;
$this->title = (string) $this->simple_xml->query->pages->page['title'];
$this->ns = (integer) $this->simple_xml->query->pages->page['ns'];
$this->contributor = (string) $this->simple_xml->query->pages->page->revisions->rev['user'];
$this->timestamp = (string) $this->simple_xml->query->pages->page->revisions->rev['timestamp'];
if(isset($this->simple_xml->query->pages->page['redirect']))
{
$this->redirect = (string) $this->simple_xml->query->pages->page['redirect']->attributes()->title;
}
}elseif($this->simple_xml)
{
$this->text = (string) $this->simple_xml->revision->text;
$this->title = (string) $this->simple_xml->title;
$this->ns = (integer) $this->simple_xml->ns;
$this->contributor = (string) $this->simple_xml->revision->contributor->username;
$this->timestamp = (string) $this->simple_xml->revision->timestamp;
if(isset($this->simple_xml->redirect))
{
$this->redirect = (string) $this->simple_xml->redirect->attributes()->title;
}
} else
{
$this->text = $this->title = $this->ns = $this->contributor = $this->timestamp = "";
}
}
}
public static function from_api($title)
{
$api_url = self::$API_URL.'?action=query&format=xml&prop=revisions&titles='. urlencode($title) .'&rvprop=ids|timestamp|user|content&redirects';
echo $api_url."\n";
return new WikimediaPage(php_active_record\Functions::get_remote_file($api_url));
}
// Fast versions - these do not require a parsed page
public static function fast_is_gallery($xml)
{
return (substr($xml, strpos($xml, "<ns>")+4, 2) == '0<');
}
public static function fast_is_media($xml)
{
return (substr($xml, strpos($xml, "<ns>")+4, 2) == '6<');
}
public static function fast_is_template($xml)
{
return (substr($xml, strpos($xml, "<ns>")+4, 3) == '10<');
}
public static function fast_is_category($xml)
{
return (substr($xml, strpos($xml, "<ns>")+4, 3) == '14<');
}
public static function fast_is_gallery_category_or_template($xml)
{
$test = substr($xml, strpos($xml, "<ns>")+4, 3);
return ($test == '0</' || $test == '14<' || $test == '10<');
}
public static function fast_is_gallery_category_or_media($xml)
{
$test = substr($xml, strpos($xml, "<ns>")+4, 3);
return ($test == '6</' || $test == '14<' || $test == '0</');
}
// these are less dependent on the exact XML string, but require a page to have been parsed, so are slower
public function is_gallery()
{
return ($this->ns == self::$NS['Gallery']);
}
public function is_media()
{
return ($this->ns == self::$NS['Media']);
}
public function is_category()
{
return ($this->ns == self::$NS['Category']);
}
public function is_template()
{
return ($this->ns == self::$NS['Template']);
}
public static function expand_templates($text)
{
$url = self::$API_URL.'?action=expandtemplates&format=xml&text='. urlencode($text);
$response = \php_active_record\Functions::lookup_with_cache($url, array('validation_regex' => '<text', 'expire_seconds' => 518400));
$hash = simplexml_load_string($response);
if(@$hash->expandtemplates) return (string) $hash->expandtemplates[0];
}
public function expanded_text()
{
if(isset($this->expanded_text)) return $this->expanded_text;
$url = self::$API_URL.'?action=parse&format=xml&prop=text&redirects&page='. urlencode($this->title);
$response = \php_active_record\Functions::lookup_with_cache($url, array('validation_regex' => '<text', 'expire_seconds' => 518400));
$hash = simplexml_load_string($response);
if(@$hash->parse->text) $this->expanded_text = (string) $hash->parse->text[0];
return $this->expanded_text;
}
public function active_wikitext()
{
// the text we should search for when looking for templates, categories, etc.
if(isset($this->active_wikitext)) return $this->active_wikitext;
$this->active_wikitext = WikiParser::active_wikitext($this->text);
return $this->active_wikitext;
}
public function information()
{
if(isset($this->information)) return $this->information;
foreach(array("[Ii]nformation", "[Ss]pecimen", "[Ff]lickr") as $template_name)
{
$this->information = WikiParser::template_as_array($this->active_wikitext(), $template_name);
if(!empty($this->information)) break;
}
// remove the template name
array_shift($this->information);
// Some templates, e.g. http://commons.wikimedia.org/wiki/Template:Flickr have "photographer" not (as we normally expect) "author"
if (!(array_key_exists('author', $this->information) || array_key_exists('Author', $this->information)) && array_key_exists('photographer', $this->information))
$this->information['author'] = $this->information['photographer'];
return $this->information;
}
private function fill_includes_recursively(&$arr, $include_arrays, &$visited = array())
{
if(!empty($arr['taxo']['Include']))
{
$include = "Template:".(WikiParser::make_valid_pagetitle($arr['taxo']['Include']));
if(!isset($visited[$include])) // stops infinite recursive loops
{
$visited[$include] = true;
if(isset($include_arrays[$include]))
{
$this->fill_includes_recursively($include_arrays[$include], $include_arrays, $visited);
$arr['taxo'] = array_merge($include_arrays[$include]['taxo'], $arr['taxo']);
$arr['last_mod'] = max($include_arrays[$include]['last_mod'], $arr['last_mod']);
}else
{
echo "Found non-existent Taxonav include value: '$include' within ".implode(":",$arr['taxo'])." in page $this->title\n";
flush();
}
unset($arr['taxo']['Include']);
}
}
return $arr;
}
public function taxonomy_via_API()
{
// can't use actual parsed text to detect last changed time
$taxonomy = new TaxonomyParameters($this->timestamp, null);
$mesg = "";
if(preg_match("/^<div style=\"float:left; margin:2px auto; border-top:1px solid #ccc; border-bottom:1px solid #aaa; font-size:97%\">(.*?)<\/div>\n/ms", $this->expanded_text(), $arr))
{
$taxonomy_box = $arr[1];
$authority = "";
if(preg_match("/^<div.*?>(.*)/", $taxonomy_box, $arr)) $taxonomy_box = $arr[1];
if(preg_match("/^'''.*?''': (.*)/", $taxonomy_box, $arr)) $taxonomy_box = $arr[1];
$parts = preg_split("/<\/b> ? • ?/", WikiParser::mb_trim($taxonomy_box));
while($part = array_pop($parts))
{
if(preg_match("/^(<b>)?([a-z]+)(<b>)?: (.*)$/ims", $part, $arr))
{
$taxonomy->add_wiki_info($arr[2], $arr[4]);
}
}
}
$mesg .= $this->fill_taxon_info_from_outside_Taxonavigation($taxonomy);
if(!empty($mesg)) echo "<http://commons.wikimedia.org/wiki/".$this->title."> ".$mesg."\n";
return $taxonomy;
}
private function taxonomy_via_wikitext(&$taxonav_include_arrays)
{
$Taxonav = array('taxo' => $this->taxonav_as_array("[Tt]axonavigation"), 'last_mod' => @strtotime($this->timestamp));
$Taxonav = $this->fill_includes_recursively($Taxonav, $taxonav_include_arrays);
$taxonomy = new TaxonomyParameters($this->timestamp, $Taxonav['last_mod']);
$mesg = "";
foreach($Taxonav['taxo'] as $wiki_rank => $name)
{
$mesg .= $taxonomy->add_wiki_info($wiki_rank, $name);
}
$mesg .= $this->fill_taxon_info_from_outside_Taxonavigation($taxonomy);
if(!empty($mesg)) echo "<".$this->title."> ".$mesg."\n";
return $taxonomy;
}
private function fill_taxon_info_from_outside_Taxonavigation(&$taxonomy)
{
$mesg = "";
// there are often some extra ranks under the Taxonnavigation box -
if(preg_match("/\}\}\s*\n(\s*----\s*\n)?((\*?(genus|species):.*?\n)*)/muis", $this->active_wikitext(), $arr))
{
$entries = explode("\n", $arr[2]);
// make sure species is checked last (to use linked authority)
foreach(array('genus','species') as $rank)
{
foreach($entries as $entry)
{
if(is_null($taxonomy->get($rank)) && preg_match("/^\*?$rank:(.*)/muis", WikiParser::mb_trim($entry), $arr))
{
// usually the name is in italics, followed by the authority
// e.g. http://commons.wikimedia.org/wiki/Shorea_roxburghii
// mark the difference by placing a newline between the two
$fullname = preg_replace("/<\/i>/", "$0\n", WikiParser::strip_syntax($arr[1], true), 1);
$fullname = explode("\n", $fullname);
$mesg .= $taxonomy->add_info($rank, strip_tags($fullname[0]));
if(is_null($taxonomy->get($rank)))
{
$mesg .= "Info gleaned from outside Taxonavigation box: $rank set to '".$taxonomy->get($rank)."'";
if(isset($fullname[1]))
{
// if we end up using this species or genus data, we should use associated authority
if(empty($taxonomy->authority)) $mesg .= " & authority set to"; else $mesg .= " & authority replaced by";
$taxonomy->add_info('authority', strip_tags($fullname[1]));
$mesg .=" '".$taxonomy->authority."'";
}
$mesg .= ". ";
}
}
}
}
}
return $mesg;
}
public function taxonomy(&$taxonav_include_arrays = null)
{
if(!isset($this->taxonomy))
{
if(empty($taxonav_include_arrays)) $this->taxonomy = $this->taxonomy_via_API();
else $this->taxonomy = $this->taxonomy_via_wikitext($taxonav_include_arrays);
}
return $this->taxonomy;
}
private static function license_types()
{
// The licenses should be listed in order of preference
static $license_types = array(
'public domain',
'http://creativecommons.org/publicdomain/zero/',
'http://www.flickr.com/commons/usage/',
'http://creativecommons.org/licenses/by/',
'http://creativecommons.org/licenses/by-nc/',
'http://creativecommons.org/licenses/by-sa/',
'http://creativecommons.org/licenses/by-nc-sa/');
return $license_types;
}
private static function sort_identified_licenses($a, $b)
{
$license_types = self::license_types();
$a_index = array_search($a['category'], $license_types);
$b_index = array_search($b['category'], $license_types);
if($a_index == $b_index)
{
if($a['version'] == $b['version']) return 0;
// larger version first
return (floatval($a['version']) > floatval($b['version'])) ? -1 : 1;
}
// smaller index first
return ($a_index < $b_index) ? -1 : 1;
}
public function best_license($potential_licenses, $is_wikitext = true)
{
// Can be used to identify either licenses in templates {{cc-by-1.0}} or categories [[CC-BY-1.0]]
// usually these are of the same format, apart from e.g. {{XXX-no known copyright restrictions}}
// Currently we miss files categorised under the FAL (http://en.wikipedia.org/wiki/Free_Art_License)
// which may in future be compatible with CC-BY (see http://wiki.creativecommons.org/Version_4#Compatibility)
// Also for images like https://commons.wikimedia.org/wiki/File:Aequorea1.jpeg which only require
// attribution only, we could consider redistributing as CC-BY, but some legal opinion is probably needed
// (see https://commons.wikimedia.org/wiki/Template_talk:Attribution#Compatibility_with_CC-BY)
$identified_licenses = array();
foreach($potential_licenses as $potential_license)
{
// catch e.g. PD-USGov-CIA-WF, etc and Copyrighted_free_use (but *not* "Copyrighted free use provided that")
if(preg_match("/^(PD|Public[ _]domain.*|CC-PD|usaid|nih|noaa|CopyrightedFreeUse|Copyrighted[ _]Free[ _]Use(?![ _]provided[ _]that))($| |-)/mui", $potential_license))
{
$identified_licenses[] = array(
'license' => 'public domain',
'category' => 'public domain',
'version' => null);
}
// cc-zero
if(preg_match("/^CC-Zero/mui", $potential_license))
{
$identified_licenses[] = array(
'license' => 'http://creativecommons.org/publicdomain/zero/1.0/',
'category' => 'http://creativecommons.org/publicdomain/zero/',
'version' => '1.0');
}
// no known copyright restrictions
// (listed under http://commons.wikimedia.org/wiki/Category:No_known_restrictions_license_tags)
if((($is_wikitext) && preg_match("/^(flickr-)?no known copyright restrictions/mui", $potential_license)) ||
((!$is_wikitext) && preg_match("/^Files from Flickr's 'The Commons'/mui", $potential_license)))
{
$identified_licenses[] = array(
'license' => 'http://www.flickr.com/commons/usage/',
'category' => 'http://www.flickr.com/commons/usage/',
'version' => null);
}
// {{gfdl|migration=relicense}} can be relicensed as cc-by-sa-3.0 (when categories, CC-BY-SA-3.0 is automatically set)
if($is_wikitext && preg_match("/migration=relicense/mui", $potential_license))
{
$identified_licenses[] = array(
'license' => 'http://creativecommons.org/licenses/by-sa/3.0/',
'category' => 'http://creativecommons.org/licenses/by-sa/',
'version' => '3.0');
}
// cc-sa-1.0
if(preg_match("/^(CC-SA)(.*)$/mui", $potential_license, $arr))
{
$license = "by-sa";
$rest = $arr[2];
if(preg_match("/^-?([0-9]\.[0-9])/u", $rest, $arr)) $version = $arr[1];
else $version = "3.0";
$identified_licenses[] = array(
'license' => "http://creativecommons.org/licenses/$license/$version/",
'category' => "http://creativecommons.org/licenses/$license/",
'version' => $version);
}
// catch all the cc-licenses
if(preg_match("/^CC-(BY(?:-NC)?(?:-ND)?(?:-SA)?)(.*)$/mui", $potential_license, $arr))
{
$license = strtolower($arr[1]);
$rest = $arr[2];
if(preg_match("/^-?([0-9]\.[0-9])/u", $rest, $arr)) $version = $arr[1];
else $version = "3.0";
if($license === 'by-nc-nd') continue;
$identified_licenses[] = array(
'license' => "http://creativecommons.org/licenses/$license/$version/",
'category' => "http://creativecommons.org/licenses/$license/",
'version' => $version);
}
}
if(!$identified_licenses) return null;
usort($identified_licenses, array('\WikimediaPage', 'sort_identified_licenses'));
return $identified_licenses[0]['license'];
}
public function get_data_object_parameters()
{
return $this->data_object_parameters;
}
public function initialize_data_object($url, $mimetype, $dcmi, $role)
{
$this->data_object_parameters["title"] = $this->title;
$this->data_object_parameters["identifier"] = str_replace(" ", "_", $this->title);
// unfortunately we have to alter the identifier to make strings with different cases look different
// so I'm just adding up the ascii values of the strings and appending that to the identifier
$this->data_object_parameters["identifier"] .= "_" . array_sum(array_map('ord', str_split($this->data_object_parameters["identifier"])));
$this->data_object_parameters["source"] = "http://commons.wikimedia.org/wiki/".str_replace(" ", "_", $this->title);
$this->data_object_parameters["language"] = 'en';
if($this->description() && !php_active_record\Functions::is_utf8($this->description()))
{
$this->data_object_parameters["description"] = "";
}else $this->data_object_parameters["description"] = $this->description();
if($this->point())
{
$this->data_object_parameters["point"] = new \SchemaPoint($this->point());
}
if($this->location())
{
$this->data_object_parameters["location"] = $this->location();
}
$this->data_object_parameters['mediaURL'] = $url;
$this->data_object_parameters['dataType'] = $dcmi;
$this->set_mimeType(php_active_record\Functions::get_mimetype($this->title));
if (!empty($mimetype)) $this->set_mimeType($mimetype);
$this->data_object_parameters["agents"] = array();
if ($a = $this->agent_parameters($role))
{
if(php_active_record\Functions::is_utf8($a['fullName'])) $this->data_object_parameters["agents"][] = new SchemaAgent($a);
}
// the following properties may be overridden later by category data from the API.
$this->licenses = $this->licenses_via_wikitext();
$this->set_license($this->best_license($this->licenses));
}
public function reset_role_to_default()
{
//use this for edge cases where the normal "role" title for this media type is inappropriate
if (count($this->data_object_parameters["agents"]))
{
$this->data_object_parameters["agents"][0]->role = self::$default_role;
}
}
public function has_license()
{
if(empty($this->data_object_parameters['license'])) return false;
else return true;
}
public function has_valid_mime_type($valid_mime_types)
{
if(empty($this->data_object_parameters['mimeType'])) return false;
if(!in_array($this->data_object_parameters['mimeType'], $valid_mime_types)) return false;
return true;
}
public function reassess_licenses_with_additions($potential_license_categories)
{
if(!$potential_license_categories) return;
$this->licenses = array_merge($this->licenses, $potential_license_categories);
if($license = $this->best_license($this->licenses, false))
{
$this->set_license($license);
}
}
public function set_license($license)
{
if(isset($this->data_object_parameters['license']) && ($this->data_object_parameters['license'] != $license))
{
echo "Overriding license for $this->title : current = ". $this->data_object_parameters['license'] .", new = $license\n";
}
$this->data_object_parameters['license'] = $license;
}
public function set_mimeType($mimeType)
{
if(isset($this->data_object_parameters['mimeType']) && ($this->data_object_parameters['mimeType'] != $mimeType))
{
echo "Overriding mimeType for $this->title : current = ". $this->data_object_parameters['mimeType'] .", new = $mimeType\n";
}
$this->data_object_parameters['mimeType'] = $mimeType;
}
public function set_additionalInformation($text)
{
if(isset($this->data_object_parameters['additionalInformation']))
{
$this->data_object_parameters['additionalInformation'] .= $text;
}else $this->data_object_parameters['additionalInformation'] = $text;
}
public function get_categories($added_categories_only = false)
{
if(!property_exists($this,'categories_from_wikitext'))
{
$this->categories_from_wikitext = array();
if(preg_match_all('/\[\[\s*[Cc]ategory:\s*(.*?)\s*(?:\]\]|\|)/uS', $this->active_wikitext(), $matches))
{
$this->categories_from_wikitext = $matches[1];
}
}
if(!property_exists($this,'added_categories')) $this->added_categories = array();
if($added_categories_only) return($this->added_categories);
else return($this->categories_from_wikitext + $this->added_categories);
}
public function add_extra_category($category)
{
$this->added_categories[] = $category;
}
public function add_galleries($array_of_galleries)
{
$this->galleries = array_merge($this->galleries, $array_of_galleries);
}
public function get_galleries()
{
// NB not all media pages will be associated with a gallery
if(isset($this->galleries)) return $this->galleries;
else return null;
}
public function agent_parameters($role="")
{
if(isset($this->agent_parameters)) return $this->agent_parameters;
$author = $this->author();
//some complicated regexps for sanitizing author information
$homepage = "";
$email = "";
if(preg_match("/<a href='mailto:(.+?)'>/u", $author, $arr)) $email = $arr[1];
if(preg_match("/<a href='(http.+?)'>/u", $author, $arr)) $homepage = $arr[1];
//only allow wiki users, disallow arbitrary URLs (presumably to avoid linking to malicious sites)
if(!preg_match("/\/wiki\/(user|:[a-z]{2})/ui", $homepage) || preg_match("/;/u", $homepage)) $homepage = "";
$author = preg_replace("/<br\W*>/iu", "\n", $author);
//insert a space between a word char or appropriate punctuation "." "," ")" and a following html tag
$author = preg_replace("/(?<=[\w\.\),])<(?!\s*\/)/u", " <", $author);
$author = strip_tags($author);
//replace bullet points (* ) or indents (:) with simple newlines
$author = preg_replace("/^\s*(:+|\*+)/mu", "\n", $author);
//trim newlines at start & end
$author = preg_replace("/^\n+/u", "", $author);
$author = preg_replace("/\n+$/u", "", $author);
//Newlines to sentences. 1) Colons at end-of-line are not new sentences, UNLESS followed by a line with a colon
//see e.g. http://commons.wikimedia.org/wiki/File:Schistosoma_bladder_histopathology.jpeg
$author = preg_replace("/:\n+([^\n]+)(?=:)/u", ". $1", $author);
// 2) Make sentence from newline (unless the line ends in punctuation already)
$author = preg_replace("/(?<![\.,:;])\s*\n+/u", ". ", $author);
//contract multiple spaces
$author = preg_replace("/\s+/u", " ", $author);
//some unneeded text which is commonly found in Author attributions,
//e.g. File:Black_Ruby_Barb_700.jpg, File:Aspidistra_elatior_Amomokawo_BotGardBln1205.jpg, File:Lumbar_plant_acerleaf_sick.jpg
$author = preg_replace("/\(talk\)/ui", "", $author);
$author = preg_replace("/^(photo(graph)? |image |picture )?(taken )?by(:| and)?/ui", "", $author);
//swap copyright text for ©
$author = preg_replace("/^\bcopyright\b/ui", "©", $author);
$author = preg_replace("/\(c\)/ui", "©", $author);
//remove copyright sign & potential date (plus comma)
$author = preg_replace("/©( *)(\d\d\d\d *,?)?(by)?/", "", $author);
//replace e.g. é with unicode é
$author = WikiParser::mb_trim(html_entity_decode($author));
$agent_parameters = array();
if($author)
{
$agent_parameters["fullName"] = $author;
if(strlen($homepage) && php_active_record\Functions::is_ascii($homepage) && !preg_match("/[\[\]\(\)'\",;\^]/u", $homepage)) $agent_parameters["homepage"] = str_replace(" ", "_", $homepage);
if(strlen($email) && php_active_record\Functions::is_ascii($email)) $agent_parameters["email"] = $email;
if ($role)
{
$agent_parameters["role"] = $role;
} else {
$agent_parameters["role"] = self::$default_role;
}
}
$this->agent_parameters = $agent_parameters;
return $agent_parameters;
}
// this just looks through the plain wikitext for things like {{GFDL}}
public function licenses_via_wikitext()
{
if(isset($this->licenses_via_wikitext)) return $this->licenses_via_wikitext;
$licenses = array();
if(preg_match_all("/(\{\{.*?\}\})/u", $this->active_wikitext(), $matches, PREG_SET_ORDER))
{
foreach($matches as $match)
{
while(preg_match("/(\{|\|)(cc-.*?|pd|pd-.*?|gfdl|gfdl-.*?|noaa|usaid|nih|copyrighted free use|CopyrightedFreeUse|creative commons.*?|migration=.*?|flickr-no known copyright.*?|no known copyright.*?)(\}|\|)(.*)/umsi", $match[1], $arr))
{
$licenses[] = WikiParser::mb_trim($arr[2]);
$match[1] = $arr[3].$arr[4];
}
}
}
if(!$licenses && preg_match("/permission\s*=\s*(cc-.*?|gpl.*?|public domain.*?|creative commons .*?)(\}|\|)/umsi", $this->text, $arr))
{
$licenses[] = WikiParser::mb_trim($arr[1]);
}
$this->licenses_via_wikitext = $licenses;
return $licenses;
}
public function author()
{
if(isset($this->author)) return $this->author;
$author = "";
if($info = $this->information())
{
foreach($info as $attr => $val)
{
if($attr === "author" || $attr === "Author") $author = WikiParser::strip_syntax($val, true);
}
}
$this->author = $author;
return $author;
}
public function rights()
{
if(isset($this->rights)) return $this->rights;
$rights = "";
if($info = $this->information())
{
foreach($info as $attr => $val)
{
if($attr === "permission" || $attr === "Permission") $rights = WikiParser::strip_syntax($val, true);
}
}
$this->rights = $rights;
return $rights;
}
public function description()
{
if(isset($this->description)) return $this->description;
$description = "";
if($info = $this->information())
{
foreach($info as $attr => $val)
{
if($attr === "description" || $attr === "Description")
{
$description = WikiParser::strip_syntax($val, true);
}
}
}
$this->description = $description;
return $description;
}
public function point()
{
if(isset($this->georef)) return $this->georef;
$this->georef = false;
$this->location = false;
if(count($location = WikiParser::template_as_array($this->active_wikitext(), "(?:[Oo]bject )?[Ll]ocation(?: dec)?")))
{
if(!isset($location[8]))
{
// see http://commons.wikimedia.org/wiki/Template:Location_dec
if(isset($location[1]) && isset($location[2]) && is_numeric($location[1]) && is_numeric($location[2]))
{
$this->georef["latitude"] = $location[1];
$this->georef["longitude"] = $location[2];
}
if(isset($location[3]))
{
$this->location = $location[3];
}
}else
{
// lazy - assume parameters 1-7 are set too
$this->georef["latitude"] = $location[1] + ((($location[2] * 60) + ($location[3])) / 3600);
if(stripos($location[4], "N") === false) $this->georef["latitude"] *= -1;
$this->georef["longitude"] = $location[5] + ((($location[6] * 60) + ($location[7])) / 3600);
if(stripos($location[8], "W") === true) $this->georef["longitude"] *= -1;
if(isset($location[9]))
{
$this->location = $location[9];
}
}
}
if($this->georef && (! is_numeric($this->georef["latitude"]) || ! is_numeric($this->georef["longitude"]) || ! $this->georef["latitude"] || ! $this->georef["longitude"]))
{
$this->georef = false;
}
return $this->georef;
}
public function location()
{
// Very crude: just bungs the 9th parameter giving GeoHack server metadata into "location": coded region, heading, scale, etc.
if(isset($this->location)) return $this->location;
$this->point();
return $this->location;
}
public function media_on_page()
{
$media = array();
$text = $this->active_wikitext();
$text = $this->remove_unrelated_species_text($text);
$lines = explode("\n", $text);
foreach($lines as $line)
{
/* < > [ ] | { } not allowed in titles, so if we see this, it is end of filename (spots e.g. Image:xxx.jpg</gallery>)
see http://en.wikipedia.org/wiki/Wikipedia:Naming_conventions_(technical_restrictions)#Forbidden_characters
This is a horribly long regexp because "spaces" in the string may be "unicode spaces" or control characters
- matched by [\pZ\pC]. */
if(preg_match("/^[\pZ\pC]*\[{0,2}[\pZ\pC]*(Image|File)[\pZ\pC]*:(.*?)([|#<>{}[\]]|$)/iums", $line, $arr))
{
$media[] = WikiParser::make_valid_pagetitle(rawurldecode($arr[2]));
}
}
return $media;
}
public function remove_unrelated_species_text($text)
{
// This will remove galleries of images for 'related' but not the same taxon.
// See #DATA-749, http://commons.wikimedia.org/wiki/Boletus
if(preg_match("/(==(". implode("|", self::$GALLERIES_UNRELATED_TO_TAXON) .")==\s*<gallery>.*?<\/gallery>)/iums", $text, $arr))
{
$text = str_replace($arr[1], '', $text);
}
return $text;
}
public function contains_template($template)
{
return preg_match("/\{\{".$template."\s*[\|\}]/u", $this->active_wikitext());
}
public function transcluded_categories()
{
//look for transclusions like {{:Category:Homo sapiens}} or {{Category:Homo sapiens}}
if(preg_match_all("/\{\{:?Category:([^\}]+)\s*\}\}/u", $this->active_wikitext(), $arr))
{
return array_map(function($cat) { return "Category:".\WikiParser::make_valid_pagetitle($cat);}, $arr[1]);
} else
{
return array();
}
}
public function taxonav_as_array($template_name, $strip_syntax = true)
{
// A special format for Taxonavigations, where e.g. param[1] is "Cladus" and param[2] is "magnoliids"
// Place param[1] as the key, and param[2] as the value of the returned array, so that e.g.
// Taxonavigation|Cladus|magnoliids|Ordo|Laurales becomes [0=>Taxonavigation, Cladus=>magnoliids, Ordo=>Laurales]
// Take care when using, as $template_name is allowed to be a RegExp.
$plain_array = WikiParser::template_as_array($this->active_wikitext(), $template_name);
$tnav_array = array();
foreach($plain_array as $param => $value)
{
$value = WikiParser::mb_trim($value);
// numerical array elements get reassigned.
if(is_int($param))
{
// $param = 1,3,5
if($param % 2)
{
if($value != "")
{
if(isset($plain_array[$param+1]))
{
if($strip_syntax)
{
$tnav_array[WikiParser::mb_ucfirst($value)] = WikiParser::strip_syntax($plain_array[$param+1]);
}else
{
$tnav_array[WikiParser::mb_ucfirst($value)] = $plain_array[$param+1];
}
}else
{
echo "Note: there don't seem to be the right number of parameters in $template_name within http://commons.wikimedia.org/wiki/$this->title\n";
}
}
}
}else
{
$tnav_array[WikiParser::mb_ucfirst($param)] = $value;
}
}
return $tnav_array;
}
public static function call_API(&$url, $titles)
{
if(!$titles) return array();
// return an array with $title => json_result
$real_titles = array_combine($titles, $titles);
$results = array();
//use curl_version and phpversion to give a polite user-agent to Commons, see http://meta.wikimedia.org/wiki/User-Agent_policy
$curl_info = curl_version();
$curl_options = array(
'user_agent' => 'EoLWikimediaHarvestingBot/1.0 (http://EoL.org; https://github.com/EOL; tech@eol.org) PHP_'.phpversion().'-libcurl/'.$curl_info['version'],
'download_wait_time' => 5000000,
'download_attempts' => 3,
'encoding' => 'gzip,deflate',
'validation_regex' => 'query',
'expire_seconds' => 518400);
if(count($titles) > self::$max_titles_per_lookup)
{
echo "ERROR: only allowed a maximum of ". self::$max_titles_per_lookup ." titles in a single API query.\n";
return $results;
}elseif(count($titles) == 0) return;
$url .= "&titles=". urlencode(implode("|", $titles));
$continue = "&continue=";
while(!empty($continue))
{
$result = php_active_record\Functions::lookup_with_cache($url.$continue, $curl_options);
// return as an associative array
$json = json_decode($result, true);
$query = $json['query'];
if(isset($query['normalized']))
{
foreach($query['normalized'] as $norm)
{
$from = (string) $norm['from'];
$to = (string) $norm['to'];
echo "Possible error: page title '$from' should really be '$to'. This may cause problems later.\n";
$real_titles[$to] = $from;
}
}
if(isset($query['redirects']))
{
// All redirected pages should have been caught in the XML dump.
// Here we should only have pages which have changed since the dump was produced.
foreach($query['redirects'] as $redir)
{
$from = (string) $redir['from'];
$to = (string) $redir['to'];
echo "Page $from has been redirected to $to, but doesn't seem to be redirected in the XML dump";
echo "(has it changed since the dump?). Using Wikitext from old version, but url, categories, etc. from new.\n";
$real_titles[$to] = $from;
}
}
if(!isset($query['pages']))
{
echo "\nERROR: couldn't get JSON API query from $url\n";
} else
{
foreach($query['pages'] as $page)
{
if(empty($page['title']))
{
if(isset($page['pageid']))
{
echo "ERROR: empty title when querying API - pageId =".((string) $page['pageid'])."($url)\n";
}else
{
/* odd "feature" of mediawiki API: when you get a redirect, not only does it return info on the
new page to which the redirect points, but also an empty page ( JSON = {"imagerepository":""} )
corresponding to the original, old page. We can safely ignore these empty results */
}
continue;
}
$title = (string) $page['title'];
if(!isset($real_titles[$title]))
{
echo "ERROR: couldn't find <$title> when querying API ($url)\n";
continue;
}
// see http://www.mediawiki.org/wiki/API:Query#Missing_and_invalid_titles
if(array_key_exists("missing",$page))
{
echo "The file <$title> is missing from Commons. Perhaps it has been deleted? Leaving it out.\n";
continue;
}
// see http://www.mediawiki.org/wiki/API:Query#Missing_and_invalid_titles
if(array_key_exists("invalid",$page))
{
echo "The name <$title> is invalid. Leaving it out.\n";
continue;
}
// we've already done one pass
if(isset($results[$real_titles[$title]]))
{
$results[$real_titles[$title]] = array_merge_recursive($results[$real_titles[$title]], $page);
}else $results[$real_titles[$title]] = $page;
}
}
if(isset($json['continue']))
{
$continue = "&". http_build_query($json['continue'], "", "&");
}else $continue = "";
}
return $results;
}
public static function process_pages_using_API(&$array_of_pages)
{
// Work on an array of pages, querying the Mediawiki API about them.
// If the page is missing or invalid (e.g. has been deleted), then remove it from the array.
$url = self::$API_URL.'?action=query&format=json&prop=imageinfo%7Ccategories&iiprop=url%7Cmime%7Cmediatype&cllimit='. self::$max_categories_per_lookup .'&redirects';
$titles = array_map(function($page) { return $page->title; }, $array_of_pages);
$json_array = self::call_API($url, $titles);
foreach($array_of_pages as $index => &$page)
{
if(!isset($json_array[$page->title]))
{
unset($array_of_pages[$index]);
}else
{
$json_info = $json_array[$page->title];
$page->initialize_data_object_from_api_response($json_info, $url);
$page->initialize_categories_from_api_response($json_info, $url);
}
}
}
private function initialize_data_object_from_api_response($json_info, $reference_url)
{
// set URL, mimetype, mediatype
$url = @$json_info['imageinfo'][0]['url'];
$mimetype = @$json_info['imageinfo'][0]['mime'];
$mediatype = @$json_info['imageinfo'][0]['mediatype'];
$dcmi="";
$role="";
if (empty($url))
{
$url = "";
echo "That's odd. No URL returned in API query for $this->title (from $reference_url)\n";
};
if (empty($mimetype))
{
echo "That's odd. No mimetype returned in API query for $this->title (from $reference_url)\n";
};
if (empty($mediatype))
{
echo "That's odd. No mediatype returned in API query for $this->title (from $reference_url)\n";
} elseif (!isset(self::$mediatypes[$mediatype]))
{
echo "Non-compatible mediatype: $mediatype for $this->title (from $reference_url)\n";
} else {
$dcmi = self::$mediatypes[$mediatype]['dcmitype'];
$role = self::$mediatypes[$mediatype]['role'];
}
if($dcmi) $this->initialize_data_object($url, $mimetype, $dcmi, $role);
else echo "\nWill not create object. \n url=[$url], \n mimetype=[$mimetype], \n dcmi=[$dcmi], role=[$role]\n";
}
private function initialize_categories_from_api_response($json_info, $reference_url)
{
// fill in categories - this will allow us to check taxonomy, license, & map-type later
if(isset($json_info['categories']))
{
foreach($json_info['categories'] as $cat)
{
if(strpos($cat['title'], "Category:") === 0)
{
$this->add_extra_category(substr($cat['title'], 9));
}else
{
$this->add_extra_category($cat['title']);
echo "That's odd. The category ". $cat['title'] ." doesn't start with 'Category:' in API query for $this->title (from $reference_url).\n";
}
}
}else