-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathapiFunctions.php
1584 lines (1532 loc) · 75.3 KB
/
apiFunctions.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
declare(strict_types=1);
require_once 'constants.php'; // @codeCoverageIgnore
require_once 'user_messages.php'; // @codeCoverageIgnore
require_once 'Template.php'; // @codeCoverageIgnore
require_once 'NameTools.php'; // @codeCoverageIgnore
/** @param array<string> $pmids
@param array<Template> $templates */
function query_pmid_api (array $pmids, array &$templates): void { // Pointer to save memory
entrez_api($pmids, $templates, 'pubmed');
}
/** @param array<string> $pmcs
@param array<Template> $templates */
function query_pmc_api (array $pmcs, array &$templates): void { // Pointer to save memory
entrez_api($pmcs, $templates, 'pmc');
}
final class AdsAbsControl {
private const MAX_CACHE_SIZE = 50000;
private static int $big_counter = 0;
private static int $small_counter = 0;
/** @var array<string> $doi2bib */
private static array $doi2bib = [];
/** @var array<string> $bib2doi */
private static array $bib2doi = [];
public static function big_gave_up_yet(): bool {
self::$big_counter = max(self::$big_counter - 1, 0);
return self::$big_counter !== 0;
}
public static function big_give_up(): void {
self::$big_counter = 1000;
}
public static function big_back_on(): void {
self::$big_counter = 0;
}
public static function small_gave_up_yet(): bool {
self::$small_counter = max(self::$small_counter - 1, 0);
return self::$small_counter !== 0;
}
public static function small_give_up(): void {
self::$small_counter = 1000;
}
public static function small_back_on(): void {
self::$small_counter = 0;
}
public static function add_doi_map(string $bib, string $doi): void {
self::check_memory_use();
if ($bib === '' || $doi === '') {
report_minor_error('Bad parameter in add_doi_map: ' . echoable($bib) . ' : ' . echoable($doi)); // @codeCoverageIgnore
return; // @codeCoverageIgnore
}
if ($doi === 'X') {
self::$bib2doi[$bib] = 'X';
} elseif (doi_works($doi)) { // paranoid
self::$bib2doi[$bib] = $doi;
if (stripos($bib, 'tmp') === false && stripos($bib, 'arxiv') === false) {
self::$doi2bib[$doi] = $bib;
}
}
}
public static function get_doi2bib(string $doi): string {
return (string) @self::$doi2bib[$doi];
}
public static function get_bib2doi(string $bib): string {
return (string) @self::$bib2doi[$bib];
}
public static function check_memory_use(): void {
$usage = count(self::$doi2bib) + count(self::$bib2doi);
if ($usage > self::MAX_CACHE_SIZE) {
self::free_memory(); // @codeCoverageIgnore
}
}
public static function free_memory(): void {
self::$doi2bib = [];
self::$bib2doi = [];
gc_collect_cycles();
}
}
/**
@param array<string> $ids
@param array<Template> $templates
*/
function entrez_api(array $ids, array &$templates, string $db): void { // Pointer to save memory
set_time_limit(120);
if (!count($ids) ||
$ids === ['XYZ'] ||
$ids === ['1'] ||
$ids === ['']) {
return; // junk data from test suite
}
if ($db !== 'pubmed' && $db !== 'pmc') {
report_error("Invalid Entrez type passed in: " . echoable($db)); // @codeCoverageIgnore
}
report_action("Using {$db} API to retrieve publication details: ");
$xml = get_entrez_xml($db, implode(',', $ids));
if ($xml === null) {
report_warning("Error in PubMed search: No response from Entrez server"); // @codeCoverageIgnore
return; // @codeCoverageIgnore
}
// A few PMC do not have any data, just pictures of stuff
if (isset($xml->DocSum->Item) && count($xml->DocSum->Item) > 0) {
foreach($xml->DocSum as $document) {
report_info("Found match for {$db} identifier " . echoable((string) $document->Id));
foreach($ids as $template_key => $an_id) { // Cannot use array_search since that only returns first
$an_id = (string) $an_id;
if (!array_key_exists($template_key, $templates)) {
bot_debug_log('Key not found in entrez_api ' . (string) $template_key . ' ' . $an_id); // @codeCoverageIgnore
$an_id = '-3333'; // @codeCoverageIgnore
}
if ($an_id === (string) $document->Id) {
$this_template = $templates[$template_key];
$this_template->record_api_usage('entrez', $db === 'pubmed' ? 'pmid' : 'pmc');
foreach ($document->Item as $item) {
if (preg_match("~10\.\d{4}/[^\s\"']*~", (string) $item, $match)) {
$this_template->add_if_new('doi', $match[0], 'entrez');
}
switch ($item["Name"]) {
case "Title":
$this_template->add_if_new('title', str_replace(["[", "]"], "", (string) $item), 'entrez'); // add_if_new will format the title
break;
case "PubDate":
if (preg_match("~(\d+)\s*(\w*)~", (string) $item, $match)) {
$this_template->add_if_new('year', $match[1], 'entrez');
}
break;
case "FullJournalName":
$this_template->add_if_new('journal', mb_ucwords((string) $item), 'entrez'); // add_if_new will format the title
break;
case "Volume":
$this_template->add_if_new('volume', (string) $item, 'entrez');
break;
case "Issue":
$this_template->add_if_new('issue', (string) $item, 'entrez');
break;
case "Pages":
$this_template->add_if_new('pages', (string) $item, 'entrez');
break;
case "PmId":
$this_template->add_if_new('pmid', (string) $item, 'entrez');
break;
case "AuthorList":
$i = 0;
foreach ($item->Item as $key => $subItem) {
$subItem = (string) $subItem;
if (preg_match('~^\d~', $subItem)) { // Author started with a number, skip all remaining authors.
break; // @codeCoverageIgnore
} elseif ((string) $key === "CollectiveName") { // This is often really long string of gibberish
break; // @codeCoverageIgnore
} elseif (strlen($subItem) > 100) {
break; // @codeCoverageIgnore
} elseif (author_is_human($subItem)) {
$jr_test = junior_test($subItem);
$subItem = $jr_test[0];
$junior = $jr_test[1];
if (preg_match("~(.*) (\w+)$~", $subItem, $names)) {
$first = trim(preg_replace('~(?<=[A-Z])([A-Z])~', ". $1", $names[2]));
if (strpos($first, '.') && substr($first, -1) !== '.') {
$first .= '.';
}
$i++;
$this_template->add_if_new("author{$i}", $names[1] . $junior . ',' . $first, 'entrez');
}
} else {
// We probably have a committee or similar. Just use 'author$i'.
$i++;
$this_template->add_if_new("author{$i}", $subItem, 'entrez');
}
}
break;
case "LangList":
case 'ISSN':
break;
case "ArticleIds":
foreach ($item->Item as $subItem) {
switch ($subItem["Name"]) {
case "pubmed":
case "pmid":
preg_match("~\d+~", (string) $subItem, $match);
$this_template->add_if_new("pmid", $match[0], 'entrez');
break;
case "pmc":
preg_match("~\d+~", (string) $subItem, $match);
$this_template->add_if_new('pmc', $match[0], 'entrez');
break;
case "pmcid":
if (preg_match("~embargo-date: ?(\d{4})\/(\d{2})\/(\d{2})~", (string) $subItem, $match)) {
$date_emb = date("F j, Y", mktime(0, 0, 0, (int) $match[2], (int) $match[3], (int) $match[1])); // @codeCoverageIgnore
$this_template->add_if_new('pmc-embargo-date', $date_emb, 'entrez'); // @codeCoverageIgnore
}
break;
case "doi":
case "pii":
if (preg_match("~10\.\d{4}/[^\s\"']*~", (string) $subItem, $match)) {
$this_template->add_if_new('doi', $match[0], 'entrez');
}
}
}
break;
}
}
}
}
}
}
return;
}
/**
@param array<string> $bibcodes
@param array<Template> $templates
*/
function query_bibcode_api(array $bibcodes, array &$templates): void { // Pointer to save memory
adsabs_api($bibcodes, $templates, 'bibcode');
}
/**
@param array<Template> $templates
*/
function expand_arxiv_templates (array &$templates): void { // Pointer to save memory
$ids = [];
$arxiv_templates = [];
foreach ($templates as $this_template) {
if ($this_template->wikiname() === 'cite arxiv') {
$this_template->rename('arxiv', 'eprint');
} else {
$this_template->rename('eprint', 'arxiv');
}
$eprint = str_ireplace("arXiv:", "", $this_template->get('eprint') . $this_template->get('arxiv'));
if ($eprint && stripos($eprint, 'CITATION_BOT') === false) {
$ids[] = $eprint;
$arxiv_templates[] = $this_template;
}
}
arxiv_api($ids, $arxiv_templates);
}
/**
@param array<string> $ids
@param array<Template> $templates
*/
function arxiv_api(array $ids, array &$templates): void { // Pointer to save memory
static $ch = null;
if ($ch === null) {
$ch = bot_curl_init(1.0, []);
}
set_time_limit(120);
if (count($ids) === 0) {
return;
}
report_action("Getting data from arXiv API");
/** @psalm-taint-escape ssrf */
$request = "https://export.arxiv.org/api/query?start=0&max_results=2000&id_list=" . implode(',', $ids);
curl_setopt($ch, CURLOPT_URL, $request);
$response = bot_curl_exec($ch);
if ($response) {
$xml = @simplexml_load_string(
preg_replace("~(</?)(\w+):([^>]*>)~", "$1$2$3", $response)
);
unset($response);
} else {
report_warning("No response from arXiv."); // @codeCoverageIgnore
return; // @codeCoverageIgnore
}
if (!is_object($xml)) {
report_warning("No valid from arXiv."); // @codeCoverageIgnore
return; // @codeCoverageIgnore
}
if ((string) $xml->entry->title === "Error") {
$the_error = (string) $xml->entry->summary;
if (stripos($the_error, 'incorrect id format for') !== false) {
report_warning("arXiv search failed: " . echoable($the_error));
} else {
report_minor_error("arXiv search failed - please report the error: " . echoable($the_error)); // @codeCoverageIgnore
}
return;
}
$this_template = current($templates); // advance at end of foreach loop
foreach ($xml->entry as $entry) {
$i = 0;
report_info("Found match for arXiv " . echoable($ids[$i]));
if ($this_template->add_if_new("doi", (string) $entry->arxivdoi, 'arxiv')) {
if ($this_template->blank(['journal', 'volume', 'issue']) && $this_template->has('title')) {
// Move outdated/bad arXiv title out of the way
$the_arxiv_title = $this_template->get('title');
$the_arxiv_contribution = $this_template->get('contribution');
if ($the_arxiv_contribution !== '') {
$this_template->set('contribution', '');
}
$this_template->set('title', '');
expand_by_doi($this_template);
if ($this_template->blank('title')) {
$this_template->set('title', $the_arxiv_title);
if ($the_arxiv_contribution !== '') {
$this_template->set('contribution', $the_arxiv_contribution);
}
} else {
if ($the_arxiv_contribution !== '' && $this_template->blank('contribution')) {
$this_template->forget('contribution');
}
}
unset($the_arxiv_title);
unset($the_arxiv_contribution);
} else {
expand_by_doi($this_template);
}
}
foreach ($entry->author as $auth) {
$i++;
$name = (string) $auth->name;
if (preg_match("~(.+\.)(.+?)$~", $name, $names) || preg_match('~^\s*(\S+) (\S+)\s*$~', $name, $names)) {
$this_template->add_if_new("last{$i}", $names[2], 'arxiv');
$this_template->add_if_new("first{$i}", $names[1], 'arxiv');
} else {
$this_template->add_if_new("author{$i}", $name, 'arxiv');
}
if ($this_template->blank(["last{$i}", "first{$i}", "author{$i}"])) {
$i--; // Deal with authors that are empty or just a colon as in https://export.arxiv.org/api/query?start=0&max_results=2000&id_list=2112.04678
}
}
$the_title = (string) $entry->title;
// arXiv fixes these when it sees them
while (preg_match('~\$\^{(\d+)}\$~', $the_title, $match)) {
$the_title = str_replace($match[0], '<sup>' . $match[1] . '</sup>', $the_title); // @codeCoverageIgnore
}
while (preg_match('~\$_(\d+)\$~', $the_title, $match)) {
$the_title = str_replace($match[0], '<sub>' . $match[1] . '</sub>', $the_title); // @codeCoverageIgnore
}
while (preg_match('~\\ce{([^}{^ ]+)}~', $the_title, $match)) { // arXiv fixes these when it sees them
$the_title = str_replace($match[0], ' ' . $match[1] . ' ', $the_title); // @codeCoverageIgnore
$the_title = str_replace(' ', ' ', $the_title); // @codeCoverageIgnore
}
$this_template->add_if_new("title", $the_title, 'arxiv'); // Formatted by add_if_new
$this_template->add_if_new("class", (string) $entry->category["term"], 'arxiv');
$int_time = strtotime((string) $entry->published);
if ($int_time) {
$this_template->add_if_new("year", date("Y", $int_time), 'arxiv');
}
if ($this_template->has('publisher')) {
if (stripos($this_template->get('publisher'), 'arxiv') !== false) {
$this_template->forget('publisher');
}
}
$this_template = next($templates);
}
if ($this_template !== false) {
report_minor_error('Unexpected error in arxiv_api()' . echoable($this_template->parsed_text())); // @codeCoverageIgnore
}
return;
}
/**
@param array<string> $ids
@param array<Template> $templates
*/
function adsabs_api(array $ids, array &$templates, string $identifier): void { // Pointer to save memory
set_time_limit(120);
if (count($ids) === 0) {
return;
}
foreach ($ids as $key => $bibcode) {
if (stripos($bibcode, 'CITATION') !== false || strlen($bibcode) !== 19) {
unset($ids[$key]); // @codeCoverageIgnore
}
}
// Use cache
foreach ($templates as $template) {
if ($template->has('bibcode') && $template->blank('doi')) {
$doi = AdsAbsControl::get_bib2doi($template->get('bibcode'));
if (doi_works($doi)) {
$template->add_if_new('doi', $doi);
}
}
}
$NONE_IS_INCOMPLETE = true;
foreach ($templates as $template) {
if ($template->has('bibcode') && $template->incomplete()) {
$NONE_IS_INCOMPLETE = false;
break;
}
if (stripos($template->get('bibcode'), 'tmp') !== false || stripos($template->get('bibcode'), 'arxiv') !== false) {
$NONE_IS_INCOMPLETE = false;
break;
}
}
if ($NONE_IS_INCOMPLETE ||
AdsAbsControl::big_gave_up_yet() || !PHP_ADSABSAPIKEY) {
return;
}
// API docs at https://github.com/adsabs/adsabs-dev-api/blob/master/Search_API.ipynb
$adsabs_url = "https://" . (TRAVIS ? 'qa' : 'api')
. ".adsabs.harvard.edu/v1/search/bigquery?q=*:*"
. "&fl=arxiv_class,author,bibcode,doi,doctype,identifier,"
. "issue,page,pub,pubdate,title,volume,year&rows=2000";
report_action("Expanding from BibCodes via AdsAbs API");
$curl_opts=[
CURLOPT_URL => $adsabs_url,
CURLOPT_HTTPHEADER => ['Content-Type: big-query/csv', 'Authorization: Bearer ' . PHP_ADSABSAPIKEY],
CURLOPT_HEADER => "1",
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => "{$identifier}\n" . implode("\n", $ids),
];
$response = Bibcode_Response_Processing($curl_opts, $adsabs_url);
if (!isset($response->docs)) {
return;
}
foreach ($response->docs as $record) { // Check for remapped bibcodes
$record = (object) $record; // Make static analysis happy
if (isset($record->bibcode) && !in_array($record->bibcode, $ids, true) && isset($record->identifier)) {
foreach ($record->identifier as $identity) {
if (in_array($identity, $ids, true)) {
$record->citation_bot_new_bibcode = $record->bibcode; // save it
$record->bibcode = $identity; // unmap it
}
}
}
}
$matched_ids = [];
foreach ($response->docs as $record) {
report_info("Found match for bibcode " . bibcode_link($record->bibcode));
$matched_ids[] = $record->bibcode;
foreach($ids as $template_key => $an_id) { // Cannot use array_search since that only returns first
if (isset($record->bibcode) && strtolower($an_id) === strtolower((string) $record->bibcode)) { // BibCodes at not case-sensitive
$this_template = $templates[$template_key];
if (isset($record->citation_bot_new_bibcode)) {
$this_template->set('bibcode', (string) $record->citation_bot_new_bibcode);
$record->bibcode = $record->citation_bot_new_bibcode;
unset($record->citation_bot_new_bibcode);
} elseif ($an_id !== (string) $record->bibcode) { // Existing one is wrong case
$this_template->set('bibcode', (string) $record->bibcode);
}
if ((stripos($an_id, 'book') === false) && (stripos($an_id, 'PhD') === false)) {
process_bibcode_data($this_template, $record);
} else {
expand_book_adsabs($this_template, $record);
}
}
}
}
$unmatched_ids = array_udiff($ids, $matched_ids, 'strcasecmp');
if (count($unmatched_ids)) {
foreach ($unmatched_ids as $bad_boy) {
if (preg_match('~^(\d{4}NatSR....)E(.....)$~i', $bad_boy, $match_bad)) {
$good_boy = $match_bad[1] . '.' . $match_bad[2];
foreach ($templates as $template) {
if ($template->get('bibcode') === $bad_boy) {
$template->set('bibcode', $good_boy);
}
}
} else {
bot_debug_log("No match for bibcode identifier: " . $bad_boy);
report_warning("No match for bibcode identifier: " . $bad_boy);
}
}
}
foreach ($templates as $template) {
if ($template->blank(['year', 'date']) && preg_match('~^(\d{4}).*book.*$~', $template->get('bibcode'), $matches)) {
$template->add_if_new('year', $matches[1]); // Fail safe book code to grab a year directly from the bibcode itself
}
}
return;
}
/** @param array<string> $_ids
@param array<Template> $templates */
function query_doi_api(array $_ids, array &$templates): void { // $id not used yet // Pointer to save memory
foreach ($templates as $template) {
expand_by_doi($template);
}
return;
}
function expand_by_doi(Template $template, bool $force = false): void {
set_time_limit(120);
$template->verify_doi(); // Sometimes CrossRef has Data even when DOI is broken, so try CrossRef anyway even when return is false
$doi = $template->get_without_comments_and_placeholders('doi');
if ($doi === $template->last_searched_doi) {
return;
}
$template->last_searched_doi = $doi;
if (preg_match(REGEXP_DOI_ISSN_ONLY, $doi)) {
return;
}
if (isset(BAD_DOI_ARRAY[$doi])) { // Really bad ones that do not really exist at all
return;
}
if ($doi && preg_match('~^10\.2307/(\d+)$~', $doi)) {
$template->add_if_new('jstor', substr($doi, 8));
}
if ($doi && ($force || $template->incomplete())) {
$crossRef = query_crossref($doi);
if ($crossRef) {
if (in_array(strtolower((string) @$crossRef->article_title), BAD_ACCEPTED_MANUSCRIPT_TITLES, true)) {
return ;
}
if ($template->has('title') && trim((string) @$crossRef->article_title) && $template->get('title') !== 'none') { // Verify title of DOI matches existing data somewhat
$bad_data = true;
$new = (string) $crossRef->article_title;
if (preg_match('~^(.................+)[\.\?]\s+([IVX]+)\.\s.+$~i', $new, $matches)) {
$new = $matches[1];
$new_roman = $matches[2];
} elseif (preg_match('~^([IVX]+)\.[\s\-\—]*(.................+)$~i', $new, $matches)) {
$new = $matches[2];
$new_roman = $matches[1];
} else {
$new_roman = false;
}
foreach (THINGS_THAT_ARE_TITLES as $possible) {
if ($template->has($possible)) {
$old = $template->get($possible);
if (preg_match('~^(.................+)[\.\?]\s+([IVX]+)\.\s.+$~i', $old, $matches)) {
$old = $matches[1];
$old_roman = $matches[2];
} elseif (preg_match('~^([IVX]+)\.[\s\-\—]*(.................+)$~i', $old, $matches)) {
$old = $matches[2];
$old_roman = $matches[1];
} else {
$old_roman = false;
}
if (titles_are_similar($old, $new)) {
if ($old_roman && $new_roman) {
if ($old_roman === $new_roman) { // If they got roman numeral truncted, then must match
$bad_data = false;
break;
}
} else {
$bad_data = false;
break;
}
}
}
}
if (isset($crossRef->series_title)) {
foreach (THINGS_THAT_ARE_TITLES as $possible) { // Series === series could easily be false positive
if ($template->has($possible) && titles_are_similar(preg_replace("~# # # CITATION_BOT_PLACEHOLDER_TEMPLATE \d+ # # #~i", "�", $template->get($possible)), (string) $crossRef->series_title)) {
$bad_data = false;
break;
}
}
}
if ($bad_data) {
report_warning("CrossRef title did not match existing title: doi:" . doi_link($doi));
if (isset($crossRef->series_title)) {
report_info("Possible new title: " . str_replace("\n", "", echoable((string) $crossRef->series_title)));
}
if (isset($crossRef->article_title)) {
report_info("Possible new title: " . echoable((string) $crossRef->article_title));
}
foreach (THINGS_THAT_ARE_TITLES as $possible) {
if ($template->has($possible)) {
report_info("Existing old title: " . echoable(preg_replace("~# # # CITATION_BOT_PLACEHOLDER_TEMPLATE \d+ # # #~i", "�", $template->get($possible))));
}
}
return;
}
}
report_action("Querying CrossRef: doi:" . doi_link($doi));
if ((string) @$crossRef->volume_title === 'Professional Paper') {
unset($crossRef->volume_title);
}
if ((string) @$crossRef->series_title === 'Professional Paper') {
unset($crossRef->series_title);
}
if ($template->has('book-title')) {
unset($crossRef->volume_title);
}
if ($crossRef->volume_title && ($template->blank(WORK_ALIASES) || $template->wikiname() === 'cite book')) {
if (mb_strtolower($template->get('title')) === mb_strtolower((string) $crossRef->article_title)) {
$template->rename('title', 'chapter');
} else {
$new_title = CrossRefTitle($doi);
if ($new_title !== '' && $crossRef->article_title) {
$template->add_if_new('chapter', $new_title);
} else {
$template->add_if_new('chapter', restore_italics((string) $crossRef->article_title), 'crossref');
}
}
$template->add_if_new('title', restore_italics((string) $crossRef->volume_title), 'crossref'); // add_if_new will wikify title and sanitize the string
} else {
$new_title = CrossRefTitle($doi);
if ($new_title !== '' && $crossRef->article_title) {
$template->add_if_new('title', $new_title, 'crossref');
} else {
$template->add_if_new('title', restore_italics((string) $crossRef->article_title), 'crossref');
}
}
$template->add_if_new('series', (string) $crossRef->series_title, 'crossref'); // add_if_new will format the title for a series?
if (strpos($doi, '10.7817/jameroriesoci') === false || (string) $crossRef->year !== '2021') { // 10.7817/jameroriesoci "re-published" everything in 2021
$template->add_if_new("year", (string) $crossRef->year, 'crossref');
}
if ( $template->blank(['editor', 'editor1', 'editor-last', 'editor1-last', 'editor-last1']) // If editors present, authors may not be desired
&& $crossRef->contributors->contributor
) {
$au_i = 0;
$ed_i = 0;
// Check to see whether a single author is already set
// This might be, for example, a collaboration
$existing_author = $template->first_author();
$add_authors = $existing_author === '' || author_is_human($existing_author);
foreach ($crossRef->contributors->contributor as $author) {
if (strtoupper((string) $author->surname) === '&NA;') {
break; // No Author, leave loop now! Have only seen upper-case in the wild
}
if ((string) $author["contributor_role"] === 'editor') {
++$ed_i;
if ($ed_i < 31 && !isset($crossRef->journal_title)) {
$template->add_if_new("editor-last{$ed_i}", format_surname((string) $author->surname), 'crossref');
$template->add_if_new("editor-first{$ed_i}", format_forename((string) $author->given_name), 'crossref');
}
} elseif ((string) $author['contributor_role'] === 'author' && $add_authors) {
++$au_i;
$template->add_if_new("last{$au_i}", format_surname((string) $author->surname), 'crossref');
$template->add_if_new("first{$au_i}", format_forename((string) $author->given_name), 'crossref');
}
}
}
$template->add_if_new('isbn', (string) $crossRef->isbn, 'crossref');
$template->add_if_new('journal', (string) $crossRef->journal_title); // add_if_new will format the title
if ((int) $crossRef->volume > 0) {
$template->add_if_new('volume', (string) $crossRef->volume, 'crossref');
}
if (((strpos((string) $crossRef->issue, '-') > 0 || (int) $crossRef->issue > 1))) {
// "1" may refer to a journal without issue numbers,
// e.g. 10.1146/annurev.fl.23.010191.001111, as well as a genuine issue 1. Best ignore.
$template->add_if_new('issue', (string) $crossRef->issue, 'crossref');
}
if ($template->blank("page")) {
if ($crossRef->last_page && (strcmp((string) $crossRef->first_page, (string) $crossRef->last_page) !== 0)) {
if (strpos((string) $crossRef->first_page . (string) $crossRef->last_page, '-') === false) { // Very rarely get stuff like volume/issue/year added to pages
$template->add_if_new("pages", $crossRef->first_page . "-" . $crossRef->last_page, 'crossref'); //replaced by an endash later in script
}
} else {
if (strpos((string) $crossRef->first_page, '-') === false) { // Very rarely get stuff like volume/issue/year added to pages
$template->add_if_new("pages", (string) $crossRef->first_page, 'crossref');
}
}
}
} else {
report_info("No CrossRef record found for doi '" . echoable($doi) ."'");
expand_doi_with_dx($template, $doi);
}
}
return;
}
function query_crossref(string $doi): ?object {
static $ch = null;
if ($ch === null) {
$ch = bot_curl_init(1.0, []);
}
if (strpos($doi, '10.2307') === 0) {
return null; // jstor API is better
}
set_time_limit(120);
$url = "https://www.crossref.org/openurl/?pid=" . CROSSREFUSERNAME . "&id=doi:" . doi_encode($doi) . "&noredirect=TRUE";
curl_setopt($ch, CURLOPT_URL, $url);
for ($i = 0; $i < 2; $i++) {
$raw_xml = bot_curl_exec($ch);
if (!$raw_xml) {
sleep(1); // @codeCoverageIgnore
continue; // @codeCoverageIgnore
// Keep trying...
}
$raw_xml = preg_replace(
'~(\<year media_type=\"online\"\>\d{4}\<\/year\>\<year media_type=\"print\"\>)~',
'<year media_type="print">',
$raw_xml);
$xml = @simplexml_load_string($raw_xml);
unset($raw_xml);
if (is_object($xml) && isset($xml->query_result->body->query)) {
$result = $xml->query_result->body->query;
if ((string) @$result["status"] === "resolved") {
if (stripos($doi, '10.1515/crll') === 0) {
$volume = intval(trim((string) @$result->volume));
if ($volume > 1820) {
if (isset($result->issue)) {
$result->volume = $result->issue;
unset($result->issue);
} else {
unset($result->volume);
}
}
}
if (stripos($doi, '10.3897/ab.') === 0) {
unset($result->volume);
unset($result->page);
unset($result->issue);
}
return $result;
} else {
return null;
}
} else {
sleep(1); // @codeCoverageIgnore
// Keep trying...
}
}
report_warning("Error loading CrossRef file from DOI " . echoable($doi) . "!"); // @codeCoverageIgnore
return null; // @codeCoverageIgnore
}
function expand_doi_with_dx(Template $template, string $doi): void {
// See https://crosscite.org/docs.html for discussion of API we are using -- not all agencies resolve the same way
// https://api.crossref.org/works/$doi can be used to find out the agency
// https://www.doi.org/registration_agencies.html https://www.doi.org/RA_Coverage.html List of all ten doi granting agencies - many do not do journals
// Examples of DOI usage https://www.doi.org/demos.html
// This basically does this:
// curl -LH "Accept: application/vnd.citationstyles.csl+json" https://dx.doi.org/10.5524/100077
// Data Quality is CrossRef > DX.doi.org > Zotero
static $ch = null;
if ($ch === null) {
$ch = bot_curl_init(1.5, // can take a long time when nothing to be found
[CURLOPT_HTTPHEADER => ["Accept: application/vnd.citationstyles.csl+json"]]);
}
if (strpos($doi, '10.2307') === 0 || // jstor API is better
strpos($doi, '10.24436') === 0 || // They have horrible meta-data
strpos($doi, '10.5284/1028203') === 0) { // database
return;
}
set_time_limit(120);
/** @param array|string|int|null $data */
$try_to_add_it = static function(string $name, $data) use($template): void {
if ($template->has($name)) {
return; // Not worth updating based upon DX
}
if (is_null($data)) {
return;
}
while (is_array($data)) {
if (!isset($data['0']) || isset($data['1'])) {
return;
}
$data = $data['0'];
}
$data = (string) $data;
if ($data === '') {
return;
}
if ($data === 'Array') {
return;
}
if (str_ends_with(strtolower($data), '.pdf')) {
return;
}
if (strpos($name, 'author') !== false) { // Remove dates from names from 10.11501/ dois
if (preg_match('~^(.+), \d{3,4}\-\d{3,4}$~', $data, $matched)) {
$data = $matched[1];
}
if (preg_match('~^(.+), \d{3,4}\-$~', $data, $matched)) {
$data = $matched[1];
}
if (preg_match('~^(.+), \-\d{3,4}$~', $data, $matched)) {
$data = $matched[1];
}
}
$template->add_if_new($name, $data, 'dx');
return;
};
if (!$doi) {
return;
}
/** @psalm-taint-escape ssrf */
$doi = trim($doi);
curl_setopt($ch, CURLOPT_URL, 'https://doi.org/' . $doi);
report_action("Querying dx.doi.org: doi:" . doi_link($doi));
try {
$data = bot_curl_exec($ch);
} catch (Exception $e) { // @codeCoverageIgnoreStart
$template->mark_inactive_doi();
return;
} // @codeCoverageIgnoreEnd
if ($data === "" || stripos($data, 'DOI Not Found') !== false || stripos($data, 'DOI prefix') !== false) {
$template->mark_inactive_doi();
return;
}
$json = @json_decode($data, true);
unset($data);
if($json === false || $json === null) {
return;
}
// BE WARNED: this code uses the "@$var" method.
// If the variable is not set, then PHP just passes null, then that is interpreted as a empty string
if ($template->blank(['date', 'year'])) {
$try_to_add_it('year', @$json['issued']['date-parts']['0']['0']);
$try_to_add_it('year', @$json['created']['date-parts']['0']['0']);
$try_to_add_it('year', @$json['published-print']['date-parts']['0']['0']);
}
$try_to_add_it('issue', @$json['issue']);
$try_to_add_it('pages', @$json['pages']);
$try_to_add_it('volume', @$json['volume']);
$try_to_add_it('isbn', @$json['ISBN']['0']);
$try_to_add_it('isbn', @$json['isbn-type']['0']['value']);
if (isset($json['author'])) {
$i = 0;
foreach ($json['author'] as $auth) {
$i += 1;
$full_name = mb_strtolower(trim((string) @$auth['given'] . ' ' . (string) @$auth['family'] . (string) @$auth['literal']));
if (in_array($full_name, BAD_AUTHORS, true)) {
break;
}
if (((string) @$auth['family'] === '') && ((string) @$auth['given'] !== '')) {
$try_to_add_it('author' . (string) $i, @$auth['given']); // First name without last name. Probably an organization or chinese/korean/japanese name
} else {
$try_to_add_it('last' . (string) $i, @$auth['family']);
$try_to_add_it('first' . (string) $i, @$auth['given']);
$try_to_add_it('author' . (string) $i, @$auth['literal']);
}
}
}
// Publisher hiding as journal name - defective data
if (isset($json['container-title']) && isset($json['publisher']) && ($json['publisher'] === $json['container-title'])) {
unset($json['container-title']); // @codeCoverageIgnore
}
$type = (string) @$json['type'];
if ($type === 'article-journal' ||
$type === 'journal-article' ||
$type === 'article' ||
$type === 'proceedings-article' ||
$type === 'conference-paper' ||
$type === 'entry' ||
($type === '' && (isset($json['container-title']) || isset($json['issn']['0'])))) {
$try_to_add_it('journal', @$json['container-title']);
$try_to_add_it('title', @$json['title']);
$try_to_add_it('issn', @$json['issn']); // Will not add if journal is set
} elseif ($type === 'journal-issue') { // Very rare: Do not add "title": should be blank anyway. Got this once from DOI:10.7592/fejf2015.62
$try_to_add_it('journal', @$json['container-title']); // @codeCoverageIgnore
$try_to_add_it('issn', @$json['issn']); // @codeCoverageIgnore
} elseif ($type === 'journal') { // Very rare: Do not add "title": should be blank anyway. Got this once from DOI:10.1007/13539.2190-6009 and DOI:10.14296/rih/issn.1749.8155
$try_to_add_it('issn', @$json['issn']); // @codeCoverageIgnore
} elseif ($type === 'reference-entry' || $type === 'component') { // Very rare: reference-entry from 10.1002/14356007.a02_115.pub2, component from 10.3998/mpub.11422327.cmp.11
$try_to_add_it('work', @$json['container-title']); // @codeCoverageIgnore
$try_to_add_it('title', @$json['title']); // @codeCoverageIgnore
} elseif ($type === 'monograph' || $type === 'book' || $type === 'edited-book') {
$try_to_add_it('title', @$json['title']);
$try_to_add_it('title', @$json['container-title']);// Usually not set, but just in case this instead of title is set
$try_to_add_it('location', @$json['publisher-location']);
$try_to_add_it('publisher', @$json['publisher']);
} elseif ($type === 'reference-book') { // VERY rare
$try_to_add_it('title', @$json['title']); // @codeCoverageIgnore
$try_to_add_it('title', @$json['container-title']); // @codeCoverageIgnore
$try_to_add_it('chapter', @$json['original-title']); // @codeCoverageIgnore
$try_to_add_it('location', @$json['publisher-location']); // @codeCoverageIgnore
$try_to_add_it('publisher', @$json['publisher']); // @codeCoverageIgnore
} elseif ($type === 'chapter' || $type === 'book-chapter' || $type === 'book-section') {
$try_to_add_it('title', @$json['container-title']);
$try_to_add_it('chapter', @$json['title']);
$try_to_add_it('location', @$json['publisher-location']);
$try_to_add_it('publisher', @$json['publisher']);
} elseif ($type === 'other') {
if (isset($json['container-title'])) {
$try_to_add_it('title', @$json['container-title']);
$try_to_add_it('chapter', @$json['title']);
} else {
$try_to_add_it('title', @$json['title']);
}
$try_to_add_it('location', @$json['publisher-location']);
$try_to_add_it('publisher', @$json['publisher']);
} elseif ($type === 'dataset') {
$try_to_add_it('type', 'Data Set');
$try_to_add_it('title', @$json['title']);
$try_to_add_it('location', @$json['publisher-location']);
$try_to_add_it('publisher', @$json['publisher']);
if (!isset($json['categories']['1']) &&
(($template->wikiname() === 'cite book') || $template->blank(WORK_ALIASES))) { // No journal/magazine set and can convert to book
$try_to_add_it('chapter', @$json['categories']['0']); // Not really right, but there is no cite data set template
}
} elseif ($type === '' || $type === 'graphic' || $type === 'report' || $type === 'report-component') { // Add what we can where we can
$try_to_add_it('title', @$json['title']);
$try_to_add_it('location', @$json['publisher-location']);
$try_to_add_it('publisher', @$json['publisher']);
} elseif ($type === 'thesis' || $type === 'dissertation' || $type === 'dissertation-thesis') {
$template->change_name_to('cite thesis');
$try_to_add_it('title', @$json['title']);
$try_to_add_it('location', @$json['publisher-location']);
$try_to_add_it('publisher', @$json['publisher']);
if (stripos(@$json['URL'], 'hdl.handle.net')) {
$template->get_identifiers_from_url($json['URL']);
}
} elseif ($type === 'posted-content' || $type === 'grant' || $type === 'song' || $type === 'motion_picture' || $type === 'patent' || $type === 'database') { // posted-content is from bioRxiv
$try_to_add_it('title', @$json['title']);
} else {
$try_to_add_it('title', @$json['title']); // @codeCoverageIgnore
if (!HTML_OUTPUT) {
print_r($json); // @codeCoverageIgnore
}
report_minor_error('dx.doi.org returned unexpected data type ' . echoable($type) . ' for ' . doi_link($doi)); // @codeCoverageIgnore
}
return;
}
function expand_by_jstor(Template $template): void {
static $ch = null;
if ($ch === null) {
$ch = bot_curl_init(1.0, []);
}
set_time_limit(120);
if ($template->incomplete() === false) {
return;
}
if ($template->has('jstor')) {
$jstor = trim($template->get('jstor'));
} elseif(preg_match('~^https?://(?:www\.|)jstor\.org/stable/(.*)$~', $template->get('url'), $match)) {
$jstor = $match[1];
} else {
return;
}
if (preg_match('~^(.*)(?:\?.*)$~', $jstor, $match)) {
$jstor = $match[1]; // remove ?seq= stuff
}
/** @psalm-taint-escape ssrf */
$jstor = trim($jstor);
if (strpos($jstor, ' ') !== false) {
return ; // Comment/template found
}
if (substr($jstor, 0, 1) === 'i') {
return ; // We do not want i12342 kind
}
curl_setopt($ch, CURLOPT_URL, 'https://www.jstor.org/citation/ris/' . $jstor);
$dat = bot_curl_exec($ch);
if ($dat === '') {
report_info("JSTOR API returned nothing for ". jstor_link($jstor)); // @codeCoverageIgnore
return; // @codeCoverageIgnore
}
if (stripos($dat, 'No RIS data found for') !== false) {
report_info("JSTOR API found nothing for ". jstor_link($jstor)); // @codeCoverageIgnore
return; // @codeCoverageIgnore
}
if (stripos($dat, 'Block Reference') !== false) {
report_info("JSTOR API blocked bot for ". jstor_link($jstor)); // @codeCoverageIgnore
return; // @codeCoverageIgnore
}
if (stripos($dat, 'A problem occurred trying to deliver RIS data') !== false) {
report_info("JSTOR API had a problem for ". jstor_link($jstor));
return;
}
if ($template->has('title')) {
$bad_data = true;
$ris = explode("\n", html_entity_decode($dat, ENT_COMPAT | ENT_HTML401, 'UTF-8'));
foreach ($ris as $ris_line) {
$ris_part = explode(" - ", $ris_line . " ", 2);
if (!isset($ris_part[1])) {
$ris_part[0] = ""; // Ignore
}
switch (trim($ris_part[0])) {
case "T1":
case "TI":
case "T2":
case "BT":
$new_title = trim($ris_part[1]);
foreach (THINGS_THAT_ARE_TITLES as $possible) {
if ($template->has($possible) && titles_are_similar($template->get($possible), $new_title)) {
$bad_data = false;
}
}
break;
default:
break;
}
}
if ($bad_data) { // Now for TI: T1 existing titles (title followed by sub-title)
$got_count = 0;
$new_title = ': ';
foreach ($ris as $ris_line) {
$ris_part = explode(" - ", $ris_line . " ", 2);
if (!isset($ris_part[1])) {
$ris_part[0] = ""; // Ignore
}
switch (trim($ris_part[0])) {
case "T1":
$new_title .= trim($ris_part[1]);
$got_count += 10;
break;
case "TI":
$new_title = trim($ris_part[1]) . $new_title;