/**
  * Shows a themed error page.
  * @see Kohana_Exception::handle
  */
 private static function _show_themed_error_page(Exception $e)
 {
     // Create a text version of the exception
     $error = Kohana_Exception::text($e);
     // Add this exception to the log
     Kohana_Log::add('error', $error);
     // Manually save logs after exceptions
     Kohana_Log::save();
     if (!headers_sent()) {
         if ($e instanceof Kohana_Exception) {
             $e->sendHeaders();
         } else {
             header("HTTP/1.1 500 Internal Server Error");
         }
     }
     $view = new Theme_View("page.html", "other", "error");
     if ($e instanceof Kohana_404_Exception) {
         $view->page_title = t("Dang...  Page not found!");
         $view->content = new View("error_404.html");
         $user = identity::active_user();
         $view->content->is_guest = $user && $user->guest;
         if ($view->content->is_guest) {
             $view->content->login_form = new View("login_ajax.html");
             $view->content->login_form->form = auth::get_login_form("login/auth_html");
             // Avoid anti-phishing protection by passing the url as session variable.
             Session::instance()->set("continue_url", url::current(true));
         }
     } else {
         $view->page_title = t("Dang...  Something went wrong!");
         $view->content = new View("error.html");
     }
     print $view;
 }
 public function login()
 {
     $form = $errors = array("user" => "", "password" => "");
     $post = new Validation($_POST);
     $post->add_rules("user", "required");
     $post->add_rules("password", "required");
     if ($valid = $post->validate()) {
         try {
             $token = G3Remote::instance()->get_access_token($post["user"], $post["password"]);
             Session::instance()->set("g3_client_access_token", $token);
             $response = G3Remote::instance()->get_resource("gallery");
             $valid = true;
             $content = $this->_get_main_view($response->resource);
         } catch (Exception $e) {
             Kohana_Log::add("error", Kohana_Exception::text($e));
             $valid = false;
         }
     }
     if (!$valid) {
         $content = new View('login.html');
         $content->form = arr::overwrite($form, $post->as_array());
         $content->errors = arr::overwrite($errors, $post->errors());
     }
     $this->auto_render = false;
     print json_encode(array("status" => $valid ? "ok" : "error", "content" => (string) $content));
 }
Beispiel #3
0
 /**
  * Return the SQL query string.
  *
  * @return  string
  */
 public final function __toString()
 {
     try {
         // Return the SQL string
         return $this->compile(Database::instance());
     } catch (Exception $e) {
         return Kohana_Exception::text($e);
     }
 }
 /**
  * Logs with an arbitrary level.
  *
  * @param string  $level  a PSR LogLevel constant
  * @param string $message
  * @param array  $context
  *
  * @return null
  */
 public function log($level, $message, array $context = array())
 {
     $level = $this->convert_psr_to_kohana_level($level);
     if ($exception = $this->get_exception_from_context($context)) {
         $message .= \PHP_EOL . \Kohana_Exception::text($exception);
     } elseif ($message instanceof \Exception) {
         $context['exception'] = $message;
         $message = \Kohana_Exception::text($message);
     }
     $this->log->add($level, $message, array(), $context);
 }
Beispiel #5
0
 /**
  * Inline exception handler, displays the error message, source of the
  * exception, and the stack trace of the error.
  *
  * @uses    Kohana_Exception::text
  * @param   object   exception object
  * @return  boolean
  */
 public static function handler(Exception $e)
 {
     try {
         // Get the exception information
         $type = get_class($e);
         $code = $e->getCode();
         $message = $e->getMessage();
         $file = $e->getFile();
         $line = $e->getLine();
         // Create a text version of the exception
         $error = Kohana_Exception::text($e);
         if (is_object(Kohana::$log)) {
             // Add this exception to the log
             Kohana::$log->add(Log::ERROR, $error);
             // Make sure the logs are written
             Kohana::$log->write();
         }
         if (Kohana::$is_cli) {
             // Just display the text of the exception
             echo "\n{$error}\n";
             return TRUE;
         }
         if ($e instanceof ErrorException) {
             if (isset(Kohana_Exception::$php_errors[$code])) {
                 // Use the human-readable error name
                 $code = Kohana_Exception::$php_errors[$code];
             }
         }
         if (!headers_sent()) {
             Request::$current->response()->status($code);
             Request::$current->response()->headers('Content-Type', 'text/plain; charset=' . Kohana::$charset);
             Request::$current->response()->send_headers();
         }
         if (Kohana::$environment === Kohana::DEVELOPMENT) {
             echo $error;
         } else {
             echo $message;
         }
         return TRUE;
     } catch (Exception $e) {
         // Clean the output buffer if one exists
         ob_get_level() and ob_clean();
         // Make sure the proper content type is sent with a 500 status
         header('Content-Type: text/plain; charset=' . Kohana::$charset, TRUE, 500);
         // Display the exception message
         if (Kohana::$environment === Kohana::DEVELOPMENT) {
             echo Kohana_Exception::text($e), "\n";
         } else {
             echo $e->getMessage(), "\n";
         }
         // Exit with an error status
         // exit(1);
     }
 }
