<?php
defined('WikyBlog') or die("Not an entry point...");

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///	Keywords/Tags	//////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//

//	
//	Updates the $pageOwner array of keywords
//	Called from toolOptions.php, toolSavePage.php, toolDelete.php 
//
function updateTags($delete,$add,$keywords=false){
	global $page;
	
	//if keywords aren't supplied, use $pageOwner
	if( $keywords===false ){
		global $pageOwner;
		$keywords =& $pageOwner['keywords'];
	}
	
	if($delete === $add){
		return;
	}
	
	$page->keywords = true;
	$delete = wbExplode(',',$delete);
	$add = wbExplode(',',$add);
	$del = array();
	$prev = '';
	$deleteDirs = array();
	$addDirs = array();

	
	if( !is_array($keywords) ){
		$keywords = array();
	}
	
	//Clean the Add Values
	foreach($add as $value){
		$value = trim($value,": \t\n\r\0\x0B"); //normal trim with ":" character
		
		if( empty($value) ){
			continue;
		}
		if( $pos = wbStrpos($value,':') ){
			$dir = wbSubstr($value,0,$pos);
			$addDirs[$dir] = 1;
		}
		$addDirs[$value] = 1;
	}
	//Do The Adding
	foreach( $addDirs as $value => $null){
		if( isset($keywords[$value]) ){
			$keywords[$value]++;
		}else{
			$keywords[$value] = 1;
		}
	}
	
	//Clean The Delete Values
	foreach( $delete as $value){
		$value = trim($value,": \t\n\r\0\x0B");//normal trim with :
		if( empty($value) ){
			continue;
		}
		
		$dir = $value;
		if( $pos = wbStrpos($value,':') ){
			$dir = wbSubstr($value,0,$pos);
			$deleteDirs[$dir] = 1;
		}
		$deleteDirs[$value] = 1;
	}
	
	//Do The Deleting
	foreach( $deleteDirs as $value => $null){
		if( isset($keywords[$value]) ){
			$keywords[$value]--;
		}else{
			$keywords[$value] = -1;
		}
	}		
	
	if( !is_array($keywords) ){
		return;
	}
	
	//sort
	//case insensitive, unless they are equal
	uksort($keywords,'strnatcasecmp2');
	
	//rearrange
	//this joins keys that are only different because of case
	foreach($keywords as $keyword => $num){
		if( (strnatcasecmp($prev,$keyword) === 0) && ($prev !== $keyword) ){
			
			$keywords[$prev] += $num;
			unset( $keywords[$keyword] );
			if( $keywords[$prev] < 1){
				$del[$prev] = true;
			}
			
		}else{
			$prev = $keyword;
		}
		
		if( $num < 1){
			$del[$keyword] = true;
		}
	}
	
	foreach($del as $key => $bool){
		unset($keywords[$key]);
	}
	if( $keywords !==false ){
		return $keywords;
	}
}



//used by updateTags() function
//order is rather important
//had to do this so that capital/lowercase were ordered consistently
function strnatcasecmp2($a,$b){
	$comparison = strnatcasecmp($a,$b);
	if( $comparison === 0){
		$comparison = strnatcmp($a,$b);
		if( $comparison === 0 ){
			return strcmp($a,$b);
		}
	}
	return $comparison;
}