示例#1
0
文件: CacheTest.php 项目: tourze/base
 public function testCache()
 {
     $key = uniqid();
     $value = time();
     Base::getCache()->set($key, $value);
     $this->assertEquals($value, Base::getCache()->get($key));
 }
示例#2
0
文件: Patch.php 项目: rockefys/server
 /**
  * 实现register_shutdown_function
  */
 public static function applyShutdownFunction()
 {
     Base::getLog()->debug(__METHOD__ . ' apply shutdown functions');
     foreach (self::$shutdownFunctions as $pair) {
         call_user_func_array(Arr::get($pair, 'callback'), Arr::get($pair, 'params'));
     }
 }
示例#3
0
文件: Message.php 项目: tourze/base
 /**
  * 读取消息文本
  *
  *     // 读取message/text.php中的username
  *     $username = Message::load('text', 'username');
  *
  * @param   string $file    文件名
  * @param   string $path    键名
  * @param   mixed  $default 键名不存在时返回默认值
  * @return  string|array  内容,如果$path为空的话,就返回完整数组内容
  */
 public static function load($file, $path = null, $default = null)
 {
     static $messages;
     if (!isset($messages[$file])) {
         $messages[$file] = [];
         $files = [];
         foreach (self::$_messagePaths as $includePath) {
             if (is_file($includePath . $file . self::$ext)) {
                 $files[] = $includePath . $file . self::$ext;
             }
         }
         if (!empty($files)) {
             foreach ($files as $f) {
                 $messages[$file] = Arr::merge($messages[$file], Base::load($f));
             }
         }
     }
     if (null === $path) {
         // 返回完整的数组
         return $messages[$file];
     } else {
         // 返回指定的键名
         return Arr::path($messages[$file], $path, $default);
     }
 }
示例#4
0
 /**
  * @inheritdoc
  */
 public function executeAction()
 {
     // 继续执行
     parent::executeAction();
     Base::getLog()->debug(__METHOD__ . ' render json content type', ['type' => $this->contentType]);
     $this->response->headers('content-type', $this->contentType);
     $this->response->body = json_encode($this->actionResult);
 }
示例#5
0
 /**
  * 完成模板渲染,并输出
  */
 public function after()
 {
     if ($this->autoRender) {
         Base::getLog()->debug(__METHOD__ . ' render template view');
         $this->response->body = $this->template->render();
     }
     parent::after();
 }
示例#6
0
文件: Main.php 项目: tourze/bootstrap
 /**
  * 每个请求层,最终被调用的方法
  *
  * @return mixed
  */
 public function handle()
 {
     Base::getLog()->debug(__METHOD__ . ' handle main flow - start');
     if (!Route::exists('default')) {
         Base::getLog()->debug(__METHOD__ . ' set default route');
         Route::set('default', '(<controller>(/<action>(/<id>)))')->defaults(['controller' => 'Site', 'action' => 'index']);
     }
     $this->flow->contexts['uri'] = Url::detectUri();
     Base::getLog()->debug(__METHOD__ . ' handle main flow - end');
 }
示例#7
0
 /**
  * @inheritdoc
  */
 public function destroy()
 {
     // 清空session数据
     $_SESSION = [];
     Base::getLog()->debug(__METHOD__ . ' clean $_SESSION');
     // 删除对应的session文件
     $sessionID = HttpProtocol::getSessionID();
     $file = HttpProtocol::getSessionFile($sessionID);
     FileHelper::delete($file);
     Base::getLog()->debug(__METHOD__ . ' delete session file', ['file' => $file]);
 }
示例#8
0
 /**
  * @return bool
  */
 protected function _destroy()
 {
     // Destroy the current session
     session_destroy();
     // Did destruction work?
     $status = !Base::getHttp()->sessionID();
     if ($status) {
         // Make sure the session cannot be restarted
         Cookie::delete($this->_name);
     }
     return $status;
 }
