init('tagging',dirname(__FILE__).'/db/'); $db->create_function('CLEANTAG', array($this, 'cleanTag'), 1); return $db; } /** * Canonicalizes the tag to its lower case nospace form * * @param $tag * @return string */ public function cleanTag($tag) { $tag = str_replace(' ', '', $tag); $tag = utf8_strtolower($tag); return $tag; } public function replaceTags($id, $user, $tags) { $db = $this->getDB(); $db->query('BEGIN TRANSACTION'); $queries = array(array('DELETE FROM taggings WHERE pid = ? AND tagger = ?', $id, $user)); foreach ($tags as $tag) { $queries[] = array('INSERT INTO taggings (pid, tagger, tag) VALUES(?, ?, ?)', $id, $user, $tag); } foreach ($queries as $query) { if (!call_user_func_array(array($db, 'query'), $query)) { $db->query('ROLLBACK TRANSACTION'); return false; } } return $db->query('COMMIT TRANSACTION'); } /** * Get a list of Tags or Pages matching search criteria * * @param array $filter What to search for array('field' => 'searchterm') * @param string $type What field to return 'tag'|'pid' * @return array associative array in form of value => count */ public function findItems($filter, $type) { $db = $this->getDB(); if(!$db) return array(); // create WHERE clause $where = '1=1'; foreach($filter as $field => $value) { // compare clean tags only if ($field === 'tag') { $field = 'CLEANTAG(tag)'; $q = 'CLEANTAG(?)'; } else { $q = '?'; } // detect LIKE filters if ($this->useLike($value)) { $where .= " AND $field LIKE $q"; } else { $where .= " AND $field = $q"; } } // group and order if($type == 'tag') { $groupby = 'CLEANTAG(tag)'; $orderby = 'CLEANTAG(tag)'; } else { $groupby = $type; $orderby = "cnt DESC, $type"; } // create SQL $sql = "SELECT $type AS item, COUNT(*) AS cnt FROM taggings WHERE $where GROUP BY $groupby ORDER BY $orderby"; // run query and turn into associative array $res = $db->query($sql, array_values($filter)); $res = $db->res2arr($res); $ret = array(); foreach ($res as $row) { $ret[$row['item']] = $row['cnt']; } return $ret; } /** * Check if the given string is a LIKE statement * * @param string $value * @return bool */ private function useLike($value) { return strpos($value, '%') === 0 || strrpos($value, '%') === strlen($value) - 1; } /** * Constructs the URL to search for a tag * * @param $tag * @return string */ public function getTagSearchURL($tag) { return '?do=search&id=' . rawurlencode($tag); } public function cloudData($tags, $levels = 10) { $min = min($tags); $max = max($tags); // calculate tresholds $tresholds = array(); for($i=0; $i<=$levels; $i++){ $tresholds[$i] = pow($max - $min + 1, $i/$levels) + $min - 1; } // assign weights foreach($tags as $tag => $cnt){ foreach($tresholds as $tresh => $val){ if($cnt <= $val){ $tags[$tag] = $tresh; break; } $tags[$tag] = $levels; } } return $tags; } public function html_cloud($tags, $type, $func, $wrap = true, $return = false) { $ret = ''; if ($wrap) $ret .= '