<?php
$_GET['m']='bbs';
$_GET['c']='post';
$_GET['a']='doreply';
isset($_POST['tid']) ? $_GET['tid']=$_POST['tid'] : $_GET['tid']='';

$_SERVER['HTTP_X_REWRITE_URL']=$_SERVER['REQUEST_URI']=$_SERVER['REQUEST_URI'].'?m=bbs&c=post&a=doreply&tid='.$_GET['tid'];

error_reporting(E_ERROR | E_PARSE);
define('WEKIT_PATH', dirname(__FILE__) . DIRECTORY_SEPARATOR.'src'. DIRECTORY_SEPARATOR);//zzcuty modi
define('WEKIT_VERSION', '0.3.9');
define('NEXT_VERSION', '9.0');
define('NEXT_RELEASE', '20130227');
define('NEXT_FIXBUG','9000001');
defined('WIND_DEBUG') || define('WIND_DEBUG', 0);

/* 框架版本信息 */
define('WIND_VERSION', '1.0.0');
/* 路径相关配置信息 */
define('WIND_PATH', dirname(__FILE__). DIRECTORY_SEPARATOR.'wind');//zzcuty modi
/*
 * 二进制:十进制 模式描述 
 * 00: 0 关闭 
 * 01: 1 window 
 * 10: 2 log 
 * 11: 3 window|log
 */
!defined('WIND_DEBUG') && define('WIND_DEBUG', 0);
/**
 *
 * @author Qiong Wu <papa0924@gmail.com> 2011-10-9
 * @copyright ©2003-2103 phpwind.com
 * @license http://www.windframework.com
 * @version $Id: Wind.php 3904 2013-01-08 07:01:26Z yishuo $
 */
class Wind {
	public static $isDebug = 0;
	public static $_imports = array();
	public static $_classes = array();
	private static $_extensions = 'php';
	private static $_isAutoLoad = true;
	private static $_namespace = array();
	private static $_includePaths = array();
	
	/**
	 *
	 * @var AbstractWindFrontController
	 */
	private static $_front = null;

	/**
	 * command line mode application 应用入口
	 * 
	 * @param string $appName        
	 * @param string|array $config        
	 * @return WindCommandFrontController
	 */
	public static function commandApplication($appName = '', $config = array()) {
		if (self::$_front === null) {
			self::$_classes['WindCommandFrontController'] = 'command/WindCommandFrontController';
			self::$_front = new WindCommandFrontController($appName, $config);
		}
		return self::$_front;
	}

	/**
	 * Web Application应用入口
	 * 
	 * @param string $appName        
	 * @param string|array $config        
	 * @return WindWebApplication
	 */
	public static function application($appName = '', $config = array()) {
		if (self::$_front === null) {
			self::$_classes['WindWebFrontController'] = 'web/WindWebFrontController';
			self::$_front = new WindWebFrontController($appName, $config);
		}
		return self::$_front;
	}

	/**
	 * 获取系统组建
	 * 
	 * @param string $alias        
	 * @param array $args        
	 * @return Ambigous <NULL, multitype:, WindClassProxy, WindModule, unknown,
	 *         mixed>
	 */
	public static function getComponent($alias, $args = array()) {
		return WindFactory::_getInstance()->getInstance($alias, $args);
	}

	/**
	 * 注册系统组建
	 * <code>
	 * 对象方式注册:
	 * $converter = new WindGeneralConverter();
	 * Wind::registeComponent($converter,'windConverter',singleton);
	 * 定义方式注册:
	 * Wind::registeComponent(array('path' =>
	 * 'WIND:convert.WindGeneralConverter', 'scope' => 'singleton'),
	 * 'windConverter');</code>
	 * 
	 * @param object|array $componentInstance        
	 * @param string $componentName        
	 * @param string $scope        
	 * @return boolean
	 */
	public static function registeComponent($componentInstance, $componentName, $scope = 'application') {
		if (is_array($componentInstance)) {
			isset($componentInstance['scope']) || $componentInstance['scope'] = $scope;
			WindFactory::_getInstance()->loadClassDefinitions(
				array($componentName => $componentInstance));
		} elseif (is_object($componentInstance)) {
			WindFactory::_getInstance()->registInstance($componentInstance, $componentName, $scope);
		} else
			throw new WindException('[Wind.registeComponent] registe component fail, array or object is required', 
				WindException::ERROR_PARAMETER_TYPE_ERROR);
	}

	/**
	 *
	 * @see WindFrontController::getAppName()
	 * @return string
	 */
	public static function getAppName() {
		return self::$_front->getAppName();
	}

	/**
	 * 返回当前的app应用
	 * 
	 * @param string $appName        
	 * @see WindFrontController::getApp()
	 * @return WindWebApplication
	 */
	public static function getApp() {
		return self::$_front->getApp();
	}

	/**
	 * 加载一个类或者加载一个包
	 * 如果加载的包中有子文件夹不进行循环加载
	 * 参数格式说明：'WIND:base.WFrontController'
	 * WIND 注册的应用名称，应用名称与路径信息用‘:’号分隔
	 * base.WFrontController 相对的路径信息
	 * 如果不填写应用名称 ，例如‘base.WFrontController’，那么加载路径则相对于默认的应用路径
	 * 加载一个类的参数方式：'WIND:base.WFrontController'
	 * 加载一个包的参数方式：'WIND:base.*'
	 * 
	 * @param string $filePath
	 *        | 文件路径信息 或者className
	 * @return string null
	 */
	public static function import($filePath) {
		if (!$filePath) return;
		if (isset(self::$_imports[$filePath])) return self::$_imports[$filePath];
		if (($pos = strrpos($filePath, '.')) !== false)
			$fileName = substr($filePath, $pos + 1);
		elseif (($pos = strrpos($filePath, ':')) !== false)
			$fileName = substr($filePath, $pos + 1);
		else
			$fileName = $filePath;
		$isPackage = $fileName === '*';
		if ($isPackage) {
			$filePath = substr($filePath, 0, $pos + 1);
			$dirPath = self::getRealPath(trim($filePath, '.'), false);
			self::register($dirPath, '', true);
		} else
			self::_setImport($fileName, $filePath);
		return $fileName;
	}

//zzcity
	public static function zzimport($filePath) {
		if (!$filePath) return;
		if (isset(self::$_imports[$filePath])) return self::$_imports[$filePath];
		if (($pos = strrpos($filePath, '.')) !== false)
			$fileName = substr($filePath, $pos + 1);
		elseif (($pos = strrpos($filePath, ':')) !== false)
			$fileName = substr($filePath, $pos + 1);
		else
			$fileName = $filePath;
		return $fileName;
	}


	/**
	 * 将路径信息注册到命名空间,该方法不会覆盖已经定义过的命名空间
	 * 
	 * @param string $path
	 *        需要注册的路径
	 * @param string $name
	 *        路径别名
	 * @param boolean $includePath
	 *        | 是否同时定义includePath
	 * @param boolean $reset
	 *        | 是否覆盖已经存在的定义，默认false
	 * @return void
	 * @throws Exception
	 */
	public static function register($path, $alias = '', $includePath = false, $reset = false) {
		if (!$path) return;
		if (!empty($alias)) {
			$alias = strtolower($alias);
			if (!isset(self::$_namespace[$alias]) || $reset) self::$_namespace[$alias] = rtrim(
				$path, '\\/') . DIRECTORY_SEPARATOR;
		}
		if ($includePath) {
			if (empty(self::$_includePaths)) {
				self::$_includePaths = array_unique(explode(PATH_SEPARATOR, get_include_path()));
				if (($pos = array_search('.', self::$_includePaths, true)) !== false) unset(
					self::$_includePaths[$pos]);
			}
			array_unshift(self::$_includePaths, $path);
			if (set_include_path(
				'.' . PATH_SEPARATOR . implode(PATH_SEPARATOR, self::$_includePaths)) === false) {
				throw new Exception('[Wind.register] set include path error.');
			}
		}
	}

	/**
	 * 返回命名空间的路径信息
	 * 
	 * @param string $namespace        
	 * @return string Ambigous multitype:>
	 */
	public static function getRootPath($namespace) {
		$namespace = strtolower($namespace);
		return isset(self::$_namespace[$namespace]) ? self::$_namespace[$namespace] : '';
	}

	/**
	 * 类文件自动加载方法 callback
	 * 
	 * @param string $className        
	 * @param string $path        
	 * @return null
	 */
	public static function autoLoad($className, $path = '') {
		if ($path)
			include $path . '.' . self::$_extensions;
		elseif (isset(self::$_classes[$className])) {
			include self::$_classes[$className] . '.' . self::$_extensions;
		} else
			include $className . '.' . self::$_extensions;
	}

	/**
	 * 解析路径信息，并返回路径的详情
	 * 
	 * @param string $filePath
	 *        路径信息
	 * @param boolean $suffix
	 *        是否存在文件后缀true，false，default
	 * @return string array('isPackage','fileName','extension','realPath')
	 */
	public static function getRealPath($filePath, $suffix = '', $absolut = false) {
		if (false !== strpos($filePath, DIRECTORY_SEPARATOR)) return realpath($filePath);
		if (false !== ($pos = strpos($filePath, ':'))) {
			$namespace = self::getRootPath(substr($filePath, 0, $pos));
			$filePath = substr($filePath, $pos + 1);
		} else
			$namespace = $absolut ? self::getRootPath(self::getAppName()) : '';
		
		$filePath = str_replace('.', '/', $filePath);
		$namespace && $filePath = $namespace . $filePath;
		if ($suffix === '') return $filePath . '.' . self::$_extensions;
		if ($suffix === true && false !== ($pos = strrpos($filePath, '/'))) {
			$filePath[$pos] = '.';
			return $filePath;
		}
		return $suffix ? $filePath . '.' . $suffix : $filePath;
	}

