Ejemplo n.º 1
1
 public function start($option = [])
 {
     if ($this->session instanceof Session) {
         $this->session->start();
     }
     $jobs = [];
     try {
         $option['job'] = function ($job) use(&$jobs) {
             $jobs[] = $job;
         };
         $this->main($option);
     } catch (Redirect $e) {
         $this->response->redirect($e->getLocation(), $e->getCode());
     } catch (Error $e) {
         $this->respondError($e);
     } catch (\Exception $e) {
         $this->respondError(new Error(500, [], $e));
     } finally {
         if ($this->session instanceof Session) {
             $this->session->clear();
             $this->session->writeClose();
         }
     }
     flush();
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     }
     foreach ($jobs as $job) {
         $job();
     }
 }
Ejemplo n.º 2
1
 static function _start()
 {
     if (self::_flushOutputBuffers()) {
         if (function_exists('fastcgi_finish_request')) {
             fastcgi_finish_request();
         } else {
             flush();
         }
     }
     ob_start(self::$class . '_checkOutputBuffer');
     self::register(self::$class . '_end');
 }
Ejemplo n.º 3
1
Archivo: Log.php Proyecto: sysuyc/phpio
 function stop()
 {
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     }
     $last_error = error_get_last();
     if (is_array($last_error)) {
         call_user_func_array(array(PHPIO::$hooks['Error'], '_error_handler'), $last_error);
     }
     ini_set("aop.enable", "0");
     $this->start = false;
 }
Ejemplo n.º 4
0
function log_error($param)
{
    $logdir = APP_ROOT . APP_DIR . '/webroot/data/logs/';
    if (!is_dir($logdir)) {
        return;
    }
    $error = error_get_last();
    function_exists('fastcgi_finish_request') && fastcgi_finish_request();
    if (!is_array($error) || !in_array($error['type'], array(E_ERROR, E_COMPILE_ERROR, E_CORE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR))) {
        return;
    }
    $error = '';
    $error .= date('Y-m-d H:i:s') . '--';
    //$error .= 'Type:' . $error['type'] . '--';
    $error .= 'Msg:' . $error['message'] . '--';
    $error .= 'File:' . $error['file'] . '--';
    $error .= 'Line:' . $error['line'] . '--';
    $error .= 'Ip:' . (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0') . '--';
    $error .= 'Uri:' . (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '') . '--';
    $error .= empty($_SERVER['CONTENT_TYPE']) ? '' : 'Content-Type:' . $_SERVER['CONTENT_TYPE'] . '--';
    $error .= $_SERVER['REQUEST_METHOD'] . $_SERVER['REQUEST_URI'];
    $error .= '<br/>';
    $size = file_exists($file) ? @filesize($file) : 0;
    file_put_contents($logdir . $param['file'], $error, $size < $param['maxsize'] ? FILE_APPEND : null);
}
Ejemplo n.º 5
0
 public function send()
 {
     Hook::triggerAction('response.before_send', array(&$this));
     $this->sendHeaders();
     $this->sendContent();
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     } elseif ('cli' !== PHP_SAPI) {
         // ob_get_level() never returns 0 on some Windows configurations, so if
         // the level is the same two times in a row, the loop should be stopped.
         $previous = null;
         $obStatus = ob_get_status(1);
         while (($level = ob_get_level()) > 0 && $level !== $previous) {
             $previous = $level;
             if ($obStatus[$level - 1]) {
                 if (version_compare(PHP_VERSION, '5.4', '>=')) {
                     if (isset($obStatus[$level - 1]['flags']) && $obStatus[$level - 1]['flags'] & PHP_OUTPUT_HANDLER_REMOVABLE) {
                         ob_end_flush();
                     }
                 } else {
                     if (isset($obStatus[$level - 1]['del']) && $obStatus[$level - 1]['del']) {
                         ob_end_flush();
                     }
                 }
             }
         }
         flush();
     }
     Hook::triggerAction('response.after_send', array(&$this));
     return $this;
 }
 public function startExecution(Executable $manager)
 {
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     }
     parent::startExecution($manager);
 }
