Activation Routes and controller - php

What I'm trying to do is figure out IF I am going to need a route for this situation. After the user registers for my site they are sent a verification email in which they click a link and sent to the activate controller where it verifies that the first parameter is numeric and the second is a string and then if they match together with a record in the db then the user was successfully activated.
Here's what I have for my controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Activate extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('auth');
}
public function index()
{
//Config Defaults Start
$msgBoxMsgs = array();//msgType = dl, info, warn, note, msg
$cssPageAddons = '';//If you have extra CSS for this view append it here
$jsPageAddons = '';//If you have extra JS for this view append it here
$metaAddons = '';//Sometimes there is a need for additional Meta Data such in the case of Facebook addon's
$siteTitle = '';//alter only if you need something other than the default for this view.
//Config Defaults Start
//examples of how to use the message box system (css not included).
//$msgBoxMsgs[] = array('msgType' => 'dl', 'theMsg' => 'This is a Blank Message Box...');
/**********************************************************Your Coding Logic Here, Start*/
$x = 0;
if(($param1 !== NULL)&&($param2 !== NULL))
{
//params not null yay..
if((isset($param1))&&((trim($param1) !== '')||(!empty($param1))))
{
if(!is_numeric($param1))
{
$x++;
}
}
if((isset($param2))&&((trim($param2) !== '')||(!empty($param2))))
{
if(!preg_match('/^[A-Za-z0-9]+$/', $param2))
{
$x++;
}
}
if($x !== 0)
{
$bodyContent = $this->config->item('defaultTemplate') ."error_page";
}
else
{
$bodyContent = $this->config->item('defaultTemplate') ."/usermanagement/forms/activate";//which view file
}
}
else
{
$bodyContent = "error_page";
}
/***********************************************************Your Coding Logic Here, End*/
//Double checks if any default variables have been changed, Start.
//If msgBoxMsgs array has anything in it, if so displays it in view, else does nothing.
if(count($msgBoxMsgs) !== 0)
{
$msgBoxes = $this->msgboxes->buildMsgBoxesOutput(array('display' => 'show', 'msgs' =>$msgBoxMsgs));
}
else
{
$msgBoxes = array('display' => 'none');
}
if($siteTitle == '')
{
$siteTitle = $this->metatags->SiteTitle(); //reads
}
//Double checks if any default variables have been changed, End.
$this->data['msgBoxes'] = $msgBoxes;
$this->data['cssPageAddons'] = $cssPageAddons;//if there is any additional CSS to add from above Variable this will send it to the view.
$this->data['jsPageAddons'] = $jsPageAddons;//if there is any addictional JS to add from the above variable this will send it to the view.
$this->data['siteTitle'] = $siteTitle;//defaults can be changed via models/metatags.php
$this->data['bodyType'] = $bodyType;
$this->data['bodyContent'] = $bodyContent;
$this->load->view($this->config->item('defaultTemplate') .'/usermanagement/index', $this->data);
}
}
/* End of file register.php */
/* Location: ./application/controllers/register.php */
My urls look like siteurl.com/activate/10000/7dfdao87fda8f7

if your URL will be http://example.com/activate/account/12345/abcde then you won't need a route.
if it will be http://example.com/activate/12345/abcde then you will need a route like so:
$route["activate/(:num)/(:any)"] = "activate/account/$1/$2";
that is taking for granted that the activate controller has a method called account which you use to activate accounts.
what this does is takes the first bracketed value (which is a number) and inserts it into the place of $1, then takes the second bracketed value (which is any character) and inserts it in the place of $2
you then need to use the following controller / method:
class Activate extends CI_Controller {
public function account ($var1, $var2) {
// ...process vars etc
}
}
if you use the index method, you'd need to pass the variables to it and then call it in the route :
class Activate extends CI_Controller {
public function index ($var1, $var2) {
// ...process vars etc
}
}
$route["activate/(:num)/(:any)"] = "activate/index/$1/$2";
this is because by changing it to activate/$1/$2you are telling it to look for the method in $1, not the index method.

Related

Laravel extend/include layout if variable == 0

