<?php

/*
 * Process.class.php    (处理模型)
 * @projectname  QCCMS
 * @package      
 * @author       qccms
 * @copyright    qccms
 * @license     
 * @version      2013-08-14
 */

class Process {

	//读取协议说明
	public function getLicense() {
		$errorMsg = "<span style='color:red;'>协议许可说明不存在!!</span>";
		if (!file_exists(ROOT_PATH . 'license.txt'))
			return $errorMsg;
		else {
			$handle = @fopen(ROOT_PATH . 'license.txt', 'r');
			if ($handle) {
				while (($line = fgets($handle)) != FALSE) {
					$content.=$line . '<br />';
				}
			}
			fclose($handle);
			return $content;
		}
	}

	//环境检查
	public function checkEnv() {
		$env['system'] = array('value' => PHP_OS, 'status' => 1);
		if (version_compare(PHP_VERSION, '5.4.0', '<')) {
			$env['phpVersion'] = array('value' => PHP_VERSION, 'status' => 0);
			$GLOBALS['installSuccess'] = 0;
		}
		else
			$env['phpVersion'] = array('value' => PHP_VERSION, 'status' => 1);
		$env['uploadMaxSize'] = (ini_get('file_uploads')) ? ini_get('upload_max_filesize') : '未知';
		$gdInfo = (function_exists('gd_info')) ? gd_info() : array();
		$env['gdVersion'] = ($gdInfo['GD Version']) ? array('value' => $gdInfo['GD Version'], 'status' => 1) : array('value' => '未知', 'status' => 0);
		$env['space'] = function_exists('disk_free_space') ? floor(disk_free_space(ROOT_PATH) / (1024 * 1024)) . 'M' : '未知';
		return $env;
	}

	//获取检查目录文件的结果
	public function getDirFile() {
		$this->checkDirFile($GLOBALS['dirfile_items']);
		foreach ($GLOBALS['dirfile_items'] as $k => $v) {
			$dirFile.='<tr><td>' . $v['path'] . '</td><td class="w pdleft1">' . ($v['needStatus'] == 1 ? '可读可写' : '可读') . '</td>';
            $haveError = 0;
            if ($v['needStatus'] > $v['status']) {
                $GLOBALS['installSuccess'] = 0;
                $haveError = 1;
            }
			if ($v['status'] == 1)
				$dirFile .= '<td class="'.($haveError?'n':'').'w pdleft1">可读可写</td>';
			elseif ($v['status'] == 0)
				$dirFile .= '<td class="'.($haveError?'n':'').'w pdleft1">可读</td>';
			else
				$dirFile .= '<td class="nw pdleft1">不存在</td>';
			$dirFile .= '</tr>';
		}
		return $dirFile;
	}

	//返回函数检查结果
	public function checkFuns() {
		foreach ($GLOBALS['checkFuns'] as $k => &$v) {
			if (!function_exists($k)) {
				$v['status'] = 0;
				$GLOBALS['installSuccess'] = 0;
			}
			$funsResult.='<tr>';
			$funsResult.='<td>' . $k . '()</td>';
			$funsResult.=($v['status']) ? '<td class = "w pdleft1">支持</td><td class = "padleft">无</td>' : '<td class = "nw pdleft1">不支持</td><td><span style="color:red;">' . $v['suggest'] . '</span></td>';
			$funsResult.='</tr>';
		}
		return $funsResult;
	}

