Example #1
0
 /**
  * Shutdown handler for log fatal errors
  */
 public static function _shutdownHandler()
 {
     $error = error_get_last();
     if (self::$sendErrors && in_array($error['type'], self::$unrecoverable)) {
         Rollbar::report_exception($error);
     }
 }
Example #2
0
 /**
  * 处理致命错误
  */
 function handleFatalError()
 {
     if ($e = error_get_last()) {
         $msg = $e['message'] . " in " . $e['file'] . ' line ' . $e['line'];
         log_message('error', 'PHP Fatal error: ' . $msg);
     }
 }
 /**
  * @covers Starter\routers\RestRouter::admin_panel_edit_user
  */
 public function test_admin_panel_edit_user()
 {
     ob_start();
     $this->router->admin_panel_edit_user(1);
     ob_end_clean();
     self::assertNull(error_get_last());
 }
Example #4
0
/**
 * shutdown函数,用于捕获至命错误
 */
function shutdown()
{
    $error = error_get_last();
    if ($error) {
        show_error($error['message'], $error['type'], $error['file'], $error['line']);
    }
}
Example #5
0
/**
 * 
 */
function breathe_shutdown_function()
{
    $error = error_get_last();
    if ($error !== null) {
        error::Ret()->Log('breathe_shutdown_function: ' . print_r($error, true));
    }
}
Example #6
0
/**
 * Checks for a fatal error, work around for set_error_handler not working on fatal errors.
 */
function check_for_fatal()
{
    $error = error_get_last();
    if ($error["type"] == E_ERROR) {
        errorHandler($error["type"], $error["message"], $error["file"], $error["line"]);
    }
}
Example #7
0
 /**
  * Log fatal error to Mautic's logs and throw exception for the parent generic error page to catch
  *
  * @throws \Exception
  */
 public function handleFatal()
 {
     $error = error_get_last();
     if ($error !== null) {
         $name = $this->getErrorName($error['type']);
         $this->logger->error("{$name}: {$error['message']} - in file {$error['file']} - at line {$error['line']}");
         if ($error['type'] === E_ERROR || $error['type'] === E_CORE_ERROR || $error['type'] === E_USER_ERROR) {
             defined('MAUTIC_OFFLINE') or define('MAUTIC_OFFLINE', 1);
             if (MAUTIC_ENV == 'dev') {
                 $message = "<pre>{$error['message']} - in file {$error['file']} - at line {$error['line']}</pre>";
                 // Get a trace
                 ob_start();
                 debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
                 $trace = ob_get_contents();
                 ob_end_clean();
                 // Remove first item from backtrace as it's this function which
                 // is redundant.
                 $trace = preg_replace('/^#0\\s+' . __FUNCTION__ . "[^\n]*\n/", '', $trace, 1);
                 // Renumber backtrace items.
                 $trace = preg_replace('/^#(\\d+)/me', '\'#\' . ($1 - 1)', $trace);
                 $submessage = "<pre>{$trace}</pre>";
             } else {
                 $message = 'The site is currently offline due to encountering an error. If the problem persists, please contact the system administrator.';
                 $submessage = 'System administrators, check server logs for errors.';
             }
             include __DIR__ . '/../../../../offline.php';
         }
     }
 }
Example #8
0
 /**
  * Run application
  *
  * @return bool|\Phalcon\Http\ResponseInterface
  */
 public function run()
 {
     $this->_initLoader($this->_dependencyInjector);
     $this->_initServices($this->_dependencyInjector, $this->config);
     $this->_initModule();
     $handle = $this->handle();
     if ($this->config->logError) {
         $error = error_get_last();
         if ($error) {
             $logKey = md5(implode('|', $error));
             /**
              * @var $corePhpLog CorePhpLogs
              */
             $corePhpLog = CorePhpLogs::findFirst(['conditions' => 'log_key = ?0', 'bind' => [$logKey]]);
             if ($corePhpLog) {
                 $corePhpLog->status = 0;
             } else {
                 $corePhpLog = new CorePhpLogs();
                 $corePhpLog->assign(['log_key' => $logKey, 'type' => $error['type'], 'message' => $error['message'], 'file' => $error['file'], 'line' => $error['line'], 'status' => 0]);
             }
             $corePhpLog->save();
         }
     }
     return $handle;
 }
