summaryrefslogtreecommitdiff
path: root/platform/www/lib/plugins/refnotes/bibtex.php
blob: 04b335f11da966067cba7ecd914e89fea6d56cee (plain)
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
<?php

/**
 * Plugin RefNotes: BibTeX parser
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Mykola Ostrovskyy <dwpforge@gmail.com>
 */

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_parser extends \dokuwiki\Parsing\Parser {

    private static $instance = NULL;

    /**
     *
     */
    public static function getInstance() {
        if (self::$instance == NULL) {
            self::$instance = new refnotes_bibtex_parser();
        }

        return self::$instance;
    }

    /**
     * Constructor
     */
    public function __construct() {
        $this->handler = new refnotes_bibtex_handler();
        $this->lexer = new refnotes_bibtex_lexer($this->handler, 'base', true);

        $this->addBibtexMode(new refnotes_bibtex_outside_mode());
        $this->addBibtexMode(new refnotes_bibtex_entry_mode('parented'));
        $this->addBibtexMode(new refnotes_bibtex_entry_mode('braced'));
        $this->addBibtexMode(new refnotes_bibtex_field_mode());
        $this->addBibtexMode(new refnotes_bibtex_integer_value_mode());
        $this->addBibtexMode(new refnotes_bibtex_string_value_mode('quoted'));
        $this->addBibtexMode(new refnotes_bibtex_string_value_mode('braced'));
        $this->addBibtexMode(new refnotes_bibtex_nested_braces_mode('quoted'));
        $this->addBibtexMode(new refnotes_bibtex_nested_braces_mode('braced'));
        $this->addBibtexMode(new refnotes_bibtex_concatenation_mode());
    }

    /**
     *
     */
    private function addBibtexMode($mode) {
        $this->addMode($mode->getName(), $mode);
    }

    /**
     *
     */
    public function connectModes() {
        if (!$this->connected) {
            $this->modes['outside']->connectTo('base');
            $this->modes['entry_parented']->connectTo('base');
            $this->modes['entry_braced']->connectTo('base');

            parent::connectModes();
        }
    }

    /**
     *
     */
    public function parse($text) {
        $this->connectModes();

        $this->handler->reset();
        $this->lexer->parse(str_replace("\r\n", "\n", $text));

        return $this->handler->finalize();
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_lexer extends \dokuwiki\Parsing\Lexer\Lexer {

    /**
     *
     */
    public function parse($text) {
        $lastMode = '';

        while (is_array($parsed = $this->reduce($text))) {
            list($unmatched, $matched, $mode) = $parsed;

            if (!$this->dispatchTokens($unmatched, $matched, $mode, 0, 0)) {
                return false;
            }

            if (empty($unmatched) && empty($matched) && ($lastMode == $this->modeStack->getCurrent())) {
                return false;
            }

            $lastMode = $this->modeStack->getCurrent();
        }

        if (!$parsed) {
            return false;
        }

        return $this->invokeHandler($text, DOKU_LEXER_UNMATCHED, 0);
    }

    /**
     *
     */
    protected function invokeHandler($text, $state, $pos) {
        if ($text == "" && $state == DOKU_LEXER_UNMATCHED) {
            return true;
        }

        $mode = $this->modeStack->getCurrent();
        $handler = isset($this->mode_handlers[$mode]) ? $this->mode_handlers[$mode] : $mode;

        return $this->handler->$handler($text, $state, $pos);
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_mode extends \dokuwiki\Parsing\ParserMode\AbstractMode {

    protected $name;
    protected $handler;
    protected $specialPattern;
    protected $entryPattern;
    protected $exitPattern;

    /**
     * Constructor
     */
    public function __construct() {
        $this->name = preg_replace('/refnotes_bibtex_(\w+)_mode/', '$1', get_class($this));
        $this->handler = '';

        $this->specialPattern = array();
        $this->entryPattern = array();
        $this->exitPattern = array();
    }

    /**
     *
     */
    public function getSort() {
        return 0;
    }

    /**
     *
     */
    public function getName() {
        return $this->name;
    }

    /**
     *
     */
    public function connectTo($mode) {
        foreach ($this->specialPattern as $pattern) {
            $this->Lexer->addSpecialPattern($pattern, $mode, $this->name);
        }

        foreach ($this->entryPattern as $pattern) {
            $this->Lexer->addEntryPattern($pattern, $mode, $this->name);
        }

        if ($this->handler != '') {
            $this->Lexer->mapHandler($this->name, $this->handler);
        }
    }

    /**
     *
     */
    public function postConnect() {
        foreach ($this->exitPattern as $pattern) {
            $this->Lexer->addExitPattern($pattern, $this->name);
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_outside_mode extends refnotes_bibtex_mode {

    /**
     * Constructor
     */
    public function __construct() {
        parent::__construct();

        $this->specialPattern[] = '[^@]+(?=@)';
    }

    /**
     *
     */
    public function connectTo($mode) {
        parent::connectTo($mode);

        $this->Lexer->mapHandler('base', $this->name);
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_entry_mode extends refnotes_bibtex_mode {

    /**
     * Constructor
     */
    public function __construct($type) {
        parent::__construct();

        $this->handler = $this->name;
        $this->name .= '_' . $type;

        list($open, $close) = ($type == 'parented') ? array('\(', '\)') : array('{', '}');

        $this->entryPattern[] = '^@\w+\s*' . $open . '(?=.*' . $close . ')';
        $this->exitPattern[] = '\s*(?:' . $close . '|(?=@))';

        $this->allowedModes = array('field');
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_field_mode extends refnotes_bibtex_mode {

    /**
     * Constructor
     */
    public function __construct() {
        parent::__construct();

        $this->entryPattern[] = '^\s*\w[\w-]+\s*=\s*';
        $this->exitPattern[] = '\s*(?:,|(?=[\)}@]))';

        $this->allowedModes = array('integer_value', 'string_value_quoted', 'string_value_braced', 'concatenation');
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_integer_value_mode extends refnotes_bibtex_mode {

    /**
     * Constructor
     */
    public function __construct() {
        parent::__construct();

        $this->specialPattern[] = '^\d+';
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_string_value_mode extends refnotes_bibtex_mode {

    /**
     * Constructor
     */
    public function __construct($type) {
        parent::__construct();

        $this->handler = $this->name;
        $this->name .= '_' . $type;

        list($open, $close, $exit) = ($type == 'quoted') ? array('"', '"', '"') : array('{', '}', '(?:}|(?=@))');

        $this->entryPattern[] = '^' . $open . '(?=.*' . $close . ')';
        $this->exitPattern[] = $exit;

        $this->allowedModes = array('nested_braces_' . $type);
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_nested_braces_mode extends refnotes_bibtex_mode {

    /**
     * Constructor
     */
    public function __construct($type) {
        parent::__construct();

        $this->handler = $this->name;
        $this->name .= '_' . $type;

        $this->entryPattern[] = '{(?=.*})';
        $this->exitPattern[] = ($type == 'quoted') ? '}' : '(?:}|(?=@))';

        $this->allowedModes = array($this->name);
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_concatenation_mode extends refnotes_bibtex_mode {

    /**
     * Constructor
     */
    public function __construct() {
        parent::__construct();

        $this->specialPattern[] = '\s*#\s*';
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_handler {

    private $entries;
    private $entry;
    private $field;

    /**
     * Constructor
     */
    public function __construct() {
        $this->reset();
    }

    /**
     *
     */
    public function reset() {
        $this->entries = new refnotes_bibtex_entry_stash();
        $this->entry = NULL;
        $this->field = NULL;
    }

    /**
     *
     */
    public function finalize() {
        $entries = $this->entries->getEntries();

        foreach ($entries as &$entry) {
            if (array_key_exists('author', $entry)) {
                $authors = explode(' and ', $entry['author']);

                foreach ($authors as &$author) {
                    $author = implode(' ', array_reverse(explode(', ', $author)));
                }

                $entry['author'] = implode(', ', $authors);
            }
        }

        return $entries;
    }

    /**
     *
     */
    public function outside($match, $state) {
        /* Ignore everything outside the entries */
        return true;
    }

    /**
     *
     */
    public function entry($match, $state) {
        switch ($state) {
            case DOKU_LEXER_ENTER:
                $this->entry = new refnotes_bibtex_entry(preg_replace('/@(\w+)\W+/', '$1', $match));
                break;

            case DOKU_LEXER_UNMATCHED:
                $this->entry->handleUnmatched($match);
                break;

            case DOKU_LEXER_EXIT:
                $this->entries->add($this->entry);
                $this->entry = NULL;
                break;
        }

        return true;
    }

    /**
     *
     */
    public function field($match, $state) {
        switch ($state) {
            case DOKU_LEXER_ENTER:
                $this->field = new refnotes_bibtex_field(preg_replace('/\W*(\w[\w-]+)\W*/', '$1', $match));
                break;

            case DOKU_LEXER_UNMATCHED:
                $this->field->addToken('unmatched', $match);
                break;

            case DOKU_LEXER_EXIT:
                $this->entry->addField($this->field);
                $this->field = NULL;
                break;
        }

        return true;
    }

    /**
     *
     */
    public function integer_value($match, $state) {
        $this->field->addToken('integer', $match);

        return true;
    }

    /**
     *
     */
    public function string_value($match, $state) {
        if ($state == DOKU_LEXER_UNMATCHED) {
            $this->field->addToken('string', $match);
        }

        return true;
    }

    /**
     *
     */
    public function nested_braces($match, $state) {
        if ($state == DOKU_LEXER_UNMATCHED) {
            $this->field->addToken('braces', $match);
        }

        return true;
    }

    /**
     *
     */
    public function concatenation($match, $state) {
        /* Nothing special to do, concatenation will happen anyway */
        return true;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_entry_stash {

    private $entry;
    private $strings;
    private $namespace;

    /**
     * Constructor
     */
    public function __construct() {
        $this->entry = array();
        $this->strings = new refnotes_bibtex_strings();
        $this->namespace = ':';
    }

    /**
     *
     */
    public function getEntries() {
        return $this->entry;
    }

    /**
     *
     */
    public function add($entry) {
        static $entryType = array(
            'article', 'book', 'booklet', 'conference', 'inbook', 'incollection', 'inproceedings', 'manual',
            'mastersthesis', 'misc', 'phdthesis', 'proceedings', 'techreport', 'unpublished');

        $type = $entry->getType();
        $name = $entry->getName();

        if (in_array($type, $entryType)) {
            if ($this->isValidRefnotesName($name)) {
                if ($name[0] != ':') {
                    $name = $this->namespace . $name;
                }

                $this->entry[] = array_merge(array('note-name' => $name), $entry->getData($this->strings));
            }
        }
        elseif ($type == 'string') {
            $data = $entry->getData($this->strings);
            $name = reset(array_keys($data));

            if ($this->isValidStringName($name)) {
                $this->strings->add($name, $data[$name]);
            }
        }
        elseif (($type == 'comment') && (strtolower($name) == 'refnotes')) {
            $data = $entry->getData($this->strings);

            if (isset($data['namespace']) && $this->isValidRefnotesName($data['namespace'])) {
                $this->namespace = refnotes_namespace::canonizeName($data['namespace']);
            }
        }
    }

    /**
     *
     */
    private function isValidRefnotesName($name) {
        return preg_match('/^' . refnotes_note::getNamePattern('full-extended') . '$/', $name) == 1;
    }

    /**
     *
     */
    private function isValidStringName($name) {
        return preg_match('/^[[:alpha:]]\w*$/', $name) == 1;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_entry {

    private $type;
    private $name;
    private $field;

    /**
     * Constructor
     */
    public function __construct($type) {
        $this->type = strtolower($type);
        $this->name = '';
        $this->field = array();
    }

    /**
     *
     */
    public function getType() {
        return $this->type;
    }

    /**
     *
     */
    public function getName() {
        return $this->name;
    }

    /**
     *
     */
    public function getData($strings) {
        $data = array();

        foreach ($this->field as $field) {
            $data[$field->getName()] = $field->getValue($strings);
        }

        return $data;
    }

    /**
     *
     */
    public function handleUnmatched($token) {
        if (($this->name == '') && (preg_match('/\s*([^\s,]+)\s*,/', $token, $match) == 1)) {
            $this->name = $match[1];
        }
    }

    /**
     *
     */
    public function addField($field) {
        $this->field[] = $field;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_field {

    private $name;
    private $token;

    /**
     * Constructor
     */
    public function __construct($name) {
        $this->name = strtolower($name);
        $this->token = array();
    }

    /**
     *
     */
    public function getName() {
        return $this->name;
    }

    /**
     *
     */
    public function getValue($strings) {
        $value = '';

        foreach ($this->token as $token) {
            $text = $token->text;

            if ($token->type == 'unmatched') {
                $text = $strings->lookup(strtolower(trim($text)));
            }

            $value .= $text;
        }

        return preg_replace('/\s+/', ' ', trim($value));
    }

    /**
     *
     */
    public function addToken($type, $text) {
        $this->token[] = new refnotes_bibtex_field_token($type, $text);
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_field_token {

    public $type;
    public $text;

    /**
     * Constructor
     */
    public function __construct($type, $text) {
        $this->type = $type;
        $this->text = $text;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
class refnotes_bibtex_strings {

    private $string;

    /**
     * Constructor
     */
    public function __construct() {
        $this->string = array();
    }

    /**
     *
     */
    public function add($name, $value) {
        $this->string[$name] = $value;
    }

    /**
     *
     */
    public function lookup($name) {
        return array_key_exists($name, $this->string) ? $this->string[$name] : '';
    }
}