<?php 

require_once('../config.php');

$test = tag_create(" abcd ,coooltag cOOol, blah, MoOdLe ");
tag_delete('abcd ,coooltag coool, blah, moodle');

tag_an_item('user','3','coool guy, yeah');
tag_an_item('user','4','coool guy, aaaa');
tag_an_item('user','3','coool guy');
//untag_an_item('user','3','coool guy, helll yeah');

$tes = get_items_tagged_with('user','coool guy');

$a = 1;

/**
 * Creates tags
 * 
 * Ex: tag_create('A VeRY   cOoL    Tag, Another NICE tag')
 * will create the following normalized entries in tag_names table: 
 * 		'a very cool tag'  
 *  	'another nice tag'
 * 
 * @param string $tag_names_csv CSV tag names (can be unnormalized) to be created.
 * @param string $tag_type type of tag to be created ("default" is the default value).
 * @return an array of tags, indexed by their normalized names
 */
function tag_create($tag_names_csv, $tag_type="default")
{
	$normalized_tag_names_csv = tag_normalize($tag_names_csv) ;
	
	$tags = explode(",", $normalized_tag_names_csv );

	$tag_object = new StdClass;
	$tag_object->type = $tag_type;

	foreach ($tags as $tag_name) {

		$tag_object->name = $tag_name;

		if ( !record_exists('tag_names', 'name', $tag_name) ) {
			insert_record('tag_names', $tag_object);
		}
	}

	return tag_id($normalized_tag_names_csv);

}

/**
 * Delete tags
 * 
 * Ex: tag_delete('A VeRY   cOoL    Tag, Another NICE tag')
 * 	Will delete the tag entries with the following names (if they exist!) from the 
 * 	tag_names table: 
 * 		'a very cool tag'  
 *  	'another nice tag'
 * 
 * 
 * @param string $tag_names_csv >>normalized<< CSV tag names to be deleted.
 */

function tag_delete($tag_names_csv)
{

	$tags = explode(",", $tag_names_csv);

	foreach ($tags as $tag_name) {

		delete_records('tag_names', 'name', trim($tag_name));

	}

}

/**
 * Get all the tags from the records
 *
 * @param string $tag_type (optional, default value is "default").
 */
function get_all_tags($tag_type="default")
{
	get_records_list('tagn_names','type', $tag_type);
}

/**
 * Determines if a tag exists
 *
 * @param string $tag_name >>normalized<< tag name to be checked.
 * @return true if exists or false otherwise
 * 
 */
function tag_exists($tag_name)
{
	record_exists('tag_names', 'name', $tag_name);
}


/**
 * Function that gets the ids of tags
 * 
 * Ex: tag_id('A VeRY   cOoL    Tag, Another NICE tag')
 * 
 * @param string $tag_names_csv CSV tag names (can be unnormalized).
 * @return an array of tags, indexed by their normalized names
 */

function tag_id($tag_names_csv)
{
	$tags = explode(",", tag_normalize($tag_names_csv));

	$tag_names_csv_with_apos = "'".implode("','", $tags)."'";
	
	return get_records_list('tag_names','name', $tag_names_csv_with_apos, "" , "name, id" );

}

/**
 * Associates a tag with an item
 * 
 * Ex: tag_an_item('user', '1', 'hisTOrY, RELIGIONS, roman' )
 * 	 This will tag an user whose id is 1 with "history", "religions", "roman"
 *   If the tag names passed do not exist, they will get created.
 * 
 * @param string $item_type name of the table where the item is stored. Ex: 'user'
 * @param string $item_id id of the item to be tagged
 * @param string $tag_names_csv CSV tag names (can be unnormalized).
 * @param string $tag_type type of the tags that are beeing added (optional, default value is "default")
 */

function tag_an_item($item_type, $item_id, $tag_names_csv, $tag_type="default")
{

	$tags_created = tag_create($tag_names_csv,$tag_type);

	$tagging = new StdClass;
	$tagging->itemtype = $item_type;
	$tagging->itemid = $item_id;

	if (is_array($tags_created)) {
		foreach ($tags_created as $tag){
			$tagging->tagid = $tag->id;
			insert_record('tag_taggings',$tagging);
		}
	}

}

