コード例 #1
0
function file_force_download($file)
{
    if (file_exists($file)) {
        // сбрасываем буфер вывода PHP, чтобы избежать переполнения памяти выделенной под скрипт
        // если этого не сделать файл будет читаться в память полностью!
        if (ob_get_level()) {
            ob_end_clean();
        }
        // заставляем браузер показать окно сохранения файла
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename=' . basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        // читаем файл и отправляем его пользователю
        if ($fd = fopen($file, 'rb')) {
            while (!feof($fd)) {
                print fread($fd, 1024);
            }
            fclose($fd);
        }
        exit;
    }
}
コード例 #2
0
ファイル: comet.php プロジェクト: abbra/midcom
 public function action_messages($route_id, &$data, $args)
 {
     $uimessages = $_MIDCOM->serviceloader->load('uimessages');
     if (!$uimessages->supports('comet') || !$uimessages->can_view()) {
         return;
     }
     $type = null;
     $name = null;
     if (isset($_MIDCOM->dispatcher->get["cometType"])) {
         $type = $_MIDCOM->dispatcher->get["cometType"];
     }
     if (isset($_MIDCOM->dispatcher->get["cometName"])) {
         $name = $_MIDCOM->dispatcher->get["cometName"];
     }
     if ($type == null && $name == null) {
         throw new midcom_exception_notfound("No comet name or type defined");
     }
     if (ob_get_level() == 0) {
         ob_start();
     }
     while (true) {
         $messages = '';
         if ($uimessages->has_messages()) {
             $messages = $uimessages->render_as('comet');
         } else {
             $uimessages->add(array('title' => 'Otsikko from comet', 'message' => 'viesti from comet...'));
         }
         midcom_core_helpers_comet::pushdata($messages, $type, $name);
         ob_flush();
         flush();
         sleep(5);
     }
     // $data['messages'] = $messages;
 }
コード例 #3
0
 public function handle($e)
 {
     $app = App::getInstance();
     while (ob_get_level() > 0) {
         ob_end_clean();
     }
     // header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
     if ($app->config('bono.debug') !== true) {
         if (isset($app->response)) {
             $app->response->setStatus(500);
         }
         if (isset($app->theme)) {
             $view = $app->theme->getView();
             $errorTemplate = 'error';
         } else {
             $view = new View();
             $errorTemplate = '../templates/error.php';
             if (is_readable($errorTemplate)) {
                 $view->setTemplatesDirectory('.');
             }
         }
         return $view->display($errorTemplate, array('error' => $e), 500);
     }
     return call_user_func_array(array($app->whoops, Run::EXCEPTION_HANDLER), func_get_args());
 }
コード例 #4
0
ファイル: queue.php プロジェクト: Maplecms/shopnc-api
 public function indexOp()
 {
     if (ob_get_level()) {
         ob_end_clean();
     }
     $logic_queue = Logic('queue');
     $worker = new QueueServer();
     $queues = $worker->scan();
     while (true) {
         $content = $worker->pop($queues, 1800);
         if (is_array($content)) {
             $method = key($content);
             $arg = current($content);
             $result = $logic_queue->{$method}($arg);
             if (!$result['state']) {
                 $this->log($result['msg'], false);
             }
             //                 echo date('Y-m-d H:i:s',time()).' '.$method."\n";
             //                 flush();
             //                 ob_flush();
         } else {
             $model = Model();
             $model->checkActive();
             unset($model);
             //                 echo date('Y-m-d H:i:s',time())."  ---\n";
             //                 flush();
             //                 ob_flush();
         }
     }
 }