示例#9
0
 /**
  * {@inheritdoc}
  */
 public function prepareActionList()
 {
     $actions = parent::prepareActionList();
     Base::getLog()->debug(__METHOD__ . ' handle rest controller request', ['method' => $this->request->method]);
     if (isset($this->methodMapping[$this->request->method])) {
         $action = $this->methodMapping[$this->request->method];
         Base::getLog()->debug(__METHOD__ . ' found rest action', ['method' => $this->request->method, 'action' => $action]);
         $actions[] = $action;
     }
     Base::getLog()->debug(__METHOD__ . ' generate final rest action list', ['actions' => $actions]);
     return $actions;
 }
示例#10
0
 /**
  * @inheritdoc
  */
 public function executeAction()
 {
     if (!($callback = $this->request->query($this->callbackParam)) && !$this->autoSink) {
         throw new JsonpInvalidParameterException('The required parameter ":param" not found.', [':param' => $this->callbackParam]);
     }
     // 继续执行
     parent::executeAction();
     // 附加上callback
     if ($callback) {
         Base::getLog()->debug(__METHOD__ . ' append callback string', ['callback' => $callback]);
         $this->response->body = $callback . '(' . $this->response->body . ')';
     }
 }
示例#11
0
 /**
  * 执行外部请求,并返回接口
  *
  *     $request->execute();
  *
  * @param  Request  $request
  * @param  Response $response
  * @return Response
  * @throws Exception
  */
 public function executeRequest(Request $request, Response $response)
 {
     $previous = Request::$current;
     Request::$current = $request;
     // 如果post数据了
     if ($post = $request->post()) {
         $request->body = http_build_query($post, null, '&');
         $request->headers('content-type', 'application/x-www-form-urlencoded; charset=' . $request->charset);
     }
     // 如果需要暴露框架信息
     if (Base::$expose) {
         $request->headers('user-agent', Base::version());
     }
     try {
         // 处理header
         $sendHeaders = [];
         if ($headers = $request->headers()) {
             foreach ($headers as $key => $value) {
                 if (is_array($value)) {
                     $value = implode(', ', $value);
                 }
                 $sendHeaders[$key] = $value;
             }
         }
         // 处理cookie
         if ($cookies = $request->cookie()) {
             $sendHeaders['Cookie'] = http_build_query($cookies, null, '; ');
         }
         $url = $request->uri;
         if ($query = $request->query()) {
             $url .= '?' . http_build_query($query, null, '&');
         }
         // 执行请求
         $result = Requests::request($url, $sendHeaders, $request->body, $request->method, $this->options);
         if (!$result->success) {
             throw new RequestException('Error fetching remote :url [ status :code ]', [':url' => $url, ':code' => $result->status_code]);
         }
         foreach ($result->headers as $k => $v) {
             $response->headers($k, $v);
         }
         $response->status = $result->status_code;
         $response->body = $result->body;
     } catch (Exception $e) {
         Request::$current = $previous;
         throw $e;
     }
     Request::$current = $previous;
     return $response;
 }
示例#12
0
文件: Http.php 项目: tourze/bootstrap
 /**
  * 每个请求层,最终被调用的方法
  *
  * @return mixed
  */
 public function handle()
 {
     Base::getLog()->debug(__METHOD__ . ' handle request flow - start');
     $request = new Request($this->flow->contexts['uri']);
     // 上下文
     $this->flow->contexts['request'] = $request;
     // 处理HTTP相关,例如过滤变量,初始化相关设置
     $flow = Flow::instance('tourze-http');
     $flow->contexts =& $this->flow->contexts;
     $flow->layers = ['tourze\\Bootstrap\\Flow\\Http\\Initialization', 'tourze\\Bootstrap\\Flow\\Http\\Authentication', 'tourze\\Bootstrap\\Flow\\Http\\Authorization'];
     $flow->start();
     // 执行请求
     $response = $request->execute();
     echo $response->sendHeaders(true)->body;
     Base::getLog()->debug(__METHOD__ . ' handle request flow - end');
 }
示例#13
0
 /**
  * 处理请求统计
  *
  * @param ConnectionInterface $connection
  * @param string              $data
  * @return bool|void
  */
 public function onMessage($connection, $data)
 {
     Base::getLog()->info(__METHOD__ . ' handle message', $data);
     $data = json_decode($data, true);
     if (empty($data) || !isset($data['cmd'])) {
         Base::getLog()->info(__METHOD__ . ' no cmd param, or the data format is wrong', $data);
         return false;
     }
     // 无法解析的包
     if (empty($data['cmd']) || $data['cmd'] != 'REPORT_IP') {
         return false;
     }
     Base::getLog()->info(__METHOD__ . ' response ok');
     /** @var \Workerman\Connection\ConnectionInterface $connection */
     return $connection->send(json_encode(['result' => 'ok']));
 }
