<?php
//=== get path =====
//include('D:\xampp\htdocs\dozenofshops\wp-content\info\debug.php');
$site_url = get_bloginfo('url');
$domainId = '';
$hddlSTAct = '';	
define('CUSTOM_DIR_LOC', get_bloginfo('template_url'));
$endIndex = strpos(dirname(__FILE__), 'wp-content', 0);
$initialPath = substr(dirname(__FILE__), 0, $endIndex);
$midPath = wpContentUrl(CUSTOM_DIR_LOC);	
$finalPath = $initialPath.$midPath;
$endIndex = strrpos($finalPath, '\\', 0);
$finalPath = substr($finalPath, 0, $endIndex);
$finalPath .='\\thesis_18\\custom';

if ( is_admin() ) {
	//plugin activation
	//add_action('activate_wp3-iis/skin-editor.php', 'wp3iis_init');
	register_activation_hook($mainPlugFile, 'skineditor_init' );
	//settings menu
	add_action('admin_menu', 'skineditor_tools_menu');
	//load css
	add_action('admin_print_styles', 'skineditor_load_stylesheets' );
	//add data returning ajax refresh table function
	add_action('wp_ajax_skineditor_addSubTheme', 'addSubTheme', 10);
	add_action('wp_ajax_skineditor_loopActivateTheme', 'loopActivateTheme', 10);
	add_action('wp_ajax_skineditor_addVariation', 'addVariation', 10);
	add_action('wp_ajax_skineditor_activate', 'activateVariation', 10);
	add_action('wp_ajax_skineditor_edit', 'editFiles', 10);
}
else{
	//load css
	add_action('wp_head', 'skineditor_load_stylesheets');
}
//============== ajax functions ============================== D:\xampp\htdocs\dwdining\  
function addSubTheme(){
	global $initialPath;
	$txtSubTheme = trim($_GET['txtSubTheme']);	
	if ($txtSubTheme == ''||strpos($txtSubTheme, 'ype skin name here', 0)){		
		pathetic_fail('please type the skin name');
		return;
	}	
	$txtSubTheme = str_replace(' ','_',$txtSubTheme);
	// ========== check if exists =========================	
	$searchTheme = readRecords("SELECT `sub_theme` FROM `wp_se_sub_theme` WHERE `sub_theme` = '{$txtSubTheme}';");
	if (count($searchTheme)>0){		
		pathetic_fail('skin exists');
		return;
	}
	// ============= create sub theme file =================== D:\xampp\htdocs\dwdining\wp-content\themes
	$subThemePath = $initialPath . 'wp-content\\themes\\skins\\' . $txtSubTheme;	
	alterFiles($subThemePath . '\\images');	
		$strData ="<?php \n";
		$strData .="/** \n";
		$strData .="* @package WordPress \n";
		$strData .="* @subpackage {$txtSubTheme} \n";
		$strData .="*/ \n";
		$strData .="//========= put you custom code here ============ \n";		
		$strData .="\n";
		$strData .="?>";
	alterFiles('', $subThemePath.'\\functions.php', $strData);
		$strData ="/*\n";
		$strData .="Theme Name: {$txtSubTheme}\n";
		$strData .="Theme URI: http://www.dennisonwolfe.com\n";
		$descr = $_GET['txtDescription'];
		if (strpos($descr, 'ype Description', 0)){		
			$descr = '';
		}
		$strData .="Description: {$descr}\n";
		$strData .="Version: 1.0\n";
		$strData .="Author: Dennison+Wolfe Internet Group\n";
		$strData .="Author URI: http://www.dennisonwolfe.com\n";
		$strData .="Template: {$_GET['ddlThemesTypes']}\n";
		$strData .="css: level2\n";
		$strData .="\n";
		$strData .="\tThe CSS, XHTML and design is released under GPL:\n";
		$strData .="\thttp://www.opensource.org/licenses/gpl-license.php\n";
		$strData .="\n";
		$strData .="*/\n";
		$strData .="\n";
		$strData .="@import url(\"../../{$_GET['ddlThemesTypes']}/style.css\");\n\n";
		$strData .="/* ==========================================  applies to all ============================================================================================== */\n";
		$strData .=".clear {\n";
		$strData .="\tclear: both;\n";
		$strData .="\theight: 0px;\n";
		$strData .="\tpadding: 0px;\n";
		$strData .="\tmargin: 0px;\n";
		$strData .="}\n";
	alterFiles('', $subThemePath.'\\style.css', $strData);
	// ============= save name to data base ==================
	$subThemePath = 'wp-content\\themes\\skins\\' . $txtSubTheme;
	$subThemePath = str_replace('\\', '\\\\', $subThemePath);	
	alterDb('update', "INSERT INTO wp_se_sub_theme ( sub_theme, sub_theme_path, sub_theme_template) VALUES ('{$txtSubTheme}','{$subThemePath}','{$_GET['ddlThemesTypes']}');");
	//============ fill stuff ===============================
	$dropdown = fillListSubThemes('ddlSubThemes',true);
	echo 'document.getElementById("listSubThemes").innerHTML="'.$dropdown.'";';
	$dropdown = fillListSubThemes('ddlSTAct',true);
	echo 'document.getElementById("listSTAct").innerHTML="'.$dropdown.'";';
	$dropdown = fillListSubThemes('ddlSTEdit',true);
	echo 'document.getElementById("listSTEdit").innerHTML="'.$dropdown.'";';
	echo 'document.getElementById("info_message").innerHTML="skin files have been created";';		
	die;
}