コード例 #5
0
 /**
  * This function could be used eventually to support more modes.
  *
  * @return integer  the output buffer mode
  */
 private function _getMode()
 {
     $mode = 0;
     if ($GLOBALS['cfg']['OBGzip'] && function_exists('ob_start')) {
         if (ini_get('output_handler') == 'ob_gzhandler') {
             // If a user sets the output_handler in php.ini to ob_gzhandler, then
             // any right frame file in phpMyAdmin will not be handled properly by
             // the browser. My fix was to check the ini file within the
             // PMA_outBufferModeGet() function.
             $mode = 0;
         } elseif (function_exists('ob_get_level') && ob_get_level() > 0) {
             // If output buffering is enabled in php.ini it's not possible to
             // add the ob_gzhandler without a warning message from php 4.3.0.
             // Being better safe than sorry, check for any existing output handler
             // instead of just checking the 'output_buffering' setting.
             $mode = 0;
         } else {
             $mode = 1;
         }
     }
     // Zero (0) is no mode or in other words output buffering is OFF.
     // Follow 2^0, 2^1, 2^2, 2^3 type values for the modes.
     // Usefull if we ever decide to combine modes.  Then a bitmask field of
     // the sum of all modes will be the natural choice.
     return $mode;
 }
コード例 #6
0
 public function createImageKey($user, $dblink)
 {
     if ($stm = $dblink->prepare("SELECT 2fa_imgname FROM  " . TABLE_USERS . " WHERE email = ?")) {
         $stm->execute(array($user));
         $row = $stm->fetch();
         $stm = NULL;
         $file = 'uploads/2fa/' . $row['2fa_imgname'];
     }
     $im = new Image();
     $imageclean = $im->loadLocalFile($file);
     $imagekey = $im->embedStegoKey($imageclean);
     $stegoKey = $im->stegoKey;
     $hash = password_hash($stegoKey, PASSWORD_DEFAULT);
     if ($stm = $dblink->prepare("UPDATE " . TABLE_USERS . " SET 2fa_hash = ? WHERE email = ?")) {
         $stm->execute(array($hash, $user));
         $stm = NULL;
     }
     if (ob_get_level()) {
         ob_end_clean();
     }
     header('Content-Description: File Transfer');
     header('Content-Type: application/octet-stream');
     header('Content-Disposition: attachment; filename=KeyImage.png');
     header('Content-Transfer-Encoding: binary');
     header('Expires: 0');
     header('Cache-Control: must-revalidate');
     header('Pragma: public');
     //header('Content-Length: ' . filesize($file));
     $ok = imagepng($imagekey);
     //, NULL, 9
     imagedestroy($imagekey);
     return $ok;
 }
コード例 #7
0
ファイル: PhpEngine.php プロジェクト: anctemarry27/cogs
 /**
  * Handle a view exception.
  *
  * @param  \Exception  $e
  * @param  int  $obLevel
  * @return void
  *
  * @throws $e
  */
 protected function handleViewException(Exception $e, $obLevel)
 {
     while (ob_get_level() > $obLevel) {
         ob_end_clean();
     }
     throw $e;
 }
