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