Ejemplo n.º 7
0
 /**
  * Call
  */
 public function call()
 {
     $this->next->call();
     //Fetch status, header, and body
     list($status, $headers, $body) = $this->app->response->result();
     //Send headers
     if (headers_sent() === false) {
         if ('cli' == $this->app->sapi_type) {
             header(sprintf('Status: %s', $status));
         } else {
             header(sprintf('HTTP/%s %s', '1.1', $status));
         }
         foreach ($headers as $name => $value) {
             $hValues = explode("\n", $value);
             foreach ($hValues as $hVal) {
                 header("{$name}: {$hVal}", false);
             }
         }
     }
     echo $this->app->view->format($body);
     //fastcgi
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     }
     $module = $this->app->module;
     if ($module && method_exists($module, 'asyncJob')) {
         $module->asyncJob();
     }
 }
Ejemplo n.º 8
0
 /**
  * Single shot defer handeler install
  */
 protected static function install_shutdown()
 {
     if (static::$inited_shutdown) {
         return;
     }
     // Disable time limit
     set_time_limit(0);
     // HHVM support
     if (function_exists('register_postsend_function')) {
         register_postsend_function(function () {
             Event::trigger('core.shutdown');
         });
     } else {
         if (function_exists('fastcgi_finish_request')) {
             register_shutdown_function(function () {
                 fastcgi_finish_request();
                 Event::trigger('core.shutdown');
             });
         } else {
             register_shutdown_function(function () {
                 Event::trigger('core.shutdown');
             });
         }
     }
     static::$inited_shutdown = true;
 }
Ejemplo n.º 9
0
 public function handleRequest()
 {
     ini_set('display_errors', '0');
     $as = new \FutoIn\RI\ScopedSteps();
     $as->add(function ($as) {
         $reqinfo = $this->getBaseRequestInfo($as);
         $this->configureRequestInfo($as, $reqinfo);
         $as->reqinfo = $reqinfo;
         $this->process($as);
         $as->add(function ($as) {
             $reqinfo = $as->reqinfo;
             $reqinfo_info = $reqinfo->info();
             if (!is_null($reqinfo_info->{RequestInfo::INFO_RAW_RESPONSE})) {
                 header('Content-Type: application/futoin+json');
                 echo $reqinfo_info->{RequestInfo::INFO_RAW_RESPONSE};
             }
             if (function_exists('fastcgi_finish_request')) {
                 fastcgi_finish_request();
             }
             $as->success();
         });
     }, function ($as, $err) {
         error_log("{$err}: " . $as->error_info);
         http_response_code(500);
         header('Content-Type: application/futoin+json');
         echo '{"e":"InvalidRequest"}';
     });
     $as->run();
 }
Ejemplo n.º 10
0
 public function generateAndMatchMidi(Request $request)
 {
     echo 'true';
     // =======这部分是将输出内容刷新到用户浏览器并断开和浏览器的连接=====
     // 如果使用的是php-fpm
     if (function_exists('fastcgi_finish_request')) {
         // 刷新buffer
         ob_flush();
         flush();
         // 断开浏览器连接
         fastcgi_finish_request();
     }
     // ========下面是后台要继续执行的内容========
     // 查看midi是否已经存在
     $midi_exists = self::midiExists($request);
     Log::info('[查询 midi是否生成] ' . $midi_exists);
     // 若midi不存在,执行wav转midi, 否则执行匹配midi
     if ($midi_exists == 'false') {
         Log::info('[转换 midi] ' . $request->uid . '/' . $request->pid . '/' . $request->wav);
         // wav转midi
         $this->midiIsGenerated($request);
     } else {
         Log::info('[匹配 midi] ' . $request->uid . '/' . $request->pid . '/' . $request->wav);
         // 匹配midi
         self::matchMidi($request);
     }
 }
