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

/*

A Note to Developers
====================
With version 1.7.1a of WikyBlog, the `all_blog` table was added to cache the abbreviated output of blogged files.
The downside of caching this content primarily affects developers in that changes made to abbrevOutput() methods
won't be immediately seen unless the `all_blog` table is purged/truncated.

*/

class BlogContent{
	
	function blogQuery($calc=false,$allFiles=array()){
		global $wbTables,$pageOwner;
		
		$query = 'SELECT /* BLOG QUERY */ ';
		if( $calc ){
			$query .= ' SQL_CALC_FOUND_ROWS ';
		}
		$query .= ' `modified`, `created`, `flags`, ';
		$query .= $wbTables['all_files'].'.`file_id`, ';
		$query .= $wbTables['all_files'].'.`owner_id`, ';
		$query .= $wbTables['all_files'].'.`info`, ';
		foreach($allFiles as $key){
			$query .= $wbTables['all_files'].'.`'.$key.'`, ';
		}
		$query .= ' `content` ';
		$query .= ' FROM ';
		$query .= $wbTables['all_files'];
		$query .= ' LEFT JOIN ';
		$query .= $wbTables['all_blog'];
		$query .= ' USING (`file_id`) ';
		$query .= ' WHERE '.$wbTables['all_files'].'.`owner_id` = "'.$pageOwner['user_id'].'" ';
		$query .= ' AND '.$wbTables['all_files'].'.`visible` = 1 ';
		
		if( isset($pageOwner['sBlog']) && ($pageOwner['sBlog'] == 'On') ){
			$query .= ' AND FIND_IN_SET("blogged", '.$wbTables['all_files'].'.`flags`) ';
		}else{
			$query .= ' AND !FIND_IN_SET("template", '.$wbTables['all_files'].'.`flags`) ';
			$query .= ' AND !FIND_IN_SET("redirect", '.$wbTables['all_files'].'.`flags`) ';
		}
		$query .= 'ORDER BY `posted` DESC ';
		return $query;
	}
	
	function blog($wrap=true){
		global $page, $pageOwner,$wbTables;
		static $included = false;
		
		//so the blog isn't shown twice on the home page
		if( $included ){
			return;
		}
		$included = true;
		
		$query = BlogContent::blogQuery();
		$query .= ' LIMIT '.$pageOwner['nBlog'];
		
		$result = wbDB::runQuery($query);
		$actualRowsFound = mysql_num_rows($result);
		
		ob_start();
		BlogContent::whileResult($result);
		
		if( $wrap ){
			//would need to change this if a blog is going to be more flexible.. different data types..
			if( ($actualRowsFound == $pageOwner['nBlog']) ){
				echo '<p>'.wbLinks::special('Blog?offset='.$pageOwner['nBlog'],'MORE_RECENT_POST').'</p>';
			}
		}
		
		return wb::get_clean();
	}
	
	
	function whileResult(&$result){
		global $page;
		
		
		while( $row = BlogContent::fetch_object($result) ){
			//set last-modified for each row
			if( is_array($row) && isset($row['modified'])){
				$page->setLastModified($row['modified']);
			}elseif( isset($row->modified) ){
				$page->setLastModified($row->modified);
			}
			
			if( strpos($row->content,'<h2 class="heading') !== 0 ){
				$row->title = basename($row->info);
				$row->uniqLink = $row->info;
				dbPage::abbrevOutputHeader($row); //needs uniqLink && title
			}else{
				//think about purging files if they have the header
			}
			echo $row->content;
		}
	}
	
	function fetch_object(&$result){
		$row = mysql_fetch_object($result);
		if( !$row ){
			return false;
		}
		if( empty($row->content) ){
			$row->content = BlogContent::getContent($row->file_id);
		}
		return $row;
	}
		

	
	function getContent($file_id){
		global $dbInfo, $wbTables;
		
		
		//figure out which space
		$query = 'SELECT '.$wbTables['all_files'].'.`file_id` ';
		$query .= ' , CASE ';
		$join = $wbTables['all_files'];
		foreach($dbInfo as $space => $info){
			if( !isset($info['dbTable']) ){
				continue;
			}
			$query .= ' WHEN '.$info['dbTable'].'.`file_id` IS NOT NULL THEN  "'.$space.'" ';
			$join .= ' LEFT JOIN '.$info['dbTable'];
			$join .= ' ON '.$wbTables['all_files'].'.`file_id` = '.$info['dbTable'].'.`file_id` ';

			//$query .= ' If( '.$info['dbTable'].'.`file_id` IS NOT NULL,
			//$query .= ' , "'.$space.'" ';
			
		}
		$query .= ' END AS `space` ';
		$query .= ' FROM '.$join;
		$query .= ' WHERE '.$wbTables['all_files'].'.`file_id` = "'.$file_id.'" ';
		$query .= ' LIMIT 1 OFFSET 0 ';
		$result = wbDB::runQuery($query);
		$row = mysql_fetch_assoc($result);
		$space = $row['space'];
		if( empty($space) ){
			//file was probably deleted
			return '';
		}
		
		
		//Get the content
		$query = 'SELECT /* BlogContent::getContent()  */ ';
		$query .= ' `modified`, `created`, `flags`, `owner_id` ';
		$query .= ', '.$wbTables['all_files'].'.`file_id` ';
		$query .= ', '.wbData::dbInfo($space,'querySelect');
		$query .= ', '.wbData::dbInfo($space,'uniqLink').' as uniqLink ';
		$query .= ' FROM ';
		$query .= wbData::dbInfo($space,'queryFrom');
		$query .= ' JOIN ';
		$query .= $wbTables['all_files'];//join to all_files needs to be last!
		$query .= ' ON '.$wbTables['all_files'].'.`file_id` = '.wbData::dbInfo($space,'dbTable').'.`file_id` ';
		$query .= ' WHERE '.$wbTables['all_files'].'.`file_id` = "'.$file_id.'" ';
		$result = wbDB::runQuery($query);
		$row = mysql_fetch_object($result);
		
		
		//update flag5
		$query = 'UPDATE '.$wbTables['all_files'];
		$query .= ' SET `modified` = `modified` ';
		$query .= ' , `flags` = '. wbDB::add_to_set('flag5','`flags`');
		$query .= ' WHERE '.$wbTables['all_files'].'.`file_id` = "'.$file_id.'" ';
		$result = wbDB::runQuery($query);
		
	
		//Get the class
		$class = wbData::getClass($space,true);
		return BlogContent::getFormattedContent(&$row,$class);
	}

	
	//new..
	function getFormattedContent(&$object,$class=false){
		global $pageOwner,$dbInfo;
		
		if( $class === false ){
			$class = get_class($object);
		}
		
		if( !is_callable(array($class,'abbrevOutputContent')) ){
			return false;
		}
		if( !BlogContent::bloggedObject($object,$class) ){
			return false;
		}
		
	
		ob_start();
		call_user_func(array($class,'abbrevOutputContent'),$object);
		return wb::get_clean();
	}

