xref: /plugin/tagging/helper.php (revision 3496cc8a340142b071d9dbd955e2ad094fbea0a8)
1<?php
2
3if(!defined('DOKU_INC')) die();
4
5class helper_plugin_tagging extends DokuWiki_Plugin {
6
7    /**
8     * Gives access to the database
9     *
10     * Initializes the SQLite helper and register the CLEANTAG function
11     *
12     * @return helper_plugin_sqlite|bool false if initialization fails
13     */
14    public function getDB() {
15        static $db = null;
16        if(!is_null($db)) {
17            return $db;
18        }
19
20        /** @var helper_plugin_sqlite $db */
21        $db = plugin_load('helper', 'sqlite');
22        if(is_null($db)) {
23            msg('The tagging plugin needs the sqlite plugin', -1);
24            return false;
25        }
26        $db->init('tagging', dirname(__FILE__) . '/db/');
27        $db->create_function('CLEANTAG', array($this, 'cleanTag'), 1);
28        return $db;
29    }
30
31    /**
32     * Return the user to use for accessing tags
33     *
34     * Handles the singleuser mode by returning 'auto' as user. Returnes false when no user is logged in.
35     *
36     * @return bool|string
37     */
38    public function getUser() {
39        if(!isset($_SERVER['REMOTE_USER'])) return false;
40        if($this->getConf('singleusermode')) return 'auto';
41        return $_SERVER['REMOTE_USER'];
42    }
43
44    /**
45     * Canonicalizes the tag to its lower case nospace form
46     *
47     * @param $tag
48     * @return string
49     */
50    public function cleanTag($tag) {
51        $tag = str_replace(' ', '', $tag);
52        $tag = utf8_strtolower($tag);
53        return $tag;
54    }
55
56    /**
57     * Create or Update tags of a page
58     *
59     * Uses the translation plugin to store the language of a page (if available)
60     *
61     * @param string $id The page ID
62     * @param string $user
63     * @param array $tags
64     * @return bool|SQLiteResult
65     */
66    public function replaceTags($id, $user, $tags) {
67        global $conf;
68        /** @var helper_plugin_translation $trans */
69        $trans = plugin_load('helper', 'translation');
70        if($trans) {
71            $lang = $trans->realLC($trans->getLangPart($id));
72        } else {
73            $lang = $conf['lang'];
74        }
75
76        $db = $this->getDB();
77        $db->query('BEGIN TRANSACTION');
78        $queries = array(array('DELETE FROM taggings WHERE pid = ? AND tagger = ?', $id, $user));
79        foreach($tags as $tag) {
80            $queries[] = array('INSERT INTO taggings (pid, tagger, tag, lang) VALUES(?, ?, ?, ?)', $id, $user, $tag, $lang);
81        }
82
83        foreach($queries as $query) {
84            if(!call_user_func_array(array($db, 'query'), $query)) {
85                $db->query('ROLLBACK TRANSACTION');
86                return false;
87            }
88        }
89        return $db->query('COMMIT TRANSACTION');
90    }
91
92    /**
93     * Get a list of Tags or Pages matching search criteria
94     *
95     * @param array $filter What to search for array('field' => 'searchterm')
96     * @param string $type What field to return 'tag'|'pid'
97     * @param int $limit Limit to this many results, 0 for all
98     * @return array associative array in form of value => count
99     */
100    public function findItems($filter, $type, $limit = 0) {
101        $db = $this->getDB();
102        if(!$db) return array();
103
104        // create WHERE clause
105        $where = '1=1';
106        foreach($filter as $field => $value) {
107            // compare clean tags only
108            if($field === 'tag') {
109                $field = 'CLEANTAG(tag)';
110                $q     = 'CLEANTAG(?)';
111            } else {
112                $q = '?';
113            }
114            // detect LIKE filters
115            if($this->useLike($value)) {
116                $where .= " AND $field LIKE $q";
117            } else {
118                $where .= " AND $field = $q";
119            }
120        }
121        // group and order
122        if($type == 'tag') {
123            $groupby = 'CLEANTAG(tag)';
124            $orderby = 'CLEANTAG(tag)';
125        } else {
126            $groupby = $type;
127            $orderby = "cnt DESC, $type";
128        }
129
130        // limit results
131        if($limit) {
132            $limit = " LIMIT $limit";
133        } else {
134            $limit = '';
135        }
136
137        // create SQL
138        $sql = "SELECT $type AS item, COUNT(*) AS cnt
139                  FROM taggings
140                 WHERE $where
141              GROUP BY $groupby
142              ORDER BY $orderby
143                $limit
144              ";
145
146        // run query and turn into associative array
147        $res = $db->query($sql, array_values($filter));
148        $res = $db->res2arr($res);
149
150        $ret = array();
151        foreach($res as $row) {
152            $ret[$row['item']] = $row['cnt'];
153        }
154        return $ret;
155    }
156
157    /**
158     * Check if the given string is a LIKE statement
159     *
160     * @param string $value
161     * @return bool
162     */
163    private function useLike($value) {
164        return strpos($value, '%') === 0 || strrpos($value, '%') === strlen($value) - 1;
165    }
166
167    /**
168     * Constructs the URL to search for a tag
169     *
170     * @param string $tag
171     * @param string $ns
172     * @return string
173     */
174    public function getTagSearchURL($tag, $ns = '') {
175        // wrap tag in quotes if non clean
176        $ctag = utf8_stripspecials($this->cleanTag($tag));
177        if($ctag != utf8_strtolower($tag)) $tag = '"' . $tag . '"';
178
179        $ret = '?do=search&id=' . rawurlencode($tag);
180        if($ns) $ret .= rawurlencode(' @' . $ns);
181
182        return $ret;
183    }
184
185    /**
186     * Calculates the size levels for the given list of clouds
187     *
188     * Automatically determines sensible tresholds
189     *
190     * @param array $tags list of tags => count
191     * @param int $levels
192     * @return mixed
193     */
194    public function cloudData($tags, $levels = 10) {
195        $min = min($tags);
196        $max = max($tags);
197
198        // calculate tresholds
199        $tresholds = array();
200        for($i = 0; $i <= $levels; $i++) {
201            $tresholds[$i] = pow($max - $min + 1, $i / $levels) + $min - 1;
202        }
203
204        // assign weights
205        foreach($tags as $tag => $cnt) {
206            foreach($tresholds as $tresh => $val) {
207                if($cnt <= $val) {
208                    $tags[$tag] = $tresh;
209                    break;
210                }
211                $tags[$tag] = $levels;
212            }
213        }
214        return $tags;
215    }
216
217    /**
218     * Display a tag cloud
219     *
220     * @param array $tags list of tags => count
221     * @param string $type 'tag'
222     * @param Callable $func The function to print the link (gets tag and ns)
223     * @param bool $wrap wrap cloud in UL tags?
224     * @param bool $return returnn HTML instead of printing?
225     * @param string $ns Add this namespace to search links
226     * @return string
227     */
228    public function html_cloud($tags, $type, $func, $wrap = true, $return = false, $ns = '') {
229        global $INFO;
230
231        $hidden_str = $this->getConf('hiddenprefix');
232        $hidden_len = strlen($hidden_str);
233
234        $ret = '';
235        if($wrap) $ret .= '<ul class="tagging_cloud clearfix">';
236        if(count($tags) === 0) {
237            // Produce valid XHTML (ul needs a child)
238            $this->setupLocale();
239            $ret .= '<li><div class="li">' . $this->lang['js']['no' . $type . 's'] . '</div></li>';
240        } else {
241            $tags = $this->cloudData($tags);
242            foreach($tags as $val => $size) {
243                // skip hidden tags for users that can't edit
244                if($type == 'tag' and
245                    $hidden_len and
246                    substr($val, 0, $hidden_len) == $hidden_str and
247                    !($this->getUser() && $INFO['writable'])
248                ) {
249                    continue;
250                }
251
252                $ret .= '<li class="t' . $size . '"><div class="li">';
253                $ret .= call_user_func($func, $val, $ns);
254                $ret .= '</div></li>';
255            }
256        }
257        if($wrap) $ret .= '</ul>';
258        if($return) return $ret;
259        echo $ret;
260        return '';
261    }
262
263    /**
264     * Get the link to a search for the given tag
265     *
266     * @param string $tag search for this tag
267     * @param string $ns limit search to this namespace
268     * @return string
269     */
270    protected function linkToSearch($tag, $ns = '') {
271        return '<a href="' . hsc($this->getTagSearchURL($tag, $ns)) . '">' . $tag . '</a>';
272    }
273
274    /**
275     * Display the Tags for the current page and prepare the tag editing form
276     *
277     * @param bool $print Should the HTML be printed or returned?
278     * @return string
279     */
280    public function tpl_tags($print = true) {
281        global $INFO;
282        global $lang;
283        $tags = $this->findItems(array('pid' => $INFO['id']), 'tag');
284
285        $ret = '';
286
287        $ret .= '<div class="plugin_tagging_edit">';
288        $ret .= $this->html_cloud($tags, 'tag', array($this, 'linkToSearch'), true, true);
289
290        if($this->getUser() && $INFO['writable']) {
291            $lang['btn_tagging_edit'] = $lang['btn_secedit'];
292            $ret .= html_btn('tagging_edit', $INFO['id'], '', array());
293            $form = new Doku_Form(array('id' => 'tagging__edit'));
294            $form->addHidden('tagging[id]', $INFO['id']);
295            $form->addHidden('call', 'plugin_tagging_save');
296            $form->addElement(form_makeTextField('tagging[tags]', implode(', ', array_keys($this->findItems(array('pid' => $INFO['id'], 'tagger' => $this->getUser()), 'tag')))));
297            $form->addElement(form_makeButton('submit', 'save', $lang['btn_save'], array('id' => 'tagging__edit_save')));
298            $form->addElement(form_makeButton('submit', 'cancel', $lang['btn_cancel'], array('id' => 'tagging__edit_cancel')));
299            $ret .= $form->getForm();
300        }
301        $ret .= '</div>';
302
303        if($print) echo $ret;
304        return $ret;
305    }
306
307    /**
308     * @return array
309     */
310    public function getAllTags() {
311
312        $db  = $this->getDb();
313        $res = $db->query('SELECT pid, tag, tagger FROM taggings ORDER BY tag');
314
315        $tags_tmp = $db->res2arr($res);
316        $tags     = array();
317        foreach($tags_tmp as $tag) {
318            $tid = $this->cleanTag($tag['tag']);
319
320            if(!isset($tags[$tid]['orig'])) $tags[$tid]['orig'] = array();
321            $tags[$tid]['orig'][] = $tag['tag'];
322
323            if(isset($tags[$tid]['count'])) {
324                $tags[$tid]['count']++;
325                $tags[$tid]['tagger'][] = $tag['tagger'];
326            } else {
327                $tags[$tid]['count']  = 1;
328                $tags[$tid]['tagger'] = array($tag['tagger']);
329            }
330        }
331        return $tags;
332    }
333
334    /**
335     * Renames a tag
336     *
337     * @param string $formerTagName
338     * @param string $newTagName
339     */
340    public function renameTag($formerTagName, $newTagName) {
341
342        if(empty($formerTagName) || empty($newTagName)) {
343            msg($this->getLang("admin enter tag names"), -1);
344            return;
345        }
346
347        $db = $this->getDb();
348
349        $res   = $db->query('SELECT pid FROM taggings WHERE CLEANTAG(tag) = ?', $this->cleanTag($formerTagName));
350        $check = $db->res2arr($res);
351
352        if(empty($check)) {
353            msg($this->getLang("admin tag does not exists"), -1);
354            return;
355        }
356
357        $res = $db->query("UPDATE taggings SET tag = ? WHERE CLEANTAG(tag) = ?", $newTagName, $this->cleanTag($formerTagName));
358        $db->res2arr($res);
359
360        msg($this->getLang("admin renamed"), 1);
361        return;
362    }
363
364}
365