xref: /plugin/tagging/helper.php (revision 89ed97adc6d7f9c2ec90ca4f233633251c6fc491)
1<?php
2/**
3 * Tagging Plugin (hlper component)
4 *
5 * @license GPL 2
6 */
7class helper_plugin_tagging extends DokuWiki_Plugin {
8
9    /**
10     * Gives access to the database
11     *
12     * Initializes the SQLite helper and register the CLEANTAG function
13     *
14     * @return helper_plugin_sqlite|bool false if initialization fails
15     */
16    public function getDB() {
17        static $db = null;
18        if ($db !== null) {
19            return $db;
20        }
21
22        /** @var helper_plugin_sqlite $db */
23        $db = plugin_load('helper', 'sqlite');
24        if ($db === null) {
25            msg('The tagging plugin needs the sqlite plugin', -1);
26
27            return false;
28        }
29        $db->init('tagging', __DIR__ . '/db/');
30        $db->create_function('CLEANTAG', array($this, 'cleanTag'), 1);
31        $db->create_function('GROUP_SORT',
32            function ($group, $newDelimiter) {
33                $ex = array_filter(explode(',', $group));
34                sort($ex);
35
36                return implode($newDelimiter, $ex);
37            }, 2);
38        $db->create_function('GET_NS', 'getNS', 1);
39
40        return $db;
41    }
42
43    /**
44     * Return the user to use for accessing tags
45     *
46     * Handles the singleuser mode by returning 'auto' as user. Returnes false when no user is logged in.
47     *
48     * @return bool|string
49     */
50    public function getUser() {
51        if (!isset($_SERVER['REMOTE_USER'])) {
52            return false;
53        }
54        if ($this->getConf('singleusermode')) {
55            return 'auto';
56        }
57
58        return $_SERVER['REMOTE_USER'];
59    }
60
61    /**
62     * Canonicalizes the tag to its lower case nospace form
63     *
64     * @param $tag
65     *
66     * @return string
67     */
68    public function cleanTag($tag) {
69        $tag = str_replace(array(' ', '-', '_'), '', $tag);
70        $tag = utf8_strtolower($tag);
71
72        return $tag;
73    }
74
75    /**
76     * Canonicalizes the namespace, remove the first colon and add glob
77     *
78     * @param $namespace
79     *
80     * @return string
81     */
82    public function globNamespace($namespace) {
83        return cleanId($namespace) . '*';
84    }
85
86    /**
87     * Create or Update tags of a page
88     *
89     * Uses the translation plugin to store the language of a page (if available)
90     *
91     * @param string $id The page ID
92     * @param string $user
93     * @param array  $tags
94     *
95     * @return bool|SQLiteResult
96     */
97    public function replaceTags($id, $user, $tags) {
98        global $conf;
99        /** @var helper_plugin_translation $trans */
100        $trans = plugin_load('helper', 'translation');
101        if ($trans) {
102            $lang = $trans->realLC($trans->getLangPart($id));
103        } else {
104            $lang = $conf['lang'];
105        }
106
107        $db = $this->getDB();
108        $db->query('BEGIN TRANSACTION');
109        $queries = array(array('DELETE FROM taggings WHERE pid = ? AND tagger = ?', $id, $user));
110        foreach ($tags as $tag) {
111            $queries[] = array('INSERT INTO taggings (pid, tagger, tag, lang) VALUES(?, ?, ?, ?)', $id, $user, $tag, $lang);
112        }
113
114        foreach ($queries as $query) {
115            if (!call_user_func_array(array($db, 'query'), $query)) {
116                $db->query('ROLLBACK TRANSACTION');
117
118                return false;
119            }
120        }
121
122        return $db->query('COMMIT TRANSACTION');
123    }
124
125    /**
126     * Get a list of Tags or Pages matching search criteria
127     *
128     * @param array  $filter What to search for array('field' => 'searchterm')
129     * @param string $type   What field to return 'tag'|'pid'
130     * @param int    $limit  Limit to this many results, 0 for all
131     *
132     * @return array associative array in form of value => count
133     */
134    public function findItems($filter, $type, $limit = 0) {
135
136        global $INPUT;
137
138        /** @var helper_plugin_tagging_querybuilder $queryBuilder */
139        $queryBuilder = new \helper_plugin_tagging_querybuilder();
140
141        $queryBuilder->setField($type);
142        $queryBuilder->setLimit($limit);
143        $queryBuilder->setTags($this->getTags($filter));
144        if (isset($filter['ns'])) $queryBuilder->includeNS($filter['ns']);
145        if (isset($filter['notns'])) $queryBuilder->excludeNS($filter['notns']);
146        if (isset($filter['tagger'])) $queryBuilder->setTagger($filter['tagger']);
147        if (isset($filter['pid'])) $queryBuilder->setPid($filter['pid']);
148
149        return $this->queryDb($queryBuilder->getQuery());
150
151    }
152
153    /**
154     * Constructs the URL to search for a tag
155     *
156     * @param string $tag
157     * @param string $ns
158     *
159     * @return string
160     */
161    public function getTagSearchURL($tag, $ns = '') {
162        // wrap tag in quotes if non clean
163        $ctag = utf8_stripspecials($this->cleanTag($tag));
164        if ($ctag != utf8_strtolower($tag)) {
165            $tag = '"' . $tag . '"';
166        }
167
168        $ret = '?do=search&sf=1&id=' . rawurlencode($tag);
169        if ($ns) {
170            $ret .= rawurlencode(' @' . $ns);
171        }
172
173        return $ret;
174    }
175
176    /**
177     * Calculates the size levels for the given list of clouds
178     *
179     * Automatically determines sensible tresholds
180     *
181     * @param array $tags list of tags => count
182     * @param int   $levels
183     *
184     * @return mixed
185     */
186    public function cloudData($tags, $levels = 10) {
187        $min = min($tags);
188        $max = max($tags);
189
190        // calculate tresholds
191        $tresholds = array();
192        for ($i = 0; $i <= $levels; $i++) {
193            $tresholds[$i] = pow($max - $min + 1, $i / $levels) + $min - 1;
194        }
195
196        // assign weights
197        foreach ($tags as $tag => $cnt) {
198            foreach ($tresholds as $tresh => $val) {
199                if ($cnt <= $val) {
200                    $tags[$tag] = $tresh;
201                    break;
202                }
203                $tags[$tag] = $levels;
204            }
205        }
206
207        return $tags;
208    }
209
210    /**
211     * Display a tag cloud
212     *
213     * @param array    $tags   list of tags => count
214     * @param string   $type   'tag'
215     * @param Callable $func   The function to print the link (gets tag and ns)
216     * @param bool     $wrap   wrap cloud in UL tags?
217     * @param bool     $return returnn HTML instead of printing?
218     * @param string   $ns     Add this namespace to search links
219     *
220     * @return string
221     */
222    public function html_cloud($tags, $type, $func, $wrap = true, $return = false, $ns = '') {
223        global $INFO;
224
225        $hidden_str = $this->getConf('hiddenprefix');
226        $hidden_len = strlen($hidden_str);
227
228        $ret = '';
229        if ($wrap) {
230            $ret .= '<ul class="tagging_cloud clearfix">';
231        }
232        if (count($tags) === 0) {
233            // Produce valid XHTML (ul needs a child)
234            $this->setupLocale();
235            $ret .= '<li><div class="li">' . $this->lang['js']['no' . $type . 's'] . '</div></li>';
236        } else {
237            $tags = $this->cloudData($tags);
238            foreach ($tags as $val => $size) {
239                // skip hidden tags for users that can't edit
240                if ($type === 'tag' and
241                    $hidden_len and
242                    substr($val, 0, $hidden_len) == $hidden_str and
243                    !($this->getUser() && $INFO['writable'])
244                ) {
245                    continue;
246                }
247
248                $ret .= '<li class="t' . $size . '"><div class="li">';
249                $ret .= call_user_func($func, $val, $ns);
250                $ret .= '</div></li>';
251            }
252        }
253        if ($wrap) {
254            $ret .= '</ul>';
255        }
256        if ($return) {
257            return $ret;
258        }
259        echo $ret;
260
261        return '';
262    }
263
264    /**
265     * Get the link to a search for the given tag
266     *
267     * @param string $tag search for this tag
268     * @param string $ns  limit search to this namespace
269     *
270     * @return string
271     */
272    protected function linkToSearch($tag, $ns = '') {
273        return '<a href="' . hsc($this->getTagSearchURL($tag, $ns)) . '">' . $tag . '</a>';
274    }
275
276    /**
277     * Display the Tags for the current page and prepare the tag editing form
278     *
279     * @param bool $print Should the HTML be printed or returned?
280     *
281     * @return string
282     */
283    public function tpl_tags($print = true) {
284        global $INFO;
285        global $lang;
286
287        $filter = array('pid' => $INFO['id']);
288        if ($this->getConf('singleusermode')) {
289            $filter['tagger'] = 'auto';
290        }
291
292        $tags = $this->findItems($filter, 'tag');
293
294        $ret = '';
295
296        $ret .= '<div class="plugin_tagging_edit">';
297        $ret .= $this->html_cloud($tags, 'tag', array($this, 'linkToSearch'), true, true);
298
299        if ($this->getUser() && $INFO['writable']) {
300            $lang['btn_tagging_edit'] = $lang['btn_secedit'];
301            $ret .= '<div id="tagging__edit_buttons_group">';
302            $ret .= html_btn('tagging_edit', $INFO['id'], '', array());
303            if (auth_isadmin()) {
304                $ret .= '<label>' . $this->getLang('toggle admin mode') . '<input type="checkbox" id="tagging__edit_toggle_admin" /></label>';
305            }
306            $ret .= '</div>';
307            $form = new dokuwiki\Form\Form();
308            $form->id('tagging__edit');
309            $form->setHiddenField('tagging[id]', $INFO['id']);
310            $form->setHiddenField('call', 'plugin_tagging_save');
311            $tags = $this->findItems(array(
312                'pid'    => $INFO['id'],
313                'tagger' => $this->getUser(),
314            ), 'tag');
315            $form->addTextarea('tagging[tags]')->val(implode(', ', array_keys($tags)))->addClass('edit')->attr('rows', 4);
316            $form->addButton('', $lang['btn_save'])->id('tagging__edit_save');
317            $form->addButton('', $lang['btn_cancel'])->id('tagging__edit_cancel');
318            $ret .= $form->toHTML();
319        }
320        $ret .= '</div>';
321
322        if ($print) {
323            echo $ret;
324        }
325
326        return $ret;
327    }
328
329    /**
330     * @param string $namespace empty for entire wiki
331     *
332     * @param string $order_by
333     * @param bool $desc
334     * @param array $filters
335     * @return array
336     */
337    public function getAllTags($namespace = '', $order_by = 'tag', $desc = false, $filters = []) {
338        $order_fields = array('pid', 'tid', 'orig', 'taggers', 'ns', 'count');
339        if (!in_array($order_by, $order_fields)) {
340            msg('cannot sort by ' . $order_by . ' field does not exists', -1);
341            $order_by = 'tag';
342        }
343
344        list($having, $params) = $this->getFilterSql($filters);
345
346        $db = $this->getDb();
347
348        $query = 'SELECT    "pid",
349                            CLEANTAG("tag") AS "tid",
350                            GROUP_SORT(GROUP_CONCAT("tag"), \', \') AS "orig",
351                            GROUP_SORT(GROUP_CONCAT("tagger"), \', \') AS "taggers",
352                            GROUP_SORT(GROUP_CONCAT(GET_NS("pid")), \', \') AS "ns",
353                            GROUP_SORT(GROUP_CONCAT("pid"), \', \') AS "pids",
354                            COUNT(*) AS "count"
355                        FROM "taggings"
356                        WHERE "pid" GLOB ?
357                        GROUP BY "tid"';
358        $query .= $having;
359        $query .=      'ORDER BY ' . $order_by;
360        if ($desc) {
361            $query .= ' DESC';
362        }
363
364        array_unshift($params, $this->globNamespace($namespace));
365        $res = $db->query($query, $params);
366
367        return $db->res2arr($res);
368    }
369
370    /**
371     * Get all pages with tags and their tags
372     *
373     * @return array ['pid' => ['tag1','tag2','tag3']]
374     */
375    public function getAllTagsByPage() {
376        $query = '
377        SELECT pid, GROUP_CONCAT(tag) AS tags
378        FROM taggings
379        GROUP BY pid
380        ';
381        $db = $this->getDb();
382        $res = $db->query($query);
383        return array_map(
384            function ($i) {
385                return explode(',', $i);
386            },
387            array_column($db->res2arr($res), 'tags', 'pid')
388        );
389    }
390
391    /**
392     * Renames a tag
393     *
394     * @param string $formerTagName
395     * @param string $newTagName
396     */
397    public function renameTag($formerTagName, $newTagName) {
398
399        if (empty($formerTagName) || empty($newTagName)) {
400            msg($this->getLang("admin enter tag names"), -1);
401
402            return;
403        }
404
405        $db = $this->getDb();
406
407        $res = $db->query('SELECT pid FROM taggings WHERE CLEANTAG(tag) = ?', $this->cleanTag($formerTagName));
408        $check = $db->res2arr($res);
409
410        if (empty($check)) {
411            msg($this->getLang("admin tag does not exists"), -1);
412
413            return;
414        }
415
416        $res = $db->query("UPDATE taggings SET tag = ? WHERE CLEANTAG(tag) = ?", $newTagName, $this->cleanTag($formerTagName));
417        $db->res2arr($res);
418
419        msg($this->getLang("admin renamed"), 1);
420
421        return;
422    }
423
424    /**
425     * Rename or delete a tag for all users
426     *
427     * @param string $pid
428     * @param string $formerTagName
429     * @param string $newTagName
430     *
431     * @return array
432     */
433    public function modifyPageTag($pid, $formerTagName, $newTagName) {
434
435        $db = $this->getDb();
436
437        $res = $db->query('SELECT pid FROM taggings WHERE CLEANTAG(tag) = ? AND pid = ?', $this->cleanTag($formerTagName), $pid);
438        $check = $db->res2arr($res);
439
440        if (empty($check)) {
441            return array(true, $this->getLang('admin tag does not exists'));
442        }
443
444        if (empty($newTagName)) {
445            $res = $db->query('DELETE FROM taggings WHERE pid = ? AND CLEANTAG(tag) = ?', $pid, $this->cleanTag($formerTagName));
446        } else {
447            $res = $db->query('UPDATE taggings SET tag = ? WHERE pid = ? AND CLEANTAG(tag) = ?', $newTagName, $pid, $this->cleanTag($formerTagName));
448        }
449        $db->res2arr($res);
450
451        return array(false, $this->getLang('admin renamed'));
452    }
453
454    /**
455     * Deletes a tag
456     *
457     * @param array  $tags
458     * @param string $namespace current namespace context as in getAllTags()
459     */
460    public function deleteTags($tags, $namespace = '') {
461        if (empty($tags)) {
462            return;
463        }
464
465        $namespace = cleanId($namespace);
466
467        $db = $this->getDB();
468
469        $queryBody = 'FROM taggings WHERE pid GLOB ? AND (' .
470            implode(' OR ', array_fill(0, count($tags), 'CLEANTAG(tag) = ?')) . ')';
471        $args = array_map(array($this, 'cleanTag'), $tags);
472        array_unshift($args, $this->globNamespace($namespace));
473
474
475        $affectedPagesQuery= 'SELECT DISTINCT pid ' . $queryBody;
476        $resAffectedPages = $db->query($affectedPagesQuery, $args);
477        $numAffectedPages = count($resAffectedPages->fetchAll());
478
479        $deleteQuery = 'DELETE ' . $queryBody;
480        $db->query($deleteQuery, $args);
481
482        msg(sprintf($this->getLang("admin deleted"), count($tags), $numAffectedPages), 1);
483    }
484
485    /**
486     * Updates tags with a new page name
487     *
488     * @param string $oldName
489     * @param string $newName
490     */
491    public function renamePage($oldName, $newName) {
492        $db = $this->getDb();
493        $db->query('UPDATE taggings SET pid = ? WHERE pid = ?', $newName, $oldName);
494    }
495
496    /**
497     * Extracts tags from search query
498     *
499     * @param array $parsedQuery
500     * @return array
501     */
502    public function getTags($parsedQuery)
503    {
504        $tags = [];
505        if (isset($parsedQuery['phrases'][0])) {
506            $tags = $parsedQuery['phrases'];
507        } elseif (isset($parsedQuery['and'][0])) {
508            $tags = $parsedQuery['and'];
509        } elseif (isset($parsedQuery['tag'])) {
510            // handle autocomplete call
511            $tags[] = $parsedQuery['tag'];
512        }
513        return $tags;
514    }
515
516    /**
517     * Search for tagged pages
518     *
519     * @return array
520     */
521    public function searchPages()
522    {
523        global $INPUT;
524        global $QUERY;
525        $parsedQuery = ft_queryParser(new Doku_Indexer(), $QUERY);
526
527        /** @var helper_plugin_tagging_querybuilder $queryBuilder */
528        $queryBuilder = new \helper_plugin_tagging_querybuilder();
529
530        $queryBuilder->setField('pid');
531        $queryBuilder->setTags($this->getTags($parsedQuery));
532        $queryBuilder->setLogicalAnd($INPUT->str('taggings') === 'and');
533        if (isset($parsedQuery['ns'])) $queryBuilder->includeNS($parsedQuery['ns']);
534        if (isset($parsedQuery['notns'])) $queryBuilder->excludeNS($parsedQuery['notns']);
535        if (isset($parsedQuery['tagger'])) $queryBuilder->setTagger($parsedQuery['tagger']);
536        if (isset($parsedQuery['pid'])) $queryBuilder->setPid($parsedQuery['pid']);
537
538        return $this->queryDb($queryBuilder->getPages());
539    }
540
541    /**
542     * Display tag management table
543     */
544    public function html_table() {
545        global $ID, $INPUT;
546
547        $headers = array(
548            array('value' => $this->getLang('admin tag'), 'sort_by' => 'tid'),
549            array('value' => $this->getLang('admin occurrence'), 'sort_by' => 'count'),
550            array('value' => $this->getLang('admin writtenas'), 'sort_by' => 'orig'),
551            array('value' => $this->getLang('admin namespaces'), 'sort_by' => 'ns'),
552            array('value' => $this->getLang('admin taggers'), 'sort_by' => 'taggers'),
553            array('value' => $this->getLang('admin actions'), 'sort_by' => false),
554        );
555
556        $sort = explode(',', $INPUT->str('sort'));
557        $order_by = $sort[0];
558        $desc = false;
559        if (isset($sort[1]) && $sort[1] === 'desc') {
560            $desc = true;
561        }
562        $filters = $INPUT->arr('tagging__filters');
563
564        $tags = $this->getAllTags($INPUT->str('filter'), $order_by, $desc, $filters);
565
566        $form = new dokuwiki\Form\Form();
567        $form->setHiddenField('do', 'admin');
568        $form->setHiddenField('page', 'tagging');
569        $form->setHiddenField('id', $ID);
570        $form->setHiddenField('sort', $INPUT->str('sort'));
571
572        /**
573         * Actions dialog
574         */
575        $form->addTagOpen('div')->id('tagging__action-dialog')->attr('style', "display:none;");
576        $form->addTagClose('div');
577
578        /**
579         * Tag pages dialog
580         */
581        $form->addTagOpen('div')->id('tagging__taggedpages-dialog')->attr('style', "display:none;");
582        $form->addTagClose('div');
583
584        /**
585         * Tag management table
586         */
587        $form->addTagOpen('table')->addClass('inline plugin_tagging');
588
589        /**
590         * Table headers
591         */
592        $form->addTagOpen('tr');
593        foreach ($headers as $header) {
594            $form->addTagOpen('th');
595            if ($header['sort_by'] !== false) {
596                $param = $header['sort_by'];
597                $icon = 'arrow-both';
598                $title = $this->getLang('admin sort ascending');
599                if ($header['sort_by'] === $order_by) {
600                    if ($desc === false) {
601                        $icon = 'arrow-up';
602                        $title = $this->getLang('admin sort descending');
603                        $param .= ',desc';
604                    } else {
605                        $icon = 'arrow-down';
606                    }
607                }
608                $form->addButtonHTML("fn[sort][$param]", $header['value'] . ' ' . inlineSVG(dirname(__FILE__) . "/images/$icon.svg"))
609                    ->addClass('plugin_tagging sort_button')
610                    ->attr('title', $title);
611            } else {
612                $form->addHTML($header['value']);
613            }
614            $form->addTagClose('th');
615        }
616        $form->addTagClose('tr');
617
618        /**
619         * Table filters for all sortable columns
620         */
621        $form->addTagOpen('tr');
622        foreach ($headers as $header) {
623            $form->addTagOpen('th');
624            if ($header['sort_by'] !== false) {
625                $field = $header['sort_by'];
626                $form->addTextInput("tagging__filters[$field]");
627            }
628            $form->addTagClose('th');
629        }
630        $form->addTagClose('tr');
631
632
633        foreach ($tags as $taginfo) {
634            $tagname = $taginfo['tid'];
635            $taggers = $taginfo['taggers'];
636            $written = $taginfo['orig'];
637            $ns = $taginfo['ns'];
638            $pids = explode(',',$taginfo['pids']);
639
640            $form->addTagOpen('tr');
641            $form->addHTML('<td><a class="tagslist" href="#" data-pids="' . $taginfo['pids'] . '">' . hsc($tagname) . '</a></td>');
642            $form->addHTML('<td>' . $taginfo['count'] . '</td>');
643            $form->addHTML('<td>' . hsc($written) . '</td>');
644            $form->addHTML('<td>' . hsc($ns) . '</td>');
645            $form->addHTML('<td>' . hsc($taggers) . '</td>');
646
647            /**
648             * action buttons
649             */
650            $form->addHTML('<td>');
651
652            // check ACLs
653            $userEdit = false;
654            /** @var \helper_plugin_sqlite $sqliteHelper */
655            $sqliteHelper = plugin_load('helper', 'sqlite');
656            foreach ($pids as $pid) {
657                if ($sqliteHelper->_getAccessLevel($pid) >= AUTH_EDIT) {
658                    $userEdit = true;
659                    continue;
660                }
661            }
662
663            if ($userEdit) {
664                $form->addButtonHTML('fn[actions][rename][' . $taginfo['tid'] . ']', inlineSVG(dirname(__FILE__) . '/images/edit.svg'))
665                    ->addClass('plugin_tagging action_button')->attr('data-action', 'rename')->attr('data-tid', $taginfo['tid']);
666                $form->addButtonHTML('fn[actions][delete][' . $taginfo['tid'] . ']', inlineSVG(dirname(__FILE__) . '/images/delete.svg'))
667                    ->addClass('plugin_tagging action_button')->attr('data-action', 'delete')->attr('data-tid', $taginfo['tid']);
668            }
669
670            $form->addHTML('</td>');
671            $form->addTagClose('tr');
672        }
673
674        $form->addTagClose('table');
675        return $form->toHTML();
676    }
677
678    /**
679     * Executes the query and returns the results as array
680     *
681     * @param array $query
682     * @return array
683     */
684    protected function queryDb($query)
685    {
686        $db = $this->getDB();
687        if (!$db) {
688            return [];
689        }
690
691        $res = $db->query($query[0], $query[1]);
692        $res = $db->res2arr($res);
693
694        $ret = [];
695        foreach ($res as $row) {
696            $ret[$row['item']] = $row['cnt'];
697        }
698        return $ret;
699    }
700
701    /**
702     * Construct the HAVING part of the search query
703     *
704     * @param array $filters
705     * @return array
706     */
707    protected function getFilterSql($filters)
708    {
709        $having = '';
710        $parts = [];
711        $params = [];
712        $filters = array_filter($filters);
713        if (!empty($filters)) {
714            $having = ' HAVING ';
715            foreach ($filters as $filter => $value) {
716                $parts[] = " $filter LIKE ? ";
717                $params[] = "%$value%";
718            }
719            $having .= implode(' AND ', $parts);
720        }
721        return [$having, $params];
722    }
723}
724