xref: /plugin/tagging/helper.php (revision 204c069b8283f2494df9107ab62d37e45921a471)
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
115            if (substr($field,0,6) === 'notpid') {
116                $field = 'pid';
117
118                // detect LIKE filters
119                if($this->useLike($value)) {
120                    $where .= " AND $field NOT LIKE $q";
121                } else {
122                    $where .= " AND $field != $q";
123                }
124            } else {
125                // detect LIKE filters
126                if($this->useLike($value)) {
127                    $where .= " AND $field LIKE $q";
128                } else {
129                    $where .= " AND $field = $q";
130                }
131            }
132        }
133        // group and order
134        if($type == 'tag') {
135            $groupby = 'CLEANTAG(tag)';
136            $orderby = 'CLEANTAG(tag)';
137        } else {
138            $groupby = $type;
139            $orderby = "cnt DESC, $type";
140        }
141
142        // limit results
143        if($limit) {
144            $limit = " LIMIT $limit";
145        } else {
146            $limit = '';
147        }
148
149        // create SQL
150        $sql = "SELECT $type AS item, COUNT(*) AS cnt
151                  FROM taggings
152                 WHERE $where
153              GROUP BY $groupby
154              ORDER BY $orderby
155                $limit
156              ";
157
158        // run query and turn into associative array
159        $res = $db->query($sql, array_values($filter));
160        $res = $db->res2arr($res);
161
162        $ret = array();
163        foreach($res as $row) {
164            $ret[$row['item']] = $row['cnt'];
165        }
166        return $ret;
167    }
168
169    /**
170     * Check if the given string is a LIKE statement
171     *
172     * @param string $value
173     * @return bool
174     */
175    private function useLike($value) {
176        return strpos($value, '%') === 0 || strrpos($value, '%') === strlen($value) - 1;
177    }
178
179    /**
180     * Constructs the URL to search for a tag
181     *
182     * @param string $tag
183     * @param string $ns
184     * @return string
185     */
186    public function getTagSearchURL($tag, $ns = '') {
187        // wrap tag in quotes if non clean
188        $ctag = utf8_stripspecials($this->cleanTag($tag));
189        if($ctag != utf8_strtolower($tag)) $tag = '"' . $tag . '"';
190
191        $ret = '?do=search&id=' . rawurlencode($tag);
192        if($ns) $ret .= rawurlencode(' @' . $ns);
193
194        return $ret;
195    }
196
197    /**
198     * Calculates the size levels for the given list of clouds
199     *
200     * Automatically determines sensible tresholds
201     *
202     * @param array $tags list of tags => count
203     * @param int $levels
204     * @return mixed
205     */
206    public function cloudData($tags, $levels = 10) {
207        $min = min($tags);
208        $max = max($tags);
209
210        // calculate tresholds
211        $tresholds = array();
212        for($i = 0; $i <= $levels; $i++) {
213            $tresholds[$i] = pow($max - $min + 1, $i / $levels) + $min - 1;
214        }
215
216        // assign weights
217        foreach($tags as $tag => $cnt) {
218            foreach($tresholds as $tresh => $val) {
219                if($cnt <= $val) {
220                    $tags[$tag] = $tresh;
221                    break;
222                }
223                $tags[$tag] = $levels;
224            }
225        }
226        return $tags;
227    }
228
229    /**
230     * Display a tag cloud
231     *
232     * @param array $tags list of tags => count
233     * @param string $type 'tag'
234     * @param Callable $func The function to print the link (gets tag and ns)
235     * @param bool $wrap wrap cloud in UL tags?
236     * @param bool $return returnn HTML instead of printing?
237     * @param string $ns Add this namespace to search links
238     * @return string
239     */
240    public function html_cloud($tags, $type, $func, $wrap = true, $return = false, $ns = '') {
241        global $INFO;
242
243        $hidden_str = $this->getConf('hiddenprefix');
244        $hidden_len = strlen($hidden_str);
245
246        $ret = '';
247        if($wrap) $ret .= '<ul class="tagging_cloud clearfix">';
248        if(count($tags) === 0) {
249            // Produce valid XHTML (ul needs a child)
250            $this->setupLocale();
251            $ret .= '<li><div class="li">' . $this->lang['js']['no' . $type . 's'] . '</div></li>';
252        } else {
253            $tags = $this->cloudData($tags);
254            foreach($tags as $val => $size) {
255                // skip hidden tags for users that can't edit
256                if($type == 'tag' and
257                    $hidden_len and
258                    substr($val, 0, $hidden_len) == $hidden_str and
259                    !($this->getUser() && $INFO['writable'])
260                ) {
261                    continue;
262                }
263
264                $ret .= '<li class="t' . $size . '"><div class="li">';
265                $ret .= call_user_func($func, $val, $ns);
266                $ret .= '</div></li>';
267            }
268        }
269        if($wrap) $ret .= '</ul>';
270        if($return) return $ret;
271        echo $ret;
272        return '';
273    }
274
275    /**
276     * Get the link to a search for the given tag
277     *
278     * @param string $tag search for this tag
279     * @param string $ns limit search to this namespace
280     * @return string
281     */
282    protected function linkToSearch($tag, $ns = '') {
283        return '<a href="' . hsc($this->getTagSearchURL($tag, $ns)) . '">' . $tag . '</a>';
284    }
285
286    /**
287     * Display the Tags for the current page and prepare the tag editing form
288     *
289     * @param bool $print Should the HTML be printed or returned?
290     * @return string
291     */
292    public function tpl_tags($print = true) {
293        global $INFO;
294        global $lang;
295        $tags = $this->findItems(array('pid' => $INFO['id']), 'tag');
296
297        $ret = '';
298
299        $ret .= '<div class="plugin_tagging_edit">';
300        $ret .= $this->html_cloud($tags, 'tag', array($this, 'linkToSearch'), true, true);
301
302        if($this->getUser() && $INFO['writable']) {
303            $lang['btn_tagging_edit'] = $lang['btn_secedit'];
304            $ret .= html_btn('tagging_edit', $INFO['id'], '', array());
305            $form = new Doku_Form(array('id' => 'tagging__edit'));
306            $form->addHidden('tagging[id]', $INFO['id']);
307            $form->addHidden('call', 'plugin_tagging_save');
308            $form->addElement(form_makeTextField('tagging[tags]', implode(', ', array_keys($this->findItems(array('pid' => $INFO['id'], 'tagger' => $this->getUser()), 'tag')))));
309            $form->addElement(form_makeButton('submit', 'save', $lang['btn_save'], array('id' => 'tagging__edit_save')));
310            $form->addElement(form_makeButton('submit', 'cancel', $lang['btn_cancel'], array('id' => 'tagging__edit_cancel')));
311            $ret .= $form->getForm();
312        }
313        $ret .= '</div>';
314
315        if($print) echo $ret;
316        return $ret;
317    }
318
319    /**
320     * @return array
321     */
322    public function getAllTags() {
323
324        $db  = $this->getDb();
325        $res = $db->query('SELECT pid, tag, tagger FROM taggings ORDER BY tag');
326
327        $tags_tmp = $db->res2arr($res);
328        $tags     = array();
329        foreach($tags_tmp as $tag) {
330            $tid = $this->cleanTag($tag['tag']);
331
332            if(!isset($tags[$tid]['orig'])) $tags[$tid]['orig'] = array();
333            $tags[$tid]['orig'][] = $tag['tag'];
334
335            if(isset($tags[$tid]['count'])) {
336                $tags[$tid]['count']++;
337                $tags[$tid]['tagger'][] = $tag['tagger'];
338            } else {
339                $tags[$tid]['count']  = 1;
340                $tags[$tid]['tagger'] = array($tag['tagger']);
341            }
342        }
343        return $tags;
344    }
345
346    /**
347     * Renames a tag
348     *
349     * @param string $formerTagName
350     * @param string $newTagName
351     */
352    public function renameTag($formerTagName, $newTagName) {
353
354        if(empty($formerTagName) || empty($newTagName)) {
355            msg($this->getLang("admin enter tag names"), -1);
356            return;
357        }
358
359        $db = $this->getDb();
360
361        $res   = $db->query('SELECT pid FROM taggings WHERE CLEANTAG(tag) = ?', $this->cleanTag($formerTagName));
362        $check = $db->res2arr($res);
363
364        if(empty($check)) {
365            msg($this->getLang("admin tag does not exists"), -1);
366            return;
367        }
368
369        $res = $db->query("UPDATE taggings SET tag = ? WHERE CLEANTAG(tag) = ?", $newTagName, $this->cleanTag($formerTagName));
370        $db->res2arr($res);
371
372        msg($this->getLang("admin renamed"), 1);
373        return;
374    }
375
376}
377