	/**
	 * 解析路径信息，并返回路径的详情
	 * 
	 * @param string $filePath
	 *        路径信息
	 * @param boolean $absolut
	 *        是否返回绝对路径
	 * @return string array('isPackage','fileName','extension','realPath')
	 */
	public static function getRealDir($dirPath, $absolut = false) {
		if (false !== ($pos = strpos($dirPath, ':'))) {
			$namespace = self::getRootPath(substr($dirPath, 0, $pos));
			$dirPath = substr($dirPath, $pos + 1);
		} else
			$namespace = $absolut ? self::getRootPath(self::getAppName()) : '';
		
		return ($namespace ? $namespace : '') . str_replace('.', '/', $dirPath);
	}

	/**
	 * 初始化框架
	 */
	public static function init() {
		self::$isDebug = WIND_DEBUG;
		function_exists('date_default_timezone_set') && date_default_timezone_set('Etc/GMT+0');
		self::register(WIND_PATH, 'WIND', true);
		if (!self::$_isAutoLoad) return;
		if (function_exists('spl_autoload_register'))
			spl_autoload_register('Wind::autoLoad');
		else
			self::$_isAutoLoad = false;
		self::_loadBaseLib();
	}

	/**
	 * 日志记录
	 * 
	 * 调用WindLogger组建进行日志记录
	 * @param string $message
	 * @param string $logType
	 * @throws WindMailException
	 */
	public static function log($message, $logType = 'wind.core') {
		if (self::$isDebug) {
			$traces = debug_backtrace();
			if (isset($traces[1])) {
				$message = "\r\n" . $traces[0]['file'] . " (" . $traces[0]['line'] . ") [" . 
					$traces[1]['class'] . "::" . $traces[1]['function'] . "]\r\n" . $message;
			}
			Wind::getComponent('windLogger')->info($message, $logType);
		}
	}

	/**
	 *
	 * @param string $className        
	 * @param string $classPath        
	 * @return void
	 */
	private static function _setImport($className, $classPath) {
		self::$_imports[$classPath] = $className;
		if (!isset(self::$_classes[$className])) {
			$_classPath = self::getRealPath($classPath, false);
			self::$_classes[$className] = $_classPath;
		} else
			$_classPath = self::$_classes[$className];
		if (!self::$_isAutoLoad) self::autoLoad($className, $_classPath);
	}

	/**
	 * 加载核心层库函数
	 * 
	 * @return void
	 */
	private static function _loadBaseLib() {
		self::$_classes = array(
			'AbstractWindBootstrap' => 'base/AbstractWindBootstrap', 
			'AbstractWindFrontController' => 'base/AbstractWindFrontController', 
			//'AbstractWindApplication' => 'base/AbstractWindApplication',  //zzcity
			'IWindController' => 'base/IWindController', 
			'IWindRequest' => 'base/IWindRequest', 
			'IWindResponse' => 'base/IWindResponse', 
			'WindActionException' => 'base/WindActionException', 
			'WindEnableValidateModule' => 'base/WindEnableValidateModule', 
			'WindError' => 'base/WindError', 
			'WindErrorMessage' => 'base/WindErrorMessage', 
			'WindException' => 'base/WindException', 
			'WindFactory' => 'base/WindFactory', 
			'WindFinalException' => 'base/WindFinalException', 
			'WindForwardException' => 'base/WindForwardException', 
			'WindModule' => 'base/WindModule', 
			'WindActionFilter' => 'filter/WindActionFilter', 
			'WindHandlerInterceptor' => 'filter/WindHandlerInterceptor', 
			'WindHandlerInterceptorChain' => 'filter/WindHandlerInterceptorChain', 
			'WindLogger' => 'log/WindLogger', 
			'WindLangResource' => 'i18n/WindLangResource', 
			'WindConfigParser' => 'parser/WindConfigParser', 
			'WindArray' => 'utility/WindArray', 
			'WindConvert' => 'utility/WindConvert', 
			'WindCookie' => 'utility/WindCookie', 
			'WindDate' => 'utility/WindDate', 
			'WindFile' => 'utility/WindFile', 
			'WindFolder' => 'utility/WindFolder', 
			'WindGeneralDate' => 'utility/WindGeneralDate', 
			'WindImage' => 'utility/WindImage', 
			'WindJson' => 'utility/WindJson', 
			'WindPack' => 'utility/WindPack', 
			'WindSecurity' => 'utility/WindSecurity', 
			'WindString' => 'utility/WindString', 
			'WindUrlHelper' => 'utility/WindUrlHelper', 
			'WindUtility' => 'utility/WindUtility', 
			'WindValidator' => 'utility/WindValidator');
	}
}

Wind::init();


abstract class AbstractWindApplication extends WindModule {
	/**
	 * 请求对象
	 *
	 * @var WindHttpRequest
	 */
	protected $request;
	
	/**
	 * 响应对象
	 *
	 * @var WindHttpResponse
	 */
	protected $response;
	
	/**
	 * 组建工厂对象
	 *
	 * @var WindFactory
	 */
	protected $factory = null;
	
	/**
	 * 路由对象
	 *
	 * @var WindRouter
	 */
	protected $handlerAdapter = null;

	/**
	 * 应用初始化操作
	 *
	 * @param WindHttpRequest $request
	 * @param WindHttpResponse $response
	 * @param WindFactory $factory
	 */
	public function __construct($request, $response, $factory) {
		$this->response = $response;
		$this->request = $request;
		$this->factory = $factory;
	}

	/**
	 * 请求处理完毕后，进一步分发
	 * 
	 * @param WindForward $forward        
	 * @param boolean $display        
	 */
	abstract public function doDispatch($forward);

	/**
	 * 处理错误请求
	 * 根据错误请求的相关信息,将程序转向到错误处理句柄进行错误处理
	 *
	 * @param WindErrorMessage $errorMessage
	 * @param int $errorcode
	 * @return void
	 */
	abstract protected function sendErrorMessage($errorMessage, $errorcode);
	
	/*
	 * (non-PHPdoc) @see IWindApplication::run()
	 */
	public function run($handlerAdapter = null) {
		$handlerAdapter !== null && $this->handlerAdapter = $handlerAdapter;
		$module = $this->getModules();
		$handlerPath = $module['controller-path'] . '.' . ucfirst($this->handlerAdapter->getController()) . $module['controller-suffix'];
		$className = Wind::zzimport($handlerPath); //zzcity
		
		if (!class_exists($className)) throw new WindException(
			'Your requested \'' . $handlerPath . '\' was not found on this server.', 404);
		$handler = new $className();
		$handler->setDelayAttributes(
			array('errorMessage' => array('ref' => 'errorMessage'), 'forward' => array('ref' => 'forward')));
		
		$handlerAdapter !== null && $this->resolveActionFilters($handler);
		
		try {
		
			$forward = $handler->doAction($this->handlerAdapter);
//			$this->doDispatch($forward); //zzcity

		} catch (WindForwardException $e) {
			echo('[err]'.$e->getMessage().'[/err]');
			exit;
//			$this->doDispatch($e->getForward());
		} catch (WindActionException $e) {
			echo('[err]'.$e->getMessage().'[/err]');
			exit;
//			$this->sendErrorMessage(($e->getError() ? $e->getError() : $e->getMessage()), 
//				$e->getCode());
		} catch (WindException $e) {
			echo('[err]'.$e->getMessage().'[/err]');
			exit;
//			$this->sendErrorMessage($e->getMessage(), $e->getCode());
		}
	}

	/**
	 * 添加module配置
	 * <code>
	 * <controller-path>controller</controller-path>
	 * <!-- 指定该模块下的controller的后缀格式 -->
	 * <controller-suffix>Controller</controller-suffix>
	 * <!-- 配置该模块的error处理的action controller类 -->
	 * <error-handler>WIND:web.WindErrorHandler</error-handler>
	 * <!-- 试图相关配置，config中配置可以根据自己的需要进行配置或是使用缺省 -->
	 * <!-- 可以在这里进行view的配置，该配置只会影响该module下的view行为，该配置可以设置也可以不设置 -->
	 * <!-- 指定模板路径 -->
	 * <template-dir>template</template-dir>
	 * <!-- 指定模板后缀 -->
	 * <template-ext>htm</template-ext></code>
	 * 
	 * @param string $name
	 *        module名称
	 * @param array $config
	 *        配置数组
	 * @param boolean $replace
	 *        如果module已经存在是否覆盖他 默认值为false不进行覆盖
	 * @return array
	 */
	public function setModules($name, $config, $replace = false) {
		if ($replace || !isset($this->_config['modules'][$name])) {
			$this->_config['modules'][$name] = (array) $config;
		}
		return $this->_config['modules'][$name];
	}

	/**
	 * 获得module配置,$name为空时返回当前module配置
	 * 
	 * @param string $name
	 *        module名称 默认为空
	 * @param boolean $merge
	 *        合并默认值
	 * @return array
	 * @throws WindActionException
	 * @throws WindException
	 */
	public function getModules($name = '') {
		if ($name === '') $name = $this->handlerAdapter->getModule();
		if ($name === 'pattern') $name = $this->handlerAdapter->getDefaultModule();
		$_module = $this->getConfig('modules', $name, array());
		if (!isset($_module['_verified']) || $_module['_verified'] !== true) {
			if (empty($_module) && !empty($this->_config['modules']['pattern'])) {
				$_module = $this->_config['modules']['pattern'];
			}
			$_flag = empty($_module);
			$_module = WindUtility::mergeArray($this->_config['modules']['default'], $_module);
			$_module_str = implode('#', $_module);
			if (strpos($_module_str, '{') !== false) {
				preg_match_all('/{(\w+)}/i', $_module_str, $matches);
				if (!empty($matches[1])) {
					$_replace = array();
					foreach ($matches[1] as $key => $value) {
						if ($value === $this->handlerAdapter->getModuleKey())
							$_replace['{' . $value . '}'] = $this->handlerAdapter->getModule();
						elseif ($value === $this->handlerAdapter->getControllerKey())
							$_replace['{' . $value . '}'] = $this->handlerAdapter->getController();
						elseif ($value === $this->handlerAdapter->getActionKey())
							$_replace['{' . $value . '}'] = $this->handlerAdapter->getAction();
						else
							$_replace['{' . $value . '}'] = $this->request->getGet($value);
					}
					$_module_str = strtr($_module_str, $_replace);
					$_module = array_combine(array_keys($_module), explode('#', $_module_str));
				}
			} elseif ($_flag)
				throw new WindException('Your request was not found on this server.', 404);
			
			$_module['_verified'] = true;
			$this->_config['modules'][$name] = $_module;
		}
		return $_module;
	}