コード例 #8
0
ファイル: __init_script__.php プロジェクト: rwray/libphutil
function __phutil_init_script__()
{
    // Adjust the runtime language configuration to be reasonable and inline with
    // expectations. We do this first, then load libraries.
    // There may be some kind of auto-prepend script configured which starts an
    // output buffer. Discard any such output buffers so messages can be sent to
    // stdout (if a user wants to capture output from a script, there are a large
    // number of ways they can accomplish it legitimately; historically, we ran
    // into this on only one install which had some bizarre configuration, but it
    // was difficult to diagnose because the symptom is "no messages of any
    // kind").
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
    error_reporting(E_ALL | E_STRICT);
    $config_map = array('display_errors' => true, 'log_errors' => true, 'error_log' => null, 'xdebug.max_nesting_level' => null, 'memory_limit' => -1);
    foreach ($config_map as $config_key => $config_value) {
        ini_set($config_key, $config_value);
    }
    if (!ini_get('date.timezone')) {
        // If the timezone isn't set, PHP issues a warning whenever you try to parse
        // a date (like those from Git or Mercurial logs), even if the date contains
        // timezone information (like "PST" or "-0700") which makes the
        // environmental timezone setting is completely irrelevant. We never rely on
        // the system timezone setting in any capacity, so prevent PHP from flipping
        // out by setting it to a safe default (UTC) if it isn't set to some other
        // value.
        date_default_timezone_set('UTC');
    }
    // Now, load libphutil.
    $root = dirname(dirname(__FILE__));
    require_once $root . '/src/__phutil_library_init__.php';
}
コード例 #9
0
ファイル: console.php プロジェクト: jcs/halfmoon
 public function __construct($args)
 {
     $this->args = $args;
     Console::$have_readline = function_exists("readline");
     for ($x = 1; $x < count($args); $x++) {
         switch ($args[$x]) {
             case "-h":
             case "--help":
                 $this->usage();
                 break;
             default:
                 if (substr($args[$x], 0, 1) == "-") {
                     $this->usage();
                 } elseif (defined("HALFMOON_ENV")) {
                     $this->usage();
                 } else {
                     define("HALFMOON_ENV", $args[$x]);
                 }
         }
     }
     require_once __DIR__ . "/../halfmoon.php";
     error_reporting(E_ALL | E_STRICT);
     ini_set("error_log", NULL);
     ini_set("log_errors", 1);
     ini_set("html_errors", 0);
     ini_set("display_errors", 0);
     while (ob_get_level()) {
         ob_end_clean();
     }
     ob_implicit_flush(true);
     /* TODO: forcibly load models so they're in the tab-completion cache */
     print "Loaded " . HALFMOON_ENV . " environment (halfmoon)\n";
     $this->loop();
 }
コード例 #10
0
 /**
  * Renders the main content of the view.
  * The content is divided into sections, such as summary, items, pager.
  * Each section is rendered by a method named as "renderXyz", where "Xyz" is the section name.
  * The rendering results will replace the corresponding placeholders in {@link template}.
  */
 public function renderContent()
 {
     if ($this->disableBuffering) {
         while (ob_get_level()) {
             ob_end_clean();
         }
     }
     if (!$this->disableHttpHeaders) {
         if ($this->mimetype) {
             header('Content-Type: ' . $this->mimetype . '; charset=' . ($this->encoding === null ? 'utf-8' : $this->encoding));
         }
         if ($this->filename !== null && strlen($this->filename) > 0) {
             $filename = $this->filename;
             if ($this->fileExt !== null && strlen($this->fileExt) > 0) {
                 $filename .= date('_U_Ymd.') . $this->fileExt;
             }
             header('Content-Disposition: attachment; filename="' . $filename . '"');
         }
         header('Pragma: no-cache');
         header('Expires: 0');
     }
     $this->renderItems();
     if (!$this->disableHttpHeaders) {
         Yii::app()->end();
     }
 }
コード例 #11
0
 /**
  * starts new clean output buffer
  *
  * @access  public
  *
  * @author  patrick.kracht
  */
 public function clean_ob()
 {
     if (!ob_get_length() || !ob_get_level()) {
         ob_start();
     }
     session_cache_limiter('must-revalidate');
 }
