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