示例#14
0
文件: View.php 项目: tourze/view
 /**
  * {@inheritdoc}
  */
 protected function capture($viewFilename, array $viewData)
 {
     TourzeBase::getLog()->debug(__METHOD__ . ' capture view output', ['file' => $viewFilename]);
     // 导入变量
     extract($viewData, EXTR_SKIP);
     if (!empty(View::$_globalData)) {
         extract(View::$_globalData, EXTR_SKIP | EXTR_REFS);
     }
     ob_start();
     try {
         include $viewFilename;
     } catch (Exception $e) {
         ob_end_clean();
         throw $e;
     }
     // 获取最终内容
     return ob_get_clean();
 }
示例#15
0
 /**
  * 处理请求
  *
  *     $request->execute();
  *
  * @param   Request  $request
  * @param   Response $response
  * @return \tourze\Http\Response
  * @throws \tourze\Base\Exception\BaseException
  */
 public function executeRequest(Request $request, Response $response)
 {
     $className = 'Controller';
     // 控制器
     $controller = $request->controller;
     $className = Inflector::classify($controller) . $className;
     // 目录
     $directory = $request->directory;
     if ($directory) {
         $directory = str_replace('/', '\\', $directory);
         $className = $directory . $className;
     }
     // 保存请求状态
     $previous = Request::$current;
     Request::$current = $request;
     Base::getLog()->info(__METHOD__ . ' controller class', ['class' => $className]);
     try {
         if (!class_exists($className)) {
             Base::getLog()->debug(__METHOD__ . ' class not found', ['class' => $className]);
             throw HttpException::factory(Http::NOT_FOUND, 'The requested URL :uri was not found on this server.', [':uri' => $request->uri])->request($request);
         }
         $class = new ReflectionClass($className);
         if ($class->isAbstract()) {
             Base::getLog()->error(__METHOD__ . ' calling abstract controller class', ['class' => $className]);
             throw new BaseException('Cannot create instances of abstract :controller', [':controller' => $className]);
         }
         $controller = $class->newInstance(['request' => $request, 'response' => $response]);
         $response = $class->getMethod('execute')->invoke($controller);
         if (!$response instanceof Response) {
             Base::getLog()->error(__METHOD__ . ' unknown response type');
             throw new BaseException('Controller failed to return a Response');
         }
     } catch (HttpException $e) {
         if (null === $e->request()) {
             $e->request($request);
         }
         $response = $e->getResponse();
     }
     Request::$current = $previous;
     return $response;
 }
示例#16
0
 public function getStasticLog($module, $interface, $startTime, $endTime, $count = 10)
 {
     $ipList = !empty($_GET['ip']) && is_array($_GET['ip']) ? $_GET['ip'] : Cache::$serverIpList;
     $offsetList = !empty($_GET['offset']) && is_array($_GET['offset']) ? $_GET['offset'] : [];
     $port = Config::load('statServer')->get('providerPort');
     $requestBufferArray = [];
     foreach ($ipList as $key => $ip) {
         $offset = isset($offsetList[$key]) ? $offsetList[$key] : 0;
         $buffer = ['cmd' => 'get-log', 'module' => $module, 'interface' => $interface, 'start_time' => $startTime, 'end_time' => $endTime, 'offset' => $offset, 'count' => $count];
         Base::getLog()->info(__METHOD__ . ' generate buffer fot getting log', $buffer);
         $requestBufferArray["{$ip}:{$port}"] = json_encode($buffer) . "\n";
     }
     $readBufferArray = StatServer::multiRequest($requestBufferArray);
     ksort($readBufferArray);
     foreach ($readBufferArray as $address => $buf) {
         $bodyData = json_decode(trim($buf), true);
         $logData = isset($bodyData['data']) ? $bodyData['data'] : '';
         $offset = isset($bodyData['offset']) ? $bodyData['offset'] : 0;
         $readBufferArray[$address] = ['offset' => $offset, 'data' => $logData];
     }
     return $readBufferArray;
 }
