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



//	test: template
class CLASStemplate extends dbPage{
	// database values
	//var $objectType = 'template';

	
	//var $content; will contain the raw user data for $template
	//var $templateName; == title
	var $isTemplate = true;
	var $template;
	var $templateFileName;
	var $css1;
	var $css1FileName;
	var $css2 = false;
	var $css2FileName;
	var $tab_html = '';
	
	//var $keys = array('owner'=>1,'title'=>1);
	var $dbValues = array('owner'=>1,'title'=>1,'content'=>1,'tab_html'=>1);
	var $userValues = array('content'=>1,'css1'=>1,'css2'=>1,'keywords'=>1,'tab_html'=>1); //content is the raw user values
	var $files = array('templateFileName'=>1,'css1FileName'=>1,'css2FileName'=>1);
	
	//Translation
	var $translationArray = array();
	var $requiredVariables = array();
	var $oldTrans = array();
	var $toUser = array();
	var $toFile = array();
	
	
	var $varCharStart = '{{{';
	var $varCharEnd = '}}}';
	
	function CLASStemplate($type){
		$this->objectType = $type;
		$this->setDbInfo();
		
		//	Translations can be much simpler once the user values are stored in the database..
		//	we'll no longer have the need to translate back to the user.. won't need the Commented Translations
		//
		
		/////////////////////////////////////////////////////////////////////////////////////
		//
		//		Commented Translations
		//		<!-- DisplayPage --> ... <!-- DisplayPage -->
		//		The PHP Value can be changed whenever without affecting the translation
		//		.. also opens door for hack by injecting php code... just use the translationArray[] oldTrans[] and
		//
		//
		//				---User Value--      ---PHP Value--
		$this->newTranslation['Content'] = '<?php echo $page->displayPage() ?>';
		$this->newTranslation['ToolMenu'] = '<?php echo $page->displayActions(); ?>';
		$this->newTranslation['UserDir'] = '<?php echo "/userfiles/".toStorage($pageOwner["username"],true); ?>';
		$this->newTranslation['keywords'] = '<div id="WBkeywords"><?php getKeywords(); ?></div>';
		$this->newTranslation['UserMenu'] = '<div id="WBuserMenu"><?php getUserMenu(); ?></div>';
		$this->newTranslation['WBExtras'] = '<?php echo $page->extras; ?>';
		$this->newTranslation['PageFooter'] = '<?php echo $page->getFooter(); ?>';
		$this->newTranslation['WBSearch'] = '<?php echo $page->search(); ?>';
		
		//new values..
		//!!version V1.4.14
		$this->newTranslation['links'] = '<?php echo $page->getLinks(); ?>';
		$this->newTranslation['UserMenuNew'] = '<?php $page->userMenu(); ?>';
		$this->newTranslation['KeywordsNew'] = '<?php $page->getKeywords(); ?>';
		$this->newTranslation['NavBarNew'] = '<?php $page->getNavBar(); ?>';
		
		
				
		/////////////////////////////////////////////////////////////////////////////////////
		//
		//		Simple Translations
		//
		// Some have to stay with the older/simpler translation
		$this->translationArray['PageOwner'] = '<?php echo toDisplay($pageOwner["username"]); ?>';
		$this->translationArray['PageTitle'] = '<?php echo $page->displayTitle; ?>';
		$this->translationArray['PageTitle2'] = '<?php echo $page->displayTitle2; ?>';
		$this->translationArray['ServerName1'] = '<?php echo $serverName1; ?>';
		$this->translationArray['ServerName2'] = '<?php echo $serverName2; ?>';
		$this->translationArray['ServerName3'] = '<?php echo $serverName3; ?>';
		$this->translationArray['linkPrefix'] = '<?php echo $GLOBALS["wbLinkPrefix"]; ?>';
		
		
		
		//--------------	replace		------------------------	pattern		--------------------------------------
		
		//this needs to work for copying from package templates
		$this->toUser['[[specialLink:$1|$2]]'] = '#<\?php echo wbLinks::special\(\'([^\(\),]+)\',\'([^\(\),]+)\'\); \?>#';
		$this->toUser['[[localLink:$1|$2]]'] = '#<\?php echo wbLinks::local\(\'([^\(\),]*)\',\'([^\(\),]*)\'\); \?>#';
		$this->toUser['[[helpLink:$1|$2]]'] = '#<\?php echo wbLinks::help\(\'([^\(\),]+)\',\'([^\(\),]+)\'\); \?>#';
		$this->toUser['[[wbImage:$1]]'] = '#<\?php echo wbLinks::image\(\'([^\(\),]+)\'\); \?>#';
		
		
		//version ... phased out v1.1.5 2006-09-14
		//	this actually shouldn't pose a problem since we've been saving user displayable values in the database..
 		$this->toUser['[[SpecialLink:$1|$2]]'] = '#<\?php echo specialLink\(\'([^\(\),]+)\',\'([^\(\),]+)\'\); \?>#'; 
 		$this->toUser['[[LocalLink:$1|$2]]'] = '#<\?php echo localLink\(\'([^\(\),]+)\',\'([^\(\),]+)\'\); \?>#';
		
		/*--------------	replace		------------------------	pattern		--------------------------------------
		*/
		$this->toFile['formatTemplateLinks(\'$1\',\'$2\')'] = '#\[\[([a-z]*):([^\]]+?)\]\]#ie';

		
		
		// required
		$this->requiredVariables[] = 'Content';
		$this->requiredVariables[] = 'ToolMenu';
		//$this->requiredVariables[] = 'UserMenu';
		$this->requiredVariables[] = 'PageFooter';
		$this->requiredVariables[] = 'NavBarNew'; //used for map links
		$this->requiredVariables[] = 'WBExtras';
	}
	