Beispiel #6
0
Datei: geo.php Projekt: anqh/core
 /**
  * Get from GeoNames by geonameId
  *
  * @static
  * @param   integer  $id
  * @return  array
  */
 private static function _get($id, $lang = 'en')
 {
     $url = Kohana::$config->load('geo.base_url') . '/get?geonameId=' . (int) $id . '&lang=' . $lang . '&style=full';
     try {
         $xml = new SimpleXMLElement($url, null, true);
         Kohana::$log->add(Log::DEBUG, 'GeoNames OK: ' . $url);
         return $xml;
     } catch (Exception $e) {
         Kohana::$log->add(Log::ERROR, 'GeoNames failed: ' . $url . ' - ' . Kohana_Exception::text($e));
         return false;
     }
 }
Beispiel #7
0
 public function execute()
 {
     // try
     $options = isset($this->options) ? $this->options->as_array(FALSE) : array();
     $options['task'] = $this->task;
     $success = FALSE;
     try {
         // create minion task
         $minion = Minion_Task::factory($options);
         // validate options here, to handle invalid tasks
         $validation = Validation::factory($minion->get_options());
         $validation = $minion->build_validation($validation);
         if (!$validation->check()) {
             $errors = $validation->errors(TRUE);
             $error = array_shift($errors);
             // don't execute task, log validation error
             Kohana::$log->add(Log::ERROR, 'Task of id: :id and type: :type failed validation: ":msg"', array(':id' => (string) $this->_id, ':type' => (string) $this->task, ':msg' => $error));
             // no need to retry
             $this->try = $this->max_tries;
             $this->message = $error;
         } else {
             $minion->execute();
             $success = TRUE;
         }
     } catch (Exception $e) {
         $error = Kohana_Exception::text($e);
         Kohana::$log->add(Log::ERROR, 'Task :id failed on try: :try with message :msg', array(':id' => (string) $this->_id, ':msg' => $error, ':try' => $this->try));
         $this->message = $error;
     }
     if ($success) {
         // success, delete task
         $this->delete();
     } else {
         $this->status = 'failed';
         if ($this->try < $this->max_tries) {
             // requeue
             $this->status = 'queued';
             $this->update();
         } else {
             if ($this->keep_failed) {
                 $this->update();
             } else {
                 $this->delete();
             }
         }
     }
     Kohana::$log->write();
     return $success;
 }
Beispiel #8
0
 public static function _handler(Exception $e)
 {
     if (method_exists($e, 'get_response')) {
         return $e->get_response();
     }
     /**
      * Things are going *really* badly for us, We now have no choice
      * but to bail. Hard.
      */
     // Clean the output buffer if one exists
     ob_get_level() and ob_clean();
     // Set the Status code to 500, and Content-Type to text/plain.
     header('Content-Type: text/plain; charset=' . Kohana::$charset, TRUE, 500);
     echo Kohana_Exception::text($e);
 }
 /**
  * Logs an exception.
  *
  * @uses    Kohana_Exception::text
  * @param   Exception  $e
  * @param   int        $level
  * @return  void
  */
 public static function log(Exception $e, $level = Log::EMERGENCY)
 {
     if (is_object(Kohana::$log)) {
         // Create a text version of the exception
         $error = Kohana_Exception::text($e);
         // add url to error
         $error .= "\n on " . URL::current();
         if (isset($_SERVER['HTTP_REFERER'])) {
             $error .= "\n from " . $_SERVER['HTTP_REFERER'];
         }
         // Add this exception to the log
         Kohana::$log->add($level, $error, NULL, array('exception' => $e));
         // Make sure the logs are written
         Kohana::$log->write();
     }
 }
