Parameters for activation page - php

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.

Related

Can't set error message in Code Igniter 3 when using callback function

I am writing a method that uses POST variables posted by AJAX to add a user to a certain course in the database, but I can't get the callback to work correctly:
public function enroll()
{
$package = array();
$this->load->library('form_validation');
$this->form_validation->set_rules('course', 'Vak', 'required|callback_not_enrolled');
$fields = array("course");
if ($this->form_validation->run($this) === FALSE) {
$errors = array();
$success = array();
foreach ($fields as $field) {
$error = form_error($field);
if ($error !== "") {
$errors[$field] = $error;
} else {
$success[$field] = True;
}
}
$package["field_errors"] = $errors;
$package["field_success"] = $success;
$package["success"] = False;
} else {
$package["database"] = $this->course_model->enroll_user($this->data["user"], $this->input->post("course"));
$package["success"] = True;
}
echo json_encode($package);
}
I wrote the callback not_enrolled to check if the user is not already enrolled to the database. Note that I can't use is_unique because I have to test the combined uniqueness of two fields (so just one or two separate ones don't do the trick) and the id of the user is not included in the form (because it's part of the Code Igniter session).
The callback function:
public function _not_enrolled($course)
{
$exists = ($this->user->is_enrolled($course, $this->data["user_id"]) != False);
if ($exists != False) {
$this->form_validation->set_message("not_enrolled", "Already enrolled");
return False;
} else {
return True;
}
}
And finally the method is_enrolled from the model:
public function is_enrolled($course, $user=False) {
if($user==False){
$user = $this->data["user_id"];
}
$this->db->select()->from("course_participant")->where("user_id", $user)->where("course_id", $course);
$query = $this->db->get();
return($query->num_rows()>0);
}
Through a call to var_dump($this->_not_enrolled($existing_course_id)); I know that both the callback function and the method from the model work, as it correctly returned true.
When I var_dump the $package array or validation_errors() I don't get any validation errors except that it says Unable to access an error message corresponding to your field name Vak(not_enrolled).
I tried removing the initial _ from the function name but that gives me a Server Status 500 error.
I have another setup exactly like this, albeit other database calls, with a callback using the same syntax. This method works perfectly.

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.

Function parameters when variables values are not set

How can I call a function without throwing any errors when certain variables are not set?
For example, I need to logUserActivity($uName,$uId). This'll work ok if a user is logged in and both those variables are set. However, it will not work if a user is not logged in, and will throw an error.
In that case can, something be done to make those two values NULL?
I did this: logUserActivity($uName=NULL,$uId=NULL) but this makes them forever NULL.
I also did function logUserActivity($uName=NULL, $uId=NULL), by this still throws an error.
You have to set default value of a function to make it optional
Like try this
function logUserActivity($uName='', $uId='')
function logUserActivity($uName=NULL, $uId=NULL){
if($uName != ''){
echo 'Uname is set - '.$uName;
}
if($uId != ''){
echo 'uId is set - '.$uId;
}
}
logUserActivity(NULL,20);//O/p - uId is set - 20
logUserActivity('Test',NULL);//O/p - Uname is set - Test
logUserActivity('Test',20);//O/p - uId is set - 20,uId is set - 20
logUserActivity(NULL,NULL);//NO O/p
Write like this:
function logUserActivity($uName=NULL, $uId=NULL) // If nothing is passed it will take it as null
{
if($uName==NULL && $uId == NULL) {
//User is not logged in
}
else
{
//user is logged in
}
}
And Call it as when user is logged in
logUserActivity("userName", 12345);
And When user is not logged in
logUserActivity();
For more information you can check this out:http://us2.php.net/manual/en/functions.arguments.php
function logUserActivity($uName=null,$uId=null) {
if ( !isset($uName) || !$uName ) {
$uName = 'some default'; // optionally, return; could be sued
}
if ( !isset($uId) || !$uId) {
$uId = 'some default'; // optionally, return; could be sued
}
}

Activation Routes and controller

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.

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){
}
}
}

Categories