	function setKeys(&$pathArray){
		parent::setKeys($pathArray);
/*
		if( is_numeric($this->title) ){
			message('numeric');
		}		
*/
		$this->setFileLocations();
	}
	
	function setFileLocations(){
		// set file locations
		global $rootDir;
		$temp = $rootDir.'/templates/'.wbStrtolower($this->owner.'/'.$this->title);
		
		wbData::loadFileFunctions();
		if( !checkPath($temp,'templates') ){
			$this->editable = false;
			return;
		}
		
		$this->css1FileName = $temp.'/style1.css';
		$this->css2FileName = $temp.'/style2.css';
		$this->templateFileName = $temp.'/template.php';
	}
		
	
	function setLinks(){
		global $page,$langA;
		
		$page->displayTitle = $langA['theme'].' > '.toDisplay($this->title);
		
		parent::setLinks();
		$page->regLink('?', $langA['theme']. '?en=Theme');
	}
	
	function getStep1(&$pathArray){
		parent::getStep1($pathArray);

		
		$this->setFileLocations(); //because cmd=delete uses the file_id not the title
		
		if(!$this->exists){
			$this->isTemplate = false;
			return;
		}
		$this->setFromDisk();
	}
	
	function setFromDisk(){
		//$_SESSION is not available here
		//$this->css1 = getContents($this->css1FileName);
		//$this->css2 = getContents($this->css2FileName);
		
		
		$this->template = getContents($this->templateFileName);
		$this->UpdateContent($this->template); //$this->template won't have any variables in user form at this state ... but we wan't it to be update so the check function doesn't report missing variables
		$this->UpdateContent($this->content);
		
		
		$this->css1 = getContents($this->css1FileName);
		
		$css2 = getContents($this->css2FileName);
		if( !empty($css2) ){
			$this->UpdateHead($this->content); //add rss feeds
			
			$this->css1 .= "\n".$css2;
			$this->css2 = true;
		}
		
	}
	
