* * 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. * */ /** * * Modified By Susenjit Chanda * - PEAR :: DB compiatable * Last Updated: Jun 15, 2010 * */ /** * 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 ADOConnection The ADODB Database connection instance. */ var $_db; /** * @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 object PEAR DB Object. * * @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($DBObject, $options = NULL) { $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($options)) { foreach ($options as $key => $value) { $this->show_debug_text("Option: $key"); if (in_array($key, $available_options) ) { $this->show_debug_text("Valid Config options: $key
"); $property = '_'.$key; $this->$property = $value; $this->show_debug_text("Setting $property to $value
"); } else { $this->show_debug_text("ERROR: Config option: $key is not a valid option"); } } } if(is_object($DBObject)) { $this->db = $DBObject; } else { $this->show_debug_text("DB Object is required"); } $this->db->setFetchMode(DB_FETCHMODE_ASSOC); } /** * 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 Array [assiociative array] $pArgumentsInArray * - tag: The normalized tag * - offset: The numerical offset to begin display at. Defaults to 0. * - limit: The number of results per page to show. Defaults to 100. * - tagger_id: The unique ID of the 'user' who tagged the object. * - prefix: Prefix of freetag database tables. * * @return An array of Object ID numbers that reference your original objects. */ function get_objects_with_tag($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; if(!isset($pArgumentsInArray['tag'])) { return false; } $offset = (isset($pArgumentsInArray['offset']))?$pArgumentsInArray['offset']:0; $limit = (isset($pArgumentsInArray['limit']))?$pArgumentsInArray['limit']:100; $tag = $this->db->quote($pArgumentsInArray['tag']); if(isset($pArgumentsInArray['tagger_id']) && ($pArgumentsInArray['tagger_id'] > 0)) { $tagger_sql = "AND tagger_id =". $pArgumentsInArray['tagger_id']; } else { $tagger_sql = ""; } $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->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } $i = 0; while($rows = $rs->fetchRow()) { $retarr[] = $rows; $i++; } 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 Array [assiociative array] $pArgumentsInArray * - tag: The normalized tag * - tagger_id: The unique ID of the 'user' who tagged the object. * - prefix: Prefix of freetag database tables. * * @return An array of Object ID numbers that reference your original objects. */ function get_objects_with_tag_all($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; if(!isset($pArgumentsInArray['tag'])) { return false; } $tag = $this->db->quote($pArgumentsInArray['tag']); if(isset($pArgumentsInArray['tagger_id']) && ($pArgumentsInArray['tagger_id'] > 0)) { $tagger_sql = "AND tagger_id =". $pArgumentsInArray['tagger_id']; } else { $tagger_sql = ""; } $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->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } $retarr = array(); $i = 0; while($rows = $rs->fetchRow()) { $retarr[] = $rows; $i++; } 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 [assiociative array] $pArgumentsInArray * - tagArray: Array of normalized form tags * - offset: The numerical offset to begin display at. Defaults to 0. * - limit: The number of results per page to show. Defaults to 100. * - tagger_id: The unique ID of the 'user' who tagged the object. * - prefix: Prefix of freetag database tables. * * @return An array of Object ID numbers that reference your original objects. */ function get_objects_with_tag_combo($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; if (!isset($pArgumentsInArray['tagArray']) || !is_array($pArgumentsInArray['$tagArray'])) { return false; } $offset = (isset($pArgumentsInArray['offset']))?$pArgumentsInArray['offset']:0; $limit = (isset($pArgumentsInArray['limit']))?$pArgumentsInArray['limit']:100; $retarr = array(); if (count($pArgumentsInArray['tagArray']) == 0) { return $retarr; } if(isset($pArgumentsInArray['tagger_id']) && ($pArgumentsInArray['tagger_id'] > 0)) { $tagger_sql = "AND tagger_id =". $pArgumentsInArray['tagger_id']; } else { $tagger_sql = ""; } foreach ($pArgumentsInArray['tagArray'] as $key => $value) { $tagArray[$key] = $this->db->qstr($value, get_magic_quotes_gpc()); } $tagArray = array_unique($pArgumentsInArray['tagArray']); $tag_sql = join(",", $tagArray); $numTags = count($tagArray); // 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->show_debug_text("Tag combo: " . join("+", $tagArray) . " SQL: $sql"); $rs = $this->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } $i = 0; while($rows = $db->fetchRow()) { $retarr[] = $rows['object_id']; $i++; } 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 Array [assiociative array] $pArgumentsInArray * - tag_id: The ID number of the tag * - offset: The numerical offset to begin display at. Defaults to 0. * - limit: The number of results per page to show. Defaults to 100. * - tagger_id: The unique ID of the 'user' who tagged the object. * - prefix: Prefix of freetag database tables. * * @return An array of Object ID numbers that reference your original objects. */ function get_objects_with_tag_id($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; if(!isset($pArgumentsInArray['tag_id'])) { return false; } $offset = (isset($pArgumentsInArray['offset']))?$pArgumentsInArray['offset']:0; $limit = (isset($pArgumentsInArray['limit']))?$pArgumentsInArray['limit']:100; if(isset($pArgumentsInArray['tagger_id']) && ($pArgumentsInArray['tagger_id'] > 0)) { $tagger_sql = "AND tagger_id =". $pArgumentsInArray['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->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } $retarr = array(); $i = 0; while($rows = $rs->fetchRow()) { $retarr[] = $rows['object_id']; $i++; } 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 Array [assiociative array] $pArgumentsInArray * - object_id: Unique ID of the object in question. * - offset: The numerical offset to begin display at. Defaults to 0. * - limit: The number of results per page to show. Defaults to 100. * - tagger_id: The unique ID of the 'user' who tagged the object, if user-level tags only are preferred. * - prefix: Prefix of freetag database tables. * * @return array Returns a PHP array with object elements ordered by object ID. Each element is an associative */ function get_tags_on_object($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; if(!isset($pArgumentsInArray['object_id'])) { return false; } else { $object_id = intVal($pArgumentsInArray['object_id']); } if(isset($pArgumentsInArray['tagger_id']) && ($pArgumentsInArray['tagger_id'] > 0)) { $tagger_sql = "AND tagger_id =". $pArgumentsInArray['tagger_id']; } else { $tagger_sql = ""; } $offset = (isset($pArgumentsInArray['offset']))?$pArgumentsInArray['offset']:0; $limit = (isset($pArgumentsInArray['limit']))?$pArgumentsInArray['limit']:100; if($limit <= 0) { $limit_sql = ""; } else { $limit_sql = "LIMIT $offset, $limit"; } $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->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } $retarr = array(); $i = 0; while($rows = $rs->fetchRow()) { $retarr[] = array( 'tag' => $rows['tag'], 'raw_tag' => $rows['raw_tag'], 'tagger_id' => $rows['tagger_id'] ); $i++; } 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 Array [assiociative array] $pArgumentsInArray * - tagger_id: The unique ID of the person who tagged the object with this tag. * - object_id: Unique ID of the object in question. * - tag: A raw string from a web form containing tags. * - prefix: Prefix of freetag database tables. * * @return boolean Returns true if successful, false otherwise. Does not operate as a transaction. */ function safe_tag($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; if(!isset($pArgumentsInArray['tagger_id'])||!isset($pArgumentsInArray['object_id'])||!isset($pArgumentsInArray['tag'])) { $this->show_debug_text("safe_tag argument missing", TRUE); return false; } else { $object_id = $pArgumentsInArray['object_id']; $tagger_id = $pArgumentsInArray['tagger_id']; } if ($this->_append_to_integer != '' && is_numeric($pArgumentsInArray['tag']) && intval($pArgumentsInArray['tag']) == $pArgumentsInArray['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, $pArgumentsInArray['tag']); } else { $tag = $pArgumentsInArray['tag']; } $normalized_tag = $this->db->quote($this->normalize_tag(array('tag' => $tag))); $tag = $this->db->quote($tag); // 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->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } $rows = $rs->fetchRow(); if($rows['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->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } $rows = $rs->fetchRow(); if(isset($rows['id'])) { $tag_id = $rows['id']; } else { // Add new tag! $sql = "INSERT INTO ${prefix}freetags (tag, raw_tag) VALUES ($normalized_tag, $tag)"; $rs = $this->db->query($sql); $sql = "SELECT * FROM ${prefix}freetags WHERE tag=".$normalized_tag." AND raw_tag=".$tag; $rs = $this->db->query($sql); $rows = $rs->fetchRow(); $tag_id = $rows['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, '".strftime('%Y-%m-%d %H:%M:%S',time())."')"; $rs = $this->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } 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 Array [assiociative array] $pArgumentsInArray * - tag: An individual tag in raw form that should be normalized. * * @return string Returns the tag in normalized form. */ function normalize_tag($pArgumentsInArray) { if ($this->_normalize_tags) { $normalized_valid_chars = $this->_normalized_valid_chars; $normalized_tag = preg_replace("/[^$normalized_valid_chars]/", "", $pArgumentsInArray['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 Array [assiociative array] $pArgumentsInArray * - tagger_id: The unique ID of the 'user' who tagged the object. * - object_id: Unique ID of the object in question. * - tag: A raw string from a web form containing tags. * - prefix: Prefix of freetag database tables. * * @return string Returns the tag in normalized form. */ function delete_object_tag($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; if(!isset($pArgumentsInArray['tagger_id'])||!isset($pArgumentsInArray['object_id'])||!isset($pArgumentsInArray['tag'])) { $this->show_debug_text("delete_object_tag argument missing", TRUE); return false; } else { $tagger_id = $pArgumentsInArray['tagger_id']; $object_id = $pArgumentsInArray['object_id']; $tag_id = $this->get_raw_tag_id($pArgumentsInArray); } 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->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } 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 Array [assiociative array] $pArgumentsInArray * - object_id: Unique ID of the object in question. * - prefix: Prefix of freetag database tables. * * @return boolean Returns true if successful, false otherwise. It will return true if the tagged object does not exist. */ function delete_all_object_tags($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; if($pArgumentsInArray['object_id'] > 0) { $sql = "DELETE FROM ${prefix}freetagged_objects WHERE object_id =". $pArgumentsInArray['object_id']; $rs = $this->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } 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 Array [assiociative array] $pArgumentsInArray * - tagger_id: The unique ID of the 'user' who tagged the object, if user-level tags only are preferred. * - object_id: Unique ID of the object in question. * - prefix: Prefix of freetag database tables. * * @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($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; if(!isset($pArgumentsInArray['tagger_id'])||!isset($pArgumentsInArray['object_id'])) { $this->show_debug_text("delete_all_object_tags_for_user argument missing", TRUE); return false; } if($object_id > 0) { $sql = "DELETE FROM ${prefix}freetagged_objects WHERE tagger_id = ".$pArgumentsInArray['tagger_id']." AND object_id = ".$pArgumentsInArray['object_id']; $rs = $this->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } 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 Array [assiociative array] $pArgumentsInArray * - tag: The normalized form of the tag * - prefix: Prefix of freetag database tables. * * @return string Returns the tag in normalized form. */ function get_tag_id($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; if(!isset($pArgumentsInArray['tag'])) { $this->show_debug_text("get_tag_id argument missing", TRUE); return false; } $tag = $this->db->quote($pArgumentsInArray['tag']); $sql = "SELECT id FROM ${prefix}freetags WHERE tag = $tag LIMIT 1 "; $rs = $this->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } $rows = $rs->fetchRow(); return $rows['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 Array [assiociative array] $pArgumentsInArray * - tag: The raw string form of the tag to fetch. * - prefix: Prefix of freetag database tables. * * @return string Returns the tag in normalized form. */ function get_raw_tag_id($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; if(!isset($pArgumentsInArray['tag'])) { $this->show_debug_text("get_tag_id argument missing", TRUE); return false; } $tag = $this->db->quote($pArgumentsInArray['tag']); $sql = "SELECT id FROM ${prefix}freetags WHERE raw_tag = $tag LIMIT 1 "; $rs = $this->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } $rows = $rs->fetchRow(); return $rows['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 Array [assiociative array] $pArgumentsInArray * - tagger_id_list: A comma-separated list of unique id's of the tagging subject(s). * - object_id_list: A comma-separated list of unique id's of the object(s) in question. * - tag_string: The raw string form of the tag to delete. See above for notes. * - skip_updates: Whether to skip the update portion for objects that haven't been tagged; default is set:1. * * @return string Returns the tag in normalized form. */ function tag_object($pArgumentsInArray) { if($pArgumentsInArray['tag_string'] == '') { // If an empty string was passed, just return true, don't die. // die("Empty tag string passed"); return true; } $skip_updates = (isset($pArgumentsInArray['skip_updates']))?$pArgumentsInArray['skip_updates']:1; // Break up CSL's for tagger id's and object id's $tagger_id_array = split(',', $pArgumentsInArray['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(',', $pArgumentsInArray['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($pArgumentsInArray); $pArgArr = array( 'object_id' => 0, 'offset' => 0, 'limit' => 0, 'tagger_id' => 0, ); 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); $pArgArr['object_id'] = $object_id; $pArgArr['tagger_id'] = $tagger_id; $oldTags = $this->get_tags_on_object($pArgArr); $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. $pArgArr['tag'] = $tagItem['raw_tag']; $this->delete_object_tag($pArgArr); } else { // We need to preserve old tags that appear (to save timestamps) $preserveTags[] = $tagItem['raw_tag']; } } } $newTags = array_diff($tagArray, $preserveTags); $pArgArr['tagArray'] = $newTags; $this->_tag_object_array($pArgArr); } } return true; } /** * _tag_object_array * * Private method to add tags to an object from an array. * * @param Array [assiociative array] $pArgumentsInArray * - tagger_id: Unique ID of tagger. * - object_id: Unique ID of object. * - tagArray: Array of tags to add. * * @return boolean True if successful, false otherwise. */ function _tag_object_array($pArgumentsInArray) { $pArgArr = array( 'tagger_id' => 0, 'object_id' => 0, 'tag' => '', ); foreach($pArgumentsInArray['tagArray'] as $tag) { $tag = trim($tag); if(($tag != '') && (strlen($tag) <= $this->_MAX_TAG_LENGTH)) { if(get_magic_quotes_gpc()) { $tag = addslashes($tag); } $pArgArr['tagger_id'] = $pArgumentsInArray['tagger_id']; $pArgArr['object_id'] = $pArgumentsInArray['object_id']; $pArgArr['tag'] = $tag; $this->safe_tag($pArgArr); } } return true; } /** * _parse_tags * * Private method to parse tags out of a string and into an array. * * @param Array [assiociative array] $pArgumentsInArray * - tag_string: String to parse. * * @return array Returns an array of the raw "tags" parsed according to the freetag settings. */ function _parse_tags($pArgumentsInArray) { $newwords = array(); if ($pArgumentsInArray['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($pArgumentsInArray['tag_string'])); } else { $query = trim($pArgumentsInArray['tag_string']); } $words = preg_split('/(")/', $query,-1,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE); $delim = 0; foreach ($words as $key => $word) { if ($word == '"') { $delim++; continue; } if (($delim % 2 == 1) && $words[$key - 1] == '"') { $newwords[] = $word; } else { $newwords = array_merge($newwords, preg_split('/\s+/', $word, -1, PREG_SPLIT_NO_EMPTY)); } } return $newwords; } /** * get_most_popular_tags * * This function returns the most popular tags in the freetag system, with * offset and limit support for pagination. It also supports restricting to * an individual user. Call it with no parameters for a list of 25 most popular * tags. * * @param Array [assiociative array] $pArgumentsInArray * - tagger_id: The unique ID of the 'user' who tagged the object. * - offset: The numerical offset to begin display at. Defaults to 0. * - limit: The number of results per page to show. Defaults to 25. * - prefix: Prefix of freetag database tables. * * @return array Returns a PHP array with tags ordered by popularity descending. * Each element is an associative array with the following elements: * - 'tag' => Normalized-form tag * - 'count' => The number of objects tagged with this tag. */ function get_most_popular_tags($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; $offset = (isset($pArgumentsInArray['offset']))?$pArgumentsInArray['offset']:0; $limit = (isset($pArgumentsInArray['limit']))?$pArgumentsInArray['limit']:25; if(isset($pArgumentsInArray['tagger_id']) && ($pArgumentsInArray['tagger_id'] > 0)) { $tagger_sql = "AND tagger_id =". $pArgumentsInArray['tagger_id']; } else { $tagger_sql = ""; } $sql = "SELECT tag, COUNT(*) as count FROM ${prefix}freetags INNER JOIN ${prefix}freetagged_objects ON (id = tag_id) WHERE 1 $tagger_sql GROUP BY tag ORDER BY count DESC, tag ASC LIMIT $offset, $limit "; $rs = $this->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } $retarr = array(); $i = 0; while($rows = $rs->fetchRow()) { $retarr[] = array( 'tag' => $rows['tag'], 'count' => $rows['count'], ); $i++; } return $retarr; } /** * get_most_recent_objects * * This function returns the most recent object ids in the * freetag system, with offset and limit support for * pagination. It also supports restricting to an individual * user. Call it with no parameters for a list of 25 most * recent tags. * * @param Array [assiociative array] $pArgumentsInArray * - tagger_id: The unique ID of the 'user' who tagged the object. * - tag: Tag to filter by. * - offset: The numerical offset to begin display at. Defaults to 0. * - limit: The number of results per page to show. Defaults to 25. * - prefix: Prefix of freetag database tables. * * @return array Returns a PHP array with object ids ordered by * timestamp descending. * Each element is an associative array with the following elements: * - 'object_id' => Object id * - 'tagged_on' => The timestamp of each object id */ function get_most_recent_objects($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; $offset = (isset($pArgumentsInArray['offset']))?$pArgumentsInArray['offset']:0; $limit = (isset($pArgumentsInArray['limit']))?$pArgumentsInArray['limit']:25; if(isset($pArgumentsInArray['tagger_id']) && ($pArgumentsInArray['tagger_id'] > 0)) { $tagger_sql = "AND tagger_id =". $pArgumentsInArray['tagger_id']; } else { $tagger_sql = ""; } $sql = ""; if(!isset($pArgumentsInArray['tag'])) { $sql = "SELECT DISTINCT object_id, tagged_on FROM ${prefix}freetagged_objects WHERE 1 $tagger_sql ORDER BY tagged_on DESC LIMIT $offset, $limit "; } else { $tag = $this->db->quote($pArgumentsInArray['tag']); $sql = "SELECT DISTINCT object_id, tagged_on FROM ${prefix}freetagged_objects INNER JOIN ${prefix}freetags ON (tag_id = id) WHERE tag = $tag $tagger_sql ORDER BY tagged_on DESC LIMIT $offset, $limit "; } $rs = $this->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } $retarr = array(); $i = 0; while($rows = $rs->fetchRow()) { $retarr[] = array( 'object_id' => $rows['object_id'], 'tagged_on' => $rows['tagged_on'], ); $i++; } return $retarr; } /** * count_tags * * Returns the total number of tag->object links in the system. * It might be useful for pagination at times, but i'm not sure if I actually use * this anywhere. Restrict to a person's tagging by using the $tagger_id parameter. * It does NOT include any tags in the system that aren't directly linked * to an object. * * @param Array [assiociative array] $pArgumentsInArray * - tagger_id: The unique ID of the 'user' who tagged the object. * - normalized_version: Defaults to 0. * - prefix: Prefix of freetag database tables. * * @return int Returns the count */ function count_tags($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; $normalized_version = (isset($pArgumentsInArray['normalized_version']))?$pArgumentsInArray['normalized_version']:0; if(isset($pArgumentsInArray['tagger_id']) && ($pArgumentsInArray['tagger_id'] > 0)) { $tagger_sql = "AND tagger_id =". $pArgumentsInArray['tagger_id']; } else { $tagger_sql = ""; } if ($normalized_version == 1) { $distinct_col = 'tag'; } else { $distinct_col = 'tag_id'; } $sql = "SELECT COUNT(DISTINCT $distinct_col) as count FROM ${prefix}freetags INNER JOIN ${prefix}freetagged_objects ON (id = tag_id) WHERE 1 $tagger_sql "; $rs = $this->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } $rows = $rs->fetchRow(); if(isset($rows['count'])) { return $rows['count']; } return false; } /** * get_tag_cloud_html * * This is a pretty straightforward, flexible method that automatically * generates some html that can be dropped in as a tag cloud. * It uses explicit font sizes inside of the style attribute of SPAN * elements to accomplish the differently sized objects. * * It will also link every tag to $tag_page_url, appended with the * normalized form of the tag. You should adapt this value to your own * tag detail page's URL. * * @param Array [assiociative array] $pArgumentsInArray * - num_tags: The number of tags to return. (default: 100) * - min_font_size: The minimum font size in the cloud. (default: 10) * - max_font_size: The maximum font size in the cloud. (default: 20) * - font_units: The "units" for the font size (i.e. 'px', 'pt', 'em') (default: px) * - span_class: The class to use for all spans in the cloud. (default: cloud_tag) * - tag_page_url: The tag page URL (default: /tag/) * - tagger_id: The unique ID of the 'user' who tagged the object. * - offset: The numerical offset to begin display at. Defaults to 0. * * @return string Returns an HTML snippet that can be used directly as a tag cloud. */ function get_tag_cloud_html($pArgumentsInArray) { $num_tags = (isset($pArgumentsInArray['num_tags']))?$pArgumentsInArray['num_tags']:100; $min_font_size = (isset($pArgumentsInArray['min_font_size']))?$pArgumentsInArray['min_font_size']:10; $max_font_size = (isset($pArgumentsInArray['max_font_size']))?$pArgumentsInArray['max_font_size']:20; $font_units = (isset($pArgumentsInArray['font_units']))?$pArgumentsInArray['font_units']:'px'; $span_class = (isset($pArgumentsInArray['span_class']))?$pArgumentsInArray['span_class']:'cloud_tag'; $tag_page_url = (isset($pArgumentsInArray['tag_page_url']))?$pArgumentsInArray['tag_page_url']:'/tag/'; $offset = (isset($pArgumentsInArray['offset']))?$pArgumentsInArray['offset']:0; $tagger_id = $pArgumentsInArray['tagger_id']; $pArgArr = array( 'num_tags' => $num_tags, 'tagger_id' => $tagger_id, 'offset' => $offset, ); $tag_list = $this->get_tag_cloud_tags($pArgArr); // Get the maximum qty of tagged objects in the set if (count($tag_list)) { $max_qty = max(array_values($tag_list)); // Get the min qty of tagged objects in the set $min_qty = min(array_values($tag_list)); } else { return ''; } // For ever additional tagged object from min to max, we add // $step to the font size. $spread = $max_qty - $min_qty; if (0 == $spread) { // Divide by zero $spread = 1; } $step = ($max_font_size - $min_font_size)/($spread); // Since the original tag_list is alphabetically ordered, // we can now create the tag cloud by just putting a span // on each element, multiplying the diff between min and qty // by $step. $cloud_html = ''; $cloud_spans = array(); foreach ($tag_list as $tag => $qty) { $size = $min_font_size + ($qty - $min_qty) * $step; $cloud_span[] = '' . htmlspecialchars(stripslashes($tag)) . ''; } $cloud_html = join("\n ", $cloud_span); return $cloud_html; } /* * get_tag_cloud_tags * * This is a function built explicitly to set up a page with most popular tags * that contains an alphabetically sorted list of tags, which can then be sized * or colored by popularity. * * Also known more popularly as Tag Clouds! * * Here's the example case: http://upcoming.org/tag/ * * @param Array [assiociative array] $pArgumentsInArray * - max: The maximum number of tags to return. (default: 100) * - tagger_id: The unique ID of the tagger to restrict to * - offset: Specify starting record (default: 0) * - prefix: Prefix of freetag database tables. * * @return array Returns an array where the keys are normalized tags, and the * values are numeric quantity of objects tagged with that tag. */ function get_tag_cloud_tags($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; $max = (isset($pArgumentsInArray['max']))?$pArgumentsInArray['max']:100; $offset = (isset($pArgumentsInArray['offset']))?$pArgumentsInArray['offset']:0; if(isset($pArgumentsInArray['tagger_id']) && ($pArgumentsInArray['tagger_id'] > 0)) { $tagger_sql = "AND tagger_id =". $pArgumentsInArray['tagger_id']; } else { $tagger_sql = ""; } $max = intval($max); $offset = intval($offset); if ($offset >= 0 && $max >= 0) { $limit_sql = " LIMIT $offset, $max "; } elseif ($max >= 0) { $limit_sql = " LIMIT 0, $max "; } else { $max = 100; $limit_sql = " LIMIT 0, $max "; } $sql = "SELECT tag, COUNT(object_id) AS quantity FROM ${prefix}freetags INNER JOIN ${prefix}freetagged_objects ON (${prefix}freetags.id = tag_id) WHERE 1 $tagger_sql GROUP BY tag ORDER BY quantity DESC $limit_sql "; $rs = $this->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } $retarr = array(); $i = 0; while($rows = $rs->fetchRow()) { $retarr[$rows['tag']] = $rows['quantity']; $i++; } ksort($retarr); print_r($retarr); return $retarr; } /** * count_unique_tags * An alias to count_tags. * * @param Array [assiociative array] $pArgumentsInArray * - tagger_id: The unique ID of the tagger to restrict to * - normalized_version: Specify starting record Whether to count normalized tags or all raw tags(0 = raw, 1 = normalized)[default:0] * * @return int Returns the count */ function count_unique_tags($pArgumentsInArray) { return $this->count_tags($pArgumentsInArray); } /** * similar_tags * * Finds tags that are "similar" or related to the given tag. * It does this by looking at the other tags on objects tagged with the tag specified. * Confusing? Think of it like e-commerce's "Other users who bought this also bought," * as that's exactly how this works. * * Returns an empty array if no tag is passed, or if no related tags are found. * Hint: You can detect related tags returned with count($retarr > 0) * * It's important to note that the quantity passed back along with each tag * is a measure of the *strength of the relation* between the original tag * and the related tag. It measures the number of objects tagged with both * the original tag and its related tag. * * Thanks to Myles Grant for contributing this function! * * @param Array [assiociative array] $pArgumentsInArray * - tag: The normalized tag * - max: The maximum number of tags to return. * - tagger_id: The unique ID of the 'user' who tagged the object. * - prefix: Prefix of freetag database tables. * * @return array Returns an array where the keys are normalized tags, and the * values are numeric quantity of objects tagged with BOTH tags, sorted by * number of occurences of that tag (high to low). */ function similar_tags($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; $max = (isset($pArgumentsInArray['max']))?$pArgumentsInArray['max']:100; $retarr = array(); if(!isset($pArgumentsInArray['tag'])) { return $retarr; } $tag = $this->db->quote($pArgumentsInArray['tag']); $where_sql = ""; if(isset($pArgumentsInArray['tagger_id']) && ($pArgumentsInArray['tagger_id'] > 0)) { $tagger_id = intval($pArgumentsInArray['tagger_id']); $where_sql .= " AND o1.tagger_id = $tagger_id AND o2.tagger_id = $tagger_id "; } // This query was written using a double join for PHP. If you're trying to eke // additional performance and are running MySQL 4.X, you might want to try a subselect // and compare perf numbers. $sql = "SELECT t1.tag, COUNT( o1.object_id ) AS quantity FROM ${prefix}freetagged_objects o1 INNER JOIN ${prefix}freetags t1 ON ( t1.id = o1.tag_id ) INNER JOIN ${prefix}freetagged_objects o2 ON ( o1.object_id = o2.object_id ) INNER JOIN ${prefix}freetags t2 ON ( t2.id = o2.tag_id ) WHERE t2.tag = $tag AND t1.tag != $tag $where_sql GROUP BY o1.tag_id ORDER BY quantity DESC LIMIT 0, $max "; $rs = $this->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } $i = 0; while($rows = $rs->fetchRow()) { $retarr[$rows['tag']] = $rows['quantity']; $i++; } return $retarr; } /** * similar_objects * * This method implements a simple ability to find some objects in the database * that might be similar to an existing object. It determines this by trying * to match other objects that share the same tags. * * The user of the method has to use a threshold (by default, 1) which specifies * how many tags other objects must have in common to match. If the original object * has no tags, then it won't match anything. Matched objects are returned in order * of most similar to least similar. * * The more tags set on a database, the better this method works. Since this * is such an expensive operation, it requires a limit to be set via max_objects. * * @param Array [assiociative array] $pArgumentsInArray * - object_id: The unique ID of the object to find similar objects for. * - threshold: The Threshold of tags that must be found in common (default: 1). * - max_objects: The maximum number of similar objects to return (default: 5). * - tagger_id: The unique ID of the 'user' who tagged the object. * - prefix: Prefix of freetag database tables. * * @return array Returns a PHP array with matched objects ordered by strength of match descending. * Each element is an associative array with the following elements: * - 'strength' => A floating-point strength of match from 0-1.0 * - 'object_id' => Unique ID of the matched object * */ function similar_objects($pArgumentsInArray) { $prefix = (isset($pArgumentsInArray['prefix']))?$pArgumentsInArray['prefix']:$this->_table_prefix; $threshold = (isset($pArgumentsInArray['threshold']))?$pArgumentsInArray['threshold']:1; $max_objects = (isset($pArgumentsInArray['max_objects']))?$pArgumentsInArray['max_objects']:5; $retarr = array(); $object_id = intval($pArgumentsInArray['object_id']); $threshold = intval($threshold); $max_objects = intval($max_objects); if (!isset($object_id) || !($object_id > 0)) { return $retarr; } if ($threshold <= 0) { return $retarr; } if ($max_objects <= 0) { return $retarr; } // Pass in a zero-limit to get all tags. $pArgArr = array( 'object_id' => $object_id, 'offset' => 0, 'limit' => 0, 'tagger_id' => 0, ); $tagItems = $this->get_tags_on_object($pArgArr); $tagArray = array(); foreach ($tagItems as $tagItem) { $tagArray[] = $this->db->quote($tagItem['tag']); } $tagArray = array_unique($tagArray); $numTags = count($tagArray); if ($numTags == 0) { return $retarr; // Return empty set of matches } $tagList = join(',', $tagArray); $sql = "SELECT matches.object_id, COUNT( matches.object_id ) AS num_common_tags FROM ${prefix}freetagged_objects as matches INNER JOIN ${prefix}freetags as tags ON ( tags.id = matches.tag_id ) WHERE tags.tag IN ($tagList) GROUP BY matches.object_id HAVING num_common_tags >= $threshold ORDER BY num_common_tags DESC LIMIT 0, $max_objects "; $rs = $this->db->query($sql); if($this->db->isError($rs)) { $this->show_debug_text($rs); } $i = 0; while($rows = $rs->fetchRow()) { $retarr[] = array ( 'object_id' => $rows['object_id'], 'strength' => ($rows['num_common_tags'] / $numTags), ); $i++; } return $retarr; } /* * Prints debug text if debug is enabled. * * @param string/Error Object * @param boolean default:FALSE * @return boolean Always returns true */ function show_debug_text($er, $EndFlag= FALSE) { $DebugMesage = ""; if(is_object($er) && $this->db->isError($er)) { $DebugMesage = $er->getMessage(); } elseif(!is_object($er) && $er != "") { $DebugMesage = $er; } if($EndFlag) { echo $DebugMesage; exit(); } else { if($this->_debug) { echo $DebugMesage; } } return TRUE; } } ?>