xref: /plugin/box2/syntax.php (revision 3174f200004f2d93ddd60dc9a4fc22ad830cfd42)
1<?php
2/**
3 * Box Plugin: Draw highlighting boxes around wiki markup
4 *
5 * Syntax:     <box width% classes|title>
6 *   width%    width of the box, must use % unit
7 *   classes   one or more classes used to style the box, several predefined styles included in style.css
8 *   padding   can be defined with each direction or as composite
9 *   margin    can be defined with each direction or as composite
10 *   title     (optional) all text after '|' will be rendered above the main code text with a
11 *             different style.
12 *
13 * Acknowledgements:
14 *  Rounded corners based on snazzy borders by Stu Nicholls (http://www.cssplay.co.uk/boxes/snazzy)
15 *  which is in turn based on nifty corners by Alessandro Fulciniti (http://pro.html.it/esempio/nifty/)
16 *
17 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
18 * @author     Christopher Smith <chris@jalakai.co.uk>
19 * @author     i-net software <tools@inetsoftware.de>
20 */
21
22if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../').'/');
23if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
24require_once(DOKU_PLUGIN.'syntax.php');
25
26/**
27 * All DokuWiki plugins to extend the parser/rendering mechanism
28 * need to inherit from this class
29 */
30class syntax_plugin_box2 extends DokuWiki_Syntax_Plugin {
31
32    var $title_mode = false;
33
34    // the following are used in rendering and are set by _xhtml_boxopen()
35    var $_xb_colours      = array();
36    var $_content_colours = '';
37    var $_title_colours   = '';
38
39    function getType(){ return 'protected';}
40    function getAllowedTypes() { return array('container','substition','protected','disabled','formatting','paragraphs'); }
41    function getPType(){ return 'block';}
42
43    // must return a number lower than returned by native 'code' mode (200)
44    function getSort(){ return 195; }
45
46    // override default accepts() method to allow nesting
47    // - ie, to get the plugin accepts its own entry syntax
48    function accepts($mode) {
49        if ($mode == substr(get_class($this), 7)) return true;
50
51        return parent::accepts($mode);
52    }
53
54    /**
55     * Connect pattern to lexer
56     */
57    function connectTo($mode) {
58        $this->Lexer->addEntryPattern('<box>(?=.*?</box.*?>)',$mode,'plugin_box2');
59        $this->Lexer->addEntryPattern('<box\s[^\r\n\|]*?>(?=.*?</box.*?>)',$mode,'plugin_box2');
60        $this->Lexer->addEntryPattern('<box\|(?=[^\r\n]*?\>.*?</box.*?\>)',$mode,'plugin_box2');
61        $this->Lexer->addEntryPattern('<box\s[^\r\n\|]*?\|(?=[^\r\n]*?>.*?</box.*?>)',$mode,'plugin_box2');
62    }
63
64    function postConnect() {
65        $this->Lexer->addPattern('>', 'plugin_box2');
66        $this->Lexer->addExitPattern('</box.*?>', 'plugin_box2');
67    }
68
69    /**
70     * Handle the match
71     */
72    function handle($match, $state, $pos, Doku_Handler $handler){
73
74        switch ($state) {
75            case DOKU_LEXER_ENTER:
76                $data = $this->_boxstyle(trim(substr($match, 4, -1)));
77                if (substr($match, -1) == '|') {
78                    $this->title_mode = true;
79                    return array('title_open',$data, $pos);
80                } else {
81                    return array('box_open',$data, $pos);
82                }
83
84            case DOKU_LEXER_MATCHED:
85                if ($this->title_mode) {
86                    $this->title_mode = false;
87                    return array('box_open','', $pos);
88                } else {
89                    return array('data', $match, $pos);
90                }
91
92            case DOKU_LEXER_UNMATCHED:
93                if ($this->title_mode) {
94                    return array('title', $match, $pos);
95                }
96
97                $handler->_addCall('cdata',array($match), $pos);
98                return false;
99            case DOKU_LEXER_EXIT:
100                $pos += strlen($match); // has to be done becvause the ending tag comes after $pos
101                $data = trim(substr($match, 5, -1));
102                $title =  ($data && $data{0} == "|") ? substr($data,1) : '';
103
104                return array('box_close', $title, $pos);
105
106        }
107        return false;
108    }
109
110    /**
111     * Create output
112     */
113    function render($mode, Doku_Renderer $renderer, $indata) {
114        global $ID, $ACT;
115
116        // $pos is for the current position in the wiki page
117        if (empty($indata)) return false;
118        list($instr, $data, $pos) = $indata;
119
120        if($mode == 'xhtml'){
121            switch ($instr) {
122                case 'title_open' :
123                    $this->title_mode = true;
124                    $renderer->doc .= $this->_xhtml_boxopen($renderer, $pos, $data);
125                    $renderer->doc .= '<h2 class="box_title"' . $this->_title_colours . '>';
126                    break;
127
128                case 'box_open' :
129                    if ($this->title_mode) {
130                        $this->title_mode = false;
131                        $renderer->doc .= "</h2>\n<div class=\"box_content\"" . $this->_content_colours . '>';
132                    } else {
133                        $renderer->doc .= $this->_xhtml_boxopen($renderer, $pos, $data);
134
135                        if ( strlen( $this->_content_colours ) > 0 ) {
136							$renderer->doc .= '<div class="box_content"' . $this->_content_colours . '>';
137						}
138                    }
139                    break;
140
141                case 'title':
142                case 'data' :
143                    $output = $renderer->_xmlEntities($data);
144
145                    if ( $this->title_mode ) {
146                        $hid = $renderer->_headerToLink($output,true);
147                        $renderer->doc .= '<a id="' . $hid . '" name="' . $hid . '">' . $output . '</a>';
148                        break;
149                    }
150
151                    $renderer->doc .= $output;
152                    break;
153
154                case 'box_close' :
155					if ( strlen( $this->_content_colours ) > 0 ) {
156	                    $renderer->doc .= "</div>\n";
157					}
158
159                    if ($data) {
160                        $renderer->doc .= '<p class="box_caption"' . $this->_title_colours . '>' . $renderer->_xmlEntities($data) . "</p>\n";
161                    }
162
163                    // insert the section edit button befor the box is closed - array_pop makes sure we take the last box
164                    if ( method_exists($renderer, "finishSectionEdit") ) {
165                        $renderer->nocache();
166                        $renderer->finishSectionEdit($pos);
167                    }
168
169                    $renderer->doc .= "\n" . $this->_xhtml_boxclose();
170
171                    break;
172            }
173
174            return true;
175        }
176        return false;
177    }
178
179    function _boxstyle($str) {
180        if (!strlen($str)) return array();
181
182        $styles = array();
183
184        $tokens = preg_split('/\s+/', $str, 9);                      // limit is defensive
185        foreach ($tokens as $token) {
186            if (preg_match('/^\d*\.?\d+(%|px|em|ex|pt|cm|mm|pi|in)$/', $token)) {
187                $styles['width'] = $token;
188                continue;
189            }
190
191            if (preg_match('/^(
192              (\#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}))|        #colorvalue
193              (rgb\(([0-9]{1,3}%?,){2}[0-9]{1,3}%?\))     #rgb triplet
194              )$/x', $token)) {
195                $styles['colour'][] = $token;
196                continue;
197            }
198
199            if (preg_match('/^#[A-Za-z0-9_-]+$/', $token)) {
200                $styles['id'] = substr($token, 1);
201                continue;
202            }
203
204            if ( preg_match('/^(margin|padding)(-(left|right|top|bottom))?:\d+(%|px|em|ex|pt|cm|mm|pi|in)$/', $token)) {
205                $styles['spacing'][] = $token;
206            }
207
208            // restrict token (class names) characters to prevent any malicious data
209            if (preg_match('/[^A-Za-z0-9_-]/',$token)) continue;
210            $styles['class'] = (isset($styles['class']) ? $styles['class'].' ' : '').$token;
211        }
212        if (!empty($styles['colour'])) {
213            $styles['colour'] = $this->_box_colours($styles['colour']);
214        }
215
216        return $styles;
217    }
218
219    function _box_colours($colours) {
220        $triplets = array();
221
222        // only need the first four colours
223        if (count($colours) > 4) $colours = array_slice($colours,0,4);
224        foreach ($colours as $colour) {
225            $triplet[] = $this->_colourToTriplet($colour);
226        }
227
228        // there must be one colour to get here - the primary background
229        // calculate title background colour if not present
230        if (empty($triplet[1])) {
231            $triplet[1] = $triplet[0];
232        }
233
234        // calculate outer background colour if not present
235        if (empty($triplet[2])) {
236            $triplet[2] = $triplet[0];
237        }
238
239        // calculate border colour if not present
240        if (empty($triplet[3])) {
241            $triplet[3] = $triplet[0];
242        }
243
244        // convert triplets back to style sheet colours
245        $style_colours['content_background'] = 'rgb('.join(',',$triplet[0]).')';
246        $style_colours['title_background'] = 'rgb('.join(',',$triplet[1]).')';
247        $style_colours['outer_background'] = 'rgb('.join(',',$triplet[2]).')';
248        $style_colours['borders'] = 'rgb('.join(',',$triplet[3]).')';
249
250        return $style_colours;
251    }
252
253    function _colourToTriplet($colour) {
254        if ($colour{0} == '#') {
255            if (strlen($colour) == 4) {
256                // format #FFF
257                return array(hexdec($colour{1}.$colour{1}),hexdec($colour{2}.$colour{2}),hexdec($colour{3}.$colour{3}));
258            } else {
259                // format #FFFFFF
260                return array(hexdec(substr($colour,1,2)),hexdec(substr($colour,3,2)), hexdec(substr($colour,5,2)));
261            }
262        } else {
263            // format rgb(x,y,z)
264            return explode(',',substr($colour,4,-1));
265        }
266    }
267
268    function _xhtml_boxopen($renderer, $pos, $styles) {
269        $class = 'class="box' . (isset($styles['class']) ? ' '.$styles['class'] : '') . (method_exists($renderer, "startSectionEdit") ? " " . $renderer->startSectionEdit($pos, array( 'target' => 'section', 'name' => 'box-' . $pos)) : "") . '"';
270        $style = isset($styles['width']) ? "width: {$styles['width']};" : '';
271        $style .= isset($styles['spacing']) ? implode(';', $styles['spacing']) : '';
272
273        if (isset($styles['colour'])) {
274            $style .= 'background-color:'.$styles['colour']['outer_background'].';';
275            $style .= 'border-color: '.$styles['colour']['borders'].';';
276
277            $this->_content_colours = 'style="background-color: '.$styles['colour']['content_background'].'; border-color: '.$styles['colour']['borders'].'"';
278            $this->_title_colours = 'style="background-color: '.$styles['colour']['title_background'].';"';
279
280        } else {
281            $this->_content_colours = '';
282            $this->_title_colours = '';
283        }
284
285        if (strlen($style)) $style = ' style="'.$style.'"';
286        if (array_key_exists('id', $styles)) {
287            $class = 'id="' . $styles['id'] . '" ' . $class;
288        }
289
290        $this->_xb_colours[] = $colours;
291
292        $html = "<div $class$style>\n";
293
294        // Don't do box extras if there is no style for them
295        if ( !empty($colours) ) {
296            $html .= '<b class="xtop"><b class="xb1"' . $colours . '>&nbsp;</b><b class="xb2"' . $colours . '">&nbsp;</b><b class="xb3"' . $colours . '>&nbsp;</b><b class="xb4"' . $colours . '>&nbsp;</b></b>' . "\n";
297            $html .= '<div class="xbox"' . $colours . ">\n";
298        }
299
300        return $html;
301    }
302
303    function _xhtml_boxclose() {
304
305        $colours = array_pop($this->_xb_colours);
306
307        // Don't do box extras if there is no style for them
308        if ( !empty($colours) ) {
309            $html = "</div>\n";
310            $html .= '<b class="xbottom"><b class="xb4"' . $colours .  '>&nbsp;</b><b class="xb3"' . $colours . '>&nbsp;</b><b class="xb2"' . $colours . '>&nbsp;</b><b class="xb1"' . $colours . '>&nbsp;</b></b>' . "\n";
311        }
312        $html .= '</div> <!-- Extras -->' . "\n";
313
314        return $html;
315    }
316
317}
318
319//Setup VIM: ex: et ts=4 enc=utf-8 :