	function setFromPost(){
		global $wbParser,$langA;
		initiateParser();
		//$_SESSION is available here
		
		// don't user parent::setFromPost() because we parseXML($template) right away... 
		//	but this might change with saving the raw user input in the database
		//
		//	parent::setFromPost();
		// 		$this->setVariables( fromPost($_POST) , $this->userValues );

		globalFromPost();
		$this->setVariables($_POST , $this->userValues );
		
		//parseXML..
		//	should never have the 'safe' flag
		$this->template = $wbParser->parseXML($this->content,true,$this,true); //this is different for templates
		
		$this->getParserInfo();
		if( $wbParser && $wbParser->errors ){
			$link = wbLinks::local($this->uniqLink.'?cmd=viewErrors',$langA['syntax_error']);
		}
		
		$this->template =  $this->translateFromUser($this->template); //ok, which of these goes first!
		//$this->css1 =  $this->translateFromUser($this->css1);
		//$this->css2 =  $this->translateFromUser($this->css2);
		$this->css1 =  $this->translateFromUser($this->css1);
		
		
		// $this->validData = false;
		// message('To File: '.wbHtmlspecialchars($this->template));
		// message('To User: '.wbHtmlspecialchars($this->translateToUser($this->template)));
		
		if( $wbParser->errors ){
			$this->validData = false;
		}
	}
	
	function checkData(){
		global $langA;
		if( !empty($this->tab_html) && !is_numeric($this->tab_html) ){
			message('Invalid tab_html');
			$this->validData = false;
			return false;
		}
		
		//already found to be bad by setFromPost
		if( $this->validData === false){
			
			$link = wbLinks::local($this->uniqLink.'?cmd=viewErrors',$langA['syntax_error']);
			message('THEME_SYNTAX_WARN');
			includeFile('tool/Errors.php');
			return;
		}

		$missing = array();
		$warn = false;
		
		foreach($this->requiredVariables as $variable){
			
			$variable = $this->varCharStart.$variable.$this->varCharEnd;
			
			if( strpos($this->template,$variable) === false){
				$warn = true;
				$missing[] = wbHtmlspecialchars($variable);
				$this->validData = false;
			}
		}
		
		if( $warn ){
			message('THEME_MISSING_VARS',implode(', ',$missing));
			return;
		}
	}
	
	function newPage(){
		global $page,$langA;
		parent::newPage();
		
		$field = $this->uniqLink;
		
		if( $this->editable ){
			$page->contentB[$field] = $langA['THEME_DEFAULT_CONTENT'];
			
			$page->contentB[$field] .='<blockquote>';
			foreach($this->requiredVariables as $var){
				$var = $this->varCharStart.$var.$this->varCharEnd;
				$page->contentB[$field] .= '<br/>'.$var;
			}
			$page->contentB[$field] .= '</blockquote>';
			
			
		}else{
			$page->contentB[$field] = $langA['DEFAULT_CONTENT_PROTECTED'];
		}
	}
	