Ejemplo n.º 11
0
 public function track()
 {
     $url = 'www.google-analytics.com';
     $page = '/collect';
     $googleip = $this->memcacheget('googleip');
     if (empty($googleip)) {
         $googleip = gethostbyname($url);
         $this->memcacheset('googleip', $googleip, 3600);
     }
     //set POST variables
     if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
         $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
     }
     $fields = array('v' => '1', 'tid' => $this->GA_ID, 'cid' => $this->gaParseCookie(), 't' => 'pageview', 'cm' => $_GET["api_key"], 'dr' => $this->project_url, 'cs' => $this->project, 'dh' => 'webservice.fanart.tv', 'dp' => $this->ttype . '/' . $this->tid, 'uip' => $_SERVER['REMOTE_ADDR'], 'ua' => $_SERVER['HTTP_USER_AGENT']);
     $fields_string = http_build_query($fields);
     //die($this->myfunc_getIP($url));
     $fp = fsockopen($googleip, 80, $errno, $errstr, 5);
     //$fp = fsockopen($url, 80, $errno, $errstr, 5);
     stream_set_blocking($fp, 0);
     stream_set_timeout($fp, 5);
     $output = "POST http://" . $url . $page . " HTTP/1.1\r\n";
     $output .= "Host: {$url}\r\n";
     $output .= "Content-Length: " . strlen($fields_string) . "\r\n";
     $output .= "Connection: close\r\n\r\n";
     $output .= $fields_string;
     //die($output);
     fastcgi_finish_request();
     $sentData = 0;
     $toBeSentData = strlen($output);
     while ($sentData < $toBeSentData) {
         $sentData += fwrite($fp, $output);
     }
     fclose($fp);
 }
Ejemplo n.º 12
0
function xhprof_shutdown()
{
    global $xhprofMainConfig;
    $xhprof_data = xhprof_disable();
    if (function_exists('fastcgi_finish_request')) {
        fastcgi_finish_request();
    }
    try {
        require_once __DIR__ . '/../xhprof/classes/data.php';
        $xhprof_data_obj = new \ay\xhprof\Data($xhprofMainConfig['pdo']);
        $xhprof_data_obj->save($xhprof_data);
    } catch (Exception $e) {
        // old php versions don't like Exceptions in shutdown functions
        // -> log them to have some usefull info in the php-log
        if (PHP_VERSION_ID < 504000) {
            if (function_exists('log_exception')) {
                log_exception($e);
            } else {
                error_log($e->__toString());
            }
        }
        // re-throw to show the caller something went wrong
        throw $e;
    }
}
Ejemplo n.º 13
0
 public static function finishExecution()
 {
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     } else {
         exit(0);
     }
 }
Ejemplo n.º 14
0
 /**
  * Try to create a zombie.
  *
  * @return  bool
  */
 public static function fork()
 {
     if (true !== static::test()) {
         throw new Exception('This program must run behind PHP-FPM to create a zombie.', 0);
     }
     fastcgi_finish_request();
     return true;
 }
Ejemplo n.º 15
0
 /**
  * 处理器入口
  *
  * @access public static
  * @return void
  */
 public static function run($ini, $url, $post = null)
 {
     $dsp = new self($ini);
     $dsp->dispach($url, $post);
     if (empty($GLOBALS['__in_debug_tools']) && function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     }
 }
Ejemplo n.º 16
0
 function finish()
 {
     Assert::isFalse($this->isFinished, 'already finished');
     $this->isFinished = true;
     // http://php-fpm.anight.org/extra_features.html
     // TODO: cut out this functionality to the outer class descendant (e.g., PhpFpmResponse)
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     }
 }
Ejemplo n.º 17
0
 public function send()
 {
     $this->sendHeaders();
     $this->sendBody();
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     } elseif ('cli' !== PHP_SAPI) {
         static::closeOutputBuffers(0, true);
     }
     return $this;
 }
Ejemplo n.º 18
0
 public function __construct($config = [])
 {
     parent::__construct($config);
     register_shutdown_function(function () {
         if ($this->_promises) {
             if (function_exists('\\fastcgi_finish_request')) {
                 \fastcgi_finish_request();
             }
             P\inspect_all($this->_promises);
         }
     });
 }
Ejemplo n.º 19
0
 /**
  * call event when you need.
  */
 public static function call()
 {
     if (!SsdPHP::isDebug()) {
         $ISCGI = 0 === strpos(PHP_SAPI, 'cgi') || false !== strpos(PHP_SAPI, 'fcgi') ? true : false;
         /* 冲刷(flush)所有响应的数据给客户端并结束请求。 这使得客户端结束连接后,需要大量时间运行的任务能够继续运行 */
         $ISCGI && fastcgi_finish_request();
     }
     foreach (self::$_events as $event) {
         $callback = array_shift($event);
         call_user_func_array($callback, $event);
     }
 }