Beispiel #10
0
 public function loop(array $config)
 {
     if ($this->_auto_terminate && memory_get_usage() > $this->_auto_terminate) {
         Kohana::$log->add(Log::WARNING, "Queue autoterminating. Memory usage (:usage bytes) higher than limit (:limit bytes).", array(":usage" => memory_get_usage(), ":limit" => $this->_auto_terminate));
         return FALSE;
     } else {
         if (count($this->_pids) < $this->_max_tasks) {
             try {
                 // find next task
                 $task = Mango::factory('task')->get_next();
             } catch (MongoException $e) {
                 Kohana::$log->add(Log::ERROR, Kohana_Exception::text($e));
                 Kohana::$log->add(Log::ERROR, 'Error loading next task. Exiting');
                 return FALSE;
             }
             if ($task->loaded()) {
                 // Write log to prevent memory issues
                 Kohana::$log->write();
                 // close all database connections before forking
                 foreach (MangoDB::$instances as $instance) {
                     $instance->disconnect();
                 }
                 $pid = pcntl_fork();
                 if ($pid == -1) {
                     // error forking
                     Kohana::$log->add(Log::ERROR, 'Queue. Could not spawn child task process.');
                     Kohana::$log->write();
                     exit;
                 } else {
                     if ($pid) {
                         // parent process
                         $this->_pids[$pid] = time();
                     } else {
                         // child process
                         $task->execute();
                         exit(0);
                     }
                 }
             }
         }
     }
     return TRUE;
 }
Beispiel #11
0
 /**
  * Inline exception handler.
  *
  * @param   Exception  exception object
  * @return  string
  * @uses    Arr::get
  * @uses    Kohana::find_file
  * @uses    Kohana_Exception::handler
  * @uses    Kohana_Exception::text
  */
 function kandler(Exception $e)
 {
     try {
         // Get error code
         $code = $e->getCode();
         // Retrieve Kandler's config
         $config = Kohana::$config->load('kandler');
         // Use views defined by user or use default
         $view = Arr::get($config->errors, $code, $code);
         // Create path to error view
         $path = $config->path . DIRECTORY_SEPARATOR . $view;
         if (Kohana::find_file('views', $path)) {
             // Set an exception view
             Kohana_Exception::$error_view = $path;
         }
         // Handle an exception using Kohana's handler
         Kohana_Exception::handler($e);
     } catch (Exception $e) {
         return Kohana_Exception::text($e);
     }
 }
 public static function handler(Exception $e)
 {
     /*
      * In development, use the in-built Kohana
      * exception handler to display and log the
      * exception/error.
      */
     if (Kohana::$environment >= Kohana::DEVELOPMENT) {
         Kohana_Exception::handler($e);
     } else {
         try {
             $exception_text = Kohana_Exception::text($e);
             // Log the error
             Kohana::$log->add(Log::ERROR, $exception_text);
             // Email the error
             if (class_exists('Email')) {
                 $email_subject = Kohana::$config->load('error.website.name') . ' Error';
                 $email_message = $exception_text;
                 $email_from = Kohana::$config->load('error.email.from');
                 foreach ('error.email.to' as $email_to) {
                     Email::send($email_to, $email_from, $email_subject, $email_mesage);
                 }
             } else {
                 Kohana::$log->add(Log::NOTICE, 'Email module not installed, errors can not be sent.');
             }
             // Show an error page
             $action = $e instanceof HTTP_Exception ? $e->getCode() : 500;
             $post = array('message' => $e->getMessage(), 'requested_url' => Request::$current ? Request::$current->uri() : 'Unknown');
             echo Request::factory(Route::get('error-handler')->uri(array('action' => $action)))->method(Request::POST)->post($post)->execute()->send_headers()->body();
         } catch (Exception $e) {
             // Clean the output buffer if one exists
             ob_get_level() and ob_clean();
             // Display the exception text
             echo Kohana_Exception::text($e);
             // Exit with an error status
             exit(1);
         }
     }
 }
Beispiel #13
0
 public static function response($e)
 {
     try {
         $class = get_class($e);
         $code = $e->getCode();
         $message = $e->getMessage();
         $file = $e->getFile();
         $line = $e->getLine();
         $trace = $e->getTrace();
         if ($e instanceof ErrorException) {
             if (isset(Kohana_Exception::$php_errors[$code])) {
                 $code = Kohana_Exception::$php_errors[$code];
             }
         }
         $response = View::factory(Kohana_Exception::$error_view, get_defined_vars());
         return $response;
     } catch (Exception $e) {
         ob_get_level() and ob_clean();
         header('Content-Type: text/plain; charset=utf-8', TRUE, 500);
         echo Kohana_Exception::text($e);
         exit(1);
     }
 }
