xref: /plugin/tagging/helper.php (revision 59cd4311f7d53edb162642d462a695727af21e1e)
1f61105deSAdrian Lang<?php
2f61105deSAdrian Lang
3f61105deSAdrian Langif(!defined('DOKU_INC')) die();
43496cc8aSAndreas Gohr
5e4543b6dSAdrian Langclass helper_plugin_tagging extends DokuWiki_Plugin {
6f61105deSAdrian Lang
7289f50bdSAndreas Gohr    /**
8b12334e1SAndreas Gohr     * Gives access to the database
9b12334e1SAndreas Gohr     *
10b12334e1SAndreas Gohr     * Initializes the SQLite helper and register the CLEANTAG function
11b12334e1SAndreas Gohr     *
12b12334e1SAndreas Gohr     * @return helper_plugin_sqlite|bool false if initialization fails
13289f50bdSAndreas Gohr     */
14289f50bdSAndreas Gohr    public function getDB() {
15302a38efSAndreas Gohr        static $db = null;
16f61105deSAdrian Lang        if(!is_null($db)) {
17f61105deSAdrian Lang            return $db;
18f61105deSAdrian Lang        }
19f61105deSAdrian Lang
20302a38efSAndreas Gohr        /** @var helper_plugin_sqlite $db */
21f61105deSAdrian Lang        $db = plugin_load('helper', 'sqlite');
22f61105deSAdrian Lang        if(is_null($db)) {
23f61105deSAdrian Lang            msg('The tagging plugin needs the sqlite plugin', -1);
24f61105deSAdrian Lang            return false;
25f61105deSAdrian Lang        }
267e6afce6SAndreas Gohr        $db->init('tagging', dirname(__FILE__) . '/db/');
27302a38efSAndreas Gohr        $db->create_function('CLEANTAG', array($this, 'cleanTag'), 1);
28f61105deSAdrian Lang        return $db;
29f61105deSAdrian Lang    }
30f61105deSAdrian Lang
31302a38efSAndreas Gohr    /**
322ace74f4SAndreas Gohr     * Return the user to use for accessing tags
332ace74f4SAndreas Gohr     *
342ace74f4SAndreas Gohr     * Handles the singleuser mode by returning 'auto' as user. Returnes false when no user is logged in.
352ace74f4SAndreas Gohr     *
362ace74f4SAndreas Gohr     * @return bool|string
372ace74f4SAndreas Gohr     */
382ace74f4SAndreas Gohr    public function getUser() {
392ace74f4SAndreas Gohr        if(!isset($_SERVER['REMOTE_USER'])) return false;
402ace74f4SAndreas Gohr        if($this->getConf('singleusermode')) return 'auto';
412ace74f4SAndreas Gohr        return $_SERVER['REMOTE_USER'];
422ace74f4SAndreas Gohr    }
432ace74f4SAndreas Gohr
442ace74f4SAndreas Gohr    /**
45302a38efSAndreas Gohr     * Canonicalizes the tag to its lower case nospace form
46302a38efSAndreas Gohr     *
47302a38efSAndreas Gohr     * @param $tag
48302a38efSAndreas Gohr     * @return string
49302a38efSAndreas Gohr     */
50302a38efSAndreas Gohr    public function cleanTag($tag) {
51302a38efSAndreas Gohr        $tag = str_replace(' ', '', $tag);
52302a38efSAndreas Gohr        $tag = utf8_strtolower($tag);
53302a38efSAndreas Gohr        return $tag;
54302a38efSAndreas Gohr    }
55302a38efSAndreas Gohr
5656d82720SAndreas Gohr    /**
5756d82720SAndreas Gohr     * Create or Update tags of a page
5856d82720SAndreas Gohr     *
5956d82720SAndreas Gohr     * Uses the translation plugin to store the language of a page (if available)
6056d82720SAndreas Gohr     *
6156d82720SAndreas Gohr     * @param string $id The page ID
6256d82720SAndreas Gohr     * @param string $user
6356d82720SAndreas Gohr     * @param array $tags
6456d82720SAndreas Gohr     * @return bool|SQLiteResult
6556d82720SAndreas Gohr     */
66f61105deSAdrian Lang    public function replaceTags($id, $user, $tags) {
6756d82720SAndreas Gohr        global $conf;
6856d82720SAndreas Gohr        /** @var helper_plugin_translation $trans */
6956d82720SAndreas Gohr        $trans = plugin_load('helper', 'translation');
7056d82720SAndreas Gohr        if($trans) {
7156d82720SAndreas Gohr            $lang = $trans->realLC($trans->getLangPart($id));
7256d82720SAndreas Gohr        } else {
7356d82720SAndreas Gohr            $lang = $conf['lang'];
7456d82720SAndreas Gohr        }
7556d82720SAndreas Gohr
76f61105deSAdrian Lang        $db = $this->getDB();
77f61105deSAdrian Lang        $db->query('BEGIN TRANSACTION');
78f61105deSAdrian Lang        $queries = array(array('DELETE FROM taggings WHERE pid = ? AND tagger = ?', $id, $user));
79f61105deSAdrian Lang        foreach($tags as $tag) {
8056d82720SAndreas Gohr            $queries[] = array('INSERT INTO taggings (pid, tagger, tag, lang) VALUES(?, ?, ?, ?)', $id, $user, $tag, $lang);
81f61105deSAdrian Lang        }
82f61105deSAdrian Lang
83f61105deSAdrian Lang        foreach($queries as $query) {
84f61105deSAdrian Lang            if(!call_user_func_array(array($db, 'query'), $query)) {
85f61105deSAdrian Lang                $db->query('ROLLBACK TRANSACTION');
86f61105deSAdrian Lang                return false;
87f61105deSAdrian Lang            }
88f61105deSAdrian Lang        }
89f61105deSAdrian Lang        return $db->query('COMMIT TRANSACTION');
90f61105deSAdrian Lang    }
91f61105deSAdrian Lang
920a518a11SAndreas Gohr    /**
93b12334e1SAndreas Gohr     * Get a list of Tags or Pages matching search criteria
940a518a11SAndreas Gohr     *
95b12334e1SAndreas Gohr     * @param array $filter What to search for array('field' => 'searchterm')
96b12334e1SAndreas Gohr     * @param string $type What field to return 'tag'|'pid'
97077ff864SAndreas Gohr     * @param int $limit Limit to this many results, 0 for all
980a518a11SAndreas Gohr     * @return array associative array in form of value => count
990a518a11SAndreas Gohr     */
100077ff864SAndreas Gohr    public function findItems($filter, $type, $limit = 0) {
101f61105deSAdrian Lang        $db = $this->getDB();
102b12334e1SAndreas Gohr        if(!$db) return array();
103f61105deSAdrian Lang
104b12334e1SAndreas Gohr        // create WHERE clause
105b12334e1SAndreas Gohr        $where = '1=1';
106b12334e1SAndreas Gohr        foreach($filter as $field => $value) {
107b12334e1SAndreas Gohr            // compare clean tags only
108b12334e1SAndreas Gohr            if($field === 'tag') {
109b12334e1SAndreas Gohr                $field = 'CLEANTAG(tag)';
110b12334e1SAndreas Gohr                $q     = 'CLEANTAG(?)';
111b12334e1SAndreas Gohr            } else {
112b12334e1SAndreas Gohr                $q = '?';
113b12334e1SAndreas Gohr            }
114204c069bSMichael Große
115204c069bSMichael Große            if (substr($field,0,6) === 'notpid') {
116204c069bSMichael Große                $field = 'pid';
117204c069bSMichael Große
118204c069bSMichael Große                // detect LIKE filters
119204c069bSMichael Große                if($this->useLike($value)) {
120204c069bSMichael Große                    $where .= " AND $field NOT LIKE $q";
121204c069bSMichael Große                } else {
122204c069bSMichael Große                    $where .= " AND $field != $q";
123204c069bSMichael Große                }
124204c069bSMichael Große            } else {
125b12334e1SAndreas Gohr                // detect LIKE filters
126b12334e1SAndreas Gohr                if($this->useLike($value)) {
127b12334e1SAndreas Gohr                    $where .= " AND $field LIKE $q";
128b12334e1SAndreas Gohr                } else {
129b12334e1SAndreas Gohr                    $where .= " AND $field = $q";
130b12334e1SAndreas Gohr                }
131b12334e1SAndreas Gohr            }
132204c069bSMichael Große        }
133b12334e1SAndreas Gohr        // group and order
134b12334e1SAndreas Gohr        if($type == 'tag') {
135b12334e1SAndreas Gohr            $groupby = 'CLEANTAG(tag)';
136b12334e1SAndreas Gohr            $orderby = 'CLEANTAG(tag)';
137b12334e1SAndreas Gohr        } else {
138b12334e1SAndreas Gohr            $groupby = $type;
139466524f5SAndreas Gohr            $orderby = "cnt DESC, $type";
140b12334e1SAndreas Gohr        }
141b12334e1SAndreas Gohr
142077ff864SAndreas Gohr        // limit results
143077ff864SAndreas Gohr        if($limit) {
144077ff864SAndreas Gohr            $limit = " LIMIT $limit";
145077ff864SAndreas Gohr        } else {
146077ff864SAndreas Gohr            $limit = '';
147077ff864SAndreas Gohr        }
148077ff864SAndreas Gohr
149b12334e1SAndreas Gohr        // create SQL
150b12334e1SAndreas Gohr        $sql = "SELECT $type AS item, COUNT(*) AS cnt
151b12334e1SAndreas Gohr                  FROM taggings
152b12334e1SAndreas Gohr                 WHERE $where
153b12334e1SAndreas Gohr              GROUP BY $groupby
154077ff864SAndreas Gohr              ORDER BY $orderby
155077ff864SAndreas Gohr                $limit
156077ff864SAndreas Gohr              ";
157b12334e1SAndreas Gohr
158b12334e1SAndreas Gohr        // run query and turn into associative array
159b12334e1SAndreas Gohr        $res = $db->query($sql, array_values($filter));
160f61105deSAdrian Lang        $res = $db->res2arr($res);
161b12334e1SAndreas Gohr
162f61105deSAdrian Lang        $ret = array();
163b12334e1SAndreas Gohr        foreach($res as $row) {
164*59cd4311SPPPCR            if (!isHiddenPage($row['item']) && auth_quickaclcheck($row['item']) >= AUTH_READ) {
165b12334e1SAndreas Gohr                $ret[$row['item']] = $row['cnt'];
166f61105deSAdrian Lang            }
167*59cd4311SPPPCR        }
168f61105deSAdrian Lang        return $ret;
169f61105deSAdrian Lang    }
170f61105deSAdrian Lang
171b12334e1SAndreas Gohr    /**
172b12334e1SAndreas Gohr     * Check if the given string is a LIKE statement
173b12334e1SAndreas Gohr     *
174b12334e1SAndreas Gohr     * @param string $value
175b12334e1SAndreas Gohr     * @return bool
176b12334e1SAndreas Gohr     */
177b12334e1SAndreas Gohr    private function useLike($value) {
178b12334e1SAndreas Gohr        return strpos($value, '%') === 0 || strrpos($value, '%') === strlen($value) - 1;
179b2073787SDominik Eckelmann    }
180b2073787SDominik Eckelmann
181302a38efSAndreas Gohr    /**
182302a38efSAndreas Gohr     * Constructs the URL to search for a tag
183302a38efSAndreas Gohr     *
1845540f91dSAndreas Gohr     * @param string $tag
1855540f91dSAndreas Gohr     * @param string $ns
186302a38efSAndreas Gohr     * @return string
187302a38efSAndreas Gohr     */
1885540f91dSAndreas Gohr    public function getTagSearchURL($tag, $ns = '') {
189bed9f360SAndreas Gohr        // wrap tag in quotes if non clean
1902cb25ec1SAndreas Gohr        $ctag = utf8_stripspecials($this->cleanTag($tag));
191bed9f360SAndreas Gohr        if($ctag != utf8_strtolower($tag)) $tag = '"' . $tag . '"';
192bed9f360SAndreas Gohr
193bed9f360SAndreas Gohr        $ret = '?do=search&id=' . rawurlencode($tag);
1945540f91dSAndreas Gohr        if($ns) $ret .= rawurlencode(' @' . $ns);
1955540f91dSAndreas Gohr
1965540f91dSAndreas Gohr        return $ret;
197f61105deSAdrian Lang    }
198f61105deSAdrian Lang
1995540f91dSAndreas Gohr    /**
2005540f91dSAndreas Gohr     * Calculates the size levels for the given list of clouds
2015540f91dSAndreas Gohr     *
2025540f91dSAndreas Gohr     * Automatically determines sensible tresholds
2035540f91dSAndreas Gohr     *
2045540f91dSAndreas Gohr     * @param array $tags list of tags => count
2055540f91dSAndreas Gohr     * @param int $levels
2065540f91dSAndreas Gohr     * @return mixed
2075540f91dSAndreas Gohr     */
208f61105deSAdrian Lang    public function cloudData($tags, $levels = 10) {
209f61105deSAdrian Lang        $min = min($tags);
210f61105deSAdrian Lang        $max = max($tags);
211f61105deSAdrian Lang
212f61105deSAdrian Lang        // calculate tresholds
213f61105deSAdrian Lang        $tresholds = array();
214f61105deSAdrian Lang        for($i = 0; $i <= $levels; $i++) {
215f61105deSAdrian Lang            $tresholds[$i] = pow($max - $min + 1, $i / $levels) + $min - 1;
216f61105deSAdrian Lang        }
217f61105deSAdrian Lang
218f61105deSAdrian Lang        // assign weights
219f61105deSAdrian Lang        foreach($tags as $tag => $cnt) {
220f61105deSAdrian Lang            foreach($tresholds as $tresh => $val) {
221f61105deSAdrian Lang                if($cnt <= $val) {
222f61105deSAdrian Lang                    $tags[$tag] = $tresh;
223f61105deSAdrian Lang                    break;
224f61105deSAdrian Lang                }
225f61105deSAdrian Lang                $tags[$tag] = $levels;
226f61105deSAdrian Lang            }
227f61105deSAdrian Lang        }
228f61105deSAdrian Lang        return $tags;
229f61105deSAdrian Lang    }
230f61105deSAdrian Lang
2315540f91dSAndreas Gohr    /**
2325540f91dSAndreas Gohr     * Display a tag cloud
2335540f91dSAndreas Gohr     *
2345540f91dSAndreas Gohr     * @param array $tags list of tags => count
2355540f91dSAndreas Gohr     * @param string $type 'tag'
2365540f91dSAndreas Gohr     * @param Callable $func The function to print the link (gets tag and ns)
2375540f91dSAndreas Gohr     * @param bool $wrap wrap cloud in UL tags?
2385540f91dSAndreas Gohr     * @param bool $return returnn HTML instead of printing?
2395540f91dSAndreas Gohr     * @param string $ns Add this namespace to search links
2405540f91dSAndreas Gohr     * @return string
2415540f91dSAndreas Gohr     */
2425540f91dSAndreas Gohr    public function html_cloud($tags, $type, $func, $wrap = true, $return = false, $ns = '') {
243a66f6715SAndreas Gohr        global $INFO;
244a66f6715SAndreas Gohr
245a66f6715SAndreas Gohr        $hidden_str = $this->getConf('hiddenprefix');
246a66f6715SAndreas Gohr        $hidden_len = strlen($hidden_str);
247a66f6715SAndreas Gohr
248f61105deSAdrian Lang        $ret = '';
2490dbdc3fcSAdrian Lang        if($wrap) $ret .= '<ul class="tagging_cloud clearfix">';
250f61105deSAdrian Lang        if(count($tags) === 0) {
251f61105deSAdrian Lang            // Produce valid XHTML (ul needs a child)
252f61105deSAdrian Lang            $this->setupLocale();
253f61105deSAdrian Lang            $ret .= '<li><div class="li">' . $this->lang['js']['no' . $type . 's'] . '</div></li>';
254f61105deSAdrian Lang        } else {
255f61105deSAdrian Lang            $tags = $this->cloudData($tags);
256f61105deSAdrian Lang            foreach($tags as $val => $size) {
257a66f6715SAndreas Gohr                // skip hidden tags for users that can't edit
258a66f6715SAndreas Gohr                if($type == 'tag' and
259a66f6715SAndreas Gohr                    $hidden_len and
260a66f6715SAndreas Gohr                    substr($val, 0, $hidden_len) == $hidden_str and
261a66f6715SAndreas Gohr                    !($this->getUser() && $INFO['writable'])
262a66f6715SAndreas Gohr                ) {
263a66f6715SAndreas Gohr                    continue;
264a66f6715SAndreas Gohr                }
265a66f6715SAndreas Gohr
266f61105deSAdrian Lang                $ret .= '<li class="t' . $size . '"><div class="li">';
2675540f91dSAndreas Gohr                $ret .= call_user_func($func, $val, $ns);
268f61105deSAdrian Lang                $ret .= '</div></li>';
269f61105deSAdrian Lang            }
270f61105deSAdrian Lang        }
271f61105deSAdrian Lang        if($wrap) $ret .= '</ul>';
272f61105deSAdrian Lang        if($return) return $ret;
273f61105deSAdrian Lang        echo $ret;
2745540f91dSAndreas Gohr        return '';
275f61105deSAdrian Lang    }
276f61105deSAdrian Lang
2775540f91dSAndreas Gohr    /**
2785540f91dSAndreas Gohr     * Get the link to a search for the given tag
2795540f91dSAndreas Gohr     *
2805540f91dSAndreas Gohr     * @param string $tag search for this tag
2815540f91dSAndreas Gohr     * @param string $ns limit search to this namespace
2825540f91dSAndreas Gohr     * @return string
2835540f91dSAndreas Gohr     */
2845540f91dSAndreas Gohr    protected function linkToSearch($tag, $ns = '') {
2855540f91dSAndreas Gohr        return '<a href="' . hsc($this->getTagSearchURL($tag, $ns)) . '">' . $tag . '</a>';
286f61105deSAdrian Lang    }
287f61105deSAdrian Lang
288fb1d0583SAndreas Gohr    /**
289fb1d0583SAndreas Gohr     * Display the Tags for the current page and prepare the tag editing form
2903496cc8aSAndreas Gohr     *
2913496cc8aSAndreas Gohr     * @param bool $print Should the HTML be printed or returned?
2923496cc8aSAndreas Gohr     * @return string
293fb1d0583SAndreas Gohr     */
2943496cc8aSAndreas Gohr    public function tpl_tags($print = true) {
295f61105deSAdrian Lang        global $INFO;
296f61105deSAdrian Lang        global $lang;
297fbf38c5bSAndreas Gohr        $tags = $this->findItems(array('pid' => $INFO['id']), 'tag');
2983496cc8aSAndreas Gohr
2993496cc8aSAndreas Gohr        $ret = '';
3003496cc8aSAndreas Gohr
3013496cc8aSAndreas Gohr        $ret .= '<div class="plugin_tagging_edit">';
3023496cc8aSAndreas Gohr        $ret .= $this->html_cloud($tags, 'tag', array($this, 'linkToSearch'), true, true);
303f61105deSAdrian Lang
3042ace74f4SAndreas Gohr        if($this->getUser() && $INFO['writable']) {
305f61105deSAdrian Lang            $lang['btn_tagging_edit'] = $lang['btn_secedit'];
3063496cc8aSAndreas Gohr            $ret .= html_btn('tagging_edit', $INFO['id'], '', array());
307289f50bdSAndreas Gohr            $form = new Doku_Form(array('id' => 'tagging__edit'));
308fbf38c5bSAndreas Gohr            $form->addHidden('tagging[id]', $INFO['id']);
309289f50bdSAndreas Gohr            $form->addHidden('call', 'plugin_tagging_save');
3102ace74f4SAndreas Gohr            $form->addElement(form_makeTextField('tagging[tags]', implode(', ', array_keys($this->findItems(array('pid' => $INFO['id'], 'tagger' => $this->getUser()), 'tag')))));
311289f50bdSAndreas Gohr            $form->addElement(form_makeButton('submit', 'save', $lang['btn_save'], array('id' => 'tagging__edit_save')));
312289f50bdSAndreas Gohr            $form->addElement(form_makeButton('submit', 'cancel', $lang['btn_cancel'], array('id' => 'tagging__edit_cancel')));
3133496cc8aSAndreas Gohr            $ret .= $form->getForm();
314f61105deSAdrian Lang        }
3153496cc8aSAndreas Gohr        $ret .= '</div>';
3163496cc8aSAndreas Gohr
3173496cc8aSAndreas Gohr        if($print) echo $ret;
3183496cc8aSAndreas Gohr        return $ret;
319f61105deSAdrian Lang    }
320872edc7cSRené Corinth
3218a1a3846SAndreas Gohr    /**
3228a1a3846SAndreas Gohr     * @return array
3238a1a3846SAndreas Gohr     */
324872edc7cSRené Corinth    public function getAllTags() {
325872edc7cSRené Corinth
326872edc7cSRené Corinth        $db  = $this->getDb();
3278a1a3846SAndreas Gohr        $res = $db->query('SELECT pid, tag, tagger FROM taggings ORDER BY tag');
328872edc7cSRené Corinth
329872edc7cSRené Corinth        $tags_tmp = $db->res2arr($res);
330872edc7cSRené Corinth        $tags     = array();
331872edc7cSRené Corinth        foreach($tags_tmp as $tag) {
332302a38efSAndreas Gohr            $tid = $this->cleanTag($tag['tag']);
333872edc7cSRené Corinth
334fb1d0583SAndreas Gohr            if(!isset($tags[$tid]['orig'])) $tags[$tid]['orig'] = array();
335fb1d0583SAndreas Gohr            $tags[$tid]['orig'][] = $tag['tag'];
336872edc7cSRené Corinth
337302a38efSAndreas Gohr            if(isset($tags[$tid]['count'])) {
338302a38efSAndreas Gohr                $tags[$tid]['count']++;
339302a38efSAndreas Gohr                $tags[$tid]['tagger'][] = $tag['tagger'];
340872edc7cSRené Corinth            } else {
341302a38efSAndreas Gohr                $tags[$tid]['count']  = 1;
342302a38efSAndreas Gohr                $tags[$tid]['tagger'] = array($tag['tagger']);
343872edc7cSRené Corinth            }
344872edc7cSRené Corinth        }
345872edc7cSRené Corinth        return $tags;
346872edc7cSRené Corinth    }
347872edc7cSRené Corinth
3488a1a3846SAndreas Gohr    /**
3498a1a3846SAndreas Gohr     * Renames a tag
3508a1a3846SAndreas Gohr     *
3518a1a3846SAndreas Gohr     * @param string $formerTagName
3528a1a3846SAndreas Gohr     * @param string $newTagName
3538a1a3846SAndreas Gohr     */
354872edc7cSRené Corinth    public function renameTag($formerTagName, $newTagName) {
355872edc7cSRené Corinth
356872edc7cSRené Corinth        if(empty($formerTagName) || empty($newTagName)) {
3578a1a3846SAndreas Gohr            msg($this->getLang("admin enter tag names"), -1);
3588a1a3846SAndreas Gohr            return;
359872edc7cSRené Corinth        }
360872edc7cSRené Corinth
361872edc7cSRené Corinth        $db = $this->getDb();
362872edc7cSRené Corinth
363fb1d0583SAndreas Gohr        $res   = $db->query('SELECT pid FROM taggings WHERE CLEANTAG(tag) = ?', $this->cleanTag($formerTagName));
364872edc7cSRené Corinth        $check = $db->res2arr($res);
365872edc7cSRené Corinth
366872edc7cSRené Corinth        if(empty($check)) {
3678a1a3846SAndreas Gohr            msg($this->getLang("admin tag does not exists"), -1);
3688a1a3846SAndreas Gohr            return;
369872edc7cSRené Corinth        }
370872edc7cSRené Corinth
371fb1d0583SAndreas Gohr        $res = $db->query("UPDATE taggings SET tag = ? WHERE CLEANTAG(tag) = ?", $newTagName, $this->cleanTag($formerTagName));
372872edc7cSRené Corinth        $db->res2arr($res);
373872edc7cSRené Corinth
374fb1d0583SAndreas Gohr        msg($this->getLang("admin renamed"), 1);
3758a1a3846SAndreas Gohr        return;
376872edc7cSRené Corinth    }
377872edc7cSRené Corinth
378f61105deSAdrian Lang}
379