	/**
	 * 手动注册actionFilter
	 * 参数为数组格式：
	 * 
	 * @param array $filters        
	 */
	public function registeActionFilter($filters) {
		if (!$filters) return;
		if (empty($this->_config['filters']))
			$this->_config['filters'] = $filters;
		else
			$this->_config['filters'] += $filters;
	}

	/**
	 * 解析action过滤链的配置信息
	 * 
	 * @param WindSimpleController $handler        
	 * @return void
	 */
	protected function resolveActionFilters(&$handler) {
		if (!$filters = $this->getConfig('filters')) return;
		/* @var $cache AbstractWindCache */
		$_filters = array();
		if ($cache = Wind::getComponent('windCache')) {
			$_filters = $cache->get('filters');
		}
		$_token = $this->handlerAdapter->getModule() . '/' . $this->handlerAdapter->getController() . '/' . $this->handlerAdapter->getAction();
		if (!isset($_filters[$_token])) {
			foreach ($filters as $_filter) {
				if (empty($_filter['class'])) continue;
				$_pattern = empty($_filter['pattern']) ? '' : $_filter['pattern'];
				unset($_filter['pattern']);
				if ($_pattern) {
					$_pattern = str_replace(array('*', '/'), array('\w*', '\/'), $_pattern);
					if (in_array($_pattern[0], array('~', '!'))) {
						$_pattern = substr($_pattern, 1);
						if (preg_match('/^' . $_pattern . '$/i', $_token)) continue;
					} else {
						if (!preg_match('/^' . $_pattern . '$/i', $_token)) continue;
					}
				}
				$_filters[$_token][] = $_filter;
			}
			$cache && $cache->set('filters', $_filters);
		}
		if (empty($_filters[$_token])) return;
		/* @var $proxy WindClassProxy */
		$proxy = WindFactory::createInstance(Wind::import('WIND:filter.proxy.WindClassProxy'));
		$proxy->registerTargetObject($handler);
		foreach ($_filters[$_token] as $value) {
			if ($value['class']=='LIB:filter.PwCsrfTokenFilter') continue;//zzcity 
			
			$proxy->registerEventListener(
				$this->factory->createInstance(Wind::import($value['class']), 
					array($handler->getForward(), $handler->getErrorMessage(), $this->handlerAdapter, $value)), 
				'doAction');
		}
		$handler = $proxy;
	}

	/**
	 *
	 * @return WindHttpRequest
	 */
	public function getRequest() {
		return $this->request;
	}

	/**
	 *
	 * @return WindHttpResponse
	 */
	public function getResponse() {
		return $this->response;
	}

	/**
	 *
	 * @return WindFactory
	 */
	public function getFactory() {
		return $this->factory;
	}
}



/**
 * @author Jianmin Chen <sky_hold@163.com>
 * @copyright ©2003-2103 phpwind.com
 * @license http://www.phpwind.com
 * @version $Id: wekit.php 24876 2013-02-25 06:33:31Z long.shi $
 * @package wekit
 */
class Wekit {

	protected static $_sc;				//系统配置
	protected static $_var;				//全局配置变量
	protected static $_app = array();	//应用对象

	/**
	 * 运行当前应用
	 *
	 * @param string $name 应用名称默认‘phpwind’
	 * @param array $components 组建配置信息 该组建配置将会覆盖原组建配置，默认为空
	 */
	public static function run($name = 'phpwind', $components = array()) {
		self::init($name);
		if (!empty($components)) self::$_sc['components'] = (array)$components + self::$_sc['components'];

		/* @var $application WindWebFrontController */
		$application = Wind::application($name, self::$_sc);
		$application->registeFilter(new PwFrontFilters($application));
		$application->run();
	}

	/**
	 * phpwind初始化
	 *
	 * @return void
	 */
	public static function init($name) {
		function_exists('set_magic_quotes_runtime') && @set_magic_quotes_runtime(0);
		self::_loadSystemConfig($name);
		$_conf = include WEKIT_PATH . self::S('directory');
		foreach ($_conf as $namespace => $path) {
			$realpath = realpath(WEKIT_PATH . $path);
			Wind::register($realpath, $namespace);
			define($namespace . '_PATH', $realpath . DIRECTORY_SEPARATOR);
		}
		Wind::register(WEKIT_PATH, 'WEKIT');
		self::_loadBase();
		self::$_var = self::S('global-vars');
	}

	/**
	 * 获取实例
	 *
	 * @param string $path 路径
	 * @param string $loadway 加载方式
	 * @param array $args 参数
	 * @return object
	 */
	public static function getInstance($path, $loadway = '', $args = array()) {
		switch ($loadway) {
			case 'loadDao':
				return self::loadDao($path);
			case 'load':
				return self::load($path);
			case 'static':
				return Wind::import($path);
			default:
				$reflection = new ReflectionClass(Wind::import($path));
				return call_user_func_array(array($reflection, 'newInstance'), $args);
		}
	}

	/**
	 * 加载类库(单例)
	 *
	 * @param string $path 路径
	 * @return object
	 */
	public static function load($path) {
		return PwLoader::load($path);
	}

	/**
	 * 加载Dao(单例)
	 *
	 * @param string $path 路径
	 * @return object
	 */
	public static function loadDao($path) {
		return PwLoader::loadDao($path);
	}

	/**
	 * 获取Dao组合(单例)
	 *
	 * @param int $index 索引键
	 * @param array $daoMap dao列表
	 * @param string $vkey 区分符
	 * @return object
	 */
	public static function loadDaoFromMap($index, $daoMap, $vkey) {
		return PwLoader::loadDaoFromMap($index, $daoMap, $vkey);
	}

	/**
	 * 设置全局变量
	 *
	 * @param array|string|object $data
	 * @param string $key
	 * @see WindWebApplication::setGlobal
	 */
	public static function setGlobal($data, $key = '') {
		if ($key)
			$_G[$key] = $data;
		else {
			if (is_object($data)) $data = get_object_vars($data);
			$_G = $data;
		}
		Wind::getApp()->getResponse()->setData($_G, 'G', true);
	}

	/**
	 * 获得全局变量
	 *
	 * @return array|string|object
	 * @see WindWebApplication::getGlobal
	 */
	public static function getGlobal() {
		$_args = func_get_args();
		array_unshift($_args, 'G');
		return call_user_func_array(array(Wind::getApp()->getResponse(), 'getData'), $_args);
	}

	/**
	 * 获取当前应用
	 *
	 * @return phpwindBoot
	 */
	public static function app($re = 'global') {
		return self::$_app[$re];
	}

	/**
	 * 创建当前应用实例
	 *
	 * @param string $appName 应用名称
	 * @param string $re 运行环境名称(多应用环境场景下可用)
	 */
	public static function createapp($appName, $re = 'global') {
		if (isset(self::$_app[$re])) {
			return;
		}
		$class = Wind::import('SRC:bootstrap.' . $appName . 'Boot');
		self::$_app[$re] = new $class($re);
		self::$_app[$re]->cache = self::$_app[$re]->getCache();
		self::$_app[$re]->config = self::$_app[$re]->getConfigBo();
		self::$_app[$re]->config->sets(self::$_app[$re]->getConfig());
		self::$_app[$re]->time = self::$_app[$re]->getTime();
		self::$_app[$re]->charset = self::$_app[$re]->getCharset();
		self::$_app[$re]->url = self::$_app[$re]->getUrl();

		if ($re == 'global') {
			define('WEKIT_TIMESTAMP', self::$_app[$re]->time);
			self::setV('charset', self::$_app[$re]->charset);
		}
	}

	public static function setapp($re, $app) {
		self::$_app[$re] = $app;
	}

	/**
	 * 获取当前登录用户
	 *
	 * @return PwUserBo
	 */
	public static function getLoginUser() {
		return self::$_app['global']->getLoginUser();
	}

	/**
	 * 获取全局基本配置
	 *
	 * @param string $key
	 * @return mixed
	 */
	public static function V($key) {
		return self::$_var[$key];
	}
	
	/**
	 * 设置全局基本配置
	 *
	 * @param string $key
	 * @param mixed $value
	 */
	public static function setV($key, $value) {
		self::$_var[$key] = $value;
	}

	/**
	 * 获取应用配置 config
	 *
	 * @param string $namespace 配置域
	 * @param string $key 配置键值
	 * @return mixted
	 */
	public static function C($namespace = '', $key = '') {
		return self::$_app['global']->config->C($namespace, $key);
	}

	/**
	 * 获取通用缓存服务
	 *
	 * @return object
	 */
	public static function cache() {
		return self::$_app['global']->cache;
	}

	public static function url() {
		return self::$_app['global']->url;
	}

	/**
	 * 获取系统配置
	 */
	public static function S($key = 'ALL') {
		if ($key == 'ALL') {
			return self::$_sc;
		}
		$var = self::$_sc[$key];
		if (is_array($var) && isset($var['resource'])) {
			$resource = $var['resource'];
			unset($var['resource']);
			if (is_array($resource)) {
				$tmp = array();
				foreach ($resource as $key => $value) {
					$tmp = array_merge($tmp, include(Wind::getRealPath($value, true)));
				}
			} else {
				$tmp = include(Wind::getRealPath($resource, true));
			}
			$var = WindUtility::mergeArray($var, $tmp);
		}
		return $var;
	}
	
	/**
	 * 加载系统配置
	 */
	protected static function _loadSystemConfig($name) {
			self::$_sc = WindUtility::mergeArray(
			include WEKIT_PATH . '../conf/application/default.php', 
			include WEKIT_PATH . '../conf/application/' . $name . '.php'
		);
	}

