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