/**
* Converts all data from the template table for a style into the style table
*
* @param	integer	Style ID
* @param	string	Title of style
* @param	array	Array of actions set to true/false: docss/dostylevars/doreplacements/doposteditor
* @param	string	List of parent styles
* @param	string	Indent for HTML printing
*/
function build_style($styleid, $title = '', $actions = array(), $parentlist = '', $indent = '')
{
	global $vbulletin, $_queries, $vbphrase, $_query_special_templates;
	static $phrase, $csscache;

	if (($actions['doreplacements'] OR $actions['docss'] OR $actions['dostylevars']) AND $vbulletin->options['storecssasfile'])
	{
		$actions['docss'] = true;
		$actions['doreplacements'] = true;
	}

	if ($styleid != -1)
	{
		$QUERY = array(
			'' => "dateline = " . TIMENOW
		);
		// echo the title and start the listings
		echo "$indent<li><b>$title</b> ... <span class=\"smallfont\">";
		vbflush();

		// build the templateid cache
		if (!$parentlist)
		{
			$parentlist = fetch_parentids($styleid);
		}

		$templatelist = build_template_id_cache($styleid, 1, $parentlist);
		$QUERY[] = "templatelist = '" . $vbulletin->db->escape_string($templatelist)  . "'";
		echo "($vbphrase[templates]) ";
		vbflush();

		// cache special templates
		if ($actions['docss'] OR $actions['dostylevars'] OR $actions['doreplacements'] OR $actions['doposteditor'])
		{
			// get special templates for this style
			$template_cache = array();
			$templateids = implode(',' , unserialize($templatelist));
			$templates = $vbulletin->db->query_read("
				SELECT title, template, templatetype
				FROM " . TABLE_PREFIX . "template
				WHERE templateid IN ($templateids)
					AND (templatetype <> 'template' OR title IN('" . implode("', '", $_query_special_templates) . "'))
			");
			while ($template = $vbulletin->db->fetch_array($templates))
			{
				$template_cache["$template[templatetype]"]["$template[title]"] = $template;
			}
			$vbulletin->db->free_result($templates);
		}

		// style vars
		if ($actions['dostylevars'])
		{
			// rebuild the stylevars field for this style
			$stylevars = array();
			foreach($template_cache['stylevar'] AS $template)
			{
				// set absolute paths for image directories
				/*if (substr($template['title'], 0, 7) == 'imgdir_')
				{
					if (!preg_match('#^https?://#i', $template['template']))
					{
						$template['template'] = "$template[template]";
					}
				}*/
				$stylevars["$template[title]"] = $template['template'];
			}

			$QUERY[] = "stylevars = '" . $vbulletin->db->escape_string(serialize($stylevars)) . '\'';
			echo "($vbphrase[stylevars]) ";
			vbflush();


			static $master_stylevar_cache = null;
			if ($master_stylevar_cache === null)
			{
				$master_stylevar_cache = array();
				$master_stylevars = $vbulletin->db->query_read("
				SELECT stylevardfn.stylevarid, stylevardfn.datatype, stylevar.value
				FROM " . TABLE_PREFIX . "stylevardfn AS stylevardfn
				LEFT JOIN " . TABLE_PREFIX . "stylevar AS stylevar ON (stylevardfn.stylevarid = stylevar.stylevarid AND stylevar.styleid = -1)
				");
				while ($master_stylevar = $vbulletin->db->fetch_array($master_stylevars))
				{
					$tmp = unserialize($master_stylevar['value']);
					if (!is_array($tmp))
					{
						$tmp = array('value' => $tmp);
					}

					$master_stylevar_cache[$master_stylevar['stylevarid']] = $tmp;
					$master_stylevar_cache[$master_stylevar['stylevarid']]['datatype'] = $master_stylevar['datatype'];
				}

			}

			$newstylevars = $master_stylevar_cache;

			if (substr(trim($parentlist), 0, -3) != '')
			{
				$new_stylevars = $vbulletin->db->query_read($sql = "
				SELECT stylevarid, styleid, value, INSTR(',$parentlist,', CONCAT(',', styleid, ',') ) AS ordercontrol
				FROM " . TABLE_PREFIX . "stylevar
				WHERE styleid IN (" . substr(trim($parentlist), 0, -3) . ")
				ORDER BY ordercontrol DESC
				");
				while ($new_stylevar = $vbulletin->db->fetch_array($new_stylevars))
				{
					$newstylevars[$new_stylevar['stylevarid']] = unserialize($new_stylevar['value']);
					$newstylevars[$new_stylevar['stylevarid']]['datatype'] = $master_stylevar_cache[$new_stylevar['stylevarid']]['datatype'];
				}
			}

			$QUERY[] = "newstylevars = '" . $vbulletin->db->escape_string(serialize($newstylevars)) . '\'';

		}

		// replacements
		if ($actions['doreplacements'])
		{
			// rebuild the replacements field for this style
			$replacements = array();
			if (is_array($template_cache['replacement']))
			{
				foreach($template_cache['replacement'] AS $template)
				{
					// set the key to be a case-insentitive preg find string
					$replacementkey = '#' . preg_quote($template['title'], '#') . '#si';

					$replacements["$replacementkey"] = $template['template'];
				}
				$QUERY[] = 'replacements = \'' . $vbulletin->db->escape_string(serialize($replacements)) . '\'';
			}
			else
			{
				$QUERY[] = 'replacements = \'\'';
			}
			echo "($vbphrase[replacement_variables]) ";
			vbflush();
		}



		// css -- old style css
		if ($actions['docss'])
		{
			// build a quick cache with the ~old~ contents of the css fields from the style table
			if (!is_array($csscache))
			{
				$csscache = array();
				$fetchstyles = $vbulletin->db->query_read("SELECT styleid, css FROM " . TABLE_PREFIX . "style");
				while ($fetchstyle = $vbulletin->db->fetch_array($fetchstyles))
				{
					$fetchstyle['css'] .= "\n";
					$csscache["$fetchstyle[styleid]"] = $fetchstyle['css'];
				}
			}

			// rebuild the css field for this style
			$css = array();
			foreach($template_cache['css'] AS $template)
			{
				$css["$template[title]"] = unserialize($template['template']);
			}

			// build the CSS contents
			$csscolors = array();
			$css = construct_css($css, $styleid, $title, $csscolors);

			// attempt to delete the old css file if it exists
			delete_css_file($styleid, $csscache["$styleid"]);

			$adblock_is_evil = str_replace('ad', 'be', substr(md5(microtime()), 8, 8));
			$cssfilename = 'clientscript/vbulletin_css/style-' . $adblock_is_evil . '-' . str_pad($styleid, 5, '0', STR_PAD_LEFT) . '.css';

			// if we are going to store CSS as files, run replacement variable substitution on the file to be saved
			if ($vbulletin->options['storecssasfile'])
			{
				$css = process_replacement_vars($css, array('styleid' => $styleid, 'replacements' => serialize($replacements)));
				$css = preg_replace('#(?<=[^a-z0-9-]|^)url\((\'|"|)(.*)\\1\)#iUe', "rewrite_css_file_url('\\2', '\\1')", $css);
				if (write_css_file($cssfilename, $css))
				{
					$css = "@import url(\"$cssfilename\");";
				}
			}

			$fullcsstext = "<style type=\"text/css\" id=\"vbulletin_css\">\r\n" .
				"/**\r\n* vBulletin " . $vbulletin->options['templateversion'] . " CSS\r\n* Style: '$title'; Style ID: $styleid\r\n*/\r\n" .
				"$css\r\n</style>\r\n" .
				"<link rel=\"stylesheet\" type=\"text/css\" href=\"clientscript/vbulletin_important.css?v=" . $vbulletin->options['simpleversion'] . "\" />"
			;

			$QUERY[] = "css = '" . $vbulletin->db->escape_string($fullcsstext) . "'";
			$QUERY[] = "csscolors = '" . $vbulletin->db->escape_string(serialize($csscolors)) . "'";

			echo "($vbphrase[css]) ";
			vbflush();
		}

		// post editor styles
		if ($actions['doposteditor'])
		{
			$editorstyles = array();
			foreach ($template_cache['template'] AS $template)
			{
				if (substr($template['title'], 0, 13) == 'editor_styles')
				{
					$title = 'pi' . substr($template['title'], 13);
					$item = fetch_posteditor_styles($template['template']);
					$editorstyles["$title"] = array($item['background'], $item['color'], $item['padding'], $item['border']);
				}
			}
			$QUERY[] = 'editorstyles = \'' . $vbulletin->db->escape_string(serialize($editorstyles)) . '\'';
			echo "($vbphrase[controls]) ";
			vbflush();
		}

		// do the style update query
		if (sizeof($QUERY))
		{
			$vbulletin->db->query_write("UPDATE " . TABLE_PREFIX . "style SET\n" . implode(",\n", $QUERY) . "\nWHERE styleid = $styleid");
		}

		//write out the new css -- do this *after* we update the style record
		if ($vbulletin->options['storecssasfile'])
		{
			if (!write_style_css_directory($styleid, $parentlist, 'ltr'))
			{
				echo fetch_error("rebuild_failed_to_write_css");
			}
			else if (!write_style_css_directory($styleid, $parentlist, 'rtl'))
			{
				echo fetch_error("rebuild_failed_to_write_css");
			}
		}
		else
		{
			// race condition here
			//delete_style_css_directory($styleid, 'ltr');
			//delete_style_css_directory($styleid, 'rtl');
		}

		// finish off the listings
		echo "</span><b>" . $vbphrase['done'] . "</b>.<br />&nbsp;</li>\n"; vbflush();
	}

	$childsets = $vbulletin->db->query_read("
		SELECT styleid, title, parentlist
		FROM " . TABLE_PREFIX . "style
		WHERE parentid = $styleid
	");
	if ($vbulletin->db->num_rows($childsets))
	{
		echo "$indent<ul class=\"ldi\">\n";
		while ($childset = $vbulletin->db->fetch_array($childsets))
		{
			build_style($childset['styleid'], $childset['title'], $actions, $childset['parentlist'], $indent . "\t");
		}
		echo "$indent</ul>\n";
	}
}
/**
* Converts all data from the template table for a style into the style table
*
* @param	integer	Style ID
* @param	string	Title of style
* @param	array	Array of actions set to true/false: docss/dostylevars/doreplacements/doposteditor
* @param	string	List of parent styles
* @param	string	Indent for HTML printing
*/
function build_style($styleid, $title = '', $actions, $parentlist = '', $indent = '')
{
    global $vbulletin, $_queries, $vbphrase, $_query_special_templates;
    static $phrase, $csscache;
    if (($actions['doreplacements'] or $actions['docss']) and $vbulletin->options['storecssasfile']) {
        $actions['docss'] = true;
        $actions['doreplacements'] = true;
    }
    if ($styleid != -1) {
        $QUERY = array();
        // echo the title and start the listings
        echo "{$indent}<li><b>{$title}</b> ... <span class=\"smallfont\">";
        vbflush();
        // build the templateid cache
        $templatelist = build_template_id_cache($styleid, 1, $parentlist);
        $QUERY[] = "templatelist = '" . $vbulletin->db->escape_string($templatelist) . "'";
        echo "({$vbphrase['templates']}) ";
        vbflush();
        // cache special templates
        if ($actions['docss'] or $actions['dostylevars'] or $actions['doreplacements'] or $actions['doposteditor']) {
            // get special templates for this style
            $template_cache = array();
            $templateids = implode(',', unserialize($templatelist));
            $templates = $vbulletin->db->query_read("\n\t\t\t\tSELECT title, template, templatetype\n\t\t\t\tFROM " . TABLE_PREFIX . "template\n\t\t\t\tWHERE templateid IN ({$templateids})\n\t\t\t\t\tAND (templatetype <> 'template' OR title IN('" . implode("', '", $_query_special_templates) . "'))\n\t\t\t");
            while ($template = $vbulletin->db->fetch_array($templates)) {
                $template_cache["{$template['templatetype']}"]["{$template['title']}"] = $template;
            }
            $vbulletin->db->free_result($templates);
        }
        // style vars
        if ($actions['dostylevars']) {
            // rebuild the stylevars field for this style
            $stylevars = array();
            foreach ($template_cache['stylevar'] as $template) {
                // set absolute paths for image directories
                /*if (substr($template['title'], 0, 7) == 'imgdir_')
                		{
                			if (!preg_match('#^https?://#i', $template['template']))
                			{
                				$template['template'] = "$template[template]";
                			}
                		}*/
                $stylevars["{$template['title']}"] = $template['template'];
            }
            $QUERY[] = "stylevars = '" . $vbulletin->db->escape_string(serialize($stylevars)) . '\'';
            echo "({$vbphrase['stylevars']}) ";
            vbflush();
        }
        // replacements
        if ($actions['doreplacements']) {
            // rebuild the replacements field for this style
            $replacements = array();
            if (is_array($template_cache['replacement'])) {
                foreach ($template_cache['replacement'] as $template) {
                    // set the key to be a case-insentitive preg find string
                    $replacementkey = '#' . preg_quote($template['title'], '#') . '#si';
                    $replacements["{$replacementkey}"] = $template['template'];
                }
                $QUERY[] = 'replacements = \'' . $vbulletin->db->escape_string(serialize($replacements)) . '\'';
            } else {
                $QUERY[] = 'replacements = \'\'';
            }
            echo "({$vbphrase['replacement_variables']}) ";
            vbflush();
        }
        // css
        if ($actions['docss']) {
            // build a quick cache with the ~old~ contents of the css fields from the style table
            if (!is_array($csscache)) {
                $csscache = array();
                $fetchstyles = $vbulletin->db->query_read("SELECT styleid, css FROM " . TABLE_PREFIX . "style");
                while ($fetchstyle = $vbulletin->db->fetch_array($fetchstyles)) {
                    $fetchstyle['css'] .= "\n";
                    $csscache["{$fetchstyle['styleid']}"] = $fetchstyle['css'];
                }
            }
            // rebuild the css field for this style
            $css = array();
            foreach ($template_cache['css'] as $template) {
                $css["{$template['title']}"] = unserialize($template['template']);
            }
            // build the CSS contents
            $csscolors = array();
            $css = construct_css($css, $styleid, $title, $csscolors);
            // attempt to delete the old css file if it exists
            delete_css_file($styleid, $csscache["{$styleid}"]);
            $adblock_is_evil = str_replace('ad', 'be', substr(md5(microtime()), 8, 8));
            $cssfilename = 'clientscript/vbulletin_css/style-' . $adblock_is_evil . '-' . str_pad($styleid, 5, '0', STR_PAD_LEFT) . '.css';
            // if we are going to store CSS as files, run replacement variable substitution on the file to be saved
            if ($vbulletin->options['storecssasfile'] and write_css_file($cssfilename, process_replacement_vars($css, array('styleid' => $styleid, 'replacements' => serialize($replacements))))) {
                $css = "@import url(\"{$cssfilename}\");";
            }
            $fullcsstext = "<style type=\"text/css\" id=\"vbulletin_css\">\r\n" . "/**\r\n* vBulletin " . $vbulletin->options['templateversion'] . " CSS\r\n* Style: '{$title}'; Style ID: {$styleid}\r\n*/\r\n" . "{$css}\r\n</style>\r\n" . "<link rel=\"stylesheet\" type=\"text/css\" href=\"clientscript/vbulletin_important.css?v=" . $vbulletin->options['simpleversion'] . "\" />";
            $QUERY[] = "css = '" . $vbulletin->db->escape_string($fullcsstext) . "'";
            $QUERY[] = "csscolors = '" . $vbulletin->db->escape_string(serialize($csscolors)) . "'";
            echo "({$vbphrase['css']}) ";
            vbflush();
        }
        // post editor styles
        if ($actions['doposteditor']) {
            $editorstyles = array();
            foreach ($template_cache['template'] as $template) {
                if (substr($template['title'], 0, 13) == 'editor_styles') {
                    $title = 'pi' . substr($template['title'], 13);
                    $item = fetch_posteditor_styles($template['template']);
                    $editorstyles["{$title}"] = array($item['background'], $item['color'], $item['padding'], $item['border']);
                }
            }
            $QUERY[] = 'editorstyles = \'' . $vbulletin->db->escape_string(serialize($editorstyles)) . '\'';
            echo "({$vbphrase['controls']}) ";
            vbflush();
        }
        // do the style update query
        if (sizeof($QUERY)) {
            $vbulletin->db->query_write("UPDATE " . TABLE_PREFIX . "style SET\n" . implode(",\n", $QUERY) . "\nWHERE styleid = {$styleid}");
        }
        // finish off the listings
        echo "</span><b>" . $vbphrase['done'] . "</b>.<br />&nbsp;</li>\n";
        vbflush();
    }
    $childsets = $vbulletin->db->query_read("\n\t\tSELECT styleid, title, parentlist\n\t\tFROM " . TABLE_PREFIX . "style\n\t\tWHERE parentid = {$styleid}\n\t");
    if ($vbulletin->db->num_rows($childsets)) {
        echo "{$indent}<ul class=\"ldi\">\n";
        while ($childset = $vbulletin->db->fetch_array($childsets)) {
            build_style($childset['styleid'], $childset['title'], $actions, $childset['parentlist'], $indent . "\t");
        }
        echo "{$indent}</ul>\n";
    }
}
/**
* Converts all data from the template table for a style into the style table
*
* @param	integer	Style ID
* @param	string	Title of style
* @param	array	Array of actions set to true/false: docss/dostylevars/doreplacements
* @param	string	List of parent styles
* @param	string	Indent for HTML printing
* @param	boolean	Reset the master cache
*/
function build_style($styleid, $title = '', $actions = array(), $parentlist = '', $indent = '', $resetcache = false)
{
    global $vbulletin, $_queries, $vbphrase, $_query_special_templates;
    static $phrase, $csscache;
    if (($actions['doreplacements'] or $actions['docss'] or $actions['dostylevars']) and $vbulletin->options['storecssasfile']) {
        $actions['docss'] = true;
        $actions['doreplacements'] = true;
    }
    if ($styleid != -1 and $styleid != -2) {
        $style = $vbulletin->db->query_first("\n\t\t\tSELECT *\n\t\t\tFROM " . TABLE_PREFIX . "style\n\t\t\tWHERE styleid = {$styleid}\n\t\t");
        $masterstyleid = $style['type'] == 'standard' ? -1 : -2;
        $QUERY = array('' => "dateline = " . TIMENOW);
        if (VB_AREA != 'Upgrade' and VB_AREA != 'Install') {
            // echo the title and start the listings
            echo "{$indent}<li><b>{$title}</b> ... <span class=\"smallfont\">";
            vbflush();
        }
        // build the templateid cache
        if (!$parentlist) {
            $parentlist = fetch_parentids($styleid);
        }
        $templatelist = build_template_id_cache($styleid, 1, $parentlist);
        $QUERY[] = "templatelist = '" . $vbulletin->db->escape_string($templatelist) . "'";
        if (VB_AREA != 'Upgrade' and VB_AREA != 'Install') {
            echo "({$vbphrase['templates']}) ";
            vbflush();
        }
        // cache special templates
        if ($actions['docss'] or $actions['dostylevars'] or $actions['doreplacements']) {
            // get special templates for this style
            $template_cache = array();
            if ($templateids = implode(',', unserialize($templatelist))) {
                $templates = $vbulletin->db->query_read("\n\t\t\t\t\tSELECT title, template, templatetype\n\t\t\t\t\tFROM " . TABLE_PREFIX . "template\n\t\t\t\t\tWHERE templateid IN ({$templateids})\n\t\t\t\t\t\tAND (templatetype <> 'template' OR title IN('" . implode("', '", $_query_special_templates) . "'))\n\t\t\t\t");
                while ($template = $vbulletin->db->fetch_array($templates)) {
                    $template_cache["{$template['templatetype']}"]["{$template['title']}"] = $template;
                }
                $vbulletin->db->free_result($templates);
            }
        }
        // style vars
        if ($actions['dostylevars']) {
            // rebuild the stylevars field for this style
            $stylevars = array();
            if ($template_cache['stylevar']) {
                foreach ($template_cache['stylevar'] as $template) {
                    $stylevars["{$template['title']}"] = $template['template'];
                }
                $QUERY[] = "stylevars = '" . $vbulletin->db->escape_string(serialize($stylevars)) . '\'';
            }
            if (VB_AREA != 'Upgrade' and VB_AREA != 'Install') {
                echo "({$vbphrase['stylevars']}) ";
                vbflush();
            }
            static $master_stylevar_cache = array(-1 => null, -2 => null);
            static $resetcachedone = array(-1 => false, -2 => false);
            if ($resetcache and !$resetcachedone[$masterstyleid]) {
                $resetcachedone[$masterstyleid] = true;
                $master_stylevar_cache[$masterstyleid] = null;
            }
            if ($master_stylevar_cache[$masterstyleid] === null) {
                $master_stylevar_cache[$masterstyleid] = array();
                $master_stylevars = $vbulletin->db->query_read("\n\t\t\t\tSELECT stylevardfn.stylevarid, stylevardfn.datatype, stylevar.value\n\t\t\t\tFROM " . TABLE_PREFIX . "stylevardfn AS stylevardfn\n\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "stylevar AS stylevar ON (stylevardfn.stylevarid = stylevar.stylevarid AND stylevar.styleid = {$masterstyleid})\n\t\t\t\t");
                while ($master_stylevar = $vbulletin->db->fetch_array($master_stylevars)) {
                    $tmp = unserialize($master_stylevar['value']);
                    if (!is_array($tmp)) {
                        $tmp = array('value' => $tmp);
                    }
                    $master_stylevar_cache[$masterstyleid][$master_stylevar['stylevarid']] = $tmp;
                    $master_stylevar_cache[$masterstyleid][$master_stylevar['stylevarid']]['datatype'] = $master_stylevar['datatype'];
                }
            }
            $newstylevars = $master_stylevar_cache[$masterstyleid];
            if (substr(trim($parentlist), 0, -3) != '') {
                $new_stylevars = $vbulletin->db->query_read($sql = "\n\t\t\t\tSELECT\n\t\t\t\t\tstylevarid, styleid, value, INSTR(',{$parentlist},', CONCAT(',', styleid, ',') ) AS ordercontrol\n\t\t\t\tFROM " . TABLE_PREFIX . "stylevar\n\t\t\t\tWHERE\n\t\t\t\t\tstyleid IN (" . substr(trim($parentlist), 0, -3) . ")\n\t\t\t\tORDER BY\n\t\t\t\t\tordercontrol DESC\n\t\t\t\t");
                while ($new_stylevar = $vbulletin->db->fetch_array($new_stylevars)) {
                    $newstylevars[$new_stylevar['stylevarid']] = unserialize($new_stylevar['value']);
                    $newstylevars[$new_stylevar['stylevarid']]['datatype'] = $master_stylevar_cache[$masterstyleid][$new_stylevar['stylevarid']]['datatype'];
                }
            }
            if ($newstylevars) {
                $QUERY[] = "newstylevars = '" . $vbulletin->db->escape_string(serialize($newstylevars)) . '\'';
            }
        }
        // replacements
        if ($actions['doreplacements']) {
            // rebuild the replacements field for this style
            $replacements = array();
            if (is_array($template_cache['replacement'])) {
                foreach ($template_cache['replacement'] as $template) {
                    // set the key to be a case-insentitive preg find string
                    $replacementkey = '#' . preg_quote($template['title'], '#') . '#si';
                    $replacements["{$replacementkey}"] = $template['template'];
                }
                $QUERY[] = 'replacements = \'' . $vbulletin->db->escape_string(serialize($replacements)) . '\'';
            } else {
                $QUERY[] = 'replacements = \'\'';
            }
            if (VB_AREA != 'Upgrade' and VB_AREA != 'Install') {
                echo "({$vbphrase['replacement_variables']}) ";
                vbflush();
            }
        }
        // css -- old style css
        if ($actions['docss'] and $template_cache['css']) {
            // build a quick cache with the ~old~ contents of the css fields from the style table
            if (!is_array($csscache)) {
                $csscache = array();
                $fetchstyles = $vbulletin->db->query_read("SELECT styleid, css FROM " . TABLE_PREFIX . "style");
                while ($fetchstyle = $vbulletin->db->fetch_array($fetchstyles)) {
                    $fetchstyle['css'] .= "\n";
                    $csscache["{$fetchstyle['styleid']}"] = $fetchstyle['css'];
                }
            }
            // rebuild the css field for this style
            $css = array();
            foreach ($template_cache['css'] as $template) {
                $css["{$template['title']}"] = unserialize($template['template']);
            }
            // build the CSS contents
            $csscolors = array();
            $css = construct_css($css, $styleid, $title, $csscolors);
            // attempt to delete the old css file if it exists
            delete_css_file($styleid, $csscache["{$styleid}"]);
            $adblock_is_evil = str_replace('ad', 'be', substr(md5(microtime()), 8, 8));
            $cssfilename = 'clientscript/vbulletin_css/style-' . $adblock_is_evil . '-' . str_pad($styleid, 5, '0', STR_PAD_LEFT) . '.css';
            // if we are going to store CSS as files, run replacement variable substitution on the file to be saved
            if ($vbulletin->options['storecssasfile']) {
                $css = process_replacement_vars($css, array('styleid' => $styleid, 'replacements' => serialize($replacements)));
                $css = preg_replace('#(?<=[^a-z0-9-]|^)url\\((\'|"|)(.*)\\1\\)#iUe', "rewrite_css_file_url('\\2', '\\1')", $css);
                if (write_css_file($cssfilename, $css)) {
                    $css = "@import url(\"{$cssfilename}\");";
                }
            }
            $fullcsstext = "<style type=\"text/css\" id=\"vbulletin_css\">\r\n" . "/**\r\n* vBulletin " . $vbulletin->options['templateversion'] . " CSS\r\n* Style: '{$title}'; Style ID: {$styleid}\r\n*/\r\n" . "{$css}\r\n</style>\r\n" . "<link rel=\"stylesheet\" type=\"text/css\" href=\"clientscript/vbulletin_important.css?v=" . $vbulletin->options['simpleversion'] . "\" />";
            $QUERY[] = "css = '" . $vbulletin->db->escape_string($fullcsstext) . "'";
            $QUERY[] = "csscolors = '" . $vbulletin->db->escape_string(serialize($csscolors)) . "'";
            if (VB_AREA != 'Upgrade' and VB_AREA != 'Install') {
                echo "({$vbphrase['css']}) ";
                vbflush();
            }
        }
        // do the style update query
        if (sizeof($QUERY)) {
            $vbulletin->db->query_write("UPDATE " . TABLE_PREFIX . "style SET\n" . implode(",\n", $QUERY) . "\nWHERE styleid = {$styleid}");
        }
        //write out the new css -- do this *after* we update the style record
        if ($vbulletin->options['storecssasfile']) {
            if (!write_style_css_directory($styleid, $parentlist, 'ltr')) {
                if (VB_AREA != 'Upgrade' and VB_AREA != 'Install') {
                    echo fetch_error("rebuild_failed_to_write_css");
                } else {
                    return fetch_error("rebuild_failed_to_write_css");
                }
            } else {
                if (!write_style_css_directory($styleid, $parentlist, 'rtl')) {
                    if (VB_AREA != 'Upgrade' and VB_AREA != 'Install') {
                        echo fetch_error("rebuild_failed_to_write_css");
                    } else {
                        return fetch_error("rebuild_failed_to_write_css");
                    }
                }
            }
        } else {
            // race condition here
            //delete_style_css_directory($styleid, 'ltr');
            //delete_style_css_directory($styleid, 'rtl');
        }
        // finish off the listings
        if (VB_AREA != 'Upgrade' and VB_AREA != 'Install') {
            echo "</span><b>" . $vbphrase['done'] . "</b>.<br />&nbsp;</li>\n";
            vbflush();
        }
    }
    $childsets = $vbulletin->db->query_read("\n\t\tSELECT\n\t\t\tstyleid, title, parentlist\n\t\tFROM " . TABLE_PREFIX . "style\n\t\tWHERE\n\t\t\tparentid = {$styleid}\n\t");
    if ($vbulletin->db->num_rows($childsets)) {
        if (VB_AREA != 'Upgrade' and VB_AREA != 'Install') {
            echo "{$indent}<ul class=\"ldi\">\n";
        }
        while ($childset = $vbulletin->db->fetch_array($childsets)) {
            if ($error = build_style($childset['styleid'], $childset['title'], $actions, $childset['parentlist'], $indent . "\t", $resetcache)) {
                return $error;
            }
        }
        if (VB_AREA != 'Upgrade' and VB_AREA != 'Install') {
            echo "{$indent}</ul>\n";
        }
    }
}
Beispiel #4
0
 /**
  *	Internal function to handle the recursion for buildStyle.
  *
  */
 private function buildStyleInternal($styleid, $title = '', $actions = array(), $parentlist = '', $resetcache = false)
 {
     $assertor = vB::getDbAssertor();
     require_once DIR . '/includes/adminfunctions.php';
     require_once DIR . '/includes/adminfunctions_template.php';
     static $csscache = array();
     if (($actions['doreplacements'] or $actions['docss'] or $actions['dostylevars']) and vB::getDatastore()->getOption('storecssasfile')) {
         $actions['docss'] = true;
         $actions['doreplacements'] = true;
     }
     if ($styleid != -1) {
         unset($this->stylesById[$styleid]);
         // build the templateid cache
         if (!$parentlist) {
             $parentlist = $this->fetchTemplateParentlist($styleid);
         }
         $templatelist = $this->buildTemplateIdCache($styleid, 1, $parentlist);
         $styleupdate = array();
         $styleupdate['templatelist'] = $templatelist;
         // cache special templates
         if ($actions['docss'] or $actions['dostylevars'] or $actions['doreplacements'] or $actions['doposteditor']) {
             // get special templates for this style
             $template_cache = array();
             $templateids = unserialize($templatelist);
             $specials = vB_Api::instanceInternal('template')->fetchSpecialTemplates();
             if ($templateids) {
                 $templates = vB::getDbAssertor()->assertQuery('vBForum:fetchtemplatewithspecial', array('templateids' => $templateids, 'specialtemplates' => $specials));
                 foreach ($templates as $template) {
                     $template_cache["{$template['templatetype']}"]["{$template['title']}"] = $template;
                 }
             }
         }
         // style vars
         if ($actions['dostylevars']) {
             if ($template_cache['stylevar']) {
                 // rebuild the stylevars field for this style
                 $stylevars = array();
                 foreach ($template_cache['stylevar'] as $template) {
                     $stylevars["{$template['title']}"] = $template['template'];
                 }
             }
             // new stylevars
             static $master_stylevar_cache = null;
             if ($resetcache) {
                 $resetcachedone = true;
                 $master_stylevar_cache = null;
             }
             if ($master_stylevar_cache === null) {
                 $master_stylevar_cache = array();
                 $master_stylevars = vB::getDbAssertor()->assertQuery('vBForum:getDefaultStyleVars', array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_STORED));
                 foreach ($master_stylevars as $master_stylevar) {
                     $tmp = unserialize($master_stylevar['value']);
                     if (!is_array($tmp)) {
                         $tmp = array('value' => $tmp);
                     }
                     $master_stylevar_cache[$master_stylevar['stylevarid']] = $tmp;
                     $master_stylevar_cache[$master_stylevar['stylevarid']]['datatype'] = $master_stylevar['datatype'];
                 }
             }
             $newstylevars = $master_stylevar_cache;
             if (substr(trim($parentlist), 0, -3) != '') {
                 $data = array('stylelist' => explode(',', substr(trim($parentlist), 0, -3)), 'parentlist' => $parentlist);
                 $new_stylevars = vB::getDbAssertor()->getRows('vBForum:getStylesFromList', $data);
                 foreach ($new_stylevars as $new_stylevar) {
                     ob_start();
                     $newstylevars[$new_stylevar['stylevarid']] = unserialize($new_stylevar['value']);
                     if (ob_get_clean() or !is_array($newstylevars[$new_stylevar['stylevarid']])) {
                         continue;
                     }
                     $newstylevars[$new_stylevar['stylevarid']]['datatype'] = $master_stylevar_cache[$new_stylevar['stylevarid']]['datatype'];
                 }
             }
             $styleupdate['newstylevars'] = serialize($newstylevars);
         }
         // replacements
         if ($actions['doreplacements']) {
             // rebuild the replacements field for this style
             $replacements = array();
             if (is_array($template_cache['replacement'])) {
                 foreach ($template_cache['replacement'] as $template) {
                     // set the key to be a case-insentitive preg find string
                     $replacementkey = '#' . preg_quote($template['title'], '#') . '#si';
                     $replacements["{$replacementkey}"] = $template['template'];
                 }
                 $styleupdate['replacements'] = serialize($replacements);
             } else {
                 $styleupdate['replacements'] = "''";
             }
         }
         // css -- old style css
         if ($actions['docss'] and $template_cache['css']) {
             // build a quick cache with the ~old~ contents of the css fields from the style table
             if (empty($csscache)) {
                 $fetchstyles = vB::getDbAssertor()->assertQuery('vBForum:style', array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_SELECT));
                 foreach ($fetchstyles as $fetchstyle) {
                     $fetchstyle['css'] .= "\n";
                     $csscache["{$fetchstyle['styleid']}"] = $fetchstyle['css'];
                 }
             }
             // rebuild the css field for this style
             $css = array();
             foreach ($template_cache['css'] as $template) {
                 $css["{$template['title']}"] = unserialize($template['template']);
             }
             // build the CSS contents
             $csscolors = array();
             $css = construct_css($css, $styleid, $title, $csscolors);
             // attempt to delete the old css file if it exists
             delete_css_file($styleid, $csscache["{$styleid}"]);
             $adblock_is_evil = str_replace('ad', 'be', substr(md5(microtime()), 8, 8));
             $cssfilename = DIR . vB_Api::instanceInternal('style')->fetchCssLocation() . '/style-' . $adblock_is_evil . '-' . str_pad($styleid, 5, '0', STR_PAD_LEFT) . '.css';
             // if we are going to store CSS as files, run replacement variable substitution on the file to be saved
             if (vB::getDatastore()->getOption('storecssasfile')) {
                 $css = process_replacement_vars($css, array('styleid' => $styleid, 'replacements' => serialize($replacements)));
                 $css = preg_replace_callback('#(?<=[^a-z0-9-]|^)url\\((\'|"|)(.*)\\1\\)#iU', function ($matches) {
                     return rewrite_css_file_url($matches[2], $matches[1]);
                 }, $css);
                 if (write_css_file($cssfilename, $css)) {
                     $css = "@import url(\"{$cssfilename}\");";
                 }
             }
         }
         // post editor styles
         if ($actions['doposteditor'] and $template_cache['template']) {
             $editorstyles = array();
             if (!empty($template_cache['template'])) {
                 foreach ($template_cache['template'] as $template) {
                     if (substr($template['title'], 0, 13) == 'editor_styles') {
                         $title = 'pi' . substr($template['title'], 13);
                         $item = fetch_posteditor_styles($template['template']);
                         $editorstyles["{$title}"] = array($item['background'], $item['color'], $item['padding'], $item['border']);
                     }
                 }
             }
         }
         // do the style update query
         if (!empty($styleupdate)) {
             $styleupdate['styleid'] = $styleid;
             $styleupdate[vB_dB_Query::TYPE_KEY] = vB_dB_Query::QUERY_UPDATE;
             vB::getDbAssertor()->assertQuery('vBForum:style', $styleupdate);
         }
         //write out the new css -- do this *after* we update the style record
         if (vB::getDatastore()->getOption('storecssasfile')) {
             if (!write_style_css_directory($styleid, $parentlist, 'ltr')) {
                 return fetch_error("rebuild_failed_to_write_css");
             } else {
                 if (!write_style_css_directory($styleid, $parentlist, 'rtl')) {
                     return fetch_error("rebuild_failed_to_write_css");
                 }
             }
         }
     }
     $childsets = vB::getDbAssertor()->getRows('style', array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_SELECT, vB_dB_Query::CONDITIONS_KEY => array('parentid' => $styleid)));
     if (count($childsets)) {
         foreach ($childsets as $childset) {
             if ($error = $this->buildStyleInternal($childset['styleid'], $childset['title'], $actions, $childset['parentlist'], false)) {
                 return $error;
             }
         }
     }
     //We want to force a fastDS rebuild, but we can't just call rebuild. There may be dual web servers,
     // and calling rebuild only rebuilds one of them.
     $options = vB::getDatastore()->getValue('miscoptions');
     $options['tmtdate'] = vB::getRequest()->getTimeNow();
     vB::getDatastore()->build('miscoptions', serialize($options), 1);
 }
 /**
  * Returns a vB3 stylevar value
  *
  * @param	string	The vB3 stylevar type [csscolors|stylevars|editorstyles]
  * @param	string	The vB3 stylevar name
  *
  * @return	mixed	The vB3 stylevar value or null if the stylevar doesn't exist/is not set
  */
 protected function get_vb3_stylevar($stylevar_type, $stylevar_name)
 {
     if ($this->vb3_stylevar_cache === null) {
         $style = $this->db->query_first("\n\t\t\t\tSELECT *\n\t\t\t\tFROM " . TABLE_PREFIX . "style\n\t\t\t\tWHERE styleid = " . intval($this->styleid) . "\n\t\t\t");
         $this->vb3_stylevar_cache = array('csscolors' => unserialize($style['csscolors']), 'stylevars' => unserialize($style['stylevars']), 'editorstyles' => unserialize($style['editorstyles']));
         // Add empty values for items that have been customized as empty
         // by checking to see if they are defined in the master style.
         // Ignore editorstyles as they will not be customizable in vB4.
         $master = $this->db->query_read("\n\t\t\t\tSELECT title, templatetype, template\n\t\t\t\tFROM " . TABLE_PREFIX . "template\n\t\t\t\tWHERE\n\t\t\t\t\tstyleid = {$this->masterstyleid}\n\t\t\t\t\t\tAND\n\t\t\t\t\ttemplatetype IN('stylevar', 'css')\n\t\t\t");
         $css = array();
         $stylevars = array();
         while ($template = $this->db->fetch_array($master)) {
             if ($template['templatetype'] == 'css') {
                 $css[$template['title']] = unserialize($template['template']);
             } else {
                 $stylevars[$template['title']] = $template['template'];
             }
         }
         require_once DIR . '/includes/adminfunctions_template.php';
         $csscolors = array();
         construct_css($css, '', '', $csscolors);
         foreach ($csscolors as $k => $v) {
             if (!isset($this->vb3_stylevar_cache['csscolors'][$k])) {
                 $this->vb3_stylevar_cache['csscolors'][$k] = '';
             }
         }
         foreach ($stylevars as $k => $v) {
             if (!isset($this->vb3_stylevar_cache['stylevars'][$k])) {
                 $this->vb3_stylevar_cache['stylevars'][$k] = '';
             }
         }
     }
     if (isset($this->vb3_stylevar_cache[$stylevar_type][$stylevar_name])) {
         return $this->vb3_stylevar_cache[$stylevar_type][$stylevar_name];
     } else {
         return null;
     }
 }