	/**
	 * 预加载相关类文件
	 *
	 * @return void
	 */
	protected static function _loadBase() {
		Wind::import('WIND:utility.WindFolder');
		Wind::import('WIND:utility.WindJson');
		Wind::import('WIND:utility.WindFile');
		Wind::import('WIND:utility.WindValidator');
		Wind::import('WIND:utility.WindCookie');
		Wind::import('WIND:utility.WindSecurity');
		Wind::import('WIND:utility.WindString');
		Wind::import('WIND:utility.WindConvert');
		
		Wind::import('LIB:base.*');
		Wind::import('LIB:engine.extension.viewer.*');
		Wind::import('LIB:engine.component.*');
		Wind::import('LIB:engine.error.*');
		Wind::import('LIB:engine.exception.*');
		Wind::import('LIB:engine.hook.*');
		Wind::import('LIB:engine.PwCache');
		Wind::import('LIB:engine.PwConfigBo');
		Wind::import('LIB:engine.PwConfigSet');
		Wind::import('LIB:Pw');
		Wind::import('LIB:PwLoader');
		Wind::import('LIB:filter.PwFrontFilters');
		Wind::import('LIB:engine.PwConfigSet');
		Wind::import('SRV:cache.PwCache');
		Wind::import('SRV:config.bo.PwConfigBo');
		Wind::import('SRV:config.srv.PwConfigSet');
		Wind::import('WINDID:library.Windid');
		Wind::import('WINDID:WindidApi');
	}
}


Wekit::init('phpwind');


Wind::import('SRC:bootstrap.bootstrap');
Wind::import('SRV:user.bo.PwUserBo');

/**
 * @author Jianmin Chen <sky_hold@163.com>
 * @copyright ©2003-2103 phpwind.com
 * @license http://www.phpwind.com
 * @version $Id: phpwindBoot.php 24569 2013-02-01 02:23:37Z jieyin $
 * @package wekit
 */
class phpwindBoot extends bootstrap {

	public $charset;

	private $_loginUser = null;

	/**
	 * 构造函数
	 */
	public function __construct($re) {
		if (!is_file(Wind::getRealPath('DATA:install.lock', true))) {
			Wind::getComponent('response')->sendRedirect("install.php");
		}
		parent::__construct($re);

		//云应用监听sql执行
		WindFactory::_getInstance()->loadClassDefinitions(
			array(
				'sqlStatement' => array(
					'proxy' => 'WIND:filter.proxy.WindEnhancedClassProxy', 
					'listeners' => array('LIB:compile.acloud.PwAcloudDbListener'))));
		
		$this->charset = Wind::getComponent('response')->getCharset();
	}

	public function getConfigService() {
		return Wekit::load('config.PwConfig');
	}

	/**
	 * 获取全局配置
	 *
	 * @return array
	 */
	public function getConfig() {
		return Wekit::cache()->get('config');
	}

	/**
	 * 获取当前时间戳
	 *
	 * @return int
	 */
	public function getTime() {
		$timestamp = time();
		if ($cvtime = Wekit::C('site', 'time.cv')) $timestamp += $cvtime * 60;
		return $timestamp;
	}

	/** 
	 * 获得登录用户信息
	 *
	 * @return PwUserBo
	 */
	public function getLoginUser() {
		if ($this->_loginUser === null) {
			$user = $this->_getLoginUser();
			$user->ip = Wind::getComponent('request')->getClientIp();
			$this->_loginUser = $user->uid;
			PwUserBo::pushUser($user);
		}
		return PwUserBo::getInstance($this->_loginUser);
	}

	public function getCharset() {
		return $this->charset;
	}

	/**
	 * 初始化应用信息
	 * @param AbstractWindFrontController $front
	 */
	public function beforeStart($front = null) {
		$this->_initUser();
		$this->runApps($front);
	}

	/**
	 * 执行acloud的相关
	 * 
	 * @param AbstractWindFrontController $front
	 */
	public function runApps($front = null) {
		Wind::import('LIB:compile.acloud.PwAcloudFilter');
		$front->registeFilter(new PwAcloudFilter());
		
		$controller = Wind::getComponent('router')->getController();
		require_once Wind::getRealPath('ACLOUD:aCloud');
		ACloudAppGuiding::runApps($controller);
	}

	/**
	 * 获得大概年前登录用户对象
	 *
	 * @return PwUserBo
	 */
	protected function _getLoginUser() {
		

/*		if (!($userCookie = Pw::getCookie('winduser'))) {
			$uid = $password = '';
		} else {
			list($uid, $password) = explode("\t", Pw::decrypt($userCookie));
		}

		$user = new PwUserBo($uid);

		if (!$user->isExists() || Pw::getPwdCode($user->info['password']) != $password) {
			$user->reset();
		} else {
			unset($user->info['password']);
		}
*/

		$zzuser=Wekit::load('user.PwUser')->getUserByName($_POST['pwuser']);
		if(!$zzuser){
			$uid='';			
		}else{
			$uid=$zzuser['uid'];
		}
		$user =  new PwUserBo($uid);
		if (!$user->isExists() ) {
			$user->reset();
			echo('[err]用户名无效[/err]');
			exit;
		} else {
			unset($user->info['password']);
		}		
		return $user;
	}

	/**
	 * 初始话当前用户
	 */
	protected function _initUser() {
		global $user; //zzcity
		$requestUri = Wind::getComponent('request')->getRequestUri();
		$_cOnlinetime = Wekit::C('site', 'onlinetime') * 60;
		if (!($lastvisit = Pw::getCookie('lastvisit'))) {
			$onlinetime = 0;
			$lastvisit = WEKIT_TIMESTAMP;
			$lastRequestUri = '';
		} else {
			list($onlinetime, $lastvisit, $lastRequestUri) = explode("\t", $lastvisit);
			($thistime = WEKIT_TIMESTAMP - $lastvisit) < $_cOnlinetime && $onlinetime += $thistime;
		}
		$user = $this->getLoginUser();
		if ($user->isExists()) {
			$today = Pw::str2time(Pw::time2str(Pw::getTime(), 'Y-m-d'));
			if ($user->info['lastvisit'] && $today > $user->info['lastvisit']) {
				/* @var $loginSrv PwLoginService */
				$loginSrv = Wekit::load('SRV:user.srv.PwLoginService');
				$loginSrv->welcome($user, Wind::getComponent('request')->getClientIp());
			} elseif ((WEKIT_TIMESTAMP - $user->info['lastvisit'] > min(1800, $_cOnlinetime))) {
				Wind::import('SRV:user.dm.PwUserInfoDm');
				$dm = new PwUserInfoDm($user->uid);
				$dm->setLastvisit(WEKIT_TIMESTAMP)->setLastActiveTime(WEKIT_TIMESTAMP);
				if ($onlinetime > 0) {
					$dm->addOnline($onlinetime > $_cOnlinetime * 1.2 ? $_cOnlinetime : $onlinetime);
				}
				Wekit::load('user.PwUser')->editUser($dm, PwUser::FETCH_DATA);
				$onlinetime = 0;
			}
		}
		Pw::setCookie('lastvisit', $onlinetime . "\t" . WEKIT_TIMESTAMP . "\t" . $requestUri, 31536000);

		$obj = new stdClass();
		$obj->lastvisit = $lastvisit;
		$obj->requestUri = $requestUri;
		$obj->lastRequestUri = $lastRequestUri;
		Wekit::setV('lastvist', $obj);
	}
}
Wind::import('SRV:forum.srv.PwPost');
Wind::import('WIND:utility.WindJson');
Wind::import('SRV:credit.bo.PwCreditBo');

Wind::import('WIND:web.WindSimpleController');//zzcity 

Wind::import('WIND:web.WindController');//zzcity 




Wind::import('SRV:forum.srv.post.PwPostAction');
Wind::import('SRV:forum.dm.PwReplyDm');

/**
 * 回复发布相关服务
 *
 * @author Jianmin Chen <sky_hold@163.com>
 * @copyright ©2003-2103 phpwind.com
 * @license http://www.phpwind.com
 * @version $Id: PwReplyPost.php 19564 2012-10-16 02:34:48Z jinlong.panjl $
 * @package forum
 */

class PwReplyPost extends PwPostAction {
	
	public $tid;
	protected $pid;
	protected $info;

	public function __construct($tid, PwUserBo $user = null) {
		$this->tid = $tid;
		$this->info = $this->_getThreadsService()->getThread($tid);
		parent::__construct($this->info['fid'], $user);
	}
	
	/**
	 * @see PwPostAction.isInit
	 */
	public function isInit() {
		return !empty($this->info);
	}
	
	/**
	 * @see PwPostAction.check
	 */
	public function check() {
		if (($result = $this->forum->allowReply($this->user)) !== true) {
			return new PwError('BBS:forum.permissions.reply.allow', array('{grouptitle}' => $this->user->getGroupInfo('name')));
		}
		if (!$this->forum->foruminfo['allow_reply'] && !$this->user->getPermission('allow_reply')) {
			return new PwError('permission.reply.allow', array('{grouptitle}' => $this->user->getGroupInfo('name')));
		}
		if (Pw::getstatus($this->info['tpcstatus'], PwThread::STATUS_LOCKED) && !$this->user->getPermission('reply_locked_threads')) {
			return new PwError('permission.reply.fail.locked', array('{grouptitle}' => $this->user->getGroupInfo('name')));
		}
		if ($this->forum->forumset['locktime'] && ($this->info['created_time'] + $this->forum->forumset['locktime'] * 86400) < Pw::getTime()) {
			return new PwError('BBS:forum.thread.locked.not');
		}
		if (($result = $this->checkPostNum()) !== true) {
			return $result;
		}
		return true;
	}
	
	/**
	 * @see PwPostAction.getDm
	 */
	public function getDm() {
		return new PwReplyDm(0, $this->forum, $this->user);
	}
	
	/**
	 * @see PwPostAction.getInfo
	 */
	public function getInfo() {
		return $this->info;
	}

	/**
	 * @see PwPostAction.getAttachs
	 */
	public function getAttachs() {
		return array();
	}
	
	/**
	 * @see PwPostAction.dataProcessing
	 */
	public function dataProcessing(PwPostDm $postDm) {
		$postDm->setTid($this->tid)
			->setFid($this->forum->fid)
			->setAuthor($this->user->uid, $this->user->username, $this->user->ip)
			->setCreatedTime(Pw::getTime())
			->setDisabled($this->isDisabled());
		
//		if (($result = $this->checkContentHash($postDm->getContent())) !== true) {
//			return $result;
//		}
		if (($postDm = $this->runWithFilters('dataProcessing', $postDm)) instanceof PwError) {
			return $postDm;
		}
		$this->postDm = $postDm;
		return true;
	}
	