	//
	//	When someone clicks "Create New Template", I want to give them a working template..
	//		-	The best way to do this would be to copy an existing (main/home).. but what if the site admin has added <script> tags and such..
	//		-	and, the user display version is in the database!.. does installation put it in the database?..no it doesn't
	//		===>
	//			-	maybe the create package script should copy the template to a php file.. /include/
	//		
	function copyPackageTheme(){
		global $page,$includeDir;
		$_POST += array('which'=>'');
		
		if( strpos($_POST['which'],'./') ){
			message('INVALID_THEME');
			return;
		}
			
		$dir = $includeDir.'/themes/'.$_POST['which'];
		if( !is_dir($dir)){
			message('INVALID_THEME');
			$page->userCmd = '';
			return;
		}
		
		$css1 = $dir.'/style1.css';
		//$css2 = $dir.'/style2.css';
		$template = dirname($dir).'/template.php';
		
		//for content negotiation
		$css1css = $css1.'.css';
		//$css2css = $css2.'.css';
		
		if( !is_file($template) ){
			message('INVALID_THEME');
			$page->userCmd = '';
			return;
		}
		
		
		if( is_file($css1) ){
			
			//$this->css1 = getContents($css1);
			//$this->css2 = getContents($css2);
			$this->css1 = getContents($css1);

		}elseif( is_file($css1css) ){
			
			//$this->css1 = getContents($css1css);
			//$this->css2 = getContents($css2css);
			$this->css1 = getContents($css1css);
						
		}else{
			
			message('INVALID_THEME');
			$page->userCmd = '';
			return;
			
		}
		
		$this->template = getContents($template);
		$this->UpdateContent($this->template);
		
		
		//translate contents
		$this->content = $this->translateToUser($this->template);
		$this->translateCssUrls($this->css1);
		//$this->translateCssUrls($this->css2);

		$page->userCmd = 'edit';//'edit';
	}
	
	
	function UpdateHead(&$text){
		global $pageOwner;
		// rss links
		//!! this won't work, it'll keep adding these links to the head over and over
		$htmlHead[] = '<link href="'.wbLinks::getUrl('/Special/'.$pageOwner['username'].'/atom?field=blog').'" rel="alternate" title="Blog Feed for '.$pageOwner['username'].'" type="application/rss+xml" />';
		$htmlHead[] = '<link href="'.wbLinks::getUrl('/Special/'.$pageOwner['username'].'/atom').'" rel="alternate" title="Recently Modified Feed for '.$pageOwner['username'].'" type="application/rss+xml" />'; //!!lang
		$htmlHead[] = '<link href="'.wbLinks::getUrl('/Special/'.$pageOwner['username'].'/atom?field=1').'" rel="alternate" title="Recently Posted Feed for '.$pageOwner['username'].'" type="application/rss+xml" />';
		$htmlHead = implode("\n",$htmlHead) . "\n\n</head";
		
		$text = str_replace('</head',$htmlHead,$text);
	}
		
	
	
	//Update old themes with new data
	function UpdateContent(&$text){
		global $pageOwner;
		
		$text = str_replace('&NavBar&','&NavBarNew&',$text);
		
		$FromValues = array();
		$ToValues = array();
		
		foreach($this->newTranslation as $key => $value){
			$FromValues[] = '&'.$key.'&';
			$ToValues[] = $this->varCharStart.$key.$this->varCharEnd;
		}
		
		foreach($this->translationArray as $VarName => $VarValue){
			$FromValues[] = '&'.$VarName.'&';
			$ToValues[] = $this->varCharStart.$VarName.$this->varCharEnd;
		}
		$text = str_replace($FromValues,$ToValues,$text);
	}
	
		
		
		
	
	
	//	from	/plugins/default/blue/
	//	to		/templates/username/tname/
	function translateCssUrls(&$css){
		global $rootDir;
		$matches = array();
		
		$full = '';
		preg_match_all('#url\(([^\)\(]*)\)#',$css,$matches,PREG_PATTERN_ORDER);
		$matches = array_unique($matches[1]);

		$pluginPath = array('include','themes');
		$pluginPath = array_merge( $pluginPath, explode('/',$_POST['which']));
		foreach($matches as $path){
			$replace = $path;
			$temp = $pluginPath;
			while( (strpos($path,'../') === 0) && (count($temp) > 0)){
				$path = substr($path,3);
				array_pop($temp);
			}
			if( count($temp) == 0){
				$newPath = '../../../'.$path;
			}else{
				$newPath = '../../../'.implode('/',$temp).'/'.$path;
			}
			
			//message('replace: '.$replace.' with '.$newPath);
			$css = str_replace('url('.$replace.')','url('.$newPath.')',$css);
		}
	}
	
