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