Example #9
0
 public function __construct($filename = null, array $options = array(), $binary = false, $type = null)
 {
     $this->filename = $filename;
     $this->remote = false;
     $this->binary = (bool) $binary;
     $this->assertFileAvaiable();
     $this->detectFormat($type);
     if ($this->binary) {
         $this->oldImage = @imagecreatefromstring($this->filename);
     } else {
         switch ($this->format) {
             case self::TYPE_PNG:
                 $this->oldImage = @imagecreatefrompng($this->filename);
                 break;
             case self::TYPE_JPEG:
                 $this->oldImage = @imagecreatefromjpeg($this->filename);
                 break;
             case self::TYPE_GIF:
                 $this->oldImage = @imagecreatefromgif($this->filename);
                 break;
         }
     }
     if (!$this->oldImage) {
         $error = error_get_last();
         throw new \InvalidArgumentException('create image with given resource failed' . ($error ? ' with error ' . $error['message'] : ''));
     }
     $this->currentDimensions = array('width' => imagesx($this->oldImage), 'height' => imagesy($this->oldImage));
     $this->setOptions($options);
 }
Example #10
0
function sgfun($filter, $params = null)
{
    $fp = fopen('php://memory', 'w');
    $filter = @stream_filter_append($fp, $filter, STREAM_FILTER_WRITE, $params);
    if ($filter === false) {
        fclose($fp);
        $error = error_get_last() + array('message' => '');
        throw new RuntimeException('Unable to access built-in filter: ' . $error['message']);
    }
    // append filter function which buffers internally
    $buffer = '';
    sgappend($fp, function ($chunk) use(&$buffer) {
        $buffer .= $chunk;
        // always return empty string in order to skip actually writing to stream resource
        return '';
    }, STREAM_FILTER_WRITE);
    $closed = false;
    return function ($chunk = null) use($fp, $filter, &$buffer, &$closed) {
        if ($closed) {
            throw new RuntimeException('Unable to perform operation on closed stream');
        }
        if ($chunk === null) {
            $closed = true;
            $buffer = '';
            fclose($fp);
            return $buffer;
        }
        // initialize buffer and invoke filters by attempting to write to stream
        $buffer = '';
        fwrite($fp, $chunk);
        // buffer now contains everything the filter function returned
        return $buffer;
    };
}
Example #11
0
 /**
  * Método executado quando ocorre algum erro fatal no PHP, esse método é chamado 
  * antes que o PHP pare a execução da página
  * @return	void
  */
 public static function shutdown()
 {
     $error = error_get_last();
     if (is_array($error)) {
         self::handle($error['type'], $error['message'], $error['file'], $error['line']);
     }
 }
Example #12
0
    /**
     * This fatal error shutdown handler will only get called when there is a serious fatal
     * error with your application.
     */
    public static function tierShutdownFunction()
    {
        $fatals = [E_ERROR, E_PARSE, E_USER_ERROR, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING];
        $lastError = error_get_last();
        if (empty($lastError) !== true && in_array($lastError['type'], $fatals) === true) {
            if (headers_sent() === true) {
                return;
            }
            extract($lastError);
            $msg = sprintf("Fatal error: %s in %s on line %d", $message, $file, $line);
            $preStyles = ["color: red", "white-space: pre-wrap", "white-space: -moz-pre-wrap", "white-space: -pre-wrap", "white-space: -o-pre-wrap", "word-wrap: break-word"];
            $preStyle = implode(";", $preStyles);
            $html = <<<HTML
<html>
  <body>
    <h1>500 Internal Server Error</h1>
    <hr/>
    <pre style='%s'>%s</pre>
  </body>
</html>
HTML;
            $output = sprintf($html, $preStyle, $msg);
            $body = new HtmlBody($output, 500);
            self::sendRawBodyResponse($body);
        }
    }