	function doActions(){
		global $page,$langA;
		
		
		switch( $page->userCmd ){
			case 'copydefault':
				$this->copyPackageTheme();
			break;
// 			case 'editlinks':
// 				$this->editLinks();
// 			break;
			
		}
		parent::doActions();
	}
		
	
	//this method would leave the links hard coded into the template, 
	//making things less than ideal for someone playing around with multiple templates
	function editLinks(){
		//message('here: '.nl2br(htmlspecialchars($this->content)) );
		
		$regExp = '#<[dD][iI][vV][^<]*class="sideMenuArea".*?</[dD][iI][vV]>#msi';
		preg_match_all($regExp,$this->content,$matches,PREG_PATTERN_ORDER);
		
		message(showArray($matches));
	}
		

	
	
	function toDB(){//aka save
		
		if( !$this->validData ){
			return false;
		}
		wbData::loadFileFunctions();
		
		$repl = '<'.'?php $page->htmlHead();';
		$repl .= ' ?'.'>';
		$repl .= "\n</head";
						
		$template = '<'.'?php defined(\'WikyBlog\') or die(\'Not an entry point...\'); '."\n";
		
		$template .= 'global $wbTabHtml;'."\n";
		$template .= '$wbTabHtml = '.$this->tab_html.';';	//this has to be on it's own line!
		$template .= "\n";
		$template .= '?'.'>';
		$template .= "\n\n";
		$template .= str_replace('</head',$repl,$this->template);

		
		$bool = saveFile($this->css1FileName, $this->css1);
		//$bool = $bool && saveFile($this->css2FileName, $this->css2);
		$bool = $bool && saveFile($this->templateFileName, $template);
		
		
		//to delete the css2 file so it's not added over and over to the css1 file
		if( $this->css2 !== false ){
			$temp = '';
			saveFile($this->css2FileName, $temp);	//write empty
			@wbUnlink($this->css2FileName);			//try to delete it
		}

		
		if( !($bool) ){
			return false;
		}
		
		//so that the update will always change!.. 
		//	this breaks one of the checks to see if changes were made in toolSavePage.php
		return parent::toDB();
	}

	//called by preview and viewing page
	//	this is where css would be included in a page
	function outputObj($field=true){
		global $page,$langA;
		static $notShown = true;
		static $i = 0;
		
		
		if( !$this->validData ){
			return false;
		}
		if( $field === true ){
			$field = $this->uniqLink;
		}
		
		$notShown = true;
		
		ob_start();
		echo '<div style="margin:2em 7em 2em 7em;">';
		
		
		if( isset($_SESSION['username']) ){

			echo '<h2>'.$langA['your_theme'].'</h2>';
			if( isset($_SESSION['template']) && (toStorage($_SESSION['template'],true) == toStorage($this->owner.'/'.$this->title,true)) ){
				echo $langA['using_this_theme'];
				
			}else{
				if( isset($_SESSION['template']) ){
					echo '<p>'.wbLang::text('CURRENT_THEME',$_SESSION['template']).'</p>';
				}
				echo '<p>'.wbLinks::special('Preferences?cmd=set&template='.$this->owner.'/'.$this->title,$langA['use_this_theme'],'',$_SESSION['username']).'</p>';
			}

			echo '<p>';
			echo $langA['MAKE_THEME'];
			echo '<br/> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" size="20" value="" name="to" />';
			echo '<input type="submit" name="cmd" value="'.$langA['copy'].'" /> ';
			echo '</p>';
		}
		
		echo $langA['EDIT_THEME_TEXT'];
		echo '</div>';
		$page->contentB[$field] = wb::get_clean();
		$page->autoForm = true;
		return $field;
	}
	
