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


//	B: Discussion Page
class CLASScomment extends dbPage{
	var $objectType = 'comment';

	var $subject;
	var $prefix;
	var $parent_id;
	var $checkOwner = false;
	var $CanHaveChildren = false;

	
	var $dbValues = array('owner'=>1,'title'=>1,'subject'=>1,'prefix'=>1,'content'=>1,'parent_id'=>1);
	var $userValues = array('content'=>1,'keywords'=>1);
	var $pathLen = array('title'=>40,'subject'=>40);
	
	function CLASScomment(){
		$this->commands['hide'] = false;
		$this->commands['append'] = true;
		$this->commands['comments'] = false;
		
		$this->setDbInfo();
	}
	
	
	function newPage(){
		global $langA;
		parent::newPage();
		
		$this->editable = $this->checkParent();
		
		if( $this->editable ){
			global $page;
			$this->content = $langA['DEFAULT_CONTENT'];
			if( empty($page->userCmd) && cookies() ){
				$page->userCmd = 'edit';
			}
			
		}else{
			$this->content = $langA['DEFAULT_CONTENT_PROTECTED'];
		}
	}
	
	//
	//	check the parent file
	//		-	it must exist
	//		-	it must not have "nocomments" flag
	//
	function checkParent(){
		global $dbInfo,$wbTables;
		
		
		//parent object
		if( empty($this->prefix) ){
			$type = 'page';
		}else{
			$type = substr($this->prefix,0,-1);//get rid of "/" char
		}
		if( !isset($dbInfo[$type]) ){
			return false;
		}
		if( !isset($dbInfo[$type]['dbTable']) ){
			return false;
		}
		$parInfo = $dbInfo[$type];
		wbData::newObject($type,$tempObj,true);

		
		//create query
		$query = 'SELECT `flags`, '.$wbTables['all_files'].'.`file_id` as `file_id` ';
		$query .= ', FIND_IN_SET("nocomments", '.$wbTables['all_files'].'.`flags`) AS `found` ';
		$query .= ' FROM '.wbData::dbInfo($type,'queryFrom');
		$query .= ' INNER JOIN '.$wbTables['all_files'];//join to all_files needs to be last!
		$query .= ' ON '.$wbTables['all_files'].'.`file_id` = '.$parInfo['dbTable'].'.`file_id` ';
		$query .= ' WHERE ';
		$tempObj->setKeys($this->pathArray);
		$query .= $tempObj->where($tempObj->dbInfo['dbTable']);
		$query .= ' LIMIT 1';
		
		
		//run query
		$result = wbDB::runQuery($query);
		$num = mysql_num_rows($result);
		if( $num != 1){
			return false;
		}
		$row = mysql_fetch_assoc($result);
		$this->parent_id = $row['file_id'];
		if($row['found'] > 0 ){
			return false;
		}
		return $this->editable;
	}
	
	
	function setKeys(&$pathArray){
		
		
		if( !empty($pathArray['type2']) ){
			$this->prefix = $pathArray['type2'].'/';
		}
		
		if( empty($pathArray['owner']) ){
			$this->owner = $GLOBALS['wbConfig']['pUser'];
		}else{
			$this->owner = $pathArray['owner'];
		}
		
		if( isset($_POST['new_title']) ){
			$_POST['new_title'] = str_replace(array('/','\\'),array(''),$_POST['new_title']);
			array_push($pathArray['path'],$_POST['new_title']);
		}
		
		$this->pathArray = $pathArray;
		$subject = array_pop($this->pathArray['path']);
		
		if( is_numeric($subject) ){
			$this->file_id = $subject;
			
		}else{
			
			$this->subject = toStorage( $subject );
			$this->title = toStorage( implode('/',$this->pathArray['path']) );
			
			
			
			$temp = trim($this->title);
			if( empty($temp) ){
				$this->title = $this->subject;
				$this->subject = date('l,_F_j,_Y'); //$langA is not available yet
			}
		}
	}
			