function addVariation(){
	global $initialPath, $hddlSTAct;
	$txtVariations = trim($_GET['txtVariations']);
	$ddlSubThemes = $_GET['ddlSubThemes'];
	
	if ($_GET['actionChoise']=='fill'){
		$dropdown = fillListVariation('lstVariations', $_GET['ddlSubThemes'], true);
		echo 'document.getElementById("listVariation").innerHTML="'.$dropdown.'";';
		echo 'document.getElementById("info_message").innerHTML="";';
	}else{
		if ($ddlSubThemes == '' || strpos($ddlSubThemes, 'elect', 0)){		
			pathetic_fail('please select a skin');
			return;
		}
		if ($txtVariations == ''||strpos($txtVariations, 'ype variation name', 0)){		
			pathetic_fail('please type variation name');
			return;
		}
		// ========== check if exists =========================	
		$searchTheme = readRecords("SELECT `sub_theme_variation` FROM `wp_se_sub_theme_variation` WHERE `sub_theme_variation` = '{$txtVariations}' AND `sub_theme` = '{$ddlSubThemes}';");
		if (count($searchTheme)>0){		
			pathetic_fail('variation exists');
			return;
		}
		$txtVariations = str_replace(' ','_',$txtVariations);
		//=============== add image folder =========================================== 		
		$variationPath = $initialPath . 'wp-content\\themes\\skins\\'.$ddlSubThemes.'\\'.$txtVariations;
		alterFiles($variationPath . '\\images');		
		//=============== add files ==================================================
		$strData ="/*\n";
		$strData .="Version: 1.0\n";
		$strData .="Author: Dennison+Wolfe Internet Group\n";
		$strData .="Author URI: http://www.dennisonwolfe.com\n";
		$strData .="Sub Theme: ".$ddlSubThemes."\n";
		$strData .="Variation Name: ".$txtVariations."\n";
		$strData .="css: level3\n";
		$strData .="*/\n";
		alterFiles('', $variationPath.'\\'.$txtVariations.'.css', $strData);
		
		//=============== add database record ==========================================$variationPath = $variationPath.'\\'.$txtVariations.'.css';	
		$variationPath = 'wp-content\\themes\\skins\\'.$ddlSubThemes.'\\'.$txtVariations.'\\'.$txtVariations.'.css';
		$variationPath = str_replace('\\', '\\\\', $variationPath);		
		alterDb('update', "INSERT INTO wp_se_sub_theme_variation ( sub_theme, sub_theme_variation, sub_theme_variation_path) VALUES ('{$ddlSubThemes}','{$txtVariations}','{$variationPath}');");
		$dropdown = fillListVariation('lstVariations', $_GET['ddlSubThemes'], true);
		echo 'document.getElementById("listVariation").innerHTML="'.$dropdown.'";';			
		$dropdown = fillListVariation('ddlVAct', $_GET['hddlSTAct'], true, true);		
		echo 'document.getElementById("listVAct").innerHTML="'.$dropdown.'";';
		$dropdown = fillListVariation('ddlVEdit', $_GET['hddlSTAct'], true, true);		
		echo 'document.getElementById("listVEdit").innerHTML="'.$dropdown.'";';
		echo 'document.getElementById("info_message").innerHTML="variation files have been created";';
	}	
	die;
}