Example #13
0
 public function createTrace($type = null, $message = null, $file = null, $line = null, $custom_data = array())
 {
     if (empty($type)) {
         $e = error_get_last();
         if (!empty($e)) {
             $message = $e['message'];
             $file = $e['file'];
             $type = $e['type'];
             $line = $e['line'];
         }
     }
     if (!empty($type)) {
         $levels = array(E_ERROR => 'Error', E_WARNING => 'Warning', E_PARSE => 'Parsing Error', E_NOTICE => 'Notice', E_CORE_ERROR => 'Core Error', E_CORE_WARNING => 'Core Warning', E_COMPILE_ERROR => 'Compile Error', E_COMPILE_WARNING => 'Compile Warning', E_USER_ERROR => 'User Error', E_USER_WARNING => 'User Warning', E_USER_NOTICE => 'User Notice', E_STRICT => 'Runtime Notice');
         // Set error type
         $type = isset($levels[$type]) ? $levels[$type] : 'Unknown';
         // Fetch router
         $router =& load_class('Router', 'core');
         // Set up the trace file (1 level is better than none)
         $trace = array();
         $trace[0] = array();
         $trace[0]['function'] = $router->fetch_method();
         $trace[0]['class'] = $router->fetch_class();
         $trace[0]['type'] = $type;
         $trace[0]['args'] = array();
         $trace[0]['file'] = $file;
         $trace[0]['line'] = $line;
         // Send to airbrake
         self::sendToTracker($type . ': ' . $message, $type, $trace, $custom_data);
     }
 }
Example #14
0
 /**
  * @inheritdoc
  */
 protected function setUpExceptionHandler(SapiInterface $sapi, ContainerInterface $container)
 {
     error_reporting(E_ALL);
     $createHandler = function () use($container) {
         $has = $container->has(ExceptionHandlerInterface::class);
         $handler = $has === true ? $container->get(ExceptionHandlerInterface::class) : new DefaultHandler();
         return $handler;
     };
     $throwableHandler = function (Throwable $throwable) use($sapi, $container, $createHandler) {
         /** @var ExceptionHandlerInterface $handler */
         $handler = $createHandler();
         $handler->handleThrowable($throwable, $sapi, $container);
     };
     $exceptionHandler = function (Exception $exception) use($sapi, $container, $createHandler) {
         /** @var ExceptionHandlerInterface $handler */
         $handler = $createHandler();
         $handler->handleException($exception, $sapi, $container);
     };
     set_exception_handler(PHP_MAJOR_VERSION >= 7 ? $throwableHandler : $exceptionHandler);
     set_error_handler(function ($severity, $message, $fileName, $lineNumber) use($exceptionHandler) {
         $errorException = new ErrorException($message, 0, $severity, $fileName, $lineNumber);
         $exceptionHandler($errorException);
         throw $errorException;
     });
     // handle fatal error
     register_shutdown_function(function () use($container, $createHandler) {
         $error = error_get_last();
         if ($error !== null && (int) $error['type'] & (E_ERROR | E_COMPILE_ERROR)) {
             /** @var ExceptionHandlerInterface $handler */
             $handler = $createHandler();
             $handler->handleFatal($error, $container);
         }
     });
 }