/**
 * Removes the association of an item with a tag
 * 
 * Ex: untag_an_item('user', '1', 'history, religions, roman' )
 * 	 The user with id 1 will no longer be tagged with 'history', 'religions' and 'roman'
 * 
 * @param string $item_type name of the table where the item is stored. Ex: 'user'
 * @param string $item_id id of the item to be untagged
 * @param string $tag_names_csv >>normalized<< CSV tag names. (optional, 
 * 									if none is given all tags of the item will be removed)
 */

function untag_an_item($item_type, $item_id, $tag_names_csv="")
{
	if ($tag_names_csv == ""){

		delete_records('tag_taggings','itemtype', $item_type, 'itemid', $item_id);

	}
	else {
		
		$tags_id = tag_id($tag_names_csv);

		$tags_id_csv = "'";
		foreach($tags_id as $tag) {
			$tags_id_csv = $tags_id_csv.$tag->id."','";
		}
		$tags_id_csv = substr($tags_id_csv,0,-2);

		delete_records_select('tag_taggings', 
			"tagid IN ($tags_id_csv) AND itemtype='$item_type' AND itemid='$item_id'");
	}


}

/**
 * Function that gets the tags that are associated with an item
 * 
 * Ex: get_item_tags('user', '1')
 * 
 * @param string $item_type name of the table where the item is stored. Ex: 'user'
 * @param string $item_id id of the item beeing queried
 * @return mixed an array of objects, or false if no records were found or an error occured.
 */

function get_item_tags($item_type, $item_id)
{
	global $CFG;
	$query = "
		SELECT
			tn.id,
			tn.name,
			tn.type 
		FROM 
			{$CFG->prefix}tag_taggings tt
		INNER JOIN
			{$CFG->prefix}tag_names tn
		ON
			tn.id = tt.tagid
		WHERE 
			tt.itemtype = '{$item_type}' AND
			tt.itemid = '{$item_id}'";
	
	return get_records_sql($query);

}

/**
 * Function that gets all the items of a certain type associated with a certain tag
 * 
 * Ex: get_items_tagged_with('user', 'bANAana')
 * 
 * @param string $item_type name of the table where the item is stored. Ex: 'user'
 * @param string @tag_name is a single tag name (can be unormalized)
 * @return mixed an array of objects, or false if no records were found or an error occured.
 */

function get_items_tagged_with($item_type, $tag_name)
{
	global $CFG;
	
	$tag_name = tag_normalize($tag_name);
	$tag_id = tag_id($tag_name);
	$tag_id = $tag_id[$tag_name]->id;
	
	$query = "
		SELECT
			it.* 
		FROM 
			{$CFG->prefix}{$item_type} it
		INNER JOIN
			{$CFG->prefix}tag_taggings tt
		ON
			it.id = tt.itemid
		WHERE 
			tt.itemtype = '{$item_type}' AND
			tt.tagid = '{$tag_id}' ";
	
	
	return get_records_sql($query);
	
}


function is_item_tagged_with($item_type,$item_id, $tag_name)
{

}


/**
 * Function that normalizes a tag name
 * 
 * Ex: tag_normalize('bANAana')   -> returns 'banana'
 * 	   tag_normalize('lots    of    spaces') -> returns 'lots of spaces'
 * 	   tag_normalize('%!%!% non alpha numeric %!%!%') -> returns 'non alpha numeric'
 * 	   tag_normalize('tag one,   TAG TWO, TAG three, and anotheR tag') 
 * 						-> returns 'tag one,tag two, tag three, and another tag' 
 * 					
 * @param string $tag_names_csv unnormalized CSV tag names
 * @return string $tag_names_csv >>normalized<< CSV tag names
 */

function tag_normalize($tag_names_csv)
{

	$tags = explode(",", $tag_names_csv);

	if(sizeof($tags) > 1) {

		foreach ($tags as &$tag) {
			$tag = tag_normalize($tag);
		}

		return implode("," , $tags);

	}
	// only one tag was passed
	else {
		// value is converted to lowercase and all non-alphanumeric caracters are removed
		$value = preg_replace('|[^a-z0-9 ]|i', '', strtolower(trim($tag_names_csv)));

		//make sure that between words there´s only one whitespace
		$value = preg_replace('|[\s]+|i', ' ', $value);

		return $value;
	}

}

function is_tag_clean($tag_names_csv)
{
	
}

?>