function activateVariation(){
global $initialPath, $domainId;
	switch ($_GET['actionChoise']) {
		case "fill":
			$dropdown = fillListDomain('ddlUrl', $_GET['txtUrl'], true);
			echo 'document.getElementById("listUrl").innerHTML="'.$dropdown.'";';
			echo 'document.getElementById("info_message").innerHTML="'.trim($_GET['txtUrl']).'";';
			break;
		case "fillAct":	
			if ($_GET['ddlUrl'] == 'select'){				
				echo 'document.getElementById("ddlSTAct").selectedIndex=0;';	
				pathetic_fail('please select domain/url');				
			}
			$dropdown = fillListVariation('ddlVAct', $_GET['ddlSTAct'], true, true);
			echo 'document.getElementById("listVAct").innerHTML="'.$dropdown.'";';
			echo 'document.getElementById("info_message").innerHTML="";';
			break;
		case "deactivate":
			alterDb('update', "UPDATE wp_se_skin_activation SET `active` = 0 WHERE (`domain` = '{$_GET['ddlUrl']}');");
			echo 'document.getElementById("info_message").innerHTML="deactivated";';
			break;
		case "activate":			
			validateActivate($_GET['ddlUrl'], $_GET['ddlSTAct'], $_GET['ddlVAct']);
			alterDb('update', "UPDATE wp_se_skin_activation SET `active` = 0 WHERE (`domain` = '{$_GET['ddlUrl']}');");
			//======== activate sub theme ==========================			
				/* activating of the sub theme is done from the javascrpt side*/ 
			// ========== check if exists ===========================
			$searchTheme = readRecords("SELECT `sub_theme` FROM `wp_se_skin_activation` WHERE (`domain` = '{$_GET['ddlUrl']}' AND `sub_theme` = '{$_GET['ddlSTAct']}' AND `sub_theme_variation` = '{$_GET['ddlVAct']}');");
			if (count($searchTheme)>0){					
				alterDb('update', "UPDATE wp_se_skin_activation SET `active` = 1 WHERE (`domain` = '{$_GET['ddlUrl']}' AND `sub_theme` = '{$_GET['ddlSTAct']}' AND `sub_theme_variation` = '{$_GET['ddlVAct']}');");				
				echo 'document.getElementById("info_message").innerHTML="activated";';
				
			}else{			
				//======== create files ================================
				$sitefilepath = create_skin_folder($_GET['ddlUrl'], $_GET['ddlSTAct'], $_GET['ddlVAct']);
				$sitefilepath = str_replace('\\', '\\\\', $sitefilepath);				
				//============ add record in db ========================
				$variationPath = $initialPath.'\\variations\\'.$_GET['ddlSTAct'];
				$variationPath = 'wp-content\\themes\\skins\\' . $_GET['ddlSTAct'].'\\'.$_GET['ddlVAct'];
				$variationPath = $variationPath.'\\'.$_GET['ddlVAct'].'.css';
				$variationPath = str_replace('\\', '\\\\', $variationPath);				
				alterDb('update', "INSERT INTO wp_se_skin_activation (`fulldomain`, `domain`, `sub_theme`, `sub_theme_variation`, `sub_theme_variation_path`, `site_level_file`, `site_level_file_path`, `active`) VALUES ('{$_GET['domainName']}','{$_GET['ddlUrl']}','{$_GET['ddlSTAct']}','{$_GET['ddlVAct']}','{$variationPath}','{$_GET['ddlVAct']}','{$sitefilepath}',1);");			
				echo 'document.getElementById("info_message").innerHTML="activated";';
			}
			break;
		case "createUrl":
			validateActivate($_GET['ddlUrl'], $_GET['ddlSTAct'], $_GET['ddlVAct']);
			//============== constrct activation url =====================================
			$getTemplate = readRecords("SELECT `sub_theme_template` FROM `wp_se_sub_theme` WHERE `sub_theme` = '{$_GET['ddlSTAct']}';");
			$template = $getTemplate[0]->sub_theme_template;			
			$stylesheet = 'skins/'.$_GET['ddlSTAct'];		
			if($stylesheet==getOptionVal($_GET['domainName'], 'stylesheet', $domainId)){
				echo 'document.getElementById("hiddenUrl").innerHTML = "<input type=\'hidden\' name=\'subThemeActivate\' id=\'subThemeActivate\' value=\'\'>";';
			}else{
				echo 'document.getElementById("hiddenUrl").innerHTML = "<input type=\'hidden\' name=\'subThemeActivate\' id=\'subThemeActivate\' value=\''.wp_nonce_url("http://{$_GET['domainName']}/wp-admin/themes.php?action=activate&amp;template=".urlencode($template)."&amp;stylesheet=".urlencode($stylesheet), 'switch-theme_' . $template).'\'>";';
			}
			//=======================================================================				
			echo 'document.getElementById("btActivate").style.display = "block";';			
			echo 'document.getElementById("info_message").innerHTML = "";';
			break;		
	}	
	die;
}

