/** * 初始化方法 * @author jry <*****@*****.**> */ protected function _initialize() { // 系统开关 if (!C('TOGGLE_WEB_SITE')) { $this->error('站点已经关闭,请稍后访问~'); } // 获取所有模块配置的用户导航 $mod_con['status'] = 1; $_user_nav_main = array(); $_user_nav_list = D('Admin/Module')->where($mod_con)->getField('user_nav', true); foreach ($_user_nav_list as $key => $val) { if ($val) { $val = json_decode($val, true); if ($val['main']) { $_user_nav_main = array_merge($_user_nav_main, $val['main']); } } } // 监听行为扩展 \Think\Hook::listen('corethink_behavior'); $this->assign('meta_keywords', C('WEB_SITE_KEYWORD')); $this->assign('meta_description', C('WEB_SITE_DESCRIPTION')); $this->assign('_new_message', cookie('_new_message')); // 获取用户未读消息数量 $this->assign('_user_auth', session('user_auth')); // 用户登录信息 $this->assign('_user_nav_main', $_user_nav_main); // 用户导航信息 $this->assign('_user_center_side', C('USER_CENTER_SIDE')); // 用户中心侧边 $this->assign('_user_login_modal', C('USER_LOGIN_MODAL')); // 用户登录弹窗 $this->assign('_home_public_layout', C('HOME_PUBLIC_LAYOUT')); // 页面公共继承模版 }
/** * 查询指定分类的详细信息 * @param int $info detail 查询的 id 或者slug */ public function detail($info = 1) { if (get_opinion("auto_channel", false, false)) { $this->channel($info); Hook::listen('app_end'); die; } $CatsLogic = new CatsLogic(); $PostsLogic = new PostsLogic(); $cat = $CatsLogic->detail($info); // $this->assign('cat_id', $cat['cat_id']); // 赋值数据集 $this->if404($cat, "非常抱歉,没有这个分类,可能它已经躲起来了"); //优雅的404 $posts_id = $CatsLogic->getPostsId($cat['cat_id']); $count = sizeof($posts_id); $count == 0 ? $res404 = 0 : ($res404 = 1); if (!empty($posts_id)) { $Page = new GreenPage($count, get_opinion('PAGER')); $pager_bar = $Page->show(); $limit = $Page->firstRow . ',' . $Page->listRows; $posts_list = $PostsLogic->getList($limit, 'single', 'post_date desc', true, array(), $posts_id); } $this->assign('title', '分类 ' . $cat['cat_name'] . ' 所有文章'); // 赋值数据集 $this->assign('res404', $res404); $this->assign('postslist', $posts_list); // 赋值数据集 $this->assign('pager', $pager_bar); // 赋值分页输出 $this->assign('breadcrumbs', get_breadcrumbs('cats', $cat['cat_id'])); $this->display('Archive/single-list'); }
/** * 初始化方法 * @author jry <*****@*****.**> */ protected function _initialize() { // 系统开关 if (!C('TOGGLE_WEB_SITE')) { $this->error('站点已经关闭,请稍后访问~'); } // 获取所有模块配置的用户导航 $mod_con['status'] = 1; $_user_nav_main = array(); $_user_nav_list = D('Admin/Module')->where($mod_con)->getField('user_nav', true); foreach ($_user_nav_list as $key => $val) { if ($val) { $val = json_decode($val, true); $_user_nav_main = array_merge($_user_nav_main, $val['main']); } } // 监听行为扩展 \Think\Hook::listen('corethink_behavior'); $this->assign('meta_keywords', C('WEB_SITE_KEYWORD')); $this->assign('meta_description', C('WEB_SITE_DESCRIPTION')); $this->assign('_new_message', cookie('_new_message')); // 获取用户未读消息数量 $this->assign('_user_auth', session('user_auth')); // 用户登录信息 $this->assign('_user_nav_main', $_user_nav_main); // 用户导航信息 }
/** * 发送数据到客户端 * @access public * @param mixed $data 数据 * @param string $type 返回类型 * @param bool $return 是否返回数据 * @return mixed */ public function send($data = [], $type = '', $return = false) { if ('' == $type) { $type = $this->type ?: (IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type')); } $type = strtolower($type); $data = $data ?: $this->data; if (!headers_sent() && isset($this->contentType[$type])) { header('Content-Type:' . $this->contentType[$type] . '; charset=utf-8'); } if (is_callable($this->transform)) { $data = call_user_func_array($this->transform, [$data]); } else { switch ($type) { case 'json': // 返回JSON数据格式到客户端 包含状态信息 $data = json_encode($data, JSON_UNESCAPED_UNICODE); break; case 'jsonp': // 返回JSON数据格式到客户端 包含状态信息 $handler = !empty($_GET[Config::get('var_jsonp_handler')]) ? $_GET[Config::get('var_jsonp_handler')] : Config::get('default_jsonp_handler'); $data = $handler . '(' . json_encode($data, JSON_UNESCAPED_UNICODE) . ');'; break; } } APP_HOOK && Hook::listen('return_data', $data); if ($return) { return $data; } echo $data; $this->isExit() && exit; }
public function testImport() { Hook::import(['my_pos' => ['\\tests\\thinkphp\\library\\think\\behavior\\One', '\\tests\\thinkphp\\library\\think\\behavior\\Three']]); Hook::import(['my_pos' => ['\\tests\\thinkphp\\library\\think\\behavior\\Two']], false); Hook::import(['my_pos' => ['\\tests\\thinkphp\\library\\think\\behavior\\Three', '_overlay' => true]]); $data['id'] = 0; $data['name'] = 'thinkphp'; Hook::listen('my_pos', $data); $this->assertEquals(3, $data['id']); }
public function SmsReady($mobile, $content) { $mobileids = $mobile . date('YmdHis'); $result = self::sendSMS($mobile, $content, $mobileids); if ($result != true) { \Think\Hook::listen('HomeLog', $parm = array('function' => 'SendSmsModel::SmsReady -> $result', 'logmsg' => 'result is false, ' . "{$result}", 'level' => 'ALERT')); return false; } return true; }
public function GetUsers($UsersId, $Feild) { $where['userid'] = array('IN', $UsersId); $result = self::where($where)->field($Feild)->select(); if ($result !== false) { return $result; } else { \Think\Hook::listen('HomeLog', $parm = array('function' => 'GetUsers -> $result', 'logmsg' => 'result is false', 'level' => 'ALERT')); } }
/** * 显示404页 * @function 404 ERROR 需要显示错误的信息 * * @param string $message */ public function error404($message = "非常抱歉,你需要的页面暂时不存在,可能它已经躲起来了。.") { $this->assign("message", $message); if (File::file_exists(T('Home@Index/404'))) { $this->display('Index/404'); } else { $this->show($message); } Hook::listen('app_end'); die; }
public function BlackNew($RecordId, $UserId) { $data = array('recordid' => $RecordId, 'userid' => $UserId, 'lasttime' => time()); $result = self::add($data); if ($result !== false) { return true; } else { return false; \Think\Hook::listen('HomeLog', $parm = array('function' => 'BlackNew -> $result', 'logmsg' => 'result is false', 'level' => 'ALERT')); } }
/** * @todo: 发送评论 * @author Saki <*****@*****.**> * @date 2014-12-22 上午9:34:18 * @version V1.0 */ public function PostComment() { $model = new \Admin\Model\ArticleCommentModel(); $post = $_POST['ArticleComment']; $id = $post['aid']; $comment_id = $model->createComment($post); //发送邮件,这里为游客发送评论,则为管理员邮箱收到邮件 if ($comment_id) { \Think\Hook::listen('postComment', $comment_id); \Think\Hook::add('postComment', 'Home\\Behaviors\\emailBehavior'); } $this->redirect('Article/view', array('id' => $id, 'p' => 1)); }
public function ajax_add(&$json) { $offset = I('offset'); $data['content'] = I('content'); Hook::listen('hy_filter', $data['content']); $data['user_id'] = ss_uid(); $data['create_time'] = time(); $data['anonymous'] = 0; if (false === $this->add($data)) { return $json['info'] = $this->getError(); } $json['status'] = true; $json['data'] = $this->lists($offset); }
/** * @todo: 发送评论-后台管理员发送 * @author Saki <*****@*****.**> * @date 2014-12-22 上午9:34:18 * @version V1.0 */ public function PostComment() { $model = new \Admin\Model\ArticleCommentModel(); $post = $_POST['ArticleComment']; $id = $post['aid']; $admin_info = $this->admin_info; $post['is_admin'] = $admin_info['id']; $comment_id = $model->createComment($post); if ($comment_id) { \Think\Hook::listen('postComment', $comment_id); \Think\Hook::add('postComment', 'Home\\Behaviors\\emailBehavior'); } $this->redirect('ArticleList/view', array('id' => $id, 'p' => 1)); }
/** * 用户存放在数据库中的配置,覆盖config中的 */ function customConfig() { $customConfig = S('customConfig'); if ($customConfig && APP_Cache) { $options = $customConfig; } else { $options = D('Options')->where(array('autoload' => 'yes'))->select(); if (APP_Cache) { S('customConfig', $options); } } foreach ($options as $config) { C($config['option_name'], $config['option_value']); } Hook::listen('base_customConfig'); }
/** * 初始化方法 * @author jry <*****@*****.**> */ protected function _initialize() { // 系统开关 if (!C('TOGGLE_WEB_SITE')) { $this->error('站点已经关闭,请稍后访问~'); } // 监听行为扩展 try { \Think\Hook::listen('corethink_behavior'); } catch (\Exception $e) { file_put_contents(RUNTIME_PATH . 'error.json', json_encode($e->getMessage())); } // 记录当前url if (MODULE_NAME !== 'User' && IS_GET === true) { cookie('forward', (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER["REQUEST_URI"]); } }
/** * 显示首页为空时 * @param $method * @param $args */ public function _empty($method, $args) { Hook::listen('home_index_empty'); }
/** * 初始化应用 */ public static function initCommon() { if (empty(self::$init)) { // 初始化应用 $config = self::init(); self::$suffix = $config['class_suffix']; // 应用调试模式 self::$debug = Config::get('app_debug'); if (!self::$debug) { ini_set('display_errors', 'Off'); } else { //重新申请一块比较大的buffer if (ob_get_level() > 0) { $output = ob_get_clean(); } ob_start(); if (!empty($output)) { echo $output; } } // 应用命名空间 self::$namespace = $config['app_namespace']; Loader::addNamespace($config['app_namespace'], APP_PATH); if (!empty($config['root_namespace'])) { Loader::addNamespace($config['root_namespace']); } // 加载额外文件 if (!empty($config['extra_file_list'])) { foreach ($config['extra_file_list'] as $file) { $file = strpos($file, '.') ? $file : APP_PATH . $file . EXT; if (is_file($file)) { include_once $file; } } } // 设置系统时区 date_default_timezone_set($config['default_timezone']); // 监听app_init Hook::listen('app_init'); self::$init = $config; } return self::$init; }
private static function init() { // 加载初始化文件 if (is_file(APP_PATH . 'init' . EXT)) { include APP_PATH . 'init' . EXT; // 加载模块配置 $config = Config::get(); } else { // 加载模块配置 $config = Config::load(APP_PATH . 'config' . EXT); // 加载应用状态配置 if ($config['app_status']) { $config = Config::load(APP_PATH . $config['app_status'] . EXT); } // 读取扩展配置文件 if ($config['extra_config_list']) { foreach ($config['extra_config_list'] as $name => $file) { $filename = APP_PATH . $file . EXT; Config::load($filename, is_string($name) ? $name : pathinfo($filename, PATHINFO_FILENAME)); } } // 加载别名文件 if (is_file(APP_PATH . 'alias' . EXT)) { Loader::addMap(include APP_PATH . 'alias' . EXT); } // 加载行为扩展文件 if (APP_HOOK && is_file(APP_PATH . 'tags' . EXT)) { Hook::import(include APP_PATH . 'tags' . EXT); } // 加载公共文件 if (is_file(APP_PATH . 'common' . EXT)) { include APP_PATH . 'common' . EXT; } } // 注册根命名空间 if (!empty($config['root_namespace'])) { Loader::addNamespace($config['root_namespace']); } // 加载额外文件 if (!empty($config['extra_file_list'])) { foreach ($config['extra_file_list'] as $file) { $file = strpos($file, '.') ? $file : APP_PATH . $file . EXT; if (is_file($file)) { include_once $file; } } } // 设置系统时区 date_default_timezone_set($config['default_timezone']); // 监听app_init APP_HOOK && Hook::listen('app_init'); }
/** * 模型检索处理 */ protected function searchMap() { if (!is_array($search = I('search')) || !$search) { return; } $log = array('msg' => "检索"); Hook::listen('hy_log', $log); $mapKey = array(); foreach ($search as $k => $v) { if ('' === $v || $mapKey[$k] || !$this->fieldsOptions[$k]) { continue; } if ($tmp = $this->fieldsOptions[$k]['list']['search']['sql']) { $mapKey[$k] = true; $tmp = preg_replace_callback('/\\{:([\\w\\-#]+)}/', function ($matches) use($search) { return $search[$matches[1]]; }, $tmp); $this->addMap($tmp); continue; } if ($tmp = $this->fieldsOptions[$k]['list']['search']['callback']) { $mapKey[$k] = true; $this->addMap($this->callbackHandler($tmp, $k, $search)); continue; } $field = $this->fieldsOptions[$k]['table'] ? $this->fieldsOptions[$k]['table'] . '.' . $k : "{$k}"; $this->fieldsOptions[$k]['list']['search']['query'] = $this->fieldsOptions[$k]['list']['search']['query'] ?: 'eq'; switch ($query = strtolower($this->fieldsOptions[$k]['list']['search']['query'])) { case 'time_string': $field = "UNIX_TIMESTAMP({$field})"; case 'time_stamp': $start = $v['start_time'] ? strtotime($v['start_time']) : 0; $end = $v['end_time'] ? strtotime($v['end_time']) + 24 * 60 * 60 - 1 : 0; if ($start && $end && $end > $start) { $tmp .= " and ( {$field} >= {$start} and {$field} <= {$end})"; } elseif ($start) { $tmp .= " and ( {$field} >= {$start})"; } elseif ($end) { $tmp .= " and ( {$field} <= {$end})"; } $this->addMap($tmp); break; case 'like': $this->addMap(array($field => array('like', "%{$v}%"))); break; default: $this->addMap(array($field => array($query ?: 'eq', $v))); break; } } return; }
/** * 输出异常信息 * @param \Exception $exception * @param Array $vars 异常信息 * @return void */ public static function output($exception, array $vars) { http_response_code($exception instanceof Exception ? $exception->getHttpStatus() : 500); $type = Config::get('default_return_type'); if (IS_API && 'html' != $type) { // 异常信息输出监听 APP_HOOK && Hook::listen('error_output', $data); // 输出异常内容 Response::send($data, $type, Config::get('response_return')); } else { //ob_end_clean(); extract($vars); include Config::get('exception_tmpl'); } }
/** * URL调度 * @access public * @return void */ public static function dispatch($config) { if (isset($_GET[$config['var_pathinfo']])) { // 判断URL里面是否有兼容模式参数 $_SERVER['PATH_INFO'] = $_GET[$config['var_pathinfo']]; unset($_GET[$config['var_pathinfo']]); } elseif (IS_CLI) { // CLI模式下 index.php module/controller/action/params/... $_SERVER['PATH_INFO'] = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : ''; } // 检测域名部署 if (!IS_CLI && isset($config['sub_domain_deploy']) && $config['sub_domain_deploy']) { Route::checkDomain(); } // 监听path_info Hook::listen('path_info'); // 分析PATHINFO信息 if (!isset($_SERVER['PATH_INFO']) && $_SERVER['SCRIPT_NAME'] != $_SERVER['PHP_SELF']) { $types = explode(',', $config['pathinfo_fetch']); foreach ($types as $type) { if (0 === strpos($type, ':')) { // 支持函数判断 $_SERVER['PATH_INFO'] = call_user_func(substr($type, 1)); break; } elseif (!empty($_SERVER[$type])) { $_SERVER['PATH_INFO'] = 0 === strpos($_SERVER[$type], $_SERVER['SCRIPT_NAME']) ? substr($_SERVER[$type], strlen($_SERVER['SCRIPT_NAME'])) : $_SERVER[$type]; break; } } } if (empty($_SERVER['PATH_INFO'])) { $_SERVER['PATH_INFO'] = ''; define('__INFO__', ''); define('__EXT__', ''); } else { $_SERVER['PATH_INFO'] = trim($_SERVER['PATH_INFO'], '/'); define('__INFO__', $_SERVER['PATH_INFO']); // URL后缀 define('__EXT__', strtolower(pathinfo($_SERVER['PATH_INFO'], PATHINFO_EXTENSION))); $_SERVER['PATH_INFO'] = __INFO__; if (__INFO__ && !defined('BIND_MODULE')) { if ($config['url_deny_suffix'] && preg_match('/\\.(' . $config['url_deny_suffix'] . ')$/i', __INFO__)) { exit; } $paths = explode($config['pathinfo_depr'], __INFO__, 2); // 获取URL中的模块名 if ($config['require_module'] && !isset($_GET[VAR_MODULE])) { $_GET[VAR_MODULE] = array_shift($paths); $_SERVER['PATH_INFO'] = implode('/', $paths); } } // 去除URL后缀 $_SERVER['PATH_INFO'] = preg_replace($config['url_html_suffix'] ? '/\\.(' . trim($config['url_html_suffix'], '.') . ')$/i' : '/\\.' . __EXT__ . '$/i', '', $_SERVER['PATH_INFO']); } // URL常量 define('__SELF__', strip_tags($_SERVER[$config['url_request_uri']])); // 获取模块名称 define('MODULE_NAME', defined('BIND_MODULE') ? BIND_MODULE : self::getModule($config)); // 模块初始化 if (MODULE_NAME && $config['common_module'] != MODULE_NAME && is_dir(APP_PATH . MODULE_NAME)) { Hook::listen('app_begin'); define('MODULE_PATH', APP_PATH . MODULE_NAME . '/'); define('VIEW_PATH', MODULE_PATH . VIEW_LAYER . '/'); // 初始化模块 self::initModule(MODULE_PATH, $config); } else { throw new Exception('module not exists :' . MODULE_NAME); } // 路由检测和控制器、操作解析 Route::check($_SERVER['PATH_INFO'], $config['pathinfo_depr']); // 获取控制器名 define('CONTROLLER_NAME', strip_tags(strtolower(isset($_GET[VAR_CONTROLLER]) ? $_GET[VAR_CONTROLLER] : $config['default_controller']))); // 获取操作名 define('ACTION_NAME', strip_tags(strtolower(isset($_GET[VAR_ACTION]) ? $_GET[VAR_ACTION] : $config['default_action']))); unset($_GET[VAR_ACTION], $_GET[VAR_CONTROLLER], $_GET[VAR_MODULE]); //保证$_REQUEST正常取值 $_REQUEST = array_merge($_POST, $_GET, $_COOKIE); }
/** * 处理标签扩展 * @param string $tag 标签名称 * @param mixed $params 传入参数 * @return mixed */ function tag($tag, &$params = null) { return \Think\Hook::listen($tag, $params); }
/** * 实时写入日志信息 并支持行为 * @param mixed $msg 调试信息 * @param string $type 信息类型 * @param bool $force 是否强制写入 * @return bool */ public static function write($msg, $type = 'log', $force = false) { // 封装日志信息 if (true === $force || empty(self::$config['level'])) { $log[$type][] = $msg; } elseif (in_array($type, self::$config['level'])) { $log[$type][] = $msg; } else { return false; } // 监听log_write Hook::listen('log_write', $log); if (is_null(self::$driver)) { self::init(Config::get('log')); } // 写入日志 return self::$driver->save($log); }
private function PrivateUpdateBinding($BindingId, $Data) { $where['bindingid'] = array('EQ', $BindingId); $result = self::where($where)->save($Data); if ($result !== false) { return true; } else { \Think\Hook::listen('HomeLog', $parm = array('function' => 'UpdateBinding -> $result', 'logmsg' => 'result is false', 'level' => 'ALERT')); } }
/** * 输出异常信息 * @param \Exception $exception * @param Array $vars 异常信息 * @return null */ public static function output(\Exception $exception, array $vars) { if ($exception instanceof Exception) { http_response_code($exception->getHttpStatus()); } else { http_response_code(500); } // header('Content-Type: application/json'); // echo json_encode($vars);exit; $type = Config::get('default_return_type'); if (IS_API && 'html' != $type) { // 异常信息输出监听 APP_HOOK && Hook::listen('error_output', $data); // 输出异常内容 Response::send($data, $type, Config::get('response_return')); } else { ob_end_clean(); extract($vars); include Config::get('exception_tmpl'); } }
/** * 处理标签扩展 * @param string $tag 标签名称 * @param mixed $params 传入参数 * @return void */ function tag($tag, &$params = NULL) { \Think\Hook::listen($tag, $params); }
private static function module($result, $config) { if (APP_MULTI_MODULE) { // 多模块部署 $module = strtolower($result[0] ?: $config['default_module']); // 获取模块名称 define('MODULE_NAME', strip_tags($module)); // 模块初始化 if (MODULE_NAME && !in_array(MODULE_NAME, $config['deny_module_list']) && is_dir(APP_PATH . MODULE_NAME)) { define('MODULE_PATH', APP_PATH . MODULE_NAME . DS); define('VIEW_PATH', MODULE_PATH . VIEW_LAYER . DS); // 初始化模块 self::initModule(MODULE_NAME, $config); } else { throw new Exception('module [ ' . MODULE_NAME . ' ] not exists ', 10005); } } else { // 单一模块部署 define('MODULE_NAME', ''); define('MODULE_PATH', APP_PATH); define('VIEW_PATH', MODULE_PATH . VIEW_LAYER . DS); } // 获取控制器名 $controllerName = strip_tags($result[1] ?: Config::get('default_controller')); defined('CONTROLLER_NAME') or define('CONTROLLER_NAME', Config::get('url_controller_convert') ? strtolower($controllerName) : $controllerName); // 获取操作名 $actionName = strip_tags($result[2] ?: Config::get('default_action')); defined('ACTION_NAME') or define('ACTION_NAME', Config::get('url_action_convert') ? strtolower($actionName) : $actionName); // 执行操作 if (!preg_match('/^[A-Za-z](\\/|\\.|\\w)*$/', CONTROLLER_NAME)) { // 安全检测 throw new Exception('illegal controller name:' . CONTROLLER_NAME, 10000); } $instance = Loader::controller(CONTROLLER_NAME, '', Config::get('use_controller_suffix'), Config::get('empty_controller')); // 获取当前操作名 $action = ACTION_NAME . Config::get('action_suffix'); try { // 操作方法开始监听 $call = [$instance, $action]; APP_HOOK && Hook::listen('action_begin', $call); if (!preg_match('/^[A-Za-z](\\w)*$/', $action)) { // 非法操作 throw new \ReflectionException('illegal action name :' . ACTION_NAME); } // 执行操作方法 $data = self::invokeMethod($call); } catch (\ReflectionException $e) { // 操作不存在 if (method_exists($instance, '_empty')) { $method = new \ReflectionMethod($instance, '_empty'); $data = $method->invokeArgs($instance, [$action, '']); APP_DEBUG && Log::record('[ RUN ] ' . $method->getFileName(), 'info'); } else { throw new Exception('method [ ' . (new \ReflectionClass($instance))->getName() . '->' . $action . ' ] not exists ', 10002); } } return $data; }
/** * 处理插件钩子 * @param string $hook 钩子名称 * @param mixed $params 传入参数 * @return void * @author jry <*****@*****.**> */ function hook($hook, $params = array()) { \Think\Hook::listen($hook, $params); }
/** * 解析json 返回html * @param $json json字符串 * { header : {} , * content: [ * { name: , resoures : , theme :} , ..... * ], * footer: {}, * } * @return string html */ public function resolve_json($site_id, $json) { $content = json_decode($json, true); // var_dump($content); $widgets = []; foreach ($content['content'] as $item) { $temp = $this->load_widget($item['name'], $item); if ($temp == false) { continue; } $widgets[] = $temp; } $links = []; foreach ($widgets as $widget) { $links = array_merge_recursive($links, $widget->load_template_link()); } $links['js'] = array_unique($links['js']); $links['css'] = array_unique($links['css']); // 页面缓存 ob_start(); ob_implicit_flush(0); foreach ($widgets as $widget) { $widget->index($site_id); } $content = ob_get_clean(); \Think\Hook::listen('view_filter', $content); return array('content' => $content, 'links' => $links); }
/** * 下载文件 */ public function download_site() { $site_id = I('site_id', session('site_info.id')); if (empty($site_id)) { return $this->error('请选择网站'); } $site_info = M()->table('site_info')->field('site_name,url,json')->where(array('id' => $site_id, 'user_id' => session('user_info.id'), 'status' => 0))->find(); if (empty($site_info)) { return $this->error('此网站无效'); } $info = M()->table('user_column')->where(array('site_id' => $site_id, 'forbidden' => 0))->order('sort')->select(); if (empty($info)) { return $this->error('没有找到文件'); } $rootpath = C('TEMP_DIR') . $site_info['url'] . "/"; if (is_dir($rootpath)) { deleteAll($rootpath, true); } elseif (!mkdir($rootpath)) { return $this->error('创建根目录失败'); } $public_rootpath = $rootpath . "Public/"; if (!mkdir($public_rootpath)) { return $this->error('创建Public目录失败'); } /*=================================生成html==============================*/ $html_rootpath = $rootpath . "html/"; if (!mkdir($html_rootpath)) { return $this->error('创建html目录失败'); } $user_info = M()->table('user_info')->field('nickname,head_img')->find(session('user_info')['id']); $site_common = A('Panel')->get_site_common($site_id); $theme_templet = $site_common['theme_templet']; unset($site_common['theme_templet']); $this->collect_link($site_common['theme_links']); //var_dump($site_common['theme_links']); $this->assign($site_common); $this->assign('user_info', $user_info); $this->assign('download', true); /*==================生成栏目页===================*/ foreach ($info as $key => $value) { $widget_common = A('Panel')->resolve_json($site_id, $value['html']); $this->collect_link($widget_common['links']); $links = array_merge_recursive($site_common['theme_links'], $widget_common['links']); $this->assign($links); $this->assign('now_column', $value['id']); $this->assign('content', $widget_common['content']); $html = $this->fetch('Theme/theme'); $html = $this->replaceHtml($html); $result = file_put_contents($html_rootpath . $value['url'] . '.html', $html); if (!$result) { ////***删除文件**/// deleteAll($rootpath); return $this->error('下载失败:html失败'); } } /*==================生成详情页===================*/ $desc = json_decode($site_info['json'], true); foreach ($desc as $key => $value) { $desc_info = D($key)->get_all_info($site_id); $desc_path = $rootpath . '/' . $key . '/'; if (!mkdir($desc_path)) { deleteAll($rootpath); return $this->error('创建$key目录失败'); } $widget = A('Panel')->load_widget(ucwords(strtolower($key)) . 'Desc', $value); $widget_link = $widget->load_template_link(); $this->collect_link($widget_link, $rootpath); $links = array_merge_recursive($site_common['theme_links'], $widget_link); $this->assign($links); foreach ($desc_info as $desc_key => $desc_resource) { ob_start(); ob_implicit_flush(0); $widget->index($site_id, null, $desc_resource); $content = ob_get_clean(); \Think\Hook::listen('view_filter', $content); $this->assign('content', $content); $html = $this->fetch('Theme/theme'); $html = $this->replaceHtml($html); $result = file_put_contents($desc_path . $desc_resource['id'] . '.html', $html); if (!$result) { ////***删除文件**/// deleteAll($rootpath); return $this->error('下载失败:article失败'); } } } /*=================================引入资源文件==============================*/ /*=============引入js css=============*/ $this->download_theme_link($public_rootpath, $site_common['site_ifno']['theme']); $this->download_widget_link($public_rootpath); /*=============引入img=============*/ $img_path = $rootpath . 'Uploads/'; $photo_info = M()->table('photo as a')->field('c.savename,c.savepath')->join('home_picture as c on a.pic_id = c.id')->where(array('a.site_id' => $site_id))->select(); $admin_column_info = M()->table('user_column as a')->field('b.savename,b.savepath')->join('left join picture as b on a.icon = b.id')->where(array('a.site_id' => $site_id, 'a.is_default' => 1))->select(); $home_column_info = M()->table('user_column as a')->field('b.savename,b.savepath')->join('left join home_picture as b on a.icon = b.id')->where(array('a.site_id' => $site_id, 'a.is_default' => 0))->select(); $article_info = M()->table('article as a')->field('b.savename,b.savepath')->join('left join home_picture as b on a.pic_id = b.id')->where(array('a.site_id' => $site_id))->select(); $img_info = array_merge($photo_info, $admin_column_info, $home_column_info, $article_info); $uploads_path = C('PICTURE_UPLOAD')['rootPath']; foreach ($img_info as $key => $value) { hCopy($uploads_path . $value['savepath'] . $value['savename'], $img_path . $value['savepath'] . $value['savename']); } /*========================生成zip==============================*/ load("@.HZip#class"); $zip_name = C('TEMP_DIR') . $site_info['url'] . '.zip'; $zip = \HZip::zipDir(C('TEMP_DIR') . $site_info['url'], $zip_name); /*========================下载==================================*/ header("Cache-Control: max-age=0"); header("Content-Description: File Transfer"); header('Content-disposition: attachment; filename=' . basename($zip_name)); // 文件名 header("Content-Type: application/zip"); // zip格式的 header("Content-Transfer-Encoding: binary"); //二进制文件 header('Content-Length: ' . filesize($zip_name)); // 告诉浏览器,文件大小 @readfile($zip_name); //输出文件; unlink($zip_name); deleteAll($rootpath); }
/** * 析构方法 * @access public */ public function __destruct() { // 执行后续操作 Hook::listen('action_end'); }