xref: /plugin/todo/syntax/todo.php (revision aa11d6a46e34fdcba785525ca93431f9f30b4c89)
1<?php
2/**
3 * ToDo Plugin: Creates a checkbox based todo list
4 *
5 * Syntax: <todo [@username] [#]>Name of Action</todo> -
6 *  Creates a Checkbox with the "Name of Action" as
7 *  the text associated with it. The hash (#, optional)
8 *  will cause the checkbox to be checked by default.
9 *  The @ sign followed by a username can be used to assign this todo to a user.
10 *  examples:
11 *     A todo without user assignment
12 *       <todo>Something todo</todo>
13 *     A completed todo without user assignment
14 *       <todo #>Completed todo</todo>
15 *     A todo assigned to user User
16 *       <todo @leo>Something todo for Leo</todo>
17 *     A completed todo assigned to user User
18 *       <todo @leo #>Todo completed for Leo</todo>
19 *
20 * In combination with dokuwiki searchpattern plugin version (at least v20130408),
21 * it is a lightweight solution for a task management system based on dokuwiki.
22 * use this searchpattern expression for open todos:
23 *     ~~SEARCHPATTERN#'/<todo[^#>]*>.*?<\/todo[\W]*?>/'?? _ToDo ??~~
24 * use this searchpattern expression for completed todos:
25 *     ~~SEARCHPATTERN#'/<todo[^#>]*#[^>]*>.*?<\/todo[\W]*?>/'?? _ToDo ??~~
26 * do not forget the no-cache option
27 *     ~~NOCACHE~~
28 *
29 * Compatibility:
30 *     Release 2013-03-06 "Weatherwax RC1"
31 *     Release 2012-10-13 "Adora Belle"
32 *
33 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
34 * @author     Babbage <babbage@digitalbrink.com>; Leo Eibler <dokuwiki@sprossenwanne.at>
35 */
36
37/**
38 * ChangeLog:
39 *
40 ** [04/13/2013]: by Leo Eibler <dokuwiki@sprossenwanne.at> / http://www.eibler.at
41 **               bugfix: config option Strikethrough
42 * [04/11/2013]: by Leo Eibler <dokuwiki@sprossenwanne.at> / http://www.eibler.at
43 *               bugfix: encoding html code (security risk <todo><script>alert('hi')</script></todo>) - bug reported by Andreas
44 *               bugfix: use correct <todo> tag if there are more than 1 in the same line.
45 * [04/08/2013]: by Leo Eibler <dokuwiki@sprossenwanne.at> / http://www.eibler.at
46 *               migrate changes made by Christian Marg to current version of plugin
47 * [04/08/2013]: by Christian Marg <marg@rz.tu-clausthal.de>
48 *               changed behaviour - when multiple todo-items have the same text, only the clicked one is checked.
49 * [04/08/2013]: by Leo Eibler <dokuwiki@sprossenwanne.at> / http://www.eibler.at
50 *               add description / comments and syntax howto about integration with searchpattern
51 *               check compatibility with dokuwiki release 2012-10-13 "Adora Belle"
52 *               remove getInfo() call because it's done by plugin.info.txt (since dokuwiki 2009-12-25 "Lemming")
53 * [04/07/2013]: by Leo Eibler <dokuwiki@sprossenwanne.at> / http://www.eibler.at
54 *               add handler method _searchpatternHandler() for dokuwiki searchpattern extension.
55 *               add user assignment for todos (with @username syntax in todo tag e.g. <todo @leo>do something</todo>)
56 * [04/05/2013]: by Leo Eibler <dokuwiki@sprossenwanne.at> / http://www.eibler.at
57 *               upgrade plugin to work with newest version of dokuwiki (tested version Release 2013-03-06 Weatherwax RC1).
58 * [08/16/2010]: Fixed another bug where javascript would not decode the action
59 *               text properly (replaced unescape with decodeURIComponent).
60 * [04/03/2010]: Fixed a bug where javascript would not decode the action text
61 *               properly.
62 * [03/31/2010]: Fixed a bug where checking or unchecking an action whose text
63 *               appeared outside of the todo tags, would result in mangling the
64 *               code on your page. Also added support for using the ampersand
65 *               character (&) and html entities inside of your todo action.
66 * [02/27/2010]: Created an action plugin to insert a ToDo button into the
67 *               editor toolbar.
68 * [10/14/2009]: Added the feature so that if you have Links turned off and you
69 *               click on the text of an action, it will check that action off.
70 *               Thanks to Tero for the suggestion! (Plugin Option: CheckboxText)
71 * [10/08/2009]: I am no longer using the short open php tag (<?) for my
72 *               ajax.php file. This was causing some problems for people who had
73 *               short_open_tags=Off in their php.ini file (thanks Marcus!)
74 * [10/01/2009]: Updated javascript to use .nextSibling instead of .nextElementSibling
75 *               to make it compatible with older versions of Firefox and IE.
76 * [09/13/2009]: Replaced ':' with a '-' in the action link so as not to create
77 *               unnecessary namespaces (if the links option is active)
78 * [09/10/2009]: Removed unnecessary function calls (urlencode) in _createLink() function
79 * [09/09/2009]: Added ability for user to choose where Action links point to
80 * [08/30/2009]: Initial Release
81 */
82
83if(!defined('DOKU_INC')) die();
84
85/**
86 * All DokuWiki plugins to extend the parser/rendering mechanism
87 * need to inherit from this class
88 */
89class syntax_plugin_todo_todo extends DokuWiki_Syntax_Plugin {
90
91    /**
92     * Get the type of syntax this plugin defines.
93     *
94     * @return String
95     */
96    public function getType() {
97        return 'substition';
98    }
99
100    /**
101     * Paragraph Type
102     *
103     * 'normal' - The plugin can be used inside paragraphs
104     * 'block'  - Open paragraphs need to be closed before plugin output
105     * 'stack'  - Special case. Plugin wraps other paragraphs.
106     */
107    function getPType(){
108        return 'normal';
109    }
110
111    /**
112     * Where to sort in?
113     *
114     * @return Integer
115     */
116    public function getSort() {
117        return 999;
118    }
119
120    /**
121     * Connect lookup pattern to lexer.
122     *
123     * @param $mode String The desired rendermode.
124     * @return void
125     * @see render()
126     */
127    public function connectTo($mode) {
128        $this->Lexer->addEntryPattern('<todo[\s]*?.*?>(?=.*?</todo>)', $mode, 'plugin_todo_todo');
129    }
130
131    public function postConnect() {
132        $this->Lexer->addExitPattern('</todo>', 'plugin_todo_todo');
133    }
134
135    /**
136     * Handler to prepare matched data for the rendering process.
137     *
138     * @param $match    string  The text matched by the patterns.
139     * @param $state    int     The lexer state for the match.
140     * @param $pos      int     The character position of the matched text.
141     * @param &$handler Doku_Handler  Reference to the Doku_Handler object.
142     * @return int The current lexer state for the match.
143     */
144    public function handle($match, $state, $pos, Doku_Handler &$handler) {
145        switch($state) {
146            case DOKU_LEXER_ENTER :
147                #Search to see if the '#' is in the todotag (if so, this means the Action has been completed)
148                $x = preg_match('%<todo([^>]*)>%i', $match, $tododata);
149                if($x) {
150                    list($handler->checked, $handler->todo_user) = $this->parseTodoArgs($tododata[1]);
151                }
152                if(!is_numeric($handler->todo_index)) {
153                    $handler->todo_index = 0;
154                }
155                break;
156            case DOKU_LEXER_MATCHED :
157                break;
158            case DOKU_LEXER_UNMATCHED :
159                /**
160                 * Structure:
161                 * input(checkbox)
162                 * <span>
163                 * -<a> (if links is on) or <span> (if links is off)
164                 * --<del> (if strikethrough is on) or --NOTHING--
165                 * -</a> or </span>
166                 * </span>
167                 */
168
169                #Make sure there is actually an action to create
170                if(trim($match) != '') {
171
172                    $data = array($state, $match, $handler->todo_index, $handler->todo_user, $handler->checked);
173
174                    $handler->todo_index++;
175                    return $data;
176                }
177
178                break;
179            case DOKU_LEXER_EXIT :
180                #Delete temporary checked variable
181                unset($handler->todo_user);
182                unset($handler->checked);
183                //unset($handler->todo_index);
184                break;
185            case DOKU_LEXER_SPECIAL :
186                break;
187        }
188        return array();
189    }
190
191    /**
192     * Handle the actual output creation.
193     *
194     * @param  $mode     String        The output format to generate.
195     * @param &$renderer Doku_Renderer A reference to the renderer object.
196     * @param  $data     Array         The data created by the <tt>handle()</tt> method.
197     * @return Boolean true: if rendered successfully, or false: otherwise.
198     */
199    public function render($mode, Doku_Renderer &$renderer, $data) {
200        global $ID;
201        list($state, $todotitle, $todoindex, $todouser, $checked) = $data;
202        if($mode == 'xhtml') {
203            /** @var $renderer Doku_Renderer_xhtml */
204            if($state == DOKU_LEXER_UNMATCHED) {
205
206                #Output our result
207                $renderer->doc .= $this->createTodoItem($renderer, $todotitle, $todoindex, $todouser, $checked, $ID);
208                return true;
209            }
210
211        } elseif($mode == 'metadata') {
212            /** @var $renderer Doku_Renderer_metadata */
213            if($state == DOKU_LEXER_UNMATCHED) {
214                $id = $this->_composePageid($todotitle);
215                $renderer->internallink($id, $todotitle);
216            }
217        }
218        return false;
219    }
220
221    /**
222     * Parse the arguments of todotag
223     *
224     * @param string $todoargs
225     * @return array(bool, false|string) with checked and user
226     */
227    protected function parseTodoArgs($todoargs) {
228        $checked = $todouser = false;
229
230        if(strpos($todoargs, '#') !== false) {
231            $checked = true;
232        }
233        if(($userStartPos = strpos($todoargs, '@')) !== false) {
234            $userraw = substr($todoargs, $userStartPos);
235            $x = preg_match('%@([-.\w]+)%i', $userraw, $usermatch);
236            if($x) {
237                $todouser = $usermatch[1];
238            }
239        }
240        return array($checked, $todouser);
241    }
242
243    /**
244     * @param Doku_Renderer_xhtml &$renderer
245     * @param string $todotitle Title of todoitem
246     * @param int    $todoindex which number the todoitem has, null is when not at the page
247     * @param string $todouser  User assigned to todoitem
248     * @param bool   $checked   whether item is done
249     * @param string $id of page
250     * @return string html of an item
251     */
252    protected function createTodoItem(&$renderer, $todotitle, $todoindex, $todouser, $checked, $id) {
253        //set correct context
254        global $ID;
255        $oldID = $ID;
256        $ID = $id;
257
258
259        $return = '<input type="checkbox" class="todocheckbox"'
260            . ' data-index="' . $todoindex . '"'
261            . ' data-date="' . hsc(@filemtime(wikiFN($ID))) . '"'
262            . ' data-pageid="' . hsc($ID) . '"'
263            . ' data-strikethrough="' . ($this->getConf("Strikethrough") ? '1' : '0') . '"'
264            . ($checked ? 'checked="checked"' : '') . ' /> ';
265        if($todouser) {
266            $return .= '<span class="todouser">[' . hsc($todouser) . ']</span>';
267        }
268
269        $spanclass = 'todotext';
270        if($this->getConf("CheckboxText") && !$this->getConf("AllowLinks")) {
271            $spanclass .= ' clickabletodo todohlght';
272        }
273        $return .= '<span class="' . $spanclass . '">';
274
275        if($checked && $this->getConf("Strikethrough")) {
276            $return .= '<del>';
277        }
278
279        $return .= '<span class="todoinnertext">';
280        if($this->getConf("AllowLinks")) {
281            $return .= $this->_createLink($renderer, $todotitle, $todotitle);
282        } else {
283            $return .= hsc($todotitle);
284        }
285        $return .= '</span>';
286
287        if($checked && $this->getConf("Strikethrough")) {
288            $return .= '</del>';
289        }
290
291        $return .= '</span>';
292
293        //restore page ID
294        $ID = $oldID;
295        return $return;
296    }
297
298    /**
299     * Generate links from our Actions if necessary.
300     *
301     * @param Doku_Renderer_xhtml &$renderer
302     * @param string $pagename
303     * @param string $name
304     * @return string
305     */
306    private function _createLink(&$renderer, $pagename, $name = NULL) {
307        $id = $this->_composePageid($pagename);
308
309        return $renderer->internallink($id, $name, null, true);
310    }
311
312    /**
313     * Compose the pageid of the pages linked by a todoitem
314     *
315     * @param string $pagename
316     * @return string page id
317     */
318    private function _composePageid($pagename) {
319        #Get the ActionNamespace and make sure it ends with a : (if not, add it)
320        $actionNamespace = $this->getConf("ActionNamespace");
321        if(strlen($actionNamespace) == 0 || substr($actionNamespace, -1) != ':') {
322            $actionNamespace .= ":";
323        }
324
325        #Replace ':' in $pagename so we don't create unnecessary namespaces
326        $pagename = str_replace(':', '-', $pagename);
327
328        //resolve and build link
329        $id = $actionNamespace . $pagename;
330        return $id;
331    }
332
333    /**
334     * @brief this function can be called by dokuwiki plugin searchpattern to process the todos found by searchpattern.
335     * use this searchpattern expression for open todos:
336     *          ~~SEARCHPATTERN#'/<todo[^#>]*>.*?<\/todo[\W]*?>/'?? _ToDo ??~~
337     * use this searchpattern expression for completed todos:
338     *          ~~SEARCHPATTERN#'/<todo[^#>]*#[^>]*>.*?<\/todo[\W]*?>/'?? _ToDo ??~~
339     * this handler method uses the table and layout with css classes from searchpattern plugin
340     *
341     * @param $type   string type of the request from searchpattern plugin
342     *                (wholeoutput, intable:whole, intable:prefix, intable:match, intable:count, intable:suffix)
343     *                wholeoutput     = all output is done by THIS plugin (no output will be done by search pattern)
344     *                intable:whole   = the left side of table (page name) is done by searchpattern, the right side
345     *                                  of the table will be done by THIS plugin
346     *                intable:prefix  = on the right side of table - THIS plugin will output a prefix header and
347     *                                  searchpattern will continue it's default output
348     *                intable:match   = if regex, right side of table - THIS plugin will format the current
349     *                                  outputvalue ($value) and output it instead of searchpattern
350     *                intable:count   = if normal, right side of table - THIS plugin will format the current
351     *                                  outputvalue ($value) and output it instead of searchpattern
352     *                intable:suffix  = on the right side of table - THIS plugin will output a suffix footer and
353     *                                  searchpattern will continue it's default output
354     * @param Doku_Renderer_xhtml &$renderer current rendering object (use $renderer->doc .= 'text' to output text)
355     * @param array $data     whole data multidemensional array( array( $page => $countOfMatches ), ... )
356     * @param array $matches  whole regex matches multidemensional array( array( 0 => '1st Match', 1 => '2nd Match', ... ), ... )
357     * @param string $page     id of current page
358     * @param array $params   the parameters set by searchpattern (see search pattern documentation)
359     * @param string $value    value which should be outputted by searchpattern
360     * @return bool true if THIS method is responsible for the output (using $renderer->doc) OR false if searchpattern should output it's default
361     */
362    public function _searchpatternHandler($type, &$renderer, $data, $matches, $params = array(), $page = null, $value = null) {
363        $renderer->nocache();
364
365        $type = strtolower($type);
366        switch($type) {
367            case 'wholeoutput':
368                // $matches should hold an array with all <todo>matches</todo> or <todo #>matches</todo>
369                if(!is_array($matches)) {
370                    return false;
371                }
372                //file_put_contents( dirname(__FILE__).'/debug.txt', print_r($matches,true), FILE_APPEND );
373                //file_put_contents( dirname(__FILE__).'/debug.txt', print_r($params,true), FILE_APPEND );
374                $renderer->doc .= '<div class="sp_main">';
375                $renderer->doc .= '<table class="inline sp_main_table">'; //create table
376
377                foreach($matches as $page => $allTodosPerPage) {
378                    $renderer->doc .= '<tr class="sp_title"><th class="sp_title" colspan="2"><a href="' . wl($page) . '">' . $page . '</a></td></tr>';
379                    //entry 0 contains all whole matches
380                    foreach($allTodosPerPage[0] as $todoindex => $todomatch) {
381                        $x = preg_match('%<todo([^>]*)>(.*)</[\W]*todo[\W]*>%i', $todomatch, $tododata);
382
383                        if($x) {
384                            list($checked, $todouser) = $this->parseTodoArgs($tododata[1]);
385                            $todotitle = trim($tododata[2]);
386                            if(empty($todotitle)) {
387                                continue;
388                            }
389                            $renderer->doc .= '<tr class="sp_result"><td class="sp_page" colspan="2">';
390
391                            // in case of integration with searchpattern there is no chance to find the index of an element
392                            $renderer->doc .= $this->createTodoItem($renderer, $todotitle, $todoindex, $todouser, $checked, $page);
393
394                            $renderer->doc .= '</td></tr>';
395                        }
396                    }
397                }
398                $renderer->doc .= '</table>'; //end table
399                $renderer->doc .= '</div>';
400                // true means, that this handler method does the output (searchpattern plugin has nothing to do)
401                return true;
402                break;
403            case 'intable:whole':
404                break;
405            case 'intable:prefix':
406                //$renderer->doc .= '<b>Start on Page '.$page.'</b>';
407                break;
408            case 'intable:match':
409                //$renderer->doc .= 'regex match on page '.$page.': <pre>'.$value.'</pre>';
410                break;
411            case 'intable:count':
412                //$renderer->doc .= 'normal count on page '.$page.': <pre>'.$value.'</pre>';
413                break;
414            case 'intable:suffix':
415                //$renderer->doc .= '<b>End on Page '.$page.'</b>';
416                break;
417            default:
418                break;
419        }
420        // false means, that this handler method does not output anything. all should be done by searchpattern plugin
421        return false;
422    }
423}
424
425//Setup VIM: ex: et ts=4 enc=utf-8 :