function editFiles(){
global $finalPath,$initialPath;
	switch ($_GET['actionChoise']) {
		case "filldomain":			
			$dropdown = fillListDomain('ddlUrlEdit', $_GET['txtUrlEdit'], true);			
			echo 'document.getElementById("listUrlEdit").innerHTML="'.$dropdown.'";';
			echo 'document.getElementById("error_message").innerHTML="'.trim($_GET['txtUrlEdit']).'";';
			break;
		case "clear":
			echo 'document.getElementById("error_message").innerHTML="";';
			echo 'document.getElementById("info_message_edit").innerHTML="";';
			break;
		case "fillvariationedit":			
			$dropdown = fillListVariation('ddlVEdit', $_GET['ddlSTEdit'], true, true);			
			echo 'document.getElementById("listVEdit").innerHTML="'.$dropdown.'";';			
			break;
		case "editfile":			
			switch ($_GET['csslevel']) {
				case "custom":
					//construct path to custom
					if($_GET['optFiles']=='cssfile'){						
						readFiles($finalPath.'\\custom.css');
					}else{						
						readFiles($finalPath.'\\custom_functions.php');						
					}
					break;
				case "subtheme":
					//construct path to subtheme
					$getPath = readRecords("SELECT `sub_theme_path` FROM `wp_se_sub_theme` WHERE `sub_theme` = '{$_GET['ddlSTEdit']}';",true);
					if($_GET['optFiles']=='cssfile'){						
						readFiles($initialPath.$getPath[0]->sub_theme_path.'\\style.css');
					}else{
						readFiles($initialPath.$getPath[0]->sub_theme_path.'\\functions.php');
					}
					break;
				case "variation":
					//construct path to variation
					$getPath = readRecords("SELECT `sub_theme_variation_path` FROM `wp_se_sub_theme_variation` WHERE `sub_theme` = '{$_GET['ddlSTEdit']}' AND `sub_theme_variation` = '{$_GET['ddlVEdit']}';",true);
					if($_GET['optFiles']=='cssfile'){
						readFiles($initialPath.$getPath[0]->sub_theme_variation_path);
					}else{
						//this is code is to be uncommented if there is a functional file  breadFiles($getPath[0]->sub_theme_path.'\\functions.php');
					}
					break;
				case "sitelevel":
					//construct path to sitelevel	
					$getPath = readRecords("SELECT `site_level_file_path` FROM `wp_se_skin_activation` WHERE `domain` = '{$_GET['ddlUrlEdit']}' AND `sub_theme` = '{$_GET['ddlSTEdit']}' AND `sub_theme_variation` = '{$_GET['ddlVEdit']}';",true);
					if($_GET['optFiles']=='cssfile'){
						readFiles($initialPath.$getPath[0]->site_level_file_path.'.css');
					}else{
						readFiles($initialPath.$getPath[0]->site_level_file_path.'_functions.php');
					}
					break;
			}
			echo 'document.getElementById("saved_msg").innerHTML="";';
			break;
		case "savefile":
			writeFiles($_GET['mypath'], $_GET['txtcontent']);
			echo 'document.getElementById("saved_msg").innerHTML="File Saved";';
			break;
	}	
	die;
}

function fillListDomain($cntID, $filter='', $ajaxCall=false){	
	if (!strpos(trim($filter), 'ype here to filter domain', 0)){		
		$txtUrl = trim($filter);
	}	
	$myList = readRecords("SELECT `domain`,`blog_id` FROM `wp_blogs` WHERE `domain` like '{$txtUrl}%' ;");		
	if(count($myList)<1){
		if($ajaxCall){
			return 'no items';
		}
		echo 'no items';		
		return;
	}
	$myHtml = "<select id='{$cntID}' name='{$cntID}' class='widefat'>";
	$myHtml .="<option value='select'>Select Domain</option>";
	foreach($myList as $item){		
		$domain = substr($item->domain, 0, strpos($item->domain, '.'));
		$myHtml .="<option value='{$domain}'>{$item->domain}</option>";
	}
	$myHtml .="</select>";
	if($ajaxCall){
		$myHtml = str_replace('\'', '\\\'', $myHtml);		
		return $myHtml;
	}
	echo $myHtml;
	return;
}

function fillListSubThemes($cntID,$ajaxCall=false){	
	$myList = extrtactActiveTheme();
	if(count($myList)<1){
		if($ajaxCall){
			return 'no items';
		}
		echo 'no items';		
		return;
	}
	$myHtml = "<select id='{$cntID}' name='{$cntID}' class='widefat widthz' >";
	$myHtml .="<option value='select'>Select skin</option>";
	foreach($myList as $item){
		$myHtml .="<option value='{$item['sub_theme']}'>{$item['sub_theme']}</option>";
	}
	$myHtml .="</select>";
	if($ajaxCall){
		$myHtml = str_replace('\'', '\\\'', $myHtml);
		return $myHtml;
	}
	echo $myHtml;
	return;
}

