<?php

defined('WikyBlog') or die("Not an entry point...");
wbLang::getFile('toolRename');

class copyRename{
	

	////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//			Copy
	//
	
	function copy(){
		global $dbObject,$page;
	
		$fromUrl = $dbObject->uniqLink;
		
		//	Signed in?
			if( !isset($_SESSION['username']) ){
				message('LOGIN_REQUIRED');
				return false;
			}
			
		//	Set New Values and test
			$toName = copyRename::newValues(false);
			if( $toName === false ){
				return;
			}
			
			$page->displayTitle = 'Copy to '.$toName;
			$dbObject->modified = '';
			
			message('COPY_TO',$fromUrl,$dbObject->uniqLink);
			includeFile('tool/EditPage.php');
			initEdit::init();
	}
	
	////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//			Rename
	//
	
	
	function rename(){
		global $langA,$wbTables,$dbObject,$wbNow, $page;
		$files = false;
		
		
		
		
		//Must be able to edit the file
			if( !$dbObject->editable ){
				message('PROTECTED_FILE');
				return false;
			}
			
		//	Going to need information for later insertion/creation of redirect
			$closeTab = $dbObject->uniqLink;
			$redirRow = $dbObject->keyArray();
			if( method_exists($dbObject,'setFileLocations')){
				$files = array();
				foreach($dbObject->files as $file => $nothing){
					$files[$file] = $dbObject->$file;
				}
			}
			
			$toName = copyRename::newValues();
			if( $toName === false ){
				return;
			}
		
		//	Rename the existing rows/files 
			if( is_array($files) ){
				$dbObject->setFileLocations();
				wbData::loadFileFunctions();
				foreach($files as $file => $oldName){
					if( !file_exists($oldName) ){
						continue;
					}
					if( !renameFile($oldName,$dbObject->$file) ){
						message('COULDNT_RENAMED');
						return false;
					}
				}
			}
		
		//
		//	Update the existing row
		//
		//		if the file was recently deleted.. this won't work..
		
			$query1 = 'UPDATE IGNORE /* rename() */ '.$wbTables['all_files'].', '.$dbObject->dbInfo['dbTable'];
			$query1 .= ' SET ';
			$query1 .= wbDB::toSet($dbObject->keyArray(),false,$dbObject->dbInfo['dbTable']);
			$query1 .= ' , '.$wbTables['all_files'].'.`info` = "'.wbDB::escape($dbObject->uniqLink).'" ';
			$query1 .= 'WHERE '.$wbTables['all_files'].'.`file_id`="'.$dbObject->file_id.'"';
			$query1 .= ' AND '.$dbObject->dbInfo['dbTable'].'.`file_id` = '.$wbTables['all_files'].'.`file_id` ';
		
			$num = wbDB::runQuery($query1,true);
			
			if( $num < 1 ){
				message('NOT_RENAMED',$toName);
				return false;
			}
			
			message('RENAMED');
			$field = $dbObject->outputObj();
			$dbObject->addFooter($field);
			
		//
		//	Changed to/from Template:
		//
			copyRename::templateChange($toName);
			
			
		//
		//	Insert Redirect Page
		//
			//if the name change is only a case change then we don't want to do this
			$check2 = $dbObject->keyArray();
			$check2 = implode('\\',$check2);
			$check1 = implode('\\',$redirRow);
			if( wbStrcasecmp($check2,$check1) ){
				return;
			}
			
			
		
			$allFilesRow = array();
			$allFilesRow['username'] = $_SESSION['username'];
			$allFilesRow['created'] = $wbNow;
			$allFilesRow['modified'] = $wbNow;
			$allFilesRow['posted'] = $wbNow;
			$allFilesRow['flags'] = 'safe,redirect,locked'; //only the owner can remove the redirect, since only the owner can rename
			$allFilesRow['info'] = $dbObject->uniqLink;
			$allFilesRow['keywords'] = '';
			$allFilesRow['owner_id'] = $dbObject->owner_id;
			wbDB::dbInsert2($wbTables['all_files'],$allFilesRow);
			
			
			$newId = mysql_insert_id();
			$redirRow['file_id'] = $newId;
			$redirRow['summary'] = $langA['redirected_to'].' '.$dbObject->uniqLink;
			
			//try to avoid MySQL Warnings for columns without default values
			foreach($dbObject->dbValues as $key => $null ){
				if( !isset($redirRow[$key]) ){
					$redirRow[$key] = $dbObject->$key;
				}
			}
			wbDB::dbInsert2($dbObject->dbInfo['dbTable'],$redirRow);
			
			
		//
		//	Affected Comments
		//
			if( $dbObject->comments > 0 ){
				copyRename::renameComments($dbObject);
			}
			
			
		//
		//	all_links
		//		1) Change the to_id for the old title
		//		2) Update to_id rows with new title
		
			$query = 'UPDATE '.$wbTables['all_links'];
			$query .= ' SET `to_id` = "'.$newId.'" ';
			$query .= ' WHERE `to_id` = "'.$dbObject->file_id.'" ';
			wbDB::runQuery($query);
			
			$query = 'UPDATE '.$wbTables['all_links'];
			$query .= ' SET `to_id` = "'.$dbObject->file_id.'" ';
			$query .= ' WHERE `to_link` = "'.wbDB::escape($dbObject->uniqStorage).'" ';
			wbDB::runQuery($query);
			
			
		//
		//	Try to close the old tab
		//	
		//	
		if( $page->ajaxRequest ){
			
			//place the renamed page directly after the old title
			$page->prevTab = toStorageUrl($closeTab);
			
			
			$addContent = new content();
			$addContent->aa = 'eval';
			//$addContent->bb = 'var ids = Array();ids[0] = "'.$_GET['wb']['u'].'";wbCA.close2(ids);';
			$addContent->bb = 'wbCA.close2(Array("'.toStorageUrl($closeTab).'"));';
			
			//close the options tab as well
			//$optionsTab = '/Edit'.$closeTab.'?cmd=options';
			//$addContent->bb = 'wbCA.close2(Array("'.toStorageUrl($closeTab).'","'.toStorageUrl($optionsTab).'"));';
			
			$addContent->bb .= 'WBt.go("'.toStorageUrl($dbObject->uniqLink).'");';  //show the new tab.. since the close2() call will change which tab is shown
			$page->contentClasses[] = $addContent;
		}
	}
	
