<?php
// 定义当前目录
define("APP_PATH",dirname(__FILE__));

if( true == @file_exists(APP_PATH.'/config.php') )exit();
$defaults = array(
	
	"DB_HOST" => "localhost",
	"DB_USER" => "root",
	"DB_PASSWORD" => "",
	"DB_DBNAME" => "speedcms",
	"DB_PREFIX" => "sc_",
		
		
	"SITENAME" => "SpeedCMS演示网站",
	"SITEINTRO" => "这是一个新的SpeedCMS网站",
	"COPYRIGHT" => "Copyright (C) SpeedCMS.",
	"SUBDOMAIN" => 0,
	"PATH_INFO" => 0,
		
		
	"USERNAME" => "admin",
	"NICKNAME" => "admin",
	"SEX" => 0,
	"EMAIL" => "",
	"PASSWORD" => ""
);
	
	
function ins_checkdblink($configs){
	global $dblink,$err;
	$dblink = mysql_connect($configs['DB_HOST'], $configs['DB_USER'], $configs['DB_PASSWORD']);
	if(false == $dblink){$err = '无法链接网站数据库，请检查网站数据库设置！';return false;}
	if(! mysql_select_db($configs['DB_DBNAME'], $dblink)){$err = '无法选择网站数据库，请确定网站数据库名称正确！'; return false;}
	ins_query("SET NAMES UTF8");
	return true;
}

function ins_query($sql,$prefix = ""){
	global $dblink,$err;
	$sqlarr = explode(";", $sql);
	foreach($sqlarr as $single){
		if( !empty($single) && strlen($single) > 5 ){
			$single = str_replace("\n",'',$single);
			$single = str_replace("#DBPREFIX#",$prefix,$single );
			if( !mysql_query($single, $dblink) ){$err = "数据库执行错误：".mysql_error();return false;}
		}
	}
}

function ins_registeruser($configs, $prefix = "")	{
	global $dblink,$err,$adminsql;
	$password = md5($configs["PASSWORD"]);

	$ctime = date('Y-m-d H:i:s');
	$adminsql = "INSERT INTO `{$prefix}user` ( `uname`, `upass`, `acl`, `firstname`, `lastname`, `email`, `street`, `city`, `country`, `state`, `zip`, `tel`, `enabled`, `addtime`) VALUES ( '{$configs[USERNAME]}', '{$password}', 'WEBMASTER', '{$configs[NICKNAME]}', '', '{$configs[EMAIL]}', '', '', '', '', '', '', 1, '{$ctime}');";
	return true;

}

function ins_writeconfig($configs){
	$configex = file_get_contents(APP_PATH."/config_sample.php");
	foreach( $configs as $skey => $value ){
		$skey = "#".$skey."#";
		$configex = str_replace($skey, $value, $configex);
	}
	file_put_contents (APP_PATH."/config.php" ,$configex);
}


$sql = "