	function translateToUser($text){
		//echo preg_replace($pattern, $replacement, $string);
		//$this->newTranslation['new2'] = '<'.'?= $page->displayTitle ?'.'>';
		
		//
		// tabHtml
		//
		$lines = explode("\n",$text);
		foreach($lines as $i => $line){
			if(strpos($line,'?'.'>') !== false){
				break;
			}
			if( strpos($line,'$wbTabHtml') === 0){
				global $wbTabHtml;
				$line = trim($line);
				$len = strcspn($line,'1234567890');
				$line = substr($line,$len);
				$this->tab_html = (int)($line{0});
				
				// eval($line);
				// $this->tab_html = $wbTabHtml;
				break;
			}
		}
		
		//
		// links..
		//
		$search = array_keys($this->oldTrans);
		$replace = array_values($this->oldTrans);
		$text = str_replace($search,$replace,$text);
		
		$patt = array_values($this->toUser);
		$repl = array_keys($this->toUser);
		
		//build other pattern/replacemenst from $newTranslation
		foreach($this->newTranslation as $key => $value){
			$repl[] = $this->varCharStart.$key.$this->varCharEnd;
			$patt[] = '#<!-- '.$this->varCharStart.$key.$this->varCharEnd.' Start -->.*?<!-- '.$this->varCharStart.$key.$this->varCharEnd.' End -->#s';
		}
		
		$text = preg_replace($patt,$repl,$text);
		
		$FromValues = array();
		$ToValues = array();
		foreach($this->translationArray as $ToValue => $FromValue){
			$ToValue = $this->varCharStart.$ToValue.$this->varCharEnd;
			$FromValues[] = $FromValue;
			$ToValues[] = $ToValue;
		}
		$text = str_replace($FromValues,$ToValues,$text);
		
		//Get Rid of Any Left-Over PHP
		return preg_replace('#<\?.*?\?>#s','',$text);
	}
	
	function translateFromUser($text){
		// values will be changed to php values..ie <!-- DisplayPage -->.. 
		//	.. it must be done after xmlParse
		$patt = array();
		$repl = array();
		
		$patt = array_values($this->toFile);
		$repl = array_keys($this->toFile);
		
		foreach($this->newTranslation as $key => $value){
			$patt[] = '#'.$this->varCharStart.$key.$this->varCharEnd.'#';
			$repl[] = '<!-- '.$this->varCharStart.$key.$this->varCharEnd.' Start -->'."\r\n\t".$value."\r\n\t".'<!-- '.$this->varCharStart.$key.$this->varCharEnd.' End -->';
		}
		$text = preg_replace($patt,$repl,$text);
		
		
		
		//version 0.9 added because the use of &linkPrefix& in a link is now 
		//	changed to &amp;linkPrefix&amp; by the xmlParser (html attributes are wbHtmlspecialchars'd)
		//	.. also for links rev="&PageOwner&" becomes rev="&pageowner&" ...
		$FromValues = array();
		$ToValues = array();
		foreach($this->translationArray as $FromValue => $ToValue){ 
			$FromValue = $this->varCharStart.$FromValue.$this->varCharEnd;
			$FromValues[] = $FromValue;
			$ToValues[] = $ToValue;
			
			
			$FromValues[] = wbHtmlspecialchars($FromValue);
			$ToValues[] = $ToValue;
			
			$FromValues[] = wbHtmlspecialchars(strtolower($FromValue));
			$ToValues[] = $ToValue;
		}
		
		
		return str_replace($FromValues,$ToValues,$text);
	}
	