	//安装数据库检查
	public function dbSetup(&$post) {
        @set_time_limit(300);
		foreach ($GLOBALS['dbInfo'] as $k => $v) {
			if (empty($post['dbinfo'][$k])) {
				$GLOBALS['installSuccess'] = 0;
				$GLOBALS['installMsg'] = '请输入' . $v . '!';
				return false;
			}
		}
		foreach ($GLOBALS['adminInfo'] as $k => $v) {
			if (empty($post['admininfo'][$k])) {
				$GLOBALS['installSuccess'] = 0;
				$GLOBALS['installMsg'] = '请输入' . $v . '!';
				return false;
			}
		}
		if ($post['admininfo']['password'] != $post['admininfo']['password2']) {
			$GLOBALS['installSuccess'] = 0;
			$GLOBALS['installMsg'] = '重复密码错误!';
			return false;
		}
		//数据库连接检查
		$mysqli = @new mysqli($post['dbinfo']['dbhost'], $post['dbinfo']['dbuser'], $post['dbinfo']['dbpw']);
		if (mysqli_connect_error()) {
			$GLOBALS['installSuccess'] = 0;
			$GLOBALS['installMsg'] = '数据库连接错误:' . mysqli_connect_error() . '!';
			return false;
		}
		$mysqli->query("SET NAMES 'utf8'");
		//检查数据库是否存在，若不存在创建
		if (!$mysqli->select_db($post['dbinfo']['dbname'])) {
            //创建数据库
            if (!$mysqli->query('CREATE DATABASE IF NOT EXISTS `' . $post['dbinfo']['dbname'] . '` DEFAULT CHARACTER SET utf8 ;')) {
                $GLOBALS['installSuccess'] = 0;
                $GLOBALS['installMsg'] = '创建数据库' . $post['dbinfo']['dbname'] . '失败!';
                return false;
            }
		}
		
		if (!file_exists(QCCMS_SQL)) {
			$GLOBALS['installSuccess'] = 0;
			$GLOBALS['installMsg'] = '缺少数据库文件！';
			return false;
		}
		if (!$mysqli->select_db($post['dbinfo']['dbname'])) {
			$GLOBALS['installSuccess'] = 0;
			$GLOBALS['installMsg'] = '数据库' . $post['dbinfo']['dbname'] . '不存在!';
			return false;
		}
		$qccmsSql = file_get_contents(QCCMS_SQL);
		$sql = sql_format($qccmsSql, $post['dbinfo']['tablepre']);
		foreach ($sql as $v) {
			if (strpos($v, 'CREATE TABLE') !== false) {
				preg_match('/CREATE TABLE `([^ ]*)`/', $v, $matches);
				$result = $mysqli->query($v);
				if ($result) {
					$message .= '<font color="#FCAB03">成功创建数据表：' . $matches[1] . '  </font><br />';
				} else {
					$message .= '<font  color="red">创建数据表失败：' . $matches[1] . ' </font><br />';
				}
			} else {
				$result = $mysqli->query($v);
			}
		}
        $password = generatePassword($post['admininfo']['password']);
        $authKey = generateAuthKey();
		//更改管理员信息
		$adminSql = "update ".$post['dbinfo']['tablepre']."user set username='" . $post['admininfo']['username'] . "',auth_key='" . $authKey . "',password_hash='" . $password . "' where user_id=1";
		$message.=(false !== $mysqli->query($adminSql)) ? '<font color="#FCAB03">更改管理员信息成功</font><br />' : '<font  color="red">更改管理员信息失败</font><br />';
		//替换数据库配置文件
		$tempDbConfig = file_get_contents(TEMP_DBCONFIG);
		$dbSearch = array('{$DB_HOST}', '{$DB_NAME}', '{$DB_USER}', '{$DB_PWD}', '{$DB_PORT}', '{$DB_PREFIX}');
		$dbReplace = array($post['dbinfo']['dbhost'], $post['dbinfo']['dbname'], $post['dbinfo']['dbuser'], $post['dbinfo']['dbpw'], $post['dbinfo']['dbport'], $post['dbinfo']['tablepre']);
		$tempDbConfig= str_replace($dbSearch, $dbReplace, $tempDbConfig);
		$message.=(false!==file_put_contents(APP_DBCONFIG, $tempDbConfig))?'<font color="#FCAB03">替换数据库配置文件成功</font><br />': '<font  color="red">替换数据库配置文件失败</font><br />';
		//建立安装锁
		if (!copy(TEMP_LOCK, INSTALL_LOCK)) {
            $message.='<font  color="red">建立安装锁定文件失败！！请检查web根目录下是否有写入文件权限！</font><br />';
            $GLOBALS['installSuccess'] = 0;
			$GLOBALS['installMsg'] = '建立安装锁定文件失败!';
			return false;
        }

		return $message;
	}

	//检查目录文件
	public function checkDirFile(&$dirfile_items) {
		foreach ($dirfile_items as $key => $item) {
			$item_path = $item['path'];
			if ($item['type'] == 'dir') {
				if (!dir_writeable(ROOT_PATH . $item_path)) {
					if (is_dir(ROOT_PATH . $item_path)) {
						$dirfile_items[$key]['status'] = 0;
						$dirfile_items[$key]['current'] = '+r';
					} else {
						$dirfile_items[$key]['status'] = -1;
						$dirfile_items[$key]['current'] = 'nodir';
					}
				} else {
					$dirfile_items[$key]['status'] = 1;
					$dirfile_items[$key]['current'] = '+r+w';
				}
			} else {
				if (file_exists(ROOT_PATH . $item_path)) {
					if (is_writable(ROOT_PATH . $item_path)) {
						$dirfile_items[$key]['status'] = 1;
						$dirfile_items[$key]['current'] = '+r+w';
					} else {
						$dirfile_items[$key]['status'] = 0;
						$dirfile_items[$key]['current'] = '+r';
					}
				} else {
					if (dir_writeable(dirname(ROOT_PATH . $item_path))) {
						$dirfile_items[$key]['status'] = 1;
						$dirfile_items[$key]['current'] = '+r+w';
					} else {
						$dirfile_items[$key]['status'] = -1;
						$dirfile_items[$key]['current'] = 'nofile';
					}
				}
			}
		}
	}

}

?>
