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