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


class fileComments{

	
	
	
	function updateAll(&$object){
		global $wbTables, $wbTablePrefix;
			
			$array = array();
			
			if( $object->objectType == 'comment' ){
				$parent_id = fileComments::getParentId(&$object);
				$array['prefix'] = $object->prefix;
				
			}else{
				$parent_id = $object->file_id;
				if( $object->objectType !== 'page' ){
					$array['prefix'] = $object->objectType.'/';
				}else{
					$array['prefix'] = ''; //for page
				}
			}
				
			$array['owner'] = $object->owner;
			$array['title'] = $object->title;
			
	
			//update parent_id
			$query = 'UPDATE '.wbData::dbInfo('comment','dbTable');
			$query .= ' SET ';
			$query .= ' `parent_id` = '.$parent_id;
			$query .= ' WHERE ';
			$query .= wbDB::toQuery($array,'AND',true);
			$num = wbDB::runQuery($query,true);
			//message('udated '.$num);
			
		$object->comments = fileComments::updateByFileId($parent_id);
	}
		
	function getParentId(&$object){
		
		//get parent id
		$object->checkParent();
		return $object->parent_id;
	}
	
	
			
	function updateByFileId($file_id){
		global $wbTables, $wbTablePrefix;
		$file_id = (int)$file_id;
		$comments = 0;
		
		
			//count comments
			$object->comments = 0;
			$query = 'SELECT COUNT(*) as count FROM '.wbData::dbInfo('comment','dbTable');
			$query .= ' INNER JOIN '.$wbTables['all_files'].' USING(`file_id`) WHERE ';
			$query .= ' `parent_id` = '.$file_id;
			$query .= ' AND '.$wbTables['all_files'].'.`visible` = 1 ';					//deleted, hidden and relvisible flags
			$query .= ' AND !FIND_IN_SET("redirect", '.$wbTables['all_files'].'.`flags`) ';
			$result = wbDB::runQuery($query);
			if( $row = mysql_fetch_assoc($result) ){
				if( (int)$row['count'] > 0){
					$comments = (int)$row['count'];
				}
			}
			
			//update comment count
			$query = 'UPDATE '.$wbTables['all_files'];
			$query .= ' SET `modified` = `modified` ';
			$query .= ', `comments` =  '.$comments;
			$query .= ' WHERE `file_id` = '.$file_id;
			$result = wbDB::runQuery($query);
			
			//update comment count for comments
			$query = 'UPDATE '.$wbTables['all_files'];
			$query .= ' JOIN '.wbData::dbInfo('comment','dbTable');
			$query .= ' USING(`file_id` )';
			$query .= ' SET `modified` = `modified` ';
			$query .= ', `comments` =  '.$comments;
			$query .= ' WHERE `parent_id` = '.$file_id;
			$result = wbDB::runQuery($query);
			
			//message('found '.$comments.' comments');
		
		return $comments;

	}
	
}