1<?php
2
3/**
4 * Plugin TableWidth
5 *
6 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
7 * @author     Mykola Ostrovskyy <dwpforge@gmail.com>
8 */
9
10class syntax_plugin_tablewidth extends DokuWiki_Syntax_Plugin {
11
12    private $mode;
13
14    public function __construct() {
15        $this->mode = substr(get_class($this), 7);
16    }
17
18    public function getType() {
19        return 'container';
20    }
21
22    public function getPType() {
23        return 'block';
24    }
25
26    public function getSort() {
27        return 5;
28    }
29
30    public function connectTo($mode) {
31        $this->Lexer->addSpecialPattern('[\t ]*\n\|<[^\n]+?>\|(?=\s*?\n[|^])', $mode, $this->mode);
32    }
33
34    public function handle($match, $state, $pos, Doku_Handler $handler) {
35        if ($state == DOKU_LEXER_SPECIAL) {
36            if (preg_match('/\|<(\s*)(.+?)(\s*)>\|/', $match, $match) != 1) {
37                return false;
38            }
39
40            // Sanitize the width spec to avoid injection of HTML tags
41            $widthSpec = str_replace(array('<', '>'), '', $match[2]);
42            $tableAlign = $this->getTableAlign($match[1], $match[3]);
43
44            return array($tableAlign . $widthSpec);
45        }
46
47        return false;
48    }
49
50    public function render($mode, Doku_Renderer $renderer, $data) {
51        if ($mode == 'xhtml') {
52            $renderer->doc .= '<!-- table-width ' . $data[0] . ' -->' . DOKU_LF;
53
54            return true;
55        }
56
57        return false;
58    }
59
60    private function getTableAlign($paddingLeft, $paddingRight) {
61        if (strlen($paddingLeft) > 1) {
62            if (strlen($paddingRight) > 1) {
63                return '>< ';
64            }
65            else {
66                return '> ';
67            }
68        }
69        else {
70            if (strlen($paddingRight) > 1) {
71                return '< ';
72            }
73        }
74
75        return '';
76    }
77}
78