	function saveFromObject(&$object){
		global $pageOwner,$dbInfo,$wbTables;
		
		$content = BlogContent::getFormattedContent(&$object);
		if( $content === false ){
			return;
		}
		
		if( $pageOwner['lang'] !== $GLOBALS['userLanguage'] ){
			return; //!! this could make the service slow if the cache has to be purged a lot
		}
		
		$done = BlogContent::saveContent($object->file_id,$object->owner_id,$content);
	
		//update flag5
		if( $done ){
			$query = 'UPDATE '.$wbTables['all_files'];
			$query .= ' SET `modified` = `modified` ';
			$query .= ' , `flags` = '. wbDB::remove_from_set('flag5','`flags`');
			$query .= ' WHERE '.$wbTables['all_files'].'.`file_id` = "'.$object->file_id.'" ';
			wbDB::runQuery($query);
		}
		
	}
	
	function bloggedObject(&$object,&$class){
		global $pageOwner,$dbInfo;
		
		
		if( isset($pageOwner['sBlog']) && ($pageOwner['sBlog'] == 'On') ){
			if( strpos($object->flags,'blogged') === false ){
				return false;
			}
		}else{
			$blogT = $pageOwner['blogT'];
			if( strcasecmp( $dbInfo[$blogT]['class']  , $class  ) != 0 ){
				return false;
			}
		}	
		return true;
	}
		
	function saveContent(&$file_id,&$owner_id,&$content){
		global $wbTables;
		
		if( !is_numeric($file_id) || !is_numeric($owner_id) ){
			trigger_error('Not numeric value (owner_id:'.$owner_id.') (file_id:'.$file_id.')');
			return;
		}
			
		$query = 'REPLACE INTO ';
		$query .= $wbTables['all_blog'];
		$query .= ' SET ';
		$query .= ' `file_id` = "'.wbDB::escape($file_id).'" ';
		$query .= ' , `owner_id` = "'.wbDB::escape($owner_id).'" ';
		$query .= ' , `content` = "'.wbDB::escape($content).'" ';
		return wbDB::runQuery($query);

	}
	
	//
	//	Purging Cache
	//
	
	function purge(&$object){
		BlogContent::purgeParents($object);
		BlogContent::purgeIncluding($object);
		
	}

	
	//
	//	purges all_blog based on the title of a file
	//
	function purgeParents(&$object){
		global $pageOwner, $wbTables;
		
		//get the root for parents
		$keys = array_flip($object->dbInfo['keys']);
		$titleKey = end($keys);
		$field = $object->{$titleKey};
		
		$pieces = explode('/',$field);
		if( count($pieces) < 2 ){
			return;
		}
		
		
		//start the query
		$queryStart = 'DELETE /* BlogContent.php::purgeParents() */ ';
		$queryStart .= $wbTables['all_blog'];
		$queryStart .= ' FROM ';
		$queryStart .= $object->dbInfo['dbTable'].' JOIN '.$wbTables['all_blog'].' USING(`file_id`) ';
		$queryStart .= ' WHERE 1 ';
		foreach($object->dbInfo['keys'] as $key => $none){
			if( $key == $titleKey ){
				continue;
			}
			$queryStart .= ' AND `'.$key.'` = "'.wbDB::escape($object->{$key}).'" ';
		}
		
		
		
		//foreach level, run delete query
		$parentPieces = array();
		array_pop($pieces);
		foreach($pieces as $piece ){
			$parentPieces[] = $piece;
			$query = $queryStart;
			$query .= ' AND `'.$titleKey.'` = "'.wbDB::escape(implode('/',$parentPieces)).'" ';
			$num = wbDB::runQuery($query,true);
			//message('purged: '.$num);
		}
	}
	
	function purgeIncluding(&$object){
		global $wbTables, $dbInfo;
		
		///won't have including files if it's not a template
		if( strpos($object->flags,'template') === false ){
			return;
		}
		
		//start the query
		$query = 'DELETE /* BlogContent.php::purgeIncluding() */ ';
		$query .= $wbTables['all_blog'];
		$query .= ' FROM ';
		$query .= $wbTables['all_included'].' JOIN '.$wbTables['all_blog'].' USING(`file_id`) ';
		$query .= ' WHERE  ';
		$query .= $wbTables['all_included'].'.`incl_id` = "'.wbDB::escape($object->file_id).'" ';
		$num = wbDB::runQuery($query,true);
	}
	
}