Beispiel #14
0
 public function action_index()
 {
     $post = $this->request->current()->post();
     $group = Arr::get($post, 'group');
     $album_id = (int) Arr::get($post, 'album');
     $items = Arr::get($post, 'items');
     $operation = Arr::get($post, 'operation');
     $album_orm = ORM::factory('photo_Album')->where('group', '=', $group)->and_where('id', '=', $album_id)->find();
     if (!$album_orm->loaded() or !$this->acl->is_allowed($this->user, $album_orm, 'edit')) {
         throw new HTTP_Exception_404();
     }
     if (empty($items) or !is_array($items) or empty($operation)) {
         throw new HTTP_Exception_404();
     }
     try {
         $this->_group_operation_move($operation, $items, $album_orm);
     } catch (Exception $e) {
         $code = $e->getCode();
         $this->response->status(ctype_digit($code) ? $code : 500)->body(Kohana_Exception::text($e));
         return;
     }
     $this->response->body('OK');
 }
Beispiel #15
0
 public function __toString()
 {
     try {
         // Return the SQL string
         return $this->compile();
     } catch (Exception $e) {
         return Kohana_Exception::text($e);
     }
 }
Beispiel #16
0
 protected function daemon()
 {
     while (!$this->_sigterm) {
         if (count($this->_pids) < $this->_config['max']) {
             try {
                 // find next task
                 $task = Mango::factory('task')->get_next();
             } catch (MongoException $e) {
                 Kohana::$log->add($this->_config['log']['error'], Kohana_Exception::text($e));
                 Kohana::$log->add($this->_config['log']['error'], 'Error loading next task. Exiting');
                 Kohana::$log->write();
                 $this->clean();
                 exit;
             }
             if ($task->loaded()) {
                 if (!$task->valid()) {
                     // invalid tasks are discarded immediately
                     Kohana::$log->add($this->_config['log']['error'], strtr('Discarded invalid :type task"', array(':type' => $task->type)));
                     $task->delete();
                 } else {
                     // Write log to prevent memory issues
                     Kohana::$log->write();
                     $pid = $this->fork();
                     if ($pid == -1) {
                         Kohana::$log->add($this->_config['log']['error'], 'Queue. Could not spawn child task process.');
                         exit;
                     } elseif ($pid) {
                         // Parent - add the child's PID to the running list
                         $this->_pids[$pid] = time();
                     } else {
                         $task->execute($this->_config);
                         exit;
                     }
                 }
             } else {
                 // queue is empty
                 usleep($this->_config['sleep']);
             }
         } else {
             // daemon is busy
             usleep($this->_config['sleep']);
         }
     }
     // clean up
     $this->clean();
 }
Beispiel #17
0
 /**
  * Inline exception handler, displays the error message, source of the
  * exception, and the stack trace of the error.
  *
  * @uses    Kohana_Exception::text
  * @param   object   exception object
  * @return  boolean
  */
 public static function handler(Exception $e)
 {
     try {
         // Get the exception information
         $type = get_class($e);
         $code = $e->getCode();
         $message = $e->getMessage();
         $file = $e->getFile();
         $line = $e->getLine();
         // Get the exception backtrace
         $trace = $e->getTrace();
         if ($e instanceof ErrorException) {
             if (isset(Kohana_Exception::$php_errors[$code])) {
                 // Use the human-readable error name
                 $code = Kohana_Exception::$php_errors[$code];
             }
             if (version_compare(PHP_VERSION, '5.3', '<')) {
                 // Workaround for a bug in ErrorException::getTrace() that exists in
                 // all PHP 5.2 versions. @see http://bugs.php.net/bug.php?id=45895
                 for ($i = count($trace) - 1; $i > 0; --$i) {
                     if (isset($trace[$i - 1]['args'])) {
                         // Re-position the args
                         $trace[$i]['args'] = $trace[$i - 1]['args'];
                         // Remove the args
                         unset($trace[$i - 1]['args']);
                     }
                 }
             }
         }
         // Create a text version of the exception
         $error = Kohana_Exception::text($e);
         if (is_object(Kohana::$log)) {
             // Add this exception to the log
             Kohana::$log->add(Log::ERROR, $error);
             $strace = Kohana_Exception::text($e) . "\n--\n" . $e->getTraceAsString();
             Kohana::$log->add(Log::STRACE, $strace);
             // Make sure the logs are written
             Kohana::$log->write();
         }
         if (Kohana::$is_cli) {
             // Just display the text of the exception
             echo "\n{$error}\n";
             exit(1);
         }
         if (!headers_sent()) {
             // Make sure the proper http header is sent
             $http_header_status = $e instanceof HTTP_Exception ? $code : 500;
             header('Content-Type: ' . Kohana_Exception::$error_view_content_type . '; charset=' . Kohana::$charset, TRUE, $http_header_status);
         }
         if (Request::$current !== NULL and Request::current()->is_ajax() === TRUE) {
             // Just display the text of the exception
             echo "\n{$error}\n";
             exit(1);
         }
         // Start an output buffer
         ob_start();
         // Include the exception HTML
         if ($view_file = Kohana::find_file('views', Kohana_Exception::$error_view)) {
             include $view_file;
         } else {
             throw new Kohana_Exception('Error view file does not exist: views/:file', array(':file' => Kohana_Exception::$error_view));
         }
         // Display the contents of the output buffer
         echo ob_get_clean();
         exit(1);
     } catch (Exception $e) {
         // Clean the output buffer if one exists
         ob_get_level() and ob_clean();
         // Display the exception text
         echo Kohana_Exception::text($e), "\n";
         // Exit with an error status
         exit(1);
     }
 }