	function editValues(){
		global $page,$jsNum,$langA;
		$page->scripts[] = '/include/js/editing.js?'.$jsNum;
		$page->scripts[] = '/include/js/editingAll.js?'.$jsNum;
		$page->css2 = true;		
		
		if( ($page->userCmd == 'preview') || ($page->userCmd == 'save') ){
			$array['content'] =& $_POST['content'];
			//$array['CSS1'] = $this->translateToUser($_POST['css1']);
			//$array['CSS2'] = $this->translateToUser($_POST['css2']);
			$array['CSS1'] = $this->translateToUser($_POST['css1']);
			
		}else{
			//version 0.9.1 changed on June 02
			if( !empty($this->content)){
				$array['content'] =& $this->content;
			}else{
				$array['content'] = $this->translateToUser($this->template);
			}
			$array['CSS1'] =& $this->css1;
			//$array['CSS2'] =& $this->css2;
		}

		$editLink = $page->findLink($this->editLabel);
		$css1Link = $editLink.'#WBnoneCSS1';
		//$css2Link = $editLink.'#WBnoneCSS2';
		$saveLink = $editLink.'#WBnoneSave';
		
		$page->regLink('CSS',$css1Link);
		//$page->regLink('CSS2',$css2Link);
		$page->regLink($langA['save'],$saveLink);
		
		//make boxes
		$page->contentB[$editLink] = toEditArea($array['content'],false,'content');
		$page->contentB[$editLink] .= '<div style="text-align:right">'.$langA['back'].'.. &nbsp; ';
		$page->contentB[$editLink] .= wbLinks::local($css1Link,$langA['continue'].'...').' &nbsp; ';
		$page->contentB[$editLink] .= wbLinks::local($saveLink,$langA['save'].'...');
		$page->contentB[$editLink] .= '</div>';
		$page->contentB[$editLink] .= '<input type="hidden" name="tab_html" value="'.$this->tab_html.'" />';
		
		
		$page->contentB[$css1Link] = toEditArea($array['CSS1'],false,'css1');
		$page->contentB[$css1Link] .= '<div style="text-align:right">';
		$page->contentB[$css1Link] .= wbLinks::local($editLink,$langA['back'].'...').' &nbsp; ';
		//$page->contentB[$css1Link] .= wbLinks::local($css2Link,$langA['continue'].'...').' &nbsp; ';
		$page->contentB[$css1Link] .= wbLinks::local($saveLink,$langA['save'].'...');
		$page->contentB[$css1Link] .= '</div>';
		
		
// 		$page->contentB[$css2Link] = toEditArea($array['CSS2'],false,'css2');
// 		$page->contentB[$css2Link] .= '<div style="text-align:right">';
// 		$page->contentB[$css2Link] .= wbLinks::local($css1Link,$langA['back'].'..').' &nbsp; ';
// 		$page->contentB[$css2Link] .= wbLinks::local($saveLink,$langA['continue'].'...').' &nbsp; ';
// 		$page->contentB[$css2Link] .= wbLinks::local($saveLink,$langA['save'].'...');
// 		$page->contentB[$css2Link] .= '</div>';
		
		//
		//	Save Tab
		//
			
			if( empty($this->tab_html) ){
				$this->tab_html = 0;
			}
			$temp[0] = '<a> -'.$langA['link_text'].'- </a>';
			$temp[2] = '<li><a>-'.$langA['link_text'].'-</a></li>';
			$temp[1] = '<a><span class="tabLeft">-'.$langA['link_text'].'-</span><span class="tabRight">&nbsp;</span></a>';
			
		
			$t =& $page->contentB[$saveLink];
			$t = '';
			$t .= '<table class="tableRows">';
			$t .= '<tr><th colspan="2">Tab Html</th></tr>';
			foreach($temp as $i => $tabHtml){
				$t .= '<tr>';
				$t .= '<td>';
				if( $i == $this->tab_html ){
					$t .= '<input name="tab_html" type="radio" value="'.$i.'" checked="checked"/>';
				}else{
					$t .= '<input name="tab_html" type="radio" value="'.$i.'" />';
				}
				$t .= '</td>';
				$t .= '<td class="sm">'.wbHtmlspecialchars($tabHtml).'</td>';
				$t .= '</tr>';
			}
			$t .= '</table>';
			$t .= '<br/>';
			$t .= saveBar(true,false);
			$t .= '<div style="text-align:right">';
			//$t .= wbLinks::local($css2Link,$langA['back'].'..');
			$t .= wbLinks::local($css1Link,$langA['back'].'..');
			$t .= ' &nbsp; '.$langA['continue'].'.. &nbsp; '.$langA['save'].'...</div>';
		
	}
	
