Added error handling.

Also in development mode now you can install the database - provided you configured Kohana.
This commit is contained in:
Alexander Yakovlev 2011-10-15 12:57:18 +07:00
parent 21656e9666
commit 8c8b61dd29
10 changed files with 169 additions and 33 deletions

View file

@ -82,7 +82,9 @@ if (isset($_SERVER['KOHANA_ENV']))
Kohana::init(array( Kohana::init(array(
'base_url' => '/', 'base_url' => '/',
'index_file' => FALSE, 'index_file' => FALSE,
'errors' => TRUE 'errors' => TRUE,
'profile' => (Kohana::$environment == Kohana::DEVELOPMENT),
'caching' => (Kohana::$environment == Kohana::PRODUCTION)
)); ));
/** /**
@ -113,8 +115,13 @@ Kohana::modules(array(
* Set the routes. Each route must have a minimum of a name, a URI and a set of * Set the routes. Each route must have a minimum of a name, a URI and a set of
* defaults for the URI. * defaults for the URI.
*/ */
Route::set('error', 'error/<action>(/<message>)', array('action' => '[0-9]++','message' => '.+'))
->defaults(array(
'controller' => 'error',
));
Route::set('default', '(<controller>(/<action>(/<id>)))') Route::set('default', '(<controller>(/<action>(/<id>)))')
->defaults(array( ->defaults(array(
'controller' => 'copyright', 'controller' => 'copyright',
'action' => 'view', 'action' => 'view',
)); ));

View file

@ -0,0 +1,33 @@
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Error extends Controller_Template {
public $template = 'error';
/**
* Pre determine error display logic
*/
public function before() {
parent::before();
// Sub requests only!
if ($this->request->is_initial()) $this->request->action(404);
$this->response->status((int) $this->request->action());
}
/**
* Serves HTTP 404 error page
*/
//адрес страницы не выводится
public function action_404() {
$this->template->title = 'Страница не найдена';
$this->template->description = 'Запрошенная вами страница не найдена. Скорее всего, это была просто опечатка. Проверьте строку адреса.';
}
/**
* Serves HTTP 500 error page
*/
public function action_500() {
$this->template->description = 'Произошла внутренняя ошибка. Не волнуйтесь, её должны скоро исправить.';
$this->template->title ='Внутренняя ошибка сервера';
}
}

View file