	function setLinks(){
		global $page,$pageOwner,$langA;
		
// 		if( $this->exists && $this->editable ){
// 			$this->editLabel = 'Reply'; //$langA['edit'];
// 		}

		
		//Comment of which space
		$temp = $this->prefix.$this->owner.'/'.$this->title;
		$page->regLink(toDisplay($this->title),'/'.$temp);
		$page->regLink($langA['talk'],'/Talk/'.$temp);
		parent::setLinks();
		
		$page->regLink('?','Comments?en=Comments');

		
		//
		// Display Title
		//
		
		if( is_numeric($this->title) ){
			if( empty($this->prefix) ){
				$type = 'page';
			}else{
				$type = substr($this->prefix,0,-1);
			}
			
			$dTitle = wbData::dbInfo($type,'dTitle');
			$dbTable = wbData::dbInfo($type,'dbTable');
			
			$query = 'SELECT ';
			$query .= wbData::getDTitle($type);
			$query .= ' FROM '.$dbTable;
			$query .= ' WHERE `file_id` ="'.$this->title.'" ';
			$query .= ' LIMIT 1 ';
			$result = wbDB::runQuery($query);
			if($row  = mysql_fetch_assoc($result) ){
				$page->displayTitle = $row['dTitle'].' > '.$langA['talk'].' > '.toDisplay($this->subject);
				return;
			}
		}
		
		if( !empty($this->prefix) ){
			$temp = substr($this->prefix,0,-1);
			if( isset($langA[$temp]) ){
				$page->displayTitle = $langA[$temp];
			}else{
				$page->displayTitle = toDisplay($temp);
			}
			$page->displayTitle .= ' > ';
		}
		$page->displayTitle .= toDisplay($this->title).' > '.$langA['talk'].' > '.toDisplay($this->subject);

		
	}
	
	function checkKeys(){
		if( isset($_POST['quicksave']) ){
			$this->checkSubject();
		}
		parent::checkKeys();
	}
	
	function doActions(){
		global $page,$langA;
		
		//quicksave changes
		if( !empty($page->userCmd) && isset($_POST['quicksave']) ){
			
			switch( $page->userCmd ){
				case 'save':
				case wbStrtolower($langA['save']):
					if( (strpos($this->flags,'captcha') !== false)
						&& ($this->editable === 1)
						){
							$this->quickCaptcha();
							return;
					}else{
						
						$this->setUniqLink();
						if( !isset($_SESSION['editPage'][$this->uniqStorage]) ){
							$_SESSION['editPage'][$this->uniqStorage] = '';
						}
					}
				break;
				case 'continue':
			 		$this->setFromPost();
			 		$page->userCmd = 'edit';
				break;
				
				case 'preview':
				case wbStrtolower($langA['preview']):
					unset($_GET['wb']['u']); //prevent the "save now" link from showing
				break;
				
			}
		}
		
		parent::doActions();
	}
	
	function quickCaptcha(){
		global $page,$langA;
		
 		$this->setFromPost();
 		$field = $this->getOutputField();
		$page->autoForm = true;
		includeFile('tool/EditPage.php');
		fileEdit::init();

		ob_start();
		echo '<table style="margin:1em auto 1em auto"><tr><td style="text-align:center">';
 		fileEdit::captchaHTML();
 		echo '<input type="hidden" name="summary" value="" />';
 		echo '<input type="hidden" name="content" value="'.wbHtmlspecialchars($_POST['content']).'" />';
 		echo '<input type="submit" name="cmd" value="'.$langA['save'].'" />';
 		echo '</td></tr></table>';
 		$page->contentB[$this->uniqLink] = wb::get_clean();
 		
	}
	