Im using laravel 4.0 im tyring to display a layout only if a variable ==0 (just in case a user tries to navigate to the url instead of clicking through) (i know I can redirect instead of extending but this is undesirable for now)
I am trying to get the layout to only extend when the user navigates to the page manually, noajax is set to true if their is no ajax request being sent when it goes to the function, so if the user where to navigate to the url manually it will still display the page but extend the layout.
#if ($noajax==1)
#extends('layouts.master')
#endif
#section('content')
//controller
public function test($id,$model)
{
if (Request::ajax())
{
//$foreign_key and $model must be <> null
if ($id == null || $model == null) {
$this->render('../Errors/missing_arg', 'error');
return;
}
if($model=="ArtObj")
{
$partable = "art_objects";
$path='img/art-objects/';
}
$parid=$id;
$noajax=0;
$mediaimgs = Media::where('parent_id' , $id )->where('parent_table', $partable)->paginate(15);
$response = Response::Json($mediaimgs);
return View::make('/Admin/manageimage/manage_image',compact('parid','mediaimgs','model','path','noajax'));
}
else{
if($model=="ArtObj")
{
$partable = "art_objects";
$path='img/art-objects/';
}
$parid=$id;
$mediaimgs = Media::where('parent_id' , $id )->where('parent_table', $partable)->paginate(15);
$response = Response::Json($mediaimgs);
$noajax = 1;
return View::make('/Admin/manageimage/manage_image',compact('parid','mediaimgs','model','path','noajax'));
}
}
In this case you should use 2 views in controller.
In controller you should use:
if ($noajax) {
return View::make('noajax');
}
else {
return View::make('ajax');
}
In noajax view you can extend from any other view and if noajax and ajax have common code, you should put it in separate file and use #include in those both views to include common part of code.

Parameters for activation page