Example #15
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);
}
Example #16
0
 /**
  * Configures PHP error handling.
  * @return void
  */
 public static function setupErrors()
 {
     error_reporting(E_ALL | E_STRICT);
     ini_set('display_errors', TRUE);
     ini_set('html_errors', FALSE);
     ini_set('log_errors', FALSE);
     set_exception_handler(array(__CLASS__, 'handleException'));
     set_error_handler(function ($severity, $message, $file, $line) {
         if (in_array($severity, array(E_RECOVERABLE_ERROR, E_USER_ERROR), TRUE) || ($severity & error_reporting()) === $severity) {
             Environment::handleException(new \ErrorException($message, 0, $severity, $file, $line));
         }
         return FALSE;
     });
     register_shutdown_function(function () {
         Assert::$onFailure = array(__CLASS__, 'handleException');
         // note that Runner is unable to catch this errors in CLI & PHP 5.4.0 - 5.4.6 due PHP bug #62725
         $error = error_get_last();
         register_shutdown_function(function () use($error) {
             if (in_array($error['type'], array(E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE), TRUE)) {
                 if (($error['type'] & error_reporting()) !== $error['type']) {
                     // show fatal errors hidden by @shutup
                     echo "\nFatal error: {$error['message']} in {$error['file']} on line {$error['line']}\n";
                 }
             } elseif (Environment::$checkAssertions && !Assert::$counter) {
                 echo "\nError: This test forgets to execute an assertion.\n";
                 exit(Runner\Job::CODE_FAIL);
             }
         });
     });
 }
Example #17
0
function shutdown()
{
    $error = error_get_last();
    if ($error['type'] != 0) {
        var_dump($error);
    }
}
function shutdown()
{
    $error = error_get_last();
    if ($error['type'] === E_ERROR) {
        echo json_encode(array('error' => sprintf(__('<strong>PHP Error</strong> line %s: %s'), $error['line'], $error['message'])));
    }
}
Example #19
0
function error_alert()
{
	$sTableID = "tbl_php_commandline";
	$arErrorType = array(
		E_ERROR => "Fatal error",
		E_PARSE => "Parse error",
	);
	$e = error_get_last();
	if(is_null($e) === false && isset($arErrorType[$e['type']]))
	{
		ob_end_clean();
		echo "<h2>".GetMessage("php_cmd_error")."&nbsp;</h2><p>";
		echo '<b>'.$arErrorType[$e['type']].'</b>: '.htmlspecialcharsbx($e['message']).' in <b>'.htmlspecialcharsbx($e['file']).'</b> on line <b>'.htmlspecialcharsbx($e['line']).'</b>';
	}
	else
	{
		global $DB;
		if(
			isset($DB)
			&& is_object($DB)
			&& $DB->GetErrorMessage() != ''
		)
		{
			ob_end_clean();
			echo "<h2>".GetMessage("php_cmd_error")."&nbsp;</h2><p>";
			echo '<font color=#ff0000>Query Error: '.htmlspecialcharsbx($DB->GetErrorSQL()).'</font> ['.htmlspecialcharsbx($DB->GetErrorMessage()).']';
		}
	}
}
Example #20
0
 public function fatalErrorPhp()
 {
     $debug = isset($this->core->conf->system->core->debug['errors']) ? $this->core->conf->system->core->debug['errors'] : true;
     $mr = isset($this->core->conf->system->core->debug['mail-report']) ? $this->core->conf->system->core->debug['mail-report'] : true;
     $error = error_get_last();
     if (isset($error)) {
         //Если фатальная ошибка, то обработка этой ошибки
         if ($error['type'] == E_ERROR || $error['type'] == E_PARSE || $error['type'] == E_COMPILE_ERROR || $error['type'] == E_CORE_ERROR) {
             ob_end_clean();
             if (empty($this->core->getParams()['api']['code'])) {
                 header('HTTP/1.0 500');
             } else {
                 header('HTTP/1.0 ' . $this->core->getParams()['api']['code']);
             }
             $error['file'] = $this->pathReplacer($error['file']);
             $mysql = $this->core->mysql;
             if (!$debug) {
                 $errA = array('error' => 'Unfortunately, there is an error there. But our team is working on elimination of this problem.');
             } else {
                 $errA = array('error' => "[{$error['type']}][{$error['file']}:{$error['line']}] {$error['message']}\r\n");
             }
             echo json_encode($errA);
             if ($mr && isset($this->core->mail)) {
                 if ($this->core->mysql->isConnect($mysql::DB_NAME)) {
                     $this->core->mail->addWaitingList($this->core->conf->system->core->admin_mail, '000', array('code' => $error['type'], 'msg' => $error['message'], 'file' => $error['file'], 'line' => $error['line'], 'time' => time()));
                 }
             }
             $er_j = json_encode(array('code' => $error['type'], 'msg' => $error['message'], 'file' => $error['file'], 'line' => $error['line'], 'time' => time()));
             $this->core->statCache('error', $er_j, true);
         }
     }
     ob_end_flush();
 }