Beispiel #18
0
 /**
  * Get a Response object representing the exception
  *
  * @uses    Kohana_Exception::text
  * @param   Exception  $e
  * @return  Response
  */
 public static function response(Exception $e)
 {
     // Log the exception
     Kohana_Exception::log($e);
     try {
         // Get the exception information
         $code = $e->getCode();
         $message = $e->getMessage();
         if (!headers_sent()) {
             // Make sure the proper http header is sent
             $http_header_status = $e instanceof HTTP_Exception ? $code : 500;
         }
         if ($e instanceof ErrorException && isset(Kohana_Exception::$php_errors[$code])) {
             // Use the human-readable error name
             $code = Kohana_Exception::$php_errors[$code];
         }
         // Prepare the response object.
         $response = Response::factory();
         // Set the response status
         $response->status($e instanceof HTTP_Exception ? $e->getCode() : 500);
         // Set the response headers
         $response->headers('Content-Type', 'application/api-problem+json; charset=' . Kohana::$charset);
         if (empty($message)) {
             $message = Arr::get(Response::$messages, $response->status());
         }
         // Set the response body
         $response->body($message);
     } catch (Exception $e) {
         /**
          * Things are going badly for us, Lets try to keep things under control by
          * generating a simpler response object.
          */
         $response = Response::factory();
         $response->status(500);
         $response->headers('Content-Type', 'text/plain');
         $response->body(Kohana_Exception::text($e));
     }
     return $response;
 }
Beispiel #19
0
 /**
  * exception handler, displays the error message, source of the
  * exception, and the stack trace of the error.
  *
  * @uses    Kohana::message()
  * @uses    Kohana_Exception::text()
  * @param   object   exception object
  * @return  void
  */
 public static function handle(Exception $e)
 {
     try {
         // Get the exception information
         $type = get_class($e);
         $code = $e->getCode();
         $message = $e->getMessage();
         // Create a text version of the exception
         $error = Kohana_Exception::text($e);
         // Add this exception to the log
         Kohana_Log::add('error', $error);
         // Manually save logs after exceptions
         Kohana_Log::save();
         if (Kohana::config('core.display_errors') === FALSE) {
             // Do not show the details
             $file = $line = NULL;
             $trace = array();
             $template = '_disabled';
         } else {
             $file = $e->getFile();
             $line = $e->getLine();
             $trace = $e->getTrace();
             $template = '';
         }
         if ($e instanceof Kohana_Exception) {
             $template = $e->getTemplate() . $template;
             if (!headers_sent()) {
                 $e->sendHeaders();
             }
             // Use the human-readable error name
             $code = Kohana::message('core.errors.' . $code);
         } else {
             $template = Kohana_Exception::$template . $template;
             if (!headers_sent()) {
                 header('HTTP/1.1 500 Internal Server Error');
             }
             if ($e instanceof ErrorException) {
                 // Use the human-readable error name
                 $code = Kohana::message('core.errors.' . $e->getSeverity());
                 if (version_compare(PHP_VERSION, '5.3', '<')) {
                     // Workaround for a bug in ErrorException::getTrace() that exists in
                     // all PHP 5.2 versions. @see http://bugs.php.net/45895
                     for ($i = count($trace) - 1; $i > 0; --$i) {
                         if (isset($trace[$i - 1]['args'])) {
                             // Re-position the arguments
                             $trace[$i]['args'] = $trace[$i - 1]['args'];
                             unset($trace[$i - 1]['args']);
                         }
                     }
                 }
             }
         }
         // Clean the output buffer if one exists
         ob_get_level() and ob_clean();
         if ($template = Kohana::find_file('views', $template)) {
             include $template;
         }
     } catch (Exception $e) {
         // Clean the output buffer if one exists
         ob_get_level() and ob_clean();
         // Display the exception text
         echo Kohana_Exception::text($e), "\n";
     }
     if (Kohana::$server_api === 'cli') {
         // Exit with an error status
         exit(1);
     }
 }