Ejemplo n.º 20
0
 /**
  * Register function for exit.
  *
  * @return void
  */
 public static function register()
 {
     static::$_isRegistered = true;
     register_shutdown_function(function () {
         if (static::$_promise) {
             if (function_exists('\\fastcgi_finish_request')) {
                 \fastcgi_finish_request();
             }
             \GuzzleHttp\Promise\inspect_all(static::$_promises);
         }
     });
 }
 static function _start()
 {
     // See http://bugs.php.net/54114
     while (ob_get_level() && ob_end_flush()) {
     }
     ob_start(array(self::$class, '_checkOutputBuffer'));
     /**/
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     }
     self::register(array(self::$class, '_end'));
 }
Ejemplo n.º 22
0
 public function send()
 {
     $this->sendHeaders();
     $this->sendContent();
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     } elseif ('cli' !== PHP_SAPI) {
         ob_end_flush();
         flush();
     }
     return $this;
 }
Ejemplo n.º 23
0
 public function endOutput()
 {
     if (!$this->finishResponse) {
         return;
     }
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     } else {
         ob_start(function () {
             return '';
         });
     }
 }
Ejemplo n.º 24
0
 /**
  * @param array $logs
  */
 protected function processLogs($logs)
 {
     if ($this->finishRequest && function_exists('fastcgi_finish_request')) {
         session_write_close();
         fastcgi_finish_request();
     }
     $ch = $this->initCurl();
     foreach ($logs as $log) {
         $data = json_encode($this->formatLogMessage($log[0], $log[1], $log[2], $log[3]), JSON_FORCE_OBJECT);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
         curl_exec($ch);
     }
 }
Ejemplo n.º 25
0
 public function send()
 {
     $this->sendHeaders();
     if (!empty($this->viewHandle)) {
         $handle = $this->viewHandle;
         $handle();
     } else {
         echo $this->content;
     }
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     }
 }
Ejemplo n.º 26
0
 public function goBackground()
 {
     ini_set('max_execution_time', 0);
     ini_set('ignore_user_abort', 'On');
     session_write_close();
     echo json_encode(array('success' => true));
     echo ob_get_clean();
     flush();
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     }
     ob_start();
 }
Ejemplo n.º 27
0
 /**
  * @return void
  */
 public function send(ResponseInterface $response)
 {
     header(sprintf('HTTP/%s %s %s', $response->protocolVersion(), $response->statusCode(), $response->reasonPhrase()));
     if (!$response->headers()->has('date')) {
         header((string) new Date(new DateValue(new \DateTime())));
     }
     foreach ($response->headers() as $header) {
         header((string) $header, false);
     }
     echo (string) $response->body();
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     }
 }
Ejemplo n.º 28
0
 /**
  * @param \DOMDocument $xml
  * @param bool|string $specificInstance
  * @param bool $dontEcho
  * @param bool $dontFillXML
  * @param bool $normalize
  * @return bool|string
  * @throws Exception
  */
 public static function render(&$xml, $specificInstance = false, $dontEcho = false, $dontFillXML = false, $normalize = true)
 {
     if ($specificInstance) {
         $instance = $specificInstance;
     } elseif (self::$instance) {
         $instance = self::$instance;
     } else {
         $instance = 'main';
     }
     Debugger::addLine("Render start (instance '{$instance}')");
     if (!($resource = Resourcer::getInstance('xslt')->compile($instance))) {
         throw new Exception("XSLT resource not found");
     }
     $xslDom = new \DomDocument();
     $xslDom->resolveExternals = true;
     $xslDom->substituteEntities = true;
     if (!$xslDom->loadXML($resource)) {
         throw new Exception("XSLT load problem for instance '{$instance}'");
     }
     $xslProcessor = new \XSLTProcessor();
     $xslProcessor->importStylesheet($xslDom);
     if (!$dontFillXML and !HttpError::$error and !Debugger::$shutdown) {
         View\XML::fillXML($xml, $instance);
     }
     // transform template
     if ($html = $xslProcessor->transformToDoc($xml)) {
         if ($normalize) {
             $html = self::normalize($html);
         } else {
             $html->formatOutput = true;
             $html = $html->saveXML();
         }
         if ($dontEcho) {
             return $html;
         }
         echo $html;
         self::$rendered = true;
         if (Debugger::isEnabled()) {
             echo '<!-- Page rendered in ' . Debugger::getTimer() . ' seconds -->';
         }
         if (function_exists('fastcgi_finish_request')) {
             fastcgi_finish_request();
         }
     } else {
         $errormsg = libxml_get_errors();
         //error_get_last();
         throw new Exception($errormsg ? $errormsg['message'] : "Can't render templates");
     }
     return true;
 }
