forked from ms609/citation-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpandFns.php
3300 lines (3150 loc) · 143 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
<?php
declare(strict_types=1);
require_once 'constants.php'; // @codeCoverageIgnore
require_once 'Template.php'; // @codeCoverageIgnore
require_once 'big_jobs.php'; // @codeCoverageIgnore
final class HandleCache {
// Greatly speed-up by having one array of each kind and only look for hash keys, not values
private const MAX_CACHE_SIZE = 100000;
public const MAX_HDL_SIZE = 1024;
private const BAD_DOI_ARRAY = [
'10.1126/science' => true,
'' => true,
'10.7556/jaoa' => true,
'10.1267/science.040579197' => true,
'10.0000/Rubbish_bot_failure_test' => true,
'10.0000/Rubbish_bot_failure_test2' => true,
'10.0000/Rubbish_bot_failure_test.x' => true,
];
/** @var array<bool> $cache_active */
public static array $cache_active = []; // DOI is in CrossRef and works
/** @var array<bool> $cache_inactive */
public static array $cache_inactive = []; // DOI either is not in CrossRef or does not work
/** @var array<bool> $cache_good */
public static array $cache_good = []; // DOI works
/** @var array<string> $cache_hdl_loc */
public static array $cache_hdl_loc = []; // Final HDL location URL
/** @var array<bool> $cache_hdl_bad */
public static array $cache_hdl_bad = self::BAD_DOI_ARRAY; // HDL/DOI does not resolve to anything
/** @var array<bool> $cache_hdl_null */
public static array $cache_hdl_null = []; // HDL/DOI resolves to null
public static function check_memory_use(): void {
$usage = count(self::$cache_inactive) +
count(self::$cache_active) +
count(self::$cache_good) +
count(self::$cache_hdl_bad) +
10*count(self::$cache_hdl_loc) + // These include a path too
count(self::$cache_hdl_null);
if ($usage > self::MAX_CACHE_SIZE) {
self::free_memory(); // @codeCoverageIgnore
}
}
public static function free_memory(): void {
self::$cache_active = [];
self::$cache_inactive = [];
self::$cache_good = [];
self::$cache_hdl_loc = [];
self::$cache_hdl_bad = self::BAD_DOI_ARRAY;
self::$cache_hdl_null = [];
gc_collect_cycles();
}
}
// ============================================= DOI functions ======================================
function doi_active(string $doi): ?bool {
$doi = trim($doi);
if (isset(HandleCache::$cache_active[$doi])) {
return true;
}
if (isset(HandleCache::$cache_inactive[$doi])) {
return false;
}
$works = doi_works($doi);
if ($works !== true) {
return $works;
}
$works = is_doi_active($doi);
if ($works === null) { // Temporary problem - do not cache
return null; // @codeCoverageIgnore
}
if ($works === false) {
HandleCache::$cache_inactive[$doi] = true;
return false;
}
HandleCache::$cache_active[$doi] = true;
return true;
}
function doi_works(string $doi): ?bool {
$doi = trim($doi);
if (strlen($doi) > HandleCache::MAX_HDL_SIZE) {
return null; // @codeCoverageIgnore
}
if (isset(HandleCache::$cache_good[$doi])) {
return true;
}
if (isset(HandleCache::$cache_hdl_bad[$doi])) {
return false;
}
if (isset(HandleCache::$cache_hdl_null[$doi])) {
return null; // @codeCoverageIgnore
}
HandleCache::check_memory_use();
$works = is_doi_works($doi);
if ($works === null) { // These are unexpected nulls
HandleCache::$cache_hdl_null[$doi] = true; // @codeCoverageIgnore
return null; // @codeCoverageIgnore
}
if ($works === false) {
HandleCache::$cache_hdl_bad[$doi] = true;
return false;
}
HandleCache::$cache_good[$doi] = true;
return true;
}
function is_doi_active(string $doi): ?bool {
static $ch = null;
if ($ch === null) {
$ch = bot_curl_init(1.0, [
CURLOPT_HEADER => "1",
CURLOPT_NOBODY => "0",
CURLOPT_USERAGENT => BOT_CROSSREF_USER_AGENT,
]);
}
$doi = trim($doi);
$url = "https://api.crossref.org/v1/works/" . doi_encode($doi) . "?mailto=".CROSSREFUSERNAME; // do not encode crossref email
curl_setopt($ch, CURLOPT_URL, $url);
$return = bot_curl_exec($ch);
$header_length = (int) curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($return, 0, $header_length);
$body = substr($return, $header_length);
$response_code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($header === "" || ($response_code === 503) || ($response_code === 429)) {
sleep(4); // @codeCoverageIgnoreStart
if ($response_code === 429) sleep(4); // WE are getting blocked
$return = bot_curl_exec($ch);
$response_code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$header_length = (int) curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($return, 0, $header_length);
$body = substr($return, $header_length); // @codeCoverageIgnoreEnd
}
if ($response_code === 429) { // WE are still getting blocked
sleep(10); // @codeCoverageIgnore
}
if ($header === "" || ($response_code === 503) || ($response_code === 429)) {
return null; // @codeCoverageIgnore
}
if ($body === 'Resource not found.'){
return false;
}
if ($response_code === 200) {
return true;
}
if ($response_code === 404) { // @codeCoverageIgnoreStart
return false;
}
$err = "CrossRef server error loading headers for DOI " . echoable($doi . " : " . (string) $response_code);
bot_debug_log($err);
report_warning($err);
return null; // @codeCoverageIgnoreEnd
}
function throttle_dx (): void {
static $last = 0.0;
$min_time = 40000.0;
$now = microtime(true);
$left = (int) ($min_time - ($now - $last));
if ($left > 0 && $left < $min_time) {
usleep($left); // less than min_time is paranoia, but do not want an inifinite delay
}
$last = $now;
}
function throttle_archive (): void {
static $last = 0.0;
$min_time = 1000000.0; // One second
$now = microtime(true);
$left = (int) ($min_time - ($now - $last));
if ($left > 0 && $left < $min_time) {
usleep($left); // less than min_time is paranoia, but do not want an inifinite delay
}
$last = $now;
}
function is_doi_works(string $doi): ?bool {
$doi = trim($doi);
// And now some obvious fails
if (strpos($doi, '/') === false){
return false;
}
if (strpos($doi, 'CITATION_BOT_PLACEHOLDER') !== false) {
return false;
}
if (preg_match('~^10\.1007/springerreference~', $doi)) {
return false;
}
if (!preg_match('~^([^\/]+)\/~', $doi, $matches)) {
return false;
}
if (isset(NULL_DOI_ANNOYING[$doi])) {
return false;
}
if (preg_match('~^10\.4435\/BSPI\.~i', $doi)) {
return false; // TODO: old ones like 10.4435/BSPI.2018.11 are casinos, and new one like 10.4435/BSPI.2024.06 go to the main page
}
$registrant = $matches[1];
// TODO this will need updated over time. See registrant_err_patterns on https://en.wikipedia.org/wiki/Module:Citation/CS1/Identifiers
// 17 August 2024 version is last check
if (strpos($registrant, '10.') === 0) { // We have to deal with valid handles in the DOI field - very rare, so only check actual DOIs
$registrant = substr($registrant, 3);
if (preg_match('~^[^1-3]\d\d\d\d\.\d\d*$~', $registrant) || // 5 digits with subcode (0xxxx, 40000+); accepts: 10000–39999
preg_match('~^[^1-7]\d\d\d\d$~', $registrant) || // 5 digits without subcode (0xxxx, 60000+); accepts: 10000–69999
preg_match('~^[^1-9]\d\d\d\.\d\d*$~', $registrant) || // 4 digits with subcode (0xxx); accepts: 1000–9999
preg_match('~^[^1-9]\d\d\d$~', $registrant) || // 4 digits without subcode (0xxx); accepts: 1000–9999
preg_match('~^\d\d\d\d\d\d+~', $registrant) || // 6 or more digits
preg_match('~^\d\d?\d?$~', $registrant) || // less than 4 digits without subcode (3 digits with subcode is legitimate)
preg_match('~^\d\d?\.[\d\.]+~', $registrant) || // 1 or 2 digits with subcode
$registrant === '5555' || // test registrant will never resolve
preg_match('~[^\d\.]~', $registrant)) { // any character that isn't a digit or a dot
return false;
}
}
throttle_dx();
$url = "https://doi.org/" . doi_encode($doi);
$headers_test = get_headers_array($url);
if ($headers_test === false) {
if (preg_match('~^10\.1038/nature\d{5}$~i', $doi)) {
return false;
}
if (isset(NULL_DOI_LIST[$doi])) {
return false;
}
foreach (NULL_DOI_STARTS_BAD as $bad_start) {
if (stripos($doi, $bad_start) === 0) {
return false; // all gone
}
}
if (isset(NULL_DOI_BUT_GOOD[$doi])) {
return true; // @codeCoverageIgnoreStart
}
$headers_test = get_headers_array($url);
bot_debug_log('Got null for HDL: ' . str_ireplace(['<', '>'], ['<', '>'], echoable($doi))); // @codeCoverageIgnoreEnd
}
if ($headers_test === false) {
$headers_test = get_headers_array($url); // @codeCoverageIgnore
}
if ($headers_test === false) { // most likely bad - note that null means do not add or remove doi-broken-date from pages
return null; // @codeCoverageIgnore
}
if (stripos($doi, '10.1126/scidip.') === 0) {
if ((string) @$headers_test['1'] === 'HTTP/1.1 404 Forbidden') { // https://doi.org/10.1126/scidip.ado5059
unset($headers_test['1']); // @codeCoverageIgnore
}
}
if (interpret_doi_header($headers_test) !== false) {
return interpret_doi_header($headers_test);
}
// Got 404 - try again, since we cache this and add doi-broken-date to pages, we should be double sure
$headers_test = get_headers_array($url);
/** We trust previous failure, so fail and null are both false */
if ($headers_test === false) {
return false;
}
return (bool) interpret_doi_header($headers_test);
}
/** @param array<string|array<string>> $headers_test */
function interpret_doi_header(array $headers_test): ?bool {
if (empty($headers_test['Location']) && empty($headers_test['location'])) {
return false; // leads nowhere
}
/** @psalm-suppress InvalidArrayOffset */
$resp0 = (string) @$headers_test['0'];
/** @psalm-suppress InvalidArrayOffset */
$resp1 = (string) @$headers_test['1'];
/** @psalm-suppress InvalidArrayOffset */
$resp2 = (string) @$headers_test['2'];
if (stripos($resp0 . $resp1 . $resp2, '404 Not Found') !== false || stripos($resp0 . $resp1 . $resp2, 'HTTP/1.1 404') !== false) {
return false; // Bad
}
if (stripos($resp0, '302 Found') !== false || stripos($resp0, 'HTTP/1.1 302') !== false) {
return true; // Good
}
if (stripos((string) @json_encode($headers_test), 'dtic.mil') !== false) { // grumpy
return true; // @codeCoverageIgnore
}
if (stripos($resp0, '301 Moved Permanently') !== false || stripos($resp0, 'HTTP/1.1 301') !== false) { // Could be DOI change or bad prefix
if (stripos($resp1, '302 Found') !== false || stripos($resp1, 'HTTP/1.1 302') !== false) {
return true; // Good
} elseif (stripos($resp1, '301 Moved Permanently') !== false || stripos($resp1, 'HTTP/1.1 301') !== false) { // @codeCoverageIgnoreStart
if (stripos($resp2, '200 OK') !== false || stripos($resp2, 'HTTP/1.1 200') !== false) {
return true;
} else {
return false;
}
} else {
return false;
}
}
report_minor_error("Unexpected response in is_doi_works " . echoable($resp0));
return null; // @codeCoverageIgnoreEnd
}
/** @param array<string|array<string>> $headers_test */
function get_loc_from_hdl_header(array $headers_test): ?string {
if (isset($headers_test['Location'][0]) && is_array(@$headers_test['Location'])) { // Should not be an array, but on rare occasions we get one
return (string) $headers_test['Location'][0]; // @codeCoverageIgnore
} elseif (isset($headers_test['location'][0]) && is_array(@$headers_test['location'])) {
return (string) $headers_test['location'][0]; // @codeCoverageIgnore
} elseif (isset($headers_test['location'])) {
return (string) $headers_test['location'];
} elseif (isset($headers_test['Location'])) { // @codeCoverageIgnore
return (string) $headers_test['Location']; // @codeCoverageIgnore
} else { // @codeCoverageIgnoreStart
bot_debug_log("Got weird header from handle: " . echoable(print_r($headers_test, true))); // Is this even possible
return null;
} // @codeCoverageIgnoreEnd
}
/** @param array<string> $_ids
@param array<Template> $templates */
function query_jstor_api(array $_ids, array &$templates): void { // Pointer to save memory
foreach ($templates as $template) {
expand_by_jstor($template);
}
}
function sanitize_doi(string $doi): string {
if (substr($doi, -1) === '.') {
$try_doi = substr($doi, 0, -1);
if (doi_works($try_doi)) { // If it works without dot, then remove it
$doi = $try_doi;
} elseif (doi_works($try_doi . '.x')) { // Missing the very common ending .x
$doi = $try_doi . '.x';
} elseif (!doi_works($doi)) { // It does not work, so just remove it to remove wikipedia error. It's messed up
$doi = $try_doi;
}
}
$doi = safe_preg_replace('~^https?://d?x?\.?doi\.org/~i', '', $doi); // Strip URL part if present
$doi = safe_preg_replace('~^/?d?x?\.?doi\.org/~i', '', $doi);
$doi = safe_preg_replace('~^doi:~i', '', $doi); // Strip doi: part if present
$doi = str_replace("+", "%2B", $doi); // plus signs are valid DOI characters, but in URLs are "spaces"
$doi = str_replace(HTML_ENCODE_DOI, HTML_DECODE_DOI, trim(urldecode($doi)));
$pos = (int) strrpos($doi, '.');
if ($pos) {
$extension = (string) substr($doi, $pos);
if (in_array(strtolower($extension), ['.htm', '.html', '.jpg', '.jpeg', '.pdf', '.png', '.xml', '.full'], true)) {
$doi = (string) substr($doi, 0, $pos);
}
}
$pos = (int) strrpos($doi, '#');
if ($pos) {
$extension = (string) substr($doi, $pos);
if (strpos(strtolower($extension), '#page_scan_tab_contents') === 0) {
$doi = (string) substr($doi, 0, $pos);
}
}
$pos = (int) strrpos($doi, ';');
if ($pos) {
$extension = (string) substr($doi, $pos);
if (strpos(strtolower($extension), ';jsessionid') === 0) {
$doi = (string) substr($doi, 0, $pos);
}
}
$pos = (int) strrpos($doi, '/');
if ($pos) {
$extension = (string) substr($doi, $pos);
if (in_array(strtolower($extension), ['/abstract', '/full', '/pdf', '/epdf', '/asset/', '/summary', '/short', '/meta', '/html', '/'], true)) {
$doi = (string) substr($doi, 0, $pos);
}
}
$new_doi = str_replace('//', '/', $doi);
if ($new_doi !== $doi) {
if (doi_works($new_doi) || !doi_works($doi)) {
$doi = $new_doi; // Double slash DOIs do exist
}
}
// And now for 10.1093 URLs
// The add chapter/page stuff after the DOI in the URL and it looks like part of the DOI to us
// Things like 10.1093/oxfordhb/9780199552238.001.0001/oxfordhb-9780199552238-e-003 and 10.1093/acprof:oso/9780195304923.001.0001/acprof-9780195304923-chapter-7
if (strpos($doi, '10.1093') === 0 && doi_works($doi) === false) {
if (preg_match('~^(10\.1093/oxfordhb.+)(?:/oxfordhb.+)$~', $doi, $match) ||
preg_match('~^(10\.1093/acprof.+)(?:/acprof.+)$~', $doi, $match) ||
preg_match('~^(10\.1093/acref.+)(?:/acref.+)$~', $doi, $match) ||
preg_match('~^(10\.1093/ref:odnb.+)(?:/odnb.+)$~', $doi, $match) ||
preg_match('~^(10\.1093/ww.+)(?:/ww.+)$~', $doi, $match) ||
preg_match('~^(10\.1093/anb.+)(?:/anb.+)$~', $doi, $match)) {
$new_doi = $match[1];
if (doi_works($new_doi)) {
$doi = $new_doi;
}
}
}
return $doi;
}
/* extract_doi
* Returns an array containing:
* 0 => text containing a DOI, possibly encoded, possibly with additional text
* 1 => the decoded DOI
*/
/** @return array<string> */
function extract_doi(string $text): array {
if (preg_match(
"~(10\.\d{4}\d?(/|%2[fF])..([^\s\|\"\?&>]|&l?g?t;|<[^\s\|\"\?&]*>)+)~",
$text, $match)) {
$doi = $match[1];
if (preg_match(
"~^(.*?)(/abstract|/e?pdf|/full|/figure|/default|</span>|[\s\|\"\?]|</).*+$~",
$doi, $new_match)) {
$doi = $new_match[1];
}
$doi_candidate = sanitize_doi($doi);
while (preg_match(REGEXP_DOI, $doi_candidate) && !doi_works($doi_candidate)) {
$last_delimiter = 0;
foreach (['/', '.', '#', '?'] as $delimiter) {
$delimiter_position = (int) strrpos($doi_candidate, $delimiter);
$last_delimiter = ($delimiter_position > $last_delimiter) ? $delimiter_position : $last_delimiter;
}
$doi_candidate = substr($doi_candidate, 0, $last_delimiter);
}
if (doi_works($doi_candidate)) {
$doi = $doi_candidate;
}
if (!doi_works($doi) && !doi_works(sanitize_doi($doi))) { // Reject URLS like ...../25.10.2015/2137303/default.htm
if (preg_match('~^10\.([12]\d{3})~', $doi, $new_match)) {
if (preg_match("~[0-3][0-9]\.10\." . $new_match[1] . "~", $text)) {
return ['', ''];
}
}
}
return [$match[0], sanitize_doi($doi)];
}
return ['', ''];
}
// ============================================= String/Text functions ======================================
function wikify_external_text(string $title): string {
$replacement = [];
$placeholder = [];
$title = safe_preg_replace_callback('~(?:\$\$)([^\$]+)(?:\$\$)~iu',
static function (array $matches): string {
return "<math>" . $matches[1] . "</math>";
},
$title);
if (preg_match_all("~<(?:mml:)?math[^>]*>(.*?)</(?:mml:)?math>~", $title, $matches)) {
$num_matches = count($matches[0]);
for ($i = 0; $i < $num_matches; $i++) {
$replacement[$i] = '<math>' .
str_replace(array_keys(MML_TAGS), array_values(MML_TAGS),
str_replace(['<mml:', '</mml:'], ['<', '</'], $matches[1][$i]))
. '</math>';
$placeholder[$i] = sprintf(TEMP_PLACEHOLDER, $i);
// Need to use a placeholder to protect contents from URL-safening
$title = str_replace($matches[0][$i], $placeholder[$i], $title);
}
$title = str_replace(['<mo stretchy="false">', "<mo stretchy='false'>"], '', $title);
}
if (mb_substr($title, -6) === " ") {
$title = mb_substr($title, 0, -6);
}
if (mb_substr($title, -10) === "&nbsp;") {
$title = mb_substr($title, 0, -10);
}
// Sometimes stuff is encoded more than once
$title = html_entity_decode($title, ENT_COMPAT | ENT_HTML401, "UTF-8");
$title = html_entity_decode($title, ENT_COMPAT | ENT_HTML401, "UTF-8");
$title = html_entity_decode($title, ENT_COMPAT | ENT_HTML401, "UTF-8");
$title = safe_preg_replace("~\s+~", " ", $title); // Remove all white spaces before
if (mb_substr($title, -6) === " ") {
$title = mb_substr($title, 0, -6); // @codeCoverageIgnore
}
// Special code for ending periods
while (mb_substr($title, -2) === "..") {
$title = mb_substr($title, 0, -1);
}
if (mb_substr($title, -1) === ".") { // Ends with a period
if (mb_substr_count($title, '.') === 1) { // Only one period
$title = mb_substr($title, 0, -1);
} elseif (mb_substr_count($title, ' ') === 0) { // No spaces at all and multiple periods
/** do nothing */
} else { // Multiple periods and at least one space
$last_word_start = (int) mb_strrpos(' ' . $title, ' ');
$last_word = mb_substr($title, $last_word_start);
if (mb_substr_count($last_word, '.') === 1 && // Do not remove if something like D.C. or D. C.
mb_substr($title, $last_word_start-2, 1) !== '.') {
$title = mb_substr($title, 0, -1);
}
}
}
$title = safe_preg_replace('~[\*]$~', '', $title);
$title = title_capitalization($title, true);
$htmlBraces = ["<", ">"];
$angleBraces = ["<", ">"];
$title = str_ireplace($htmlBraces, $angleBraces, $title);
$originalTags = ['<title>', '</title>', '</ title>', 'From the Cover: ', '<SCP>', '</SCP>', '</ SCP>', '<formula>', '</formula>', '<roman>', '</roman>', ];
$wikiTags = ['', '', '', '', '', '', '', '', '', '', ''];
$title = str_ireplace($originalTags, $wikiTags, $title);
$originalTags = ['<inf>', '</inf>'];
$wikiTags = ['<sub>', '</sub>'];
$title = str_ireplace($originalTags, $wikiTags, $title);
$originalTags = ['.<br>', '.</br>', '.</ br>', '.<p>', '.</p>', '.</ p>', '.<strong>', '.</strong>', '.</ strong>'];
$wikiTags = ['. ','. ','. ','. ','. ','. ','. ','. ','. '];
$title = str_ireplace($originalTags, $wikiTags, $title);
$originalTags = ['<br>', '</br>', '</ br>', '<p>', '</p>', '</ p>', '<strong>', '</strong>', '</ strong>'];
$wikiTags = ['. ','. ','. ','. ','. ','. ', ' ',' ',' '];
$title = trim(str_ireplace($originalTags, $wikiTags, $title));
if (preg_match("~^\. (.+)$~", $title, $matches)) {
$title = trim($matches[1]);
}
if (preg_match("~^(.+)(\.\s+)\.$~s", $title, $matches)) {
$title = trim($matches[1] . ".");
}
$title_orig = '';
while ($title !== $title_orig) {
$title_orig = $title; // Might have to do more than once. The following do not allow < within the inner match since the end tag is the same :-( and they might nest or who knows what
$title = safe_preg_replace_callback('~(?:<Emphasis Type="Italic">)([^<]+)(?:</Emphasis>)~iu',
static function (array $matches): string {
return "''" . $matches[1] . "''";
},
$title);
$title = safe_preg_replace_callback('~(?:<Emphasis Type="Bold">)([^<]+)(?:</Emphasis>)~iu',
static function (array $matches): string {
return "'''" . $matches[1] . "'''";
},
$title);
$title = safe_preg_replace_callback('~(?:<em>)([^<]+)(?:</em>)~iu',
static function (array $matches): string {
return "''" . $matches[1] . "''";
},
$title);
$title = safe_preg_replace_callback('~(?:<i>)([^<]+)(?:</i>)~iu',
static function (array $matches): string {
return "''" . $matches[1] . "''";
},
$title);
$title = safe_preg_replace_callback('~(?:<italics>)([^<]+)(?:</italics>)~iu',
static function (array $matches): string {
return "''" . $matches[1] . "''";
},
$title);
}
if (mb_substr($title, -1) === '.') {
$title = sanitize_string($title) . '.';
} else {
$title = sanitize_string($title);
}
$title = str_replace([''], [' '], $title); // Funky spaces
$title = str_ireplace('<p class="HeadingRun \'\'In\'\'">', ' ', $title);
$title = str_ireplace([' ', ' ', ' '], [' ', ' ', ' '], $title);
if (mb_strlen($title) === strlen($title)) {
$title = trim($title, " \t\n\r\0\x0B\xc2\xa0");
} else {
$title = trim($title, " \t\n\r\0");
}
$num_replace = count($replacement);
for ($i = 0; $i < $num_replace; $i++) {
$title = str_ireplace($placeholder[$i], $replacement[$i], $title); // @phan-suppress-current-line PhanTypePossiblyInvalidDimOffset
}
foreach (['<msup>', '<msub>', '<mroot>', '<msubsup>', '<munderover>', '<mrow>', '<munder>', '<mtable>', '<mtr>', '<mtd>'] as $mathy) {
if (strpos($title, $mathy) !== false) {
return '<nowiki>' . $title . '</nowiki>';
}
}
return $title;
}
function restore_italics (string $text): string {
$text = trim(str_replace([' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' '], $text));
// <em> tags often go missing around species names in CrossRef
/** $old = $text; */
$text = str_replace(ITALICS_HARDCODE_IN, ITALICS_HARDCODE_OUT, $text); // Ones to always do, since they keep popping up in our logs
$text = str_replace("xAzathioprine therapy for patients with systemic lupus erythematosus", "Azathioprine therapy for patients with systemic lupus erythematosus", $text); // Annoying stupid bad data
$text = trim(str_replace([' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' '], $text));
while (preg_match('~([a-z])(' . ITALICS_LIST . ')([A-Z\-\?\:\.\)\(\,]|species|genus| in| the|$)~', $text, $matches)) {
if (in_array($matches[3], [':', '.', '-', ','], true)) {
$pad = "";
} else {
$pad = " ";
}
$text = str_replace($matches[0], $matches[1] . " ''" . $matches[2] . "''" . $pad . $matches[3], $text);
}
$text = trim(str_replace([' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' '], $text));
$padded = ' '. $text . ' ';
if (str_replace(CAMEL_CASE, '', $padded) !== $padded) {
return $text; // Words with capitals in the middle, but not the first character
}
$new = safe_preg_replace('~([a-z]+)([A-Z][a-z]+\b)~', "$1 ''$2''", $text);
if ($new === $text) {
return $text;
}
// Do not return $new, since we are wrong much more often here than wrong with new CrossRef Code
bot_debug_log('restore_italics: ' . $text . ' SHOULD BE ' . $new); // @codeCoverageIgnore
return $text; // @codeCoverageIgnore
}
function sanitize_string(string $str): string {
// ought only be applied to newly-found data.
if ($str === '') {
return '';
}
if (strtolower(trim($str)) === 'science (new york, n.y.)') {
return 'Science';
}
if (preg_match('~^\[http.+\]$~', $str)) {
return $str; // It is a link out
}
$replacement = [];
$placeholder = [];
$math_templates_present = preg_match_all("~<\s*math\s*>.*<\s*/\s*math\s*>~", $str, $math_hits);
if ($math_templates_present) {
$num_maths = count($math_hits[0]);
for ($i = 0; $i < $num_maths; $i++) {
$replacement[$i] = $math_hits[0][$i];
$placeholder[$i] = sprintf(TEMP_PLACEHOLDER, $i);
}
$str = str_replace($replacement, $placeholder, $str);
}
$dirty = ['[', ']', '|', '{', '}', " what�s "];
$clean = ['[', ']', '|', '{', '}', " what's "];
$str = trim(str_replace($dirty, $clean, safe_preg_replace('~[;.,]+$~', '', $str)));
if ($math_templates_present) {
$str = str_replace($placeholder, $replacement, $str);
}
return $str;
}
function truncate_publisher(string $p): string {
return safe_preg_replace("~\s+(group|inc|ltd|publishing)\.?\s*$~i", "", $p);
}
function str_remove_irrelevant_bits(string $str): string {
if ($str === '') {
return '';
}
$str = trim($str);
$str = str_replace('�', 'X', $str);
$str = safe_preg_replace(REGEXP_PLAIN_WIKILINK, "$1", $str); // Convert [[X]] wikilinks into X
$str = safe_preg_replace(REGEXP_PIPED_WIKILINK, "$2", $str); // Convert [[Y|X]] wikilinks into X
$str = trim($str);
$str = safe_preg_replace("~^the\s+~i", "", $str); // Ignore leading "the" so "New York Times" == "The New York Times"
$str = safe_preg_replace("~\s~u", ' ', $str);
// punctuation
$str = str_replace(['.', ',', ';', ': ', "…"], [' ', ' ', ' ', ' ', ' '], $str);
$str = str_replace([':', '-', '—', '–', '—', '–'], ['', '', '', '', '', ''], $str);
$str = str_replace([' ', ' '], [' ', ' '], $str);
$str = str_replace(" & ", " and ", $str);
$str = str_replace(" / ", " and ", $str);
$str = trim($str);
$str = str_ireplace(['Proceedings', 'Proceeding', 'Symposium', 'Huffington ', 'the Journal of ', 'nytimes.com', '& ', '(Clifton, N.J.)', '(Clifton NJ)'],
['Proc', 'Proc', 'Sym', 'Huff ', 'journal of ', 'New York Times', 'and ', '', ''], $str);
$str = str_ireplace(['<sub>', '<sup>', '<i>', '<b>', '</sub>', '</sup>', '</i>', '</b>', '<p>', '</p>', '<title>', '</title>'], '', $str);
$str = str_ireplace(['SpringerVerlag', 'Springer Verlag Springer', 'Springer Verlag', 'Springer Springer'],
['Springer', 'Springer', 'Springer', 'Springer' ], $str);
$str = straighten_quotes($str, true);
$str = str_replace("′", "'", $str);
$str = safe_preg_replace('~\(Incorporating .*\)$~i', '', $str); // Physical Chemistry Chemical Physics (Incorporating Faraday Transactions)
$str = safe_preg_replace('~\d+ Volume Set$~i', '', $str); // Ullmann's Encyclopedia of Industrial Chemistry, 40 Volume Set
$str = safe_preg_replace('~^Retracted~i', '', $str);
$str = safe_preg_replace('~\d?\d? ?The ?sequence ?of ?\S+ ?has ?been ?deposited ?in ?the ?GenBank ?database ?under ?accession ?number ?\S+ ?\d?~i', '', $str);
$str = safe_preg_replace('~(?:\:\.\,)? ?(?:an|the) official publication of the.+$~i', '', $str);
$str = trim($str);
return strip_diacritics($str);
}
// See also titles_are_similar()
function str_equivalent(string $str1, string $str2): bool {
if (str_i_same(str_remove_irrelevant_bits($str1), str_remove_irrelevant_bits($str2))) {
return true;
}
if (string_is_book_series($str1) && string_is_book_series($str2)) { // Both series, but not the same
$str1 = trim(str_replace(COMPARE_SERIES_IN, COMPARE_SERIES_OUT, strtolower($str1)));
$str2 = trim(str_replace(COMPARE_SERIES_IN, COMPARE_SERIES_OUT, strtolower($str2)));
if ($str1 === $str2) {
return true;
}
}
return false;
}
// See also str_equivalent()
function titles_are_similar(string $title1, string $title2): bool {
if (!titles_are_dissimilar($title1, $title2)) {
return true;
}
// Try again but with funky stuff mapped out of existence
$title1 = str_replace('�', '', str_replace(array_keys(MAP_DIACRITICS), '', $title1));
$title2 = str_replace('�', '', str_replace(array_keys(MAP_DIACRITICS), '', $title2));
if (!titles_are_dissimilar($title1, $title2)) {
return true;
}
return false;
}
function de_wikify(string $string): string {
return str_replace(["[", "]", "'''", "''", "&"], ["", "", "'", "'", ""], preg_replace(["~<[^>]*>~", "~\&[\w\d]{2,7};~", "~\[\[[^\|\]]*\|([^\]]*)\]\]~"], ["", "", "$1"], $string));
}
function titles_are_dissimilar(string $inTitle, string $dbTitle): bool {
// Blow away junk from OLD stuff
if (stripos($inTitle, 'CITATION_BOT_PLACEHOLDER_') !== false) {
$possible = preg_replace("~# # # CITATION_BOT_PLACEHOLDER_[A-Z]+ \d+ # # #~isu", ' ', $inTitle);
if ($possible !== null) {
$inTitle = $possible;
} else { // When PHP fails with unicode, try without it
$inTitle = preg_replace("~# # # CITATION_BOT_PLACEHOLDER_[A-Z]+ \d+ # # #~i", ' ', $inTitle); // @codeCoverageIgnore
if ($inTitle === null) { // @codeCoverageIgnore
return true; // @codeCoverageIgnore
}
}
}
// Strip diacritics before decode
$inTitle = strip_diacritics($inTitle);
$dbTitle = strip_diacritics($dbTitle);
// always decode new data
$dbTitle = titles_simple(htmlentities(html_entity_decode($dbTitle)));
// old data both decoded and not
$inTitle2 = titles_simple($inTitle);
$inTitle = titles_simple(htmlentities(html_entity_decode($inTitle)));
$dbTitle = strip_diacritics($dbTitle);
$inTitle = strip_diacritics($inTitle);
$inTitle2 = strip_diacritics($inTitle2);
$dbTitle = mb_strtolower($dbTitle);
$inTitle = mb_strtolower($inTitle);
$inTitle2 = mb_strtolower($inTitle2);
$drops = [" ", "<strong>", "</strong>", "<em>", "</em>", " ", "&ensp", "&emsp", "&thinsp", "&zwnj",
"-", "‐", "ʼ", "'", "", "&", "'", ",", ".", ";", '"', "\n", "\r", "\t", "\v", "\e", "‐",
"-", "ʼ", "`", "]", "[", "(", ")", ":", "′", "−",
];
$inTitle = str_replace($drops, "", $inTitle);
$inTitle2 = str_replace($drops, "", $inTitle2);
$dbTitle = str_replace($drops, "", $dbTitle);
// This will convert &delta into delta
return ((strlen($inTitle) > 254 || strlen($dbTitle) > 254)
? (strlen($inTitle) !== strlen($dbTitle)
|| similar_text($inTitle, $dbTitle) / strlen($inTitle) < 0.98)
: (levenshtein($inTitle, $dbTitle) > 3))
&&
((strlen($inTitle2) > 254 || strlen($dbTitle) > 254)
? (strlen($inTitle2) !== strlen($dbTitle)
|| similar_text($inTitle2, $dbTitle) / strlen($inTitle2) < 0.98)
: (levenshtein($inTitle2, $dbTitle) > 3));
}
function titles_simple(string $inTitle): string {
// Failure leads to null or empty strings!!!!
// Leading Chapter # - Use callback to make sure there are a few characters after this
$inTitle = safe_preg_replace_callback('~^(?:Chapter \d+ \- )(.....+)~iu',
static function (array $matches): string {
return $matches[1];
}, trim($inTitle));
// Chapter number at start
$inTitle = safe_preg_replace('~^\[\d+\]\s*~iu', '', trim($inTitle));
// Trailing "a review"
$inTitle = safe_preg_replace('~(?:\: | |\:)a review$~iu', '', trim($inTitle));
// Strip trailing Online
$inTitle = safe_preg_replace('~ Online$~iu', '', $inTitle);
// Strip trailing (Third Edition)
$inTitle = safe_preg_replace('~\([^\s\(\)]+ Edition\)^~iu', '', $inTitle);
// Strip leading International Symposium on
$inTitle = safe_preg_replace('~^International Symposium on ~iu', '', $inTitle);
// Strip leading the
$inTitle = safe_preg_replace('~^The ~iu', '', $inTitle);
// Strip trailing
$inTitle = safe_preg_replace('~ A literature review$~iu', '', $inTitle);
$inTitle = safe_preg_replace("~^Editorial: ~ui", "", $inTitle);
$inTitle = safe_preg_replace("~^Brief communication: ~ui", "", $inTitle);
// Reduce punctuation
$inTitle = straighten_quotes(mb_strtolower($inTitle), true);
$inTitle = safe_preg_replace("~(?: |‐|−|-|—|–|’|—|–)~u", "", $inTitle);
$inTitle = str_replace(["\n", "\r", "\t", "‐", ":", "–", "—", "&ndash", "&mdash"], "", $inTitle);
// Retracted
$inTitle = safe_preg_replace("~\[RETRACTED\]~ui", "", $inTitle);
$inTitle = safe_preg_replace("~\(RETRACTED\)~ui", "", $inTitle);
$inTitle = safe_preg_replace("~RETRACTED~ui", "", $inTitle);
// Drop normal quotes
$inTitle = str_replace(["'", '"'], "", $inTitle);
// Strip trailing periods
$inTitle = trim(rtrim($inTitle, '.'));
// &
$inTitle = str_replace(" & ", " and ", $inTitle);
$inTitle = str_replace(" / ", " and ", $inTitle);
// greek
$inTitle = strip_diacritics($inTitle);
return str_remove_irrelevant_bits($inTitle);
}
function strip_diacritics (string $input): string {
return str_replace(array_keys(MAP_DIACRITICS), array_values(MAP_DIACRITICS), $input);
}
function straighten_quotes(string $str, bool $do_more): string { // (?<!\') and (?!\') means that it cannot have a single quote right before or after it
// These Regex can die on Unicode because of backward looking
if ($str === '') {
return '';
}
$str = str_replace('Hawaiʻi', 'CITATION_BOT_PLACEHOLDER_HAWAII', $str);
$str = str_replace('Ha‘apai', 'CITATION_BOT_PLACEHOLDER_HAAPAI', $str);
$str = safe_preg_replace('~(?<!\')̵[679];|'|ȁ[89];|[\x{FF07}\x{2018}-\x{201B}`]|&[rl]s?[b]?quo;(?!\')~u', "'", $str);
if((mb_strpos($str, '›') !== false && mb_strpos($str, '&[lsaquo;') !== false) ||
(mb_strpos($str, '\x{2039}') !== false && mb_strpos($str, '\x{203A}') !== false) ||
(mb_strpos($str, '‹') !== false && mb_strpos($str, '›') !== false)) { // Only replace single angle quotes if some of both
$str = safe_preg_replace('~&[lr]saquo;|[\x{2039}\x{203A}]|[‹›]~u', "'", $str); // Websites tiles: Jobs ›› Iowa ›› Cows ›› Ames
}
$str = safe_preg_replace('~̶[013];|[\x{201C}-\x{201F}]|&[rlb][d]?quo;~u', '"', $str);
if((mb_strpos($str, '»') !== false && mb_strpos($str, '«') !== false) ||
(mb_strpos($str, '\x{00AB}') !== false && mb_strpos($str, '\x{00AB}') !== false) ||
(mb_strpos($str, '«') !== false && mb_strpos($str, '»') !== false)) { // Only replace double angle quotes if some of both // Websites tiles: Jobs » Iowa » Cows » Ames
if ($do_more){
$str = safe_preg_replace('~&[lr]aquo;|[\x{00AB}\x{00BB}]|[«»]~u', '"', $str);
} else { // Only outer funky quotes, not inner quotes
if (preg_match('~^(?:«|»|\x{00AB}|\x{00BB}|«|»)~u', $str, $match1) &&
preg_match('~(?:«|»|\x{00AB}|\x{00BB}|«|»)$~u', $str, $match2)
) {
$count1 = substr_count($str, $match1[0]);
$count2 = substr_count($str, $match2[0]);
if ($match1[0] === $match2[0]) { // Avoid double counting
$count1 -= 1;
$count2 -= 1;
}
if ($count1 === 1 && $count2 === 1) {
$str = safe_preg_replace('~^(?:«|»|\x{00AB}|\x{00BB}|«|»)~u', '"', $str);
$str = safe_preg_replace('~(?:«|»|\x{00AB}|\x{00BB}|«|»)$~u', '"', $str);
}
}
}
}
$str = str_ireplace('CITATION_BOT_PLACEHOLDER_HAAPAI', 'Ha‘apai', $str);
return str_ireplace('CITATION_BOT_PLACEHOLDER_HAWAII', 'Hawaiʻi', $str);
}
// ============================================= Capitalization functions ======================================
function title_case(string $text): string {
if (stripos($text, 'www.') !== false || stripos($text, 'www-') !== false || stripos($text, 'http://') !== false) {
return $text; // Who knows - duplicate code below
}
return mb_convert_case($text, MB_CASE_TITLE, "UTF-8");
}
/** Returns a properly capitalized title.
* If $caps_after_punctuation is true (or there is an abundance of periods), it allows the
* letter after colons and other punctuation marks to remain capitalized.
* If not, it won't capitalize after : etc.
*/
function title_capitalization(string $in, bool $caps_after_punctuation): string {
// Use 'straight quotes' per WP:MOS
$new_case = straighten_quotes(trim($in), false);
if (mb_substr($new_case, 0, 1) === "[" && mb_substr($new_case, -1) === "]") {
return $new_case; // We ignore wikilinked names and URL linked since who knows what's going on there.
// Changing case may break links (e.g. [[Journal YZ|J. YZ]] etc.)
}
if (stripos($new_case, 'www.') !== false || stripos($new_case, 'www-') !== false || stripos($new_case, 'http://') !== false) {
return $new_case; // Who knows - duplicate code above
}
if ($new_case === mb_strtoupper($new_case)
&& mb_strlen(str_replace(["[", "]"], "", trim($in))) > 6
) {
// ALL CAPS to Title Case
$new_case = mb_convert_case($new_case, MB_CASE_TITLE, "UTF-8");
}
// Implicit acronyms
$new_case = ' ' . $new_case . ' ';
$new_case = safe_preg_replace_callback("~[^\w&][b-df-hj-np-tv-xz]{3,}(?=\W)~ui",
static function (array $matches): string { // Three or more consonants. NOT Y
return mb_strtoupper($matches[0]);
},
$new_case);
$new_case = safe_preg_replace_callback("~[^\w&][aeiou]{3,}(?=\W)~ui",
static function (array $matches): string { // Three or more vowels. NOT Y
return mb_strtoupper($matches[0]);
},
$new_case);
$new_case = mb_substr($new_case, 1, -1); // Remove added spaces
$new_case = mb_substr(str_replace(UC_SMALL_WORDS, LC_SMALL_WORDS, " " . $new_case . " "), 1, -1);
foreach(UC_SMALL_WORDS as $key=>$_value) {
$upper = UC_SMALL_WORDS[$key];
$lower = LC_SMALL_WORDS[$key];
foreach ([': ', ', ', '. ', '; '] as $char) {
$new_case = str_replace(mb_substr($upper, 0, -1) . $char, mb_substr($lower, 0, -1) . $char, $new_case);
}
}
if ($caps_after_punctuation || (substr_count($in, '.') / strlen($in)) > .07) {
// When there are lots of periods, then they probably mark abbreviations, not sentence ends
// We should therefore capitalize after each punctuation character.
$new_case = safe_preg_replace_callback("~[?.:!/]\s+[a-z]~u" /* Capitalize after punctuation */,
static function (array $matches): string {
return mb_strtoupper($matches[0]);
},
$new_case);
$new_case = safe_preg_replace_callback("~(?<!<)/[a-z]~u" /* Capitalize after slash unless part of ending html tag */,
static function (array $matches): string {
return mb_strtoupper($matches[0]);
},
$new_case);
// But not "Ann. Of...." which seems to be common in journal titles
$new_case = str_replace("Ann. Of ", "Ann. of ", $new_case);
}
$new_case = safe_preg_replace_callback(
"~ \([a-z]~u" /* uppercase after parenthesis */,
static function (array $matches): string {
return mb_strtoupper($matches[0]);
},
trim($new_case)
);
$new_case = safe_preg_replace_callback(
"~\w{2}'[A-Z]\b~u" /* Lowercase after apostrophes */,
static function (array $matches): string {
return mb_strtolower($matches[0]);
},
trim($new_case)
);
/** French l'Words and d'Words */
$new_case = safe_preg_replace_callback(
"~(\s[LD][\'\x{00B4}])([a-zA-ZÀ-ÿ]+)~u",
static function (array $matches): string {
return mb_strtolower($matches[1]) . mb_ucfirst_force($matches[2]);
},
' ' . $new_case
);
/** Italian dell'xxx words */
$new_case = safe_preg_replace_callback(
"~(\s)(Dell|Degli|Delle)([\'\x{00B4}][a-zA-ZÀ-ÿ]{3})~u",
static function (array $matches): string {
return $matches[1] . mb_strtolower($matches[2]) . $matches[3];
},
$new_case
);
$new_case = mb_ucfirst_bot(trim($new_case));
// Solitary 'a' should be lowercase
$new_case = safe_preg_replace("~(\w\s+)A(\s+\w)~u", "$1a$2", $new_case);
// but not in "U S A"
$new_case = trim(str_replace(" U S a ", " U S A ", ' ' . $new_case . ' '));
// This should be capitalized
$new_case = str_replace(['(new Series)', '(new series)'], ['(New Series)', '(New Series)'], $new_case);
// Catch some specific epithets, which should be lowercase
$new_case = safe_preg_replace_callback(
"~(?:'')?(?P<taxon>\p{L}+\s+\p{L}+)(?:'')?\s+(?P<nova>(?:(?:gen\.? no?v?|sp\.? no?v?|no?v?\.? sp|no?v?\.? gen)\b[\.,\s]*)+)~ui" /* Species names to lowercase */,
static function (array $matches): string {
return "''" . mb_ucfirst_bot(mb_strtolower($matches['taxon'])) . "'' " . mb_strtolower($matches["nova"]);
},
$new_case);
// "des" at end is "Des" for Design not german "The"
if (mb_substr($new_case, -4, 4) === ' des') {
$new_case = mb_substr($new_case, 0, -4) . ' Des';
}
// Capitalization exceptions, e.g. Elife -> eLife
$new_case = str_replace(UCFIRST_JOURNAL_ACRONYMS, JOURNAL_ACRONYMS, " " . $new_case . " ");
$new_case = mb_substr($new_case, 1, mb_strlen($new_case) - 2); // remove spaces, needed for matching in LC_SMALL_WORDS
// Single letter at end should be capitalized J Chem Phys E for example. Obviously not the spanish word "e".
if (mb_substr($new_case, -2, 1) === ' ') {
$new_case = mb_strrev(mb_ucfirst_bot(mb_strrev($new_case)));
}
if ($new_case === 'Now and then') {
$new_case = 'Now and Then'; // Odd journal name
}
// Trust existing "ITS", "its", ...
$its_in = preg_match_all('~ its(?= )~iu', ' ' . trim($in) . ' ', $matches_in, PREG_OFFSET_CAPTURE);
$new_case = trim($new_case);
$its_out = preg_match_all('~ its(?= )~iu', ' ' . $new_case . ' ', $matches_out, PREG_OFFSET_CAPTURE);
if ($its_in === $its_out && $its_in !== 0 && $its_in !== false) {
$matches_in = $matches_in[0];
$matches_out = $matches_out[0];
foreach ($matches_in as $key => $_value) {
if ($matches_in[$key][0] !== $matches_out[$key][0] &&
$matches_in[$key][1] === $matches_out[$key][1]) {
$new_case = substr_replace($new_case, trim($matches_in[$key][0]), $matches_out[$key][1], 3); // PREG_OFFSET_CAPTURE is ALWAYS in BYTES, even for unicode
}
}
}
// Trust existing "DOS", "dos", ...
$its_in = preg_match_all('~ dos(?= )~iu', ' ' . trim($in) . ' ', $matches_in, PREG_OFFSET_CAPTURE);
$new_case = trim($new_case);
$its_out = preg_match_all('~ dos(?= )~iu', ' ' . $new_case . ' ', $matches_out, PREG_OFFSET_CAPTURE);
if ($its_in === $its_out && $its_in !== 0 && $its_in !== false) {
$matches_in = $matches_in[0];
$matches_out = $matches_out[0];