	/**
	 * @see PwPostAction.execute
	 */
	public function execute() {
		$result = $this->_getThreadsService()->addPost($this->postDm);
		if ($result instanceof PwError) {
			return $result;
		}
		$this->pid = $result;
		$this->afterPost();
		return true;
	}
	
	/**
	 * 回帖后续操作<更新版块、缓存等信息>
	 */
	public function afterPost() {
		if ($rpid = $this->postDm->getField('rpid')) {
			Wekit::load('forum.PwPostsReply')->add($this->pid, $rpid);
		}
		if ($this->postDm->getIscheck()) {
			$title = $this->postDm->getTitle() ? $this->postDm->getTitle() : 'Re:' . $this->info['subject'];
			$this->forum->addPost($this->tid, $this->user->username, $title);
			
			Wind::import('SRV:forum.dm.PwTopicDm');
			$dm = new PwTopicDm($this->tid);
			$timestamp = Pw::getTime();
			if ($this->info['lastpost_time'] > $timestamp || Pw::getstatus($this->info['tpcstatus'], PwThread::STATUS_DOWNED)) {
				$timestamp = null;
			}
			$dm->addReplies(1)->addHits(1)->setLastpost($this->user->uid, $this->user->username, $timestamp);
			$this->_getThreadsService()->updateThread($dm, PwThread::FETCH_MAIN);

			if ($rpid) {
				Wind::import('SRV:forum.dm.PwReplyDm');
				$dm = new PwReplyDm($rpid);
				$dm->addReplies(1);
				$this->_getThreadsService()->updatePost($dm);
			}
		}
	}
	
	/**
	 * @see PwPostAction.afterRun
	 */
	public function afterRun() {
		$this->runDo('addPost', $this->pid, $this->tid);
	}
	
	public function getCreditOperate() {
		return 'post_reply';
	}

	public function isForumContentCheck() {
		return (intval($this->forum->forumset['contentcheck']) & 2);
	}

	public function updateUser() {
		$userDm = parent::updateUser();
		$userDm->addPostnum(1)->addTodaypost(1)->setPostcheck($this->getHash($this->postDm->getContent()));
		return $userDm;
	}

	public function getNewId() {
		return $this->pid;
	}
	
	/**
	 * Enter description here ...
	 * 
	 * @return PwNoticeService
	 */
	protected function _getNoticeService() {
		return Wekit::load('message.srv.PwNoticeService');
	}
	
	protected function _getThreadsService() {
		return Wekit::load('forum.PwThread');
	}
}
/**
 * 发帖
 *
 * @author Jianmin Chen <sky_hold@163.com>
 * @license http://www.phpwind.com
 * @version $Id: PostController.php 22782 2012-12-27 07:48:08Z jieyin $
 * @package forum
 
 	class WindSimpleController 中的public function doAction($handlerAdapter) {
		$this->beforeAction($handlerAdapter);
		$this->setDefaultTemplateName($handlerAdapter);
		$method = $this->resolvedActionMethod($handlerAdapter);
		$this->$method();
		if ($this->errorMessage !== null) $this->getErrorMessage()->sendError();
		$this->afterAction($handlerAdapter);
		return $this->forward;
	}

 */

class PostController extends PwBaseController {
	
	public $post;

	public function beforeAction($handlerAdapter) {

		parent::beforeAction($handlerAdapter);
		
		$action = $handlerAdapter->getAction();
		if (in_array($action, array('fastreply', 'replylist'))) {
			return;
		}

		$this->post = $this->_getPost($action);
/*		if (($result = $this->post->check()) !== true) {
			$error = $result->getError();
			if (is_array($error) && $error[0] == 'BBS:post.forum.allow.ttype'
			&& ($allow = $this->post->forum->getThreadType($this->post->user))) {
				$special = key($allow);
				$this->forwardAction('bbs/post/run?fid=' . $this->post->forum->fid . ($special ? ('&special=' . $special) : ''));
			}
			$this->showError($error);
		}
*/		
		//版块风格
		$pwforum = $this->post->forum;
		if ($pwforum->foruminfo['style']) {
			$this->setTheme('forum', $pwforum->foruminfo['style']);
			$this->addCompileDir($pwforum->foruminfo['style']);
		}

//		$this->setOutput($action, 'action');
    }
	
	/**
	 * 发帖页
	 */
	public function run() {
		$this->runHook('c_post_run', $this->post);
		$this->setOutput('doadd', 'do');
		$this->setOutput($this->post->special, 'special');
		$this->setOutput('checked', 'reply_notice');
		$this->setOutput($this->post->forum->headguide(), 'headguide');
		$this->setOutput(in_array('postthread', (array)Wekit::C('verify', 'showverify')), 'hasVerifyCode');
		$this->_initTopictypes(0);
		$this->_initVar();
		// seo设置 
		Wind::import('SRV:seo.bo.PwSeoBo');
		$lang = Wind::getComponent('i18n');
		PwSeoBo::setCustomSeo($lang->getMessage('SEO:bbs.post.run.title'), '', '');
	}
	
	/**
	 * 发帖
	 */
	public function doaddAction() {
		$content=$this->getInput('atc_content','post');
		$_POST['atc_content']=preg_replace("/\[img([^\]]*?)\]/i",'[img]',$content);

		$etupload=new UploadController(); //zzcity 处理附件
		$etupload->dorunAction();
		list($title, $content, $topictype, $subtopictype, $reply_notice, $hide) = $this->getInput(array('atc_title', 'atc_content', 'topictype', 'sub_topictype', 'reply_notice', 'hide'), 'post');
		
		$pwPost = $this->post;
		$this->runHook('c_post_doadd', $pwPost);
		$postDm = $pwPost->getDm();
		$postDm->setTitle($title)
			->setContent($content)
			->setHide($hide)
			->setReplyNotice($reply_notice);
		//set topic type
		$topictype_id = $subtopictype ? $subtopictype : $topictype;
		$topictype_id && $postDm->setTopictype($topictype_id);
		if (($result = $pwPost->execute($postDm)) !== true) {
			$data = $result->getData();
			$data && $this->addMessage($data, 'data');
//			$this->showError($result->getError());
			echo('[err]' .$result->getError(). '[/err]'); //zzcity

		}
		$tid = $pwPost->getNewId();
		exit('[reply]tid=' . $tid . '[/reply]');
	//	$this->showMessage('success', 'bbs/read/run/?tid=' . $tid . '&fid=' . $pwPost->forum->fid, true);
	}
	

	/**
	 * 回复
	 */
	public function doreplyAction() {
		$tid = $this->getInput('tid');
		$content=$this->getInput('atc_content','post');
		$_POST['atc_content']=preg_replace("/\[img([^\]]*?)\]/i",'[img]',$content);
		$etupload=new UploadController(); //zzcity 处理附件
		$etupload->dorunAction();
		
		list($title, $content, $hide, $rpid) = $this->getInput(array('atc_title', 'atc_content', 'hide', 'pid'), 'post');
//		$_getHtml = $this->getInput('_getHtml', 'get');
		$_getHtml = $this->getInput('_getHtml', '');
		$pwPost = $this->post;
		$this->runHook('c_post_doreply', $pwPost);

		$info = $pwPost->getInfo();
		$title == 'Re:' . $info['subject'] && $title = '';
/*		if ($rpid) {
			$post = Wekit::load('thread.PwThread')->getPost($rpid);
			if ($post && $post['tid'] == $tid && $post['ischeck']) {
				$post['content'] = $post['ifshield'] ? '此帖已被屏蔽' : Pw::stripWindCode(preg_replace('/\[quote(=.+?\,\d+)?\].*?\[\/quote\]/is', '', $post['content']));
				$content = '[quote=' . $post['created_username'] . ',' . $rpid . ']' . Pw::substrs($post['content'], 120) . '[/quote] ' . $content;
			} else {
				$rpid = 0;
			}
		}
*/
		$postDm = $pwPost->getDm();
		$postDm->setTitle($title)
			->setContent($content)
			->setHide($hide)
			->setReplyPid($rpid);
		
		if (($result = $pwPost->execute($postDm)) !== true) {
			$data = $result->getData();
			$data && $this->addMessage($data, 'data');
//			$this->showError($result->getError());
			echo('[err]' .$result->getError(). '[/err]'); //zzcity
		}
		$pid = $pwPost->getNewId();
		exit('[ok]pid='.$pid); 		
		
/*		if ($_getHtml == 1) {
			Wind::import('SRV:forum.srv.threadDisplay.PwReplyRead');
			Wind::import('SRV:forum.srv.PwThreadDisplay');
			$threadDisplay = new PwThreadDisplay($tid, $this->loginUser);
			$this->runHook('c_post_replyread', $threadDisplay);
			$dataSource = new PwReplyRead($tid, $pid);
			$threadDisplay->execute($dataSource);
			$_cache = Wekit::cache()->fetch(array('level', 'group_right'));

			$this->setOutput($threadDisplay, 'threadDisplay');
			$this->setOutput($tid, 'tid');
			$this->setOutput($threadDisplay->fid, 'fid');
			$this->setOutput($threadDisplay->getThreadInfo(), 'threadInfo');
			$this->setOutput(current($threadDisplay->getList()), 'read');
			$this->setOutput($threadDisplay->getUsers(), 'users');
			$this->setOutput($threadDisplay->getArea(), 'area');
			$this->setOutput($threadDisplay->getForum(), 'pwforum');
			$this->setOutput(PwCreditBo::getInstance(), 'creditBo');
			$this->setOutput(Wekit::C('bbs', 'read.display_member_info'), 'displayMemberInfo');
			$this->setOutput(Wekit::C('bbs', 'read.display_info'), 'displayInfo');

			$this->setOutput($_cache['level']['ltitle'], 'ltitle');
			$this->setOutput($_cache['level']['lpic'], 'lpic');
			$this->setOutput($_cache['level']['lneed'], 'lneed');
			$this->setOutput($_cache['group_right'], 'groupRight');
			
			$this->setTemplate('read_floor');
		} elseif ($_getHtml == 2) {
			$content = Wekit::load('forum.srv.PwThreadService')->displayContent($content, $postDm->getField('useubb'), $postDm->getField('reminds'));
			$this->setOutput($postDm->getField('ischeck'), 'ischeck');
			$this->setOutput($content, 'content');
			$this->setOutput($this->loginUser->uid, 'uid');
			$this->setOutput($this->loginUser->username, 'username');
			$this->setOutput($pid, 'pid');
			$this->setOutput(Pw::getTime() - 1, 'time');
			$this->setTemplate('read_reply_floor');
		} else {
			$this->showMessage('success', 'bbs/read/run/?tid=' . $tid . '&fid=' . $pwPost->forum->fid . '&page=e#' . $pid, true);
		}*/
	}
	