Beispiel #20
0
 /**
  * Sets the last_active timestamp and saves the session.
  *
  *     $session->write();
  *
  * [!!] Any errors that occur during session writing will be logged,
  * but not displayed, because sessions are written after output has
  * been sent.
  *
  * @return  boolean
  * @uses    Kohana::$log
  */
 public function write()
 {
     if (headers_sent() or $this->_destroyed) {
         // Session cannot be written when the headers are sent or when
         // the session has been destroyed
         return FALSE;
     }
     // Set the last active timestamp
     $this->_data['last_active'] = time();
     try {
         return $this->_write();
     } catch (Exception $e) {
         // Log & ignore all errors when a write fails
         Kohana::$log->add(Log::ERROR, Kohana_Exception::text($e))->write();
         return FALSE;
     }
 }
Beispiel #21
0
 /**
  * Send file download as the response. All execution will be halted when
  * this method is called! Use TRUE for the filename to send the current
  * response as the file content. The third parameter allows the following
  * options to be set:
  *
  * Type      | Option    | Description                        | Default Value
  * ----------|-----------|------------------------------------|--------------
  * `boolean` | inline    | Display inline instead of download | `FALSE`
  * `string`  | mime_type | Manual mime type                   | Automatic
  * `boolean` | delete    | Delete the file after sending      | `FALSE`
  *
  * Download a file that already exists:
  *
  *     $request->send_file('media/packages/kohana.zip');
  *
  * Download generated content as a file:
  *
  *     $request->response($content);
  *     $request->send_file(TRUE, $filename);
  *
  * [!!] No further processing can be done after this method is called!
  *
  * @param   string   filename with path, or TRUE for the current response
  * @param   string   downloaded file name
  * @param   array    additional options
  * @return  void
  * @throws  Kohana_Exception
  * @uses    File::mime_by_ext
  * @uses    File::mime
  * @uses    Request::send_headers
  */
 public function send_file($filename, $download = NULL, array $options = NULL)
 {
     if (!empty($options['mime_type'])) {
         // The mime-type has been manually set
         $mime = $options['mime_type'];
     }
     if ($filename === TRUE) {
         if (empty($download)) {
             throw new Kohana_Exception('Download name must be provided for streaming files');
         }
         // Temporary files will automatically be deleted
         $options['delete'] = FALSE;
         if (!isset($mime)) {
             // Guess the mime using the file extension
             $mime = File::mime_by_ext(strtolower(pathinfo($download, PATHINFO_EXTENSION)));
         }
         // Force the data to be rendered if
         $file_data = (string) $this->_body;
         // Get the content size
         $size = strlen($file_data);
         // Create a temporary file to hold the current response
         $file = tmpfile();
         // Write the current response into the file
         fwrite($file, $file_data);
         // File data is no longer needed
         unset($file_data);
     } else {
         // Get the complete file path
         $filename = realpath($filename);
         if (empty($download)) {
             // Use the file name as the download file name
             $download = pathinfo($filename, PATHINFO_BASENAME);
         }
         // Get the file size
         $size = filesize($filename);
         if (!isset($mime)) {
             // Get the mime type
             $mime = File::mime($filename);
         }
         // Open the file for reading
         $file = fopen($filename, 'rb');
     }
     if (!is_resource($file)) {
         throw new Kohana_Exception('Could not read file to send: :file', array(':file' => $download));
     }
     // Inline or download?
     $disposition = empty($options['inline']) ? 'attachment' : 'inline';
     // Calculate byte range to download.
     list($start, $end) = $this->_calculate_byte_range($size);
     if (!empty($options['resumable'])) {
         if ($start > 0 or $end < $size - 1) {
             // Partial Content
             $this->_status = 206;
         }
         // Range of bytes being sent
         $this->_header['content-range'] = 'bytes ' . $start . '-' . $end . '/' . $size;
         $this->_header['accept-ranges'] = 'bytes';
     }
     // Set the headers for a download
     $this->_header['content-disposition'] = $disposition . '; filename="' . $download . '"';
     $this->_header['content-type'] = $mime;
     $this->_header['content-length'] = (string) ($end - $start + 1);
     if (Request::user_agent('browser') === 'Internet Explorer') {
         // Naturally, IE does not act like a real browser...
         if (Request::$initial->secure()) {
             // http://support.microsoft.com/kb/316431
             $this->_header['pragma'] = $this->_header['cache-control'] = 'public';
         }
         if (version_compare(Request::user_agent('version'), '8.0', '>=')) {
             // http://ajaxian.com/archives/ie-8-security
             $this->_header['x-content-type-options'] = 'nosniff';
         }
     }
     // Send all headers now
     $this->send_headers();
     while (ob_get_level()) {
         // Flush all output buffers
         ob_end_flush();
     }
     // Manually stop execution
     ignore_user_abort(TRUE);
     if (!Kohana::$safe_mode) {
         // Keep the script running forever
         set_time_limit(0);
     }
     // Send data in 16kb blocks
     $block = 1024 * 16;
     fseek($file, $start);
     while (!feof($file) and ($pos = ftell($file)) <= $end) {
         if (connection_aborted()) {
             break;
         }
         if ($pos + $block > $end) {
             // Don't read past the buffer.
             $block = $end - $pos + 1;
         }
         // Output a block of the file
         echo fread($file, $block);
         // Send the data now
         flush();
     }
     // Close the file
     fclose($file);
     if (!empty($options['delete'])) {
         try {
             // Attempt to remove the file
             unlink($filename);
         } catch (Exception $e) {
             // Create a text version of the exception
             $error = Kohana_Exception::text($e);
             if (is_object(Kohana::$log)) {
                 // Add this exception to the log
                 Kohana::$log->add(Log::ERROR, $error);
                 // Make sure the logs are written
                 Kohana::$log->write();
             }
             // Do NOT display the exception, it will corrupt the output!
         }
     }
     // Stop execution
     exit;
 }
 /**
  * @param \Log $log
  */
 function it_can_accept_exception_as_message($log)
 {
     $e = new \Exception('Problem');
     $this->subject->alert($e);
     $log->add(\Log::ALERT, \Kohana_Exception::text($e), array(), array('exception' => $e))->shouldHaveBeenCalled();
 }