コード例 #12
0
 /**
  * Renders the JS required for the Backbone-based Display Tab
  */
 function display_tab_js_action($return = FALSE)
 {
     // Cache appropriately
     $this->object->do_not_cache();
     // Ensure that JS is returned
     $this->object->set_content_type('javascript');
     while (ob_get_level() > 0) {
         ob_end_clean();
     }
     // Get all entities used by the display tab
     $context = 'attach_to_post';
     $gallery_mapper = $this->get_registry()->get_utility('I_Gallery_Mapper', $context);
     $album_mapper = $this->get_registry()->get_utility('I_Album_Mapper', $context);
     $display_type_mapper = $this->get_registry()->get_utility('I_Display_Type_Mapper', $context);
     $source_mapper = $this->get_registry()->get_utility('I_Displayed_Gallery_Source_Mapper', $context);
     $security = $this->get_registry()->get_utility('I_Security_Manager');
     // Get the nextgen tags
     global $wpdb;
     $tags = $wpdb->get_results("SELECT DISTINCT name AS 'id', name FROM {$wpdb->terms}\n                        WHERE term_id IN (\n                                SELECT term_id FROM {$wpdb->term_taxonomy}\n                                WHERE taxonomy = 'ngg_tag'\n                        )");
     $all_tags = new stdClass();
     $all_tags->name = "All";
     $all_tags->id = "All";
     array_unshift($tags, $all_tags);
     $display_types = $display_type_mapper->find_all();
     usort($display_types, array($this->object, '_display_type_list_sort'));
     $output = $this->object->render_view('photocrati-attach_to_post#display_tab_js', array('displayed_gallery' => json_encode($this->object->_displayed_gallery->get_entity()), 'sources' => json_encode($source_mapper->select()->order_by('title')->run_query()), 'gallery_primary_key' => $gallery_mapper->get_primary_key_column(), 'galleries' => json_encode($gallery_mapper->find_all()), 'albums' => json_encode($album_mapper->find_all()), 'tags' => json_encode($tags), 'display_types' => json_encode($display_types), 'sec_token' => $security->get_request_token('nextgen_edit_displayed_gallery')->get_json()), $return);
     return $output;
 }
 /**
  * Output file to the browser.
  * For performance reasons, we avoid SS_HTTPResponse and just output the contents instead.
  */
 public function sendFile($file)
 {
     $path = $file->getFullPath();
     if (SapphireTest::is_running_test()) {
         return file_get_contents($path);
     }
     header('Content-Description: File Transfer');
     // Quotes needed to retain spaces (http://kb.mozillazine.org/Filenames_with_spaces_are_truncated_upon_download)
     header('Content-Disposition: inline; filename="' . basename($path) . '"');
     header('Content-Length: ' . $file->getAbsoluteSize());
     header('Content-Type: ' . HTTP::get_mime_type($file->getRelativePath()));
     header('Content-Transfer-Encoding: binary');
     // Fixes IE6,7,8 file downloads over HTTPS bug (http://support.microsoft.com/kb/812935)
     header('Pragma: ');
     if ($this->config()->min_download_bandwidth) {
         // Allow the download to last long enough to allow full download with min_download_bandwidth connection.
         increase_time_limit_to((int) (filesize($path) / ($this->config()->min_download_bandwidth * 1024)));
     } else {
         // Remove the timelimit.
         increase_time_limit_to(0);
     }
     // Clear PHP buffer, otherwise the script will try to allocate memory for entire file.
     while (ob_get_level() > 0) {
         ob_end_flush();
     }
     // Prevent blocking of the session file by PHP. Without this the user can't visit another page of the same
     // website during download (see http://konrness.com/php5/how-to-prevent-blocking-php-requests/)
     session_write_close();
     readfile($path);
     die;
 }
コード例 #14
0
ファイル: commonTest.php プロジェクト: qqlee/template
 public function testInherit()
 {
     $level = ob_get_level();
     $text = $this->getEngine()->render('index.html.php', null, true);
     $this->assertRegExp('/#layout_header\\s*#index_content\\s*#layout_footer/', $text);
     $this->assertEquals(ob_get_level(), $level);
 }
コード例 #15
0
ファイル: PhpTest.php プロジェクト: rafsalvioni/zeus-base
 /**
  * @test
  * @depends obActiveTest
  */
 public function obGetEndTest()
 {
     \ob_start();
     $n = \ob_get_level();
     echo __CLASS__;
     $this->assertTrue(\ob_get_end() === __CLASS__ && $n > \ob_get_level());
 }