function fillListVariation($cntID, $filter='', $ajaxCall=false, $dropdown=false){
	$myList = readRecords("SELECT `sub_theme_variation` FROM `wp_se_sub_theme_variation` WHERE sub_theme = '{$filter}';");
	if(count($myList)<1){
		if($ajaxCall){
			return 'no items';
		}
		echo 'no items';
		return;
	}
	if($dropdown){
		$myHtml = "<select id='{$cntID}' name='{$cntID}' class='widefat sel'>";
		$myHtml .="<option value='select'>Select Variation</option>";
		foreach($myList as $item){
			$myHtml .="<option value='{$item->sub_theme_variation}'>{$item->sub_theme_variation}</option>";
		}
		$myHtml .="</select>";
	}else{
		$myHtml = "<ul id='{$cntID}' name='{$cntID}' class='widefat sel'>";		
		foreach($myList as $item){
			$myHtml .="<li >{$item->sub_theme_variation}</li>";
		}
		$myHtml .="</ul>";
	}
	if($ajaxCall){
		$myHtml = str_replace('\'', '\\\'', $myHtml);
		return $myHtml;
	}
	echo $myHtml;
	return;
}

//============== common functions =====================================
/* initialize the plugin settings*/
function skineditor_init() {
	try_create_table();	
}

/* Load css files*/
function skineditor_load_stylesheets() {
	$style_file = plugins_url('skin-editor/skin-editor.css');
	echo '<link rel="stylesheet" type="text/css" href="' . $style_file . '" />' . "\r\n";
}

/* Configuration Screen*/
function skineditor_tools_menu() {
	global $mainPlugFile;
	add_submenu_page( 'ms-admin.php', 'Skin editor', 'Skin editor', 'manage_options', 'Skin-editor/Skin-editor.php', 'skin_forms');
	$plugin = plugin_basename($mainPlugFile); 
	add_filter( 'plugin_action_links_' . $plugin, 'skineditor_plugin_actions' );
}

/* Add Settings link to the plugins page*/
function skineditor_plugin_actions($links) {
	global $current_user;
	get_currentuserinfo();
	if(is_super_admin($current_user->ID)){
		$settings_link = '<a href="ms-admin.php?page=Skin-editor/Skin-editor.php">Settings</a>';
		$links = array_merge( array($settings_link), $links);
	}
    return $links;
}

function try_create_table() {
	if ( is_site_admin() ) {
		$query = "(
			`id` bigint(20) NOT NULL auto_increment,
			`fulldomain` varchar(50) NOT NULL,
			`domain` varchar(50) NOT NULL,
			`sub_theme` varchar(50) NOT NULL,
			`sub_theme_variation` varchar(50) ,
			`sub_theme_variation_path` varchar(255) ,
			`site_level_file` varchar(50),
			`site_level_file_path` varchar(255),
			`active` tinyint(1) default '0',
			PRIMARY KEY  (`id`)
			)";			
		alterDb('create', $query, 'se_skin_activation');

		$query = "(
			`activated` tinyint(1) NOT NULL default '0',
			`id` bigint(20) NOT NULL auto_increment,
			`sub_theme` varchar(50) NOT NULL,
			`sub_theme_path` varchar(255) NOT NULL,
			`sub_theme_template` varchar(50) NOT NULL,
			PRIMARY KEY  (`id`)
			)";		
		alterDb('create', $query, 'se_sub_theme');

		$query = "(
			`id` bigint(20) NOT NULL auto_increment,
			`sub_theme` varchar(255) NOT NULL,
			`sub_theme_variation` varchar(50) NOT NULL,
			`sub_theme_variation_path` varchar(255) NOT NULL,
			PRIMARY KEY  (`id`)
			)";	
		alterDb('create', $query, 'se_sub_theme_variation');		
	}
}

function loopActivateTheme(){	
	//============ activate sub theme =======================
	$activated = readRecords("SELECT meta_value FROM `wp_sitemeta` WHERE meta_key ='_site_transient_theme_roots'");
	$activated = $activated[0]->meta_value;
	$myList = readRecords("SELECT `sub_theme` FROM `wp_se_sub_theme` WHERE activated = 0;");	
	foreach($myList as $item){
		$theme = 'skins/'.$item->sub_theme;		
		if(strpos($activated, '"'.$theme.'"', 0)){		
			activateTheme($item->sub_theme);
			alterDb('update',"UPDATE `wp_se_sub_theme` SET activated = 1 WHERE sub_theme ='{$item->sub_theme}';");
		}		
	}
	//============ end of activate sub theme =======================
	die;
}

