<?php

/*
  PHP version 5
  Copyright (c) 2002-2018 ECISP.CN、EarcLink.COM
  警告：这不是一个免费的软件，请在许可范围内使用，请尊重知识产权，侵权必究，举报有奖
  作者：黄祥云 E-mail:6326420@qq.com  QQ:6326420 TEL:18665655030 / 13797552220
*/

use application\ESPCMS_AdminAuthority;
use application\ESPCMS_Core;
use application\ESPCMS_FileTool;
use admin_application\DBSql;
use admin_application\link\UpdateSoftLink;

class UpgradeSoft {

	public function __construct() {
		$exclude_method = array('viewUpgradeSoft', 'executeUpgradeSoft');
		ESPCMS_AdminAuthority::authorityAdminVerify($exclude_method);
	}

	public static function entranceUpgradeSoft() {
		global $espcms_admin_templates, $espcms_command;
		$admin_member_id = ESPCMS_AdminAuthority::getUserLoginInfo('admin_member_id');
		if (empty($admin_member_id) || !espcms_ismatches($admin_member_id)) {
			espcms_message_err('public_pack-espcms_input_parameter_fail', array($admin_member_id));
		}
		if (!function_exists('zip_open')) {
			espcms_message_err('public_pack-espcms_php_function_err', array('zip'));
		}
		if (!ESPCMS_Core::is_command_write()) {
			espcms_message_err('public_pack-espcms_command_err2');
		}
		$vol = $espcms_command['CON_VOLSTR'];
		$espcms_admin_templates->into('vol', $vol);
		$espcms_status = ESPCMS_Core::connect_service('UpdateSoftStatus');
		if (is_array($espcms_status)) {
			$espcms_admin_templates->into('update', $espcms_status);
		}
		$espcms_admin_templates->into('link', UpdateSoftLink::UpdateSoft_link_array());
		$espcms_admin_templates->into('token', token());
		$espcms_admin_templates->output('admin/upgrade_soft_entrance');
	}

	public static function executeUpgradeSoft() {
		$admin_member_id = ESPCMS_AdminAuthority::getUserLoginInfo('admin_member_id');
		if (empty($admin_member_id) || !espcms_ismatches($admin_member_id)) {
			espcms_public_dialog('espcms_public_dialog', 'public_pack-espcms_input_parameter_fail', 'false');
		}
		$update_pack_list = ESPCMS_Core::connect_service('UpdateSoftPack', array(), false);
		if (!$update_pack_list) {
			espcms_public_dialog('espcms_public_dialog', 'public_pack-espcms_update_pack_list_err', 'false');
		}
		exit($update_pack_list);
	}

	public static function viewUpgradeSoft() {
		if (!ESPCMS_AdminAuthority::authorityVerify('entranceUpgradeSoft')) {
			espcms_public_dialog('espcms_public_dialog', 'public_pack-espcms_authority_function_fail', 'false');
		}
		$uid = $_POST['uid'];
		if (!$uid || !espcms_ismatches($uid)) {
			espcms_public_dialog('espcms_public_dialog', 'public_pack-espcms_input_parameter_fail', 'false', array($uid));
		}
		$update_pack_view = ESPCMS_Core::connect_service('UpdateSoftPackView', array('uid' => $uid));
		if (!$update_pack_view || !is_array($update_pack_view)) {
			espcms_public_dialog('espcms_public_dialog', 'setting_pack-espcms_update_packread_err', 'false');
		}
		if (!function_exists('zip_open')) {
			espcms_public_dialog('espcms_public_dialog', 'public_pack-espcms_php_function_err', 'false', array('zip'));
		}
		if (!ESPCMS_Core::is_command_write()) {
			espcms_public_dialog('espcms_public_dialog', 'public_pack-espcms_command_err2', 'false');
		}
		$update_status = self::pack_update($update_pack_view);
		if ($update_status) {
			espcms_public_dialog('espcms_public_dialog', 'setting_pack-espcms_update_pack_ok', 'true', array($update_pack_view['volstr']), 'json', $update_pack_view);
		} else {
			espcms_public_dialog('espcms_public_dialog', 'setting_pack-espcms_update_pack_no', 'false', array($update_pack_view['volstr']));
		}
	}

