-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbibliography-builder.php
More file actions
2103 lines (1843 loc) · 60.7 KB
/
Copy pathbibliography-builder.php
File metadata and controls
2103 lines (1843 loc) · 60.7 KB
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
/**
* Plugin Name: Borges Bibliography Builder
* Plugin URI: https://github.com/dknauss/Borges/
* Description: Create accessible bibliographies from DOI, PubMed, BibTeX, CSL-JSON, and free text; export RIS.
* Version: 1.8.1
* Requires at least: 6.4
* Tested up to: 7.1
* Requires PHP: 7.4
* Author: Dan Knauss
* Author URI: https://dan.knauss.ca/
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: borges-bibliography-builder
* Domain Path: /languages
*
* @package BibliographyBuilder
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! defined( 'BIBLIOGRAPHY_BUILDER_PLUGIN_DIR' ) ) {
define( 'BIBLIOGRAPHY_BUILDER_PLUGIN_DIR', __DIR__ . '/' );
}
/**
* Maximum number of citations that may be formatted in one request.
*/
const BIBLIOGRAPHY_BUILDER_MAX_FORMAT_ITEMS = 50;
/**
* Maximum formatter request payload size.
*/
const BIBLIOGRAPHY_BUILDER_MAX_FORMAT_BYTES = 1048576;
/**
* Maximum length of any single CSL string field.
*
* Every CSL string field is run through a looped wp_strip_all_tags, and core's
* lazy script/style-stripping regex degrades to catastrophic backtracking past
* roughly 600 KB: measured at ~2.4s for 600 KB and ~12.9s for 950 KB of
* unclosed script tokens. BIBLIOGRAPHY_BUILDER_MAX_FORMAT_BYTES bounds the
* whole request body, so without a per-field limit a single field can carry the
* entire megabyte into that regex and pin a CPU core. 64 KB sits an order of
* magnitude below the cliff while staying far above any real bibliographic
* value, including long abstracts.
*/
const BIBLIOGRAPHY_BUILDER_MAX_CSL_FIELD_BYTES = 65536;
/**
* Cache TTL for repeated formatter responses.
*/
const BIBLIOGRAPHY_BUILDER_FORMAT_CACHE_TTL = 3600;
/**
* Return a block's stable `bibliographyId`, or null when it has none yet.
*
* The editor assigns a UUID to every bibliography block and keeps it unique
* within a post (Phase 05, Tier 0). Blocks saved before that, or edited by
* hand, may carry no ID or an unusable one; those report null rather than a
* value a client could not safely use as a URL segment.
*
* @param array $attrs Block attributes.
* @return string|null
*/
function bibliography_builder_get_stable_block_id( $attrs ) {
$id = isset( $attrs['bibliographyId'] ) ? $attrs['bibliographyId'] : null;
// An all-digit value would read as a block index in `{ref}` URL segments,
// so it is not a usable ID (the editor then replaces it, as in
// src/lib/stable-ids.js).
return bibliography_builder_is_block_id( $id ) ? $id : null;
}
/**
* Recursively gather bibliography block data from parsed blocks.
*
* @param array $blocks Parsed block tree.
* @param array $results Accumulator.
* @return array
*/
function bibliography_builder_collect_blocks( $blocks, $results = array() ) {
foreach ( $blocks as $block ) {
if ( ! empty( $block['blockName'] ) && 'bibliography-builder/bibliography' === $block['blockName'] ) {
$attrs = isset( $block['attrs'] ) && is_array( $block['attrs'] ) ? $block['attrs'] : array();
$results[] = array(
'bibliographyId' => bibliography_builder_get_stable_block_id( $attrs ),
'citationStyle' => isset( $attrs['citationStyle'] )
? (string) $attrs['citationStyle']
: 'chicago-notes-bibliography',
'headingText' => isset( $attrs['headingText'] )
? (string) $attrs['headingText']
: '',
'outputJsonLd' => isset( $attrs['outputJsonLd'] ) ? (bool) $attrs['outputJsonLd'] : true,
'outputCoins' => ! empty( $attrs['outputCoins'] ),
'outputCslJson' => ! empty( $attrs['outputCslJson'] ),
'citations' => isset( $attrs['citations'] )
&& is_array( $attrs['citations'] )
? array_values(
array_filter( $attrs['citations'], 'is_array' )
)
: array(),
);
}
if ( ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) ) {
$results = bibliography_builder_collect_blocks( $block['innerBlocks'], $results );
}
}
return $results;
}
/**
* Normalize bibliography API records with index and counts.
*
* @param array $bibliographies Raw bibliography arrays.
* @return array
*/
function bibliography_builder_prepare_bibliographies( $bibliographies ) {
return array_values(
array_map(
static function ( $bibliography, $index ) {
$bibliography['index'] = $index;
$bibliography['entryCount'] = count( $bibliography['citations'] );
return $bibliography;
},
$bibliographies,
array_keys( $bibliographies )
)
);
}
/**
* Get normalized bibliography data for a post.
*
* @param WP_Post $post Post object.
* @return array
*/
function bibliography_builder_get_bibliographies_for_post( $post ) {
$parsed_blocks = parse_blocks( (string) $post->post_content );
$bibliographies = bibliography_builder_collect_blocks( $parsed_blocks );
return bibliography_builder_prepare_bibliographies( $bibliographies );
}
/**
* Return the visible display text for a citation record.
*
* @param array $citation Citation record.
* @return string
*/
function bibliography_builder_get_citation_display_text( $citation ) {
if ( ! empty( $citation['displayOverride'] ) && is_string( $citation['displayOverride'] ) ) {
return $citation['displayOverride'];
}
if ( ! empty( $citation['formattedText'] ) && is_string( $citation['formattedText'] ) ) {
return $citation['formattedText'];
}
if ( ! empty( $citation['csl']['title'] ) && is_string( $citation['csl']['title'] ) ) {
return $citation['csl']['title'];
}
return '';
}
/**
* Build plain-text bibliography output from stored citation display strings.
*
* @param array $bibliography Bibliography record.
* @return string
*/
function bibliography_builder_build_plain_text( $bibliography ) {
$lines = array();
foreach ( $bibliography['citations'] as $citation ) {
$lines[] = bibliography_builder_strip_bounded( bibliography_builder_get_citation_display_text( $citation ) );
}
return implode( "\n", $lines ) . "\n";
}
/**
* Build a canonical CSL array from bibliography citations.
*
* @param array $bibliography Bibliography record.
* @return array
*/
function bibliography_builder_build_csl_json( $bibliography ) {
return array_values(
array_map(
static function ( $citation ) {
return isset( $citation['csl'] ) && is_array( $citation['csl'] ) ? $citation['csl'] : array();
},
$bibliography['citations']
)
);
}
/**
* Citation style definitions shared by PHP formatting endpoints.
*
* @return array
*/
function bibliography_builder_get_formatter_style_definitions() {
return array(
'chicago-notes-bibliography' => array(
'template' => 'chicago-notes-bibliography',
'locale' => 'en-US',
'family' => 'notes',
),
'chicago-author-date' => array(
'template' => 'chicago-author-date',
'locale' => 'en-US',
'family' => 'author-date',
),
'apa-7' => array(
'template' => 'apa',
'locale' => 'en-US',
'family' => 'author-date',
),
'mla-9' => array(
'template' => 'modern-language-association',
'locale' => 'en-US',
'family' => 'author-date',
),
'harvard' => array(
'template' => 'harvard1',
'locale' => 'en-GB',
'family' => 'author-date',
),
'ieee' => array(
'template' => 'ieee',
'locale' => 'en-US',
'family' => 'numeric',
),
'vancouver' => array(
'template' => 'vancouver',
'locale' => 'en-US',
'family' => 'numeric',
),
'oscola' => array(
'template' => 'oscola',
'locale' => 'en-GB',
'family' => 'notes',
),
'abnt' => array(
'template' => 'abnt',
'locale' => 'pt-BR',
'family' => 'author-date',
),
);
}
/**
* Get one formatter style definition, falling back to the default style.
*
* @param string $style_key Style key from the block attribute.
* @return array
*/
function bibliography_builder_get_formatter_style_definition( $style_key ) {
$styles = bibliography_builder_get_formatter_style_definitions();
return isset( $styles[ $style_key ] ) ? $styles[ $style_key ] : $styles['chicago-notes-bibliography'];
}
/**
* Load Composer autoload and verify citeproc-php is usable.
*
* @return true|WP_Error
*/
function bibliography_builder_ensure_formatter_available() {
foreach ( array( 'dom', 'intl', 'json', 'mbstring', 'SimpleXML' ) as $extension ) {
if ( ! extension_loaded( $extension ) ) {
return new WP_Error(
'bibliography_builder_formatter_extension_missing',
sprintf(
/* translators: %s: PHP extension name. */
__( 'The bibliography formatter requires the PHP %s extension.', 'borges-bibliography-builder' ),
$extension
),
array( 'status' => 500 )
);
}
}
$autoload = BIBLIOGRAPHY_BUILDER_PLUGIN_DIR . 'vendor/autoload.php';
if ( ! file_exists( $autoload ) ) {
return new WP_Error(
'bibliography_builder_formatter_missing',
__( 'The bibliography formatter dependencies are missing.', 'borges-bibliography-builder' ),
array( 'status' => 500 )
);
}
require_once $autoload;
if ( ! class_exists( '\\Seboettg\\CiteProc\\CiteProc' ) ) {
return new WP_Error(
'bibliography_builder_formatter_missing',
__( 'The bibliography formatter is unavailable.', 'borges-bibliography-builder' ),
array( 'status' => 500 )
);
}
return true;
}
/**
* JSON-encode data using WordPress when available.
*
* @param mixed $data Data to encode.
* @param int $flags Optional encoding flags.
* @param int $depth Optional maximum depth.
* @return string|false
*/
function bibliography_builder_json_encode( $data, $flags = 0, $depth = 512 ) {
if ( function_exists( 'wp_json_encode' ) ) {
return wp_json_encode( $data, $flags, $depth );
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- Test fallback when WP is absent.
return json_encode( $data, $flags, $depth );
}
/**
* Build a compact transient key for a cache group/key pair.
*
* @param string $group Cache group.
* @param string $key Cache key.
* @return string
*/
function bibliography_builder_get_transient_cache_key( $group, $key ) {
return 'bbb_' . md5( $group . ':' . $key );
}
/**
* Read a cached value from object cache with a transient fallback.
*
* @param string $key Cache key.
* @param string $group Cache group.
* @return array{hit:bool,value:mixed}
*/
function bibliography_builder_cache_get( $key, $group ) {
if ( function_exists( 'wp_cache_get' ) ) {
$found = false;
$value = wp_cache_get( $key, $group, false, $found );
if ( $found ) {
return array(
'hit' => true,
'value' => $value,
);
}
}
if ( function_exists( 'get_transient' ) ) {
$value = get_transient( bibliography_builder_get_transient_cache_key( $group, $key ) );
if ( false !== $value ) {
return array(
'hit' => true,
'value' => $value,
);
}
}
return array(
'hit' => false,
'value' => null,
);
}
/**
* Store a cached value in object cache and transient storage when available.
*
* @param string $key Cache key.
* @param mixed $value Cache value.
* @param string $group Cache group.
* @param int $expire TTL in seconds.
* @return void
*/
function bibliography_builder_cache_set( $key, $value, $group, $expire ) {
if ( function_exists( 'wp_cache_set' ) ) {
wp_cache_set( $key, $value, $group, $expire );
}
if ( function_exists( 'set_transient' ) ) {
set_transient( bibliography_builder_get_transient_cache_key( $group, $key ), $value, $expire );
}
}
/**
* Determine whether an array is a list on PHP versions before array_is_list().
*
* @param array $value Array to inspect.
* @return bool
*/
function bibliography_builder_is_list_array( $value ) {
return array() === $value || array_keys( $value ) === range( 0, count( $value ) - 1 );
}
/**
* Return the CSL item types accepted by the formatter endpoint.
*
* Keep this in sync with src/lib/csl-sanitize.js.
*
* @return array
*/
function bibliography_builder_get_known_csl_types() {
return array(
'article',
'article-journal',
'article-magazine',
'article-newspaper',
'bill',
'book',
'broadcast',
'chapter',
'classic',
'collection',
'dataset',
'document',
'entry',
'entry-dictionary',
'entry-encyclopedia',
'event',
'figure',
'graphic',
'hearing',
'interview',
'legal_case',
'legislation',
'magazine',
'manuscript',
'map',
'motion_picture',
'musical_score',
'performance',
'pamphlet',
'paper-conference',
'patent',
'periodical',
'post',
'post-weblog',
'personal_communication',
'regulation',
'report',
'review',
'review-book',
'software',
'song',
'speech',
'standard',
'thesis',
'treaty',
'webpage',
);
}
/**
* Return CSL fields that must contain strings.
*
* @return array
*/
function bibliography_builder_get_csl_string_fields() {
return array(
'title',
'container-title',
'publisher',
'page',
'number',
'volume',
'issue',
'DOI',
'URL',
'language',
'edition',
'medium',
'genre',
'publisher-place',
'event-place',
'reviewed-title',
);
}
/**
* Whether any string anywhere in a CSL value exceeds the per-field byte cap.
*
* Stripping is reached from five separate call sites — the flat string-field
* loop, author name parts, date literal/raw, and both branches of the
* string-or-array handler — and the strip is the expensive step. Capping at one
* call site leaves the same cost reachable under a different key, so the check
* lives here and runs once over the whole decoded item before any sanitization
* begins. Any string field added to any of those paths later is bounded
* automatically.
*
* Depth is bounded the same way bibliography_builder_sanitize_csl_value bounds
* it; over-deep items are rejected separately by that function.
*
* @param mixed $value CSL value, of any shape.
* @param int $depth Current recursion depth.
* @return bool True when some string exceeds the cap.
*/
function bibliography_builder_csl_has_oversized_string( $value, $depth = 0 ) {
if ( $depth > 10 ) {
return false;
}
if ( is_string( $value ) ) {
return strlen( $value ) > BIBLIOGRAPHY_BUILDER_MAX_CSL_FIELD_BYTES;
}
if ( is_array( $value ) ) {
foreach ( $value as $item ) {
if ( bibliography_builder_csl_has_oversized_string( $item, $depth + 1 ) ) {
return true;
}
}
}
return false;
}
/**
* Strip tags from text that may be arbitrarily long, bounding the work first.
*
* The write path rejects oversized strings outright, but the read path cannot:
* the text is already in post_content, and refusing to render a stored
* bibliography would break a post that exists. Truncate to the same cap
* instead, which bounds the regex cost while staying lossless for any real
* citation — 64 KB is far beyond the longest plausible formatted entry.
*
* Without this, a single oversized string stored in a published post makes
* every subsequent read of that bibliography pay ~12 seconds of CPU, on a route
* that needs no authentication.
*
* @param string $text Possibly untrusted, possibly very long text.
* @return string Stripped text.
*/
function bibliography_builder_strip_bounded( $text ) {
$text = (string) $text;
if ( strlen( $text ) > BIBLIOGRAPHY_BUILDER_MAX_CSL_FIELD_BYTES ) {
$text = function_exists( 'mb_strcut' )
? mb_strcut( $text, 0, BIBLIOGRAPHY_BUILDER_MAX_CSL_FIELD_BYTES, 'UTF-8' )
: substr( $text, 0, BIBLIOGRAPHY_BUILDER_MAX_CSL_FIELD_BYTES );
}
return wp_strip_all_tags( $text, false );
}
/**
* Strip HTML markup from CSL strings, including nested/broken tag payloads.
*
* Callers must bound the input first; see
* bibliography_builder_csl_has_oversized_string().
*
* @param string $text String value.
* @return string
*/
function bibliography_builder_strip_csl_html( $text ) {
$result = (string) $text;
do {
$previous = $result;
$result = wp_strip_all_tags( $result );
} while ( $result !== $previous );
return $result;
}
/**
* Whether a CSL key should be dropped before storage/formatting.
*
* @param string|int $key Array key.
* @return bool
*/
function bibliography_builder_is_forbidden_csl_key( $key ) {
return in_array( (string) $key, array( '__proto__', 'constructor', 'prototype' ), true );
}
/**
* Recursively sanitize a CSL value and reject excessive nesting.
*
* @param mixed $value Value to sanitize.
* @param int $depth Current recursion depth.
* @param bool $valid Validity accumulator.
* @return mixed
*/
function bibliography_builder_sanitize_csl_value( $value, $depth, &$valid ) {
if ( $depth > 10 ) {
$valid = false;
return null;
}
if ( is_string( $value ) || is_int( $value ) || is_float( $value ) || is_bool( $value ) ) {
return $value;
}
if ( is_array( $value ) ) {
$sanitized = array();
foreach ( $value as $key => $nested_value ) {
if ( bibliography_builder_is_forbidden_csl_key( $key ) ) {
continue;
}
$nested_valid = true;
$sanitized_value = bibliography_builder_sanitize_csl_value( $nested_value, $depth + 1, $nested_valid );
if ( ! $nested_valid ) {
$valid = false;
continue;
}
if ( null !== $sanitized_value ) {
$sanitized[ $key ] = $sanitized_value;
}
}
return $sanitized;
}
if ( null !== $value ) {
$valid = false;
}
return null;
}
/**
* Normalize one CSL date part to an integer.
*
* @param mixed $part Date part.
* @return int|null
*/
function bibliography_builder_normalize_csl_date_part( $part ) {
if ( is_int( $part ) ) {
return $part;
}
if ( is_float( $part ) && floor( $part ) === $part ) {
return (int) $part;
}
if ( is_string( $part ) && preg_match( '/^\d+$/', $part ) ) {
return (int) $part;
}
return null;
}
/**
* Sanitize and validate CSL date structures.
*
* @param mixed $issued CSL issued/accessed value.
* @return array|WP_Error
*/
function bibliography_builder_sanitize_csl_date( $issued ) {
if ( ! is_array( $issued ) || bibliography_builder_is_list_array( $issued ) ) {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
__( 'Invalid CSL date value.', 'borges-bibliography-builder' ),
array( 'status' => 400 )
);
}
$valid = true;
$sanitized_issued = bibliography_builder_sanitize_csl_value( $issued, 0, $valid );
if ( ! $valid || ! is_array( $sanitized_issued ) ) {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
__( 'Invalid CSL date value.', 'borges-bibliography-builder' ),
array( 'status' => 400 )
);
}
$has_valid_date = false;
if ( array_key_exists( 'date-parts', $sanitized_issued ) ) {
if ( ! is_array( $sanitized_issued['date-parts'] ) || empty( $sanitized_issued['date-parts'] ) ) {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
__( 'Invalid CSL date-parts.', 'borges-bibliography-builder' ),
array( 'status' => 400 )
);
}
$date_parts = array();
foreach ( $sanitized_issued['date-parts'] as $date_part ) {
if ( ! is_array( $date_part ) ) {
continue;
}
$normalized_date_part = array();
foreach ( $date_part as $part ) {
$normalized_part = bibliography_builder_normalize_csl_date_part( $part );
if ( null !== $normalized_part ) {
$normalized_date_part[] = $normalized_part;
}
}
if ( ! empty( $normalized_date_part ) ) {
$date_parts[] = $normalized_date_part;
}
}
if ( empty( $date_parts ) ) {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
__( 'Invalid CSL date-parts.', 'borges-bibliography-builder' ),
array( 'status' => 400 )
);
}
$sanitized_issued['date-parts'] = $date_parts;
$has_valid_date = true;
}
foreach ( array( 'literal', 'raw' ) as $field ) {
if ( ! array_key_exists( $field, $sanitized_issued ) ) {
continue;
}
if ( ! is_string( $sanitized_issued[ $field ] ) ) {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
__( 'Invalid CSL date value.', 'borges-bibliography-builder' ),
array( 'status' => 400 )
);
}
$sanitized_issued[ $field ] = bibliography_builder_strip_csl_html( $sanitized_issued[ $field ] );
$has_valid_date = true;
}
if ( ! $has_valid_date ) {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
__( 'Invalid CSL date-parts.', 'borges-bibliography-builder' ),
array( 'status' => 400 )
);
}
return $sanitized_issued;
}
/**
* Sanitize and validate one CSL name object.
*
* @param mixed $author CSL name object.
* @return array|WP_Error
*/
function bibliography_builder_sanitize_csl_author( $author ) {
if ( ! is_array( $author ) || bibliography_builder_is_list_array( $author ) ) {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
__( 'Invalid CSL author entry.', 'borges-bibliography-builder' ),
array( 'status' => 400 )
);
}
$valid = true;
$sanitized_author = bibliography_builder_sanitize_csl_value( $author, 0, $valid );
if ( ! $valid || ! is_array( $sanitized_author ) ) {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
__( 'Invalid CSL author entry.', 'borges-bibliography-builder' ),
array( 'status' => 400 )
);
}
foreach ( array( 'family', 'given', 'literal', 'ORCID' ) as $key ) {
if ( array_key_exists( $key, $sanitized_author ) && ! is_string( $sanitized_author[ $key ] ) ) {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
__( 'Invalid CSL author field.', 'borges-bibliography-builder' ),
array( 'status' => 400 )
);
}
if ( array_key_exists( $key, $sanitized_author ) ) {
$sanitized_author[ $key ] = bibliography_builder_strip_csl_html( $sanitized_author[ $key ] );
}
}
return $sanitized_author;
}
/**
* Sanitize and validate CSL name lists.
*
* @param mixed $names CSL name list.
* @param string $field Field name.
* @return array|WP_Error
*/
function bibliography_builder_sanitize_csl_name_list( $names, $field ) {
if ( ! is_array( $names ) ) {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
sprintf(
/* translators: %s: CSL field name. */
__( 'Invalid CSL %s list.', 'borges-bibliography-builder' ),
$field
),
array( 'status' => 400 )
);
}
$sanitized = array();
foreach ( $names as $author ) {
$sanitized_author = bibliography_builder_sanitize_csl_author( $author );
if ( is_wp_error( $sanitized_author ) ) {
return $sanitized_author;
}
$sanitized[] = $sanitized_author;
}
return $sanitized;
}
/**
* Sanitize and validate a string-or-string-array CSL field.
*
* @param mixed $value Field value.
* @param string $field Field name.
* @return string|array|WP_Error
*/
function bibliography_builder_sanitize_csl_string_or_array_field( $value, $field ) {
if ( is_string( $value ) ) {
return bibliography_builder_strip_csl_html( $value );
}
if ( is_array( $value ) ) {
$sanitized = array();
foreach ( $value as $item ) {
if ( ! is_string( $item ) ) {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
sprintf(
/* translators: %s: CSL field name. */
__( 'Invalid CSL %s.', 'borges-bibliography-builder' ),
$field
),
array( 'status' => 400 )
);
}
$sanitized[] = bibliography_builder_strip_csl_html( $item );
}
return $sanitized;
}
return new WP_Error(
'bibliography_builder_invalid_csl_item',
sprintf(
/* translators: %s: CSL field name. */
__( 'Invalid CSL %s.', 'borges-bibliography-builder' ),
$field
),
array( 'status' => 400 )
);
}
/**
* Validate and sanitize one CSL-JSON item for the formatter endpoint.
*
* @param mixed $csl CSL-JSON item.
* @return array|WP_Error
*/
function bibliography_builder_validate_and_sanitize_csl_item( $csl ) {
if ( ! is_array( $csl ) || bibliography_builder_is_list_array( $csl ) ) {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
__( 'Invalid CSL object.', 'borges-bibliography-builder' ),
array( 'status' => 400 )
);
}
// Bound string length before anything strips HTML. Every strip path is
// covered by this one check; see bibliography_builder_csl_has_oversized_string.
if ( bibliography_builder_csl_has_oversized_string( $csl ) ) {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
sprintf(
/* translators: %d: maximum length in bytes. */
__( 'A CSL field exceeds the maximum length of %d bytes.', 'borges-bibliography-builder' ),
BIBLIOGRAPHY_BUILDER_MAX_CSL_FIELD_BYTES
),
array( 'status' => 400 )
);
}
$valid = true;
$sanitized_csl = bibliography_builder_sanitize_csl_value( $csl, 0, $valid );
if ( ! $valid || ! is_array( $sanitized_csl ) ) {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
__( 'Invalid CSL object.', 'borges-bibliography-builder' ),
array( 'status' => 400 )
);
}
if (
empty( $sanitized_csl['type'] ) ||
! is_string( $sanitized_csl['type'] ) ||
! in_array( $sanitized_csl['type'], bibliography_builder_get_known_csl_types(), true )
) {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
__( 'Invalid CSL type.', 'borges-bibliography-builder' ),
array( 'status' => 400 )
);
}
foreach ( array( 'author', 'editor', 'reviewed-author' ) as $field ) {
if ( array_key_exists( $field, $sanitized_csl ) ) {
$sanitized_list = bibliography_builder_sanitize_csl_name_list( $sanitized_csl[ $field ], $field );
if ( is_wp_error( $sanitized_list ) ) {
return $sanitized_list;
}
$sanitized_csl[ $field ] = $sanitized_list;
}
}
foreach ( array( 'issued', 'accessed' ) as $field ) {
if ( array_key_exists( $field, $sanitized_csl ) ) {
$sanitized_date = bibliography_builder_sanitize_csl_date( $sanitized_csl[ $field ] );
if ( is_wp_error( $sanitized_date ) ) {
return $sanitized_date;
}
$sanitized_csl[ $field ] = $sanitized_date;
}
}
foreach ( bibliography_builder_get_csl_string_fields() as $field ) {
if ( array_key_exists( $field, $sanitized_csl ) ) {
if ( ! is_string( $sanitized_csl[ $field ] ) ) {
if (
'title' !== $field
&& ( is_int( $sanitized_csl[ $field ] ) || is_float( $sanitized_csl[ $field ] ) )
) {
$sanitized_csl[ $field ] = (string) $sanitized_csl[ $field ];
} else {
return new WP_Error(
'bibliography_builder_invalid_csl_item',
sprintf(
/* translators: %s: CSL field name. */
__( 'Invalid CSL %s.', 'borges-bibliography-builder' ),
$field
),
array( 'status' => 400 )
);
}
}
$sanitized_csl[ $field ] = bibliography_builder_strip_csl_html( $sanitized_csl[ $field ] );
}
}
foreach ( array( 'ISBN', 'ISSN' ) as $field ) {
if ( array_key_exists( $field, $sanitized_csl ) ) {
$sanitized_identifier = bibliography_builder_sanitize_csl_string_or_array_field(
$sanitized_csl[ $field ],
$field
);
if ( is_wp_error( $sanitized_identifier ) ) {
return $sanitized_identifier;
}
$sanitized_csl[ $field ] = $sanitized_identifier;
}
}
return $sanitized_csl;