Example #21
0
 function shutDownHandler()
 {
     $lastError = error_get_last();
     if (isset($lastError) && $lastError['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING)) {
         errorHandler($lastError['type'], $lastError['message'], $lastError['file'], $lastError['line']);
     }
 }
Example #22
0
 /**
  * Registers an error handler for PHP errors.
  *
  * @param Logger $logger
  * @param bool   $continueNativeHandler
  *
  * @return bool Returna always false to enable other handlers, including the default
  *
  * @throws Exception\InvalidArgumentException if logger is null
  */
 public static function registerErrorHandler(Logger $logger, $continueNativeHandler = false)
 {
     // Only register once per instance
     if (self::$registeredErrorHandler) {
         return false;
     }
     if ($logger === null) {
         throw new \Zend\Log\Exception\InvalidArgumentException('Invalid Logger specified');
     }
     $errorHandlerMap = [E_NOTICE => self::NOTICE, E_USER_NOTICE => self::NOTICE, E_WARNING => self::WARN, E_CORE_WARNING => self::WARN, E_USER_WARNING => self::WARN, E_ERROR => self::ERR, E_USER_ERROR => self::ERR, E_CORE_ERROR => self::ERR, E_RECOVERABLE_ERROR => self::ERR, E_STRICT => self::DEBUG, E_DEPRECATED => self::DEBUG, E_USER_DEPRECATED => self::DEBUG];
     $previous = set_error_handler(function ($errno, $errstr, $errfile, $errline) use($errorHandlerMap, $logger, $continueNativeHandler) {
         $errorLevel = error_reporting();
         if ($errorLevel && $errno) {
             if (isset($errorHandlerMap[$errno])) {
                 $priority = $errorHandlerMap[$errno];
             } else {
                 $priority = \Zend\Log\Logger::INFO;
             }
             $logger->log($priority, 'Error: ' . $errstr . ' in ' . $errfile . ' in line ' . $errline);
             return !$continueNativeHandler;
         }
     });
     register_shutdown_function(function () use($logger) {
         $error = error_get_last();
         if (null === $error) {
             return false;
         }
         $priority = \Zend\Log\Logger::ERR;
         $logger->log($priority, 'Error: ' . $error['message'] . ' in ' . $error['file'] . ' in line ' . $error['line']);
     });
     self::$registeredErrorHandler = true;
     return $previous;
 }
 /**
  * Create Icinga Web 2's configuration directory
  *
  * USAGE:
  *
  *  icingacli setup config directory [options]
  *
  * OPTIONS:
  *
  *  --config=<directory>    Path to Icinga Web 2's configuration files [/etc/icingaweb2]
  *
  *  --mode=<mode>           The access mode to use [2770]
  *
  *  --group=<group>         Owner group for the configuration directory [icingaweb2]
  *
  * EXAMPLES:
  *
  *  icingacli setup config directory
  *
  *  icingacli setup config directory --mode=2775 --config=/opt/icingaweb2/etc
  */
 public function directoryAction()
 {
     $configDir = trim($this->params->get('config', $this->app->getConfigDir()));
     if (strlen($configDir) === 0) {
         $this->fail($this->translate('The argument --config expects a path to Icinga Web 2\'s configuration files'));
     }
     $group = trim($this->params->get('group', 'icingaweb2'));
     if (strlen($group) === 0) {
         $this->fail($this->translate('The argument --group expects a owner group for the configuration directory'));
     }
     $mode = trim($this->params->get('mode', '2770'));
     if (strlen($mode) === 0) {
         $this->fail($this->translate('The argument --mode expects an access mode for the configuration directory'));
     }
     if (!file_exists($configDir) && !@mkdir($configDir)) {
         $e = error_get_last();
         $this->fail(sprintf($this->translate('Can\'t create configuration directory %s: %s'), $configDir, $e['message']));
     }
     if (!@chmod($configDir, octdec($mode))) {
         $e = error_get_last();
         $this->fail(sprintf($this->translate('Can\'t change the mode of the configuration directory to %s: %s'), $mode, $e['message']));
     }
     if (!@chgrp($configDir, $group)) {
         $e = error_get_last();
         $this->fail(sprintf($this->translate('Can\'t change the group of %s to %s: %s'), $configDir, $group, $e['message']));
     }
     printf($this->translate('Successfully created configuration directory %s') . PHP_EOL, $configDir);
 }
Example #24
0
function shutdownHandler()
{
    if (is_null($e = error_get_last()) === false) {
        $error = new myError($e);
        ErrorHandler::handler($error);
    }
}
Example #25
0
 /**
  * {@inheritdoc}
  */
 public function getFunctions()
 {
     $compiler = function () {
         throw new LogicException('Compilation not supported.');
     };
     return [new ExpressionFunction('url', $compiler, function ($arguments, $url) {
         return $url;
     }), new ExpressionFunction('link', $compiler, function ($arguments, $selector) {
         return $arguments['_crawler']->selectLink($selector);
     }), new ExpressionFunction('button', $compiler, function ($arguments, $selector) {
         return $arguments['_crawler']->selectButton($selector);
     }), new ExpressionFunction('status_code', $compiler, function ($arguments) {
         return $arguments['_response']->getStatusCode();
     }), new ExpressionFunction('headers', $compiler, function ($arguments) {
         $headers = [];
         foreach ($arguments['_response']->getHeaders() as $key => $value) {
             $headers[$key] = $value[0];
         }
         return $headers;
     }), new ExpressionFunction('body', $compiler, function ($arguments) {
         return (string) $arguments['_response']->getBody();
     }), new ExpressionFunction('header', $compiler, function ($arguments, $name) {
         $name = str_replace('_', '-', strtolower($name));
         if (!$arguments['_response']->hasHeader($name)) {
             return;
         }
         return $arguments['_response']->getHeader($name)[0];
     }), new ExpressionFunction('scalar', $compiler, function ($arguments, $scalar) {
         return $scalar;
     }), new ExpressionFunction('join', $compiler, function ($arguments, $value, $glue) {
         if ($value instanceof \Traversable) {
             $value = iterator_to_array($value, false);
         }
         return implode($glue, (array) $value);
     }), new ExpressionFunction('fake', $compiler, function ($arguments, $provider) {
         $arguments = func_get_args();
         return $this->faker->format($provider, array_splice($arguments, 2));
     }), new ExpressionFunction('regex', $compiler, function ($arguments, $regex) {
         $ret = @preg_match($regex, (string) $arguments['_response']->getBody(), $matches);
         if (false === $ret) {
             throw new InvalidArgumentException(sprintf('Regex "%s" is not valid: %s.', $regex, error_get_last()['message']));
         }
         return isset($matches[1]) ? $matches[1] : null;
     }), new ExpressionFunction('css', $compiler, function ($arguments, $selector) {
         if (null === $arguments['_crawler']) {
             throw new LogicException(sprintf('Unable to get "%s" CSS selector as the page is not crawlable.', $selector));
         }
         return $arguments['_crawler']->filter($selector);
     }), new ExpressionFunction('xpath', $compiler, function ($arguments, $selector) {
         if (null === $arguments['_crawler']) {
             throw new LogicException(sprintf('Unable to get "%s" XPATH selector as the page is not crawlable.', $selector));
         }
         return $arguments['_crawler']->filterXPath($selector);
     }), new ExpressionFunction('json', $compiler, function ($arguments, $selector) {
         if (null === ($data = json_decode((string) $arguments['_response']->getBody(), true))) {
             throw new LogicException(sprintf(' Unable to get the "%s" JSON path as the Response body does not seem to be JSON.', $selector));
         }
         return JmesPath::search($selector, $data);
     })];
 }
 /**
  * Send the given JSON as a request to the CodeClimate Server using cURL.
  * Added as a backup if PHP Streams method fails (e.g. if allow_url_fopen is disabled).
  *
  * @param string $url     The API end-point URL
  * @param string $payload The request payload as a JSON-encoded string
  *
  * @return \stdClass Response object with (code, message, headers & body properties)
  */
 private function sendWithCurl($url, $payload)
 {
     $response = new \stdClass();
     $curl = curl_init($url);
     curl_setopt($curl, CURLOPT_HEADER, true);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
     curl_setopt($curl, CURLOPT_HTTPHEADER, ['Host: codeclimate.com', 'Content-Type: application/json', 'User-Agent: Code Climate (PHP Test Reporter v' . Version::VERSION . ')', 'Content-Length: ' . strlen($payload)]);
     curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
     curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
     $rawResponse = curl_exec($curl);
     $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
     if (!empty($rawResponse)) {
         $response = $this->buildResponse($response, $rawResponse);
     } else {
         $error = error_get_last();
         preg_match('/([0-9]{3})/', $error['message'], $match);
         $errorCode = isset($match[1]) ? $match[1] : ($status ? $status : 500);
         $response->code = $errorCode;
         $response->message = $error['message'];
         $response->headers = [];
         $response->body = null;
     }
     return $response;
 }
 function _handle_fatal_error()
 {
     $error = error_get_last();
     if ($error !== NULL) {
         echo $this->_errorResponse('FATAL: ' . $error['message']);
     }
 }
Example #28
0
 /**
  * Lock the resource
  *
  * @param  bool        $blocking wait until the lock is released
  * @return bool        Returns true if the lock was acquired, false otherwise
  * @throws IOException If the lock file could not be created or opened
  */
 public function lock($blocking = false)
 {
     if ($this->handle) {
         return true;
     }
     // Silence both userland and native PHP error handlers
     $errorLevel = error_reporting(0);
     set_error_handler('var_dump', 0);
     if (!($this->handle = fopen($this->file, 'r'))) {
         if ($this->handle = fopen($this->file, 'x')) {
             chmod($this->file, 0444);
         } elseif (!($this->handle = fopen($this->file, 'r'))) {
             usleep(100);
             // Give some time for chmod() to complete
             $this->handle = fopen($this->file, 'r');
         }
     }
     restore_error_handler();
     error_reporting($errorLevel);
     if (!$this->handle) {
         $error = error_get_last();
         throw new IOException($error['message'], 0, null, $this->file);
     }
     // On Windows, even if PHP doc says the contrary, LOCK_NB works, see
     // https://bugs.php.net/54129
     if (!flock($this->handle, LOCK_EX | ($blocking ? 0 : LOCK_NB))) {
         fclose($this->handle);
         $this->handle = null;
         return false;
     }
     return true;
 }
Example #29
0
 /**
  *
  *
  */
 public static function shutdownHandler()
 {
     $error = error_get_last();
     if ($error) {
         self::exceptionHandler(new ErrorException($error['message'], $error['type'], 0, $error['file'], $error['line']));
     }
 }
Example #30
0
 /**
  * The exception/error/shutdown handler callback
  */
 public function __invoke($e = null, $msg = null)
 {
     if ($e instanceof \Exception) {
         try {
             echo static::htmlException($e);
         } catch (\Exception $ignore) {
             headers_sent() or HTTP::setResponseCode(500);
             die("FATAL ERROR");
         }
     } elseif (isset($e, $msg)) {
         throw new \Exception($msg, $e);
     } elseif ($error = error_get_last()) {
         switch ($error["type"]) {
             case E_PARSE:
             case E_ERROR:
             case E_USER_ERROR:
             case E_CORE_ERROR:
             case E_COMPILE_ERROR:
                 while (ob_get_level()) {
                     if (!@ob_end_clean()) {
                         break;
                     }
                 }
                 $message = sprintf("%s in %s at line %d", $error["message"], $error["file"], $error["line"]);
                 echo static::htmlError("Application Error", $message, 500, "");
                 break;
         }
     }
 }