示例#17
0
 /**
  * 上报统计数据
  *
  * @param string $module
  * @param string $interface
  * @param bool   $success
  * @param int    $code
  * @param string $msg
  * @param string $reportAddress
  * @return boolean
  */
 public static function report($module, $interface, $success, $code, $msg, $reportAddress = '')
 {
     // 如果msg是个数组,那么要额外处理转换成字符串
     if (is_array($msg)) {
         // $msg格式为[':message', [':message' => 'TEST']]
         if (count($msg) == 2 && !Arr::isAssoc($msg) && is_array($msg[1])) {
             $msg = __($msg[0], $msg[1]);
         }
     }
     if (strpos($msg, '[ip]') !== false) {
         $msg = str_replace('[ip]', Arr::get($_SERVER, 'REMOTE_ADDR'), $msg);
     }
     if (strpos($msg, '[ua]') !== false) {
         $msg = str_replace('[ua]', Arr::get($_SERVER, 'HTTP_USER_AGENT'), $msg);
     }
     $reportAddress = $reportAddress ? $reportAddress : Config::load('statClient')->get('ip');
     if (isset(self::$timeMap[$module][$interface]) && self::$timeMap[$module][$interface] > 0) {
         $startTime = self::$timeMap[$module][$interface];
         self::$timeMap[$module][$interface] = 0;
     } else {
         if (isset(self::$timeMap['']['']) && self::$timeMap[''][''] > 0) {
             $startTime = self::$timeMap[''][''];
             self::$timeMap[''][''] = 0;
         } else {
             $startTime = microtime(true);
         }
     }
     //echo "\n";
     //echo $startTime . "\n";
     $endTime = microtime(true);
     //echo $endTime . "\n";
     $costTime = $endTime - $startTime;
     //echo $costTime . "\n";
     $binData = Protocol::encode($module, $interface, $costTime, $success, $code, $msg);
     Base::getLog()->debug(__METHOD__ . ' prepare bin data', ['bin' => $binData]);
     return self::sendData($reportAddress, $binData);
 }
