-
Notifications
You must be signed in to change notification settings - Fork 1
/
expandFns.php
1446 lines (1350 loc) · 60.8 KB
/
expandFns.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
<?
// $Id: expandFns.php 432 2013-06-10 09:16:30Z MartinS $
session_start();
ini_set("user_agent", "Citation_bot; [email protected]");
function includeIfNew($file) {
// include missing files
$alreadyIn = get_included_files();
foreach ($alreadyIn as $include) {
if (strstr($include, $file))
return false;
}
if ($GLOBALS["linkto2"])
echo "\n// including $file";
require_once($file . $GLOBALS["linkto2"] . ".php");
return true;
}
function expandFnsRevId() {
return substr('$Id: expandFns.php 432 2013-06-10 09:16:30Z MartinS $', 19, 3);
}
function quiet_echo($text) {
global $html_output;
if ($html_output >= 0)
echo $text;
}
require_once("/home/verisimilus/public_html/Bot/DOI_bot/doiBot$linkto2.login");
# Snoopy should be set so the host name is en.wikipedia.org.
includeIfNew('Snoopy.class');
includeIfNew("wikiFunctions");
includeIfNew("DOItools");
require_once("expand.php");
if (!$abort_mysql_connection) {
require_once("/home/verisimilus/public_html/res/mysql_connect.php");
//$db = udbconnect("yarrow");
}
require_once("/home/verisimilus/public_html/crossref.login");
$crossRefId = CROSSREFUSERNAME;
$isbnKey = "268OHQMW";
$bot = new Snoopy();
$alphabet = array("", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
mb_internal_encoding('UTF-8'); // Avoid ??s
define("editinterval", 10);
define("pipePlaceholder", "doi_bot_pipe_placeholder"); #4 when online...
define("comment_placeholder", "### Citation bot : comment placeholder %s ###"); #4 when online...
define("to_en_dash", "-|\—|\xe2\x80\x94|\?\?\?"); // regexp for replacing to ndashes using mb_ereg_replace
define("blank_ref", "<ref name=\"%s\" />");
define("reflist_regexp", "~{{\s*[Rr]eflist\s*(?:\|[^}]+?)+(<ref[\s\S]+)~u");
define("en_dash", "\xe2\x80\x93"); // regexp for replacing to ndashes using mb_ereg_replace
define("wikiroot", "http://en.wikipedia.org/w/index.php?");
define("bibcode_regexp", "~^(?:" . str_replace(".", "\.", implode("|", Array(
"http://(?:\w+.)?adsabs.harvard.edu",
"http://ads.ari.uni-heidelberg.de",
"http://ads.inasan.ru",
"http://ads.mao.kiev.ua",
"http://ads.astro.puc.cl",
"http://ads.on.br",
"http://ads.nao.ac.jp",
"http://ads.bao.ac.cn",
"http://ads.iucaa.ernet.in",
"http://ads.lipi.go.id",
"http://cdsads.u-strasbg.fr",
"http://esoads.eso.org",
"http://ukads.nottingham.ac.uk",
"http://www.ads.lipi.go.id",
))) . ")/.*(?:abs/|bibcode=|query\?|full/)([12]\d{3}[\w\d\.&]{15})~");
//define("doiRegexp", "(10\.\d{4}/([^\s;\"\?&<])*)(?=[\s;\"\?&]|</)");
#define("doiRegexp", "(10\.\d{4}(/|%2F)[^\s\"\?&]*)(?=[\s\"\?&]|</)"); //Note: if a DO I is superceded by a </span>, it will pick up this tag. Workaround: Replace </ with \s</ in string to search.
//Common replacements
$doiIn = array("[", "]", "<", ">", "<!", "->", "%2F");
$doiOut = array("[", "]", "<", ">", "<!", "->", "/");
$pcDecode = array("[", "]", "<", ">");
$pcEncode = array("[", "]", "<", ">");
$dotEncode = array(".2F", ".5B", ".7B", ".7D", ".5D", ".3C", ".3E", ".3B", ".28", ".29");
$dotDecode = array("/", "[", "{", "}", "]", "<", ">", ";", "(", ")");
//Optimisation
#ob_start(); //Faster, but output is saved until page finshed.
ini_set("memory_limit", "256M");
$fastMode = $_REQUEST["fast"];
$slow_mode = $_REQUEST["slow"];
$user = $_REQUEST["user"];
$bugFix = $_REQUEST["bugfix"];
$crossRefOnly = $_REQUEST["crossrefonly"] ? true : $_REQUEST["turbo"];
if ($_REQUEST["edit"] || $_GET["doi"] || $_GET["pmid"])
$ON = true;
$editSummaryStart = ($bugFix ? "Double-checking that a [[User:DOI_bot/bugs|bug]] has been fixed. " : "Citations: ");
ob_end_flush();
################ Functions ##############
function updateBacklog($page) {
$sPage = addslashes($page);
$id = addslashes(articleId($page));
$db = udbconnect("yarrow");
$result = mysql_query("SELECT page FROM citation WHERE id = '$id'") or print (mysql_error());
$result = mysql_fetch_row($result);
$sql = $result ? "UPDATE citation SET fast = '" . date("c") . "', revision = '" . revisionID()
. "' WHERE page = '$sPage'" : "INSERT INTO citation VALUES ('"
. $id . "', '$sPage', '" . date("c") . "', '0000-00-00', '" . revisionID() . "')";
$result = mysql_query($sql) or print (mysql_error());
mysql_close($db);
}
function countMainLinks($title) {
// Counts the links to the mainpage
global $bot;
if (preg_match("/\w*:(.*)/", $title, $title))
$title = $title[1]; //Gets {{PAGENAME}}
$url = "http://en.wikipedia.org/w/api.php?action=query&bltitle=" . urlencode($title) . "&list=backlinks&bllimit=500&format=yaml";
$bot->fetch($url);
$page = $bot->results;
if (preg_match("~\n\s*blcontinue~", $page))
return 501;
preg_match_all("~\n\s*pageid:~", $page, $matches);
return count($matches[0]);
}
// This function is called from the end of this page.
function logIn($username, $password) {
global $bot; // Snoopy class loaded elsewhere
// Set POST variables to retrieve a token
$submit_vars["format"] = "json";
$submit_vars["action"] = "login";
$submit_vars["lgname"] = $username;
$submit_vars["lgpassword"] = $password;
// Submit POST variables and retrieve a token
$bot->submit(api, $submit_vars);
$first_response = json_decode($bot->results);
$submit_vars["lgtoken"] = $first_response->login->token;
// Store cookies; resubmit with new request (which hast token added to post vars)
foreach ($bot->headers as $header) {
if (substr($header, 0, 10) == "Set-Cookie") {
$cookies = explode(";", substr($header, 12));
foreach ($cookies as $oCook) {
$cookie = explode("=", $oCook);
$bot->cookies[trim($cookie[0])] = $cookie[1];
}
}
}
$bot->submit(api, $submit_vars);
$login_result = json_decode($bot->results);
if ($login_result->login->result == "Success") {
quiet_echo("\n Using account " . $login_result->login->lgusername . ".");
// Add other cookies, which are necessary to remain logged in.
$cookie_prefix = "enwiki";
$bot->cookies[$cookie_prefix . "UserName"] = $login_result->login->lgusername;
$bot->cookies[$cookie_prefix . "UserID"] = $login_result->login->lguserid;
$bot->cookies[$cookie_prefix . "Token"] = $login_result->login->lgtoken;
return true;
} else {
exit("\nCould not log in to Wikipedia servers. Edits will not be committed.\n"); // Will not display to user
global $ON;
$ON = false;
return false;
}
}
function inputValue($tag, $form) {
//Gets the value of an input, if the input's in the right format.
preg_match("~value=\"([^\"]*)\" name=\"$tag\"~", $form, $name);
if ($name)
return $name[1];
preg_match("~name=\"$tag\" value=\"([^\"]*)\"~", $form, $name);
if ($name)
return $name[1];
return false;
}
function write($page, $data, $edit_summary = "Bot edit") {
global $bot;
// Check that bot is logged in:
$bot->fetch(api . "?action=query&prop=info&meta=userinfo&format=json");
$result = json_decode($bot->results);
if ($result->query->userinfo->id == 0) {
return "LOGGED OUT: The bot has been logged out from Wikipedia servers";
}
$bot->fetch(api . "?action=query&prop=info&format=json&intoken=edit&titles=" . urlencode($page));
$result = json_decode($bot->results);
foreach ($result->query->pages as $i_page) {
$my_page = $i_page;
}
$submit_vars = array(
"action" => "edit",
"title" => $my_page->title,
"text" => $data,
"token" => $my_page->edittoken,
"summary" => $edit_summary,
"minor" => "1",
"bot" => "1",
"basetimestamp" => $my_page->touched,
"starttimestamp" => $my_page->starttimestamp,
#"md5" => hash('md5', $data), // removed because I can't figure out how to make the hash of the UTF-8 encoded string that I send match that generated by the server.
"watchlist" => "nochange",
"format" => "json",
);
$bot->submit(api, $submit_vars);
$result = json_decode($bot->results);
if ($result->edit->result == "Success") {
// Need to check for this string whereever our behaviour is dependant on the success or failure of the write operation
return "Success";
} else if ($result->edit->result) {
return $result->edit->result;
} else if ($result->error->code) {
// Return error code
return strtoupper($result->error->code) . ": " . str_replace(array("You ", " have "), array("This bot ", " has "), $result->error->info);
} else {
return "Unhandled error. Please copy this output and <a href=http://code.google.com/p/citation-bot/issues/list>report a bug.</a>";
}
}
function parameters_from_citation($c) {
while (preg_match("~(?<=\{\{)([^\{\}]*)\|(?=[^\{\}]*\}\})~", $c)) {
$c = preg_replace("~(?<=\{\{)([^\{\}]*)\|(?=[^\{\}]*\}\})~", "$1" . pipePlaceholder, $c);
}
// Split citation into parameters
$parts = preg_split("~([\n\s]*\|[\n\s]*)([\w\d-_]*)(\s*= *)~", $c, -1, PREG_SPLIT_DELIM_CAPTURE);
$partsLimit = count($parts);
if (strpos($parts[0], "|") > 0
&& strpos($parts[0], "[[") === FALSE
&& strpos($parts[0], "{{") === FALSE
) {
$p["unused_data"][0] = substr($parts[0], strpos($parts[0], "|") + 1);
}
for ($partsI = 1; $partsI <= $partsLimit; $partsI += 4) {
$value = $parts[$partsI + 3];
$pipePos = strpos($value, "|");
if ($pipePos > 0 && strpos($value, "[[") === false & strpos($value, "{{") === FALSE) {
// There are two "parameters" on one line. One must be missing an equals.
switch (strtolower($parts[$partsI + 1])) {
case 'title':
$value = str_replace('|', '|', $value);
break;
case 'url':
$value = str_replace('|', '%7C', $value);
break;
default:
$p["unused_data"][0] .= " " . substr($value, $pipePos);
$value = substr($value, 0, $pipePos);
}
}
// Load each line into $p[param][0123]
$weight += 32;
$p[strtolower($parts[$partsI + 1])] = Array($value, $parts[$partsI], $parts[$partsI + 2], "weight" => $weight); // Param = value, pipe, equals
}
return $p;
}
function reassemble_citation($p, $sort = false) {
// Load an exemplar pipe and equals symbol to deduce the parameter spacing, so that new parameters match the existing format
foreach ($p as $oP) {
$pipe = $oP[1] ? $oP[1] : null;
$equals = $oP[2] ? $oP[2] : null;
if ($pipe)
break;
}
if (!$pipe) {
$pipe = "\n | ";
}
if (!$equals) {
$equals = " = ";
}
# var_dump($pipe); var_dump($equals); var_dump(preg_replace("~[\r\n]+$~", "", $equals)); die();
if ($sort) {
echo "\n (sorting parameters)";
uasort($p, "bubble_p");
}
foreach ($p as $param => $v) {
if ($param) {
$this_equals = ($v[2] ? $v[2] : $equals);
if (trim($v[0]) && preg_match("~[\r\n]~", $this_equals)) {
$this_equals = preg_replace("~[\r\n]+\s*$~", "", $this_equals);
$nline = "\r\n";
} else {
$nline = null;
}
$cText .= ( $v[1] ? $v[1] : $pipe)
. $param
. $this_equals
. str_replace(array(pipePlaceholder, "\r", "\n"), array("|", "", " "), trim($v[0]))
. $nline;
}
if (is($param)) {
$pEnd[$param] = $v[0];
}
}
global $pStart, $modifications;
if ($pEnd) {
foreach ($pEnd as $param => $value) {
if (!$pStart[$param]) {
$modifications["additions"][$param] = true;
} elseif ($pStart[$param] != $value) {
$modifications["changes"][$param] = true;
}
}
}
return $cText;
}
function mark_broken_doi_template($article_in_progress, $oDoi) {
$page_code = getRawWikiText($article_in_progress);
if ($page_code) {
global $editInitiator;
return write($article_in_progress
, preg_replace("~\{\{\s*cite doi\s*\|\s*" . preg_quote($oDoi) . "\s*\}\}~i", "{{broken doi|$oDoi}}", $page_code)
, "$editInitiator Reference to broken [[doi:$oDoi]] using [[Template:Cite doi]]: please fix!"
);
} else {
exit("Could not retrieve getRawWikiText($article_in_progress) at expand.php#1q537");
}
}
function noteDoi($doi, $src) {
quiet_echo("<h3 style='color:coral;'>Found <a href='http://dx.doi.org/$doi'>DOI</a> $doi from $src.</h3>");
}
function isDoiBroken($doi, $p = false, $slow_mode = false) {
$doi = verify_doi($doi);
if (crossRefData($doi)) {
if ($slow_mode) {
quiet_echo("\"");
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_URL, "http://dx.doi.org/$doi");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //This means we can get stuck.
curl_setopt($ch, CURLOPT_MAXREDIRS, 5); //This means we can't get stuck.
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
$result = curl_exec($ch);
curl_close($ch);
preg_match("~\d{3}~", $result, $code);
switch ($code[0]) {
case false:
$parsed = parse_url("http://dx.doi.org/$doi");
$host = $parsed["host"];
$fp = @fsockopen($host, 80, $errno, $errstr, 20);
if ($fp) {
return false; // Page exists, but had timed out when we first tried.
} else {
logBrokenDoi($doi, $p, 404);
return 404; // DOI is correct but points to a dead page
}
case 302: // Moved temporarily
case 303: // See other
return false;
case 200:
if ($p["url"][0]) {
$ch = curl_init();
curlSetup($ch, $p["url"][0]);
$content = curl_exec($ch);
if (!preg_match("~\Wwiki(\W|pedia)~", $content) && preg_match("~" . preg_quote(urlencode($doi)) . "~", urlencode($content))) {
logBrokenDoi($doi, $p, 200);
return 200; // DOI is present in page, so probably correct
} else
return 999; // DOI could not be found in URL - or URL is a wiki mirror
} else
return 100; // No URL to check for DOI
}
} else {
return false;
}
}
return true;
}
function logBrokenDoi($doi, $p, $error) {
$file = "brokenDois.xml";
if (file_exists($file))
$xml = simplexml_load_file($file);
else
$xml = new SimpleXMLElement("<errors></errors>");
$oDoi = $xml->addChild("doi", $doi);
$oDoi->addAttribute("error_code", $error);
$oDoi->addAttribute("error_found", date("Y-m-d"));
unset($p["doi"], $p["unused_data"], $p["accessdate"]);
foreach ($p as $key => $value)
$oDoi->addAttribute($key, $value[0]);
$xml->asXML($file);
chmod($file, 0644);
}
// Error codes:
// 404 is a working DOI pointing to a page not found;
// 200 is a broken DOI, found in the source of the URL
// Broken DOIs are only logged if they can be spotted in the URL page specified.
function loadParam($param, $value, $equals, $pipe, $weight) {
global $p;
$param = strtolower(trim(str_replace("DUPLICATE DATA:", "", $param)));
if ($param == "unused_data") {
$value = trim(str_replace("DUPLICATE DATA:", "", $value));
}
if (is($param)) {
if (substr($param, strlen($param) - 1) > 0 && trim($value) != trim($p[$param][0])) {
// Add one to last1 to create last2
$param = substr($param, 0, strlen($param) - 1) . (substr($param, strlen($param) - 1) + 1);
} else {
// Parameter already exists
if ($param != "unused_data" && $p[$param][0] != $value) {
// If they have different values, best keep them; if not: discard the exact duplicate!
$param = "DUPLICATE DATA: $param";
}
}
}
$p[$param] = Array($value, $equals, $pipe, "weight" => ($weight + 3) / 4 * 10); // weight will be 10, 20, 30, 40 ...
}
function rename_parameter($old_name, $new_name, $new_value = null) {
global $p;
if (is($new_name)) {
return false;
} else {
$p[$new_name] = $p[$old_name];
if ($new_value !== null) {
$p[$new_name][0] = $new_value;
}
unset($p[$old_name]);
if ($old_name == "url") {
global $modifications;
unset($p["accessdate"]);
$modifications['removed']['accessdate'];
}
return true;
}
}
function cite_template_contents($type, $id) {
$page = get_template_prefix($type);
$replacement_template_name = $page . wikititle_encode($id);
$text = getRawWikiText($replacement_template_name);
if (!$text) {
return false;
} else {
return extract_parameters(extract_template($text, "cite journal"));
}
}
function create_cite_template($type, $id) {
$page = get_template_prefix($type);
return expand($page . wikititle_encode($id), true, true, "{{Cite journal\n | $type = $id \n}}<noinclude>{{Documentation|Template:cite_$type/subpage}}</noinclude>");
}
function get_template_prefix($type) {
return "Template: Cite "
. ($type == "jstor" ? ("doi/10.2307" . wikititle_encode("/")) : $type . "/");
// Not sure that this works:
return "Template: Cite $type/";
// Do we really need to handle JSTORs differently?
// The below code errantly produces cite jstor/10.2307/JSTORID, not cite jstor/JSTORID.
return "Template: Cite "
. ($type == "jstor" ? ("jstor/10.2307" . wikititle_encode("/")) : $type . "/");
}
//TODO:
/*
// Replace ids with appropriately formatted parameters
$c = preg_replace("~\bid(\s*=\s*)(isbn\s*)?(\d[\-\dX ]{9,})~i","isbn$1$3",
preg_replace("~(isbn\s*=\s*)isbn\s?=?\s?(\d\d)~i","$1$2",
preg_replace("~(?<![\?&]id=)isbn\s?:(\s?)(\d\d)~i","isbn$1=$1$2", $citation[$cit_i+1]))); // Replaces isbn: with isbn = */
function id_to_parameters() {
global $p, $modifications;
$id = $p["id"][0];
if (trim($id)) {
echo ("\n - Trying to convert ID parameter to parameterized identifiers.");
} else {
return false;
}
if (preg_match("~\b(PMID|DOI|ISBN|ISSN|ARVIV|LCCN)[\s:]*(\d[^\s\}\{\|]*)~iu", $id, $match)) {
if_null_set(strtolower($match[1]), $match[2]);
$id = str_replace($match[0], "", $id);
}
preg_match_all("~\{\{(?P<content>(?:[^\}]|\}[^\}])+?)\}\}[,. ]*~", $id, $match);
foreach ($match["content"] as $i => $content) {
$content = explode(pipePlaceholder, $content);
unset($parameters);
$j = 0;
foreach ($content as $fragment) {
$content[$j++] = $fragment;
$para = explode("=", $fragment);
if (trim($para[1])) {
$parameters[trim($para[0])] = trim($para[1]);
}
}
switch (strtolower(trim($content[0]))) {
case "arxiv":
array_shift($content);
if ($parameters["id"]) {
if_null_set("arxiv", ($parameters["archive"] ? trim($parameters["archive"]) . "/" : "") . trim($parameters["id"]));
} else if ($content[1]) {
if_null_set("arxiv", trim($content[0]) . "/" . trim($content[1]));
} else {
if_null_set("arxiv", implode(pipePlaceholder, $content));
}
$id = str_replace($match[0][$i], "", $id);
break;
case "lccn":
if_null_set("lccn", trim($content[1]) . $content[3]);
$id = str_replace($match[0][$i], "", $id);
break;
case "rfcurl":
$identifier_parameter = "rfc";
case "asin":
if ($parameters["country"]) {
print "\n - {{ASIN}} country parameter not supported: can't convert.";
break;
}
case "oclc":
if ($content[2]) {
print "\n - {{OCLC}} has multiple parameters: can't convert.";
break;
}
case "ol":
if ($parameters["author"]) {
print "\n - {{OL}} author parameter not supported: can't convert.";
break;
}
case "bibcode":
case "doi":
case "isbn":
case "issn":
case "jfm":
case "jstor":
if ($parameters["sici"] || $parameters["issn"]) {
print "\n - {{JSTOR}} named parameters are not supported: can't convert.";
break;
}
case "mr":
case "osti":
case "pmid":
case "pmc":
case "ssrn":
case "zbl":
if ($identifier_parameter) {
array_shift($content);
}
if (!if_null_set($identifier_parameter ? $identifier_parameter : strtolower(trim(array_shift($content))), $parameters["id"] ? $parameters["id"] : $content[0]
)) {
$modifications["removed"] = true;
}
$identifier_parameter = null;
$id = str_replace($match[0][$i], "", $id);
break;
default:
print "\n - No match found for $content[0].";
}
}
if (trim($id)) {
$p["id"][0] = $id;
} else {
unset($p["id"]);
}
}
function get_identifiers_from_url() {
// Convert URLs to article identifiers:
global $p;
$url = $p["url"][0];
// JSTOR
if (strpos($url, "jstor.org") !== FALSE) {
if (strpos($url, "sici")) {
#Skip. We can't do anything more with the SICI, unfortunately.
} elseif (preg_match("~(?|(\d{6,})$|(\d{6,})[^\d%\-])~", $url, $match)) {
rename_parameter("url", "jstor", $match[1]);
}
} else {
if (preg_match(bibcode_regexp, urldecode($url), $bibcode)) {
rename_parameter("url", "bibcode", urldecode($bibcode[1]));
} else if (preg_match("~^http://www\.pubmedcentral\.nih\.gov/articlerender.fcgi\?.*\bartid=(\d+)"
. "|^http://www\.ncbi\.nlm\.nih\.gov/pmc/articles/PMC(\d+)~", $url, $match)) {
rename_parameter("url", "pmc", $match[1] . $match[2]);
get_data_from_pubmed('pmc');
} else if (preg_match("~^http://dx\.doi\.org/(.*)", $url, $match)) {
rename_parameter("url", "doi", urldecode($match[1]));
get_data_from_doi();
} else if (preg_match("~\barxiv.org/(?:pdf|abs)/(.+)$~", $url, $match)) {
//ARXIV
rename_parameter("url", "arxiv", $match[1]);
get_data_from_arxiv();
} else if (preg_match("~http://www.ncbi.nlm.nih.gov/pubmed/.*=(\d{6,})~", $url, $match)) {
rename_parameter('url', 'pmid', $match[1]);
get_data_from_pubmed('pmid');
} else if (preg_match("~^http://www\.amazon(?P<domain>\.[\w\.]{1,7})/dp/(?P<id>\d+X?)~", $url, $match)) {
if ($match['domain'] == ".com") {
rename_parameter('url', 'asin', $match['id']);
} else {
$p["id"][0] .= " {{ASIN|{$match['id']}|country=" . str_replace(array(".co.", ".com.", "."), "", $match['domain']) . "}}";
unset($p["url"]);
unset($p["accessdate"]);
}
}
}
}
function url2template($url, $citation) {
if (preg_match("~jstor\.org/(?!sici).*[/=](\d+)~", $url, $match)) {
return "{{Cite doi | 10.2307/$match[1] }}";
} else if (preg_match("~//dx\.doi\.org/(.+)$~", $url, $match)) {
return "{{Cite doi | " . urldecode($match[1]) . " }}";
} else if (preg_match("~^http://www\.amazon(?P<domain>\.[\w\.]{1,7})/dp/(?P<id>\d+X?)~", $url, $match)) {
return ($match['domain'] == ".com") ? "{{ASIN | {$match['id']} }}" : " {{ASIN|{$match['id']}|country=" . str_replace(array(".co.", ".com.", "."), "", $match['domain']) . "}}";
} else if (preg_match("~^http://books\.google(?:\.\w{2,3}\b)+/~", $url, $match)) {
return "{{" . ($citation ? 'Cite book' : 'Cite journal') . ' | url = ' . $url . '}}';
} else if (preg_match("~^http://www\.pubmedcentral\.nih\.gov/articlerender.fcgi\?.*\bartid=(\d+)"
. "|^http://www\.ncbi\.nlm\.nih\.gov/pmc/articles/PMC(\d+)~", $url, $match)) {
return "{{Cite pmc | {$match[1]}{$match[2]} }}";
} elseif (preg_match(bibcode_regexp, urldecode($url), $bibcode)) {
return "{{Cite journal | bibcode = " . urldecode($bibcode[1]) . "}}";
} else if (preg_match("~http://www.ncbi.nlm.nih.gov/pubmed/.*=(\d{6,})~", $url, $match)) {
return "{{Cite pmid | {$match[1]} }}";
} else if (preg_match("~\barxiv.org/(?:pdf|abs)/(.+)$~", $url, $match)) {
return "{{Cite arxiv | eprint={$match[1]} }}";
} else {
return $url;
}
}
function tidy_citation() {
global $p, $pStart, $modifications;
if (!trim($pStart["title"]) && isset($p["title"][0])) {
$p["title"][0] = formatTitle($p["title"][0]);
} else if ($modifications && is("title")) {
$p["title"][0] = (mb_substr($p["title"][0], -1) == ".") ? mb_substr($p["title"][0], 0, -1) : $p["title"][0];
$p['title'][0] = straighten_quotes($p['title'][0]);
}
foreach (array("pages", "page", "issue", "year") as $oParameter) {
if (is($oParameter)) {
if (!preg_match("~^[A-Za-z ]+\-~", $p[$oParameter][0])
&& mb_ereg(to_en_dash, $p[$oParameter][0])) {
$modifications["dashes"] = true;
echo ( "\n - Upgrading to en-dash in $oParameter");
$p[$oParameter][0] = mb_ereg_replace(to_en_dash, en_dash, $p[$oParameter][0]);
}
}
}
//Edition - don't want 'Edition ed.'
if (is("edition")) {
$p["edition"][0] = preg_replace("~\s+ed(ition)?\.?\s*$~i", "", $p["edition"][0]);
}
// Don't add ISSN if there's a journal name
if (is('journal') && !isset($pStart['issn'][0])) unset($p['issn']);
// Remove publisher if [cite journal/doc] warrants it
if (is($p["journal"]) && (is("doi") || is("issn"))) unset($p["publisher"]);
if (strlen($p['issue'][0]) > 1 && $p['issue'][0][0] == '0') {
$p['issue'][0] = preg_replace('~^0+~', '', $p['issue'][0]);
}
if (strlen($p['issue'][0]) > 1 && $p['issue'][0][0] == '0') {
$p['issue'][0] = preg_replace('~^0+~', '', $p['issue'][0]);
}
// If we have any unused data, check to see if any is redundant!
if (is("unused_data")) {
$freeDat = explode("|", trim($p["unused_data"][0]));
unset($p["unused_data"]);
foreach ($freeDat as $dat) {
$eraseThis = false;
foreach ($p as $oP) {
similar_text(mb_strtolower($oP[0]), mb_strtolower($dat), $percentSim);
if ($percentSim >= 85)
$eraseThis = true;
}
if (!$eraseThis)
$p["unused_data"][0] .= "|" . $dat;
}
if (trim(str_replace("|", "", $p["unused_data"][0])) == "")
unset($p["unused_data"]);
else {
if (substr(trim($p["unused_data"][0]), 0, 1) == "|")
$p["unused_data"][0] = substr(trim($p["unused_data"][0]), 1);
echo "\nXXX Unused data in following citation: {$p["unused_data"][0]}";
}
}
if (is('accessdate') && !is('url')) {
unset($p['accessdate']);
}
if ($modifications['additions']['display-authors']) {
if_null_set('author' . ($p['display-authors'][0] + 1), '<Please add first missing authors to populate metadata.>');
}
}
function standardize_reference($reference) {
$whitespace = Array(" ", "\n", "\r", "\v", "\t");
return str_replace($whitespace, "", $reference);
}
// $comments should be an array, with the original comment content.
// $placeholder will be prepended to the comment number in the sprintf to comment_placeholder's %s.
function replace_comments($text, $comments, $placeholder = "") {
foreach ($comments as $i => $comment) {
$text = str_replace(sprintf(comment_placeholder, $placeholder . $i), $comment, $text);
}
return $text;
}
// This function may need to be called twice; the second pass will combine <ref name="Name" /> with <ref name=Name />.
function combine_duplicate_references($page_code) {
$original_encoding = mb_detect_encoding($page_code);
$page_code = mb_convert_encoding($page_code, "UTF-8");
if (preg_match_all("~<!--[\s\S]*?-->~", $page_code, $match)) {
$removed_comments = $match[0];
foreach ($removed_comments as $i => $content) {
$page_code = str_replace($content, sprintf(comment_placeholder, "sr$i"), $page_code);
}
}
// Before we start with the page code, find and combine references in the reflist section that have the same name
if (preg_match(reflist_regexp, $page_code, $match)) {
if (preg_match_all('~(?P<ref1><ref\s+name\s*=\s*(?<quote1>["\']?+)(?P<name>[^>]+)(?P=quote1)(?:\s[^>]+)?\s*>[\p{L}\P{L}]+</\s*ref>)'
. '[\p{L}\P{L}]+(?P<ref2><ref\s+name\s*=\s*(?P<quote2>["\']?+)(?P=name)\b(?P=quote2)[\p{L}\P{L}]+</\s*ref>)~iuU', $match[1], $duplicates)) {
foreach ($duplicates['ref2'] as $i => $to_delete) {
if ($to_delete == $duplicates['ref1'][$i]) {
$mb_start = mb_strpos($page_code, $to_delete) + mb_strlen($to_delete);
$page_code = mb_substr($page_code, 0, $mb_start)
. str_replace($to_delete, '', mb_substr($page_code, $mb_start));
} else {
$page_code = str_replace($to_delete, '', $page_code);
}
}
}
}
// Now look at the rest of the page:
preg_match_all("~<ref\s*name\s*=\s*(?P<quote>[\"']?)([^>]+)(?P=quote)\s*/>~", $page_code, $empty_refs);
// match 1 = ref names
if (preg_match_all("~<ref(\s*name\s*=\s*(?P<quote>[\"']?)([^>]+)(?P=quote)\s*)?>"
. "(([^<]|<(?![Rr]ef))+?)</ref>~i", $page_code, $refs)) {
// match 0 = full ref; 1 = redundant; 2= used in regexp for backreference;
// 3 = ref name; 4 = ref content; 5 = redundant
foreach ($refs[4] as $ref) {
$standardized_ref[] = standardize_reference($ref);
}
// Turn essentially-identical references into exactly-identical references
foreach ($refs[4] as $i => $this_ref) {
if (false !== ($key = array_search(standardize_reference($this_ref), $standardized_ref))
&& $key != $i) {
$full_original[] = ">" . $refs[4][$key] . "<"; // be careful; I hope that this is specific enough.
$duplicate_content[] = ">" . $this_ref . "<";
}
print_r($duplicate_content); print_r($full_original);
$page_code = str_replace($duplicate_content, $full_original, $page_code);
}
} else {
// no matches, return input
echo "\n - No references found.";
return mb_convert_encoding(replace_comments($page_code, $removed_comments, 'sr'), $original_encoding);
}
// Reset
$full_original = null;
$duplicate_content = null;
$standardized_ref = null;
// Now all references that need merging will have identical content. Proceed to do the replacements...
if (preg_match_all("~<ref(\s*name\s*=\s*(?P<quote>[\"']?)([^>]+)(?P=quote)\s*)?>"
. "(([^<]|<(?!ref))+?)</ref>~i", $page_code, $refs)) {
$standardized_ref = $refs[4]; // They were standardized above.
foreach ($refs[4] as $i => $content) {
if (false !== ($key = array_search($refs[4][$i], $standardized_ref))
&& $key != $i) {
$full_original[] = $refs[0][$key];
$full_duplicate[] = $refs[0][$i];
$name_of_original[] = $refs[3][$key];
$name_of_duplicate[] = $refs[3][$i];
$duplicate_content[] = $content;
$name_for[$content] = $name_for[$content] ? $name_for[$content] : ($refs[3][$key] ? $refs[3][$key] : ($refs[3][$i] ? $refs[3][$i] : null));
}
}
$already_replaced = Array(); // so that we can use FALSE and not NULL in the check...
if ($full_duplicate) {
foreach ($full_duplicate as $i => $this_duplicate) {
if (FALSE === array_search($this_duplicate, $already_replaced)) {
$already_replaced[] = $full_duplicate[$i]; // So that we only replace the same reference once
echo "\n - Replacing duplicate reference $this_duplicate. \n Reference name: "
. ( $name_for[$duplicate_content[$i]] ? $name_for[$duplicate_content[$i]] : "Autogenerating." ); // . " (original: $full_original[$i])";
$replacement_template_name = $name_for[$duplicate_content[$i]] ? $name_for[$duplicate_content[$i]] : get_name_for_reference($duplicate_content[$i], $page_code);
// First replace any empty <ref name=Blah content=none /> or <ref name=Blah></ref> with the new name
$ready_to_replace = preg_replace("~<ref\s*name\s*=\s*(?P<quote>[\"']?)"
. preg_quote($name_of_duplicate[$i])
. "(?P=quote)(\s*/>|\s*>\s*</\s*ref>)~"
, "<ref name=\"" . $replacement_template_name . "\"$2"
, $page_code);
if ($name_of_original[$i]) {
// Don't replace the original template!
$original_ref_end_pos = mb_strpos($ready_to_replace, $full_original[$i]) + mb_strlen($full_original[$i]);
$code_upto_original_ref = mb_substr($ready_to_replace, 0, $original_ref_end_pos);
} elseif ($name_of_duplicate[$i]) {
// This is an odd case; in a fashion the simplest.
// In effect, we switch the original and duplicate over,..
$original_ref_end_pos = 0;
$code_upto_original_ref = "";
$already_replaced[] = $full_original[$i];
$this_duplicate = $full_original[$i];
} else {
// We need add a name to the original template, and not to replace it
$original_ref_end_pos = mb_strpos($ready_to_replace, $full_original[$i]);
$code_upto_original_ref = mb_substr($ready_to_replace, 0, $original_ref_end_pos) // Sneak this in to "first_duplicate"
. preg_replace("~<ref(\s+name\s*=\s*(?P<quote>[\"']?)" . preg_quote($name_of_original[$i])
. "(?P=quote)\s*)?>~i", "<ref name=\"$replacement_template_name\">", $full_original[$i]);
$original_ref_end_pos += mb_strlen($full_original[$i]);
}
// Then check that the first occurrence won't be replaced
$page_code = $code_upto_original_ref . str_replace($this_duplicate,
sprintf(blank_ref, $replacement_template_name), mb_substr($ready_to_replace, $original_ref_end_pos));
global $modifications;
$modifications["combine_references"] = true;
}
}
}
}
$page_code = replace_comments($page_code, $removed_comments, 'sr');
echo ($already_replaced) ? "\n - Combined duplicate references." : "\n - No duplicate references to combine." ;
return $page_code;
}
// If <ref name=Bla /> appears in the reference list, it'll break things. It needs to be replaced with <ref name=Bla>Content</ref>
// which ought to exist earlier in the page. It's important to check that this doesn't exist elsewhere in the reflist, though.
function named_refs_in_reflist($page_code) {
if (preg_match(reflist_regexp, $page_code, $match) &&
preg_match_all('~[\r\n\*]*<ref name=(?P<quote>[\'"]?)(?P<name>.+?)(?P=quote)\s*/\s*>~i', $match[1], $empty_refs)) {
$temp_reflist = $match[1];
foreach ($empty_refs['name'] as $i => $ref_name) {
echo "\n - Found an empty ref in the reflist; switching with occurrence in article text."
."\n Reference #$i name: $ref_name";
$this_regexp = '~<ref name=(?P<quote>[\'"]?)' . preg_quote($ref_name)
. '(?P=quote)\s*>[\s\S]+?<\s*/\s*ref>~';
if (preg_match($this_regexp, $temp_reflist, $full_ref)) {
// A full-text reference exists elsewhere in the reflist. The duplicate can be safely deleted from the reflist.
$temp_reflist = str_replace($empty_refs[0][$i], '', $temp_reflist);
} elseif (preg_match($this_regexp, $page_code, $full_ref)) {
// Remove all full-text references from the page code. We'll add an updated reflist later.
$page_code = str_replace($full_ref[0], $empty_refs[0][$i], $page_code);
$temp_reflist = str_replace($empty_refs[0][$i], $full_ref[0], $temp_reflist);
}
}
// Add the updated reflist, which should now contain no empty references.
$page_code = str_replace($match[1], $temp_reflist, $page_code);
}
return $page_code;
}
function ref_templates($page_code, $type) {
while (false !== ($ref_template = extract_template($page_code, "ref $type"))) {
echo " Converted {{ref $type}}.";
$ref_parameters = extract_parameters($ref_template);
$ref_id = $ref_parameters[1] ? $ref_parameters[1][0] : $ref_parameters["unnamed_parameter_1"][0];
$trimmed_id = trim_identifier($ref_id);
if (!getArticleId("Template:cite $type/" . wikititle_encode($ref_id))) {
$citation_code = create_cite_template($type, $ref_id);
$template = extract_parameters(extract_template($citation_code, "cite journal"));
} else {
$template = cite_template_contents($type, $ref_id);
}
$replacement_template_name = generate_template_name(
(trim($template["last1"][0]) != "" && trim($template["year"][0]) != "") ? trim($template["last1"][0]) . trim($template["year"][0]) : "ref_"
, $page_code);
$ref_content = "<ref name=\"$replacement_template_name\">"
. $ref_template
. "</ref>";
$page_code = str_replace($ref_template,
str_ireplace("ref $type", "cite $type",
str_replace($ref_id, $trimmed_id, $ref_content)
), $page_code);
}
return $page_code;
}
function trim_identifier($id) {
$cruft = "[\.,;:><\s]*";
print $id;
preg_match("~^$cruft(?:d?o?i?:)?\s*(.*?)$cruft$~", $id, $match);
print_r($match);
return $match[1];
}
function name_references($page_code) {
echo " naming";
if (preg_match_all("~<ref>[^\{<]*\{\{\s*(?=[cC]it|[rR]ef).*</ref>~U", $page_code, $refs)) {
foreach ($refs[0] as $ref) {
$ref_name = get_name_for_reference($ref, $page_code);
if (substr($ref_name, 0, 4) != "ref_") {
// i.e. we have used an interesting reference name
$page_code = str_replace($ref, str_replace("<ref>", "<ref name=\"$ref_name\">", $ref), $page_code);
}
echo ".";
}
}
return $page_code;
}
function rename_references($page_code) {
if (preg_match_all("~(<ref name=(?P<quote>[\"']?)[Rr]ef_?[ab]?(?:[a-z]|utogenerated|erence[a-Z])?(?P=quote)\s*>)"
. "[^\{<]*\{\{\s*(?=[cC]it|[rR]ef)[\s\S]*</ref>~U", $page_code, $refs)) {
$countRefs = count($refs[0]);
for ($i = 0; $i < $countRefs; ++$i) {
$ref_name = get_name_for_reference($refs[0][$i], $page_code);
if (substr($ref_name, 0, 4) != "ref_") {
// i.e. we have used an interesting reference name
echo " renaming references with meaningless names";
$page_code = str_replace($refs[1][$i], "<ref name=\"$ref_name\">", $page_code);
}
echo ".";
}
}
return $page_code;
}
function get_name_for_reference($text, $page_code) {
if (stripos($text, "{{harv") !== FALSE && preg_match("~\|([\s\w\-]+)\|\s*([12]\d{3})\D~", $text, $match)) {
$author = $match[1];
$date = $match[2];
} else {
$parsed = parse_wikitext(strip_tags($text));
$parsed_plaintext = strip_tags($parsed);
$date = (preg_match("~rft\.date=[^&]*(\d\d\d\d)~", $parsed, $date) ? $date[1] : "" );
$author = preg_match("~rft\.aulast=([^&]+)~", $parsed, $author)
? urldecode($author[1])
: preg_match("~rft\.au=([^&]+)~", $parsed, $author) ? urldecode($author[1]) : "ref_";
$btitle = preg_match("~rft\.[bah]title=([^&]+)~", $parsed, $btitle) ? urldecode($btitle[1]) : "";
}
print "\n - $author / $btitle / \n";
if ($author != "ref_") {
preg_match("~\w+~", authorify($author), $author);
} else if ($btitle) {
preg_match("~\w+\s?\w+~", authorify($btitle), $author);
} else if ($parsed_plaintext) {
print $parsed_plaintext;
if (!preg_match("~\w+\s?\w+~", authorify($parsed_plaintext), $author)) {
preg_match("~\w+~", authorify($parsed_plaintext), $author);
}
}
if (strpos($text, "://")) {
if (preg_match("~\w+://(?:www\.)?([^/]+?)(?:\.\w{2,3}\b)+~i", $text, $match)) {
$replacement_template_name = $match[1];
} else {
$replacement_template_name = "bare_url"; // just in case there's some bizarre way that the URL doesn't match the regexp
}
} else {
$replacement_template_name = str_replace(Array("\n", "\r", "\t", " "), "", ucfirst($author[0])) . $date;
}
return generate_template_name($replacement_template_name, $page_code);
}
// Strips special characters from reference name,
// then does a check against the current page code to generate a unique name for the reference
// (by suffixing _a, etc, as necessary)
function generate_template_name($replacement_template_name, $page_code) {
$replacement_template_name = remove_accents($replacement_template_name);
if (!trim(preg_replace("~\d~", "", $replacement_template_name))) {
$replacement_template_name = "ref" . $replacement_template_name;
}
global $alphabet;
$die_length = count($alphabet);
$underscore = (preg_match("~[\d_]$~", $replacement_template_name) ? "" : "_");
while (preg_match("~<ref name=(?P<quote>['\"]?)"
. preg_quote($replacement_template_name) . "_?" . $alphabet[$i++]
. "(?P=quote)[/\s]*>~i", $page_code, $match)) {
if ($i >= $die_length) {
$replacement_template_name .= $underscore . $alphabet[++$j];
$underscore = "";
$i = 0;
}
}
if ($i < 2) {
$underscore = "";
}
return $replacement_template_name