	private static function pack_update($pack_read = array()) {
		global $espcms_command, $espcms_link_db;
		if (!$pack_read || !is_array($pack_read) || !$pack_read['upfile'] || !$pack_read['downloadurl']) {
			return false;
		}
		if ($pack_read['uservol'] != $espcms_command['CON_VOL']) {
			return false;
		}
		$filename = md5($pack_read['vol']);
		$download_file = ESPCMS_FILE_ROOT . 'espcms_datacache/cache_pack/' . $filename . '.zip';
		if (!is_file($download_file)) {
			if (!ESPCMS_FileTool::downloadFile($pack_read['upfile'], $download_file)) {
				return false;
			}
		}
		if ($pack_read['issqlbak']) {
			if (!DBSql::sqlBak()) {
				return false;
			}
		}
		$zip = zip_open($download_file);
		if (is_resource($zip)) {
			while (($zip_entry = zip_read($zip)) !== false) {
				$filename = zip_entry_name($zip_entry);
				$foldername = ESPCMS_FILE_ROOT . $filename;
				if (strpos(zip_entry_name($zip_entry), '/') !== false) {
					$last = strrpos(zip_entry_name($zip_entry), '/');
					$dir = ESPCMS_FILE_ROOT . substr(zip_entry_name($zip_entry), 0, $last);
					$file = substr(zip_entry_name($zip_entry), strrpos(zip_entry_name($zip_entry), '/') + 1);
					if (!is_dir($dir)) {
						mkdir($dir, 0755, true);
					}
					if (strlen(trim($file)) > 0) {
						$return = file_put_contents($foldername, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
						if (!$return) {
							return false;
						}
					}
				} else {
					$return = file_put_contents($foldername, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
					if (!$return) {
						return false;
					}
				}
			}
			zip_close($zip);
			ESPCMS_FileTool::delFile($download_file);
		} else {
			return false;
		}
		if ($pack_read['isadmindir'] && ESPCMS_ADMIN_DIRNAME != 'espcms_admin') {
			$now_dir_path = ESPCMS_FILE_ROOT . ESPCMS_ADMIN_DIRNAME . '/';
			$pack_dir_path = ESPCMS_FILE_ROOT . 'espcms_admin/';
			if (!ESPCMS_FileTool::file_copy($pack_dir_path, $now_dir_path)) {
				espcms_out($pack_read);
				return false;
			}
		}
		if ($pack_read['issqlbak']) {
			$db_file = ESPCMS_FILE_ROOT . $pack_read['vol'] . '.sql';
			if (!is_file($db_file)) {
				return false;
			}
			$updatesql = file_get_contents($db_file);
			if ($updatesql) {
				$updatesql = str_replace("\r\n", "\n", $updatesql);
				$ret = array();
				$num = 0;
				foreach (explode(";\n", trim($updatesql)) as $query) {
					$ret[$num] = '';
					$queries = explode("\n", trim($query));
					foreach ($queries as $query) {
						$ret[$num] .= ( isset($query[0]) && $query[0] == '#') || (isset($query[1]) && isset($query[1]) && $query[0] . $query[1] == '--') ? '' : $query;
					}
					$num++;
				}
				unset($updatesql);
				foreach ($ret as $query) {
					$query = trim($query);
					if ($query) {
						$query = str_replace('esp_', ESPCMS_DB_PREFIX, $query);
						$espcms_link_db->db_query($query);
					}
				}
				ESPCMS_FileTool::delFile($db_file);
			} else {
				return false;
			}
		}
		$db_table = ESPCMS_DB_PREFIX . "config";
		espcms_db_update_set_save($db_table, "WHERE config_name='CON_VOL'", "config_value='$pack_read[vol]'");
		espcms_db_update_set_save($db_table, "WHERE config_name='CON_VOLSTR'", "config_value='$pack_read[volstr]'");
		ESPCMS_Core::command_creat();
		return true;
	}

}
