public function forms(Post $post, CSRF $csrf) { foreach ($post as $key => $value) { $this->tpl->{$key} = $value; } $this->tpl->csrf = $csrf->generate()->input(); $this->tpl->verror = $post->verror; }
/** * REST endpoint for sharing droplets via email */ public function action_share() { $this->template = ''; $this->auto_render = FALSE; if ($this->request->method() != "POST") { throw HTTP_Exception::factory(405)->allowed('POST'); } // Extract the input data to be used for sending the email $post = Arr::extract($_POST, array('recipient', 'drop_title', 'drop_url', 'security_code')); $csrf_token = $this->request->headers('x-csrf-token'); // Setup validation $validation = Validation::factory($post)->rule('recipient', 'not_empty')->rule('recipient', 'email')->rule('security_code', 'Captcha::valid')->rule('drop_title', 'not_empty')->rule('drop_url', 'url'); // Validate if (!CSRF::valid($csrf_token) or !$validation->check()) { Kohana::$log->add(Log::DEBUG, "CSRF token or form validation failure"); throw HTTP_Exception::factory(400); } else { list($recipient, $subject) = array($post['recipient'], $post['drop_title']); // Modify the mail body to include the email address of the // use sharing content $mail_body = __(":user has shared a drop with you via SwiftRiver\n\n:url", array(':user' => $this->user['owner']['username'], ':url' => $post['drop_url'])); // Send the email Swiftriver_Mail::send($recipient, $subject, $mail_body); } }
public function Display() { global $config, $lpaths; // render header/footer $this->outputs['header'] = RenderHTML::LoadHTML('header.php'); $this->outputs['footer'] = RenderHTML::LoadHTML('footer.php'); $this->outputs['header'] = str_replace('{AddToHeader}', $this->tempHeader, $this->outputs['header']); // insert css $this->outputs['css'] = trim($this->outputs['css']); if (!empty($this->outputs['css'])) { $this->outputs['css'] = "\n" . $this->outputs['css'] . "\n"; } $this->outputs['header'] = str_replace('{css}', $this->outputs['css'], $this->outputs['header']); // common tags $this->tags['site title'] = $config['site title']; $this->tags['page title'] = $config['title']; $this->tags['lastpage'] = getLastPage(); $this->tags['sitepage title'] = $config['site title'] . (empty($config['title']) ? '' : ' - ' . $config['title']); $this->tags['token'] = CSRF::getTokenURL(); $this->tags['token form'] = CSRF::getTokenForm(); // finish rendering page $output = $this->outputs['header'] . "\n" . $this->outputs['body'] . "\n" . $this->outputs['footer'] . "\n"; RenderHTML::RenderTags($output, $this->tags); echo $output; unset($output, $this->outputs); }
function createtask_POST(Web &$w) { $w->Task->navigation($w, "Create Task"); // unserialise input from step I and store in array: arr_req $arr_req = unserialize($w->request('formone')); // set relevant dt variables with: Today. $arr_req['dt_assigned'] = Date('c'); $arr_req['dt_first_assigned'] = Date('c'); // insert Task into database $task = new Task($w); $task->fill($arr_req); $task->insert(); // if insert is successful, store additional fields as task data // we do not want to store data from step I, the task_id (as a key=>value pair) nor the FLOW_SID if ($task->id) { foreach ($_POST as $name => $value) { if ($name != "formone" && $name != "FLOW_SID" && $name != "task_id" && $name !== CSRF::getTokenID()) { $tdata = new TaskData($w); $arr = array("task_id" => $task->id, "key" => $name, "value" => $value); $tdata->fill($arr); $tdata->insert(); unset($arr); } } // return to task dashboard $w->msg("Task " . $task->title . " added", "/task/viewtask/" . $task->id); } else { // if task insert was unsuccessful, say as much $w->msg("The Task could not be created. Please inform the IT Group", "/task/index/"); } }
/** * Grab post data, but only if the CSRF token is valid * * @param InputFilterContainer $filterContainer - Type filter for POST data * @param bool $ignoreCSRFToken - Don't validate CSRF tokens * * @return array|bool * @throws SecurityAlert */ protected function post(InputFilterContainer $filterContainer = null, bool $ignoreCSRFToken = false) { if ($this->airship_http_method !== 'POST' || empty($_POST)) { return false; } if ($ignoreCSRFToken) { if ($filterContainer) { try { return $filterContainer($_POST); } catch (\TypeError $ex) { $this->log('Input validation threw a TypeError', LogLevel::ALERT, \Airship\throwableToArray($ex)); return false; } } return $_POST; } if ($this->airship_csrf->check()) { if ($filterContainer) { try { return $filterContainer($_POST); } catch (\TypeError $ex) { $this->log('Input validation threw a TypeError', LogLevel::ALERT, \Airship\throwableToArray($ex)); return false; } } return $_POST; } $state = State::instance(); if ($state->universal['debug']) { // This is only thrown during development, to be noisy. throw new SecurityAlert(\__('CSRF validation failed')); } $this->log('CSRF validation failed', LogLevel::ALERT); return false; }
/** * Generates an opening HTML form tag. * * // Form will submit back to the current page using POST * echo Form::open(); * * // Form will submit to 'search' using GET * echo Form::open('search', array('method' => 'get')); * * // When "file" inputs are present, you must include the "enctype" * echo Form::open(NULL, array('enctype' => 'multipart/form-data')); * * @param mixed form action, defaults to the current request URI, or [Request] class to use * @param array html attributes * @return string * @uses Request::instance * @uses URL::site * @uses HTML::attributes */ public static function open($action = NULL, array $attributes = NULL) { if ($action instanceof Request) { // Use the current URI $action = $action->uri(); } if (!$action) { // Allow empty form actions (submits back to the current url). $action = ''; } elseif (strpos($action, '://') === FALSE) { // Make the URI absolute $action = URL::site($action); } // Add the form action to the attributes $attributes['action'] = $action; // Only accept the default character set $attributes['accept-charset'] = Kohana::$charset; if (!isset($attributes['method'])) { // Use POST method $attributes['method'] = 'post'; } // Only render the CSRF field when the POST method is used $hidden_csrf_field = $attributes['method'] == 'post' ? self::hidden('form_auth_id', CSRF::token()) : ''; return '<form' . HTML::attributes($attributes) . '>' . $hidden_csrf_field; }
/** * Check if the credentials given can be used to establish a * connection with the DB server */ public static function checkDatabaseConnection() { try { $db = new \PDO("mysql:host=" . self::$database['host'] . ";port=" . self::$database['port'], self::$database['username'], self::$database['password'], array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION)); self::$dbh = $db; self::$dbh->exec("CREATE DATABASE IF NOT EXISTS `" . self::$database['dbname'] . "`"); self::$dbh->query("USE `" . self::$database['dbname'] . "`"); $notable = false; $tables = array("options", "data"); // The Tables of Lobby foreach ($tables as $tableName) { $results = self::$dbh->prepare("SHOW TABLES LIKE ?"); $results->execute(array(self::$database['prefix'] . $tableName)); if (!$results || $results->rowCount() == 0) { $notable = true; } } if (!$notable) { /** * Database tables exist */ echo ser("Error", "Lobby Tables with prefix <b>" . self::$database['prefix'] . "</b> exists. Delete (DROP) those tables and <cl/><a class='btn orange' href='install.php?step=3&db_type=mysql" . \CSRF::getParam() . "'>Try Again</a>"); return false; } } catch (\PDOException $Exception) { self::log("Database Connection Failed : " . $Exception->getMessage()); echo ser("Error", "Unable to connect. Make sure that the settings you entered are correct. <cl/><a class='btn orange' href='install.php?step=3&db_type=mysql" . \CSRF::getParam() . "'>Try Again</a>"); return false; } }
function doCheckLogin() { global $config; if (!isset($_POST[LOGIN_FORM_USERNAME]) || !isset($_POST[LOGIN_FORM_PASSWORD])) { return; } $username = trim(stripslashes(@$_POST[LOGIN_FORM_USERNAME])); $password = stripslashes(@$_POST[LOGIN_FORM_PASSWORD]); session_init(); if (CSRF::isEnabled() && !isset($_SESSION[CSRF::SESSION_KEY])) { echo '<p style="color: red;">PHP Session seems to have failed!</p>'; CSRF::ValidateToken(); exit; } CSRF::ValidateToken(); $password = md5($password); $config['user']->doLogin($username, $password); if ($config['user']->isOk() && getVar('error') == '') { // success $lastpage = getLastPage(); if (strpos($lastpage, 'login') !== FALSE) { $lastpage = './'; } ForwardTo($lastpage); exit; } unset($username, $password); }
public function testInvalidCodeWrongIP() { CSRF::setSecret(uniqid(true)); $_SERVER['REMOTE_ADDR'] = '8.8.8.8'; $code = CSRF::generate(); $_SERVER['REMOTE_ADDR'] = '8.8.4.4'; $this->assertFalse(CSRF::verify($code)); }
/** * Define some pages by default */ public static function defaults() { /** * Route App Pages (/app/{appname}/{page}) to according apps */ self::route("/app/[:appID]?/[**:page]?", function ($request) { $AppID = $request->appID; $page = $request->page != "" ? "/{$request->page}" : "/"; /** * Check if App exists */ $App = new \Lobby\Apps($AppID); if ($App->exists && $App->enabled) { $class = $App->run(); $AppInfo = $App->info; /** * Set the title */ Response::setTitle($AppInfo['name']); /** * Add the App item to the navbar */ \Lobby\UI\Panel::addTopItem("lobbyApp{$AppID}", array("text" => $AppInfo['name'], "href" => $AppInfo['url'], "subItems" => array("app_admin" => array("text" => "Admin", "href" => "/admin/apps.php?app={$AppID}"), "app_disable" => array("text" => "Disable", "href" => "/admin/apps.php?action=disable&app={$AppID}" . \CSRF::getParam()), "app_remove" => array("text" => "Remove", "href" => "/admin/apps.php?action=remove&app={$AppID}" . \CSRF::getParam())), "position" => "left")); $pageResponse = $class->page($page); if ($pageResponse === "auto") { if ($page === "/") { $page = "/index"; } if (is_dir($class->fs->loc("src/page{$page}"))) { $page = "{$page}/index"; } $html = $class->inc("/src/page{$page}.php"); if ($html) { Response::setPage($html); } else { ser(); } } else { if ($pageResponse === null) { ser(); } else { Response::setPage($pageResponse); } } } else { echo ser(); } }); /** * Dashboard Page * The main Page. Add CSS & JS accordingly */ self::route("/", function () { Response::setTitle("Dashboard"); \Lobby\UI\Themes::loadDashboard("head"); Response::loadPage("/includes/lib/lobby/inc/dashboard.php"); }); }
function smarty_function_csrf_protected($params, $smarty) { import('system/share/security/csrf'); $name = $params['name'] ? $params['name'] : 'CSRF_TOKEN'; $csrf_token = CSRF::generate($name); return <<<EOF <input type="hidden" name="{$name}" value="{$csrf_token}" /> EOF; }
public static function __constructStatic() { if (!isset($_COOKIE['csrfToken'])) { self::$token = Helper::randStr(10); setcookie("csrfToken", self::$token, 0, "/", Lobby::getHostname()); } else { self::$token = $_COOKIE['csrfToken']; } }
public function before() { parent::before(); if (!CSRF::check()) { throw new ApplicationException("Cross site request forgery.", 403); } // Set base title $this->template->title = array('Hacker Tees'); $this->template->section = NULL; }
public static function auto_check($base_app) { if ('POST' == !$_SERVER['REQUEST_METHOD'] || !isset($_POST[self::$name])) { return true; } if (self::check() < 1) { self::deny($base_app); } self::$valid = true; }
public function executeShow(sfWebRequest $request) { $this->forward404Unless($this->inbox = Doctrine::getTable('Inbox')->find(array($request->getParameter('id'))), sprintf('Object inbox does not exist (%s).', $request->getParameter('id'))); $this->comments = Comment::getFor($this->inbox); $this->form = new CommentInboxForm(); $this->form->setCommented($this->inbox); $this->form->setDefault('noVote', 1); $this->inboxed = Doctrine_Query::create()->select()->from('sfGuardUserProfile p')->leftJoin('p.Inboxed i')->where('i.inbox_id = ?', $this->inbox->getId())->execute(); $this->csrf = CSRF::getToken(); }
public static function valid($token) { if (!CSRF::valid($token)) { $css_files = array(); $view = "access_denied"; \CODOF\Smarty\Layout::load($view, $css_files); return false; } return true; }
/** * Simple register for user * */ public function action_register() { $this->template->content = View::factory('pages/auth/register'); $this->template->content->msg = ''; //if user loged in redirect home if (Auth::instance()->logged_in()) { $this->request->redirect(Route::get('oc-panel')->uri()); } elseif (core::post('email') and CSRF::valid('register')) { $email = core::post('email'); if (Valid::email($email, TRUE)) { if (core::post('password1') == core::post('password2')) { //check we have this email in the DB $user = new Model_User(); $user = $user->where('email', '=', $email)->limit(1)->find(); if ($user->loaded()) { Form::set_errors(array(__('User already exists'))); } else { //create user $user->email = $email; $user->name = core::post('name'); $user->status = Model_User::STATUS_ACTIVE; $user->id_role = 1; //normal user $user->password = core::post('password1'); $user->seoname = $user->gen_seo_title(core::post('name')); try { $user->save(); } catch (ORM_Validation_Exception $e) { //Form::errors($content->errors); } catch (Exception $e) { throw new HTTP_Exception_500($e->getMessage()); } //login the user Auth::instance()->login(core::post('email'), core::post('password1')); //send email $user->email('auth.register', array('[USER.PWD]' => core::post('password1'), '[URL.QL]' => $user->ql('default', NULL, TRUE))); Alert::set(Alert::SUCCESS, __('Welcome!')); //login the user $this->request->redirect(Core::post('auth_redirect', Route::url('oc-panel'))); } } else { Form::set_errors(array(__('Passwords do not match'))); } } else { Form::set_errors(array(__('Invalid Email'))); } } //template header $this->template->title = __('Register new user'); }
public static function Render($template_name, $localized_strings, $data) { global $template_global_vars, $cphp_debug_enabled; $data = array_merge($data, $template_global_vars); $templater = new NewTemplater(); $templater->Load($template_name); $templater->Localize($localized_strings); $templater->Parse(); if ($cphp_debug_enabled === true) { echo $templater->root->PrintDebug(0, true); } $result = $templater->Evaluate($localized_strings, $data); $result = CSRF::InsertTokens($result); return $result; }
/** * Processes the request, executing the controller action that handles this * request, determined by the [Route]. * * 1. Before the controller action is called, the [Controller::before] method * will be called. * 2. Next the controller action will be called. * 3. After the controller action is called, the [Controller::after] method * will be called. * * By default, the output from the controller is captured and returned, and * no headers are sent. * * $request->execute(); * * @return Response * @throws Request_Exception * @throws HTTP_Exception_404 * @uses [Kohana::$profiling] * @uses [Profiler] */ public function execute() { if (!$this->_route instanceof Route) { throw new HTTP_Exception_404('Unable to find a route to match the URI: :uri', array(':uri' => $this->_uri)); } if (!$this->_client instanceof Request_Client) { throw new Request_Exception('Unable to execute :uri without a Kohana_Request_Client', array(':uri' => $this->_uri)); } // Add custom header for CSRF protection where an Ajax // request is made via HTTP POST if ($this->method() === 'POST' and $this->is_ajax()) { $this->headers('X-CSRF-Token', CSRF::token()); } return $this->_client->execute($this); }
function configwidget_POST(Web $w) { $p = $w->pathMatch("origin", "id"); // "origin", "source", "widget"); // $widget = $w->Widget->getWidget($p["origin"], $p["source"], $p["widget"]); $widget = $w->Widget->getWidgetById($p["id"]); // $widgetname = $p["widget"]; if (empty($widget->id)) { $w->error("Widget not found", "/{$p['origin']}"); } $vars = $_POST; unset($vars[CSRF::getTokenID()]); $widget->custom_config = json_encode($vars); $widget->update(); $w->msg("Widget updated", "/{$p['origin']}"); }
/** * Processa o formulário de login */ protected static function processLoginForm() { // proteção contra CSRF \CSRF::Check(); $email = isset($_POST['email']) ? $_POST['email'] : null; $password = isset($_POST['password']) ? $_POST['password'] : null; $hashedPassword = \Hash::password($password); $errors = []; if (empty($email)) { $errors[] = 'Informe seu email'; } if (empty($password)) { $errors[] = 'Informe sua senha'; } if (count($errors) > 0) { return \View::make('login', compact('errors')); } $DB = new \DB(); $sql = "SELECT id, password, status FROM users WHERE email = :email"; $stmt = $DB->prepare($sql); $stmt->bindParam(':email', $email); $stmt->execute(); $rows = $stmt->fetchAll(\PDO::FETCH_OBJ); if (count($rows) <= 0) { $errors[] = 'Usuário não encontrado'; } else { $user = $rows[0]; if ($hashedPassword != $user->password) { $errors[] = 'Senha incorreta'; } elseif ($user->status != \Models\User::STATUS_ACTIVE) { $errors[] = 'Ative sua conta antes de fazer login'; } else { // busca os dados do usuário para criar os dados no cookie $objUser = new \Models\User(); $objUser->find($user->id); // gera um token de acesso $token = $objUser->generateToken(); // salva o cookie com os dados do usuário self::saveSessionCookieForUser($objUser); // redireciona para a página inicial redirect(getBaseURL()); } } if (count($errors) > 0) { return \View::make('login', compact('errors')); } }
/** * Create a New River * Step 1 * @return void */ public function action_index() { $this->step_content = View::factory('pages/river/create/name')->bind('post', $post)->bind('errors', $errors); // Check for form submission if ($_POST and CSRF::valid($_POST['form_auth_id'])) { $post = Arr::extract($_POST, array('river_name', 'river_public')); try { $river = Model_River::create_new($post['river_name'], $post['river_public'], $this->user->account); // Redirect to the /create/open/<id> to open channels $this->request->redirect(URL::site() . $this->account_path . '/river/create/open/' . $river->id); } catch (ORM_Validation_Exception $e) { $errors = $e->errors('validation'); } catch (Database_Exception $e) { $errors = array(__("A river with the name ':name' already exists", array(':name' => $post['river_name']))); } } }
function doChangePassword() { global $config; if (!isset($_POST[CHANGEPASS_FORM_PASSWORD]) || !isset($_POST[CHANGEPASS_FORM_CONFIRM])) { return NULL; } $password = trim(stripslashes(@$_POST[CHANGEPASS_FORM_PASSWORD])); $confirm = trim(stripslashes(@$_POST[CHANGEPASS_FORM_CONFIRM])); unset($_POST[CHANGEPASS_FORM_PASSWORD]); unset($_POST[CHANGEPASS_FORM_CONFIRM]); session_init(); if (CSRF::isEnabled() && !isset($_SESSION[CSRF::SESSION_KEY])) { echo '<p style="color: red;">PHP Session seems to have failed!</p>'; CSRF::ValidateToken(); exit; } CSRF::ValidateToken(); // check passwords match if ($password !== $confirm) { $_SESSION['error'][] = 'Passwords don\'t match. Please try again.'; return FALSE; } // check password length if (strlen($password) < 6) { $_SESSION['error'][] = 'Password is to short, must be at least 6 characters long.'; return FALSE; } // update password in database $result = $config['user']->ChangePassword(md5($password)); // successful change if ($result !== FALSE) { // password has been changed $_SESSION['Temp Pass'] = FALSE; $lastpage = getLastPage(); if (strpos($lastpage, 'login') !== FALSE || strpos($lastpage, 'changepass') !== FALSE) { $lastpage = './'; } ForwardTo($lastpage); exit; } return FALSE; }
public static function Render($template_name, $localized_strings, $data, $presets = array()) { global $template_global_vars, $cphp_debug_enabled; $data = array_merge($data, $template_global_vars); $templater = new NewTemplater(); $templater->Load($template_name); $templater->Localize($localized_strings); $templater->Parse(); if ($cphp_debug_enabled === true) { echo $templater->root->PrintDebug(0, true); } if (!empty($presets)) { foreach ($presets as $preset_key => $preset_value) { $templater->SetPreset($preset_key, $preset_value); } } $result = $templater->Evaluate($localized_strings, $data); $result = CSRF::InsertTokens($result); return $result; }
/** * simple registration without password * @return [type] [description] */ public function action_register() { $provider_name = $this->request->param('id'); $this->template->content = View::factory('pages/auth/register-social', array('provider' => $provider_name, 'uid' => core::get('uid'), 'name' => core::get('name'))); if (core::post('email') and CSRF::valid('register_social')) { $email = core::post('email'); if (Valid::email($email, TRUE)) { //register the user in DB Model_User::create_social($email, core::post('name'), $provider_name, core::get('uid')); //log him in Auth::instance()->social_login($provider_name, core::get('uid')); Alert::set(Alert::SUCCESS, __('Welcome!')); //change the redirect $this->redirect(Route::url('default')); } else { Form::set_errors(array(__('Invalid Email'))); } } //template header $this->template->title = __('Register new user'); }
function editsettings_POST(Web $w) { $w->setLayout(null); $p = $w->pathMatch("id"); $id = $p["id"]; if (!$id) { $w->error("Missing parameter in request", "/channels/listprocessors"); } // Remove CSRF token from request $post = $_POST; if (!empty($post[CSRF::getTokenID()])) { unset($post[CSRF::getTokenID()]); } $processor = $w->Channel->getProcessor($id); if (empty($processor->id)) { $w->error("Invalid processor ID", "/channels/listprocessors"); } $processor->settings = json_encode($post); $processor->update(); $w->msg("Processor settings saved", "/channels/listprocessors"); }
/** * Salva a resposta */ public static function store() { // impede acesso a usuário não logado \Auth::denyNotLoggedInUsers(); // impede ataque por CSRF \CSRF::Check(); $questionID = isset($_POST['question_id']) ? (int) $_POST['question_id'] : null; $description = isset($_POST['description']) ? $_POST['description'] : null; $errors = []; if (empty($questionID)) { $errors[] = 'ID da pergunta inválido'; } if (empty($description)) { $errors[] = 'Informe a resposta'; } if (count($errors) > 0) { // se ocorrer erro, exibe-os e encerra a execução deste método, usando o return return \View::make('answer.create', compact('errors')); } // busca o usuário logado $user = \Auth::user(); $user_id = $user->getId(); $now = date('Y-m-d H:i:s'); $DB = new \DB(); $sql = "INSERT INTO answers(user_id, question_id, description, created_at, updated_at) VALUES(:user_id, :question_id, :description, :created_at, :updated_at)"; $stmt = $DB->prepare($sql); $stmt->bindParam(':question_id', $questionID, \PDO::PARAM_INT); $stmt->bindParam(':description', $description); $stmt->bindParam(':user_id', $user_id, \PDO::PARAM_INT); $stmt->bindParam(':created_at', $now); $stmt->bindParam(':updated_at', $now); if ($stmt->execute()) { // redireciona para a pergunta, já com a resposta criada redirect(getBaseURL() . '/pergunta/' . $questionID); } else { // exibe erro e gera um log com os detalhes do problema echo "Erro ao criar resposta"; \Log::error("Erro ao criar resposta: " . print_r($stmt->errorInfo(), true)); } }
function doCheckLogin() { global $config; if (!isset($_POST[LOGIN_FORM_USERNAME]) || !isset($_POST[LOGIN_FORM_PASSWORD])) { return NULL; } $username = trim(stripslashes(@$_POST[LOGIN_FORM_USERNAME])); $password = trim(stripslashes(@$_POST[LOGIN_FORM_PASSWORD])); unset($_POST[LOGIN_FORM_PASSWORD]); session_init(); if (CSRF::isEnabled() && !isset($_SESSION[CSRF::SESSION_KEY])) { echo '<p style="color: red;">PHP Session seems to have failed!</p>'; CSRF::ValidateToken(); exit; } CSRF::ValidateToken(); // check hashed password $result = $config['user']->doLogin($username, md5($password)); // try temporary password if ($result !== TRUE && strlen($password) < 32) { // unset($_GET['error']); $result = $config['user']->doLogin($username, $password); if ($result === TRUE && $config['user']->isOk() && getVar('error') == '') { $_SESSION['Temp Pass'] = TRUE; unset($_SESSION['error']); } } // successful login if ($result !== FALSE && $config['user']->isOk() && getVar('error') == '') { $lastpage = getLastPage(); if (strpos($lastpage, 'login') !== FALSE) { $lastpage = './'; } ForwardTo($lastpage); exit; } unset($username, $password); return TRUE; }
/** * Processa o formulário de criação de pergunta */ public static function store() { \Auth::denyNotLoggedInUsers(); \CSRF::Check(); $title = isset($_POST['title']) ? $_POST['title'] : null; $description = isset($_POST['description']) ? $_POST['description'] : null; $errors = []; if (empty($title)) { $errors[] = 'Informe o título da pergunta'; } if (empty($description)) { $errors[] = 'Informe a descrição da pergunta'; } if (count($errors) > 0) { // se ocorrer erro, exibe-os e encerra o método usando return return \View::make('question.create', compact('errors')); } $user = \Auth::user(); $user_id = $user->getId(); $now = date('Y-m-d H:i:s'); $DB = new \DB(); $sql = "INSERT INTO questions(user_id, title, description, created_at, updated_at) VALUES(:user_id, :title, :description, :created_at, :updated_at)"; $stmt = $DB->prepare($sql); $stmt->bindParam(':title', $title); $stmt->bindParam(':description', $description); $stmt->bindParam(':user_id', $user_id, \PDO::PARAM_INT); $stmt->bindParam(':created_at', $now); $stmt->bindParam(':updated_at', $now); if ($stmt->execute()) { // busca o ID gerado na inserção $id = $DB->lastInsertId(); // redireciona para a páginca com o pergunta criada redirect(getBaseURL() . '/pergunta/' . $id); } else { echo "Erro ao criar pergunta"; \Log::error("Erro ao criar pergunta: " . print_r($stmt->errorInfo(), true)); } }
/** * Processes the request, executing the controller action that handles this * request, determined by the [Route]. * * 1. Before the controller action is called, the [Controller::before] method * will be called. * 2. Next the controller action will be called. * 3. After the controller action is called, the [Controller::after] method * will be called. * * By default, the output from the controller is captured and returned, and * no headers are sent. * * $request->execute(); * * @return Response * @throws Request_Exception * @throws HTTP_Exception_404 * @uses [Kohana::$profiling] * @uses [Profiler] */ public function execute() { if (!$this->_external) { $processed = Request::process($this, $this->_routes); if ($processed) { // Store the matching route $this->_route = $processed['route']; $params = $processed['params']; // Is this route external? $this->_external = $this->_route->is_external(); if (isset($params['directory'])) { // Controllers are in a sub-directory $this->_directory = $params['directory']; } // Store the controller $this->_controller = $params['controller']; // Store the action $this->_action = isset($params['action']) ? $params['action'] : Route::$default_action; // These are accessible as public vars and can be overloaded unset($params['controller'], $params['action'], $params['directory']); // Params cannot be changed once matched $this->_params = $params; } } if (!$this->_route instanceof Route) { return HTTP_Exception::factory(404, 'Unable to find a route to match the URI: :uri', array(':uri' => $this->_uri))->request($this)->get_response(); } if (!$this->_client instanceof Request_Client) { throw new Request_Exception('Unable to execute :uri without a Kohana_Request_Client', array(':uri' => $this->_uri)); } // Add custom header for CSRF protection where an Ajax // request is made via HTTP POST if ($this->method() === 'POST' and $this->is_ajax()) { $this->headers('X-CSRF-Token', CSRF::token()); } return $this->_client->execute($this); }