HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/PvdBoogaard/indoorski.nl/backup/oude-site/cms/api/class.styleguide.php
<?php
/**
 * This file contains the iwp_styleguide class.
 *
 * @author Jordie <jordie+code@interspire.com>
 *
 * @package IWP
 * @subpackage IWP_API
 */

/**
 * This class extends upon the base iwp_base class.
 * This file deals specifically with the style guide for themes
 *
 * @package IWP
 * @subpackage IWP_API
 *
 * @see iwp_base
 */
class iwp_styleguide extends iwp_base {

	/**
	 * This static variable holds the current instance of this object being loaded.
	 * So using the getInstance function anywhere will return the very same instance.
	 *
	 * @var object Instance
	 */
	public static $Instance;

	/**
	 * This is the HTML string contents of the style guide file
	 *
	 * @var string
	 */

	public $styleGuide = '';
	public $templatePath = null;
	public $layoutFilePath = null;
	public $sectionPath = null;
	public $styleGuideLines = array();
	public $styleGuideLinesOrig = array();
	/**
	 * This is a variable holding the XPath object for the document
	 *
	 * @var DomXpath
	 */

	private $xpath = null;

	/**
	 * This is the full path to style guide HTML file
	 *
	 * @var string
	 */

	private $styleGuideFile = '';

	/**
	 * getInstance
	 * This is a static function that sets up the class instance and stores it to the static variable. It will then return that instantiation in the future.
	 *
	 * @return iwp_styleguide Returns the instantiated object
	 **/
	public static function getInstance(){
		if(!isset(self::$Instance)){
			self::$Instance = new self();
		}
		return self::$Instance;
	}

	/**
	 * The class constructor
	 *
	 * Calls the parent constructor
	 */
	public function __construct($path=null){
		if(is_null($path)){
			$this->templatePath = IWP_TPL_PATH;
			$this->layoutFilePath = IWP_CACHE_SECTION_HTML_PATH .'/layout.html';
			$this->sectionPath = IWP_CACHE_SECTION_HTML_PATH .'/';
			$this->styleGuideFile = $this->templatePath . '/styleguide.html';
		}else{
			$this->templatePath = $path;
			$this->layoutFilePath = IWP_CACHE_SECTION_HTML_PATH . '/layout.html';
			$this->sectionPath = IWP_CACHE_SECTION_HTML_PATH .'/';
			$this->styleGuideFile = $this->templatePath. '/styleguide.html';
		}
	}

	public function GetStyleGuideFile(){
		return $this->styleGuideFile;
	}

