-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
bibtexbrowser.php
executable file
·4993 lines (4208 loc) · 153 KB
/
bibtexbrowser.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 /* bibtexbrowser: publication lists with bibtex and PHP
<!--this is version from commit __GITHUB__ -->
URL: http://www.monperrus.net/martin/bibtexbrowser/
Questions & Bug Reports: https://github.com/monperrus/bibtexbrowser/issues
(C) 2012-2020 Github contributors
(C) 2006-2020 Martin Monperrus
(C) 2014 Markus Jochim
(C) 2013 Matthieu Guillaumin
(C) 2005-2006 The University of Texas at El Paso / Joel Garcia, Leonardo Ruiz, and Yoonsik Cheon
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
*/
// it is be possible to include( 'bibtexbrowser.php' ); several times in the same script
// added on Wednesday, June 01 2011, bug found by Carlos Bras
if (!defined('BIBTEXBROWSER')) {
// this if block ends at the very end of this file, after all class and function declarations.
define('BIBTEXBROWSER','v__GITHUB__');
// support for configuration
// set with bibtexbrowser_configure, get with config_value
// you may have bibtexbrowser_configure('foo', 'bar') in bibtexbrowser.local.php
global $CONFIGURATION;
$CONFIGURATION = array();
function bibtexbrowser_configure($key, $value) {
global $CONFIGURATION;
$CONFIGURATION[$key]=$value;
if (!defined($key)) { define($key, $value); } // for backward compatibility
}
function bibtexbrowser_configuration($key) {
global $CONFIGURATION;
if (isset($CONFIGURATION[$key])) {return $CONFIGURATION[$key];}
if (defined($key)) {return constant($key);}
throw new Exception('no such configuration parameter: '.$key);
}
function c($key) { // shortcut
return bibtexbrowser_configuration($key);
}
// *************** CONFIGURATION
// I recommend to put your changes in bibtexbrowser.local.php
// it will help you to upgrade the script with a new version
// the changes that require existing bibtexbrowser symbols should be in bibtexbrowser.after.php (included at the end of this file)
// per bibtex file configuration
@include('bibtexbrowser.local.php');
// the encoding of your bibtex file
@define('BIBTEX_INPUT_ENCODING','UTF-8');//@define('BIBTEX_INPUT_ENCODING','iso-8859-1');//define('BIBTEX_INPUT_ENCODING','windows-1252');
// the encoding of the HTML output
@define('OUTPUT_ENCODING','UTF-8');
// print a warning if deprecated variable is used
if (defined('ENCODING')) {
echo 'ENCODING has been replaced by BIBTEX_INPUT_ENCODING and OUTPUT_ENCODING';
}
// number of bib items per page
// we use the same parameter 'num' as Google
@define('PAGE_SIZE',isset($_GET['num'])?(preg_match('/^\d+$/',$_GET['num'])?$_GET['num']:10000):14);
// bibtexbrowser uses a small piece of Javascript to improve the user experience
// see http://en.wikipedia.org/wiki/Progressive_enhancement
// if you don't like it, you can be disable it by adding in bibtexbrowser.local.php
// @define('BIBTEXBROWSER_USE_PROGRESSIVE_ENHANCEMENT',false);
@define('BIBTEXBROWSER_USE_PROGRESSIVE_ENHANCEMENT',true);
@define('BIBLIOGRAPHYSTYLE','DefaultBibliographyStyle');// this is the name of a function
@define('BIBLIOGRAPHYSECTIONS','DefaultBibliographySections');// this is the name of a function
@define('BIBLIOGRAPHYTITLE','DefaultBibliographyTitle');// this is the name of a function
// shall we load MathJax to render math in $…$ in HTML?
@define('BIBTEXBROWSER_RENDER_MATH', true);
@define('MATHJAX_URI', '//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/config/TeX-AMS_HTML.js?V=2.7.1');
// the default jquery URI
@define('JQUERY_URI', '//code.jquery.com/jquery-3.6.4.min.js');
// can we load bibtex files on external servers?
@define('BIBTEXBROWSER_LOCAL_BIB_ONLY', true);
// the default view in {SimpleDisplay,AcademicDisplay,RSSDisplay,BibtexDisplay}
@define('BIBTEXBROWSER_DEFAULT_DISPLAY','SimpleDisplay');
// the default template
@define('BIBTEXBROWSER_DEFAULT_TEMPLATE','HTMLTemplate');
// the target frame of menu links
@define('BIBTEXBROWSER_MENU_TARGET','main'); // might be define('BIBTEXBROWSER_MENU_TARGET','_self'); in bibtexbrowser.local.php
@define('ABBRV_TYPE','index');// may be year/x-abbrv/key/none/index/keys-index
// are robots allowed to crawl and index bibtexbrowser generated pages?
@define('BIBTEXBROWSER_ROBOTS_NOINDEX',false);
//the default view in the "main" (right hand side) frame
@define('BIBTEXBROWSER_DEFAULT_FRAME','year=latest'); // year=latest,all and all valid bibtexbrowser queries
// Wrapper to use when we are included by another script
@define('BIBTEXBROWSER_EMBEDDED_WRAPPER', 'NoWrapper');
// Main class to use
@define('BIBTEXBROWSER_MAIN', 'Dispatcher');
// default order functions
// Contract Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
// can be @define('ORDER_FUNCTION','compare_bib_entry_by_title');
// can be @define('ORDER_FUNCTION','compare_bib_entry_by_bibtex_order');
@define('ORDER_FUNCTION','compare_bib_entry_by_year');
@define('ORDER_FUNCTION_FINE','compare_bib_entry_by_month');
// only displaying the n newest entries
@define('BIBTEXBROWSER_NEWEST',5);
@define('BIBTEXBROWSER_NO_DEFAULT', false);
// BIBTEXBROWSER_LINK_STYLE defines which function to use to display the links of a bibtex entry
@define('BIBTEXBROWSER_LINK_STYLE','bib2links_default'); // can be 'nothing' (a function that does nothing)
// do we add [bibtex] links ?
@define('BIBTEXBROWSER_BIBTEX_LINKS',true);
// do we add [pdf] links ?
// if the file extention is not .pdf, the field name (pdf, url, or file) is used instead
@define('BIBTEXBROWSER_PDF_LINKS',true);
// do we add [doi] links ?
@define('BIBTEXBROWSER_DOI_LINKS',true);
// do we add [gsid] links (Google Scholar)?
@define('BIBTEXBROWSER_GSID_LINKS',true);
// should pdf, doi, url, gsid links be opened in a new window?
@define('BIBTEXBROWSER_LINKS_TARGET','_self');// can be _blank (new window), _top (with frames)
// should authors be linked to [none/homepage/resultpage]
// none: nothing
// their homepage if defined as @strings
// their publication lists according to this bibtex
@define('BIBTEXBROWSER_AUTHOR_LINKS','homepage');
// BIBTEXBROWSER_LAYOUT defines the HTML rendering layout of the produced HTML
// may be table/list/ordered_list/definition/none (for <table>, <ol>, <dl>, nothing resp.).
// for list/ordered_list, the abbrevations are not taken into account (see ABBRV_TYPE)
// for ordered_list, the index is given by HTML directly (in increasing order)
@define('BIBTEXBROWSER_LAYOUT','table');
// should the original bibtex be displayed or a reconstructed one with filtering
// values: original/reconstructed
// warning, with reconstructed, the latex markup for accents/diacritics is lost
@define('BIBTEXBROWSER_BIBTEX_VIEW','original');
// a list of fields that will not be shown in the bibtex view if BIBTEXBROWSER_BIBTEX_VIEW=reconstructed
@define('BIBTEXBROWSER_BIBTEX_VIEW_FILTEREDOUT','comment|note|file');
// should Latex macros be executed (e.g. \'e -> é
@define('BIBTEXBROWSER_USE_LATEX2HTML',true);
// Which is the first html <hN> level that should be used in embedded mode?
@define('BIBTEXBROWSER_HTMLHEADINGLEVEL', 2);
@define('BIBTEXBROWSER_ACADEMIC_TOC', false);
@define('BIBTEXBROWSER_DEBUG',false);
// should we cache the parsed bibtex file?
// ref: https://github.com/monperrus/bibtexbrowser/issues/128
@define('BIBTEXBROWSER_USE_CACHE',true);
// how to print authors names?
// default => as in the bibtex file
// USE_COMMA_AS_NAME_SEPARATOR_IN_OUTPUT = true => "Meyer, Herbert"
// USE_INITIALS_FOR_NAMES = true => "Meyer H"
// USE_FIRST_THEN_LAST => Herbert Meyer
@define('USE_COMMA_AS_NAME_SEPARATOR_IN_OUTPUT',false);// output authors in a comma separated form, e.g. "Meyer, H"?
@define('USE_INITIALS_FOR_NAMES',false); // use only initials for all first names?
@define('USE_FIRST_THEN_LAST',false); // put first names before last names?
@define('FORCE_NAMELIST_SEPARATOR', ''); // if non-empty, use this to separate multiple names regardless of USE_COMMA_AS_NAME_SEPARATOR_IN_OUTPUT
@define('LAST_AUTHOR_SEPARATOR',' and ');
@define('USE_OXFORD_COMMA',false); // adds an additional separator in addition to LAST_AUTHOR_SEPARATOR if there are more than two authors
@define('TYPES_SIZE',10); // number of entry types per table
@define('YEAR_SIZE',20); // number of years per table
@define('AUTHORS_SIZE',30); // number of authors per table
@define('TAGS_SIZE',30); // number of keywords per table
@define('READLINE_LIMIT',1024);
@define('Q_YEAR', 'year');
@define('Q_YEAR_PAGE', 'year_page');
@define('Q_YEAR_INPRESS', 'in press');
@define('Q_YEAR_ACCEPTED', 'accepted');
@define('Q_YEAR_SUBMITTED', 'submitted');
@define('Q_FILE', 'bib');
@define('Q_AUTHOR', 'author');
@define('Q_AUTHOR_PAGE', 'author_page');
@define('Q_TAG', 'keywords');
@define('Q_TAG_PAGE', 'keywords_page');
@define('Q_TYPE', 'type');// used for queries
@define('Q_TYPE_PAGE', 'type_page');
@define('Q_ALL', 'all');
@define('Q_ENTRY', 'entry');
@define('Q_KEY', 'key');
@define('Q_KEYS', 'keys'); // filter entries using a url-encoded, JSON-encoded array of bibtex keys
@define('Q_SEARCH', 'search');
@define('Q_EXCLUDE', 'exclude');
@define('Q_RESULT', 'result');
@define('Q_ACADEMIC', 'academic');
@define('Q_DB', 'bibdb');
@define('Q_LATEST', 'latest');
@define('Q_RANGE', 'range');
@define('AUTHOR', 'author');
@define('EDITOR', 'editor');
@define('SCHOOL', 'school');
@define('TITLE', 'title');
@define('BOOKTITLE', 'booktitle');
@define('YEAR', 'year');
@define('BUFFERSIZE',100000);
@define('MULTIPLE_BIB_SEPARATOR',';');
@define('METADATA_COINS',true); // see https://en.wikipedia.org/wiki/COinS
@define('METADATA_GS',false); // metadata google scholar, see http://www.monperrus.net/martin/accurate+bibliographic+metadata+and+google+scholar
@define('METADATA_DC',true); // see http://dublincore.org/
@define('METADATA_OPENGRAPH',true); // see http://ogp.me/
@define('METADATA_EPRINTS',false); // see https://wiki.eprints.org/w/Category:EPrints_Metadata_Fields
// define sort order for special values in 'year' field
// highest number is sorted first
// don't exceed 0 though, since the values are added to PHP_INT_MAX
@define('ORDER_YEAR_INPRESS', 0);
@define('ORDER_YEAR_ACCEPTED', 1);
@define('ORDER_YEAR_SUBMITTED', 2);
@define('ORDER_YEAR_OTHERNONINT', 3);
// in embedded mode, we still need a URL for displaying bibtex entries alone
// this is usually resolved to bibtexbrowser.php
// but can be overridden in bibtexbrowser.local.php
// for instance with @define('BIBTEXBROWSER_URL',''); // links to the current page with ?
@define('BIBTEXBROWSER_URL',basename(__FILE__));
// Specify the location of the cache file for servers that need temporary files written in a specific location
@define('CACHE_DIR','');
// Specify the location of the bib file for servers that need do not allow slashes in URLs,
// where the bib file and bibtexbrowser.php are in different directories.
@define('DATA_DIR','');
// *************** END CONFIGURATION
define('Q_INNER_AUTHOR', '_author');// internally used for representing the author
define('Q_INNER_TYPE', 'x-bibtex-type');// used for representing the type of the bibtex entry internally
@define('Q_INNER_KEYS_INDEX', '_keys-index');// used for storing indices in $_GET[Q_KEYS] array
define('Q_NAME', 'name');// used to allow for exact last name matches in multisearch
define('Q_AUTHOR_NAME', 'author_name');// used to allow for exact last name matches in multisearch
define('Q_EDITOR_NAME', 'editor_name');// used to allow for exact last name matches in multisearch
// for clean search engine links
// we disable url rewriting
// ... and hope that your php configuration will accept one of these
@ini_set("session.use_only_cookies",1);
@ini_set("session.use_trans_sid",0);
@ini_set("url_rewriter.tags","");
function nothing() {}
function config_value($key) {
global $CONFIGURATION;
if (isset($CONFIGURATION[$key])) { return $CONFIGURATION[$key]; }
if (defined($key)) { return constant($key); }
die('no such configuration: '.$key);
}
/** parses $_GET[Q_FILE] and puts the result (an object of type BibDataBase) in $_GET[Q_DB].
See also zetDB().
*/
function setDB() {
list($db, $parsed, $updated, $saved) = _zetDB(@$_GET[Q_FILE]);
$_GET[Q_DB] = $db;
return $updated;
}
/** parses the $bibtex_filenames (usually semi-column separated) and returns an object of type BibDataBase.
See also setDB()
*/
function zetDB($bibtex_filenames) {
list($db, $parsed, $updated, $saved) = _zetDB($bibtex_filenames);
return $db;
}
/** @nodoc */
function default_message() {
if (config_value('BIBTEXBROWSER_NO_DEFAULT')==true) { return; }
?>
<div id="bibtexbrowser_message">
Congratulations! bibtexbrowser is correctly installed!<br/>
Now you have to pass the name of the bibtex file as parameter (e.g. bibtexbrowser.php?bib=mybib.php)<br/>
You may browse:<br/>
<?php
foreach (glob("*.bib") as $bibfile) {
$url="?bib=".urlencode($bibfile);
echo '<a href="'.htmlspecialchars($url, ENT_QUOTES, 'UTF-8').'" rel="nofollow">'.htmlspecialchars($bibfile, ENT_QUOTES, 'UTF-8').'</a><br/>';
}
echo "</div>";
}
/** returns the target of links */
function get_target() {
if (c('BIBTEXBROWSER_LINKS_TARGET')!='_self') {
return " target=\"".c('BIBTEXBROWSER_LINKS_TARGET')."\"";
}
else return "";
}
/** @nodoc */
function _zetDB($bibtex_filenames) {
$db = null;
// default bib file, if no file is specified in the query string.
if (!isset($bibtex_filenames) || $bibtex_filenames == "") {
default_message();
exit;
}
// first does the bibfiles exist:
// $bibtex_filenames can be urlencoded for instance if they contain slashes
// so we decode it
$bibtex_filenames = urldecode($bibtex_filenames);
// ---------------------------- HANDLING unexistent files
foreach(explode(MULTIPLE_BIB_SEPARATOR, $bibtex_filenames) as $bib) {
// get file extension to only allow .bib files
$ext = pathinfo($bib, PATHINFO_EXTENSION);
// this is a security protection
if (BIBTEXBROWSER_LOCAL_BIB_ONLY && (!file_exists(DATA_DIR.$bib) || strcasecmp($ext, 'bib') != 0)) {
// to automate dectection of faulty links with tools such as webcheck
header('HTTP/1.1 404 Not found');
// escape $bib to prevent XSS
$escapedBib = htmlEntities($bib, ENT_QUOTES);
die('<b>the bib file '.$escapedBib.' does not exist !</b>');
}
} // end for each
// ---------------------------- HANDLING HTTP If-modified-since
// testing with $ curl -v --header "If-Modified-Since: Fri, 23 Oct 2010 19:22:47 GMT" "... bibtexbrowser.php?key=wasylkowski07&bib=..%252Fstrings.bib%253B..%252Fentries.bib"
// and $ curl -v --header "If-Modified-Since: Fri, 23 Oct 2000 19:22:47 GMT" "... bibtexbrowser.php?key=wasylkowski07&bib=..%252Fstrings.bib%253B..%252Fentries.bib"
// save bandwidth and server cpu
// (imagine the number of requests from search engine bots...)
$bib_is_unmodified = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ;
foreach(explode(MULTIPLE_BIB_SEPARATOR, $bibtex_filenames) as $bib) {
$bib_is_unmodified =
$bib_is_unmodified
&& (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])>filemtime($bib));
} // end for each
if ( $bib_is_unmodified && !headers_sent()) {
header("HTTP/1.1 304 Not Modified");
exit;
}
$parse=true;
$updated = false;
if (config_value('BIBTEXBROWSER_USE_CACHE')==true) {
// ---------------------------- HANDLING caching of compiled bibtex files
// for sake of performance, once the bibtex file is parsed
// we try to save a "compiled" in a txt file
$compiledbib = CACHE_DIR.'bibtexbrowser_'.md5($bibtex_filenames).'.dat';
$parse=filemtime(__FILE__)>@filemtime($compiledbib);
// do we have a compiled version ?
if (is_file($compiledbib)
&& is_readable($compiledbib)
&& filesize($compiledbib)>0
) {
$f = fopen($compiledbib,'r+'); // some Unix seem to consider flock as a writing operation
//we use a lock to avoid that a call to bibbtexbrowser made while we write the object loads an incorrect object
if (flock($f,LOCK_EX)) {
$s = filesize($compiledbib);
$ser = fread($f,$s);
$db = @unserialize($ser);
flock($f,LOCK_UN);
} else { die('could not get the lock'); }
fclose($f);
// basic test
// do we have an correct version of the file
if (!is_a($db,'BibDataBase')) {
unlink($compiledbib);
if (BIBTEXBROWSER_DEBUG) { die('$db not a BibDataBase. please reload.'); }
$parse=true;
}
} else {$parse=true;}
}
// we don't have a compiled version
if ($parse) {
//echo '<!-- parsing -->';
// then parsing the file
$db = createBibDataBase();
foreach(explode(MULTIPLE_BIB_SEPARATOR, $bibtex_filenames) as $bib) {
$db->load($bib);
}
}
if (config_value('BIBTEXBROWSER_USE_CACHE')==true) {
// now we may update the database
if (!file_exists($compiledbib)) {
@touch($compiledbib);
$updated = true; // limit case
} else foreach(explode(MULTIPLE_BIB_SEPARATOR, $bibtex_filenames) as $bib) {
// is it up to date ? wrt to the bib file and the script
// then upgrading with a new version of bibtexbrowser triggers a new compilation of the bib file
if (filemtime($bib)>filemtime($compiledbib) || filemtime(__FILE__)>filemtime($compiledbib)) {
// echo "updating ".$bib;
$db->update($bib);
$updated = true;
}
}
}
// echo var_export($parse);
// echo var_export($updated);
$saved = false;
// are we able to save the compiled version ?
// note that the compiled version is saved in the current working directory
if ( config_value('BIBTEXBROWSER_USE_CACHE')==true && ( $parse || $updated ) && is_writable($compiledbib)) {
// we use 'a' because the file is not locked between fopen and flock
$f = fopen($compiledbib,'a');
//we use a lock to avoid that a call to bibbtexbrowser made while we write the object loads an incorrect object
if (flock($f,LOCK_EX)) {
// echo '<!-- saving -->';
ftruncate($f,0);
fwrite($f,serialize($db));
flock($f,LOCK_UN);
$saved = true;
} else { die('could not get the lock'); }
fclose($f);
} // end saving the cached verions
//else echo '<!-- please chmod the directory containing the bibtex file to be able to keep a compiled version (much faster requests for large bibtex files) -->';
return array($db, $parse, $updated, $saved);
} // end function setDB
// internationalization
if (!function_exists('__')){
function __($msg) {
global $BIBTEXBROWSER_LANG;
if (isset($BIBTEXBROWSER_LANG[$msg])) {
return $BIBTEXBROWSER_LANG[$msg];
}
return $msg;
}
}
// factories
// may be overridden in bibtexbrowser.local.php
if (!function_exists('createBibDataBase')) {
/** factory method for openness @nodoc */
function createBibDataBase() { $x = new BibDataBase(); return $x;}
}
if (!function_exists('createBibEntry')) {
/** factory method for openness @nodoc */
function createBibEntry() { $x = new BibEntry(); return $x;}
}
if (!function_exists('createBibDBBuilder')) {
/** factory method for openness @nodoc */
function createBibDBBuilder() { $x = new BibDBBuilder(); return $x;}
}
if (!function_exists('createBasicDisplay')) {
/** factory method for openness @nodoc */
function createBasicDisplay() { $x = new SimpleDisplay(); return $x;}
}
if (!function_exists('createBibEntryDisplay')) {
/** factory method for openness @nodoc */
function createBibEntryDisplay() { $x = new BibEntryDisplay(); return $x;}
}
if (!function_exists('createMenuManager')) {
/** factory method for openness @nodoc */
function createMenuManager() { $x = new MenuManager(); return $x;}
}
////////////////////////////////////////////////////////
/** is a generic parser of bibtex files.
usage:
<pre>
$delegate = new XMLPrettyPrinter();// or another delegate such as BibDBBuilder
$parser = new StateBasedBibtexParser($delegate);
$parser->parse(fopen('bibacid-utf8.bib','r'));
</pre>
notes:
- It has no dependencies, it can be used outside of bibtexbrowser
- The delegate is expected to have some methods, see classes BibDBBuilder and XMLPrettyPrinter
*/
class StateBasedBibtexParser {
var $delegate;
function __construct($delegate) {
$this->delegate = $delegate;
}
function parse($handle) {
if (gettype($handle) == 'string') { throw new Exception('oops'); }
$delegate = $this->delegate;
// STATE DEFINITIONS
@define('NOTHING',1);
@define('GETTYPE',2);
@define('GETKEY',3);
@define('GETVALUE',4);
@define('GETVALUEDELIMITEDBYQUOTES',5);
@define('GETVALUEDELIMITEDBYQUOTES_ESCAPED',6);
@define('GETVALUEDELIMITEDBYCURLYBRACKETS',7);
@define('GETVALUEDELIMITEDBYCURLYBRACKETS_ESCAPED',8);
@define('GETVALUEDELIMITEDBYCURLYBRACKETS_1NESTEDLEVEL',9);
@define('GETVALUEDELIMITEDBYCURLYBRACKETS_1NESTEDLEVEL_ESCAPED',10);
@define('GETVALUEDELIMITEDBYCURLYBRACKETS_2NESTEDLEVEL',11);
@define('GETVALUEDELIMITEDBYCURLYBRACKETS_2NESTEDLEVEL_ESCAPED',12);
@define('GETVALUEDELIMITEDBYCURLYBRACKETS_3NESTEDLEVEL',13);
@define('GETVALUEDELIMITEDBYCURLYBRACKETS_3NESTEDLEVEL_ESCAPED',14);
$state=NOTHING;
$entrytype='';
$entrykey='';
$entryvalue='';
$fieldvaluepart='';
$finalkey='';
$entrysource='';
// metastate
$isinentry = false;
$delegate->beginFile();
// if you encounter this error "Allowed memory size of xxxxx bytes exhausted"
// then decrease the size of the temp buffer below
$bufsize=BUFFERSIZE;
while (!feof($handle)) {
$sread=fread($handle,$bufsize);
//foreach(str_split($sread) as $s) {
for ( $i=0; $i < strlen( $sread ); $i++) { $s=$sread[$i];
if ($isinentry) $entrysource.=$s;
if ($state==NOTHING) {
// this is the beginning of an entry
if ($s=='@') {
$delegate->beginEntry();
$state = GETTYPE;
$isinentry = true;
$entrysource='@';
}
}
else if ($state==GETTYPE) {
// this is the beginning of a key
if ($s=='{') {
$state = GETKEY;
$delegate->setEntryType($entrytype);
$entrytype='';
}
else $entrytype=$entrytype.$s;
}
else if ($state==GETKEY) {
// now we get the value
if ($s=='=') {
$state = GETVALUE;
$fieldvaluepart='';
$finalkey=$entrykey;
$entrykey='';
}
// oups we only have the key :-) anyway
else if ($s=='}') {
$state = NOTHING;$isinentry = false;$delegate->endEntry($entrysource);
$entrykey='';
}
// OK now we look for values
else if ($s==',') {
$state=GETKEY;
$delegate->setEntryKey($entrykey);
$entrykey='';}
else { $entrykey=$entrykey.$s; }
}
// we just got a =, we can now receive the value, but we don't now whether the value
// is delimited by curly brackets, double quotes or nothing
else if ($state==GETVALUE) {
// the value is delimited by double quotes
if ($s=='"') {
$state = GETVALUEDELIMITEDBYQUOTES;
}
// the value is delimited by curly brackets
else if ($s=='{') {
$state = GETVALUEDELIMITEDBYCURLYBRACKETS;
}
// the end of the key and no value found: it is the bibtex key e.g. \cite{Descartes1637}
else if ($s==',') {
$state = GETKEY;
$delegate->setEntryField($finalkey,$entryvalue);
$entryvalue=''; // resetting the value buffer
}
// this is the end of the value AND of the entry
else if ($s=='}') {
$state = NOTHING;
$delegate->setEntryField($finalkey,$entryvalue);
$isinentry = false;$delegate->endEntry($entrysource);
$entryvalue=''; // resetting the value buffer
}
else if ($s==' ' || $s=="\t" || $s=="\n" || $s=="\r" ) {
// blank characters are not taken into account when values are not in quotes or curly brackets
}
else {
$entryvalue=$entryvalue.$s;
}
}
/* GETVALUEDELIMITEDBYCURLYBRACKETS* handle entries delimited by curly brackets and the possible nested curly brackets */
else if ($state==GETVALUEDELIMITEDBYCURLYBRACKETS) {
if ($s=='\\') {
$state = GETVALUEDELIMITEDBYCURLYBRACKETS_ESCAPED;
$entryvalue=$entryvalue.$s;}
else if ($s=='{') {
$state = GETVALUEDELIMITEDBYCURLYBRACKETS_1NESTEDLEVEL;
$entryvalue=$entryvalue.$s;
$delegate->entryValuePart($finalkey,$fieldvaluepart,'CURLYTOP');
$fieldvaluepart='';
}
else if ($s=='}') { // end entry
$state = GETVALUE;
$delegate->entryValuePart($finalkey,$fieldvaluepart,'CURLYTOP');
}
else {
$entryvalue=$entryvalue.$s;
$fieldvaluepart=$fieldvaluepart.$s;
}
}
// handle anti-slashed brackets
else if ($state==GETVALUEDELIMITEDBYCURLYBRACKETS_ESCAPED) {
$state = GETVALUEDELIMITEDBYCURLYBRACKETS;
$entryvalue=$entryvalue.$s;
}
// in first level of curly bracket
else if ($state==GETVALUEDELIMITEDBYCURLYBRACKETS_1NESTEDLEVEL) {
if ($s=='\\') {
$state = GETVALUEDELIMITEDBYCURLYBRACKETS_1NESTEDLEVEL_ESCAPED;
$entryvalue=$entryvalue.$s;}
else if ($s=='{') {
$state = GETVALUEDELIMITEDBYCURLYBRACKETS_2NESTEDLEVEL;$entryvalue=$entryvalue.$s;}
else if ($s=='}') {
$state = GETVALUEDELIMITEDBYCURLYBRACKETS;
$delegate->entryValuePart($finalkey,$fieldvaluepart,'CURLYONE');
$fieldvaluepart='';
$entryvalue=$entryvalue.$s;
}
else {
$entryvalue=$entryvalue.$s;
$fieldvaluepart=$fieldvaluepart.$s;
}
}
// handle anti-slashed brackets
else if ($state==GETVALUEDELIMITEDBYCURLYBRACKETS_1NESTEDLEVEL_ESCAPED) {
$state = GETVALUEDELIMITEDBYCURLYBRACKETS_1NESTEDLEVEL;
$entryvalue=$entryvalue.$s;
}
// in second level of curly bracket
else if ($state==GETVALUEDELIMITEDBYCURLYBRACKETS_2NESTEDLEVEL) {
if ($s=='\\') {
$state = GETVALUEDELIMITEDBYCURLYBRACKETS_2NESTEDLEVEL_ESCAPED;
$entryvalue=$entryvalue.$s;}
else if ($s=='{') {
$state = GETVALUEDELIMITEDBYCURLYBRACKETS_3NESTEDLEVEL;$entryvalue=$entryvalue.$s;}
else if ($s=='}') {
$state = GETVALUEDELIMITEDBYCURLYBRACKETS_1NESTEDLEVEL;$entryvalue=$entryvalue.$s;}
else { $entryvalue=$entryvalue.$s;}
}
// handle anti-slashed brackets
else if ($state==GETVALUEDELIMITEDBYCURLYBRACKETS_2NESTEDLEVEL_ESCAPED) {
$state = GETVALUEDELIMITEDBYCURLYBRACKETS_2NESTEDLEVEL;
$entryvalue=$entryvalue.$s;
}
// in third level of curly bracket
else if ($state==GETVALUEDELIMITEDBYCURLYBRACKETS_3NESTEDLEVEL) {
if ($s=='\\') {
$state = GETVALUEDELIMITEDBYCURLYBRACKETS_3NESTEDLEVEL_ESCAPED;
$entryvalue=$entryvalue.$s;}
else if ($s=='}') {
$state = GETVALUEDELIMITEDBYCURLYBRACKETS_2NESTEDLEVEL;$entryvalue=$entryvalue.$s;}
else { $entryvalue=$entryvalue.$s;}
}
// handle anti-slashed brackets
else if ($state==GETVALUEDELIMITEDBYCURLYBRACKETS_3NESTEDLEVEL_ESCAPED) {
$state = GETVALUEDELIMITEDBYCURLYBRACKETS_3NESTEDLEVEL;
$entryvalue=$entryvalue.$s;
}
/* handles entries delimited by double quotes */
else if ($state==GETVALUEDELIMITEDBYQUOTES) {
if ($s=='\\') {
$state = GETVALUEDELIMITEDBYQUOTES_ESCAPED;
$entryvalue=$entryvalue.$s;}
else if ($s=='"') {
$state = GETVALUE;
}
else { $entryvalue=$entryvalue.$s;}
}
// handle anti-double quotes
else if ($state==GETVALUEDELIMITEDBYQUOTES_ESCAPED) {
$state = GETVALUEDELIMITEDBYQUOTES;
$entryvalue=$entryvalue.$s;
}
} // end for
} // end while
$delegate->endFile();
//$d = $this->delegate;print_r($d);
} // end function
} // end class
/** a default empty implementation of a delegate for StateBasedBibtexParser */
class ParserDelegate {
function beginFile() {}
function endFile() {}
function setEntryField($finalkey,$entryvalue) {}
function setEntryType($entrytype) {}
function setEntryKey($entrykey) {}
function beginEntry() {}
function endEntry($entrysource) {}
/** called for each sub parts of type {part} of a field value
* for now, only CURLYTOP and CURLYONE events
*/
function entryValuePart($key, $value, $type) {}
} // end class ParserDelegate
/** is a possible delegate for StateBasedBibParser.
usage:
see snippet of [[#StateBasedBibParser]]
*/
class XMLPrettyPrinter extends ParserDelegate {
function beginFile() {
header('Content-type: text/xml;');
print '<?xml version="1.0" encoding="'.OUTPUT_ENCODING.'"?>';
print '<bibfile>';
}
function endFile() {
print '</bibfile>';
}
function setEntryField($finalkey,$entryvalue) {
print "<data>\n<key>".$finalkey."</key>\n<value>".$entryvalue."</value>\n</data>\n";
}
function setEntryType($entrytype) {
print '<type>'.$entrytype.'</type>';
}
function setEntryKey($entrykey) {
print '<keyonly>'.$entrykey.'</keyonly>';
}
function beginEntry() {
print "<entry>\n";
}
function endEntry($entrysource) {
print "</entry>\n";
}
} // end class XMLPrettyPrinter
/** represents @string{k=v} */
class StringEntry {
public $filename;
public $name;
public $value;
function __construct($k, $v, $filename) {
$this->name=$k;
$this->value=$v;
$this->filename=$filename;
}
function toString() {
return '@string{'.$this->name.'={'.$this->value.'}}';
}
} // end class StringEntry
/** builds arrays of BibEntry objects from a bibtex file.
usage:
<pre>
$empty_array = array();
$db = new BibDBBuilder(); // see also factory method createBibDBBuilder
$db->build('bibacid-utf8.bib'); // parses bib file
print_r($db->builtdb);// an associated array key -> BibEntry objects
print_r($db->stringdb);// an associated array key -> strings representing @string
</pre>
notes:
method build can be used several times, bibtex entries are accumulated in the builder
*/
class BibDBBuilder extends ParserDelegate {
/** A hashtable from keys to bib entries (BibEntry). */
var $builtdb = array();
/** A hashtable of constant strings */
var $stringdb = array();
var $filename;
var $currentEntry;
function build($bibfilename, $handle = NULL) {
$this->filename = $bibfilename;
if ($handle == NULL) {
$handle = fopen(DATA_DIR.$bibfilename, "r");
}
if (!$handle) die ('cannot open '.$bibfilename);
$parser = new StateBasedBibtexParser($this);
$parser->parse($handle);
fclose($handle);
//print_r(array_keys($this->builtdb));
//print_r($this->builtdb);
}
function getBuiltDb() {
//print_r($this->builtdb);
return $this->builtdb;
}
function beginFile() {
}
function endFile() {
// resolving crossrefs
// we are careful with PHP 4 semantics
foreach (array_keys($this->builtdb) as $key) {
$bib = $this->builtdb[$key];
if ($bib->hasField('crossref')) {
if (isset($this->builtdb[$bib->getField('crossref')])) {
$crossrefEntry = $this->builtdb[$bib->getField('crossref')];
$bib->crossref = $crossrefEntry;
foreach($crossrefEntry->getFields() as $k => $v) {
// copying the fields of the cross ref
// only if they don't exist yet
if (!$bib->hasField($k)) {
$bib->setField($k,$v);
}
}
}
}
}
//print_r($this->builtdb);
}
function setEntryField($fieldkey,$entryvalue) {
$fieldkey=trim($fieldkey);
// support for Bibtex concatenation
// see http://newton.ex.ac.uk/tex/pack/bibtex/btxdoc/node3.html
// (?<! is a negative look-behind assertion, see http://www.php.net/manual/en/regexp.reference.assertions.php
$entryvalue_array=preg_split('/(?<!\\\\)#/', $entryvalue);
foreach ($entryvalue_array as $k=>$v) {
// spaces are allowed when using # and they are not taken into account
// however # is not itself replaced by a space
// warning: @strings are not case sensitive
// see http://newton.ex.ac.uk/tex/pack/bibtex/btxdoc/node3.html
$stringKey=strtolower(trim($v));
if (isset($this->stringdb[$stringKey]))
{
// this field will be formated later by xtrim and latex2html
$entryvalue_array[$k]=$this->stringdb[$stringKey]->value;
// we keep a trace of this replacement
// so as to produce correct bibtex snippets
$this->currentEntry->constants[$stringKey]=$this->stringdb[$stringKey]->value;
}
}
$entryvalue=implode('',$entryvalue_array);
$this->currentEntry->setField($fieldkey,$entryvalue);
}
function setEntryType($entrytype) {
$this->currentEntry->setType($entrytype);
}
function setEntryKey($entrykey) {
//echo "new entry:".$entrykey."\n";
$this->currentEntry->setKey($entrykey);
}
function beginEntry() {
$this->currentEntry = createBibEntry();
$this->currentEntry->setFile($this->filename);
}
function endEntry($entrysource) {
// we add a timestamp
$this->currentEntry->timestamp();
// we add a key if there is no key
if (!$this->currentEntry->hasField(Q_KEY) && $this->currentEntry->getType()!='string') {
$this->currentEntry->setField(Q_KEY,md5($entrysource));
}
// we set the fulltext
$this->currentEntry->text = $entrysource;
// we format the author names in a special field
// to enable search
if ($this->currentEntry->hasField('author')) {
$this->currentEntry->setField(Q_INNER_AUTHOR,$this->currentEntry->getFormattedAuthorsString());
foreach($this->currentEntry->getCanonicalAuthors() as $author) {
$homepage_key = $this->currentEntry->getHomePageKey($author);
if (isset($this->stringdb[$homepage_key])) {
$this->currentEntry->homepages[$homepage_key] = $this->stringdb[$homepage_key]->value;
}
}
}
// ignoring jabref comments
if (($this->currentEntry->getType()=='comment')) {
/* do nothing for jabref comments */
}
// we add it to the string database
else if ($this->currentEntry->getType()=='string') {
foreach($this->currentEntry->fields as $k => $v) {
$k!=Q_INNER_TYPE and $this->stringdb[$k] = new StringEntry($k,$v,$this->filename);
}
}
// we add it to the database
else {
$this->builtdb[$this->currentEntry->getKey()] = $this->currentEntry;
}
}
} // end class BibDBBuilder
/** is an extended version of the trim function, removes linebreaks, tabs, etc.
*/
function xtrim($line) {
$line = trim($line);
// we remove the unneeded line breaks
// this is *required* to correctly split author lists into names
// 2010-06-30
// bug found by Thomas
// windows new line is **\r\n"** and not the other way around!!
// according to php.net: Proncess \r\n's first so they aren't converted twice
$line = str_replace(array("\r\n", "\r", "\n", "\t"), ' ', $line);
// remove superfluous spaces e.g. John+++Bar
$line = preg_replace('/ {2,}/',' ', $line);
return $line;
}
/** encapsulates the conversion of a single latex chars to the corresponding HTML entity.
It expects a **lower-case** char.
*/
function char2html($line,$latexmodifier,$char,$entitiyfragment) {
$line = char2html_case_sensitive($line,$latexmodifier,strtoupper($char),$entitiyfragment);
return char2html_case_sensitive($line,$latexmodifier,strtolower($char),$entitiyfragment);
}
function char2html_case_sensitive($line,$latexmodifier,$char,$entitiyfragment) {
$line = preg_replace('/\\{?\\\\'.preg_quote($latexmodifier,'/').' ?\\{?'.$char.'\\}?/','&'.$char.''.$entitiyfragment.';', $line);
return $line;
}