xref: /plugin/todo/syntax/todo.php (revision d5adcab96bfde5074b964053793c1053ccdfa1e7)
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    }
145
146    public function postConnect() {
147        $this->Lexer->addExitPattern('</todo>', 'plugin_todo_todo');
148    }
149
150    /**
151     * Handler to prepare matched data for the rendering process.
152     *
153     * @param $match    string  The text matched by the patterns.
154     * @param $state    int     The lexer state for the match.
155     * @param $pos      int     The character position of the matched text.
156     * @param &$handler Doku_Handler  Reference to the Doku_Handler object.
157     * @return int The current lexer state for the match.
158     */
159    public function handle($match, $state, $pos, Doku_Handler &$handler) {
160        switch($state) {
161            case DOKU_LEXER_ENTER :
162                #Search to see if the '#' is in the todotag (if so, this means the Action has been completed)
163                $x = preg_match('%<todo([^>]*)>%i', $match, $tododata);
164                if($x) {
165                    $handler->todoargs =  $this->parseTodoArgs($tododata[1]);
166                }
167                if(!is_numeric($handler->todo_index)) {
168                    $handler->todo_index = 0;
169                }
170                break;
171            case DOKU_LEXER_MATCHED :
172                break;
173            case DOKU_LEXER_UNMATCHED :
174                /**
175                 * Structure:
176                 * input(checkbox)
177                 * <span>
178                 * -<a> (if links is on) or <span> (if links is off)
179                 * --<del> (if strikethrough is on) or --NOTHING--
180                 * -</a> or </span>
181                 * </span>
182                 */
183
184                #Make sure there is actually an action to create
185                if(trim($match) != '') {
186
187                    $data = array_merge(array ($state, 'todotitle' => $match, 'todoindex' => $handler->todo_index, 'todouser' => $handler->todo_user, 'checked' => $handler->checked), $handler->todoargs);
188                    $handler->todo_index++;
189                    return $data;
190                }
191
192                break;
193            case DOKU_LEXER_EXIT :
194                #Delete temporary checked variable
195                unset($handler->todo_user);
196                unset($handler->checked);
197                unset($handler->todoargs);
198                //unset($handler->todo_index);
199                break;
200            case DOKU_LEXER_SPECIAL :
201                break;
202        }
203        return array();
204    }
205
206    /**
207     * Handle the actual output creation.
208     *
209     * @param  $mode     String        The output format to generate.
210     * @param &$renderer Doku_Renderer A reference to the renderer object.
211     * @param  $data     Array         The data created by the <tt>handle()</tt> method.
212     * @return Boolean true: if rendered successfully, or false: otherwise.
213     */
214    public function render($mode, Doku_Renderer &$renderer, $data) {
215        global $ID;
216        list($state, $todotitle) = $data;
217        if($mode == 'xhtml') {
218            /** @var $renderer Doku_Renderer_xhtml */
219            if($state == DOKU_LEXER_UNMATCHED) {
220
221                #Output our result
222                $renderer->doc .= $this->createTodoItem($renderer, $ID, array_merge($data, array('checkbox'=>'yes')));
223                return true;
224            }
225
226        } elseif($mode == 'metadata') {
227            /** @var $renderer Doku_Renderer_metadata */
228            if($state == DOKU_LEXER_UNMATCHED) {
229                $id = $this->_composePageid($todotitle);
230                $renderer->internallink($id, $todotitle);
231            }
232        }
233        return false;
234    }
235
236    /**
237     * Parse the arguments of todotag
238     *
239     * @param string $todoargs
240     * @return array(bool, false|string) with checked and user
241     */
242    protected function parseTodoArgs($todoargs) {
243        $data['checked'] = false;
244        unset($data['start']);
245        unset($data['due']);
246        unset($data['completeddate']);
247	$data['showdate'] = $this->getConf("ShowdateTag");
248        $data['username'] = $this->getConf("Username");
249        $options = explode(' ', $todoargs);
250        foreach($options as $option) {
251            $option = trim($option);
252            if($option[0] == '@') {
253                $data['todousers'][] = substr($option, 1); //fill todousers array
254                if(!isset($data['todouser'])) $data['todouser'] = substr($option, 1); //set the first/main todouser
255            }
256            elseif($option[0] == '#') {
257                $data['checked'] = true;
258                @list($completeduser, $completeddate) = explode(':', $option, 2);
259                $data['completeduser'] = substr($completeduser, 1);
260                if(date('Y-m-d', strtotime($completeddate)) == $completeddate) {
261                    $data['completeddate'] = new DateTime($completeddate);
262                }
263	    }
264            else {
265                @list($key, $value) = explode(':', $option, 2);
266                switch($key) {
267                    case 'username':
268                        if(in_array($value, array('user', 'real', 'none'))) {
269                            $data['username'] = $value;
270                        }
271                        break;
272                    case 'start':
273                        if(date('Y-m-d', strtotime($value)) == $value) {
274                            $data['start'] = new DateTime($value);
275                        }
276                        break;
277                    case 'due':
278                        if(date('Y-m-d', strtotime($value)) == $value) {
279                            $data['due'] = new DateTime($value);
280                        }
281                        break;
282		    case 'showdate':
283                        if(in_array($value, array('yes', 'no'))) {
284                            $data['showdate'] = ($value == 'yes');
285                        }
286                        break;
287                }
288            }
289        }
290        return $data;
291    }
292
293    /**
294     * @param Doku_Renderer_xhtml &$renderer
295     * @param string $id of page
296     * @param array  $data  data for rendering options
297     * @return string html of an item
298     */
299    protected function createTodoItem(&$renderer, $id, $data) {
300        //set correct context
301        global $ID, $INFO;
302        $oldID = $ID;
303        $ID = $id;
304        $todotitle = $data['todotitle'];
305        $todoindex = $data['todoindex'];
306        $todouser = $data['todousers'][0];
307        $checked = $data['checked'];
308
309        if($data['checkbox']) {
310            $return = '<input type="checkbox" class="todocheckbox"'
311            . ' data-index="' . $todoindex . '"'
312            . ' data-date="' . hsc(@filemtime(wikiFN($ID))) . '"'
313            . ' data-pageid="' . hsc($ID) . '"'
314            . ' data-strikethrough="' . ($this->getConf("Strikethrough") ? '1' : '0') . '"'
315            . ($checked ? 'checked="checked"' : '') . ' /> ';
316        }
317
318        // Username of first todouser in list
319        if($todouser && $data['username'] != 'none') {
320            switch ($data['username']) {
321                case "user": break;
322                case "real":
323                    if(!($todouser = userlink($todouser, true))) { //only if the user exists
324                        $todouser = $data['todousers'][0];
325                    }
326                    break;
327                case "none": unset($todouser); break;
328            }
329            $return .= '<span class="todouser">[' . hsc($todouser) . ']</span>';
330        }
331
332        // start/due date
333        unset($bg);
334        $now = new DateTime("now");
335        if(!$checked && (isset($data['start']) || isset($data['due'])) && (!isset($data['start']) || $data['start']<$now) && (!isset($data['due']) || $now<$data['due'])) $bg='todostarted';
336        if(!$checked && isset($data['due']) && $now>=$data['due']) $bg='tododue';
337
338        // show start/due date
339        if($data['showdate'] == 1 && (isset($data['start']) || isset($data['due']))) {
340            $return .= '<span class="tododates">[';
341            if(isset($data['start'])) { $return .= $data['start']->format('Y-m-d'); }
342            $return .= ' → ';
343            if(isset($data['due'])) { $return .= $data['due']->format('Y-m-d'); }
344            $return .= ']</span>';
345        }
346
347        $spanclass = 'todotext';
348        if($this->getConf("CheckboxText") && !$this->getConf("AllowLinks") && $data['checkbox']) {
349            $spanclass .= ' clickabletodo todohlght';
350        }
351        if(isset($bg)) $spanclass .= ' '.$bg;
352        $return .= '<span class="' . $spanclass . '">';
353
354        if($checked && $this->getConf("Strikethrough")) {
355            $return .= '<del>';
356        }
357        $return .= '<span class="todoinnertext">';
358        if($this->getConf("AllowLinks")) {
359            $return .= $this->_createLink($renderer, $todotitle, $todotitle);
360        } else {
361            if ($oldID != $ID) {
362                $return .= $renderer->internallink($id, $todotitle, null, true);
363            } else {
364                 $return .= hsc($todotitle);
365            }
366        }
367        $return .= '</span>';
368
369        if($checked && $this->getConf("Strikethrough")) {
370            $return .= '</del>';
371        }
372
373        $return .= '</span>';
374
375        //restore page ID
376        $ID = $oldID;
377        return $return;
378    }
379
380    /**
381     * Generate links from our Actions if necessary.
382     *
383     * @param Doku_Renderer_xhtml &$renderer
384     * @param string $pagename
385     * @param string $name
386     * @return string
387     */
388    private function _createLink(&$renderer, $pagename, $name = NULL) {
389        $id = $this->_composePageid($pagename);
390
391        return $renderer->internallink($id, $name, null, true);
392    }
393
394    /**
395     * Compose the pageid of the pages linked by a todoitem
396     *
397     * @param string $pagename
398     * @return string page id
399     */
400    private function _composePageid($pagename) {
401        #Get the ActionNamespace and make sure it ends with a : (if not, add it)
402        $actionNamespace = $this->getConf("ActionNamespace");
403        if(strlen($actionNamespace) == 0 || substr($actionNamespace, -1) != ':') {
404            $actionNamespace .= ":";
405        }
406
407        #Replace ':' in $pagename so we don't create unnecessary namespaces
408        $pagename = str_replace(':', '-', $pagename);
409
410        //resolve and build link
411        $id = $actionNamespace . $pagename;
412        return $id;
413    }
414
415    /**
416     * @brief this function can be called by dokuwiki plugin searchpattern to process the todos found by searchpattern.
417     * use this searchpattern expression for open todos:
418     *          ~~SEARCHPATTERN#'/<todo[^#>]*>.*?<\/todo[\W]*?>/'?? _ToDo ??~~
419     * use this searchpattern expression for completed todos:
420     *          ~~SEARCHPATTERN#'/<todo[^#>]*#[^>]*>.*?<\/todo[\W]*?>/'?? _ToDo ??~~
421     * this handler method uses the table and layout with css classes from searchpattern plugin
422     *
423     * @param $type   string type of the request from searchpattern plugin
424     *                (wholeoutput, intable:whole, intable:prefix, intable:match, intable:count, intable:suffix)
425     *                wholeoutput     = all output is done by THIS plugin (no output will be done by search pattern)
426     *                intable:whole   = the left side of table (page name) is done by searchpattern, the right side
427     *                                  of the table will be done by THIS plugin
428     *                intable:prefix  = on the right side of table - THIS plugin will output a prefix header and
429     *                                  searchpattern will continue it's default output
430     *                intable:match   = if regex, right side of table - THIS plugin will format the current
431     *                                  outputvalue ($value) and output it instead of searchpattern
432     *                intable:count   = if normal, right side of table - THIS plugin will format the current
433     *                                  outputvalue ($value) and output it instead of searchpattern
434     *                intable:suffix  = on the right side of table - THIS plugin will output a suffix footer and
435     *                                  searchpattern will continue it's default output
436     * @param Doku_Renderer_xhtml &$renderer current rendering object (use $renderer->doc .= 'text' to output text)
437     * @param array $data     whole data multidemensional array( array( $page => $countOfMatches ), ... )
438     * @param array $matches  whole regex matches multidemensional array( array( 0 => '1st Match', 1 => '2nd Match', ... ), ... )
439     * @param string $page     id of current page
440     * @param array $params   the parameters set by searchpattern (see search pattern documentation)
441     * @param string $value    value which should be outputted by searchpattern
442     * @return bool true if THIS method is responsible for the output (using $renderer->doc) OR false if searchpattern should output it's default
443     */
444    public function _searchpatternHandler($type, &$renderer, $data, $matches, $params = array(), $page = null, $value = null) {
445        $renderer->nocache();
446
447        $type = strtolower($type);
448        switch($type) {
449            case 'wholeoutput':
450                // $matches should hold an array with all <todo>matches</todo> or <todo #>matches</todo>
451                if(!is_array($matches)) {
452                    return false;
453                }
454                //file_put_contents( dirname(__FILE__).'/debug.txt', print_r($matches,true), FILE_APPEND );
455                //file_put_contents( dirname(__FILE__).'/debug.txt', print_r($params,true), FILE_APPEND );
456                $renderer->doc .= '<div class="sp_main">';
457                $renderer->doc .= '<table class="inline sp_main_table">'; //create table
458
459                foreach($matches as $page => $allTodosPerPage) {
460                    $renderer->doc .= '<tr class="sp_title"><th class="sp_title" colspan="2"><a href="' . wl($page) . '">' . $page . '</a></td></tr>';
461                    //entry 0 contains all whole matches
462                    foreach($allTodosPerPage[0] as $todoindex => $todomatch) {
463                        $x = preg_match('%<todo([^>]*)>(.*)</[\W]*todo[\W]*>%i', $todomatch, $tododata);
464
465                        if($x) {
466                            list($checked, $todouser) = $this->parseTodoArgs($tododata[1]);
467                            $todotitle = trim($tododata[2]);
468                            if(empty($todotitle)) {
469                                continue;
470                            }
471                            $renderer->doc .= '<tr class="sp_result"><td class="sp_page" colspan="2">';
472
473                            // in case of integration with searchpattern there is no chance to find the index of an element
474                            $renderer->doc .= $this->createTodoItem($renderer, $todotitle, $todoindex, $todouser, $checked, $page, array('checkbox'=>'yes', 'username'=>'user'));
475
476                            $renderer->doc .= '</td></tr>';
477                        }
478                    }
479                }
480                $renderer->doc .= '</table>'; //end table
481                $renderer->doc .= '</div>';
482                // true means, that this handler method does the output (searchpattern plugin has nothing to do)
483                return true;
484                break;
485            case 'intable:whole':
486                break;
487            case 'intable:prefix':
488                //$renderer->doc .= '<b>Start on Page '.$page.'</b>';
489                break;
490            case 'intable:match':
491                //$renderer->doc .= 'regex match on page '.$page.': <pre>'.$value.'</pre>';
492                break;
493            case 'intable:count':
494                //$renderer->doc .= 'normal count on page '.$page.': <pre>'.$value.'</pre>';
495                break;
496            case 'intable:suffix':
497                //$renderer->doc .= '<b>End on Page '.$page.'</b>';
498                break;
499            default:
500                break;
501        }
502        // false means, that this handler method does not output anything. all should be done by searchpattern plugin
503        return false;
504    }
505}
506
507//Setup VIM: ex: et ts=4 enc=utf-8 :
508