コード例 #16
0
 public static function sendfile(array $item)
 {
     if (ob_get_level()) {
         ob_end_clean();
     }
     if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
         if ($item['size'] . '-' . $item['hash'] == trim($_SERVER['HTTP_IF_NONE_MATCH'], '"\'')) {
             header('HTTP/1.1 304 Not Modified', true, 304);
             exit;
         }
     }
     if (!isset($_SERVER['HTTP_RANGE'])) {
         header('HTTP/1.1 200 OK', true, 200);
         self::send($item, 0, $item['size'] - 1);
     } else {
         list($unit, $ranges) = explode('=', $_SERVER['HTTP_RANGE'], 2);
         list($range) = explode(',', $ranges, 2);
         list($from, $end) = explode('-', $range, 2);
         $end = empty($end) ? $item['size'] - 1 : min(abs((int) $end), $item['size'] - 1);
         $from = empty($from) || $end < abs((int) $from) ? 0 : max(abs((int) $from), 0);
         header('HTTP/1.1 206 Partial Content', true, 206);
         header("Content-Range: bytes {$from}-{$end}/" . $item['size']);
         self::send($item, $from, $end);
     }
 }
コード例 #17
0
 /**
  * {@inheritdoc}
  *
  * Additional available options:
  *
  *  * alt: an alternative URI to render in case of an error
  */
 public function render($uri, Request $request, array $options = array())
 {
     $reference = null;
     if ($uri instanceof ControllerReference) {
         $reference = $uri;
         $uri = $this->generateFragmentUri($uri, $request);
     }
     $subRequest = $this->createSubRequest($uri, $request);
     // override Request attributes as they can be objects (which are not supported by the generated URI)
     if (null !== $reference) {
         $subRequest->attributes->add($reference->attributes);
     }
     $level = ob_get_level();
     try {
         return $this->kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
     } catch (\Exception $e) {
         // let's clean up the output buffers that were created by the sub-request
         while (ob_get_level() > $level) {
             ob_get_clean();
         }
         if (isset($options['alt'])) {
             $alt = $options['alt'];
             unset($options['alt']);
             return $this->render($alt, $request, $options);
         }
         if (!isset($options['ignore_errors']) || !$options['ignore_errors']) {
             throw $e;
         }
         return new Response();
     }
 }
コード例 #18
0
ファイル: tool.php プロジェクト: Bouhnosaure/Typesetter
 /**
  * Send a 304 Not Modified Response to the client if HTTP_IF_NONE_MATCH matched $etag and headers have not already been sent
  * Othewise, send the etag
  * @param string $etag The calculated etag for the current page
  *
  */
 public static function Send304($etag)
 {
     global $config;
     if (!$config['etag_headers']) {
         return;
     }
     if (headers_sent()) {
         return;
     }
     //always send the etag
     header('ETag: "' . $etag . '"');
     if (empty($_SERVER['HTTP_IF_NONE_MATCH']) || trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') != $etag) {
         return;
     }
     //don't use ob_get_level() in while loop to prevent endless loops;
     $level = ob_get_level();
     while ($level > 0) {
         @ob_end_clean();
         $level--;
     }
     // 304 should not have a response body or Content-Length header
     //header('Not Modified',true,304);
     self::status_header(304, 'Not Modified');
     header('Connection: close');
     exit;
 }
コード例 #19
0
 public function render($display = true)
 {
     $render = false;
     $this->pdf_renderer->setFontForLang(Context::getContext()->language->iso_code);
     foreach ($this->objects as $object) {
         $template = $this->getTemplateObject($object);
         if (!$template) {
             continue;
         }
         if (empty($this->filename)) {
             $this->filename = $template->getFilename();
             if (count($this->objects) > 1) {
                 $this->filename = $template->getBulkFilename();
             }
         }
         $template->assignHookData($object);
         $this->pdf_renderer->createHeader($template->getHeader());
         $this->pdf_renderer->createFooter($template->getFooter());
         $this->pdf_renderer->createContent($template->getContent());
         $this->pdf_renderer->writePage();
         $render = true;
         unset($template);
     }
     if ($render) {
         // clean the output buffer
         if (ob_get_level() && ob_get_length() > 0) {
             ob_clean();
         }
         return $this->pdf_renderer->render($this->filename, $display);
     }
 }
