xref: /plugin/tagging/helper.php (revision bdf1ecf014ccc20da3587eb70c86a132b8187486)
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 = explode(',', $group);
34                sort($ex);
35
36                return implode($newDelimiter, $ex);
37            }, 2);
38
39        return $db;
40    }
41
42    /**
43     * Return the user to use for accessing tags
44     *
45     * Handles the singleuser mode by returning 'auto' as user. Returnes false when no user is logged in.
46     *
47     * @return bool|string
48     */
49    public function getUser() {
50        if (!isset($_SERVER['REMOTE_USER'])) {
51            return false;
52        }
53        if ($this->getConf('singleusermode')) {
54            return 'auto';
55        }
56
57        return $_SERVER['REMOTE_USER'];
58    }
59
60    /**
61     * Canonicalizes the tag to its lower case nospace form
62     *
63     * @param $tag
64     *
65     * @return string
66     */
67    public function cleanTag($tag) {
68        $tag = str_replace(array(' ', '-', '_'), '', $tag);
69        $tag = utf8_strtolower($tag);
70
71        return $tag;
72    }
73
74    /**
75     * Canonicalizes the namespace, remove the first colon and add glob
76     *
77     * @param $namespace
78     *
79     * @return string
80     */
81    public function globNamespace($namespace) {
82        return cleanId($namespace) . '%';
83    }
84
85    /**
86     * Create or Update tags of a page
87     *
88     * Uses the translation plugin to store the language of a page (if available)
89     *
90     * @param string $id The page ID
91     * @param string $user
92     * @param array  $tags
93     *
94     * @return bool|SQLiteResult
95     */
96    public function replaceTags($id, $user, $tags) {
97        global $conf;
98        /** @var helper_plugin_translation $trans */
99        $trans = plugin_load('helper', 'translation');
100        if ($trans) {
101            $lang = $trans->realLC($trans->getLangPart($id));
102        } else {
103            $lang = $conf['lang'];
104        }
105
106        $db = $this->getDB();
107        $db->query('BEGIN TRANSACTION');
108        $queries = array(array('DELETE FROM taggings WHERE pid = ? AND tagger = ?', $id, $user));
109        foreach ($tags as $tag) {
110            $queries[] = array('INSERT INTO taggings (pid, tagger, tag, lang) VALUES(?, ?, ?, ?)', $id, $user, $tag, $lang);
111        }
112
113        foreach ($queries as $query) {
114            if (!call_user_func_array(array($db, 'query'), $query)) {
115                $db->query('ROLLBACK TRANSACTION');
116
117                return false;
118            }
119        }
120
121        return $db->query('COMMIT TRANSACTION');
122    }
123
124    /**
125     * Get a list of Tags or Pages matching search criteria
126     *
127     * @param array  $filter What to search for array('field' => 'searchterm')
128     * @param string $type   What field to return 'tag'|'pid'
129     * @param int    $limit  Limit to this many results, 0 for all
130     *
131     * @return array associative array in form of value => count
132     */
133    public function findItems($filter, $type, $limit = 0) {
134        $db = $this->getDB();
135        if (!$db) {
136            return array();
137        }
138
139        // create WHERE clause
140        $where = '1=1';
141        foreach ($filter as $field => $value) {
142            // compare clean tags only
143            if ($field === 'tag') {
144                $field = 'CLEANTAG(tag)';
145                $q = 'CLEANTAG(?)';
146            } else {
147                $q = '?';
148            }
149
150            if (substr($field, 0, 6) === 'notpid') {
151                $field = 'pid';
152
153                // detect LIKE filters
154                if ($this->useLike($value)) {
155                    $where .= " AND $field NOT LIKE $q";
156                } else {
157                    $where .= " AND $field != $q";
158                }
159            } else {
160                // detect LIKE filters
161                if ($this->useLike($value)) {
162                    $where .= " AND $field LIKE $q";
163                } else {
164                    $where .= " AND $field = $q";
165                }
166            }
167        }
168        $where .= ' AND GETACCESSLEVEL(pid) >= ' . AUTH_READ;
169
170        // group and order
171        if ($type === 'tag') {
172            $groupby = 'CLEANTAG(tag)';
173            $orderby = 'CLEANTAG(tag)';
174        } else {
175            $groupby = $type;
176            $orderby = "cnt DESC, $type";
177        }
178
179        // limit results
180        if ($limit) {
181            $limit = " LIMIT $limit";
182        } else {
183            $limit = '';
184        }
185
186        // create SQL
187        $sql = "SELECT $type AS item, COUNT(*) AS cnt
188                  FROM taggings
189                 WHERE $where
190              GROUP BY $groupby
191              ORDER BY $orderby
192                $limit
193              ";
194
195        // run query and turn into associative array
196        $res = $db->query($sql, array_values($filter));
197        $res = $db->res2arr($res);
198
199        $ret = array();
200        foreach ($res as $row) {
201            $ret[$row['item']] = $row['cnt'];
202        }
203
204        return $ret;
205    }
206
207    /**
208     * Check if the given string is a LIKE statement
209     *
210     * @param string $value
211     *
212     * @return bool
213     */
214    private function useLike($value) {
215        return strpos($value, '%') === 0 || strrpos($value, '%') === strlen($value) - 1;
216    }
217
218    /**
219     * Constructs the URL to search for a tag
220     *
221     * @param string $tag
222     * @param string $ns
223     *
224     * @return string
225     */
226    public function getTagSearchURL($tag, $ns = '') {
227        // wrap tag in quotes if non clean
228        $ctag = utf8_stripspecials($this->cleanTag($tag));
229        if ($ctag != utf8_strtolower($tag)) {
230            $tag = '"' . $tag . '"';
231        }
232
233        $ret = '?do=search&id=' . rawurlencode($tag);
234        if ($ns) {
235            $ret .= rawurlencode(' @' . $ns);
236        }
237
238        return $ret;
239    }
240
241    /**
242     * Calculates the size levels for the given list of clouds
243     *
244     * Automatically determines sensible tresholds
245     *
246     * @param array $tags list of tags => count
247     * @param int   $levels
248     *
249     * @return mixed
250     */
251    public function cloudData($tags, $levels = 10) {
252        $min = min($tags);
253        $max = max($tags);
254
255        // calculate tresholds
256        $tresholds = array();
257        for ($i = 0; $i <= $levels; $i++) {
258            $tresholds[$i] = pow($max - $min + 1, $i / $levels) + $min - 1;
259        }
260
261        // assign weights
262        foreach ($tags as $tag => $cnt) {
263            foreach ($tresholds as $tresh => $val) {
264                if ($cnt <= $val) {
265                    $tags[$tag] = $tresh;
266                    break;
267                }
268                $tags[$tag] = $levels;
269            }
270        }
271
272        return $tags;
273    }
274
275    /**
276     * Display a tag cloud
277     *
278     * @param array    $tags   list of tags => count
279     * @param string   $type   'tag'
280     * @param Callable $func   The function to print the link (gets tag and ns)
281     * @param bool     $wrap   wrap cloud in UL tags?
282     * @param bool     $return returnn HTML instead of printing?
283     * @param string   $ns     Add this namespace to search links
284     *
285     * @return string
286     */
287    public function html_cloud($tags, $type, $func, $wrap = true, $return = false, $ns = '') {
288        global $INFO;
289
290        $hidden_str = $this->getConf('hiddenprefix');
291        $hidden_len = strlen($hidden_str);
292
293        $ret = '';
294        if ($wrap) {
295            $ret .= '<ul class="tagging_cloud clearfix">';
296        }
297        if (count($tags) === 0) {
298            // Produce valid XHTML (ul needs a child)
299            $this->setupLocale();
300            $ret .= '<li><div class="li">' . $this->lang['js']['no' . $type . 's'] . '</div></li>';
301        } else {
302            $tags = $this->cloudData($tags);
303            foreach ($tags as $val => $size) {
304                // skip hidden tags for users that can't edit
305                if ($type === 'tag' and
306                    $hidden_len and
307                    substr($val, 0, $hidden_len) == $hidden_str and
308                    !($this->getUser() && $INFO['writable'])
309                ) {
310                    continue;
311                }
312
313                $ret .= '<li class="t' . $size . '"><div class="li">';
314                $ret .= call_user_func($func, $val, $ns);
315                $ret .= '</div></li>';
316            }
317        }
318        if ($wrap) {
319            $ret .= '</ul>';
320        }
321        if ($return) {
322            return $ret;
323        }
324        echo $ret;
325
326        return '';
327    }
328
329    /**
330     * Display a List of Page Links
331     *
332     * @param array    $pids   list of pids => count
333     * @return string
334     */
335    public function html_page_list($pids) {
336        $ret = '<div class="search_quickresult">';
337        $ret .= '<ul class="search_quickhits">';
338
339        if (count($pids) === 0) {
340            // Produce valid XHTML (ul needs a child)
341            $ret .= '<li><div class="li">' . $this->lang['js']['nopages'] . '</div></li>';
342        } else {
343            foreach (array_keys($pids) as $val) {
344                $ret .= '<li><div class="li">';
345                $ret .= html_wikilink($val);
346                $ret .= '</div></li>';
347            }
348        }
349
350        $ret .= '</ul>';
351        $ret .= '</div>';
352        $ret .= '<div class="clearer"></div>';
353
354        return $ret;
355    }
356
357    /**
358     * Get the link to a search for the given tag
359     *
360     * @param string $tag search for this tag
361     * @param string $ns  limit search to this namespace
362     *
363     * @return string
364     */
365    protected function linkToSearch($tag, $ns = '') {
366        return '<a href="' . hsc($this->getTagSearchURL($tag, $ns)) . '">' . $tag . '</a>';
367    }
368
369    /**
370     * Display the Tags for the current page and prepare the tag editing form
371     *
372     * @param bool $print Should the HTML be printed or returned?
373     *
374     * @return string
375     */
376    public function tpl_tags($print = true) {
377        global $INFO;
378        global $lang;
379
380        $filter = array('pid' => $INFO['id']);
381        if ($this->getConf('singleusermode')) {
382            $filter['tagger'] = 'auto';
383        }
384
385        $tags = $this->findItems($filter, 'tag');
386
387        $ret = '';
388
389        $ret .= '<div class="plugin_tagging_edit">';
390        $ret .= $this->html_cloud($tags, 'tag', array($this, 'linkToSearch'), true, true);
391
392        if ($this->getUser() && $INFO['writable']) {
393            $lang['btn_tagging_edit'] = $lang['btn_secedit'];
394            $ret .= '<div id="tagging__edit_buttons_group">';
395            $ret .= html_btn('tagging_edit', $INFO['id'], '', array());
396            if (auth_isadmin()) {
397                $ret .= '<label>' . $this->getLang('toggle admin mode') . '<input type="checkbox" id="tagging__edit_toggle_admin" /></label>';
398            }
399            $ret .= '</div>';
400            $form = new dokuwiki\Form\Form();
401            $form->id('tagging__edit');
402            $form->setHiddenField('tagging[id]', $INFO['id']);
403            $form->setHiddenField('call', 'plugin_tagging_save');
404            $tags = $this->findItems(array(
405                'pid'    => $INFO['id'],
406                'tagger' => $this->getUser(),
407            ), 'tag');
408            $form->addTextarea('tagging[tags]')->val(implode(', ', array_keys($tags)))->addClass('edit')->attr('rows', 4);
409            $form->addButton('', $lang['btn_save'])->id('tagging__edit_save');
410            $form->addButton('', $lang['btn_cancel'])->id('tagging__edit_cancel');
411            $ret .= $form->toHTML();
412        }
413        $ret .= '</div>';
414
415        if ($print) {
416            echo $ret;
417        }
418
419        return $ret;
420    }
421
422    /**
423     * @param string $namespace empty for entire wiki
424     *
425     * @return array
426     */
427    public function getAllTags($namespace = '', $order_by = 'tag', $desc = false) {
428        $order_fields = array('pid', 'tid', 'orig', 'taggers', 'count');
429        if (!in_array($order_by, $order_fields)) {
430            msg('cannot sort by ' . $order_by . ' field does not exists', -1);
431            $order_by = 'tag';
432        }
433
434        $db = $this->getDb();
435
436        $query = 'SELECT    "pid",
437                            CLEANTAG("tag") AS "tid",
438                            GROUP_SORT(GROUP_CONCAT("tag"), \', \') AS "orig",
439                            GROUP_SORT(GROUP_CONCAT("tagger"), \', \') AS "taggers",
440                            COUNT(*) AS "count"
441                        FROM "taggings"
442                        WHERE "pid" LIKE ?
443                        GROUP BY "tid"
444                        ORDER BY ' . $order_by;
445        if ($desc) {
446            $query .= ' DESC';
447        }
448
449        $res = $db->query($query, $this->globNamespace($namespace));
450
451        return $db->res2arr($res);
452    }
453
454    /**
455     * Get all pages with tags and their tags
456     *
457     * @return array ['pid' => ['tag1','tag2','tag3']]
458     */
459    public function getAllTagsByPage() {
460        $query = '
461        SELECT pid, GROUP_CONCAT(tag) AS tags
462        FROM taggings
463        GROUP BY pid
464        ';
465        $db = $this->getDb();
466        $res = $db->query($query);
467        return array_map(
468            function ($i) {
469                return explode(',', $i);
470            },
471            array_column($db->res2arr($res), 'tags', 'pid')
472        );
473    }
474
475    /**
476     * Renames a tag
477     *
478     * @param string $formerTagName
479     * @param string $newTagName
480     */
481    public function renameTag($formerTagName, $newTagName) {
482
483        if (empty($formerTagName) || empty($newTagName)) {
484            msg($this->getLang("admin enter tag names"), -1);
485
486            return;
487        }
488
489        $db = $this->getDb();
490
491        $res = $db->query('SELECT pid FROM taggings WHERE CLEANTAG(tag) = ?', $this->cleanTag($formerTagName));
492        $check = $db->res2arr($res);
493
494        if (empty($check)) {
495            msg($this->getLang("admin tag does not exists"), -1);
496
497            return;
498        }
499
500        $res = $db->query("UPDATE taggings SET tag = ? WHERE CLEANTAG(tag) = ?", $newTagName, $this->cleanTag($formerTagName));
501        $db->res2arr($res);
502
503        msg($this->getLang("admin renamed"), 1);
504
505        return;
506    }
507
508    /**
509     * Rename or delete a tag for all users
510     *
511     * @param string $pid
512     * @param string $formerTagName
513     * @param string $newTagName
514     *
515     * @return array
516     */
517    public function modifyPageTag($pid, $formerTagName, $newTagName) {
518
519        $db = $this->getDb();
520
521        $res = $db->query('SELECT pid FROM taggings WHERE CLEANTAG(tag) = ? AND pid = ?', $this->cleanTag($formerTagName), $pid);
522        $check = $db->res2arr($res);
523
524        if (empty($check)) {
525            return array(true, $this->getLang('admin tag does not exists'));
526        }
527
528        if (empty($newTagName)) {
529            $res = $db->query('DELETE FROM taggings WHERE pid = ? AND CLEANTAG(tag) = ?', $pid, $this->cleanTag($formerTagName));
530        } else {
531            $res = $db->query('UPDATE taggings SET tag = ? WHERE pid = ? AND CLEANTAG(tag) = ?', $newTagName, $pid, $this->cleanTag($formerTagName));
532        }
533        $db->res2arr($res);
534
535        return array(false, $this->getLang('admin renamed'));
536    }
537
538    /**
539     * Deletes a tag
540     *
541     * @param array  $tags
542     * @param string $namespace current namespace context as in getAllTags()
543     */
544    public function deleteTags($tags, $namespace = '') {
545        if (empty($tags)) {
546            return;
547        }
548
549        $namespace = cleanId($namespace);
550
551        $db = $this->getDB();
552
553        $queryBody = 'FROM taggings WHERE pid LIKE ? AND (' .
554            implode(' OR ', array_fill(0, count($tags), 'CLEANTAG(tag) = ?')) . ')';
555        $args = array_map(array($this, 'cleanTag'), $tags);
556        array_unshift($args, $this->globNamespace($namespace));
557
558
559        $affectedPagesQuery= 'SELECT DISTINCT pid ' . $queryBody;
560        $resAffectedPages = $db->query($affectedPagesQuery, $args);
561        $numAffectedPages = count($resAffectedPages->fetchAll());
562
563        $deleteQuery = 'DELETE ' . $queryBody;
564        $db->query($deleteQuery, $args);
565
566        msg(sprintf($this->getLang("admin deleted"), count($tags), $numAffectedPages), 1);
567    }
568}
569