	function setUniqLink(){
		parent::setUniqLink();
		$this->uniqLink = str_replace('//','/',$this->uniqLink); //hack for comments with prefixes since prefixes have "/"
	}
			


	
	function checkSubject(){
		global $page;
		$this->setUniqLink();
		
		if( isset($_SESSION['editPage']) && is_array($_SESSION['editPage']) ){
			if( array_key_exists($this->uniqStorage, $_SESSION['editPage'] ) ){
				return; //don't change the title
			}
		}
		
		$pos = wbStrpos($this->subject,'?');
		if( $pos !== false){
			$this->subject = wbSubstr($this->subject,0,$pos);
		}
		
		//check for exact match
		$query = 'SELECT `subject` FROM '.$this->dbInfo['dbTable'];
		$query .= ' WHERE ';
		$query .= ' owner = "'.wbDB::escape($this->owner).'" ';
		$query .= ' AND title = "'.wbDB::escape($this->title).'" ';
		$query .= ' AND prefix = "'.wbDB::escape($this->prefix).'" ';
		$query .= ' AND subject = "'.wbDB::escape($this->subject).'" ';
		$result = wbDB::runQuery($query);
		$num = mysql_num_rows($result);
		if( $num === 0){
			return;
		}
		$this->validData = false;
		message('TITLE_EXISTS');
		$page->userCmd = '';
		unset($_POST['quicksave']);
		
		
	//if the subject already exists.. then just add a number to the end..
	//	if unchecked, a user could potentially abuse this and add many comments by resubmitting the same form..
	//	see "flood check" in toolSavePage.php for more info
	//
		
		// //RPAD(str,len,padstr)
		// $select = ' LPAD( REPLACE( REPLACE(`subject`,"'.wbDB::escape($this->subject).'_(",""),")",""),10,"0") as number ';
		
		// $query = 'SELECT `subject`, '.$select.' FROM '.$this->dbInfo['dbTable'];
		// $query .= ' WHERE ';
		// $query .= ' owner = "'.wbDB::escape($this->owner).'" ';
		// $query .= ' AND title = "'.wbDB::escape($this->title).'" ';
		// $query .= ' AND prefix = "'.wbDB::escape($this->prefix).'" ';
		// $query .= ' AND subject LIKE "'.wbDB::escape($this->subject).'\_(%)" '; //auto_indexed subject fields will always be "<subject> (##)"
		// $query .= ' ORDER BY `number` DESC LIMIT 1';
		
		// $result = wbDB::runQuery($query);
		// $num = mysql_num_rows($result);
		// if($num  === 0){
		// 	$this->subject .= '_(1)';
		// 	return;
		// }
		// $row = mysql_fetch_assoc($result);
		// $number = (int)$row['number'];
		// $this->subject .= '_('.($number+1).')';
	}
	
	//used for blog
	function abbrevOutput(&$row){
		global $langA,$page;
		
		
		$links = array();
		$links[$langA['comment']] = $row->uniqLink;
		//$links[$langA['reply']] = '/Edit'.$row->uniqLink.'?cmd=edit';
		$links[$langA['talk']] = '/Talk/'.$row->owner.'/'.$row->title;
		
		echo '<h2 class="heading underline">';
		echo wbLinks::local($row->uniqLink, toDisplay($row->subject) );
		//echo wbLinks::local($row->uniqLink, toDisplay($row->title).' > '.toDisplay($row->subject) );
		echo '</h2>';
		
		echo ' <div class="fileInfo">';
		
			echo '<span>';
			$temp = Array();
			foreach($links as $key => $value){
				if( is_string($value) ){
					$temp[] = wbLinks::local($value,$key);
				}
			}
			echo implode(' :: ',$temp);
			echo '</span>';

			
			echo '<span>'.$langA['modified'].': '.dbFromDate($row->modified,3).'</span>';
			echo '<span>'.$langA['created'].': '. dbFromDate($row->created,3).'</span>';
		echo ' </div>';			

		CLASSpage::abbrevOutputContent($row);
	}
	
/*
	function outputObj($link=true){
		global $langA,$page;
		$link = parent::outputObj($link);
		
		if( $this->exists && $this->editable ){
			$page->contentB[$link] .= wbLinks::Local('/Edit'.$this->uniqLink.'?cmd=edit',$langA['reply']);
		}
		
		return $link;
	}
*/
	
	
}