function activateTheme($theme){
	$theme = 'skins/'.$theme;
	
	$activated = readRecords("SELECT meta_value FROM `wp_sitemeta` WHERE meta_key ='_site_transient_theme_roots'");
	$activated = $activated[0]->meta_value;
	if(!strpos($activated, '"'.$theme.'"', 0)){		
		return;
	}
	$activated = readRecords("SELECT meta_value FROM `wp_sitemeta` WHERE meta_key ='allowedthemes'");
	$activated = $activated[0]->meta_value;
	if(strpos($activated, '"'.$theme.'"', 0)){
		return;
	}
	$namelen = strlen($theme);
	$valueToBeAdded = 's:'.$namelen.':"'.$theme.'";b:1;}';
	$activatedCount = '';
	$colon = false;
	$i = 2;
	while(!$colon){	
		$activatedCount .= $activated[$i];
		$i += 1;		
		if($activated[$i]==':'){
			$colon = true;
		}
	}	
	$newActivatedCount = $activatedCount+1;
	$activated = str_replace('a:'.$activatedCount.':','a:'.$newActivatedCount.':',$activated);
	$activated = str_replace('}',$valueToBeAdded,$activated);
	alterDb('update',"UPDATE `wp_sitemeta` SET meta_value = '{$activated}' WHERE meta_key ='allowedthemes';");	
}

function extrtactActiveTheme(){
	$i=0;
	$j=0;
	$activated = readRecords("SELECT meta_value FROM `wp_sitemeta` WHERE meta_key ='allowedthemes'");
	$activated = $activated[0]->meta_value;	
	while(strpos($activated, 'skins/', $i)){		
		$colon = false;
		$i=strpos($activated, 'skins/', $i);
		$i+=6;
		while(!$colon){	
			$theme[$j]['sub_theme'] .= $activated[$i];
			$i += 1;		
			if($activated[$i]=='"'){
				$colon = true;
			}
		}
		$j += 1;
	}
	return $theme;
}

function wpContentUrl($filePath,$frontSlash=true){
	$endIndex = strpos($filePath, 'wp-content', 0);
	$halfPath =  substr($filePath, $endIndex, strlen($filePath));
	if($frontSlash){
		$halfPath = str_replace('/','\\',$halfPath);
	}else{
		$halfPath = str_replace('\\','/',$halfPath);
	}
	return $halfPath;
}

function getOptionVal($domain, $myOption, &$domainId){
	//get blog id
	$searchTheme = readRecords("SELECT `blog_id` FROM `wp_blogs` WHERE (`domain` = '{$domain}');");
	$domainId = $searchTheme[0]->blog_id;
	$optionTable = 'wp_'.$domainId.'_options';
	// get option
	$myOptions = readRecords("SELECT `option_value` FROM `{$optionTable}` WHERE (`option_name` = '{$myOption}');");
	return $myOptions[0]->option_value;
}

function validateActivate($domain, $subrTheme, $variation){
	if ($domain == 'select'){		
		pathetic_fail('please select domain/url');
		return;
	}
	if ($subrTheme == 'select'){		
		pathetic_fail('please select skin');
		return;
	}
	if ($variation == 'select'){		
		pathetic_fail('please select variation');
		return;
	}
}

function alterFiles($fileDir=null, $file=null, $fileData=null){
	if($fileDir && !is_dir($fileDir)){		
		$dirMade = mkdir($fileDir, 0777, true);		
		if(!$dirMade){
			pathetic_fail($fileDir.' creation failed');	
		}
	}
	if($file && !file_exists($file)){
		$fh = false;
		$fh = fopen($file, "w+");
		if($fh==false){			
			pathetic_fail($file.' creation failed');
		}else{
			fwrite($fh, $fileData);
			fclose($fh);
		}
	}
}

function readFiles($path){
	$path = trim($path);
	$content = file_get_contents($path);
	if(!$content){
		echo "document.getElementById('txtcontent').value = 'no file';";
		return;
	}
	$content = str_replace("\r", '', $content);
	$content = str_replace("\n", '\\n\\ ', $content);
	$content = str_replace("'", "\'", $content);	
	echo "document.getElementById('txtcontent').value = '{$content}';";	
	// $path = wpContentUrl($path,false);
	$path = str_replace('\\', '\\\\', $path);
	// $path = '\\\\'.$path;
	echo "document.getElementById('info_message_edit').innerHTML = '{$path}';";	
}

function writeFiles($path, $content){
	$content = str_replace("\'", "'", $content);
	$content = str_replace("\\\"", "\"", $content);
	$content = str_replace("\n ", "\n", $content);
	$path = trim($path);
	$fh = false;
	$fh = fopen($path, "w");
	if($fh==false){			
		pathetic_fail($path.' write failed', false);
	}else{
		fwrite($fh, $content);
		fclose($fh);
	}	
	return;
}

function alterDb($dbAction, $query=null, $tableName=null){
	global $wpdb;
	
	switch ($dbAction) {
		case 'create':
			$wpdb->dmtable = $wpdb->base_prefix . $tableName;
			if( $wpdb->get_var("SHOW TABLES LIKE '{$wpdb->dmtable}'") != $wpdb->dmtable ) {
				$result=$wpdb->query("CREATE TABLE IF NOT EXISTS `{$wpdb->dmtable}`".$query.";");
			}
			break;
		case 'update':
			$myUpdate = $wpdb->query($query);			
			if($myUpdate === false){
				pathetic_fail($query.' failed');
			}
			break;
		case 'delete':
			$myUpdate = $wpdb->query($query);			
			if($myUpdate === false){
				pathetic_fail($query.' failed');
			}
			break;
	}
}