示例#18
0
文件: Web.php 项目: rockefys/server
 /**
  * 覆盖原workerman流程,实现更多功能
  * 当接收到完整的http请求后的处理逻辑
  *
  * 1、如果请求的是以php为后缀的文件,则尝试加载
  * 2、如果请求的url没有后缀,则尝试加载对应目录的index.php
  * 3、如果请求的是非php为后缀的文件,尝试读取原始数据并发送
  * 4、如果请求的文件不存在,则返回404
  *
  * @param TcpConnection $connection
  * @param mixed         $data
  * @return mixed
  */
 public function onMessage($connection, $data)
 {
     Base::getLog()->debug(__METHOD__ . ' receive http request', ['uri' => $_SERVER['REQUEST_URI'], 'ip' => $connection->getRemoteIp(), 'port' => $connection->getRemotePort(), 'data' => $data]);
     // 请求的文件
     $urlInfo = parse_url($_SERVER['REQUEST_URI']);
     if (!$urlInfo) {
         Base::getHttp()->header('HTTP/1.1 400 Bad Request');
         Base::getLog()->warning(__METHOD__ . ' receive bad request', ['uri' => $_SERVER['REQUEST_URI'], 'ip' => $connection->getRemoteIp(), 'port' => $connection->getRemotePort()]);
         return $connection->close($this->error400);
     }
     $path = $urlInfo['path'];
     $pathInfo = pathinfo($path);
     $extension = isset($pathInfo['extension']) ? $pathInfo['extension'] : '';
     if ($extension === '') {
         $path = ($len = strlen($path)) && $path[$len - 1] === '/' ? $path . $this->indexFile : $path . '/' . $this->indexFile;
         $extension = 'php';
     }
     $serverName = Arr::get($_SERVER, 'SERVER_NAME');
     $rootDir = isset($this->serverRoot[$serverName]) ? $this->serverRoot[$serverName] : current($this->serverRoot);
     $file = "{$rootDir}/{$path}";
     // 对应的php文件不存在,而且支持rewrite
     if (!is_file($file) && $this->rewrite) {
         $file = is_string($this->rewrite) ? $rootDir . '/' . $this->rewrite : $rootDir . '/' . $this->indexFile;
         $extension = 'php';
         $_SERVER['PATH_INFO'] = $_SERVER['REQUEST_URI'];
     }
     // 请求的文件存在
     if (is_file($file)) {
         Base::getLog()->debug(__METHOD__ . ' request file existed', ['file' => $file, 'extension' => $extension]);
         // 判断是否是站点目录里的文件
         if (!($requestRealPath = realpath($file)) || !($rootDirRealPath = realpath($rootDir)) || 0 !== strpos($requestRealPath, $rootDirRealPath)) {
             Base::getHttp()->header('HTTP/1.1 400 Bad Request');
             Base::getLog()->warning(__METHOD__ . ' receive bad request', ['uri' => $_SERVER['REQUEST_URI'], 'ip' => $connection->getRemoteIp(), 'port' => $connection->getRemotePort()]);
             return $connection->close('<h1>400 Bad Request</h1>');
         }
         $file = realpath($file);
         // 如果请求的是php文件
         // PHP文件需要include
         if ($extension === 'php') {
             Base::getLog()->debug(__METHOD__ . ' handle request', ['uri' => $_SERVER['REQUEST_URI'], 'ip' => $connection->getRemoteIp(), 'port' => $connection->getRemotePort(), 'file' => $file]);
             Base::getLog()->debug(__METHOD__ . ' clean components - start');
             Base::cleanComponents();
             Base::getLog()->debug(__METHOD__ . ' clean components - end');
             $cwd = getcwd();
             chdir($rootDir);
             ini_set('display_errors', 'off');
             // 缓冲输出
             ob_start();
             // 载入php文件
             try {
                 // $_SERVER变量
                 $_SERVER['HOME'] = $_SERVER['DOCUMENT_ROOT'] = dirname($file);
                 $_SERVER['SCRIPT_FILENAME'] = $file;
                 Base::getLog()->debug(__METHOD__ . ' dispatch client info', ['ip' => $_SERVER['REMOTE_ADDR'], 'port' => $_SERVER['REMOTE_PORT']]);
                 include $file;
             } catch (Exception $e) {
                 Base::getLog()->error($e->getMessage(), ['code' => $e->getCode(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
                 // 如果不是exit
                 if ($e->getMessage() != 'jump_exit') {
                     echo $e;
                 }
             }
             Patch::applyShutdownFunction();
             $content = ob_get_clean();
             ini_set('display_errors', 'on');
             $result = $connection->close($content);
             chdir($cwd);
             return $result;
         } else {
             $contentType = Mime::getMimeFromExtension($extension, self::$defaultMimeType);
             Base::getLog()->debug(__METHOD__ . ' get static file content type', ['extension' => $extension, 'contentType' => $contentType]);
             Base::getHttp()->header('Content-Type: ' . $contentType);
             // 获取文件信息
             $info = stat($file);
             $modifiedTime = $info ? date('D, d M Y H:i:s', Arr::get($info, 'mtime')) . ' GMT' : '';
             // 如果有$_SERVER['HTTP_IF_MODIFIED_SINCE']
             if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $info) {
                 // 文件没有更改则直接304
                 if ($modifiedTime === $_SERVER['HTTP_IF_MODIFIED_SINCE']) {
                     Base::getLog()->debug(__METHOD__ . ' no modified, return 304');
                     // 304
                     Base::getHttp()->header('HTTP/1.1 304 Not Modified');
                     // 发送给客户端
                     return $connection->close('');
                 }
             }
             if ($modifiedTime) {
                 Base::getLog()->debug(__METHOD__ . ' set last modified time', ['time' => $modifiedTime]);
                 Base::getHttp()->header("Last-Modified: {$modifiedTime}");
             }
             // 发送给客户端
             return $connection->close(file_get_contents($file));
         }
     } else {
         Base::getLog()->warning(__METHOD__ . ' requested file not found', ['file' => $file]);
         // 404
         Base::getHttp()->header("HTTP/1.1 404 Not Found");
         return $connection->close($this->error404);
     }
 }
示例#19
0
文件: Route.php 项目: tourze/route
 /**
  * 获取指定的路由信息
  *
  *     $route = Route::get('default');
  *
  * @param  string $name 路由名称
  * @return Entry
  * @throws BaseException
  */
 public static function get($name)
 {
     if (!isset(Route::$routeInstances[$name])) {
         Base::getLog()->error(__METHOD__ . ' getting unknown route', ['name' => $name, 'exists' => array_keys(self::$routeInstances)]);
         throw new RouteNotFoundException('The requested route does not exist: :route', [':route' => $name]);
     }
     return Route::$routeInstances[$name];
 }
示例#20
0
文件: Db.php 项目: tourze/db
 /**
  * 单例模式,获取一个指定的实例
  *
  *     // 加载默认实例
  *     $db = Database::instance();
  *
  *     // 指定实例名称和配置
  *     $db = Database::instance('custom', $config);
  *
  * @param  string $name   实例名
  * @param  array  $config 配置参数
  * @return Connection
  */
 public static function instance($name = null, array $config = null)
 {
     if (null === $name) {
         $name = Db::$default;
     }
     if (!isset(Db::$instances[$name])) {
         // 读取配置
         if (null === $config) {
             $config = (array) Config::load(self::$configFile)->get($name);
             Base::getLog()->debug(__METHOD__ . ' get default config', ['name' => $name]);
         }
         // 合并默认配置
         if (isset(self::$defaultConfig[Arr::get($config, 'driver')])) {
             $config = Arr::merge(self::$defaultConfig[Arr::get($config, 'driver')], $config);
             Base::getLog()->debug(__METHOD__ . ' merge config', ['name' => $name]);
         }
         $conn = DriverManager::getConnection($config);
         Base::getLog()->debug(__METHOD__ . ' create dbal connection', ['name' => $name]);
         // 额外注册字段类型
         if (isset(self::$mappingType[Arr::get($config, 'driver')])) {
             $platform = $conn->getDatabasePlatform();
             foreach (self::$mappingType[Arr::get($config, 'driver')] as $dbType => $doctrineType) {
                 if (!$platform->hasDoctrineTypeMappingFor($dbType)) {
                     Base::getLog()->debug(__METHOD__ . ' add dbal mapping type', ['raw' => $dbType, 'dbal' => $doctrineType]);
                     $platform->registerDoctrineTypeMapping($dbType, $doctrineType);
                 }
             }
         }
         Db::$instances[$name] = $conn;
         Base::getLog()->debug(__METHOD__ . ' save db instance', ['name' => $name]);
     }
     return Db::$instances[$name];
 }
示例#21
0
 /**
  * 跳转的助手方法
  *
  * @param  string $uri  要跳转的URI
  * @param  int    $code HTTP状态码
  * @throws HttpException
  */
 public function redirect($uri = '', $code = 302)
 {
     Base::getLog()->debug(__METHOD__ . ' redirect from controller', ['uri' => $uri, 'code' => $code]);
     Base::getHttp()->redirect((string) $uri, $code);
 }
示例#22
0
文件: Model.php 项目: tourze/model
 /**
  * 删除当前记录
  *
  * @throws ModelException
  * @return Model
  */
 public function delete()
 {
     if (!$this->_loaded) {
         throw new ModelException('Cannot delete :model model because it is not loaded.', [':model' => $this->_objectName]);
     }
     Base::getLog()->debug(__METHOD__ . ' delete record');
     $id = $this->pk();
     $this->_db->createQueryBuilder()->delete($this->_tableName)->where($this->_primaryKey . ' = ?')->setParameter(0, $id)->execute();
     return $this->clear();
 }
示例#23
0
<?php

use tourze\Base\Base;
Base::getHttp()->header('Content-Type: text/html');
$str = date('Y-m-d H:i:s');
Base::getSession()->set(date('Y-m-d-H-i'), $str);
echo Base::getSession()->get(date('Y-m-d-H-i'));
echo "<br/>";
echo Base::getSession()->id();
echo "<pre>";
var_dump($_SESSION);
echo "</pre>";
//\tourze\Base\Base::getSession()->destroy();
//Base::getHttp()->end('end.');
示例#24
0
文件: Mail.php 项目: tourze/base
 /**
  * {@inheritdoc}
  */
 public function send($from = null, $to = null, $subject = null, $message = null)
 {
     Base::getLog()->debug(__METHOD__ . ' call send mail method', ['to' => $to, 'subject' => $subject, 'message' => $message, 'from' => $from]);
     if ($to === null) {
         $to = $this->to;
     }
     if ($subject === null) {
         $subject = $this->subject;
     }
     if ($message === null) {
         $message = $this->message;
     }
     if ($from === null) {
         $from = $this->from;
     }
     if (is_array($to)) {
         $to = implode(', ', $to);
     }
     Base::getLog()->debug(__METHOD__ . ' prepare to send mail', ['to' => $to, 'subject' => $subject, 'message' => $message, 'from' => $from]);
     $result = @mail($to, $subject, $message, 'From: ' . $from);
     Base::getLog()->debug(__METHOD__ . ' send mail result', ['result' => $result]);
     $this->to = null;
     $this->subject = null;
     $this->message = null;
     $this->from = null;
     return $result;
 }
示例#25
0
<?php

use tourze\Base\Base;
Base::getHttp()->header('Content-Type: application/json');
tourze\Server\Patch\register_shutdown_function(function () {
    echo microtime(true);
});
示例#26
0
 /**
  * 将当前进程的统计信息写入到统计文件
  *
  * @return void
  */
 protected static function writeStatisticsToStatusFile()
 {
     // 主进程部分
     if (self::$_masterPid === posix_getpid()) {
         $loadAvg = sys_getloadavg();
         file_put_contents(self::$statusFile, "---------------------------------------GLOBAL STATUS--------------------------------------------\n");
         file_put_contents(self::$statusFile, 'Tourze version:' . Base::version() . "          PHP version:" . PHP_VERSION . "\n", FILE_APPEND);
         file_put_contents(self::$statusFile, 'start time:' . date('Y-m-d H:i:s', self::$_globalStatistics['start_timestamp']) . '   run ' . floor((time() - self::$_globalStatistics['start_timestamp']) / (24 * 60 * 60)) . ' days ' . floor((time() - self::$_globalStatistics['start_timestamp']) % (24 * 60 * 60) / (60 * 60)) . " hours   \n", FILE_APPEND);
         file_put_contents(self::$statusFile, 'load average: ' . implode(", ", $loadAvg) . "\n", FILE_APPEND);
         file_put_contents(self::$statusFile, count(self::$_pidMap) . ' workers       ' . count(self::getAllWorkerPids()) . " processes\n", FILE_APPEND);
         file_put_contents(self::$statusFile, str_pad('worker_name', self::$_maxWorkerNameLength) . " exit_status     exit_count\n", FILE_APPEND);
         foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
             $worker = self::$_workers[$worker_id];
             if (isset(self::$_globalStatistics['worker_exit_info'][$worker_id])) {
                 foreach (self::$_globalStatistics['worker_exit_info'][$worker_id] as $worker_exit_status => $worker_exit_count) {
                     file_put_contents(self::$statusFile, str_pad($worker->name, self::$_maxWorkerNameLength) . " " . str_pad($worker_exit_status, 16) . " {$worker_exit_count}\n", FILE_APPEND);
                 }
             } else {
                 file_put_contents(self::$statusFile, str_pad($worker->name, self::$_maxWorkerNameLength) . " " . str_pad(0, 16) . " 0\n", FILE_APPEND);
             }
         }
         file_put_contents(self::$statusFile, "---------------------------------------PROCESS STATUS-------------------------------------------\n", FILE_APPEND);
         file_put_contents(self::$statusFile, "pid\tmemory  " . str_pad('listening', self::$_maxSocketNameLength) . " " . str_pad('worker_name', self::$_maxWorkerNameLength) . " connections " . str_pad('total_request', 13) . " " . str_pad('send_fail', 9) . " " . str_pad('throw_exception', 15) . "\n", FILE_APPEND);
         chmod(self::$statusFile, 0722);
         foreach (self::getAllWorkerPids() as $worker_pid) {
             posix_kill($worker_pid, SIGUSR2);
         }
         return;
     }
     // 子进程部分
     $worker = current(self::$_workers);
     $statusStr = posix_getpid() . "\t" . str_pad(round(memory_get_usage(true) / (1024 * 1024), 2) . "M", 7) . " " . str_pad($worker->getSocketName(), self::$_maxSocketNameLength) . " " . str_pad($worker->name === $worker->getSocketName() ? 'none' : $worker->name, self::$_maxWorkerNameLength) . " ";
     $statusStr .= str_pad(ConnectionInterface::$statistics['connection_count'], 11) . " " . str_pad(ConnectionInterface::$statistics['total_request'], 14) . " " . str_pad(ConnectionInterface::$statistics['send_fail'], 9) . " " . str_pad(ConnectionInterface::$statistics['throw_exception'], 15) . "\n";
     file_put_contents(self::$statusFile, $statusStr, FILE_APPEND);
 }
示例#27
0
<?php

use tourze\Base\Base;
Base::getHttp()->setCookie(date('Y-m-d-H-i-s'), microtime(true));
?>
<pre><?php 
print_r($_COOKIE);
?>
</pre>

示例#28
0
文件: BaseTest.php 项目: tourze/base
 /**
  * 检测load方法的结果是否正确
  *
  * @dataProvider providerLoad
  * @param string $path
  * @param mixed  $result
  */
 public function testLoad($path, $result)
 {
     $this->assertEquals($result, Base::load($path));
 }
示例#29
0
文件: Entry.php 项目: tourze/route
 /**
  * 传入参数,生成当前路由的uri
  *
  * @param  array $params URI参数
  * @return string
  * @throws RouteException
  */
 public function uri(array $params = null)
 {
     $defaults = $this->_defaults;
     if (isset($params['controller'])) {
         $params['controller'] = strtolower($params['controller']);
     }
     if (isset($params['directory'])) {
         $params['directory'] = strtolower($params['directory']);
     }
     /**
      * 匿名函数,用于循环替换路由参数
      *
      * @param  string  $portion  URI定义部分
      * @param  boolean $required 参数是否必须的
      * @return array 返回保存参数的数组
      * @throws RouteException
      */
     $compile = function ($portion, $required) use(&$compile, $defaults, $params) {
         $missing = [];
         $pattern = '#(?:' . Route::REGEX_KEY . '|' . Route::REGEX_GROUP . ')#';
         $result = preg_replace_callback($pattern, function ($matches) use(&$compile, $defaults, &$missing, $params, &$required) {
             if ('<' === $matches[0][0]) {
                 $param = $matches[1];
                 if (isset($params[$param])) {
                     $required = $required || !isset($defaults[$param]) || $params[$param] !== $defaults[$param];
                     return $params[$param];
                 }
                 // 直接返回参数默认值
                 if (isset($defaults[$param])) {
                     return $defaults[$param];
                 }
                 $missing[] = $param;
             } else {
                 $result = $compile($matches[2], false);
                 if ($result[1]) {
                     $required = true;
                     return $result[0];
                 }
             }
             return null;
         }, $portion);
         if ($required && $missing) {
             throw new RouteException('Required route parameter not passed: :param', [':param' => reset($missing)]);
         }
         return [$result, $required];
     };
     $result = $compile($this->_uri, true);
     Base::getLog()->debug(__METHOD__ . ' get route compile result', ['identify' => $this->identify, 'result' => $result]);
     $uri = $result ? array_shift($result) : $result;
     // 过滤URI中的重复斜杆
     $uri = preg_replace('#//+#', '/', rtrim($uri, '/'));
     // 如果是外部链接
     if ($this->isExternal()) {
         $host = $this->_defaults['host'];
         // 使用默认协议
         if (false === strpos($host, '://')) {
             $host = Route::$defaultProtocol . $host;
         }
         $uri = rtrim($host, '/') . '/' . $uri;
     }
     return $uri;
 }
示例#30
0
文件: Cache.php 项目: tourze/base
 /**
  * {@inheritdoc}
  */
 public function remove($name)
 {
     Base::getLog()->debug(__METHOD__ . ' remove cache', ['name' => $name]);
     unset($this->_cache[$name]);
     unset($this->_cacheHit[$name]);
     return true;
 }