	/**
	 * This function cleans up the HTML returns by DomDocument as its not 100% clean. It messes up BR tags, link tags, meta tags, etc.
	 *
	 * @param string $html The HTML to be cleaned up
	 * @param boolean $final This should be true if we're passing for the last time before output. This option ensures that the less than and greater than in the template system code are not left as HTML entities
	 */
	public function CleanUpHTML($html, $final=false){

		// DOMDocument likes to add separate closing tags for all tags, even those in HTML that are self closing.
		// Convert these tags to be self closing.
		$selfClosingTags = array('base', 'meta', 'link', 'frame', 'hr', 'br', 'basefont', 'param', 'img', 'area', 'input', 'isindex', 'col');
		foreach($selfClosingTags as $tagToFix){
			$html = preg_replace('#<'.$tagToFix.'([^>]*)>([^<]*)</'.$tagToFix.'>#ismU','<'.$tagToFix.'$1 />', $html);
			$html = preg_replace('#<' . $tagToFix .'([^>]*)([^/])>#ism', '<' . $tagToFix .'$1$2 />', $html);
			$html = str_replace('</' . $tagToFix .'>', '', $html);
		}

		// Clean up any remaining BR tags
		$html = preg_replace('#<br([^>/]*)>#ismU','<br$1 />', $html);

		if ($final === true) {
			// This should only be called if this is the last action before saving the content to files.
			// It may otherwise cause problems if it is repeatedly called

			preg_match_all('#\{([^\}]*)(&gt;|&lt;)([^\}]*)\}#ismU',$html, $matches);

			foreach($matches[0] as $k=>$fullCode){
				$new = str_replace(array('&gt;', '&lt;', '&amp;&amp;'), array('>', '<', '&&'), $fullCode);
				$html = str_replace($fullCode, $new, $html);
			}

			// Dirty hacks for IE 6 which doesn't play nice with **whitespace** in and between list items
			$html = preg_replace('#<([/])?(ul|li|a)([^>]*)>([ \s\n\r\t]*){#im','<$1$2$3>{', $html);
			$html = preg_replace('#}([ \s\n\r\t]*)<([/])?(ul|li|a)([^>]*)>#im','}<$2$3$4>', $html);
			$html = preg_replace('#{/if}([ \s\n\r\t]*){/foreach}#im','{/if}{/foreach}', $html);
			$html = preg_replace('#}([ \s\n\r\t]*)\{if([^\}]*)\}([ \s\n\r\t]*)<li#im','}{if$2}<li', $html);

			// Revert entities that have been generated inside template code
			// e.g. {if $foo && $bar} would end up like {if $foo &amp;&amp; $bar}
			$html = str_replace('&amp;&amp;', '&&', $html);

			//	Put links on a single line so spaces are not generated by the browser before and/or after the linked content.
			$html = preg_replace('#<a([^>]*)>[\s\n\t\r ]*(.*)(?-U)[\s\n\t\r ]*</a>#im','<a$1>$2</a>', $html);
			$html = preg_replace('#<a([^>]*)>[\s\n\t\r ]*<#im','<a$1><', $html);
			$html = preg_replace('#[\s\n\t\r ]*</a>#im','</a>', $html);

			// Revert the URL encoding of template code.
			// Using href="{$foo}" would end up like href="%7B%24foo%7D"
			if (preg_match_all("/(src|href)=([\"'])(.*?%7B%24.*?%7D.*?)\\2/im", $html, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) {
				//	this finds all src and href attributes that have both {$ and } in them at least once and reverses the encoding for these characters specifically

				//	go backwards through the matches so the offsets don't change
				$matches = array_reverse($matches);

				foreach ($matches as $match) {
					$replaceLength = strlen($match[0][0]);
					$replaceOffset = $match[0][1];

					$replaceUrl = strtr($match[3][0], array(
						'%7B'	=> '{',
						'%24'	=> '$',
						'%7D'	=> '}',
					));

					$replaceWith = $match[1][0] . '=' . $match[2][0] . $replaceUrl . $match[2][0];

					$html = substr_replace($html, $replaceWith, $replaceOffset, $replaceLength);
				}
			}

			// remove system classes
			// $html = preg_replace('#tplvar-[0-9a-zA-Z\-]*#im','', $html);
			// $html = preg_replace('#tplsection-[0-9a-zA-Z\-]*#im','', $html);
			// $html = preg_replace('#tplcond-[0-9a-zA-Z\-]*#im','', $html);
		}

		return $html;
	}

	/**
	 * This function takes in a string of HTML and formats it with indenting and new lines
	 *
	 * @param string $str The HTML string to format
	 * @param integer $level The number of tabs for each indent level
	 *
	 * @return string The formatted HTML string
	 */
	public function asFormattedXML($str, $level = 1) {
		// get an array containing each XML element
		$str = preg_replace('/\}\s*\{/', "}\n{", $str);
		$str = preg_replace('/>\s*<([^\!])/', ">\n<$1", $str);
		$str = preg_replace('/>([^<]{2,})<([^\!])/', ">\n$1\n<$2", $str);
		$str = preg_replace('/\}\s*<([^\!])/', "}\n<$1", $str);
		$str = preg_replace('/>\s*\{/', ">\n{", $str);
		$xml = explode("\n", $str);

		// hold current indentation level
		$indent = 0;

		// hold the XML segments
		$pretty = array();

		// shift off opening XML tag if present
		if (count($xml) && preg_match('/^<\?\s*xml/', $xml[0])) {
			$pretty[] = array_shift($xml);
		}

		foreach ($xml as $el) {
			if (preg_match('/^<([\w])+[^>\/\-]*>$/U', $el) || preg_match('/^\{([\w])+[^>\/]*\}$/U', $el) || (strpos($el, '{if') !== false && strpos($el, '{/if') === false)) {
				// opening tag, increase indent
				$pretty[] = @str_repeat("\t", $indent) . $el ;
				$indent += $level;
			} else {
				if (preg_match('/^<\/.+>$/', $el) || preg_match('/^\{\/.+\}$/', $el)) {
					// closing tag, decrease indent
					$indent -= $level;
				}
				$pretty[] = @str_repeat("\t",  $this->valid->FilterIntGreaterThanZero($indent)) . $el;
			}
		}
		return implode("\n", $pretty);
	}

	/**
	 * This function reads in the style guide and parses each block into HTML files
	 *
	 * @return	Doesn't return anything
	 */
	 public function ProcessStyleGuide(){
		if(!is_file($this->styleGuideFile)){
			throw new iwp_exception_styleguide('The style guide file does not exist');
		}

		$this->LoadStyleGuide();

		$stopExecution		= false;
		$returnXmlErrors	= array();

		// This lets us capture the XML validation errors so we can display them neatly to the user
		libxml_use_internal_errors(true);

		$xhtml = new DOMDocument;
		$xhtml->loadHTML($this->styleGuide);

		$xmlErrors = libxml_get_errors();

		if(sizeof($xmlErrors) > 0){

			foreach ($xmlErrors as $k=>$error) {
				if($error->code == '513'){
					// 513 is ID <your-id> already defined
					continue;
				}
				$thisError = $errorType = '';
				$line = $error->line;

				 switch ($error->level) {
					case LIBXML_ERR_WARNING:
						$errorType = 'Warning '.$error->code.': ';
						break;
					 case LIBXML_ERR_ERROR:
						$errorType = 'Error '.$error->code.': ';
						break;
					case LIBXML_ERR_FATAL:
						$stopExecution = true;
						$errorType = 'Fatal Error '.$error->code.': ';
						break;
				}

				$row = $this->styleGuideLines[$line-1];
				$startLen = strlen($row);
				$endLen = strlen(ltrim($row));
				$diffLen = $startLen - $endLen;

				$newLine = array_search($row, $this->styleGuideLinesOrig);

				$thisError = "<b>".$errorType." </b> <span>" . $error->message . "</span><br /><b>Location:</b> <i>Line " . ($newLine+1) . ", Column ".$error->column."</i><br />";
				$row = iwp_validation::htmlchars(substr($row,0, $error->column)) . '<span class="validation-error-chars">' . iwp_validation::htmlchars(substr($row,$error->column, 1)) .'</span>' .  iwp_validation::htmlchars(substr($row,$error->column+1));
				$thisError .= '<pre class="validation-error-code">'.trim($row)."\n".str_repeat(' ', ($error->column-$diffLen)) . "^\n".'</pre>';
				$returnXmlErrors[] = $thisError;
			}
		}

		libxml_clear_errors();

		$returnXmlErrors = array_reverse($returnXmlErrors);

		if($stopExecution){
			return $returnXmlErrors;
		}

		$cache = new iwp_cache();
		$cache->ClearCacheAll();

		// clear the template cache
		if(is_dir(IWP_CACHE_PATH .'/templates')){
			$dirObject = new DirectoryIterator(IWP_CACHE_PATH .'/templates');
			foreach($dirObject as $fileName=>$objFile){
				if($objFile->isFile()){
					@unlink($objFile->getPath()."/". $objFile->getFilename());
				}
			}
		}

		// remove all the section html files from the previous template
		if(is_dir(IWP_CACHE_PATH .'/sectionhtml')){
			$dirObject = new DirectoryIterator(IWP_CACHE_PATH .'/sectionhtml');
			foreach($dirObject as $fileName=>$objFile){
				if($objFile->isFile()){
					@unlink($objFile->getPath()."/". $objFile->getFilename());
				}
			}
		}

		if(!is_dir($this->sectionPath)){
			if(@mkdir($this->sectionPath, 0777)){
				if(!@chmod($this->sectionPath, 0777)){
					throw new iwp_exception_styleguide('Unable to set permissions on the processed template files. Please make sure "'.$this->sectionPath .'" exists and is writable.');
					return;
				}
			}else{
				throw new iwp_exception_styleguide('Unable to create a directory for the processed template files. Please make sure "'.$this->sectionPath .'" exists and is writable.');
				return;
			}
		}

		// ------ Global Website Variables ------ //
		iwp_domhelper::modifyTagByClassName($xhtml, 'tplvar-site-title', '{$websiteTitle}');
		iwp_domhelper::modifyTagByClassName($xhtml, 'tplvar-site-color', 'styles/{$config.SiteColor}.css');
		iwp_domhelper::modifyTagByClassName($xhtml, 'tplvar-site-metadescription', '{$metaDescription}');
		iwp_domhelper::modifyTagByClassName($xhtml, 'tplvar-site-metakeywords', '{$metaKeywords}');
		iwp_domhelper::modifyTagByClassName($xhtml, 'tplvar-site-siteurl', '{$urls.homepage}');
		iwp_domhelper::modifyTagByClassName($xhtml, 'tplvar-site-logoimage', '{$WebsiteLogo}');
		iwp_domhelper::modifyTagByClassName($xhtml, 'tplvar-site-name', '{$config.WebsiteTitle|iwp_htmlspecialchars}');
		iwp_domhelper::modifyTagByClassName($xhtml, 'tplvar-site-slogan', '{$config.siteSlogan|iwp_htmlspecialchars}');
		iwp_domhelper::modifyTagByClassName($xhtml, 'tplvar-site-templateurl', '{$config.siteURL}/templates/{$config.template}/');

		// do all front end language stuff
		$this->ProcessLanguageVariables($xhtml);

		$this->xpath = new DOMXPath($xhtml);

		$classSearch = 'tplcond-hideif-';
		$hideIf = $this->xpath->query('//*[contains(concat(\' \', @class, \' \'), \' ' . $classSearch . '\')]');

		if($hideIf->length > 0){
			foreach($hideIf as $thisNode) {
				$thisAttr = iwp_domhelper::getAttributes($thisNode);

				if(!isset($thisAttr['class'])) {
					continue;
				}

				$classList = preg_split('#\s+#', $thisAttr['class'], -1, PREG_SPLIT_NO_EMPTY);

				if(empty($classList)) {
					continue;
				}

				foreach($classList as $thisClass){
					if(substr($thisClass, 0, strlen($classSearch)) == $classSearch){
						$columns = substr($thisClass, strlen($classSearch));
						$columnList = preg_split('#\-#', $columns, -1, PREG_SPLIT_NO_EMPTY);

						if(empty($columnList)) {
							continue;
						}

						foreach ($columnList as $key=>$val) {
							$columnList[$key] = str_replace('columns', '', $columnList[$key]);
							$columnList[$key] = str_replace('column', '', $columnList[$key]);
							$columnList[$key] = (int)$columnList[$key];
							if($columnList[$key] < 1){
								unset($columnList[$key]);
							}
						}

						if(empty($columnList)) {
							continue;
						}

						iwp_domhelper::WrapElement($thisNode,  ' {if !in_array($layout.columnCount, array('. implode(', ', $columnList) .'))}', '{/if}');
					}
				}
			}
		}


		$blockList = array();
		$blocks = $this->xpath->query('//*[@block] | //head');

		foreach ($blocks as $blockData) {
			$writeXhtml = '';

			if(iwp_strtolower((string)$blockData->tagName) == 'head'){
				$blockData->setAttribute('block', 'htmlHead');
				$blockData->setAttribute('blockstyle', 'Standard');
			}

			$attributes = iwp_domhelper::getAttributes($blockData);

			//	place the current block name/style into the class for easy styling
			$class = $blockData->getAttribute('class');
			if ($class != '') {
				$class .= ' ';
			}
			$class .= 'tplblock-'. iwp_strtolower($attributes['block']) .' tplblockstyle-'. iwp_strtolower($attributes['block']) .'-'. iwp_strtolower($attributes['blockstyle']);
			$blockData->setAttribute('class', $class);

			$name = iwp_strtolower($attributes['block'] .'_'. str_replace(' ', '_',iwp_strtolower($attributes['blockstyle'])));

			$blockList[$attributes['block']][$name] = $attributes['blockstyle'];

			if(is_file(IWP_BASE_PATH . '/includes/sections/'.iwp_strtolower($attributes['block']).'.php')){
				include_once(IWP_BASE_PATH . '/includes/sections/'.iwp_strtolower($attributes['block']). '.php');
				$className = 'iwp_section_' . iwp_strtolower($attributes['block']);
				$objBlock = new $className;
				$writeXhtml = $objBlock->ProcessBlock($this, $blockData, $attributes);
			}else{
				$writeXhtml = iwp_domhelper::outerHTML($blockData);
			}

			// $writeXhtml = $this->asFormattedXML($writeXhtml);

			$writeXhtml = $this->CleanUpHTML(str_replace("\r", '', $writeXhtml), true);

			if(!@file_put_contents($this->sectionPath .iwp_strtolower($attributes['block']) . '_' . str_replace(' ', '_',iwp_strtolower($attributes['blockstyle'])) . '.html', $writeXhtml)){
				throw new iwp_exception_styleguide('Unable to write to the template files. Make sure "'.$this->sectionPath .'" is writable.');
				return;
			}else{
				@chmod($this->sectionPath .iwp_strtolower($attributes['block']) . '_' . str_replace(' ', '_',iwp_strtolower($attributes['blockstyle'])) . '.html', 0777);
			}
		}

		// this is used by lists when it needs to know all the types of block styles available to it
		$Insert = array('name'=> 'layoutBlocks', 'value'=>serialize($blockList), 'template'=>'systemdata');
		$this->db->Query('delete from ' . IWP_TABLE_TEMPLATE_SETTINGS . ' where name="layoutBlocks"');
		$this->db->InsertQuery(IWP_TABLE_TEMPLATE_SETTINGS, $Insert);

		// ------- THE MASTER LAYOUT FILE ------- //

		// Remove all the blocks - We don't want them in the layout file
		foreach ($blocks as $blockData) {
			$blockData->parentNode->removeChild($blockData);
		}

		// ------- The body tag ------- //
		$bodyTag = $this->xpath->query('//body')->item(0);

		$iterator = 0;

		while(true) {
			$thisElement = iwp_domhelper::GetElementByClass($bodyTag, 'tplcond-hideif-haswebsitelogo', $iterator);
			if(is_object($thisElement)){
				iwp_domhelper::WrapElement($thisElement, '{if !$hasWebsiteLogo}', '{/if} ');
				++$iterator;
			}else{
				break;
			}
		}

		$iterator = 0;

		while(true) {
			$thisElement = iwp_domhelper::GetElementByClass($bodyTag, 'tplcond-hideif-haswebsitename', $iterator);
			if(is_object($thisElement)){
				iwp_domhelper::WrapElement($thisElement, '{if !$hasWebsiteName}', '{/if} ');
				++$iterator;
			}else{
				break;
			}
		}

		$iterator = 0;

		while(true) {
			$thisElement = iwp_domhelper::GetElementByClass($bodyTag, 'tplcond-showif-haswebsitename', $iterator);
			if(is_object($thisElement)){
				iwp_domhelper::WrapElement($thisElement, '{if $hasWebsiteName}', '{/if} ');
				++$iterator;
			}else{
				break;
			}
		}


		$iterator = 0;

		while(true) {
			$thisElement = iwp_domhelper::GetElementByClass($bodyTag, 'tplcond-showif-haswebsitelogo', $iterator);
			if(is_object($thisElement)){
				iwp_domhelper::WrapElement($thisElement, '{if $hasWebsiteLogo}', '{/if}');
				++$iterator;
			}else{
				break;
			}
		}

		// Prepend the html head placeholder to the body tag
		$bodyTag->parentNode->insertBefore(iwp_domhelper::NewDOMText('{$layout.htmlHead}'), $bodyTag);

		$bodyTag->insertBefore(iwp_domhelper::NewDOMText('{$bodyTagBegin}'), $bodyTag->firstChild);
		$bodyTag->appendChild(iwp_domhelper::NewDOMText('{$bodyTagEnd}'));

		$layoutClass = 'layout-{$layout.template}';
		if (!$bodyTag->hasAttribute('class')) {
			$bodyTag->setAttribute('class', $layoutClass);
		} else {
			$bodyTag->setAttribute('class', $bodyTag->getAttribute('class') . ' ' . $layoutClass);
		}

		$sectionsList = array('top', 'bottom', 'middle', 'right', 'left');

		foreach ($sectionsList as $thisSection) {
			$thisBaseSectionClass = 'tplsection-'.$thisSection;
			$sectionXPath = $this->xpath->query('//*[contains(concat(\' \', @class, \' \'), \' '.$thisBaseSectionClass.'\')]');
			if($sectionXPath->length == 0) {
				continue;
			}
			foreach ($sectionXPath as $thisSectionElement) {
				$thisAttr = iwp_domhelper::getAttributes($thisSectionElement);

				if(!isset($thisAttr['class'])) {
					continue;
				}

				$classList = preg_split('#\s+#', $thisAttr['class'], -1, PREG_SPLIT_NO_EMPTY);

				if(empty($classList)) {
					continue;
				}

				foreach($classList as $thisClass){

					$replaceValue = '{$hookBefore' . ucfirst(iwp_strtolower($thisSection)) . '}{$layout.' . $thisSection . 'Blocks}{$hookAfter' . ucfirst(iwp_strtolower($thisSection)) . '}';

					if(in_array($thisClass, array($thisBaseSectionClass, $thisBaseSectionClass . '-inside'))){
						iwp_domhelper::insertHTMLBefore($replaceValue, $thisSectionElement->firstChild);

					}elseif(substr($thisClass, 0, strlen($thisBaseSectionClass)) == $thisBaseSectionClass){
						// we have a base class name
						$positions = preg_split('#\-#', substr($thisClass, strlen($thisBaseSectionClass)), -1, PREG_SPLIT_NO_EMPTY);

						if(empty($positions)){
							iwp_domhelper::insertHTMLBefore($replaceValue, $thisSectionElement->firstChild);
							continue;
						}

						$where = 'prepend';

						if (in_array(iwp_strtolower($positions[0]), array('after', 'before','inside','prepend', 'append', 'replace'))) {
							$where = $positions[0];
							unset($positions[0]);
						}

						if(empty($positions)){
							$positions[] = 'all';
						}

						if(!in_array($where, array('before', 'append', 'replace'))){
							$positions = array_reverse($positions);
						}

						foreach($positions as $thisPosition) {
							if(preg_match('#^block([1-9][0-9]*)$#i', trim($thisPosition), $match)){
								if(isset($match[1]) && (int)$match[1] > 0){
									$replaceValue = '{$layout.' . iwp_strtolower($thisSection) . 'Block' . (int)$match[1] .'}';
								}
							}

							switch($where){
								case 'inside':
									iwp_domhelper::replaceInnerHTML($thisSectionElement, $replaceValue);
									$where = 'prepend';
									break;
								case 'after':
									iwp_domhelper::insertHTMLAfter($replaceValue, $thisSectionElement);
									break;
								case 'before':
									iwp_domhelper::insertHTMLBefore($replaceValue, $thisSectionElement);
									break;
								case 'prepend':
									iwp_domhelper::insertHTMLBefore($replaceValue, $thisSectionElement->firstChild);
									break;
								case 'append':
									iwp_domhelper::insertHTMLAfter($replaceValue, $thisSectionElement->lastChild);
									break;
								case 'replace':
									iwp_domhelper::insertHTMLBefore($replaceValue, $thisSectionElement);
									break;
							}

						}

						if($where == 'replace') {
							$thisSectionElement->parentNode->removeChild($thisSectionElement);
						}
					}
				}
			}
		}



	 	// check for conditionals
	 	$classSearch = 'tplcond-addcolumncounttoclass-';
		$condList = $this->xpath->query('//*[contains(concat(\' \', @class, \' \'), \' ' . $classSearch . '\')]');

		if($condList->length > 0){
			foreach($condList as $thisNode) {
				$thisAttr = iwp_domhelper::getAttributes($thisNode);

				if(!isset($thisAttr['class'])) {
					continue;
				}

				$classList = preg_split('#\s+#', $thisAttr['class'], -1, PREG_SPLIT_NO_EMPTY);

				if(empty($classList)) {
					continue;
				}

				foreach($classList as $thisClass){
					if(substr($thisClass, 0, strlen($classSearch)) == $classSearch){
						$className = substr($thisClass, strlen($classSearch));
						$thisNode->setAttribute('class', $thisNode->getAttribute('class') . ' ' . $className . '{$layout.columnCount}');
					}
				}
			}
		}

		$conditions = array(1=>'tplcond-if1column-addclass-', 2=>'tplcond-if2columns-addclass-', 3=>'tplcond-if3columns-addclass-', );

		foreach ($conditions as $colCount=>$classSearch) {
			// check for conditionals
			$condList = $this->xpath->query('//*[contains(concat(\' \', @class, \' \'), \' ' . $classSearch . '\')]');

			if($condList->length > 0){
				foreach($condList as $thisNode) {
					$thisAttr = iwp_domhelper::getAttributes($thisNode);

					if(!isset($thisAttr['class'])) {
						continue;
					}

					$classList = preg_split('#\s+#', $thisAttr['class'], -1, PREG_SPLIT_NO_EMPTY);

					if(empty($classList)) {
						continue;
					}

					foreach($classList as $thisClass){
						if(substr($thisClass, 0, strlen($classSearch)) == $classSearch){
							$className = substr($thisClass, strlen($classSearch));
							$thisNode->setAttribute('class', $thisNode->getAttribute('class') . ' {if $layout.columnCount == ' . $colCount .'}' . $className . '{/if}');
						}
					}
				}
			}
		}

		// prepare for saving and then save
		$html = $this->CleanUpHTML($xhtml->saveHTML(), true);

		//if(!@file_put_contents($this->layoutFilePath, trim($this->asFormattedXML($html)))){
		if(!@file_put_contents($this->layoutFilePath, trim($html))){
			throw new iwp_exception_styleguide('Unable to write to the template files. Make sure "'.$this->sectionPath .'" is writable.');
		}

		return $returnXmlErrors;
	}

	public function ProcessLanguageVariables($document) {
		$baseClassName = 'tpllang-';

		$xPath = new DOMXPath($document);

		$classMatches = $xPath->query('//*[contains(concat(\' \', @class, \' \'), \' '.$baseClassName.'\')]');

		if($classMatches->length == 0){
			return;
		}

		foreach($classMatches as $thisElement) {
			$thisAttr = iwp_domhelper::getAttributes($thisElement);

			if(!isset($thisAttr['class'])) {
				continue;
			}

			$classList = preg_split('#\s+#', $thisAttr['class'], -1, PREG_SPLIT_NO_EMPTY);

			if(empty($classList)) {
				continue;
			}

			foreach($classList as $thisClass){
				if(substr($thisClass, 0, strlen($baseClassName)) == $baseClassName){
					// we have a base class name
					$positions = preg_split('#\-#', substr($thisClass, strlen($baseClassName)), -1, PREG_SPLIT_NO_EMPTY);
					if(empty($positions)){
						continue;
					}
					$langVar = $positions[0];
					unset($positions[0]);
					$replaceValue = '{$lang.' . $langVar .'}';

					if(empty($positions)){
						iwp_domhelper::replaceInnerHTML($thisElement, $replaceValue);
						continue;
					}

					foreach($positions as $thisPosition){
						if($thisPosition == 'inside'){
							iwp_domhelper::replaceInnerHTML($thisElement, $replaceValue);

						}elseif($thisPosition == 'append'){
							iwp_domhelper::insertHTMLAfter($replaceValue,  $thisElement->lastChild);

						}elseif($thisPosition == 'prepend'){
							iwp_domhelper::insertHTMLBefore($replaceValue,  $thisElement->firstChild);

						}elseif($thisPosition == 'spaceappend'){
							iwp_domhelper::insertHTMLAfter(' ' . $replaceValue,  $thisElement->lastChild);

						}elseif($thisPosition == 'spaceprepend'){
							iwp_domhelper::insertHTMLBefore($replaceValue . ' ',  $thisElement->firstChild);

						}elseif($thisPosition == 'classprepend'){
							if($thisElement->hasAttribute('class')){
								$thisElement->setAttribute('class', $replaceValue . ' ' . $thisElement->getAttribute('class'));
							}else{
								$thisElement->setAttribute('class', $replaceValue);
							}

						}elseif($thisPosition == 'classappend'){
							if($thisElement->hasAttribute('class')){
								$thisElement->setAttribute('class', $thisElement->getAttribute('class') . ' ' . $replaceValue);
							}else{
								$thisElement->setAttribute('class', $replaceValue);
							}

						}else{
							$thisElement->setAttribute($thisPosition, $replaceValue);
						}
					}
				}
			}
		}
	}


	/**
	 * This function loads in the styleguide html into a member variable called $this->styleGuide
	 *
	 * @param boolean $force Set this to true to force a refresh of the HTML, otherwise if the variable is already set it won't be reloaded
	 *
	 * @return void
	 */

	public function LoadStyleGuide($force=false){
		if($this->styleGuide == '' || $force === true){
			$this->styleGuide = file_get_contents($this->styleGuideFile);

			$tmp = str_replace("\r\n", "\n", $this->styleGuide );
			$tmp = str_replace("\r", "\n", $tmp );
			$this->styleGuideLinesOrig = explode("\n", $tmp);

			$this->styleGuide = preg_replace('#<\!--\{ignore\}-->.*<\!--\{/ignore\}-->#ismU', '', $this->styleGuide);
			$this->styleGuide = preg_replace('#<\!--\{ignore/\}(.*)-->#ismU', '', $this->styleGuide);

			// there are problems processing the HTML into a DOMDocument when the charset isn't valid
			// so we need to manually convert it here
			$this->styleGuide = str_ireplace('{$site.charset}', 'utf-8', $this->styleGuide);
			$tmp = str_replace("\r\n", "\n", $this->styleGuide );
			$tmp = str_replace("\r", "\n", $tmp );
			$this->styleGuideLines = explode("\n", $tmp);
		}
	}

	/**
	 * This function extracts any style tags within the head section of the style guide and returns them
	 *
	 * @return string The style tags from within the styleguide file
	 */

	public function getStyle(){
		$this->LoadStyleGuide();
		libxml_use_internal_errors(true);

		try{
			$xml = new SimpleXml($this->styleGuide);
			$xml = (string)$xml->head->style->asXml();
		} catch (Exception $e) {
			$xml = '';
		}

		return $xml;
	}

}