Ejemplo n.º 29
0
 /**
  * 执行请求
  * @param array $params 请求的参数数组
  * @throws \Sky\base\HttpException
  */
 public function run($params)
 {
     $controller = $this->getController();
     if (isset($_REQUEST['ws'])) {
         $methodName = 'action' . $this->getId();
         $method = new \ReflectionMethod($controller, $methodName);
         $useParamName = \Sky\Sky::$app->getUrlManager()->useParamName;
         if ($method->getNumberOfParameters() > 0) {
             if (isset($useParamName) && $useParamName === true) {
                 $result = $this->runWithParamsInternal($controller, $method, $params);
             } else {
                 $result = $this->runWithParamsOuter($controller, $method, $params);
             }
         } else {
             $result = $this->runInternal($controller, $methodName);
         }
         return $result;
         // 			if($result==false){
         // 				throw new \Sky\base\HttpException(400,'Your request is invalid.'/*.ob_get_clean()*/);
         // 			}else{
         // 				if ($controller->rawOutput) {
         // 					echo self::encode($this->getActionOutput());
         // 				}else{
         // 					if(!headers_sent())
         // 						header('Content-Type: application/json;charset=utf-8');
         // 					echo \Sky\help\JSON::encode($this->getActionOutput());
         // 				}
         // 			}
     } else {
         if ($this->id === $this->wsdl) {
             $_REQUEST['IsWsdlRequest'] = true;
         }
         $provider = $controller;
         // 			$namespace=\Sky\Sky::$app->getRequest()->getBaseUrl();
         if (($module = \Sky\Sky::$app->controller->module) === null) {
             $namespace = ltrim(\Sky\Sky::$app->getRequest()->getBaseUrl(), '\\/');
         } else {
             $namespace = $module->name;
             if (($pos = strrpos($module->name, '\\')) !== false) {
                 $namespace = substr($module->name, $pos + 1);
             }
         }
         $this->_service = new WebService($provider, $namespace);
         $this->_service->renderWsdl();
     }
     if (function_exists('fastcgi_finish_request')) {
         fastcgi_finish_request();
     }
     \Sky\Sky::$app->end();
 }
Ejemplo n.º 30
0
 /**
  * @acl access public
  */
 public function preview()
 {
     try {
         $post = $this->getBodyParams();
         if (empty($post) || empty($post['referencePoints'])) {
             throw new Exception('No reference points found.', 404);
         }
         if (count($post['referencePoints']) < 3) {
             throw new Exception('Not enough reference points. Minimum number of reference points required are 3.', 404);
         }
         if (empty($post['image'])) {
             throw new Exception('No image found.', 404);
         }
         if (empty($post['storeName'])) {
             throw new Exception('No store name found.', 404);
         }
         $appConfig = $this->getDI()->get(Application::DI_CONFIG);
         if (!is_file('/assets/images/' . $post['storeName'] . '_geo_warp.' . $appConfig['gdal']['fileExtension'])) {
             register_shutdown_function([$this, 'gdalConvert'], $post);
             ignore_user_abort(true);
             header('Content-Length: 0');
             header('Connection: close');
             header('Content-Encoding: none');
             header('Content-Type: application/json');
             header('Access-Control-Allow-Credentials: true');
             header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
             header('Access-Control-Allow-Headers: Accept, Accept-Encoding, Accept-Language, Authorization, Cache-Control, Content-Type, X-Requested-With');
             if (isset($appConfig['cors'])) {
                 $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
                 $origins = explode(';', $appConfig['cors']);
                 $origins = array_map('trim', $origins);
                 if (in_array($origin, $origins)) {
                     header('Access-Control-Allow-Origin: ' . $origin);
                 }
             } else {
                 header('Access-Control-Allow-Origin: *');
             }
             ob_end_flush();
             ob_flush();
             flush();
             //                session_write_close();
             fastcgi_finish_request();
             die;
         }
         return ['store' => $post['storeName']];
     } catch (Exception $ex) {
         return $ex->getMessage();
     }
 }