I am just completely stumped at this and so is my buddy who created this template system.
I have a registration page that sends the user an email with a link to the account activation page in which they must fill out there password to confirm. Inside the link is their user_id and a random string for a registration key.
Here's what I normal url would look like :
kansasoutlawwrestling.com/kowmanager/activate/10000/da54d6fad5fa5fadf
What I want to do is if either of these statements are true then it shows my 404 error page:
Doesn't have the user_id in the url
Doesn't have the registration key in the url
Doesn't have either the two parameters in the url
Activate Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Activate extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('kow_auth');
}
public function index($param1 = NULL, $param2 = NULL)
{
//Config Defaults Start
$msgBoxMsgs = array();//msgType = dl, info, warn, note, msg
$cssPageAddons = '';//If you have extra CSS for this view append it here
$jsPageAddons = '<script src="http://www.kansasoutlawwrestling.com/kowmanager/assets/js/activatevalidate.js"></script>';//If you have extra JS for this view append it here
$metaAddons = '';//Sometimes there is a need for additional Meta Data such in the case of Facebook addon's
$siteTitle = '';//alter only if you need something other than the default for this view.
//Config Defaults Start
//examples of how to use the message box system (css not included).
//$msgBoxMsgs[] = array('msgType' => 'dl', 'theMsg' => 'This is a Blank Message Box...');
/**********************************************************Your Coding Logic Here, Start*/
$x = 0;
if(($param1 !== NULL)&&($param2 !== NULL))
{
//params not null yay..
if((isset($param1))&&((trim($param1) !== '')||(!empty($param1))))
{
if(!is_numeric($param1))
{
$x++;
}
}
if((isset($param2))&&((trim($param2) !== '')||(!empty($param2))))
{
if(!is_string($param2))
{
$x++;
}
}
}
else
{
$x++;
}
if($x !== 0)
{
$bodyContent = "error_page";
}
else
{
$bodyContent = "activate_form";
}
$bodyType = "full";//type of template
/***********************************************************Your Coding Logic Here, End*/
//Double checks if any default variables have been changed, Start.
//If msgBoxMsgs array has anything in it, if so displays it in view, else does nothing.
if(count($msgBoxMsgs) !== 0)
{
$msgBoxes = $this->msgboxes->buildMsgBoxesOutput(array('display' => 'show', 'msgs' =>$msgBoxMsgs));
}
else
{
$msgBoxes = array('display' => 'none');
}
if($siteTitle == '')
{
$siteTitle = $this->metatags->SiteTitle(); //reads
}
//Double checks if any default variables have been changed, End.
$this->data['msgBoxes'] = $msgBoxes;
$this->data['cssPageAddons'] = $cssPageAddons;//if there is any additional CSS to add from above Variable this will send it to the view.
$this->data['jsPageAddons'] = $jsPageAddons;//if there is any addictional JS to add from the above variable this will send it to the view.
$this->data['metaAddons'] = $metaAddons;//if there is any addictional meta data to add from the above variable this will send it to the view.
$this->data['pageMetaTags'] = $this->metatags->MetaTags();//defaults can be changed via models/metatags.php
$this->data['siteTitle'] = $siteTitle;//defaults can be changed via models/metatags.php
$this->data['bodyType'] = $bodyType;
$this->data['bodyContent'] = $bodyContent;
$this->load->view('usermanagement/index', $this->data);
}
function activate_submit()
{
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length[6]|max_length[12]|alpha_numeric');
$user_id = $this->uri->segment(3);
$registration_key = $this->uri->segment(4);
if (($registration_key == '') OR ($user_id == ''))
{
echo json_encode(array('error' => 'yes', 'message' => 'URL was not complete!'));
}
else
{
if (!$this->form_validation->run())
{
echo json_encode(array('error' => 'yes', 'message' => 'There was a problem submitting the form! Please refresh the window and try again!'));
}
else
{
if ($this->kow_auth->activate_user($user_id, $registration_key, $this->input->post('password')))
{
echo json_encode(array('sucess' => 'yes', 'message' => 'Your account has been successfully activated!'));
}
else
{
echo json_encode(array('error' => 'yes', 'message' => 'The activation code you entered is incorrect or expired!'));
}
}
}
}
}
/* End of file activate.php */
/* Location: ./application/controllers/activate.php */
Routes:
$route['activate/:num/:any'] = 'activate/index/$1/$2';
$route['404_override'] = 'error';
Here's what I'm getting for each of those instances:
kansasoutlawwrestling.com/kowmanager/activate - correct
kansasoutlawwrestling.com/kowmanager/activate/10000/ - correct
kansasoutlawwrestling.com/kowmanager/activate/10000/271cce33ab11ced5fd10aeca41323a3c - incorrect should be showing the activate form
EDIT : Anybody have any ideas because it just seems like nothing is working.
I'll start by simplifying a bit the params checking:
$this->error = FALSE;
if(NULL != $param1 AND NULL != $param2)
{
if(!is_numeric($param1) OR (string)trim($param2)!= '')
{
$this->error = TRUE;
}
}
else
{
$this->error = TRUE;
}
$this->data['bodyContent'] = $this->error? 'error_page' : 'activate_form';
It's late here so I might messed up something, but basically:
if both params are null, set $error to TRUE (they don't have to be null);
if at least one isn't null:
- if param1 isn't numeric (userid) or
- if param2 isn't a string (nor even an empty one), $error is again TRUE.
In the end, if error is FALSE (as initialized), we pass the "activate_form" value to the view, else (i.e. if any of the above condition caused the error to be set to TRUE), we pass the "error_page" value.
Also, as per documentation, custom routes should go after fixed ones:
$route['404_override'] = 'error';
$route['activate/(:num)/(:any)'] = 'activate/index/$1/$2';
Out of curiosity...what happens if you remove the following line?
if(!is_string($param2))
And you just have:
if((isset($param2))&&((trim($param2) !== '')||(!empty($param2))))
{
$x++;
}
You dont need to create a new controlller/module for account activation, simply add a new method inside your existing auth controller/module.
IF you setup a route with conditions and they fail, your shown an error or 404.
class Auth extends CI_Controller
{
public function __construct(){parent::__construct();}
/**
* Activate user account
* $route['activate/(:num)/(:any)'] = 'auth/activate/$1/$2';
*/
public function activate($uid, $code)
{
//if need be, double check
if(!$uid OR !$code){show_404();} //BOTH need to exists
//if $route['activate/(:num)/(:any)'] = 'auth/activate/$1/$2'; FAILS CI will show error or 404
//grab $code and $uid and seek a match from DB, if failure do your own errors.
}
}
I would suggest removing the user id from the uri segment and make the activation code a UNIQUE db constraint so you only have to query for that.
Take a look at Tank Auth
It is a CI library that already does this, but with a key difference, you don't want to pass more than you have to. So just generate a HASH (encrypted for instance), that lets you find the userid & activate at the same time.
It is less checking and less issues with copy & pasting URL. Also eliminates having to do all this extra checking of ID validity + hash validity.
But as I said, look at the tank auth code, and pull out what you need for the activation part, it's fairly straight forward, and already for CI.

URI Routing for codeigniter

I'm trying to figure out how I should do this. The following controller is for a bio page for each wrestler. Here's an example.
http://kansasoutlawwrestling.com/bio/kid-wonder
Now if you notice there's three links Biography, Wrestling, Appearances.
One question I have is should all three be different functions inside this controller?
If the answer is yes are the links actually correct on the page link?
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Bio extends CI_Controller
{
function index($character = "jfkdlsjl")
{
//Config Defaults Start
$msgBoxMsgs = array();//msgType = dl, info, warn, note, msg
$cssPageAddons = '';//If you have extra CSS for this view append it here
$jsPageAddons = '';//If you have extra JS for this view append it here
$metaAddons = '';//Sometimes there is a need for additional Meta Data such in the case of Facebook addon's
$siteTitle = '';//alter only if you need something other than the default for this view.
//Config Defaults Start
//examples of how to use the message box system (css not included).
//$msgBoxMsgs[] = array('msgType' => 'dl', 'theMsg' => 'This is a Blank Message Box...');
/**********************************************************Your Coding Logic Here, Start*/
$activeTemplate = $this->sitemodel->getTemplate();
$footerLinks = $this->sitemodel->getFooterNav();
$bodyContent = "bio";//which view file
$bodyType = "main";//type of template
$this->data['activeTemplate'] = $activeTemplate;
$this->data['footerLinks']= $footerLinks;
$this->load->model('biomodel');
if($character !== "jfkdlsjl")
{
if((!empty($character))||(!isset($character))||(trim($character) !== '')||($character !== NULL))
{
$bioArray = $this->biomodel->getCharacterBio($character);
if ($bioArray == "empty")
{
$this->data['bioArray']= array();
}
else
{
if (($bioArray[0]->characters_statuses_id == 2)||($bioArray[0]->characters_statuses_id == 3)||($bioArray[0]->characters_statuses_id == 5))
{
$this->data['bioArray']= array();
}
else
{
$this->data['bioArray']= $bioArray;
$bioPagesArray = $this->biomodel->getBioPages();
$alliesArray = $this->biomodel->getCharacterAllies($bioArray[0]->id);
$rivalsArray = $this->biomodel->getCharacterRivals($bioArray[0]->id);
$quotesArray = $this->biomodel->getCharacterQuotes($bioArray[0]->id);
$this->data['bioPagesArray']= $bioPagesArray;
$this->data['alliesArray']= $alliesArray;
$this->data['rivalsArray']= $rivalsArray;
$this->data['quotesArray']= $quotesArray;
}
}
}
}
/***********************************************************Your Coding Logic Here, End*/
//Double checks if any default variables have been changed, Start.
//If msgBoxMsgs array has anything in it, if so displays it in view, else does nothing.
if(count($msgBoxMsgs) !== 0)
{
$msgBoxes = $this->msgboxes->buildMsgBoxesOutput(array('display' => 'show', 'msgs' =>$msgBoxMsgs));
}
else
{
$msgBoxes = array('display' => 'none');
}
if($siteTitle == '')
{
$siteTitle = $this->metatags->SiteTitle(); //reads
}
//Double checks if any default variables have been changed, End.
$this->data['msgBoxes'] = $msgBoxes;
$this->data['cssPageAddons'] = $cssPageAddons;//if there is any additional CSS to add from above Variable this will send it to the view.
$this->data['jsPageAddons'] = $jsPageAddons;//if there is any addictional JS to add from the above variable this will send it to the view.
$this->data['metaAddons'] = $metaAddons;//if there is any addictional meta data to add from the above variable this will send it to the view.
$this->data['pageMetaTags'] = $this->metatags->MetaTags();//defaults can be changed via models/metatags.php
$this->data['siteTitle'] = $siteTitle;//defaults can be changed via models/metatags.php
$this->data['bodyType'] = $bodyType;
$this->data['bodyContent'] = $bodyContent;
$this->load->view($activeTemplate[0]->short_name.'/index', $this->data);
}
}
/* End of file bio.php */
/* Location: ./application/controllers/bio.php */
EDIT: I'm really concerned with the biography page link when I'm on the bio page like the link above.
Here's what I have currently for my route: $route['bio/(:any)'] = "bio/index/$1";
It would be the best to have separate controllers for each of the 3 links.
But if you don't want to, and still want the links /appearances/whatever, here's the routing you need to keep it all within the Bio controller:
UPDATE - this is still a bad approach, but it should do.
if ($this->uri->segment(1) == 'bio') {
$route['bio/(:any)'] = "bio/index/$1";
} else {
$route['wrestling/(:any)'] = "bio/wrestling/$1";
$route['appearances/(:any)'] = "bio/appearances/$1";
}
UPDATE 2: you got me confused, but the first solution HAS to work, even the order doesn't matter:
$route['bio/(:any)'] = "bio/index/$1";
$route['wrestling/(:any)'] = "bio/wrestling/$1";
$route['appearances/(:any)'] = "bio/appearances/$1";
bio/kid goes to bio/index/kid
wrestling/kid goes to bio/wrestling/kid
appearances/kid goes to bio/appearances/kid
You currently have this setup:
The functions
function index($wrestlerName = null){ }
function wrestling($wrestlerName = null){ }
function appearances($wrestlerName = null){ }
The links
bio/kid-wonder
bio/wrestling/kid-wonder
bio/appearances/kid-wonder
If you wanted to have the wrestling/kid-wonder and appearances/kid-wonder without the bio at the beginning of the url, you are going to need to create new controllers for wrestling and appearances.
class wrestler extends CI_Controller {
function index($wrestlerId = NULL){
if($wrestlerId != NULL){
}
}
}
class appearances extends CI_Controller {
function index($wrestlerId = NULL){
if($wrestlerId != NULL){
}
}
}

opencart to stop view index page until login

i am using opencart in one project,
every thing is working fine but i am unable to find an option to stop view of home page until LOGIN.
actually this is project requirement, no one can see home until LOGIN.
is there way to do this with OPEN CART ?
Thanks
this is untested, but should point you in the right direction:
(OpenCart 1.4.9.x)
Save this to:
catalog/controller/common/check_login.php
<?php
class ControllerCommonCheckLogin extends Controller {
public function index() {
if (!$this->customer->isLogged()) {
// Require to be logged in
$ignore = array(
'account', 'payment'
);
$match = false;
if (isset($this->request->get['route'])) {
foreach ($ignore as $i) {
if (strpos($this->request->get['route'], $i) !== false) {
$match = true;
break;
}
}
}
// Show site if logged in as admin
$this->load->library('user');
$this->registry->set('user', new User($this->registry));
if (!$this->user->isLogged() && !$match) {
return $this->forward('account/login');
}
}
}
}
?>
Edit /index.php
Find:
// Maintenance Mode
$controller->addPreAction(new Action('common/maintenance/check'));
Add After:
// Login Check
$controller->addPreAction(new Action('common/check_login'));
Essentially use the same logic as the maintenence check... The big difference is it looks for the word 'account' in the string... If it finds it it allows the page to be displayed, if not it redirects to the login page...
Use the word "account" instead of "login" in case they need to register... All of the account pages already check for loggin so there is no worry there...
Again, untested so you may need to tweak one or two things - but it should/may work by dropping in the code
check_login.php for opencart 1.5.3
<?php
class ControllerCommonCheckLogin extends Controller {
public function index() {
// Require to be logged in
if (!$this->customer->isLogged()) {
// Require to be logged in
$ignore = array(
'account','payment'
);
$match = false;
if (isset($this->request->get['route'])) {
foreach ($ignore as $i) {
if (strpos($this->request->get['route'], $i) !== false) {
$match = true;
break;
}
}
}
// Show site if logged in as admin
$this->load->library('user');
$this->user = new User($this->registry);
if (!$this->user->isLogged() && !$match) {
$this->redirect($this->url->link('account/login'));
}
}
}
}
?>
There is nothing built-in that I know of, but you can do it yourself. Based on your answers to #CarpeNoctumDC's questions you may have to do some digging, but this should get you started:
system/library/customer.php
public function isLogged() { ... }
catalog/controller/common/home.php
if (!$this->customer->isLogged()) {
// login page
exit;
}
The right way to go about this is to open
/catalog/controller/common/home.php
find public function index() { at the top of the code, and after it put
if(!$this->customer->isLogged()) {
$this->session->data['redirect'] = $this->url->link('common/home');
$this->url->redirect('account/login', '', 'SSL');
}
In case you're unsure how to do this properly, just take a look at the first few lines after public function index() { in
/catalog/controller/account/account.php
setting your code in the home controller to common/home in place of account/account

How do I use a controller within a controller?

I am using Kohana 3.2 and I am having problems calling the ouput of a controller in another controller.
What I want...
In some pages I have got a menu, and in others I don't. I want to use make use of the flexability of the HMVC request system. In the controller of a page I want to call another controller which is responsible for the creation of the menu.
What I have a the moment:
file menu.php:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Menu extends Controller
{
private $_model = null;
public function __construct(Request $request, Response $response)
{
parent::__construct($request, $response);
$this->_model = Model::factory('menu');
}
public function action_getMenu()
{
$content = array();
$content['menuItems'] = $this->_model->getMenuItems();
// Render and output.
$this->request->response = View::factory('blocks/menu', $content);
//echo '<pre>'; print_r($this->request->response->render()); echo '</pre>'; die();
}
}
somepage.php
public function action_index()
{
$this->template->title = 'someTitle';;
$contentData['pageTitle'] = 'someTitle';
$contentData['contentData'] = 'someData';
#include the menu
$menuBlock = Request::factory('menu/getMenu')->execute();
$menuData = array('menu' => $menuBlock);
$this->template->menu = View::factory('pages/menu')->set('menu',$menuData);
$this->template->content = View::factory('pages/somePage', $contentData);
$view = $this->response->body($this->template);
$this->response->body($view);
}
If I uncomment the following line in menu.php, I see the menu rendered:
//echo '<pre>'; print_r($this->request->response->render()); echo '</pre>'; die();
So I guess that part is alright. The problem is in the following line in somepage.php:
$menuBlock = Request::factory('menu/getMenu')->execute();
This gives me back a response object. Whatever I do, I do not get the output in $this->template->menu.
$this->template->menu = View::factory('pages/menu')->set('menu',$menuData);
What must I do to have $this->template->menu contain the view, so I can use it correctly?
I hope this all makes sense. This is the way I would like to do it, but maybe I am completely on the wrong track.
I would do it this way:
class Controller_Menu extends Controller
{
public function action_build()
{
// Load the menu view.
$view = View::factory('navigation/menu');
// Return view as response-
$this->response->body($view->render());
}
}
In your controller get the menu as follows:
// Make request and get response body.
$menu = Request::factory('menu/build')->execute()->body();
// e.g. assign menu to template sidebar.
$this->template->sidebar = Request:.factory('menu/build')->execute()->body();
I would not use the __construct method in your controllers. Use before() instead, this is sufficient for most of the problems (for example auth):
public function before()
{
// Call aprent before, must be done here.
parent::before();
// e.g. heck whether user is logged in.
if ( !Auth::instance()->logged_in() )
{
//Redirect if not logged in or something like this.
}
}
I found the answer to my problem in less than an hour after asking.
I just forgot to put it here.
In somePage.php change :
$menuBlock = Request::factory('menu/getMenu')->execute();
$menuData = array('menu' => $menuBlock);
$this->template->menu = View::factory('pages/menu')->set('menu',$menuData);
To:
$this->template->menu = Request::factory('menu/getMenuBlock')->execute()->body();
And in menu.php change:
$this->request->response = View::factory('blocks/menu', $content);
To:
$request = View::factory('blocks/menu', $content);
$this->response->body($request);
I hope this will help someone else.

Categories