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