Porting Freetag to CI. This is a work in progress, so use at own risk. Please feel free to make any suggestions or bug fixes as needed. Please also make notes at the bottom of the changes you’ve made (if any).
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/* This is a port of Freetag for use with CodeIgniter. Original license info below. */
/**
* Gordon Luk's Freetag - Generalized Open Source Tagging and Folksonomy.
* Copyright (C) 2004-2006 Gordon D. Luk <gluk AT getluky DOT net>
*
* Released under both BSD license and Lesser GPL library license. Whenever
* there is any discrepancy between the two licenses, the BSD license will
* take precedence. See License.txt.
*
*/
/**
* Freetag API Implementation
*
* Freetag is a generic PHP class that can hook-in to existing database
* schemas and allows tagging of content within a social website. It's fun,
* fast, and easy! Try it today and see what all the folksonomy fuss is
* about.
*
* Contributions and/or donations are welcome.
*
* Author: Gordon Luk
* http://www.getluky.net
*
* Version: 0.260
* Last Updated: Jun 4, 2006
*
*/
class Freetag {
/**
* @access private
* @var bool Prints out limited debugging information if true, not fully implemented yet.
*/
var $_debug = FALSE;
/**
* @access private
* @var string The prefix of freetag database tables.
*/
var $_table_prefix = '';
/**
* @access private
* @var string The regex-style set of characters that are valid for normalized tags.
*/
var $_normalized_valid_chars = 'a-zA-Z0-9';
/**
* @access private
* @var string Whether to normalize tags at all.
*/
var $_normalize_tags = 1;
/**
* @access private
* @var string Whether to prevent multiple users from tagging the same object. By default, set to block (ala Upcoming.org)
*/
var $_block_multiuser_tag_on_object = 1;
/**
* @access private
* @var string Will append this string to any integer tags sent through Freetag. This is supposed to prevent PHP casting "string" integer tags as ints. Won't do anything to floats or non-numeric strings.
*/
var $_append_to_integer = '';
/**
* @access private
* @var int The maximum length of a tag.
*/
var $_MAX_TAG_LENGTH = 30;
/**
* freetag
*
* Constructor for the freetag class.
*
* @param array An associative array of options to pass to the instance of Freetag.
* The following options are valid:
* - debug: Set to TRUE for debugging information. [default:FALSE]
* - table_prefix: If you wish to create multiple Freetag databases on the same database, you can put a prefix in front of the table names and pass separate prefixes to the constructor. [default: '']
* - normalize_tags: Whether to normalize (lowercase and filter for valid characters) on tags at all. [default: 1]
* - normalized_valid_chars: Pass a regex-style set of valid characters that you want your tags normalized against. [default: 'a-zA-Z0-9' for alphanumeric]
* - block_multiuser_tag_on_object: Set to 0 in order to allow individual users to all tag the same object with the same tag. Default is 1 to only allow one occurence of a tag per object. [default: 1]
* - append_to_integer: Will append this string to any integer tags sent through Freetag. This is supposed to prevent PHP casting "string" integer tags as ints. Won't do anything to floats or non-numeric strings.
* - MAX_TAG_LENGTH: maximum length of normalized tags in chars. [default: 30]
*
*/
function Freetag($params = NULL) {
$this->object =& get_instance();
log_message('debug', "Freetag Class Initialized");
//$this->object->load->library('database');
$available_options = array('debug', 'table_prefix', 'normalize_tags', 'normalized_valid_chars', 'block_multiuser_tag_on_object', 'append_to_integer', 'MAX_TAG_LENGTH');
if (is_array($params)) {
foreach ($params as $key => $value) {
$this->debug_text("Option: $key");
if (in_array($key, $available_options) ) {
$this->debug_text("Valid Config options: $key");
$property = '_'.$key;
$this->$property = $value;
$this->debug_text("Setting $property to $value");
}
else {
$this->debug_text("ERROR: Config option: $key is not a valid option");
}
}
}
}
/**
* get_objects_with_tag
*
* Use this function to build a page of results that have been tagged with the same tag.
* Pass along a tagger_id to collect only a certain user's tagged objects, and pass along
* none in order to get back all user-tagged objects. Most of the get_*_tag* functions
* operate on the normalized form of tags, because most interfaces for navigating tags
* should use normal form.
*
* @param string - Pass the normalized tag form along to the function.
* @param int (Optional) - The numerical offset to begin display at. Defaults to 0.
* @param int (Optional) - The number of results per page to show. Defaults to 100.
* @param int (Optional) - The unique ID of the 'user' who tagged the object.
*
* @return An array of Object ID numbers that reference your original objects.
*/
function get_objects_with_tag($tag, $offset = 0, $limit = 100, $tagger_id = NULL) {
if(!isset($tag)) {
return false;
}
$tag = $this->object->db->escape($tag);
if(isset($tagger_id) && ($tagger_id > 0)) {
$tagger_sql = "AND tagger_id = $tagger_id";
}
else {
$tagger_sql = "";
}
$prefix = $this->_table_prefix;
$sql = "SELECT DISTINCT object_id
FROM ".$prefix."freetagged_objects INNER JOIN ".$prefix."freetags ON (tag_id = id)
WHERE tag = $tag
$tagger_sql
ORDER BY object_id ASC
LIMIT $offset, $limit
";
$rs = $this->object->db->query($sql);
$retarr = array();
foreach ($rs->result_array() as $row) {
$retarr[] = $row['object_id'];
}
return $retarr;
}
/**
* get_objects_with_tag_all
*
* Use this function to build a page of results that have been tagged with the same tag.
* This function acts the same as get_objects_with_tag, except that it returns an unlimited
* number of results. Therefore, it's more useful for internal displays, not for API's.
* Pass along a tagger_id to collect only a certain user's tagged objects, and pass along
* none in order to get back all user-tagged objects. Most of the get_*_tag* functions
* operate on the normalized form of tags, because most interfaces for navigating tags
* should use normal form.
*
* @param string - Pass the normalized tag form along to the function.
* @param int (Optional) - The unique ID of the 'user' who tagged the object.
*
* @return An array of Object ID numbers that reference your original objects.
*/
function get_objects_with_tag_all($tag, $tagger_id = NULL) {
if(!isset($tag)) {
return false;
}
$tag = $this->object->db->escape($tag);
if(isset($tagger_id) && ($tagger_id > 0)) {
$tagger_sql = "AND tagger_id = $tagger_id";
}
else {
$tagger_sql = "";
}
$prefix = $this->_table_prefix;
$sql = "SELECT DISTINCT object_id
FROM ".$prefix."freetagged_objects INNER JOIN ".$prefix."freetags ON (tag_id = id)
WHERE tag = $tag
$tagger_sql
ORDER BY object_id ASC
";
$rs = $this->object->db->query($sql);
$retarr = array();
foreach ($rs->result_array() as $row) {
$retarr[] = $row['object_id'];
}
return $retarr;
}
/**
* get_objects_with_tag_combo
*
* Returns an array of object ID's that have all the tags passed in the
* tagArray parameter. Use this to provide tag combo services to your users.
*
* @param array - Pass an array of normalized form tags along to the function.
* @param int (Optional) - The numerical offset to begin display at. Defaults to 0.
* @param int (Optional) - The number of results per page to show. Defaults to 100.
* @param int (Optional) - Restrict the result to objects tagged by a particular user.
*
* @return An array of Object ID numbers that reference your original objects.
*/
function get_objects_with_tag_combo($tagArray, $offset = 0, $limit = 100, $tagger_id = NULL) {
if (!isset($tagArray) || !is_array($tagArray)) {
return false;
}
//$db = &$this->object->db;
$retarr = array();
if (count($tagArray) == 0) {
return $retarr;
}
if(isset($tagger_id) && ($tagger_id > 0)) {
$tagger_sql = "AND tagger_id = $tagger_id";
}
else {
$tagger_sql = "";
}
foreach ($tagArray as $key => $value) {
$tagArray[$key] = $this->object->db->escape($value);
}
$tagArray = array_unique($tagArray);
$tag_sql = join(",", $tagArray);
$numTags = count($tagArray);
$prefix = $this->_table_prefix;
// We must adjust for duplicate normalized tags appearing multiple times in the join by
// counting only the distinct tags. It should also work for an individual user.
$sql = "SELECT ".$prefix."freetagged_objects.object_id, tag, COUNT(DISTINCT tag) AS uniques
FROM ".$prefix."freetagged_objects
INNER JOIN ".$prefix."freetags ON (".$prefix."freetagged_objects.tag_id = ".$prefix."freetags.id)
WHERE ".$prefix."freetags.tag IN ($tag_sql)
$tagger_sql
GROUP BY ".$prefix."freetagged_objects.object_id
HAVING uniques = $numTags
LIMIT $offset, $limit
";
$this->debug_text("Tag combo: " . join("+", $tagArray) . " SQL: $sql");
$rs = $this->object->db->query($sql);
foreach ($rs->result_array() as $row) {
$retarr[] = $row['object_id'];
}
return $retarr;
}
/**
* get_objects_with_tag_id
*
* Use this function to build a page of results that have been tagged with the same tag.
* This function acts the same as get_objects_with_tag, except that it accepts a numerical
* tag_id instead of a text tag.
* Pass along a tagger_id to collect only a certain user's tagged objects, and pass along
* none in order to get back all user-tagged objects.
*
* @param int - Pass the ID number of the tag.
* @param int (Optional) - The numerical offset to begin display at. Defaults to 0.
* @param int (Optional) - The number of results per page to show. Defaults to 100.
* @param int (Optional) - The unique ID of the 'user' who tagged the object.
*
* @return An array of Object ID numbers that reference your original objects.
*/
function get_objects_with_tag_id($tag_id, $offset = 0, $limit = 100, $tagger_id = NULL) {
if(!isset($tag_id)) {
return false;
}
if(isset($tagger_id) && ($tagger_id > 0)) {
$tagger_sql = "AND tagger_id = $tagger_id";
}
else {
$tagger_sql = "";
}
$prefix = $this->_table_prefix;
$sql = "SELECT DISTINCT object_id
FROM ".$prefix."freetagged_objects INNER JOIN ".$prefix."freetags ON (tag_id = id)
WHERE id = $tag_id
$tagger_sql
ORDER BY object_id ASC
LIMIT $offset, $limit
";
$rs = $this->object->db->query($sql);
$retarr = array();
foreach ($rs->result_array() as $row) {
$retarr[] = $row['object_id'];
}
return $retarr;
}
/**
* get_tags_on_object
*
* You can use this function to show the tags on an object. Since it supports both user-specific
* and general modes with the $tagger_id parameter, you can use it twice on a page to make it work
* similar to upcoming.org and flickr, where the page displays your own tags differently than
* other users' tags.
*
* @param int The unique ID of the object in question.
* @param int The offset of tags to return.
* @param int The size of the tagset to return. Use a zero size to get all tags.
* @param int The unique ID of the person who tagged the object, if user-level tags only are preferred.
*
* @return array Returns a PHP array with object elements ordered by object ID. Each element is an associative
* array with the following elements:
* - 'tag' => Normalized-form tag
* - 'raw_tag' => The raw-form tag
* - 'tagger_id' => The unique ID of the person who tagged the object with this tag.
*/
function get_tags_on_object($object_id, $offset = 0, $limit = 10, $tagger_id = NULL) {
if(!isset($object_id)) {
return false;
}
if(isset($tagger_id) && ($tagger_id > 0)) {
$tagger_sql = "AND tagger_id = $tagger_id";
}
else {
$tagger_sql = "";
}
if($limit <= 0) {
$limit_sql = "";
}
else {
$limit_sql = "LIMIT $offset, $limit";
}
$prefix = $this->_table_prefix;
$sql = "SELECT DISTINCT tag, raw_tag, tagger_id
FROM ".$prefix."freetagged_objects INNER JOIN ".$prefix."freetags ON (tag_id = id)
WHERE object_id = $object_id
$tagger_sql
ORDER BY id ASC
$limit_sql
";
$rs = $this->object->db->query($sql);
$retarr = array();
foreach ($rs->result_array() as $row) {
$retarr[] = array(
'tag' => $row['tag'],
'raw_tag' => $row['raw_tag'],
'tagger_id' => $row['tagger_id']
);
}
return $retarr;
}
/**
* safe_tag
*
* Pass individual tag phrases along with object and person ID's in order to
* set a tag on an object. If the tag in its raw form does not yet exist,
* this function will create it.
* Fails transparently on duplicates, and checks for dupes based on the
* block_multiuser_tag_on_object constructor param.
*
* @param int The unique ID of the person who tagged the object with this tag.
* @param int The unique ID of the object in question.
* @param string A raw string from a web form containing tags.
*
* @return boolean Returns true if successful, false otherwise. Does not operate as a transaction.
*/
function safe_tag($tagger_id, $object_id, $tag) {
if(!isset($tagger_id)||!isset($object_id)||!isset($tag)) {
show_error("Freetag: safe_tag argument missing");
// die("safe_tag argument missing");
return false;
}
if ($this->_append_to_integer != '' && is_numeric($tag) && intval($tag) == $tag) {
// Converts numeric tag "123" to "123_" to facilitate
// alphanumeric sorting (otherwise, PHP converts string to
// true integer).
$tag = preg_replace('/^([0-9]+)$/', "$1".$this->_append_to_integer, $tag);
}
$normalized_tag = $this->object->db->escape($this->normalize_tag($tag));
$tag = $this->object->db->escape($tag);
$prefix = $this->_table_prefix;
// First, check for duplicate of the normalized form of the tag on this object.
// Dynamically switch between allowing duplication between users on the constructor param 'block_multiuser_tag_on_object'.
// If it's set not to block multiuser tags, then modify the existence
// check to look for a tag by this particular user. Otherwise, the following
// query will reveal whether that tag exists on that object for ANY user.
if ($this->_block_multiuser_tag_on_object == 0) {
$tagger_sql = " AND tagger_id = $tagger_id";
}
else {
$tagger_sql = '';
}
$sql = "SELECT COUNT(*) as count
FROM ".$prefix."freetagged_objects INNER JOIN ".$prefix."freetags ON (tag_id = id)
WHERE 1
$tagger_sql
AND object_id = $object_id
AND tag = $normalized_tag
";
$rs = $this->object->db->query($sql);
$rs = $rs->row_array();
if($rs['count'] > 0) {
return true;
}
// Then see if a raw tag in this form exists.
$sql = "SELECT id
FROM ".$prefix."freetags
WHERE raw_tag = $tag
";
$rs = $this->object->db->query($sql);
if($rs->num_rows() > 0) {
$row = $rs->row_array();
$tag_id = $row['id'];
}
else {
// Add new tag!
$sql = "INSERT INTO ".$prefix."freetags (tag, raw_tag) VALUES ($normalized_tag, $tag)";
$rs = $this->object->db->query($sql);
$tag_id = $this->object->db->insert_id();
}
if(!($tag_id > 0)) {
return false;
}
$sql = "INSERT INTO ".$prefix."freetagged_objects
(tag_id, tagger_id, object_id, tagged_on)
VALUES ($tag_id, $tagger_id, $object_id, NOW())
";
$rs = $this->object->db->query($sql);
return true;
}
/**
* normalize_tag
*
* This is a utility function used to take a raw tag and convert it to normalized form.
* Normalized form is essentially lowercased alphanumeric characters only,
* with no spaces or special characters.
*
* Customize the normalized valid chars with your own set of special characters
* in regex format within the option 'normalized_valid_chars'. It acts as a filter
* to let a customized set of characters through.
*
* After the filter is applied, the function also lowercases the characters using strtolower
* in the current locale.
*
* The default for normalized_valid_chars is a-zA-Z0-9, or english alphanumeric.
*
* @param string An individual tag in raw form that should be normalized.
*
* @return string Returns the tag in normalized form.
*/
function normalize_tag($tag) {
if ($this->_normalize_tags) {
$normalized_valid_chars = $this->_normalized_valid_chars;
$normalized_tag = preg_replace("/[^$normalized_valid_chars]/", "", $tag);
return strtolower($normalized_tag);
}
else {
return $tag;
}
}
/**
* delete_object_tag
*
* Removes a tag from an object. This does not delete the tag itself from
* the database. Since most applications will only allow a user to delete
* their own tags, it supports raw-form tags as its tag parameter, because
* that's what is usually shown to a user for their own tags.
*
* @param int The unique ID of the person who tagged the object with this tag.
* @param int The ID of the object in question.
* @param string The raw string form of the tag to delete. See above for notes.
*
* @return string Returns the tag in normalized form.
*/
function delete_object_tag($tagger_id, $object_id, $tag) {
if(!isset($tagger_id)||!isset($object_id)||!isset($tag)) {
show_error("Freetag: delete_object_tag argument mising");
//die("delete_object_tag argument missing");
return false;
}
$tag_id = $this->get_raw_tag_id($tag);
$prefix = $this->_table_prefix;
if($tag_id > 0) {
$sql = "DELETE FROM ".$prefix."freetagged_objects
WHERE tagger_id = $tagger_id
AND object_id = $object_id
AND tag_id = $tag_id
LIMIT 1
";
$rs = $this->object->db->query($sql);
return true;
}
else {
return false;
}
}
/**
* delete_all_object_tags
*
* Removes all tag from an object. This does not
* delete the tag itself from the database. This is most useful for
* cleanup, where an item is deleted and all its tags should be wiped out
* as well.
*
* @param int The ID of the object in question.
*
* @return boolean Returns true if successful, false otherwise. It will return true if the tagged object does not exist.
*/
function delete_all_object_tags($object_id) {
$prefix = $this->_table_prefix;
if($object_id > 0) {
$sql = "DELETE FROM ".$prefix."freetagged_objects
WHERE
object_id = $object_id
";
$rs = $this->object->db->query($sql);
return true;
}
else {
return false;
}
}
/**
* delete_all_object_tags_for_user
*
* Removes all tag from an object for a particular user. This does not
* delete the tag itself from the database. This is most useful for
* implementations similar to del.icio.us, where a user is allowed to retag
* an object from a text box. That way, it becomes a two step operation of
* deleting all the tags, then retagging with whatever's left in the input.
*
* @param int The unique ID of the person who tagged the object with this tag.
* @param int The ID of the object in question.
*
* @return boolean Returns true if successful, false otherwise. It will return true if the tagged object does not exist.
*/
function delete_all_object_tags_for_user($tagger_id, $object_id) {
if(!isset($tagger_id)||!isset($object_id)) {
show_error("Freetag: delete_all_object_tags_for_user argument mising");
//die("delete_all_object_tags_for_user argument missing");
return false;
}
$prefix = $this->_table_prefix;
if($object_id > 0) {
$sql = "DELETE FROM ".$prefix."freetagged_objects
WHERE tagger_id = $tagger_id
AND object_id = $object_id
";
$rs = $this->object->db->query($sql);
return true;
}
else {
return false;
}
}
/**
* get_tag_id
*
* Retrieves the unique ID number of a tag based upon its normal form. Actually,
* using this function is dangerous, because multiple tags can exist with the same
* normal form, so be careful, because this will only return one, assuming that
* if you're going by normal form, then the individual tags are interchangeable.
*
* @param string The normal form of the tag to fetch.
*
* @return string Returns the tag in normalized form.
*/
function get_tag_id($tag) {
if(!isset($tag)) {
show_error("Freetag: get_tag_id argument missing");
//die("get_tag_id argument missing");
return false;
}
$prefix = $this->_table_prefix;
$tag = $this->object->db->escape($tag);
$sql = "SELECT id FROM ".$prefix."freetags
WHERE
tag = $tag
LIMIT 1
";
$rs = $this->object->db->query($sql);
$row = $rs->row_array();
return $row['id'];
}
/**
* get_raw_tag_id
*
* Retrieves the unique ID number of a tag based upon its raw form. If a single
* unique record is needed, then use this function instead of get_tag_id,
* because raw_tags are unique.
*
* @param string The raw string form of the tag to fetch.
*
* @return string Returns the tag in normalized form.
*/
function get_raw_tag_id($tag) {
if(!isset($tag)) {
show_error("Freetag: get_tag_id argument mising");
//die("get_tag_id argument missing");
return false;
}
$prefix = $this->_table_prefix;
$tag = $this->object->db->escape($tag);
$sql = "SELECT id FROM ".$prefix."freetags
WHERE
raw_tag = $tag
LIMIT 1
";
$rs = $this->object->db->query($sql);
$row = $rs->row_array();
return $row['id'];
}
/**
* tag_object
*
* This function allows you to pass in a string directly from a form, which is then
* parsed for quoted phrases and special characters, normalized and converted into tags.
* The tag phrases are then individually sent through the safe_tag() method for processing
* and the object referenced is set with that tag.
*
* This method has been refactored to automatically look for existing tags and run
* adds/updates/deletes as appropriate. It also has been refactored to accept comma-separated lists
* of tagger_id's and objecct_id's to create either duplicate tagings from multiple taggers or
* apply the tags to multiple objects. However, a singular tagger_id and object_id still produces
* the same behavior.
*
* @param int A comma-separated list of unique id's of the tagging subject(s).
* @param int A comma-separated list of unique id's of the object(s) in question.
* @param string The raw string form of the tag to delete. See above for notes.
* @param int Whether to skip the update portion for objects that haven't been tagged. (Default: 1)
*
* @return string Returns the tag in normalized form.
*/
function tag_object($tagger_id_list, $object_id_list, $tag_string, $skip_updates = 1) {
if($tag_string == '') {
// If an empty string was passed, just return true, don't die.
// die("Empty tag string passed");
return true;
}
// Break up CSL's for tagger id's and object id's
$tagger_id_array = split(',', $tagger_id_list);
$valid_tagger_id_array = array();
foreach ($tagger_id_array as $id) {
if (intval($id) > 0) {
$valid_tagger_id_array[] = intval($id);
}
}
if (count($valid_tagger_id_array) == 0) {
return true;
}
$object_id_array = split(',', $object_id_list);
$valid_object_id_array = array();
foreach ($object_id_array as $id) {
if (intval($id) > 0) {
$valid_object_id_array[] = intval($id);
}
}
if (count($valid_object_id_array) == 0) {
return true;
}
$tagArray = $this->_parse_tags($tag_string);
foreach ($valid_tagger_id_array as $tagger_id) {
foreach ($valid_object_id_array as $object_id) {
$oldTags = $this->get_tags_on_object($object_id, 0, 0, $tagger_id);
$preserveTags = array();
if (($skip_updates == 0) && (count($oldTags) > 0)) {
foreach ($oldTags as $tagItem) {
if (!in_array($tagItem['raw_tag'], $tagArray)) {
// We need to delete old tags that don't appear in the new parsed string.
$this->delete_object_tag($tagger_id, $object_id, $tagItem['raw_tag']);
}
else {
// We need to preserve old tags that appear (to save timestamps)
$preserveTags[] = $tagItem['raw_tag'];
}
}
}
$newTags = array_diff($tagArray, $preserveTags);
$this->_tag_object_array($tagger_id, $object_id, $newTags);
}
}
return true;
}
/**
* _tag_object_array
*
* Private method to add tags to an object from an array.
*
* @param int Unique ID of tagger
* @param int Unique ID of object
* @param array Array of tags to add.
*
* @return boolean True if successful, false otherwise.
*/
function _tag_object_array($tagger_id, $object_id, $tagArray) {
foreach($tagArray as $tag) {
$tag = trim($tag);
if(($tag != '') && (strlen($tag) <= $this->_MAX_TAG_LENGTH)) {
if(get_magic_quotes_gpc()) {
$tag = addslashes($tag);
}
$this->safe_tag($tagger_id, $object_id, $tag);
}
}
return true;
}
/**
* _parse_tags
*
* Private method to parse tags out of a string and into an array.
*
* @param string String to parse.
*
* @return array Returns an array of the raw "tags" parsed according to the freetag settings.
*/
function _parse_tags($tag_string) {
$newwords = array();
if ($tag_string == '') {
// If the tag string is empty, return the empty set.
return $newwords;
}
# Perform tag parsing
if(get_magic_quotes_gpc()) {
$query = stripslashes(trim($tag_string));
}
else {
$query = trim($tag_string);
}
$words = preg_split('/(")/', $query,-1,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$delim = 0;
foreach ($words as $key => $word)
{
&n