	function renameComments(&$object){
		devMessage('update comments!');
		
		//	Which title
			end($object->dbInfo['keys']);
			$key = key($object->dbInfo['keys']);
			reset($object->dbInfo['keys']);
			$title = $object->$key;
			
			$query = 'UPDATE '.wbData::dbInfo('comment','dbTable');
			$query .= ' SET ';
			$query .= ' `title` = "'.wbDB::escape($title).'" ';
			$query .= ' WHERE ';
			$query .= ' `parent_id` = "'.wbDB::escape($object->file_id).'" ';
			message($query);
			wbDB::runQuery($query);
			
	}
	
	
	//
	//	Changed to/from Template:
	//
	function templateChange($toName){
		global $page,$dbObject,$wbTables;
		$nowTemplate = $wasTemplate = false;
		
		if( $dbObject->objectType !== 'page'){
			return;
		}
		
		$temp = strtolower($toName);
		if( strpos($temp,'template:') === 0){
			$nowTemplate = true;
		}
		if( strpos($dbObject->flags,'template') !== false ){
			$wasTemplate = true;
		}
		if( $nowTemplate === $wasTemplate ){
			return;
		}
		
		$query = 'UPDATE IGNORE '.$wbTables['all_files'].' SET ';
		$query .= ' `modified` = `modified` ';
		
		if( $nowTemplate ){
			$query .= ' , `flags` = '. wbDB::add_to_set('template','`flags`');
		}else{
			$query .= ' , `flags` = '. wbDB::remove_from_set('template','`flags`');
		}
		
		//$query .= ', `flags` = "'.wbDB::escape($dbObject->flags).'" ';
		$query .= 'WHERE `file_id`="'.$dbObject->file_id.'" ';
		$query .= ' LIMIT 1';
		wbDB::runQuery($query);
		
	}

	
	
	////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//			Set New Values for object
	//
	function newValues($caseSensitive=true){
		global $dbObject,$wbTables,$page;
		
		//	Which key
			end($dbObject->dbInfo['keys']);
			$key = key($dbObject->dbInfo['keys']);
			reset($dbObject->dbInfo['keys']);
			
			$toName = $_POST['to'];
			$toName = toStorage($toName);
			if( wbStrpos($toName,'../') !== false){
				message('INVALID_PATH',$toName);
				return false;
			}
			
			//	compare case sensitive (space-insensitive)
			// 	copy should use a case insensitive test
			
			if( $caseSensitive ){
				$checkAgainst = toStorage($dbObject->$key);
				
				//just different case?
				//	rename to different cases aren't working because the sql queries won't change anything (the varchar fields are not case sensitive, so MySQL determines nothing is changing)
				if( wbStrcasecmp($checkAgainst,$toName) ){
					return false;
					return $toName;
				}
				
				if( $checkAgainst == $toName){ 
					message('NAME_UNCHANGED');
					return false;
				}
			}else{
				if( toStorage($dbObject->$key,true) ==  wbStrtolower($toName)){
					message('NAME_UNCHANGED');
					return false;
				}
			}
			
		//
		//	Reset the key information 
		//
			$dbObject->$key = $toName;
			$page->cLinks = array();
			//$dbObject->links = array();//need to reset it, should probably be in the $dbObject setLinks function
			$dbObject->setUniqLink();
			$dbObject->checkKeys();
			$dbObject->setLinks();
		
			if( !$dbObject->validData ){
				message('COULDNT_RENAMED');
				return false;
			}
			
		//	Check for existence
			$query = 'SELECT `modified`, '.$dbObject->dbInfo['dbTable'].'.`file_id` FROM '.$dbObject->dbInfo['dbTable'];
			$query .= ' LEFT JOIN '.$wbTables['all_files'];
			$query .= ' USING(`file_id`) ';
			$query .= ' WHERE ';
			$query .= $dbObject->where($dbObject->dbInfo['dbTable'],false);
			$query .= ' LIMIT 1 OFFSET 0';
			$result = wbDB::runQuery($query);
			$num = mysql_num_rows($result);
			if($num == 1){
				$row = mysql_fetch_assoc($result);
				if(empty($row['modified']) && !empty($row['file_id']) ){
					
					//the file doesn't really exists, so we just purge the content table similar to what we do in scheduledTasks.php
					$query = 'DELETE ';
					$query .= $dbObject->dbInfo['dbTable'];
					$query .= ' FROM ';
					$query .= $dbObject->dbInfo['dbTable'].' LEFT JOIN '.$wbTables['all_files'];
					$query .= ' USING(`file_id`) ';
					$query .= ' WHERE '.$wbTables['all_files'].'.`file_id` IS NULL ';
					wbDB::runQuery($query);
				}else{
					message('TITLE_EXISTS');
					return false;
				}
			}
			
			
		return $toName;
	}
	
	
		
}


global $dbObject,$langA;
if( !cookies() ){
	message('COOKIES_REQUIRED');
	return;
}


switch( $page->userCmd ){
	case 'rename':
		copyRename::rename();
	break;
	case 'copy':
		copyRename::copy();
	break;
}