Beispiel #23
0
 /**
  * Formating error message for display in CLI.
  * 
  * @return string
  */
 protected function _cli_text()
 {
     return parent::text($this);
 }
Beispiel #24
0
 /**
  * Magic object-to-string method.
  *
  *     echo $exception;
  *
  * @uses    Kohana_Exception::text
  * @return  string
  */
 public function __toString()
 {
     return Kohana_Exception::text($this);
 }
Beispiel #25
0
 /**
  * Tests Kohana_Exception::text()
  *
  * @test
  * @dataProvider provider_text
  * @covers Kohana_Exception::text
  * @param object $exception exception to test
  * @param string $expected  expected output
  */
 public function test_text($exception, $expected)
 {
     $this->assertEquals($expected, Kohana_Exception::text($exception));
 }
Beispiel #26
0
<?php

defined("SYSPATH") or die("No direct script access.");
echo Kohana_Exception::text($e), "\n";
Beispiel #27
0
	/**
	 * Replaces Kohana's `Kohana::exception_handler()` method. This does the
	 * same thing, but also adds email functionality and the ability to perform
	 * an action in response to the exception. These actions and emails are
	 * customizable per type in the config file for this module.
	 *
	 * @uses		Kohana::exception_text
	 * @param \Exception $e
	 * @internal param \exception $object object
	 * @return	boolean
	 */
	public static function handler(Exception $e)
	{
		try
		{
			$error = new Error();

			// Get the exception information
			$error->exception = $e;
			$error->type = get_class($e);
			$error->code = $e->getCode();
			$error->message = $e->getMessage();
			$error->file = $e->getFile();
			$error->line = $e->getLine();
			$error->request_initial = Request::initial();

			// Create a text version of the exception
			$error->text = Kohana_Exception::text($e);

			if (Kohana::$is_cli)
			{
				// Display the text of the exception
				echo "\n{$error->text}\n";
			}

			// Get the exception backtrace
			$error->trace = $e->getTrace();

			if ($e instanceof ErrorException)
			{
				if (version_compare(PHP_VERSION, '5.3', '<'))
				{
					// Workaround for a bug in ErrorException::getTrace() that exists in
					// all PHP 5.2 versions. @see http://bugs.php.net/bug.php?id=45895
					for ($i = count($error->trace) - 1;$i > 0;--$i)
					{
						if (isset($error->trace[$i - 1]['args']))
						{
							// Re-position the args
							$error->trace[$i]['args'] = $error->trace[$i - 1]['args'];

							// Remove the args
							unset($error->trace[$i - 1]['args']);
						}
					}
				}
			}

			if (!headers_sent() and (Kohana::$is_cli === false))
			{
				// Make sure the proper content type is sent with a 500 status
				header('Content-Type: text/html; charset=' . Kohana::$charset, true, 500);
			}

			// Get the contents of the output buffer
			$error->display = $error->render();

			// Log the error
			$error->log();

			// Email the error
			$error->email();

			// Respond to the error
			$error->action();

			return true;
		}
		catch (Exception $e)
		{
			// Log an error.
			if (is_object(Kohana::$log))
			{
				// Create a text version of the exception
				$error = Kohana_Exception::text($e);

				// Add this exception to the log
				Kohana::$log->add(Log::ERROR, $error);

				// Make sure the logs are written
				Kohana::$log->write();
			}

			// Clean the output buffer if one exists
			ob_get_level() and ob_clean();

			// Display the exception text
			header('HTTP/1.1 500 Internal Server Error');
			echo "Unknown Error - Exception thrown in Error::handler()";

			// Exit with an error status
			exit(1);
		}
	}