コード例 #20
0
function disable_ob()
{
    // Turn off output buffering
    ini_set('output_buffering', 'off');
    // Turn off PHP output compression
    ini_set('zlib.output_compression', false);
    // Implicitly flush the buffer(s)
    ini_set('implicit_flush', true);
    ob_implicit_flush(true);
    // Clear, and turn off output buffering
    while (ob_get_level() > 0) {
        // Get the curent level
        $level = ob_get_level();
        // End the buffering
        ob_end_clean();
        // If the current level has not changed, abort
        if (ob_get_level() == $level) {
            break;
        }
    }
    // Disable apache output buffering/compression
    if (function_exists('apache_setenv')) {
        apache_setenv('no-gzip', '1');
        apache_setenv('dont-vary', '1');
    }
}
コード例 #21
0
 /**
  * Output the content of the resource
  *
  * @param array $options An array of options for the output
  */
 public function outputContent(array $options = array())
 {
     if (empty($options['rpc_type'])) {
         $options['rpc_type'] = 'XML';
     }
     $resourceClass = 'mod' . $options['rpc_type'] . 'RPCResource';
     if (!$this->modx->resource instanceof $resourceClass) {
         $this->modx->log(modX::LOG_LEVEL_FATAL, 'Could not load ' . $options['rpc_type'] . '-RPC Server class.');
     }
     $this->modx->resource->process();
     $this->modx->resource->_output = $this->modx->resource->_content;
     /* collect any uncached element tags in the content and process them */
     $this->modx->getParser();
     $maxIterations = intval($this->modx->getOption('parser_max_iterations', null, 10));
     $this->modx->parser->processElementTags('', $this->modx->resource->_output, true, false, '[[', ']]', array(), $maxIterations);
     $this->modx->parser->processElementTags('', $this->modx->resource->_output, true, true, '[[', ']]', array(), $maxIterations);
     if (!$this->getServer()) {
         $this->modx->log(modX::LOG_LEVEL_FATAL, 'Could not load ' . $options['rpc_type'] . '-RPC Server.');
     }
     $this->server->service();
     ob_get_level() && @ob_end_flush();
     while (ob_get_level() && @ob_end_clean()) {
     }
     exit;
 }
コード例 #22
0
ファイル: pages.php プロジェクト: joostina/joostina
 /**
  * Инициализация задачи
  *
  * @static
  * @param $code
  */
 private static function init($code)
 {
     joosRequest::send_headers_by_code($code);
     if (ob_get_level()) {
         ob_end_clean();
     }
 }
コード例 #23
0
 /**
  * Prints the stack trace for this exception.
  */
 public function printStackTrace()
 {
     if (null === $this->wrappedException) {
         $this->setWrappedException($this);
     }
     $exception = $this->wrappedException;
     if (!sfConfig::get('sf_test')) {
         // log all exceptions in php log
         error_log($exception->getMessage());
         // clean current output buffer
         while (ob_get_level()) {
             if (!ob_end_clean()) {
                 break;
             }
         }
         ob_start(sfConfig::get('sf_compressed') ? 'ob_gzhandler' : '');
         header('HTTP/1.0 500 Internal Server Error');
     }
     try {
         $this->outputStackTrace($exception);
     } catch (Exception $e) {
     }
     if (!sfConfig::get('sf_test')) {
         exit(1);
     }
 }
コード例 #24
0
 /**
  * Constructor
  *
  * Sets the path to the view files and gets the initial output buffering level
  *
  * @access	public
  */
 function CI_Loader()
 {
     $this->_ci_is_php5 = floor(phpversion()) >= 5 ? TRUE : FALSE;
     $this->_ci_view_path = APPPATH . 'views/';
     $this->_ci_ob_level = ob_get_level();
     log_message('debug', "Loader Class Initialized");
 }