function readRecords($query, $validate=false){
	global $wpdb;	
	$myRecords = $wpdb->get_results($query);
	if (count($myRecords)<1 && $validate){	
		pathetic_fail("no record found",false);
	}
	return $myRecords;
}

function strlef($s1, $s2) {
	if (strpos($s1, $s2)>0){
		$values = substr($s1, 0, strpos($s1, $s2));
	}else{
		$values = $s1;
	}
	return  $values;
}

function getImagePath($filePath){
	$filePath = str_replace('\\','/',$filePath);
	$startIndex = strpos($filePath, 'wp-content', 0);
	$endIndex = strrpos($filePath, '/', 0);
	$midPath = substr($filePath, $startIndex, $endIndex-$startIndex);
	return get_bloginfo('url').'/'.$midPath.'/images';
}

function pathetic_fail($msg, $forAdding = true){
	$msg = str_replace('\\', '\\\\', $msg);
	if ($forAdding){
		echo 'document.getElementById("info_message").innerHTML="<div style=\'color: #111111\' class=\'error\'>'.$msg.'</div>"';	
		die;
	}
	echo 'document.getElementById("error_message").innerHTML="<div style=\'color: #111111\' class=\'error\'>'.$msg.'</div>"';	
	die;
}
//====================== get current URL ====================================
function siteSelfURL($WithQuery,$secureSocket) {
	$s ='';
	$s = empty($_SERVER["HTTPS"]) ? "" : ($_SERVER["HTTPS"] == "on") ? "s" : "";
	$protocol = strlef(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
	$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
	if($WithQuery){
		if($secureSocket){
			return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
		}else{
			return str_replace('https','http',$protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI']);
		}
	}else{
		if($secureSocket){
			return strlef($protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'],'?');
		}else{
			return strlef(str_replace('https','http',$protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI']),'?');
		}
	}
}

//====================== get the skin name from the url ======================== 
function extractDomainName($url,&$variationPath,&$cssPath){
	Global $wpdb;
	global $current_site;
	global $current_blog;
	$blog__id = 0;
	
	//==== check if url is mapped ===========	
	$myDomain = $current_blog->domain;
	$blog__id = $wpdb->get_var("SELECT `blog_id` FROM  wp_domain_mapping WHERE `domain` = '".$myDomain."'",0,0);	
	if ($blog__id > 0){
		//=== get blog url from database  if it is mapped ===
		$myDomain = $wpdb->get_var("SELECT `domain` FROM  wp_blogs WHERE `blog_id` = '".$blog__id."'",0,0);				
		getCssPaths($myDomain,$variationPath,$cssPath);
	}else{		
		getCssPaths($myDomain,$variationPath,$cssPath);	
	}	
	return '';
}

function getCssPaths($domain,&$variationPath,&$cssPath){
global $initialPath;
	$pathRecord = readRecords("SELECT `sub_theme_variation_path`, `site_level_file_path` FROM `wp_se_skin_activation` WHERE `fulldomain` = '{$domain}' AND `active` = 1;");
	if (count($pathRecord)<1){		
		$variationPath = "no record found";
		$cssPath = "no record found";
	}else{
		$variationPath = $initialPath.$pathRecord[0]->sub_theme_variation_path;
		$cssPath = $initialPath.$pathRecord[0]->site_level_file_path;
	}
}
//====================== constract the css html ===============================
function load_cssFile(){
	global $vPath, $siteCssPath;
	echo '<link rel="stylesheet" type="text/css" href=" ' . $vPath . '" media="screen, projection" />'. "\r\n";
	echo '<link rel="stylesheet" type="text/css" href=" ' . $siteCssPath . '" media="screen, projection" />'. "\r\n";
}

//====================== load css files ======================================
function loadCss($cssPaths){
	global $vPath, $siteCssPath, $site_url;	
	//=== load css ===	
	$siteCssPath = $site_url.'/'.wpContentUrl($cssPaths['siteCssPath'].'.css', false);		
	$vPath = $site_url.'/'.wpContentUrl($cssPaths['variationPath'], false);
	
	if (!empty($vPath))  {
		add_action('wp_head', 'load_cssFile');
	}else{
		echo '<div> skin css not available </div>';
	}		
}
	
//====================== on creation of variation create new skin folder======================================= 
function create_skin_folder ($siteName,$subtheme,$variation){	
	global $initialPath;
	$initialPath .= 'wp-content\\themes\\client-sites\\'.$siteName.'\\';
	//$initialPath .= 'wp-content\\themes\\client-sites\\'.$siteName.'\\'.$subtheme.'\\'.$variation.'\\';
	//=== get new site name =====  
	//$siteName = $_POST['blog']['domain'];	
	$newFolderPath = $initialPath.'images';
	// $newCssFileNamePath = $initialPath.'cl_'.$variation.'.css';
	// $newTplFileNamePath = $initialPath.'cl_'.$variation.'_functions.php';
	$newCssFileNamePath = $initialPath.'cl_'.$siteName.'.css';
	$newTplFileNamePath = $initialPath.'cl_'.$siteName.'_functions.php';
	// === create folder and files if they dont exist ===
	if(!(is_readable($newTplFileNamePath))){
		//$dirMade = mkdir($newFolderPath, 0777, true);
		alterFiles($newFolderPath);
		
			$stringData = "/*\n";
			$stringData .= "File:\t\t custom.css\n";
			$stringData .= "Description:\t\t Custom styles for Thesis\n";
			$stringData .= "\n";
			$stringData .= "BASIC USAGE:\n";
			$stringData .= "\n";
			$stringData .= "If you have enabled the custom stylesheet in the Thesis options panel, the <body> tag \n";
			$stringData .= "will be appended with the 'custom' class, like so: <body class='custom'>. You can use \n";
			$stringData .= "the 'custom' class to override *any* CSS declarations contained in the style.css file.\n";
			$stringData .= "\n";
			$stringData .= "For example, if you wish to change the default link color to green, you would add the \n";
			$stringData .= "following declarations to this file:\n";
			$stringData .= "\n";
			$stringData .= "\t\t .custom a, .custom a:visited { color: #090; }	<--- This makes links green\n";
			$stringData .= "\t\t .custom a:hover { color: #00f; }	<--- This makes links blue when you mouse over them\n";
			$stringData .= "\n";
			$stringData .= "WHY THIS WORKS:\n";
			$stringData .= "\n";
			$stringData .= "By using the 'custom' class, you are creating more specific CSS declarations for HTML\n";
			$stringData .= "elements. CSS styling is applied through rules of specificity, and because declarations\n";
			$stringData .= "prepended with .custom are more specific, they get applied when the page is rendered!\n";
			$stringData .= "\n";
			$stringData .= "More information about styling your Thesis installation using this file can be found\n";
			$stringData .= "in the User's Guide:\n";
			$stringData .= "\t\t http://diythemes.com/thesis/rtfm/customizing-thesis-with-customcss/\n";
			$stringData .= "\n";
			$stringData .= "css: level4\n";
			$stringData .= "*/\n";			
		alterFiles(null, $newCssFileNamePath, $stringData);
		
			$stringData  = "<?php\n";
			$stringData .= "//=========== the following lines are required so that the sub theme can work  =====================================\n";
			$stringData .= "remove_action('thesis_hook_header', 'thesis_default_header');\n";
			$stringData .= "remove_action('thesis_hook_before_header', 'thesis_nav_menu');\n";
			$stringData .= "remove_action('thesis_hook_custom_template', 'thesis_custom_template_sample');\n";
			$stringData .= "remove_action('thesis_hook_404_title', 'thesis_404_title');\n";
			$stringData .= "remove_action('thesis_hook_404_content', 'thesis_404_content');\n";
			$stringData .= "remove_action('thesis_hook_footer', 'thesis_attribution');\n";
			$stringData .= "//=========== end of lines ================================================================================\n";
			$stringData .= '$pathToImageFolder = getImagePath(__FILE__);'."\n";
			$stringData .= "?>";
		alterFiles(null, $newTplFileNamePath, $stringData);
		
	}
	return 'wp-content\\themes\\client-sites\\'.$siteName.'\\cl_'.$siteName;
	//return 'wp-content\\themes\\client-sites\\'.$siteName.'\\'.$subtheme.'\\'.$variation.'\\cl_'.$variation;
}
//add_action('wpmu_new_blog', 'create_skin_folder');

function delete_skin_folder ($blog_id){
	Global $wpdb, $finalPath;
	//=== get to be deleted site name ===== needs custom table to work
	$siteName = $wpdb->get_var("SELECT `domain` FROM  wp_blogs WHERE `blog_id` = '".$blog_id."'",0,0);				
	$siteName = strlef($myDomain, '.dwdining.');		
	$deleteFolderPath = $finalPath.'\\skins\\'.$siteName;	
}
//add_action('delete_blog', 'delete_skin_folder');

function voimitJavaScripts(){
	global $initialPath;
	//print out the sack ajax library	
	wp_enqueue_script( 'skinscripts', '/wp-content/plugins/skin-editor/skin_js.js', array('jquery-ui-tabs'), '1.0', false );
}
add_action('init', 'voimitJavaScripts');
?>