	function returnPageTemplate(){
		
		//css urls are not correct when the request uses the file_id: /Edit/theme/Main/8657?cmd=delete
		//so we need to change the paths
		$expected = wbStrtolower(wbLinks::getUrl($this->uniqLink));
		$actual = wbStrtolower($_SERVER['REQUEST_URI']);
		
		//get expected down to the relative path
		$pos = strpos($expected,'://');
		if( $pos > 0 ){
			$expected = substr($expected,$pos+3);
			$pos = strpos($expected,'/');
			$expected = substr($expected,$pos);
		}
		
		if( $expected != $actual ){
			$expected = explode('/',$expected);
			$actual = explode('/',$actual);
			do{
				$currentActual = array_shift($actual);
				$currentExpected = array_shift($expected);
				if( $currentActual == $currentExpected ){
					continue;
					
				}else{
					array_unshift($actual,$currentActual);
					array_unshift($expected,$currentExpected);
					break;
				}
			}while( (count($actual) > 0) && (count($expected) > 0) );
			
			$css = $this->CssPathsFromTo($this->css1,$expected,$actual);
		}else{
			$css = $this->css1;
		}
	
		//return str_replace('</head>',"\n<style>\n".$this->css1."\n".$this->css2."\n</style>\n</head>",$this->template);
		return str_replace('</head>',"\n<style>\n".$css."\n</style>\n</head>",$this->template);
	}
	
	
	function CssPathsFromTo($css,$fromPathArray,$toPathArray){
		global $rootDir;
		$matches = array();
		
		$full = '';
		preg_match_all('#url\(([^\)\(]*)\)#',$css,$matches,PREG_PATTERN_ORDER);
		$matches = array_unique($matches[1]);
		
	
		foreach($matches as $path){
			$replace = $path;
			$tempFrom = $fromPathArray;
			$tempTo = $toPathArray;;
			
			while( (strpos($path,'../') === 0) && (count($tempFrom) > 0) && (count($tempTo) > 0) ){
				array_pop($tempFrom);
				array_pop($tempTo);
			}
			$newPath = '';
			foreach($tempTo as $level){
				$newPath .= '../';
			}
			foreach($tempFrom as $level){
				$newPath .= $level.'/';
			}
			$newPath .= $path;
			$css = str_replace('url('.$replace.')','url('.$newPath.')',$css);
		}
		return $css;
	}
		
	
	
}

//				TEMPLATE CLASS
//
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// 				EXTRA FUNCTIONS
//

//use addslashes or addcslashes( $str,'"\\');
//	to escape ' and \
//	the " will be escaped by preg_replace
//
function formatTemplateLinks($arg1,$arg2){
	$arg2 = stripslashes($arg2); //don't escape "
	$arg2 = addcslashes($arg2,'\'\\'); //escape ' and \
	
	$pieces = wbExplode('|',$arg2);
	if( count($pieces) < 1){
		return '[['.$arg1.':'.$arg2.']]';
	}elseif(count($pieces) < 2){
		$pieces[1] = $pieces[0];
	}
	
	switch(wbStrtolower($arg1)){
		case 'speciallink':
		return '<?php echo wbLinks::special(\''.$pieces[0].'\',\''.$pieces[1].'\'); ?>';
		
		case 'locallink':
		return '<?php echo wbLinks::local(\''.$pieces[0].'\',\''.$pieces[1].'\'); ?>';
		
		case 'helplink':
		return '<?php echo wbLinks::help(\''.$pieces[0].'\',\''.$pieces[1].'\'); ?>';
		
		case 'wbimage':
		return '<?php echo wbLinks::image(\''.$pieces[0].'\'); ?>';
	}
	return '[['.$arg1.':'.$arg2.']]';
}



function getContents($fileName){
	if( is_readable($fileName) ){
		return @file_get_contents($fileName);
	}else{
		return '';
	}
}