コード例 #25
0
ファイル: SignIn.php プロジェクト: nodots/DIY
 protected function init()
 {
     if ($this->status_uid == 'people_signintolist_200' && !$this->unlocked) {
         // unlock the element
         $this->unlock();
     }
     if ($this->sessionGet('initialized_element_' . $this->element_id, 'script')) {
         // element is initialized, meaning this is the closing embed
         // unset element initialized state:
         $this->sessionClear('initialized_element_' . $this->element_id, 'script');
         if ($this->unlocked) {
             // unlocked, so clean out the buffer and don't display anything further
             $this->status_uid = 'empty';
             if (ob_get_level()) {
                 ob_end_flush();
             }
         } else {
             // locked, delete the protected output and send an empty string
             $this->status_uid = 'empty';
             if (ob_get_level()) {
                 ob_end_clean();
             }
         }
     } else {
         if ($this->unlocked) {
             // element already unlocked. do nothing.
             $this->status_uid = 'empty';
         } else {
             // element is locked. mark element as initialized, start output buffering, and display default markup
             $this->sessionSet('initialized_element_' . $this->element_id, true, 'script');
             ob_start();
         }
     }
 }
コード例 #26
0
 /**
  * Execute the callable.
  *
  * @param callable $callable
  * @param array    $arguments
  *
  * @return ResponseInterface
  */
 private function execute($callable, array $arguments = [])
 {
     ob_start();
     $level = ob_get_level();
     try {
         $return = call_user_func_array($callable, $arguments);
         if ($return instanceof ResponseInterface) {
             $response = $return;
             $return = '';
         } else {
             if (class_exists(ResponseFactory::class)) {
                 $response = (new ResponseFactory())->createResponse();
             } else {
                 $response = new Response();
             }
         }
         while (ob_get_level() >= $level) {
             $return = ob_get_clean() . $return;
         }
         $body = $response->getBody();
         if ($return !== '' && $body->isWritable()) {
             $body->write($return);
         }
         return $response;
     } catch (Throwable $exception) {
         while (ob_get_level() >= $level) {
             ob_end_clean();
         }
         throw $exception;
     }
 }
コード例 #27
0
	function __construct(){
		$this->cache_token = obcer::cache_token((COUCH?'db':NULL));
		$this->start_time = (float) array_sum(explode(' ',microtime()));
		$this->oh_memory = round(memory_get_usage() / 1024);
		// set up the 'filter' variable to determine what columns to show
		if(SHOW_ALL == FALSE){
			if(SHOW_LANGUAGE == false  ) $this->c_filter []='language';
			if(SHOW_SUPPRESS == false) $this->c_filter []='suppress';
			if(SHOW_RXCUI == false) $this->c_filter []='rxcui';
			if(SHOW_NAME == false) $this->c_filter []='name';
			if(SHOW_ALL_SYNONYM == FALSE) $this->c_filter []= 'synonym';
			if(SHOW_TTY == false) $this->c_filter []='tty';
			if(SHOW_UML == false) $this->c_filter []= 'umlscui';
		}
		// of course I could make a checkbox panel to allow for any combination of display fields, and cache entire returned xml results to do manipulations
		if(PROGRESSIVE_LOAD){
   	 	    @apache_setenv('no-gzip', 1);
			@ini_set('zlib.output_compression', 0);
			@ini_set('implicit_flush', 1);
			for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
			flush();
			ob_implicit_flush(1);
			ob_start();
		}
		// process any post if existant
		if($_POST) self::post_check();

		// if we haven't died by now then close and flush the ob cache for the final time

		// echo the footer and stats to screen.
		echo '<div id="stats">' . $this->stats().'</div>';

	}
