xref: /plugin/todo/syntax/todo.php (revision 60db5b5d600af23c8dbcf11364ec4919b6cd957e)
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 *
30 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
31 * @author     Babbage <babbage@digitalbrink.com>; Leo Eibler <dokuwiki@sprossenwanne.at>
32 */
33
34if(!defined('DOKU_INC')) die();
35
36/**
37 * All DokuWiki plugins to extend the parser/rendering mechanism
38 * need to inherit from this class
39 */
40class syntax_plugin_todo_todo extends DokuWiki_Syntax_Plugin {
41
42    /**
43     * Get the type of syntax this plugin defines.
44     *
45     * @return String
46     */
47    public function getType() {
48        return 'substition';
49    }
50
51    /**
52     * Paragraph Type
53     *
54     * 'normal' - The plugin can be used inside paragraphs
55     * 'block'  - Open paragraphs need to be closed before plugin output
56     * 'stack'  - Special case. Plugin wraps other paragraphs.
57     */
58    function getPType(){
59        return 'normal';
60    }
61
62    /**
63     * Where to sort in?
64     *
65     * @return Integer
66     */
67    public function getSort() {
68        return 999;
69    }
70
71    /**
72     * Connect lookup pattern to lexer.
73     *
74     * @param $mode String The desired rendermode.
75     * @return void
76     * @see render()
77     */
78    public function connectTo($mode) {
79        $this->Lexer->addEntryPattern('<todo[\s]*?.*?>(?=.*?</todo>)', $mode, 'plugin_todo_todo');
80        $this->Lexer->addSpecialPattern('~~NOTODO~~', $mode, 'plugin_todo_todo');
81    }
82
83    public function postConnect() {
84        $this->Lexer->addExitPattern('</todo>', 'plugin_todo_todo');
85    }
86
87    /**
88     * Handler to prepare matched data for the rendering process.
89     *
90     * @param $match    string  The text matched by the patterns.
91     * @param $state    int     The lexer state for the match.
92     * @param $pos      int     The character position of the matched text.
93     * @param $handler Doku_Handler  Reference to the Doku_Handler object.
94     * @return int The current lexer state for the match.
95     */
96    public function handle($match, $state, $pos, Doku_Handler $handler) {
97        switch($state) {
98            case DOKU_LEXER_ENTER :
99                #Search to see if the '#' is in the todotag (if so, this means the Action has been completed)
100                $x = preg_match('%<todo([^>]*)>%i', $match, $tododata);
101                if($x) {
102                    $handler->todoargs =  $this->parseTodoArgs($tododata[1]);
103                }
104                if(!is_numeric($handler->todo_index)) {
105                    $handler->todo_index = 0;
106                }
107                break;
108            case DOKU_LEXER_MATCHED :
109                break;
110            case DOKU_LEXER_UNMATCHED :
111                /**
112                 * Structure:
113                 * input(checkbox)
114                 * <span>
115                 * -<a> (if links is on) or <span> (if links is off)
116                 * --<del> (if strikethrough is on) or --NOTHING--
117                 * -</a> or </span>
118                 * </span>
119                 */
120
121                #Make sure there is actually an action to create
122                if(trim($match) != '') {
123
124                    $data = array_merge(array ($state, 'todotitle' => $match, 'todoindex' => $handler->todo_index, 'todouser' => $handler->todo_user, 'checked' => $handler->checked), $handler->todoargs);
125                    $handler->todo_index++;
126                    return $data;
127                }
128
129                break;
130            case DOKU_LEXER_EXIT :
131                #Delete temporary checked variable
132                unset($handler->todo_user);
133                unset($handler->checked);
134                unset($handler->todoargs);
135                //unset($handler->todo_index);
136                break;
137            case DOKU_LEXER_SPECIAL :
138                break;
139        }
140        return array();
141    }
142
143    /**
144     * Handle the actual output creation.
145     *
146     * @param  $mode     String        The output format to generate.
147     * @param $renderer Doku_Renderer A reference to the renderer object.
148     * @param  $data     Array         The data created by the <tt>handle()</tt> method.
149     * @return Boolean true: if rendered successfully, or false: otherwise.
150     */
151    public function render($mode, Doku_Renderer $renderer, $data) {
152        global $ID;
153        list($state, $todotitle) = $data;
154        if($mode == 'xhtml') {
155            /** @var $renderer Doku_Renderer_xhtml */
156            if($state == DOKU_LEXER_UNMATCHED) {
157
158                #Output our result
159                $renderer->doc .= $this->createTodoItem($renderer, $ID, array_merge($data, array('checkbox'=>'yes')));
160                return true;
161            }
162
163        } elseif($mode == 'metadata') {
164            /** @var $renderer Doku_Renderer_metadata */
165            if($state == DOKU_LEXER_UNMATCHED) {
166                $id = $this->_composePageid($todotitle);
167                $renderer->internallink($id, $todotitle);
168            }
169        }
170        return false;
171    }
172
173    /**
174     * Parse the arguments of todotag
175     *
176     * @param string $todoargs
177     * @return array(bool, false|string) with checked and user
178     */
179    protected function parseTodoArgs($todoargs) {
180        $data['checked'] = false;
181        unset($data['start']);
182        unset($data['due']);
183        unset($data['completeddate']);
184        $data['showdate'] = $this->getConf("ShowdateTag");
185        $data['username'] = $this->getConf("Username");
186        $options = explode(' ', $todoargs);
187        foreach($options as $option) {
188            $option = trim($option);
189            if($option[0] == '@') {
190                $data['todousers'][] = substr($option, 1); //fill todousers array
191                if(!isset($data['todouser'])) $data['todouser'] = substr($option, 1); //set the first/main todouser
192            }
193            elseif($option[0] == '#') {
194                $data['checked'] = true;
195                @list($completeduser, $completeddate) = explode(':', $option, 2);
196                $data['completeduser'] = substr($completeduser, 1);
197                if(date('Y-m-d', strtotime($completeddate)) == $completeddate) {
198                    $data['completeddate'] = new DateTime($completeddate);
199                }
200            }
201            else {
202                @list($key, $value) = explode(':', $option, 2);
203                switch($key) {
204                    case 'username':
205                        if(in_array($value, array('user', 'real', 'none'))) {
206                            $data['username'] = $value;
207                        }
208                        break;
209                    case 'start':
210                        if(date('Y-m-d', strtotime($value)) == $value) {
211                            $data['start'] = new DateTime($value);
212                        }
213                        break;
214                    case 'due':
215                        if(date('Y-m-d', strtotime($value)) == $value) {
216                            $data['due'] = new DateTime($value);
217                        }
218                        break;
219                    case 'showdate':
220                        if(in_array($value, array('yes', 'no'))) {
221                            $data['showdate'] = ($value == 'yes');
222                        }
223                        break;
224                }
225            }
226        }
227        return $data;
228    }
229
230    /**
231     * @param Doku_Renderer_xhtml $renderer
232     * @param string $id of page
233     * @param array  $data  data for rendering options
234     * @return string html of an item
235     */
236    protected function createTodoItem($renderer, $id, $data) {
237        //set correct context
238        global $ID, $INFO;
239        $oldID = $ID;
240        $ID = $id;
241        $todotitle = $data['todotitle'];
242        $todoindex = $data['todoindex'];
243        $checked = $data['checked'];
244
245        if($data['checkbox']) {
246            $return = '<input type="checkbox" class="todocheckbox"'
247            . ' data-index="' . $todoindex . '"'
248            . ' data-date="' . hsc(@filemtime(wikiFN($ID))) . '"'
249            . ' data-pageid="' . hsc($ID) . '"'
250            . ' data-strikethrough="' . ($this->getConf("Strikethrough") ? '1' : '0') . '"'
251            . ($checked ? ' checked="checked"' : '') . ' /> ';
252        }
253
254        // Username(s) of todouser(s)
255        if (!isset($data['todousers'])) $data['todousers']=array();
256        $todousers = array();
257        foreach($data['todousers'] as $user) {
258            if (($user = $this->_prepUsername($user,$data['username'])) != '') {
259                $todousers[] = $user;
260            }
261        }
262        $todouser=join(', ',$todousers);
263
264        if($todouser!='') {
265            $return .= '<span class="todouser">[' . hsc($todouser) . ']</span>';
266        }
267        if(isset($data['completeduser']) && ($checkeduser=$this->_prepUsername($data['completeduser'],$data['username']))!='') {
268            $return .= '<span class="todouser">[' . hsc('✓ '.$checkeduser);
269            if(isset($data['completeddate'])) { $return .= ', '.$data['completeddate']->format('Y-m-d'); }
270            $return .= ']</span>';
271        }
272
273        // start/due date
274        unset($bg);
275        $now = new DateTime("now");
276        if(!$checked && (isset($data['start']) || isset($data['due'])) && (!isset($data['start']) || $data['start']<$now) && (!isset($data['due']) || $now<$data['due'])) $bg='todostarted';
277        if(!$checked && isset($data['due']) && $now>=$data['due']) $bg='tododue';
278
279        // show start/due date
280        if($data['showdate'] == 1 && (isset($data['start']) || isset($data['due']))) {
281            $return .= '<span class="tododates">[';
282            if(isset($data['start'])) { $return .= $data['start']->format('Y-m-d'); }
283            $return .= ' → ';
284            if(isset($data['due'])) { $return .= $data['due']->format('Y-m-d'); }
285            $return .= ']</span>';
286        }
287
288        $spanclass = 'todotext';
289        if($this->getConf("CheckboxText") && !$this->getConf("AllowLinks") && $oldID == $ID && $data['checkbox']) {
290            $spanclass .= ' clickabletodo todohlght';
291        }
292        if(isset($bg)) $spanclass .= ' '.$bg;
293        $return .= '<span class="' . $spanclass . '">';
294
295        if($checked && $this->getConf("Strikethrough")) {
296            $return .= '<del>';
297        }
298        $return .= '<span class="todoinnertext">';
299        if($this->getConf("AllowLinks")) {
300            $return .= $this->_createLink($renderer, $todotitle, $todotitle);
301        } else {
302            if ($oldID != $ID) {
303                $return .= $renderer->internallink($id, $todotitle, null, true);
304            } else {
305                 $return .= hsc($todotitle);
306            }
307        }
308        $return .= '</span>';
309
310        if($checked && $this->getConf("Strikethrough")) {
311            $return .= '</del>';
312        }
313
314        $return .= '</span>';
315
316        //restore page ID
317        $ID = $oldID;
318        return $return;
319    }
320
321    /**
322     * Prepare user name string.
323     *
324     * @param string $username
325     * @param string $displaytype - one of 'user', 'real', 'none'
326     * @return string
327     */
328    private function _prepUsername($username, $displaytype) {
329
330        switch ($displaytype) {
331            case "real":
332                global $auth;
333                $username = $auth->getUserData($username)['name'];
334                break;
335            case "none":
336                $username="";
337                break;
338            case "user":
339            default:
340                break;
341        }
342
343        return $username;
344    }
345
346     /**
347     * Generate links from our Actions if necessary.
348     *
349     * @param Doku_Renderer_xhtml $renderer
350     * @param string $pagename
351     * @param string $name
352     * @return string
353     */
354    private function _createLink($renderer, $pagename, $name = NULL) {
355        $id = $this->_composePageid($pagename);
356
357        return $renderer->internallink($id, $name, null, true);
358    }
359
360    /**
361     * Compose the pageid of the pages linked by a todoitem
362     *
363     * @param string $pagename
364     * @return string page id
365     */
366    private function _composePageid($pagename) {
367        #Get the ActionNamespace and make sure it ends with a : (if not, add it)
368        $actionNamespace = $this->getConf("ActionNamespace");
369        if(strlen($actionNamespace) == 0 || substr($actionNamespace, -1) != ':') {
370            $actionNamespace .= ":";
371        }
372
373        #Replace ':' in $pagename so we don't create unnecessary namespaces
374        $pagename = str_replace(':', '-', $pagename);
375
376        //resolve and build link
377        $id = $actionNamespace . $pagename;
378        return $id;
379    }
380
381    /**
382     * @brief this function can be called by dokuwiki plugin searchpattern to process the todos found by searchpattern.
383     * use this searchpattern expression for open todos:
384     *          ~~SEARCHPATTERN#'/<todo[^#>]*>.*?<\/todo[\W]*?>/'?? _ToDo ??~~
385     * use this searchpattern expression for completed todos:
386     *          ~~SEARCHPATTERN#'/<todo[^#>]*#[^>]*>.*?<\/todo[\W]*?>/'?? _ToDo ??~~
387     * this handler method uses the table and layout with css classes from searchpattern plugin
388     *
389     * @param $type   string type of the request from searchpattern plugin
390     *                (wholeoutput, intable:whole, intable:prefix, intable:match, intable:count, intable:suffix)
391     *                wholeoutput     = all output is done by THIS plugin (no output will be done by search pattern)
392     *                intable:whole   = the left side of table (page name) is done by searchpattern, the right side
393     *                                  of the table will be done by THIS plugin
394     *                intable:prefix  = on the right side of table - THIS plugin will output a prefix header and
395     *                                  searchpattern will continue it's default output
396     *                intable:match   = if regex, right side of table - THIS plugin will format the current
397     *                                  outputvalue ($value) and output it instead of searchpattern
398     *                intable:count   = if normal, right side of table - THIS plugin will format the current
399     *                                  outputvalue ($value) and output it instead of searchpattern
400     *                intable:suffix  = on the right side of table - THIS plugin will output a suffix footer and
401     *                                  searchpattern will continue it's default output
402     * @param Doku_Renderer_xhtml $renderer current rendering object (use $renderer->doc .= 'text' to output text)
403     * @param array $data     whole data multidemensional array( array( $page => $countOfMatches ), ... )
404     * @param array $matches  whole regex matches multidemensional array( array( 0 => '1st Match', 1 => '2nd Match', ... ), ... )
405     * @param string $page     id of current page
406     * @param array $params   the parameters set by searchpattern (see search pattern documentation)
407     * @param string $value    value which should be outputted by searchpattern
408     * @return bool true if THIS method is responsible for the output (using $renderer->doc) OR false if searchpattern should output it's default
409     */
410    public function _searchpatternHandler($type, $renderer, $data, $matches, $params = array(), $page = null, $value = null) {
411        $renderer->nocache();
412
413        $type = strtolower($type);
414        switch($type) {
415            case 'wholeoutput':
416                // $matches should hold an array with all <todo>matches</todo> or <todo #>matches</todo>
417                if(!is_array($matches)) {
418                    return false;
419                }
420                //file_put_contents( dirname(__FILE__).'/debug.txt', print_r($matches,true), FILE_APPEND );
421                //file_put_contents( dirname(__FILE__).'/debug.txt', print_r($params,true), FILE_APPEND );
422                $renderer->doc .= '<div class="sp_main">';
423                $renderer->doc .= '<table class="inline sp_main_table">'; //create table
424
425                foreach($matches as $page => $allTodosPerPage) {
426                    $renderer->doc .= '<tr class="sp_title"><th class="sp_title" colspan="2"><a href="' . wl($page) . '">' . $page . '</a></td></tr>';
427                    //entry 0 contains all whole matches
428                    foreach($allTodosPerPage[0] as $todoindex => $todomatch) {
429                        $x = preg_match('%<todo([^>]*)>(.*)</[\W]*todo[\W]*>%i', $todomatch, $tododata);
430
431                        if($x) {
432                            list($checked, $todouser) = $this->parseTodoArgs($tododata[1]);
433                            $todotitle = trim($tododata[2]);
434                            if(empty($todotitle)) {
435                                continue;
436                            }
437                            $renderer->doc .= '<tr class="sp_result"><td class="sp_page" colspan="2">';
438
439                            // in case of integration with searchpattern there is no chance to find the index of an element
440                            $renderer->doc .= $this->createTodoItem($renderer, $todotitle, $todoindex, $todouser, $checked, $page, array('checkbox'=>'yes', 'username'=>'user'));
441
442                            $renderer->doc .= '</td></tr>';
443                        }
444                    }
445                }
446                $renderer->doc .= '</table>'; //end table
447                $renderer->doc .= '</div>';
448                // true means, that this handler method does the output (searchpattern plugin has nothing to do)
449                return true;
450                break;
451            case 'intable:whole':
452                break;
453            case 'intable:prefix':
454                //$renderer->doc .= '<b>Start on Page '.$page.'</b>';
455                break;
456            case 'intable:match':
457                //$renderer->doc .= 'regex match on page '.$page.': <pre>'.$value.'</pre>';
458                break;
459            case 'intable:count':
460                //$renderer->doc .= 'normal count on page '.$page.': <pre>'.$value.'</pre>';
461                break;
462            case 'intable:suffix':
463                //$renderer->doc .= '<b>End on Page '.$page.'</b>';
464                break;
465            default:
466                break;
467        }
468        // false means, that this handler method does not output anything. all should be done by searchpattern plugin
469        return false;
470    }
471}
472
473//Setup VIM: ex: et ts=4 enc=utf-8 :
474