Beispiel #28
0
 /**
  * Render the current image.
  *
  *     echo $image;
  *
  * [!!] The output of this function is binary and must be rendered with the
  * appropriate Content-Type header or it will not be displayed correctly!
  *
  * @return  string
  */
 public function __toString()
 {
     try {
         // Render the current image
         return $this->render();
     } catch (Exception $e) {
         if (is_object(Kohana::$log)) {
             // Get the text of the exception
             $error = Kohana_Exception::text($e);
             // Add this exception to the log
             Kohana::$log->add(Log::ERROR, $error);
         }
         // Showing any kind of error will be "inside" image data
         return '';
     }
 }
Beispiel #29
0
 /**
  * Get a Response object representing the exception
  *
  * @uses    Kohana_Exception::text
  * @param   Exception  $e
  * @return  Response
  */
 public static function response(Exception $e)
 {
     try {
         // Get the exception information
         $class = get_class($e);
         $code = $e->getCode();
         $message = $e->getMessage();
         $file = $e->getFile();
         $line = $e->getLine();
         $trace = $e->getTrace();
         /**
          * HTTP_Exceptions are constructed in the HTTP_Exception::factory()
          * method. We need to remove that entry from the trace and overwrite
          * the variables from above.
          */
         if ($e instanceof HTTP_Exception and $trace[0]['function'] == 'factory') {
             extract(array_shift($trace));
         }
         if ($e instanceof ErrorException) {
             /**
              * If XDebug is installed, and this is a fatal error,
              * use XDebug to generate the stack trace
              */
             if (function_exists('xdebug_get_function_stack') and $code == E_ERROR) {
                 $trace = array_slice(array_reverse(xdebug_get_function_stack()), 4);
                 foreach ($trace as &$frame) {
                     /**
                      * XDebug pre 2.1.1 doesn't currently set the call type key
                      * http://bugs.xdebug.org/view.php?id=695
                      */
                     if (!isset($frame['type'])) {
                         $frame['type'] = '??';
                     }
                     // XDebug also has a different name for the parameters array
                     if (isset($frame['params']) and !isset($frame['args'])) {
                         $frame['args'] = $frame['params'];
                     }
                 }
             }
             if (isset(Kohana_Exception::$php_errors[$code])) {
                 // Use the human-readable error name
                 $code = Kohana_Exception::$php_errors[$code];
             }
         }
         /**
          * The stack trace becomes unmanageable inside PHPUnit.
          *
          * The error view ends up several GB in size, taking
          * serveral minutes to render.
          */
         if (defined('PHPUnit_MAIN_METHOD')) {
             $trace = array_slice($trace, 0, 2);
         }
         // Instantiate the error view.
         $view = View::factory(Kohana_Exception::$error_view, get_defined_vars());
         // Prepare the response object.
         $response = Response::factory();
         // Set the response status
         $response->status($e instanceof HTTP_Exception ? $e->getCode() : 500);
         // Set the response headers
         $response->headers('Content-Type', Kohana_Exception::$error_view_content_type . '; charset=' . Kohana::$charset);
         // Set the response body
         $response->body($view->render());
     } catch (Exception $e) {
         /**
          * Things are going badly for us, Lets try to keep things under control by
          * generating a simpler response object.
          */
         $response = Response::factory();
         $response->status(500);
         $response->headers('Content-Type', 'text/plain');
         $response->body(Kohana_Exception::text($e));
     }
     return $response;
 }
 public function format_for_cli()
 {
     return Kohana_Exception::text($this);
 }