コード例 #28
0
 /**
  * Converts an Exception to a Response.
  *
  * @param FlattenException     $exception   A FlattenException instance
  * @param DebugLoggerInterface $logger      A DebugLoggerInterface instance
  * @param string               $format      The format to use for rendering (html, xml, ...)
  * @param integer              $code        An HTTP response code
  * @param string               $message     An HTTP response status message
  * @param array                $headers     HTTP response headers
  *
  * @return Response                         Response instance
  */
 public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null, $format = 'html')
 {
     $format = $this->getFormat($request, $format);
     if (null === $format) {
         $message = 'No matching accepted Response format could be determined, while handling: ';
         $message .= $this->getExceptionMessage($exception);
         return new Response($message, Codes::HTTP_NOT_ACCEPTABLE, $exception->getHeaders());
     }
     // the count variable avoids an infinite loop on
     // some Windows configurations where ob_get_level()
     // never reaches 0
     $count = 100;
     $currentContent = '';
     while (ob_get_level() && --$count) {
         $currentContent .= ob_get_clean();
     }
     $code = $this->getStatusCode($exception);
     $viewHandler = $this->container->get('fos_rest.view_handler');
     $parameters = $this->getParameters($viewHandler, $currentContent, $code, $exception, $logger, $format);
     try {
         $view = View::create($parameters, $code, $exception->getHeaders());
         $view->setFormat($format);
         if ($viewHandler->isFormatTemplating($format)) {
             $view->setTemplate($this->findTemplate($format, $code));
         }
         $response = $viewHandler->handle($view);
     } catch (\Exception $e) {
         $message = 'An Exception was thrown while handling: ';
         $message .= $this->getExceptionMessage($exception);
         $response = new Response($message, Codes::HTTP_INTERNAL_SERVER_ERROR, $exception->getHeaders());
     }
     return $response;
 }
コード例 #29
0
 /**
  * Execute the callable.
  *
  * @param mixed             $target
  * @param RequestInterface  $request
  * @param ResponseInterface $response
  *
  * @return ResponseInterface
  */
 private function executeCallable($target, RequestInterface $request, ResponseInterface $response)
 {
     try {
         ob_start();
         $arguments = array_merge([$request, $response], $this->arguments);
         $target = self::getCallable($target, $arguments);
         $return = call_user_func_array($target, $arguments);
         if ($return instanceof ResponseInterface) {
             $response = $return;
             $return = '';
         }
         $return = ob_get_contents() . $return;
         $body = $response->getBody();
         if ($return !== '' && $body->isWritable()) {
             $body->write($return);
         }
         return $response;
     } catch (\Exception $exception) {
         throw $exception;
     } finally {
         if (ob_get_level() > 0) {
             ob_end_clean();
         }
     }
 }
コード例 #30
-1
ファイル: error.php プロジェクト: acmadi/diantaksi
 /**
  * Handle an exception and display the exception report.
  *
  * @param  Exception  $exception
  * @param  bool       $trace
  * @return void
  */
 public static function exception($exception, $trace = true)
 {
     static::log($exception);
     ob_get_level() and ob_end_clean();
     $message = $exception->getMessage();
     // For Laravel view errors we want to show a prettier error:
     $file = $exception->getFile();
     if (str_contains($exception->getFile(), 'eval()') and str_contains($exception->getFile(), 'laravel' . DS . 'view.php')) {
         $message = 'Error rendering view: [' . View::$last['name'] . ']' . PHP_EOL . PHP_EOL . $message;
         $file = View::$last['path'];
     }
     // If detailed errors are enabled, we'll just format the exception into
     // a simple error message and display it on the screen. We don't use a
     // View in case the problem is in the View class.
     if (Config::get('error.detail')) {
         $response_body = "<html><h2>Unhandled Exception</h2>\n\t\t\t\t<h3>Message:</h3>\n\t\t\t\t<pre>" . $message . "</pre>\n\t\t\t\t<h3>Location:</h3>\n\t\t\t\t<pre>" . $file . " on line " . $exception->getLine() . "</pre>";
         if ($trace) {
             $response_body .= "\n\t\t\t\t  <h3>Stack Trace:</h3>\n\t\t\t\t  <pre>" . $exception->getTraceAsString() . "</pre></html>";
         }
         $response = Response::make($response_body, 500);
     } else {
         $response = Event::first('500', array($exception));
         $response = Response::prepare($response);
     }
     $response->render();
     $response->send();
     $response->foundation->finish();
     exit(1);
 }