@ -11,7 +11,7 @@ class Controller_Header extends Controller_Template {
foreach($styles as $style=>$media): foreach($styles as $style=>$media):
if ($media != 'screen' and $media != 'print'){ if ($media != 'screen' and $media != 'print'){
$style=$media; $style=$media;
$media="screen"; $media='screen';
} }
$temp .= '<link rel="stylesheet" type="text/css" media="'. $media .'" href="'.URL::site('assets/css/'.$style).'">'."\n"; $temp .= '<link rel="stylesheet" type="text/css" media="'. $media .'" href="'.URL::site('assets/css/'.$style).'">'."\n";
endforeach; endforeach;

View file

@ -0,0 +1,25 @@
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Install extends Controller_Template {
public $template = 'install';
public function action_view() {
if ((Kohana::$environment == Kohana::PRODUCTION)) $this->request->redirect('');
if ($_POST){
if ($this->request->post('create')){
DB::query(NULL,'CREATE DATABASE '.$database.';')->execute();
}
$queries = fopen(Kohana::find_file('', 'database', 'sql'), "r");
while (!feof($queries)) {
$buffer = fgets($queries);//btw: by default reads 1kb of string!
DB::query(NULL,$buffer)->execute();
}
fclose($queries);
$user = ORM::factory('user')->values(arr::extract($this->request->post(), array('username', 'password', 'email', 'password_confirm')));
$user->create();
$login_role = new Model_Role(array('name' =>'login'));
$admin_role = new Model_Role(array('name' =>'admin'));
$user->add('roles',$admin_role);
$user->add('roles',$login_role);
}
}
}

View file

@ -0,0 +1,40 @@
<?php defined('SYSPATH') or die('No direct script access.');
class Kohana_Exception extends Kohana_Kohana_Exception {
public static function handler(Exception $e) {
// Throw errors when in development mode
if (Kohana::$environment === Kohana::DEVELOPMENT) {
parent::handler($e);
}
else {
try{
Kohana::$log->add(Log::ERROR, Kohana_Exception::text($e));
$attributes = array(
'action' => 500,
'message' => rawurlencode($e->getMessage())
);
if ($e instanceof Http_Exception) {
$attributes['action'] = $e->getCode();
}
// Error sub request
echo Request::factory(Route::get('error')->uri($attributes))
->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 parent::text($e);
// Exit with an error status
exit(1);
}
}
}
}

View file

@ -2,30 +2,30 @@
return array return array
( (
'default' => array 'default' => array
( (
'type' => 'mysql', 'type' => 'mysql',
'connection' => array( 'connection' => array(
/** /**
* The following options are available for MySQL: * The following options are available for MySQL:
* *
* string hostname server hostname, or socket * string hostname server hostname, or socket
* string database database name * string database database name
* string username database username * string username database username
* string password database password * string password database password
* boolean persistent use persistent connections? * boolean persistent use persistent connections?
* *
* Ports and sockets may be appended to the hostname. * Ports and sockets may be appended to the hostname.
*/ */
'hostname' => 'localhost', 'hostname' => 'localhost',
'database' => 'nemove', 'database' => 'nemove',
'username' => 'dandelion', 'username' => 'dandelion',
'password' => '', 'password' => '',
'persistent' => FALSE, 'persistent' => FALSE,
), ),
'table_prefix' => '', 'table_prefix' => '',
'charset' => 'utf8', 'charset' => 'utf8',
'caching' => FALSE, 'caching' => TRUE,
'profiling' => TRUE, 'profiling' => FALSE,
), ),
); );

15
application/database.sql Normal file
View file

@ -0,0 +1,15 @@
SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS `roles_users`;
DROP TABLE IF EXISTS `roles`;
DROP TABLE IF EXISTS `users`;
DROP TABLE IF EXISTS `user_tokens`;
SET FOREIGN_KEY_CHECKS = 1;
CREATE TABLE IF NOT EXISTS `roles` (`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,`name` varchar(32) NOT NULL,`description` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `uniq_name` (`name`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `roles` (`id`, `name`, `description`) VALUES(1, 'login', 'Login privileges, granted after account confirmation');
INSERT INTO `roles` (`id`, `name`, `description`) VALUES(2, 'admin', 'Administrative user, has access to everything.');
INSERT INTO `roles` (`id`, `name`, `description`) VALUES(3, 'author', 'Uploads games');
CREATE TABLE IF NOT EXISTS `roles_users` (`user_id` int(10) UNSIGNED NOT NULL,`role_id` int(10) UNSIGNED NOT NULL, PRIMARY KEY (`user_id`,`role_id`), KEY `fk_role_id` (`role_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `users` (`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,`email` varchar(127) NOT NULL, `username` varchar(32) NOT NULL DEFAULT '', `password` char(50) NOT NULL, `logins` int(10) UNSIGNED NOT NULL DEFAULT '0', `last_login` int(10) UNSIGNED, PRIMARY KEY (`id`), UNIQUE KEY `uniq_username` (`username`), UNIQUE KEY `uniq_email` (`email`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `user_tokens` ( `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, `user_id` int(11) UNSIGNED NOT NULL, `user_agent` varchar(40) NOT NULL, `token` varchar(32) NOT NULL, `created` int(10) UNSIGNED NOT NULL, `expires` int(10) UNSIGNED NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `uniq_token` (`token`), KEY `fk_user_id` (`user_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `roles_users` ADD CONSTRAINT `roles_users_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `roles_users_ibfk_2` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE;
ALTER TABLE `user_tokens` ADD CONSTRAINT `user_tokens_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

View file

@ -0,0 +1,15 @@
<?php echo Request::factory('header/standard')->post('title','Установка движка')->post('styles','main.css')->execute() ?>
<h1>Установка движка</h1>
<p>Внимание! При продолжении база данных будет переписана.</p>
<p>Предполагается, что база данных MySQL находится по адресу localhost и использует кодировку UTF-8. Вы можете поменять настройки в файле config/database.php.</p>
<?php echo form::open('install') ?>
<p><?php echo form::label('create','Создать базу данных'); echo form::checkbox('create','') ?></p>
<p><?php echo form::label('username','Имя пользователя администратора [admin]: '); echo form::input('username','admin') ?></p>
<p><?php echo form::label('password','Пароль администратора [password]: '); echo form::password('password','password') ?></p>
<p><?php echo form::label('password_confirm','Подтверждение пароля: '); echo form::password('password_confirm','password') ?></p>
<p><?php echo form::label('email','e-mail администратора: '); echo form::input('email','admin@example.com') ?></p>
<p><?php echo form::submit('submit','Отправить') ?>
<p></p>
</p>
<?php echo form::close() ?>
<?php echo Request::factory('footer/standard')->execute() ?>

View file

@ -45,6 +45,7 @@ define('EXT', '.php');
* deprecated notices. Disable with: E_ALL & ~E_DEPRECATED * deprecated notices. Disable with: E_ALL & ~E_DEPRECATED
*/ */
error_reporting(E_ALL | E_STRICT); error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'On');
/** /**
* End of standard configuration! Changing any of the code below should only be * End of standard configuration! Changing any of the code below should only be

2
system

@ -1 +1 @@
Subproject commit ed12c18fdd2182e1cf0859860af80f388b23b1da Subproject commit 4419480faec65835f4b989cf7a73d76b4dc60756