forked from monperrus/bibtexbrowser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bibtexbrowser.php
executable file
·3957 lines (3328 loc) · 121 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 v__GITHUB__ -->
URL: http://www.monperrus.net/martin/bibtexbrowser/
Feedback & Bug Reports: [email protected]
(C) 2013 Matthieu Guillaumin
(C) 2006-2013 Martin Monperrus
(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('ENCODING', 'latin1) in bibtexbrowser.local.php
global $CONFIGURATION;
$CONFIGURATION = array();
function bibtexbrowser_configure($key, $value) {
global $CONFIGURATION;
$CONFIGURATION[$key]=$value;
}
// *************** 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)
@include(preg_replace('/\.php$/','.local.php',__FILE__));
// there is no encoding transformation from the bibtex file to the html file
// if your bibtex file contains 8 bits characters in utf-8
// change the following parameter
@define('ENCODING','UTF-8');//@define('ENCODING','iso-8859-1');//define('ENCODING','windows-1252');
// 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);
// if you disable the Javascript progressive enhancement,
// you may want the links to be open in a new window/tab
// if yes, add in bibtexbrowser.local.php define('BIBTEXBROWSER_BIB_IN_NEW_WINDOW',true);
@define('BIBTEXBROWSER_BIB_IN_NEW_WINDOW',false);
@define('BIBLIOGRAPHYSTYLE','DefaultBibliographyStyle');// this is the name of a function
@define('BIBLIOGRAPHYSECTIONS','DefaultBibliographySections');// this is the name of a function
// 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
//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');
@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');
// do we add [bibtex] links ?
@define('BIBTEXBROWSER_BIBTEX_LINKS',true);
// do we add [pdf] links ?
@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 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 (for <table>, <ol>, <dl> 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');
@define('BIBTEXBROWSER_DEBUG',false);
@define('COMMA_NAMES',false);// do have authors in a comma separated form?
@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_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('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_GS',true);
@define('METADATA_DC',true);
@define('METADATA_EPRINTS',false);
// 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__));
// *************** 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
// 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","");
// we ensure that the pages won't get polluted
// if future versions of PHP change warning mechanisms...
@error_reporting(/*pp4php:serl*/E_ALL/*lres*/);
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=".$bibfile; echo '<a href="'.$url.'" rel="nofollow">'.$bibfile.'</a><br/>';
}
echo "</div>";
}
/** @nodoc */
function _zetDB($bibtex_filenames) {
$db = null;
// Check if magic_quotes_runtime is active
if(get_magic_quotes_runtime())
{
// Deactivate
// otherwise it does not work
set_magic_quotes_runtime(false);
}
// 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($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;
}
// ---------------------------- 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 = '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);
}
}
$updated = false;
// 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 ( ($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('foo.bib');
</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 StateBasedBibtexParser(&$delegate) {
$this->delegate = &$delegate;
}
function parse($handle) {
$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='';
$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;
$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(trim($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(trim($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;}
else if ($s=='}') {
$state = GETVALUE;}
else { $entryvalue=$entryvalue.$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;$entryvalue=$entryvalue.$s;}
else { $entryvalue=$entryvalue.$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
/** is a delegate for StateBasedBibParser.
usage:
see snippet of [[#StateBasedBibParser]]
*/
class XMLPrettyPrinter {
function beginFile() {
header('Content-type: text/xml;');
print '<?xml version="1.0" encoding="'.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 {
function StringEntry($k, $v, $filename) {
$this->name=$k;
$this->value=$v;
$this->filename=$filename;
}
} // 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('foo.bib'); // parses foo.bib
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 {
/** 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($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($finalkey,$entryvalue) {
// 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($finalkey,$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($this->currentEntry->getTitle().implode('',$this->currentEntry->getRawAuthors())));
}
// 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->getFormattedAuthorsImproved());
}
// 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!!
$line = str_replace("\r\n",' ', $line);//windows like
$line = str_replace("\n",' ', $line);//unix-like
// we also replace tabs
$line = str_replace("\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) {
// old version
// $line = str_replace('\\'.$latexmodifier.$char,'&'.$char.''.$entitiyfragment.';', $line);
// $line = str_replace('\\'.$latexmodifier.' '.$char,'&'.$char.''.$entitiyfragment.';', $line);
// $line = str_replace('\\'.$latexmodifier.'{'.$char.'}','&'.$char.''.$entitiyfragment.';', $line);
$line = preg_replace('/\\\\'.preg_quote($latexmodifier,'/').' ?\\{?'.$char.'\\}?/','&'.$char.''.$entitiyfragment.';', $line);
return $line;
}
/** converts latex chars to HTML entities.
(I still look for a comprehensive translation table from late chars to html, better than [[http://isdc.unige.ch/Newsletter/help.html]])
*/
function latex2html($line) {
$maths = array();
$index = 0;
// first we escape the math env
preg_match_all('/\$.*?\$/', $line, $matches);
foreach ($matches[0] as $k) {
$maths[] = $k;
$line = str_replace($k, '__MATH'.$index.'__', $line);
$index++;
}
$line = preg_replace('/([^\\\\])~/','\\1 ', $line);
// performance increases with this test
// bug found by Serge Barral: what happens if we have curly braces only (typically to ensure case in Latex)
// added && strpos($line,'{')===false
if (strpos($line,'\\')===false && strpos($line,'{')===false) return $line;
// we should better replace this before the others
// in order not to mix with the HTML entities coming after (just in case)
$line = str_replace('\\&','&', $line);
// handling \url{....}
// often used in howpublished for @misc
$line = preg_replace('/\\\\url\{(.*)\}/U','<a href="\\1">\\1</a>', $line);
// Friday, April 01 2011
// added support for accented i
// for instance \`\i
// see http://en.wikibooks.org/wiki/LaTeX/Accents
// " the letters "i" and "j" require special treatment when they are given accents because it is often desirable to replace the dot with the accent. For this purpose, the commands \i and \j can be used to produce dotless letters."
$line = preg_replace('/\\\\([ij])/i','\\1', $line);
$line = char2html($line,"'",'a',"acute");
$line = char2html($line,"'",'e',"acute");
$line = char2html($line,"'",'i',"acute");
$line = char2html($line,"'",'o',"acute");
$line = char2html($line,"'",'u',"acute");
$line = char2html($line,"'",'y',"acute");
$line = char2html($line,"'",'n',"acute");
$line = char2html($line,'`','a',"grave");
$line = char2html($line,'`','e',"grave");
$line = char2html($line,'`','i',"grave");
$line = char2html($line,'`','o',"grave");
$line = char2html($line,'`','u',"grave");
$line = char2html($line,'~','a',"tilde");
$line = char2html($line,'~','n',"tilde");
$line = char2html($line,'~','o',"tilde");
$line = char2html($line,'"','a',"uml");
$line = char2html($line,'"','e',"uml");
$line = char2html($line,'"','i',"uml");
$line = char2html($line,'"','o',"uml");
$line = char2html($line,'"','u',"uml");
$line = char2html($line,'"','y',"uml");
$line = char2html($line,'^','a',"circ");
$line = char2html($line,'^','e',"circ");
$line = char2html($line,'^','i',"circ");
$line = char2html($line,'^','o',"circ");
$line = char2html($line,'^','u',"circ");
$line = char2html($line,'r','a',"ring");
$line = char2html($line,'c','c',"cedil");
$line = char2html($line,'v','s',"caron");
$line = str_replace('\\ae','æ', $line);
$line = str_replace('\\ss','ß', $line);
$line = str_replace('\\o','ø', $line);
$line = str_replace('\\O','Ø', $line);
$line = str_replace('\\aa','å', $line);
$line = str_replace('\\AA','Å', $line);
$line = str_replace('\\l','ł',$line);
$line = str_replace('\\L','Ł',$line);
$line = str_replace('\\k{a}','ą',$line);
// clean out extra tex curly brackets, usually used for preserving capitals
$line = str_replace('}','', $line);
$line = str_replace('{','', $line);
// we restore the math env
for($i = 0; $i < count($maths); $i++) {
$line = str_replace('__MATH'.$i.'__', $maths[$i], $line);
}
return $line;
}
/** encodes strings for Z3988 URLs. Note that & are encoded as %26 and not as &. */
function s3988($s) {return urlencode(utf8_encode($s));}
/**
see BibEntry->formatAuthor($author)
@deprecated
@nodoc
*/
function formatAuthor() {
die('Sorry, this function does not exist anymore, however, you can simply use $bibentry->formatAuthor($author) instead.');
}
// ----------------------------------------------------------------------
// BIB ENTRIES
// ----------------------------------------------------------------------
/** represents a bibliographic entry.
usage:
<pre>
$db = zetDB('metrics.bib');
$entry = $db->getEntryByKey('Schmietendorf2000');
echo bib2html($entry);
</pre>
notes:
- BibEntry are usually obtained with getEntryByKey or multisearch
*/
class BibEntry {
/** The fields (fieldName -> value) of this bib entry. */
var $fields;
/** The constants @STRINGS referred to by this entry */
var $constants;
/** The crossref entry if there is one */
var $crossref;
/** The verbatim copy (i.e., whole text) of this bib entry. */
var $text;
/** A timestamp to trace when entries have been created */
var $timestamp;
/** The name of the file containing this entry */
var $filename;
/** The short name of the entry (parameterized by ABBRV_TYPE) */
var $abbrv;
/** The index in a list of publications (e.g. [1] Foo */
var $index = '';
/** returns a debug string representation */
function __toString() {
return $this->getType()." ".$this->getKey();
}