DROP TABLE IF EXISTS #DBPREFIX#acl
;
DROP TABLE IF EXISTS #DBPREFIX#log
;
DROP TABLE IF EXISTS #DBPREFIX#module
;
DROP TABLE IF EXISTS #DBPREFIX#navigation
;
DROP TABLE IF EXISTS #DBPREFIX#news
;
DROP TABLE IF EXISTS #DBPREFIX#orderform
;
DROP TABLE IF EXISTS #DBPREFIX#settings
;
DROP TABLE IF EXISTS #DBPREFIX#user
;
DROP TABLE IF EXISTS #DBPREFIX#usergroup
;
CREATE TABLE IF NOT EXISTS `#DBPREFIX#acl` (
  `aclid` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `controller` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `action` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `acl_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`aclid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=24 ;

INSERT INTO `#DBPREFIX#acl` (`aclid`, `name`, `controller`, `action`, `acl_name`) VALUES
(1, 'Login', 'user', 'login', 'SPANONYMOUS'),
(2, 'Dashboard', 'main', 'index', 'WEBMASTER'),
(3, 'Navigation', 'navigation', 'index', 'WEBMASTER'),
(4, 'Add navigation', 'navigation', 'add', 'WEBMASTER'),
(5, 'Edit navigation', 'navigation', 'edit', 'WEBMASTER'),
(6, 'Submit navigation', 'navigation', 'post', 'WEBMASTER'),
(7, 'Content', 'content', 'index', 'WEBMASTER'),
(8, 'Edit Content', 'content', 'edit', 'WEBMASTER'),
(9, 'Submit content', 'content', 'post', 'WEBMASTER'),
(10, 'Preview content', 'content', 'preview', 'WEBMASTER'),
(11, 'Module', 'module', 'index', 'WEBMASTER'),
(12, 'module order', 'module', 'order', 'WEBMASTER'),
(13, 'Module news', 'module', 'news', 'WEBMASTER'),
(14, 'Users', 'user', 'index', 'WEBMASTER'),
(15, 'Add user', 'user', 'add', 'WEBMASTER'),
(16, 'Edit user', 'user', 'edit', 'WEBMASTER'),
(17, 'Submit user', 'user', 'post', 'WEBMASTER'),
(18, 'Logout', 'user', 'logout', 'SPANONYMOUS'),
(19, 'Settings', 'settings', 'index', 'WEBMASTER'),
(20, 'Language', 'main', 'language', 'WEBMASTER'),
(21, 'Recent pageview', 'main', 'recentpageview', 'SPANONYMOUS'),
(22, 'Recent actions', 'main', 'recent actions', 'SPANONYMOUS'),
(23, 'Delete Navigation', 'navigation', 'delete', 'WEBMASTER');

CREATE TABLE IF NOT EXISTS `#DBPREFIX#log` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `sessionid` varchar(32) NOT NULL DEFAULT '',
  `ip` varchar(16) NOT NULL DEFAULT '',
  `uri` varchar(100) NOT NULL DEFAULT '',
  `referer` varchar(255) NOT NULL DEFAULT '',
  `host` varchar(50) NOT NULL,
  `domain` varchar(40) NOT NULL,
  `navigationid` int(11) NOT NULL DEFAULT '0',
  `module` int(11) NOT NULL,
  `module_action` varchar(50) NOT NULL,
  `module_xid` int(11) NOT NULL COMMENT '记录newsid，新闻id等id',
  `addtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `sessionid` (`sessionid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `#DBPREFIX#module` (
  `mid` int(11) NOT NULL AUTO_INCREMENT COMMENT 'module id',
  `mname_en` varchar(255) NOT NULL,
  `mname_cn` varchar(255) NOT NULL,
  `module` varchar(255) NOT NULL,
  `menabled` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`mid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;


INSERT INTO `#DBPREFIX#module` (`mid`, `mname_en`, `mname_cn`, `module`, `menabled`) VALUES
(1, 'News', '新闻', 'news', 1),
(2, 'Order Form', '预定表单', 'order', 1),
(3, 'Contact Us', '联系表单', 'contact', 1);

CREATE TABLE IF NOT EXISTS `#DBPREFIX#navigation` (
  `nid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL DEFAULT '',
  `title` varchar(255) NOT NULL DEFAULT '',
  `content` text NOT NULL,
  `parentid` int(10) unsigned NOT NULL DEFAULT '0',
  `position` tinyint(4) NOT NULL,
  `type` tinyint(4) NOT NULL DEFAULT '0',
  `weight` int(10) NOT NULL DEFAULT '0',
  `enabled` tinyint(1) NOT NULL DEFAULT '1',
  `expanded` tinyint(4) NOT NULL,
  `module` int(11) NOT NULL,
  `is_del` tinyint(4) NOT NULL DEFAULT '0',
  `addtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`nid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;

INSERT INTO `#DBPREFIX#navigation` (`nid`, `name`, `title`, `content`, `parentid`, `position`, `type`, `weight`, `enabled`, `expanded`, `module`, `is_del`, `addtime`) VALUES
(1, '新闻', '新闻', '<br />', 0, 1, 0, -49, 1, 1, 1, 0, '2010-07-20 12:50:54'),
(2, '关于岩创', '关于岩创', '<p>	岩创网络科技有限公司成立于2010年6月，我们是一家专注于网站建设，网络研发，移动互联网方向的科技公司，公司拥有引以为傲的研发团队，有丰富的技术研发经验，针对客户需求提供，以客户满意为基础，以达到品牌效果为宗旨。</p><h3>	<a href=\"#\">我们的优势</a></h3><p>	我们在网站建设上有丰富的经验。我们为小公司，门户网站和财富500强提供网站和软件服务。欢迎<a href=\"/contact\">联系我们</a>。</p><h3>	<a href=\"#\">团队结构</a></h3><p>	我们的研发人员和美工人员来自各大门户网站，国际知名的外企。他们都是建设高速，高负载，高质量网站的专家。人均项目经验超过1000小时。</p><h3>	<a href=\"#\">关于本站</a></h3><p>	页面采用HTML5，程序采用python/django，数据库使用mysql</p>', 0, 2, 0, -49, 1, 0, 0, 0, '2010-07-20 12:27:11'),
(3, '普通内容', '普通内容', '<p>	<span class=\"bodytext\">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas feugiat consequat diam. Maecenas metus. Vivamus diam purus, cursus a, commodo non, facilisis vitae, nulla. Aenean dictum lacinia tortor. Nunc iaculis, nibh non iaculis aliquam, orci felis euismod neque, sed ornare massa mauris sed velit. Nulla pretium mi et risus. Fusce mi pede, tempor id, cursus ac, ullamcorper nec, enim. Sed tortor. Curabitur molestie. Duis velit augue, condimentum at, ultrices a, luctus ut, orci. Donec pellentesque egestas eros. Integer cursus, augue in cursus faucibus, eros pede bibendum sem, in tempus tellus justo quis ligula. Etiam eget tortor. Vestibulum rutrum, est ut placerat elementum, lectus nisl aliquam velit, tempor aliquam eros nunc nonummy metus. In eros metus, gravida a, gravida sed, lobortis id, turpis. Ut ultrices, ipsum at venenatis fringilla, sem nulla lacinia tellus, eget aliquet turpis mauris non enim. Nam turpis. Suspendisse lacinia. Curabitur ac tortor ut ipsum egestas elementum. Nunc imperdiet gravida mauris.</span></p>', 0, 1, 0, -50, 1, 0, 0, 0, '2010-08-04 11:15:20'),
(4, '订单', '订单系统', '<p>	<strong>Breakfast:</strong> Send your order no less than 1 hour before collection/arrival - if possible, send the night before.<br />	<strong>Lunch:</strong> Between 9am and 10.30am<br />	<strong>Dinner:</strong> Between 12.30pm and 3pm</p>', 0, 1, 0, -48, 1, 0, 2, 0, '2010-07-20 12:50:54'),
(5, '程序说明', 'SpeedCMS程序说明','<p>广告：岩创网络提供网站建设服务，欢迎咨询。</p><p> </p><p>标准化企业内容管理系统(SpeedCMS)</p><p>php框架采用SpeedPHP 感谢Jake和SpeedPHP的开发团队</p><p>	js框架采用jquery</p><p>	 </p><p>	本程序的目的在于给大家一个使用SpeedPHP建站的实例，同时也希望能够认识一些志同道合的朋友来一起开发完善<strong>SpeedCM</strong>S，实现共赢。</p><p>如果您希望将此项目进行商用，请务必联系作者获得许可，暂时并不需要商业授权费用。</p>', 0, 1, 0, -47, 1, 0, 0, 0, '2010-07-29 16:24:53'),
(6, '联系我们', '联系我们', '<p>上海市徐汇区乌鲁木齐中路261弄5号楼<br />邮编200133<br />电话:13918304704<br />	E-mail: contact( at )yancreate.com<br /></p>', 0, 2, 0, -50, 1, 0, 0, 0, '2010-07-20 12:29:38'),
(7, 'Sitemap', '', '', 0, 0, 0, 0, 0, 0, 0, 0, '2010-07-16 21:55:03');

CREATE TABLE IF NOT EXISTS `#DBPREFIX#news` (
  `newsid` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `content` text NOT NULL,
  `enabled` tinyint(4) NOT NULL DEFAULT '1',
  `views` int(11) NOT NULL DEFAULT '0',
  `addtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`newsid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;


CREATE TABLE IF NOT EXISTS `#DBPREFIX#orderform` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `tel` varchar(100) NOT NULL,
  `mealdate` date NOT NULL,
  `timearrive` varchar(255) NOT NULL,
  `encountertype` varchar(255) NOT NULL,
  `mealorder` text NOT NULL,
  `extranotes` text NOT NULL,
  `is_delete` tinyint(4) NOT NULL DEFAULT '0',
  `addtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;


CREATE TABLE IF NOT EXISTS `#DBPREFIX#settings` (
  `skey` varchar(255) NOT NULL DEFAULT '',
  `stype` enum('string','array') NOT NULL DEFAULT 'string',
  `svalue` text NOT NULL,
  PRIMARY KEY (`skey`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `#DBPREFIX#settings` (`skey`, `stype`, `svalue`) VALUES
('title_en', 'string', 'SpeedCMS demo website'),
('title_cn', 'string', 'SpeedCMS演示网站'),
('metadescription_en', 'string', 'SpeedCMS is base on speedphp'),
('metadescription_cn', 'string', 'SpeedCMS网站基于speedphp'),
('metakeywords_en', 'string', 'yancreate,speedcms,speedphp'),
('metakeywords_cn', 'string', '岩创网络,speedcms,speedphp'),
('copyrightshow', 'string', '1');

CREATE TABLE IF NOT EXISTS `#DBPREFIX#user` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `uname` varchar(20) NOT NULL,
  `upass` varchar(32) NOT NULL,
  `acl` varchar(10) NOT NULL DEFAULT 'CMSUSER',
  `firstname` varchar(255) NOT NULL,
  `lastname` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `street` varchar(255) NOT NULL,
  `city` varchar(255) NOT NULL,
  `country` varchar(255) NOT NULL,
  `state` varchar(255) NOT NULL,
  `zip` varchar(11) NOT NULL,
  `tel` varchar(50) NOT NULL,
  `enabled` tinyint(4) NOT NULL DEFAULT '0',
  `addtime` datetime NOT NULL,
  PRIMARY KEY (`uid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;


CREATE TABLE IF NOT EXISTS `#DBPREFIX#usergroup` (
  `gid` int(11) NOT NULL AUTO_INCREMENT,
  `acl` varchar(255) NOT NULL,
  `gname_cn` varchar(255) NOT NULL,
  `gdescription_cn` varchar(255) NOT NULL,
  `gname_en` varchar(255) NOT NULL,
  `gdescription_en` varchar(255) NOT NULL,
  PRIMARY KEY (`gid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;


INSERT INTO `#DBPREFIX#usergroup` (`gid`, `acl`, `gname_cn`, `gdescription_cn`, `gname_en`, `gdescription_en`) VALUES
(1, 'EDITOR', '编辑', '编辑人员能编辑一些内容和导航', 'Editor', 'Editor could edit content and edit navigation'),
(2, 'WEBMASTER', '网站管理员', '网站管理员能管理用户，编辑内容和导航', 'Webmaster', 'Webmaster could manage user, manage content and manage navigation');

";


if( empty($_GET["step"]) || 1 == $_GET["step"]  ){
	// 第一步，检查更新
	$checkurl = "http://speedcms.yancreate.com/version/?v=" . SPEEDCMS_VERSION;
	require(APP_PATH.'/template/install/step1.html');
}elseif( 2 == $_GET["step"] ){
	// 第二步，填写资料
	$tips = $defaults;
	require(APP_PATH.'/template/install/step2.html');
}else{
	// 第三步，验证资料，写入资料，完成安装
	$dblink = null;$err=null;$adminsql = null;
	while(1){
		// 检查本地数据库设置
		ins_checkdblink($_POST);if( null != $err )break;
		// 增加管理员用户
		ins_registeruser($_POST,$_POST["DB_PREFIX"]);if( null != $err )break;
		// 本地数据库入库
		$sql .= $adminsql;
		ins_query($sql,$_POST["DB_PREFIX"]);if( null != $err )break;
		// 改写本地配置文件
		ins_writeconfig($_POST);if( null != $err )break;
		break;
	}
	if( null != $err ){ // 有错误则覆盖
		$tips = array_merge($defaults, $_POST); // 显示原值或新值
		require(APP_PATH.'/template/install/step2.html');
	}else{
		require(APP_PATH.'/template/install/step3.html');
	}
}