<?php
/**
 * @link         http://www.openzc.cn/
 * @author       hexipeng | e-mail:2017412656@qq.com
 * @copyright    Copyright (c) 2020, Openzc, Inc.
 * @license      http://www.openzc.cn/license.txt
 */
    class upgrade {
        private $tables=array(
			TABLE_PRODUCTS => "products_id",
			TABLE_PRODUCTS_DESCRIPTION => "products_id",
			TABLE_PRODUCTS_ATTRIBUTES => "products_id",
			TABLE_PRODUCTS_OPTIONS => "options_id",
			TABLE_PRODUCTS_OPTIONS_VALUES => "options_values_id",
			TABLE_CONFIGURATION => "configuration_id",
			TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS => "products_options_values_to_products_options_id",
			TABLE_CATEGORIES => "categories_id",
			TABLE_CATEGORIES_DESCRIPTION => "categories_id",
			TABLE_PRODUCTS_TO_CATEGORIES => "categories_id",
			TABLE_CUSTOMERS => "customers_id",
			TABLE_SPECIALS => "specials_id",
			TABLE_SALEMAKER_SALES => "sale_id",
			TABLE_FEATURED => "featured_id",
			TABLE_MANUFACTURERS => "manufacturers_id",
			TABLE_TEMPLATE_SELECT => "template_id",
			TABLE_EZPAGES => "pages_id",
			TABLE_REVIEWS => "reviews_id",
			TABLE_REVIEWS_DESCRIPTION => "reviews_id",
			TABLE_ORDERS_PRODUCTS => "orders_id",
			DB_PREFIX."blog_categories" => "categories_id",
			DB_PREFIX."blog_categories_description" => "categories_id",
			DB_PREFIX."blog_archives_to_categories" => "categories_id",
			DB_PREFIX."blog_archives" => "archives_id",
			DB_PREFIX."blog_archives_description" => "archives_id"
		);
		
			
		function Run(){
			$this->updateFiles();
			$this->createBlogTable();
			$this->editTable($this->tables);
			$this->addTable();
			$this->createTrigger($this->tables);
			$this->fileSpeed();
			$this->showMsg('Success');
			exit;
		}
		//修改表信息
		function editTable($tables){
			global $db;
			foreach($tables as $k => $v){
				$sql="";
				switch($k){
					case TABLE_PRODUCTS:
						$sql="alter table ".$k." add (products_image_detail varchar(800) null,products_video varchar(800) null)";
					break;
					case TABLE_PRODUCTS_DESCRIPTION:
					    $sql="alter table ".$k." modify column products_description mediumtext null,modify column products_name varchar(255) not null";
					break;
					case TABLE_TEMPLATE_SELECT:
						$sql="alter table ".$k." add template_device int(5) not null default 0 after template_language"; 
					break;
					case TABLE_CONFIGURATION:
						$sql = "insert into ".TABLE_CONFIGURATION." (configuration_title,configuration_key,configuration_value,configuration_description,configuration_group_id,sort_order) values('Default newsletters email template id','DEFAULT_NEWSLETTERS_ID','1','Default newsletters email template id','12','100') ON DUPLICATE KEY UPDATE configuration_value = '1',last_modified = '".date('Y-m-d H:i:s')."'";
					break;
				}
				if($sql){
					$db->query($sql);
					$this->showMsg('OpenzcTPL ...............表`'.$k."`的字段信息已修改完成 ");
				}
			}
		}
		//新建表
		function addTable(){
			global $db;
			$sql="select table_name from information_schema.tables where table_schema='".DB_DATABASE."'";
			$tables=$db->query($sql);
			$tables=$this->tableList($tables,"table_name");
			
			if(!array_key_exists(DB_PREFIX."products_options_values_image",$tables)){
				$sql="CREATE TABLE `".DB_PREFIX."products_options_values_image` (
					`products_options_values_id` int(11) NOT NULL,
					`products_options_values_color` varchar(100) DEFAULT NULL,
					`products_options_values_image` varchar(255) DEFAULT NULL,
					PRIMARY KEY (`products_options_values_id`)
					)";
				$db->query($sql);
			}
		}
		//创建Openzc触发器
		function createTrigger($tables){
			global $db;
			$sql = "drop table if exists ".TABLE_OPENZC_TRIGGER;
			$db->query($sql);
			$sql = "CREATE TABLE ".TABLE_OPENZC_TRIGGER." (
					id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
					table_name VARCHAR(100) NOT NULL,
					action VARCHAR(100) NOT NULL,
					field VARCHAR(100) NOT NULL,
					value VARCHAR(100) NOT NULL,
					status VARCHAR(5) default 1 NOT NULL,
					last_modified INT(11) NOT NULL
				)";
			$db->query($sql);
			
			$action=array("update","delete","insert");
			foreach($tables as $k => $v){
				foreach($action as $a => $b){
					$trigger_name="trigger_".$b."_".$k;
					$sql = "DROP TRIGGER IF EXISTS ".$trigger_name;
					$db->query($sql);
					$sql = "create trigger ".$trigger_name."
							before ".$b." on ".$k." 
							for each row";
					if($k==TABLE_PRODUCTS_DESCRIPTION && $b=="update"){
						$sql .= " if new.products_viewed = old.products_viewed then
							insert into ".TABLE_OPENZC_TRIGGER." (table_name,action,field,value,last_modified) VALUES ('".$k."','".$b."','".$v."',new.".$v.",unix_timestamp(now()));
							end if";
					}else if($b=="delete"){
						$sql .= " insert into ".TABLE_OPENZC_TRIGGER." (table_name,action,field,value,last_modified) VALUES ('".$k."','".$b."','".$v."',old.".$v.",unix_timestamp(now()))";
					}
					else{
						$sql .= " insert into ".TABLE_OPENZC_TRIGGER." (table_name,action,field,value,last_modified) VALUES ('".$k."','".$b."','".$v."',new.".$v.",unix_timestamp(now()))";
					}
					$db->query($sql);
				}
			}
		}
		
		function read_all($dir,$result=array()){ 
		
			if(!is_dir($dir))return false; 
			$handle = opendir($dir); 
			if($handle){ 
				while(($fl = readdir($handle)) !== false){ 
					//$temp = iconv('GBK','utf-8',$dir.DIRECTORY_SEPARATOR.$fl);//转换成utf-8格式 
					$temp=str_replace("\\","/",$dir.$fl);
					$temp=str_replace("//","/",$temp);

					if(is_dir($temp) && $fl!='.' && $fl != '..'){
						$file=array("type"=>"dir","file"=>$temp."/");
						$result[]=$file;
						$result=$this->read_all($temp."/",$result); 
					}else{ 
						if($fl!='.' && $fl != '..'){
							$file=array("type"=>"file","file"=>$temp);
							$result[]=$file; 
						} 
					} 
				} 
			}
			return $result;
		}
		//升级创建博客数据表
		function createBlogTable(){
			global $db;
			$table=array("blog_archives","blog_archives_description","blog_reviews","blog_reviews_description","blog_categories","blog_archives_to_categories","blog_categories_description","blog_seo","newsletters_email");
			$sql="select table_name from information_schema.tables where table_schema='".DB_DATABASE."'";
			$tables=$db->query($sql);
			$tables=$this->tableList($tables,"table_name");
			
			//**判断版本>1.5.5添加后台blog导航
			if(EXPECTED_DATABASE_VERSION_MINOR>=5){
				$sql="select * from ".TABLE_ADMIN_MENUS." where menu_key='blog'";
				$check_blog=$db->query($sql);
				if($check_blog->num_rows==0){
					$sql="INSERT INTO ".TABLE_ADMIN_MENUS." (menu_key,language_key,sort_order) VALUES('blog','BOX_HEADING_BLOG','2')";
					$db->query($sql);
				}
			
				$sql="select * from ".TABLE_ADMIN_PAGES." where menu_key='blog'";
				$check_blog=$db->query($sql);
			
				if($check_blog->num_rows!=3){
					$values=" ('blogArchives','BOX_BLOG_CATEGORIES_ARCHIVES','FILENAME_BLOG','blog','Y','1'),('blogReviews','BOX_BLOG_REVIEWS','FILENAME_BLOG_REVIEWS','blog','Y','2'),('blogSeo','BOX_BLOG_SEO','FILENAME_BLOG_SEO','blog','Y','3')";
					$sql="INSERT INTO ".TABLE_ADMIN_PAGES." (page_key,language_key,main_page,menu_key,display_on_menu,sort_order) VALUES".$values;
				
					$db->query($sql);
				}
			}
			
			foreach($table as $k => $v){
				if(!array_key_exists(DB_PREFIX.$v,$tables)){
				switch($v){
					case "blog_archives":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
								`archives_id` int(11) NOT NULL AUTO_INCREMENT,
								`master_categories_id` int(11) NOT NULL,
								`archives_image` char(100) DEFAULT NULL,
								`archives_image_detail` text DEFAULT NULL,
								`archives_flag` set('p','v','f','h','r') DEFAULT NULL,
								`archives_click` mediumint(8) NOT NULL,
								`archives_type` set('video','image','text') NOT NULL,
								`related_products_id` varchar(20) DEFAULT NULL,
								`related_categories_id` varchar(20) DEFAULT NULL,
								`archives_date_added` datetime NOT NULL,
								`archives_status` tinyint(1) NOT NULL DEFAULT '1',
								`archives_sort_order` int(11) NOT NULL,
								`archives_last_modified` datetime DEFAULT NULL,
								PRIMARY KEY (`archives_id`))";
					break;
					case "blog_archives_description":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
								`archives_id` int(11) NOT NULL,
								`language_id` int(2) NOT NULL,
								`archives_name` char(200) NOT NULL,
								`archives_shorttitle` char(200) DEFAULT NULL,
								`archives_keywords` char(200) DEFAULT NULL,
								`archives_description` text,
								`archives_body` text,
								`archives_tag` varchar(255) DEFAULT NULL,
								PRIMARY KEY (`archives_id`,`language_id`)
								)";
					break;
					case "blog_reviews":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
								`reviews_id` int(11) NOT NULL AUTO_INCREMENT,
								`archives_id` int(11) NOT NULL,
								`customers_name` varchar(64) NOT NULL,
								`customers_id` int(11) NOT NULL,
								`date_added` datetime NOT NULL,
								`reviews_status` tinyint(1) NOT NULL DEFAULT '1',
								PRIMARY KEY (`reviews_id`)
								)";
					break;
					case "blog_reviews_description":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
								`reviews_id` int(11) NOT NULL,
								`language_id` int(11) NOT NULL,
								`reviews_text` text NOT NULL,
								PRIMARY KEY (`reviews_id`,`language_id`)
								)";
					break;
					case "blog_categories":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
							  `categories_id` int(11) NOT NULL AUTO_INCREMENT,
							  `categories_image` char(100) DEFAULT NULL,
							  `parent_id` int(11) NOT NULL,
							  `topid` int(11) NOT NULL,
							  `sort_order` int(3) DEFAULT NULL,
							  `date_added` datetime DEFAULT NULL,
							  `categories_status` tinyint(1) NOT NULL DEFAULT '1',
							  `last_modified` datetime DEFAULT NULL,
							  PRIMARY KEY (`categories_id`)
							  )";
					break;
					case "blog_archives_to_categories":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
								`categories_id` int(11) NOT NULL,
								`archives_id` int(11) NOT NULL,
								PRIMARY KEY (`categories_id`,`archives_id`)
								)";
					break;
					case "blog_categories_description":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
								`categories_id` int(11) NOT NULL,
								`language_id` tinyint(2) NOT NULL,
								`categories_name` varchar(32) NOT NULL,
								`categories_keywords` char(80) DEFAULT NULL,
								`categories_description` text,
								`categories_seotitle` varchar(80) DEFAULT NULL,
								PRIMARY KEY (`categories_id`,`language_id`)
								)";
					break;
					case "blog_seo":
						$sql = "CREATE TABLE ".DB_PREFIX.$v." (
								`language_id` int(2) NOT NULL,
								`seo_title` varchar(80) NOT NULL,
								`seo_keywords` varchar(100) DEFAULT NULL,
								`seo_description` varchar(255) DEFAULT NULL,
								PRIMARY KEY (`language_id`)
								)";
					break;
					case "newsletters_email":
						$sql = "CREATE TABLE `newsletters_email` (
							  `id` int(11) NOT NULL AUTO_INCREMENT,
							  `newsletters_email` varchar(255) NOT NULL,
							  `date_added` datetime DEFAULT '0001-01-01 00:00:00',
							  `last_modified` datetime DEFAULT '0001-01-01 00:00:00',
							  `last_modified_ip` varchar(200) DEFAULT NULL,
							  `newsletter_status` tinyint(1) NOT NULL DEFAULT '1',
							  PRIMARY KEY (`id`),
							  UNIQUE KEY `newsletters_email` (`newsletters_email`) USING BTREE
							) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;";
					break;
				}
				$db->query($sql);
				}
			}
			$this->showMsg("OpenzcTPL ...............博客数据结构已准备完成 ");
		}
		
		//升级必要文件
		function updateFiles(){
			$adminDir=$this->getAdmin();
			$fileDir=INSTALL_DIR."files/";
			$updateFiles=$this->read_all($fileDir);

			foreach($updateFiles as $k => $v){
				if(strstr($v['file'],"/admin/")){
					foreach($adminDir as $a => $b){
						$target=str_replace($fileDir."admin/","../".$b."/",$v['file']);
						switch($v['type']){
							case "dir":
								if(!is_dir($target)){mkdir($target);}
							break;
							case "file":
								if(is_file($target)){
									unlink($target);
								}
								copy($v['file'],$target);
							break;
						}
					}
				}else{
					$target=str_replace($fileDir,"../",$v['file']);
					
					switch($v['type']){
						case "dir":
							if(!is_dir($target)){mkdir($target);}
						break;
						case "file":
							if(is_file($target)){
								unlink($target);
							}
							copy($v['file'],$target);
						break;
					}
				}
			}
			//更新首页入口文件
			$indexContent=file_get_contents("../index.php");
			$mustString=['www.zen-cart.com','application_top.php','application_bottom.php','html_header.php','main_template_vars.php','tpl_main_page.php'];
			$error=false;
			if(!strstr($indexContent,"includes/openzctpl/openzc.php")){
				foreach($mustString as $k => $v){
					if(!strstr($indexContent,$v)){
						$error=true;
					}
				}
				if($error==false){
					$zcIndex='../includes/openzctpl/config/zcindex.php';
					if(is_file($zcIndex)){unlink($zcIndex);}
					copy("../index.php",$zcIndex);
				}
			}
			$this->showMsg('OpenzcTPL ...............升级文件已更新完毕！');
		}
		
		//修改文件提速
		function fileSpeed(){
			$file=array("log"=>"../includes/extra_configures/enable_error_logging.php","index_head"=>"../includes/modules/pages/index/header_php.php");
			foreach($file as $k => $v){
				if(is_file($v)){
					$content=file_get_contents($v);
					switch($k){
						case "log":
							chmod($v, 0666);
							$content=str_replace("@ini_set('log_errors', 1);","@ini_set('log_errors', 0);",$content);
						break;
						case "index_head":
							chmod($v, 0666);
							if(!strstr($content,"openzc_template_engine")){
								$content=str_replace("// set the product","if(!isset(\$openzc_template_engine) || \$openzc_template_engine!=true){\r\n// set the product",$content);
								$content=str_replace("// This should be last","}\r\n// This should be last",$content);
							}
						break;
					}
					$myfile = fopen($v, "w") or die("Unable to open file!");
					fwrite($myfile, $content);
					fclose($myfile);
				}
			}
		}
		function getAdmin(){
			$path=scandir("../");
			$filter=array("images","cache","data","docs","download","editors","email","extras","images","includes","logs","media","pub","zc_install");
			foreach($path as $k => $v){
				if($v != "." && $v !=".."){
					if(is_dir("../".$v)){
						foreach($filter as $a => $b){
							if($v==$b) unset($path[$k]);
						}
					}else{
						unset($path[$k]);
					}
				}else{
					unset($path[$k]);
				}
			}
			
			foreach($path as $k => $v){
				if(file_exists("../".$v."/banner_manager.php") && !file_exists("../".$v."/openzc.version.php")){
					$rs[]=$v;
				}
			}
			return $rs;
		}
		//*重置一些不必要的设置*//
		function initResetConfig(){
			global $db;
			$configuration=array("ACCOUNT_COMPANY"=>"false","ACCOUNT_SUBURB"=>"false","ACCOUNT_STATE"=>"false","DISPLAY_PRIVACY_CONDITIONS"=>"false","SHOW_COUNTS"=>"false","SHOW_COUNTS_ADMIN"=>"false");
			$sql="replace into ".TABLE_CONFIGURATION." (`configuration_key`,`configuration_value`) values";
			end($configuration);
			$end=key($configuration);
			foreach($configuration as $k => $v){
				if($k!=$end){
					$sql.=" ('".$k."','".$v."'),";
				}else{
					$sql.=" ('".$k."','".$v."')";
				}
			}
			$db->query($sql);

		}
		
		
		//*SQL数据查询转数组*//
        function tableList($data,$index=""){
			$rows=0;
			$list=array();
			if($index){
				while($row = $data->fetch_assoc()){
					if(!isset($row['table_name'])){
						$id=$row['TABLE_NAME'];
					}else{
						$id=$row[$index];
					}
					foreach($row as $k => $v){$list[$id][$k]=$v;}
				}
			}else{
				while($row = $data->fetch_assoc()) {
					foreach($row as $k => $v){$list[$rows][$k]=$v;}
					$rows++;
				}
			}
			return $list;
		}
		
		function showMsg($msg){
			ob_flush();
			flush(); 
			echo "<script>addMsg('".$msg."');</script>\r\n";
		}
	    
    }
?>