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