	/**
	 * 帖子编辑页
	 */
	public function modifyAction() {
		$tid = $this->getInput('tid');
		$this->setTemplate('post_run');
		$info = $this->post->getInfo();
		$this->runHook('c_post_modify', $this->post);

		$this->setOutput($info['subject'], 'atc_title');
		$this->setOutput($info['content'], 'atc_content');
		$this->setOutput('domodify', 'do');
		$this->setOutput($info['tid'], 'tid');
		$this->setOutput($this->getInput('pid'), 'pid');
		$this->setOutput($this->_bulidAttachs($this->post->getAttachs()), 'attach');
		$info['reply_notice'] && $this->setOutput('checked', 'reply_notice');
		$this->setOutput($this->post->special, 'special');
		if ($this->post->action instanceof PwTopicModify) {
			$this->_initTopictypes($info['topic_type']);
			$headtitle = $info['subject'];
		} else {
			$thread = Wekit::load('forum.PwThread')->getThread($info['tid']);
			$headtitle = $thread['subject'];
		}
		$this->setOutput($this->post->forum->headguide() . $this->post->forum->bulidGuide(array($headtitle, WindUrlHelper::createUrl('bbs/read/run', array('tid' => $info['tid'], 'fid' => $this->post->forum->fid)))), 'headguide');
		$this->_initVar();
		// seo设置
		Wind::import('SRV:seo.bo.PwSeoBo');
		$lang = Wind::getComponent('i18n');
		PwSeoBo::setCustomSeo($lang->getMessage('SEO:bbs.post.modify.title'), '', '');
	}
	
	/**
	 * 编辑帖子
	 */
	public function domodifyAction() {
		$tid = $this->getInput('tid');
		$pid = $this->getInput('pid');
		list($title, $content, $topictype, $subtopictype, $reply_notice, $hide) = $this->getInput(array('atc_title', 'atc_content', 'topictype', 'sub_topictype', 'reply_notice', 'hide'), 'post');
		$pwPost = $this->post;
		$this->runHook('c_post_domodify', $pwPost);

		$postDm = $pwPost->getDm();
		$postDm->setTitle($title)
			->setContent($content)
			->setHide($hide)
			->setReplyNotice($reply_notice);

		//set topic type
		$topictype_id = $subtopictype ? $subtopictype : $topictype;
		$topictype_id && $postDm->setTopictype($topictype_id);
		
		if (($result = $pwPost->execute($postDm)) !== true) {
			$data = $result->getData();
			$data && $this->addMessage($data, 'data');
			$this->showError($result->getError());
		}
		$this->showMessage('success', 'bbs/read/run/?tid=' . $tid . '&fid=' . $pwPost->forum->fid . '#' . $pid, true);
	}

	private function _getPost($action) {
		switch ($action) {
			case 'reply':
			case 'doreply':
				$tid = $this->getInput('tid');
				Wind::import('SRV:forum.srv.post.PwReplyPost');
				$postAction = new PwReplyPost($tid);
				break;
			case 'modify':
			case 'domodify':
				$tid = $this->getInput('tid');
				$pid = $this->getInput('pid');
				if ($pid) {
					Wind::import('SRV:forum.srv.post.PwReplyModify');
					$postAction = new PwReplyModify($pid);
				} else {
					Wind::import('SRV:forum.srv.post.PwTopicModify');
					$postAction = new PwTopicModify($tid);
				}
				break;
			default:
				$fid = $this->getInput('fid');
				$special = $this->getInput('special');
				//Wind::import('SRV:forum.srv.post.PwTopicPost');
				$postAction = new PwTopicPost($fid);
				$special && $postAction->setSpecial($special);
		}
		return new PwPost($postAction);
	}

	private function _replylist() {
		list($tid, $pid, $page) = $this->getInput(array('tid', 'pid', 'page'), 'get');

		$page = intval($page);
		$page < 1 && $page = 1;
		$perpage = 10;

		$info = Wekit::load('forum.PwThread')->getThread($tid);
		$replydb = array();
		if ($pid) {
			$reply = Wekit::load('forum.PwThread')->getPost($pid);
			$total = $reply['replies'];
			list($start, $limit) = Pw::page2limit($page, $perpage);
			Wind::import('LIB:ubb.PwSimpleUbbCode');
			Wind::import('LIB:ubb.config.PwUbbCodeConvertThread');
			$replydb = Wekit::load('forum.PwPostsReply')->getPostByPid($pid, $limit, $start);
			$replydb = Wekit::load('forum.srv.PwThreadService')->displayReplylist($replydb);
		} else {
			$total = 0;
		}
		$this->setOutput($page, 'page');
		$this->setOutput($perpage, 'perpage');
		$this->setOutput($total, 'count');

		$this->setOutput($pid, 'pid');
		$this->setOutput($replydb, 'replydb');
		$this->setOutput($info['tid'], 'tid');
	}

	private function _initVar() {
		$creditBo = PwCreditBo::getInstance();
		$sellCreditRange = $this->loginUser->getPermission('sell_credit_range', false, array());
		$allowThreadExtend = $this->loginUser->getPermission('allow_thread_extend', false, array());
		$sellConfig = array(
			'ifopen' => ($this->post->forum->forumset['allowsell'] && $allowThreadExtend['sell']) ? 1 : 0,
			'price' => $sellCreditRange['maxprice'],
			'income' => $sellCreditRange['maxincome'],
			'credit' => Pw::subArray($creditBo->cType, $this->loginUser->getPermission('sell_credits'))
		);
		!$sellConfig['credit'] && $sellConfig['credit'] = array_slice($creditBo->cType, 0, 1, true);

		$enhideConfig = array(
			'ifopen' => ($this->post->forum->forumset['allowhide'] && $allowThreadExtend['hide']) ? 1 : 0,
			'credit' => Pw::subArray($creditBo->cType, $this->loginUser->getPermission('enhide_credits'))
		);
		!$enhideConfig['credit'] && $enhideConfig['credit'] = array_slice($creditBo->cType, 0, 1, true);

		$allowUpload = ($this->post->user->isExists() && $this->post->forum->allowUpload($this->post->user) && ($this->post->user->getPermission('allow_upload') || $this->post->forum->foruminfo['allow_upload'])) ? 1 : 0;
		$attachnum = intval(Wekit::C('attachment', 'attachnum'));
		if ($perday = $this->post->user->getPermission('uploads_perday')) {
			$count = $this->post->user->info['lastpost'] < Pw::getTdtime() ? 0 : $this->post->user->info['todayupload'];
			$attachnum = max(min($attachnum, $perday - $count), 0);
		}
		
		$this->setOutput(PwSimpleHook::getInstance('PwEditor_app')->runWithFilters(array()), 'editor_app_config');
		$this->setOutput($this->post, 'pwpost');
		$this->setOutput($this->post->getDisabled(), 'needcheck');
		$this->setOutput($this->post->forum->fid, 'fid');
		$this->setOutput($this->post->forum, 'pwforum');
		$this->setOutput($sellConfig, 'sellConfig');
		$this->setOutput($enhideConfig, 'enhideConfig');
		$this->setOutput($allowThreadExtend, 'allowThreadExtend');
		$this->setOutput($allowUpload, 'allowUpload');
		$this->setOutput($attachnum, 'attachnum');
	}

	private function _bulidAttachs($attach) {
		if (!$attach) return '';
		$array = array();
		ksort($attach);
		reset($attach);
		foreach ($attach as $key => $value) {
			$array[$key] = array(
				'name' => $value['name'],
				'size' => $value['size'],
				'path' => Pw::getPath($value['path'], $value['ifthumb']&1),
				'thumbpath' => Pw::getPath($value['path'], $value['ifthumb']),
				'desc' => $value['descrip'],
				'special' => $value['special'],
				'cost' => $value['cost'],
				'ctype' => $value['ctype']
			);
		}
		return $array;
	}
	
	private function _initTopictypes($defaultTopicType = 0) {
		$topictypes = $jsonArray = array();
		$forceTopicType = $this->post->forum->forumset['force_topic_type'];
		if ($this->post->forum->forumset['topic_type']) {
			$permission = $this->loginUser->getPermission('operate_thread', false, array());
			$topictypes = $this->_getTopictypeDs()->getTopicTypesByFid($this->post->forum->fid, !$permission['type']);
			foreach ($topictypes['sub_topic_types'] as $key => $value) {
				if (!is_array($value)) continue;
// 				if (!$forceTopicType && $value) $jsonArray[$key][$key] = '无分类';
				foreach ($value as $k => $v) {
					$jsonArray[$key][$k] = strip_tags($v['name']);
				}
			}
		}
		if ($defaultTopicType && isset($topictypes['all_types'][$defaultTopicType])) {
			$defaultParentTopicType = $topictypes['all_types'][$defaultTopicType]['parentid'];
		} else {
			$defaultTopicType = $defaultParentTopicType = 0;
		}
		$json = Pw::jsonEncode($jsonArray);
		$this->setOutput($defaultTopicType, 'defaultTopicType');
		$this->setOutput($defaultParentTopicType, 'defaultParentTopicType');
		$this->setOutput($topictypes, 'topictypes');
		$this->setOutput($json, 'subTopicTypesJson');
		$this->setOutput($forceTopicType ? 1 : 0, 'forceTopic');
		$this->setOutput('1', 'isTopic');
	}

	/**
	 * 
	 * Enter description here ...
	 * @return PwTopicType
	 */
	private function _getTopictypeDs() {
		return Wekit::load('forum.PwTopicType');
	}

}


Wind::import('LIB:image.PwImage');



/**
 * 上传组件
 *
 * @author Jianmin Chen <sky_hold@163.com>
 * @copyright ©2003-2103 phpwind.com
 * @license http://www.phpwind.com
 * @version $Id: PwUpload.php 22380 2012-12-21 14:54:07Z jieyin $
 * @package upload
 */

class zzPwUpload {

	protected $bhv;		// 上传行为配置
	protected $store;	// 附件存储器

	public function __construct(PwUploadAction $bhv) {

		$this->bhv = $bhv;
		$this->setStore();
	}

	public function getBehavior() {
		return $this->bhv;
	}
	
	/**
	 * 检查是否可以上传
	 *
	 * @return bool|PwError
	 */
	public function check() {
		return $this->bhv->check();
	}
	
	/**
	 * 获取已上传附件个数
	 *
	 * @return int
	 */
	public function getUploadNum() {
		return $this->bhv->getUploadNum();
	}
	
	/**
	 * 检查上传文件是否符合规定
	 *
	 * @param PwUploadFile $file
	 * @return bool|PwError
	 */
	public function checkFile($file) {
//		if (!$file->ext || !isset($this->bhv->ftype[$file->ext])) {
//			return new PwError(array('upload.ext.error', array('{ext}' => '.' . $file->ext)));
//		}
		if ($file->size < 1) {
			return new PwError('upload.size.less');
		}
//		if ($file->size > $this->bhv->ftype[$file->ext] * 1024) {
//			return new PwError(array('upload.size.over', array('{size}' => $this->bhv->ftype[$file->ext])));
//		}
		return true;
	}
	
	/**
	 * 设置附件存储对象
	 */
	public function setStore() {		
		$this->store = Wind::getComponent($this->bhv->isLocal ? 'localStorage' : 'storage');
	}
	
	/**
	 * 过滤文件名
	 *
	 * @param string $filename
	 * @return string
	 */
	public function filterFileName($filename) {
		return preg_replace('/\.(php|asp|jsp|cgi|fcgi|exe|pl|phtml|dll|asa|com|scr|inf)$/i', ".scp_\\1" , $filename);
	}
	
	/**
	 * 上传附件主流程
	 *
	 * @return mixed
	 */
	public function execute() {
		global $etarratt; //zzcity
		$uploaddb = array();
		if (count($etarratt)==0){					
			$this->bhv->update($uploaddb);
			return false;
		}
		
/*		foreach ($_FILES as $key => $value) {
			if (!self::isUploadedFile($value['tmp_name']) || !$this->bhv->allowType($key)) {
				continue;
			}
			$file = new PwUploadFile($key, $value);
			if (($result = $this->checkFile($file)) !== true) {
				return $result;
			}
			$file->filename = $this->filterFileName($this->bhv->getSaveName($file));
			$file->savedir = $this->bhv->getSaveDir($file);
			$file->source = $this->store->getAbsolutePath($file->filename, $file->savedir);

			if (!self::moveUploadedFile($value['tmp_name'], $file->source)) {
				return new PwError('upload.fail');
			}
			if (($result = $file->operate($this->bhv, $this->store)) !== true) {
				return $result;
			}
			if (($result = $this->saveFile($file)) !== true) {
				return $result;
			}
			$uploaddb[] = $file->getInfo();
		}
*/	
		$charset=Wekit::app()->charset;
		$content=$_POST['atc_content'];
		foreach ($etarratt as $key => $etvalue) {
			if (!preg_match("/".preg_quote($etvalue,"/")."/i",$content)){
				continue;	
			}			
            $etrealvalue=dirname(__FILE__).preg_replace('/(.*)attachment\//i','/attachment/',$etvalue);
			if($charset=='UTF-8'){
				$etrealvalue=iconv('UTF-8','GB2312',$etrealvalue);
			}
			
			$value['name']=substr(strrchr($etvalue, '/'), 1);
			$value['size']=1;
			$key=$value['name'].'_'.$key;
			$file = new PwUploadFile($key, $value);
			$file->filename=urlencode($file->name);
			//$file->filename = $this->filterFileName($this->bhv->getSaveName($file));
			$file->savedir = $this->bhv->getSaveDir($file);
			$file->source = $this->store->getAbsolutePath($file->filename, $file->savedir);
			
//			$etrealvalue=realpath($etrealvalue);			
			if (!file_exists($etrealvalue)) { //上传临时目录是否有文件
			
				if (!file_exists($file->source)){ //附件目录是否已有文件					
/*				echo('[err]First upload files,请先上传文件到正确的附件目录[/err]');
					exit;
*/
					continue; 

				}
			}else{
				
				if (($result = $this->checkFile($file)) !== true) {
                //return $result;
                return '[err]文件大小错误[/err]';
				}
	
				if (!self::moveUploadedFile($etrealvalue, $file->source)) {
//                return new PwError('upload.fail');
                return '[err]文件移动失败[/err]';
				}
						
			}

			
			if (($result = $file->operate($this->bhv, $this->store)) !== true) {
//                return $result;
                return '[err]文件处理失败[/err]';
			}
			if (($result = $this->saveFile($file)) !== true) {
//                return $result;
                return '[err]文件移动失败[/err]';
			}
			$uploaddb[] = $file->getInfo();
		}
		//zzcity add 当前内容无图
		if(!$uploaddb){
			return false;
		}
		$this->bhv->update($uploaddb);
		$etattlist=$this->bhv->getAttachs();
		
		foreach ($etattlist as $key=>$value){
			$etvalue=$value['name'];

			$etaid=$value['aid'];
			foreach ($etarratt as $key2 => $value2) {
				if (preg_match("/".preg_quote($etvalue,"/")."/i",$value2)){
					$etvalue=	$value2;
					break;	
				}
			}
			if (preg_match("/".preg_quote($etvalue,"/")."/i",$content)){
     		$_POST['flashatt'][$etaid]['desc']='';

				$content=preg_replace("/<a([^>]*?)".preg_quote($etvalue,"/")."([^<]*?)<img([^>]*?)".preg_quote($etvalue,"/")."([^<]*?)<\/(.*?)>/i",'[attachment='.($etaid).']',$content);
				$content=preg_replace("/<img([^>]*?)".preg_quote($etvalue,"/")."([^>]*?)>/i",'[attachment='.($etaid).']',$content);
				$content=preg_replace("/\[img([^\]]*?)\]".preg_quote($etvalue,"/")."\[\/img\]/i",'[attachment='.($etaid).']',$content);
				$content=preg_replace("/<a([^>]*?)".preg_quote($etvalue,"/")."([^>]*?)>([^<]+?)<\/a(.*?)>/i",'\\3[attachment='.($etaid).']',$content);
				$content=preg_replace("/\[url=".preg_quote($etvalue,"/")."(.*?)\[\/url\]/i",'[attachment='.($etaid).']',$content);
				$content=preg_replace("/\[(flash|rm|wmv)=([^\[]*?)".preg_quote($etvalue,"/")."([^\]]*?)(flash|rm|wmv)\]/i",'\\3[attachment='.($etaid).']',$content);
				if (in_array($upload['ext'], array('swf','flv'))) {
					$content=preg_replace("/<object((?!object)(\s|\S))*".preg_quote($etvalue,"/")."((?!object)(\s|\S))*</(.*?)>/i",'[flash=314,256,1]'.$etvalue.'[/flash]',$content);
					$content=preg_replace("/<embed((?!embed)(\s|\S))*".preg_quote($etvalue,"/")."((?!embed)(\s|\S))*</(.*?)>/i",'[flash=314,256,1]'.$etvalue.'[/flash]',$content);
				}elseif  (in_array($upload['ext'], array('rm','rmvb'))){
					$content=preg_replace("/<object((?!object)(\s|\S))*".preg_quote($etvalue,"/")."((?!object)(\s|\S))*</(.*?)>/i",'[rm=314,256,1]'.$etvalue.'[/rm]',$content);
					$content=preg_replace("/<embed((?!embed)(\s|\S))*".preg_quote($etvalue,"/")."((?!embed)(\s|\S))*</(.*?)>/i",'[rm=314,256,1]'.$etvalue.'[/rm]',$content);
				}elseif  (in_array($upload['ext'], array('wmv','mp3','mp4','avi','wma'))){
					$content=preg_replace("/<object((?!object)(\s|\S))*".preg_quote($etvalue,"/")."((?!object)(\s|\S))*</(.*?)>/i",'[wmv=314,256,1]'.$etvalue.'[/wmv]',$content);
					$content=preg_replace("/<embed((?!embed)(\s|\S))*".preg_quote($etvalue,"/")."((?!embed)(\s|\S))*</(.*?)>/i",'[wmv=314,256,1]'.$etvalue.'[/wmv]',$content);				
				}      	
			}
			
		}
		$_POST['atc_content']=$content;
		$etarratt=array();
		$etattachs='';
		return true;
	}
	
	/**
	 * 保存文件
	 *
	 * @param PwUploadFile $file
	 * @return bool|PwError
	 */
	public function saveFile($file) {
		if (($result = $this->store->save($file->source, $file->fileuploadurl)) !== true) {
			return $result;
		}
		if ($thumb = $file->getThumb()) {
			foreach ($thumb as $key => $value) {
				$this->store->save($value[0], $value[1]);
			}
		}
		return true;
	}
	
	/**
	 * 统计待上传附件个数
	 *
	 * @return int
	 */
	public static function countUploadedFile() {
		$i = 0;
		foreach ($_FILES as $key => $value) {
			if (self::isUploadedFile($value['tmp_name'])) $i++;
		}
		return $i;
	}
	
	/**
	 * 判断是否是正常的上传文件
	 *
	 * @param string $tmp_name
	 * @return bool
	 */
	public static function isUploadedFile($tmp_name) {
		if (!$tmp_name || $tmp_name == 'none') {
			return false;
		} elseif (function_exists('is_uploaded_file') && !is_uploaded_file($tmp_name) && !is_uploaded_file(str_replace('\\\\', '\\', $tmp_name))) {
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * 移动上传文件
	 *
	 * @param string $tmp_name 源文件
	 * @param string $filename 移动后的文件地址
	 * @return bool
	 */
	public static function moveUploadedFile($tmp_name, $filename) {
		if (strpos($filename, '..') !== false || strpos($filename, '.php.') !== false || preg_match("/\.php$/i", $filename)) {
			exit('illegal file type!');
		}
		self::createFolder(dirname($filename));
//		if (function_exists("move_uploaded_file") && @move_uploaded_file($tmp_name, $filename)) {
//			@chmod($filename, 0777);
//			return true;
//		}
		if (self::copyFile($tmp_name, $filename)) {
			@unlink($tmp_name); //zzcity
			return true;
		}
		return false;
	}
	
	/**
	 * 复制文件
	 *
	 * @param string $srcfile 源文件
	 * @param string $dstfile 目标文件地址
	 * @return bool
	 */
	public static function copyFile($srcfile, $dstfile) {
		if (@copy($srcfile, $dstfile)) {
			@chmod($dstfile, 0777);
			return true;
		}
		if (is_readable($srcfile)) {
			file_put_contents($dstfile, file_get_contents($srcfile));
			if (file_exists($dstfile)) {
				@chmod($dstfile, 0777);
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 创建目录
	 *
	 * @param string $path
	 */
	public static function createFolder($path) {
		if (!is_dir($path)) {
			self::createFolder(dirname($path));
			@mkdir($path);
			@chmod($path, 0777);
			@fclose(@fopen($path . '/index.html', 'w'));
			@chmod($path . '/index.html', 0777);
		}
	}

	public function __call($methodName, $args) {
		if (!method_exists($this->bhv, $methodName)) {
			return false;
		}
		$method = new ReflectionMethod($this->bhv, $methodName);
		if ($method->isPublic()) {
			return call_user_func_array(array(&$this->bhv, $methodName), $args);
		}
		return false;
	}
}


/**
 * 上传文件对象
 *
 * @author Jianmin Chen <sky_hold@163.com>
 * @package upload
 */
class PwUploadFile {

	public $key;
	public $id;
	public $attname;
	public $name;
	public $size;
	public $type = 'zip';
	public $ifthumb = 0;
	public $filename;
	public $savedir;
	public $fileuploadurl = '';
	public $ext;
	
	protected $_thumb = array();

	public function __construct($key, $value) {
		list($t, $i) = explode('_', $key);
		$this->id = intval($i);
		$this->attname = $t;
		$this->name = $value['name'];
		$this->size = intval($value['size']);
		$this->ext  = strtolower(substr(strrchr($this->name, '.'), 1));
	}

	public function getInfo() {
		return array(
			'id' => $this->id,
			'attname' => $this->attname,
			'name' => $this->name,
			'size' => $this->size,
			'type' => $this->type,
			'ifthumb' => $this->ifthumb,
			'fileuploadurl' => $this->fileuploadurl,
			'ext' => $this->ext,
			'thumb' => $this->_thumb
		);
	}
	
	/**
	 * 是否是图片
	 *
	 * @return bool
	 */
	public function isImage() {
		return in_array($this->ext, array('gif','jpg','jpeg','png','bmp','swf'));
	}
	
	/**
	 * 是否是文本
	 *
	 * @return bool
	 */
	public function isTxt() {
		return $this->ext == 'txt';
	}
	
	/**
	 * 附件处理
	 *
	 * @param PwUploadAction $bhv 上传行为
	 * @param object 存储对象
	 * @return bool|PwError
	 */
	public function operate($bhv, $store) {
		$this->size = ceil(filesize($this->source) / 1024);
		$this->fileuploadurl = $this->savedir . $this->filename;

		if ($this->isImage()) {
			return $this->operateImage($bhv, $store);
		}
		if ($this->isTxt()) {
			return $this->operateTxt();
		}
		return true;
	}
	
	/**
	 * 图片处理
	 *
	 * @param PwUploadAction $bhv 上传行为
	 * @param object 存储对象
	 * @return bool|PwError
	 */
	public function operateImage($bhv, $store) {
		$image = new PwImage($this->source);
		if (!$image->isImage()) {
			return new PwError('upload.content.error');
		}
		if ($image->ext != 'swf') {
			if (!$image->getSource() && $image->ext != 'bmp') {
				return new PwError('upload.content.error');
			}
			if ($bhv->allowThumb()/* && $upload['ext'] != 'gif'*/) {
				$this->makeThumb($image, $bhv->getThumbInfo($this->filename, $this->savedir), $store);
			}
			if ($bhv->allowWaterMark()) {
				$waterinfo = $bhv->getWaterMarkInfo();
				$this->watermark($image, $waterinfo);
				foreach ($this->_thumb as $value) {
					$this->watermark(new PwImage($value[0]), $waterinfo);
				}
			}
			$this->type = 'img';
		}
		return true;
	}
	
	/**
	 * 文本处理
	 *
	 * @return bool|PwError
	 */
	public function operateTxt() {
		/*
		if (preg_match('/(onload|submit|post|form)/i', readover($source))) {
			P_unlink($source);
			showUploadMsg('upload_content_error');
		}*/
		$this->type = 'txt';
		return true;
	}
	
	/**
	 * 生成缩略图
	 *
	 * @param PwImage $image 图片对象
	 * @param array $thumbInfo 缩略图配置
	 * @param object 存储对象
	 */
	public function makeThumb(PwImage $image, $thumbInfo, $store) {
		$quality = Wekit::C('attachment', 'thumb.quality');
		foreach ($thumbInfo as $key => $value) {
			$thumburl = $store->getAbsolutePath($value[0], $value[1]);
			zzPwUpload::createFolder(dirname($thumburl));
			$result = $image->makeThumb($thumburl, $value[2], $value[3], $quality, $value[4], $value[5]);
			if ($result === true && $image->filename != $thumburl) {
				$ts = $image->getThumb();
				$this->ifthumb |= (1 << $key);
				$this->_thumb[$key] = array($thumburl, $value[1] . $value[0], $ts->getThumbWidth(), $ts->getThumbHeight());
			}
		}
	}

	public function getThumb() {
		return $this->_thumb;
	}
	
	/**
	 * 图片生成水印
	 *
	 * @param PwImage $image 图片对象
	 * @param array $options 生成方案配置
	 */
	public static function watermark(PwImage $image, $options = array()) {
		if (!in_array($image->type, array('gif', 'jpeg', 'png'))) return;
		$config = Wekit::C('attachment');
		if ($options) {
			foreach ($options as $key => $value) {
				$config['mark.' . $key] = $value;
			}
		}
		if ($image->type == 'gif' && !$config['mark.gif']) return;
		if ($image->width < $config['mark.limitwidth'] || $image->height < $config['mark.limitheight']) return;
		
		Wind::import('LIB:image.PwImageWatermark');
		$watermark = new PwImageWatermark($image);
		$watermark->setPosition($config['mark.position'])
			->setType($config['mark.type'])
			->setTransparency($config['mark.transparency'])
			->setQuality($config['mark.quality']);

		if ($config['mark.type'] == 1) {
			$watermark->setFile($config['mark.file']);
		} else {
			$watermark->setText($config['mark.text'])
				->setFontfamily($config['mark.fontfamily'])
				->setFontsize($config['mark.fontsize'])
				->setFontcolor($config['mark.fontcolor']);
		}
		$watermark->execute();
	}
}


class UploadController extends PwBaseController {

	public function run() {

		header("Content-type: text/html; charset=" . Wekit::app()->charset);
		//$pwServer['HTTP_USER_AGENT'] = 'Shockwave Flash';
		$swfhash = 1/*GetVerify($winduid)*/;
		echo Pw::jsonEncode(array('uid' => $this->loginUser->uid, 'a' => 'dorun', 'verify' => $swfhash));
		$this->setTemplate('');

	}

	public function dorunAction() {
		global $etattachs,$etarratt,$user; //zzcity
		if(trim($etattachs)=='') return false ;
		$etarratt=explode(',',$etattachs);	
		
//		if (!$user = $this->_getUser()) {
//			$this->showError('login.not');
//		}
		$fid = $this->getInput('fid', 'post');

		Wind::import('SRV:upload.action.PwAttMultiUpload');
		//Wind::import('SRV:upload.PwUpload');
		$bhv = new PwAttMultiUpload($user, $fid);

		$upload = new zzPwUpload($bhv);
		if (($result = $upload->check()) === true) {			
			$result = $upload->execute();
		}else{		
			exit('[err]文件入库失败，请检查文件类型、权限[/err]');
		}
		
		if ($result === true) {
			if (!$data = $bhv->getAttachInfo()) {
//            $this->showError('upload.fail');
					exit('[err]文件入库失败[/err]');

			}
		}elseif ($result !== false){
					exit($result);
		}
//	$this->setOutput($data, 'data');
//		$this->showMessage('upload.success');
	}

	public function replaceAction() {
		
		if (!$this->loginUser->isExists()) {
			$this->showError('login.not');
		}
		$aid = $this->getInput('aid');
		
		Wind::import('SRV:upload.action.PwAttReplaceUpload');
		Wind::import('SRV:upload.PwUpload');
		$bhv = new PwAttReplaceUpload($this->loginUser, $aid);

		$upload = new PwUpload($bhv);
		if (($result = $upload->check()) === true) {
			$result = $upload->execute();
		}
		if ($result !== true) {
			$this->showError($result->getError());
		}
		$this->setOutput($bhv->getAttachInfo(), 'data');
		$this->showMessage('upload.success');
	}

	protected function _getUser() {
		$authkey = 'winduser';
		$pre = Wekit::C('site', 'cookie.pre');
		$pre && $authkey = $pre . '_' . $authkey;

		$winduser = $this->getInput($authkey, 'post');

		list($uid, $password) = explode("\t", Pw::decrypt(urldecode($winduser)));
		$user = new PwUserBo($uid);
		if (!$user->isExists() || Pw::getPwdCode($user->info['password']) != $password) {
			return null;
		}
		unset($user->info['password']);
		return $user;
	}
}

$etattachs=$_POST['etattachs'];//zzcity add
	


Wekit::run('phpwind');
?>