Codeigniter - Facebook Login and registeration sing PHP SDK - codeigniter

I am using Facebook PHP SDK with Codeigniter to do login and registration using Facebook. For this I am using This tutorial
my controller 'facebooktest.php' code is:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Facebooktest extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('input');
$this->load->library('session');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->library('security');
}
function Facebooktest() {
parent::Controller();
$cookies = $this->load->model('facebook_model');
}
function index() {
$this->load->view('facebooktest/test2');
}
function test1() {
$data = array();
$data['user'] = $this->facebook_model->get_facebook_cookie();
$this->load->view('facebooktest/test1', $data);
}
function test2() {
$data['friends'] = $this->facebook_model->get_facebook_cookie();
$this->load->view('facebooktest/test2', $data);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
?>
view 'test2.php' has code as:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Kent is Learning CodeIgniter - Test 2</title>
</head>
<body>
<fb:login-button autologoutlink="true"
onlogin="window.location.reload(true);"></fb:login-button>
<div style="width:600px;">
<?
if(isset($friends)){
foreach($friends as $friend){
?>
<img src="http://graph.facebook.com/<?=$friend['id'];?>/picture" title="<?=$friend['name'];?>" />
<?
}
}
?>
</div>
<p><?=anchor('facebook_connect/page4','Go back to page 4 of the tutorial');?></p>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({appId: '457228377680583', status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.sessionChange', function(response) {
if (response.session) {
// A user has logged in, and a new cookie has been saved
window.location.reload(true);
} else {
// The user has logged out, and the cookie has been cleared
}
});
</script>
</body>
</html>
And model 'facebook_model.php' has code:
<?php
class Facebook_model extends CI_Model {
function __construct() {
parent::__construct();
}
function get_facebook_cookie() {
$app_id = '457228377680583';
$application_secret = '01f660b73bc085f0b78cd22322556495';
if (isset($_COOKIE['fbs_' . $app_id])) {
echo "dfgdsf";exit;
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
} else {
return null;
}
}
function getUser() {
$cookie = $this->get_facebook_cookie();
$user = #json_decode(file_get_contents(
'https://graph.facebook.com/me?access_token=' .
$cookie['access_token']), true);
return $user;
}
function getFriendIds($include_self = TRUE) {
$cookie = $this->get_facebook_cookie();
$friends = #json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
$cookie['access_token']), true);
$friend_ids = array();
foreach ($friends['data'] as $friend) {
$friend_ids[] = $friend['id'];
}
if ($include_self == TRUE) {
$friend_ids[] = $cookie['uid'];
}
return $friend_ids;
}
function getFriends($include_self = TRUE) {
$cookie = $this->get_facebook_cookie();
print_r($cookie);
$friends = #json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
$cookie['access_token']), true);
if ($include_self == TRUE) {
$friends['data'][] = array(
'name' => 'You',
'id' => $cookie['uid']
);
}
return $friends['data'];
}
function getFriendArray($include_self = TRUE) {
$cookie = $this->get_facebook_cookie();
$friendlist = #json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
$cookie['access_token']), true);
$friends = array();
foreach ($friendlist['data'] as $friend) {
$friends[$friend['id']] = array(
'name' => $friend['name'],
'picture' => 'http://graph.facebook.com/'.$friend['id'].'/picture'
);
}
if ($include_self == TRUE) {
$friends[$cookie['uid']] = 'You';
}
return $friends;
}
}
?>
The problem is that, in model, it is coming inside 'getFriends()'. From there it is going inside 'get_facebook_cookie()'. But it is not going inside if(isset($_COOKIE['fbs_' . $app_id])))
and hence, it is nor displaying data that I want.
So, if possible, please let me know whats wrong with my code.
Thanks in advance....

Related

How to change prefix locale in blade laravel?

I have middleware
public static function getLocale()
{
$mainLanguage = config('translatable.locale');
$languages = config('translatable.locales');
$uri = Request::path();
$segmentsURI = explode('/',$uri);
if (!empty($segmentsURI[0]) && in_array($segmentsURI[0], $languages)) {
return $segmentsURI[0];
} else {
return $mainLanguage;
}
}
public function handle($request, Closure $next)
{
$locale = self::getLocale();
if($locale) {
App::setLocale($locale);
}
return $next($request);
}
This is my routes/web.php
Route::group(['middleware' => ['localize'],
'prefix' => App\Http\Middleware\LocaleMiddleware::getLocale()], function () {
...routes...
});
This is my header.blade, where I want to change the language of my dropdown choice
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
#foreach(config('translatable.locales') as $locale)
<a class="dropdown-item" href="#">{{strtoupper($locale)}}</a>
#endforeach
</div>
My header is connected to layout and is available on all pages.
I want my routes to look like this (example):
.../en/news
.../en/news/1
What should I write in a href so that I can change the language?
I tried {{$locale . "/" . Request::segment(2)}}
but i get .../es/news/ru/news
I resolved my issue. I added function in route
Route::get('setlocale/{lang}', function ($lang) {
$referer = Redirect::back()->getTargetUrl();
$parse_url = parse_url($referer, PHP_URL_PATH);
$segments = explode('/', $parse_url);
if (in_array($segments[1], App\Http\Middleware\LocaleMiddleware::$languages)) {
unset($segments[1]);
}
if ($lang != App\Http\Middleware\LocaleMiddleware::$mainLanguage){
array_splice($segments, 1, 0, $lang);
}
$url = Request::root().implode("/", $segments);
if(parse_url($referer, PHP_URL_QUERY)){
$url = $url.'?'. parse_url($referer, PHP_URL_QUERY);
}
return redirect($url);
})->name('setlocale');

Object of class error in Codeigniter with loading function in array

On my Welcome controller I have a function called content_top which loads function $this->$part[0]($setting_info); in this case $this->slideshow($setting_info); Then it should display that slideshow functions view in that data array.
When I have refreshed my page I get a error
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_Loader could not be converted to string
Filename: common/content_top.php
Line Number: 7
Backtrace:
File: C:\wamp\www\cms\application\views\common\content_top.php
Line: 7
Function: _error_handler
File: C:\wamp\www\cms\application\controllers\Welcome.php
Line: 51
Function: view
File: C:\wamp\www\cms\application\controllers\Welcome.php
Line: 19
Function: content_top
File: C:\wamp\www\cms\index.php
Line: 292
Function: require_once
And
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_Loader could not be converted to string
Filename: common/welcome_message.php
Line Number: 3
Backtrace:
File: C:\wamp\www\cms\application\views\common\welcome_message.php
Line: 3
Function: _error_handler
File: C:\wamp\www\cms\application\controllers\Welcome.php
Line: 20
Function: view
File: C:\wamp\www\cms\index.php
Line: 292
Function: require_once
Question Is there any way to when I have a function in array to be able to make it display the view with out throwing error.
<?php
class Welcome extends CI_Controller {
public $data = array();
public function __construct() {
parent::__construct();
$this->load->model('design/model_layout');
$this->load->model('extension/model_module');
$this->load->model('design/model_banner');
$this->load->model('tool/model_image');
$this->load->library('image_lib');
}
public function index() {
$this->load->view('common/header');
$data['content_top'] = $this->content_top();
$this->load->view('common/welcome_message', $data);
$this->load->view('common/footer');
}
public function content_top() {
if ($this->uri->segment(1)) {
$route = $this->uri->segment(1) .'/'. $this->uri->segment(2);
} else {
$route = 'common/home';
}
$layout_id = $this->model_layout->get_layout($route);
$data['modules'] = array();
$modules = $this->model_layout->get_layout_modules($layout_id, 'content_top');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
if (isset($part[1])) {
$setting_info = $this->model_module->get_module($part[1]);
if ($setting_info) {
$data['modules'][] = $this->$part[0]($setting_info);
}
}
}
return $this->load->view('common/content_top', $data);
}
public function slideshow($setting_info) {
static $module = 0;
$data['banners'] = array();
$results = $this->model_banner->get_banner($setting_info['banner_id']);
foreach ($results as $result) {
$data['banners'][] = array(
'banner_image' => $this->model_image->resize($result['banner_image'], $setting_info['width'], $setting_info['height'])
);
}
$data['module'] = $module++;
$data['resize_errors'] = $this->image_lib->display_errors();
return $this->load->view('module/slideshow', $data);
}
}
In the CI when you loading the view and printing as a string then need to pass the third parameter as 'TRUE'.
<?php echo $this->load->view('headers/menu', '', TRUE);?>
Solved
On the controller I had to change a couple things around
I also have had to use a template layout to minimize the views
But on content_top and sideshow function I had to use return and true
return $this->load->view('folder/name', $this->data, TRUE);
Controller
<?php
class Home extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('design/model_layout');
$this->load->model('extension/model_module');
$this->load->model('design/model_banner');
$this->load->model('tool/model_image');
$this->load->library('image_lib');
}
public function index() {
$this->data['title'] = 'Home';
$this->data = array(
'column_left' => $this->column_left(),
'column_right' => $this->column_right(),
'content_bottom' => $this->content_bottom(),
'content_top' => $this->content_top(),
'page' => 'common/home'
);
$this->load->view('common/template', $this->data);
}
public function column_left() {
$route = 'common/home';
$layout_id = $this->model_layout->get_layout($route);
$this->data['modules'] = array();
$modules = $this->model_layout->get_layout_modules($layout_id, 'column_left');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
$setting_info = $this->model_module->get_module($part[1]);
$this->data['modules'][] = array (
'module_name' => $this->$part[0]($setting_info)
);
}
return $this->load->view('common/column_left', $this->data, TRUE);
}
public function column_right() {
$route = 'common/home';
$layout_id = $this->model_layout->get_layout($route);
$this->data['modules'] = array();
$modules = $this->model_layout->get_layout_modules($layout_id, 'column_right');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
$setting_info = $this->model_module->get_module($part[1]);
$this->data['modules'][] = array (
'module_name' => $this->$part[0]($setting_info)
);
}
return $this->load->view('common/column_right', $this->data, TRUE);
}
public function content_bottom() {
$route = 'common/home';
$layout_id = $this->model_layout->get_layout($route);
$this->data['modules'] = array();
$modules = $this->model_layout->get_layout_modules($layout_id, 'content_bottom');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
$setting_info = $this->model_module->get_module($part[1]);
$this->data['modules'][] = array (
'module_name' => $this->$part[0]($setting_info)
);
}
return $this->load->view('common/content_bottom', $this->data, TRUE);
}
public function content_top() {
$route = 'common/home';
$layout_id = $this->model_layout->get_layout($route);
$this->data['modules'] = array();
$modules = $this->model_layout->get_layout_modules($layout_id, 'content_top');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
$setting_info = $this->model_module->get_module($part[1]);
$this->data['modules'][] = array (
'module_name' => $this->$part[0]($setting_info)
);
}
return $this->load->view('common/content_top', $this->data, TRUE);
}
/*
Add function for modules that are enabled for this page
*/
public function slideshow($setting_info) {
static $module = 0;
$this->data['banners'] = array();
$results = $this->model_banner->get_banner($setting_info['banner_id']);
foreach ($results as $result) {
$this->data['banners'][] = array(
'banner_image' => $this->model_image->resize($result['banner_image'], $setting_info['width'], $setting_info['height'])
);
}
$this->data['module'] = $module++;
return $this->load->view('module/slideshow', $this->data, TRUE);
}
}
Template View
<?php $this->load->view('common/header');?>
<?php $this->load->view($page);?>
<?php $this->load->view('common/footer');?>
Content Top View
<?php foreach ($modules as $module) {?>
<?php echo $module['module_name'];?>
<?php }?>
Home View
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<?php echo $content_top;?>
</div>
</div>
</div>
Proof Working
This happened to me when I did this:
$model = $this->load->model('user_model);
$data = [
'model' => $model
];
instead of this:
$this->load->model('user_model);
$model = $this->user_model->edit();
$data = [
'model' => $model
];
then when I echoed out the $model, it gave me the error. So I tried to print_r then it gave me a very long array until I realize my mistake. Hope it helps.
Just remove the echo on view page when you are using CI new versions.
<?php $this->load->view('headers/menu');?>
https://stackoverflow.com/a/40675633/2790502

Codeigniter database check

i am currently working on a project where users can save note snippets in there own little user area.
I was wondering how would i check if the id of an item exists for example if a user visits
http://mysite.com/view/1 and there is a note snippet of 1 it will display all the data relating to the id of one. Now if the user was to change the url to lets say 1000, that id doesnt exist and the view just errors.
i want to be able to redirect them back to a certain page with a error message "snippet does not exist" etc.
heres what i have so far ( i currently already have a conditional statement in here to check if the snippet is private, then if it is redirect back to /publicsnippets)
Controller:
class Publicsnippets extends CI_Controller {
function __construct()
{
parent::__construct();
if (!$this->tank_auth->is_logged_in()) {
redirect('/login/');
}
$this->load->model('dashboard_model');
$this->data['user_id'] = $this->tank_auth->get_user_id();
$this->data['username']= $this->tank_auth->get_username();
}
public function index()
{
$this->data['public_snippets'] = $this->dashboard_model->public_snippets();
$this->load->view('dashboard/public_snippets', $this->data);
}
public function view($snippet_id)
{
$snippet = $this->dashboard_model->get_snippet($snippet_id);
if ($snippet['state'] === 'private')
{
$this->session->set_flashdata('message', "<b style=\"color:red;\">You are not allowed to view this snippet!</b>");
redirect('/publicsnippets');
} else {
$this->data['snippet'] = $snippet;
}
$this->load->view('dashboard/view_public_snippet', $this->data);
}
}
Model:
class Dashboard_model extends CI_Model {
public function public_snippets()
{
$this->db->select('id, title, description, tags, author, date_submitted');
$query = $this->db->get_where('snippets', array('state' => 'public'));
return $query->result_array();
}
public function private_snippets()
{
$this->db->select('id, title, description, tags, author, date_submitted');
$query = $this->db->get_where('snippets', array('user_id' => $this->tank_auth->get_user_id()));
return $query->result_array();
}
public function add_snippet($data)
{
$this->db->insert('snippets', $data);
$id = $this->db->insert_id();
return (isset($id)) ? $id : FALSE;
}
public function get_snippet($snippet_id) {
$query = $this->db->get_where('snippets', array('id' => $snippet_id));
return $query->row_array();
}
public function update_snippet($snippet_id, $data)
{
$this->db->where('id', $snippet_id);
$this->db->update('snippets', $data);
}
public function delete_snippet($snippet_id)
{
$this->db->where('id', $snippet_id);
$this->db->delete('snippets');
}
}
View:
<h3>Description</h3>
<p><?php echo $snippet['description']; ?></p>
<h3>Tags</h3>
<p><?php echo $snippet['tags']; ?></p>
<h3>Date Submitted</h3>
<p><?php echo $snippet['date_submitted']; ?></p>
<h3>Snippet</h3></pre>
<pre class="prettyprint"><?php echo $snippet['code_snippet']; ?></pre>
You work is fine just add a check like this in your view method
Controller
public function view($snippet_id)
{
$snippet = $this->dashboard_model->get_snippet($snippet_id);
if($snippet){
if ($snippet['state'] === 'private')
{
$this->session->set_flashdata('message', "<b style=\"color:red;\">You are not allowed to view this snippet!</b>");
redirect('/publicsnippets');
} else {
$this->data['snippet'] = $snippet;
}
$this->load->view('dashboard/view_public_snippet', $this->data);
}else{
$this->session->set_flashdata('message', "<b style=\"color:red;\">snippet does not exist</b>");
redirect('/publicsnippets');
}
}
if no row is found in get_snippet method the $snippet will contain false or null
and the second block of condition will run.
In your model change get_snippet() to check for rows:
public function get_snippet($snippet_id) {
$query = $this->db->get_where('snippets', array('id' => $snippet_id));
if ($query->num_rows() > 0) {
return $query->row_array();
} else {
return false;
}
}
Then in your controller:
if ($snippet = $this->dashboard_model->get_snippet($snippet_id)) {
// code if snippet exists
} else {
// code if snippet doesn't exist
}
OR
$snippet = $this->dashboard_model->get_snippet($snippet_id);
if ($snippet) {
// etc...

Codeigniter. Controller cannot receive session data

I set session successfully as output profiler show me session name and value.
But when I POST data controller cannot receive session data.
Library is loaded, $config['sess_expire_on_close'] = TRUE I've changed TRUE-FALSE without any success. Also tried rewrite code.
And another question I use two PC and on Linux machine I get error "Header already sent...", but on Win machine I don't receive this message. How to enable it on Win PC. Notices and warnings are enabled.
So ...
Controller kmgld:
function authorisation_user()
{
......
$data['set_cookie'] = "Surname";
......
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
View:
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
}
<!Doctype...>
<form action="<?php echo base_url()?>index.php/kmgld/update_kmgld" method="post" name="">
And again Controller kmgld
function update_kmgld()
{
...update DB
$test=$this->session->userdata('surname');
echo $test; //it is NULL
$this->output->enable_profiler(TRUE); // show me only now session id, ip, user agent
}
you have to set the userdata in the controller, the view isn't the proper place for it. so you probably would do something like this in your controller:
$surname = "Surname";
$this->session->set_userdata('surname',$surname);
$data['set_cookie'] = $surname;
...
$this->load->view('vheader', $data);
don't know if you autoload the session library. otherwise you have to load it in every function you need it.
remove session setting from view and do it in controller:
function authorisation_user()
{
$data['set_cookie'] = "Surname";
$this->session->set_userdata('surname',$set_cookie);
$this->load->view('vheader', $data);//are you sure here is where $data should go ?
$this->load->view('vuser_kmgld');//not $data here?
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
Controller:
<?php
class Kmgld extends CI_Controller {
function index()
{
$data['flag'] = "first";
$this->load->model('Mkmgld');
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
function get_kmgld()
{
$this->load->model('Mkmgld');
$this->Mkmgld->get_kmgld();
$this->load->view('vheader');
$this->load->view('kmgld');
$this->load->view('vfooter');
}
function authorisation_user()
{
$this->load->model('Mkmgld');
$surname_session = $this->session->userdata('surname');
$data['surname_post'] = mb_convert_case($this->input->post('surname'), MB_CASE_TITLE, "UTF-8");
$data['user_id'] = $this->Mkmgld->valid_user($data['surname_post']);
$surname = (isset($data['user_id'][0]->surname)? $data['user_id'][0]->surname: "");
if(isset($surname) and $surname !=NULL)
{
$data['query'] = $this->Mkmgld->get_kmgld($data['surname_post']);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$data['set_cookie'] = $data['surname_post'];
$this->session->sess_destroy();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
}else if (isset($surname_session) and $surname_session!= NULL)
{
//echo "you are in session";
$data['query'] = $this->Mkmgld->get_kmgld($surname_session);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
} else
{
$data['flag'] = "wrong";
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
//echo "<pre>";
//var_dump($data);
$this->output->enable_profiler(TRUE);
}//end authorisation_user()
function update_kmgld()
{
$this->load->model('Mkmgld');
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$trip_target_id = $data['get_trip_target_id'][0]->Auto_increment;
$this->Mkmgld->update_kmgld($this->input->post('day')
,$this->input->post('mon')
,$this->input->post('year')
,$this->input->post('spd_before')
,$this->input->post('spd_after')
,$this->input->post('total')
,$this->input->post('target')
,$this->input->post('approved')
,$this->input->post('user_id')
,$trip_target_id);
$a=$this->session->userdata('surname');
if ($a==NULL)
{
echo $a;
//redirect('kmgld/authorisation_user');
$this->output->enable_profiler(TRUE);
}
}
}//end class kmgld
?>
Model:
enter code here<?php
Class Mkmgld extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_kmgld($surname){
$query = $this->db->query("SELECT
*
FROM `user`
INNER JOIN `user_has_trip`
ON `user`.`user_id` = `user_has_trip`.`user_id`
INNER JOIN `trip_target`
ON `user_has_trip`.`user_has_trip_id` = `trip_target`.`trip_target_id`
WHERE `user`.`surname` = '$surname'
");
return $query->result();
}
function valid_user($surname)
{
$user_id = $this->db->query("SELECT
*
FROM `user`
WHERE `user`.`surname`='$surname'
");
return $user_id->result();
}
function get_trip_target_id()
{
$get_trip_target_id = $this->db->query("SHOW TABLE STATUS LIKE 'trip_target'");
return $get_trip_target_id->result();
}
function update_kmgld($day, $mon, $year, $spd_before, $spd_after, $total, $target, $approved, $user_id, $trip_target_id)
{
$date = $year."-".$mon."-".$day;
$this->db->query("INSERT INTO `trip_target` (`trip_target_id`
,`date`
,`speedometer_before`
,`speedometer_after`
,`duration`
,`target`
,`approved`)
VALUES (NULL
,'$date'
,'$spd_before'
,'$spd_after'
,'$total'
,'$target'
,'$approved')
");
$this->db->query("INSERT INTO `user_has_trip`
(`user_has_trip_id`
,`user_id`
,`trip_target_id`
)
VALUES (NULL
,'$user_id'
,'$trip_target_id'
)
");
}
}//end class
?>
View vauthorisation:
<?php
$surname_value = $this->session->userdata('surname');
?>
<?php
if ($flag =="wrong")
{
echo "...Bad very bad. Try use another language ";
}
?>
html:
form method="post" action="authorisation_user"
input type="text" name="surname"
View vheader:
<?php
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
echo "cookie set".$set_cookie;
}
?>
View vuser_kmgld:
html:
form action="update_kmgld"
inputs name=day, name=mon, name=year, name=spd_before...etc. After php code:
if (isset($user_id[0]->user_id))
{
foreach ($query as $row)
{
echo "<tr>
<td>".(isset($row->date)? date("d.m.Y", strtotime($row->date)): "")."</td>
<td>". (isset($row->speedometer_before)? $row->speedometer_before : "")."</td>
<td>". (isset($row->speedometer_after)? $row->speedometer_after : "")."</td>
<td>". (isset($row->duration)? $row->duration : "")."</td>
<td>". (isset($row->target)? $row->target : "")."</td>
<td>". (isset($row->aproved)? $row->aproved : "")."</td>
</tr>";
}
} //else redirect('kmgld/index');
?>

CodeIgniter form validation always return false

I've been scouring the webs and potching with my code for hours now and can't seem to figure out why this isn't working.
I have a template library which scans a template.html for {#tags} and then runs the function associated to the tag to create data for that {#tag}'s content and then replaces {#tag} for the content generated, so I can have widget like parts to my template.
On my account/access page I have a login form and a registration form, now when the template library calls the widget_register() function, the form validation doesn't seem to do anything, the data is posted as I can see from the profiler, but the form validation doesn't seem to do anything with it
Account Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Account extends CI_Controller {
public function index()
{
$this->load->helper('url');
#redirect('/');
}
public function access()
{
$this->load->helper('url');
#if($this->auth->loggedin()) redirect('/');
$this->template->compile_page();
}
public function widget_register($template)
{
$this->output->enable_profiler(TRUE);
$this->load->helper('url');
if($this->auth->loggedin()) redirect('/');
if ($this->input->post('register_submit'))
{
$this->load->model('auth_model');
$this->form_validation->set_rules('register_nickname', 'Nickname', 'required|min_length[3]|max_length[75]');
$this->form_validation->set_rules('register_email_address', 'Email Address', 'required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('register_confirm_email_address', 'Confirm Email Address', 'required|valid_email|matches[register_email_address]');
$this->form_validation->set_rules('register_password', 'Password', 'required|min_length[5]');
$this->form_validation->set_rules('register_confirm_password', 'Confirm Password', 'required|min_length[5]|matches[register_password]');
if($this->form_validation->run() !== false)
{
echo 'validation successful';
$nickname = $this->input->post('register_nickname');
$email = $this->input->post('register_email_address');
$generate_salt = $this->auth->generate_keys();
$salt = $generate_salt['1'];
$this->load->library('encrypt');
$generate_password = $salt . $this->input->post('register_password');
$password = $this->encrypt->hash($generate_password);
$generate_series_key = $this->auth->generate_keys();
$user_series_key = $generate_series_key['1'];
$this->db->query('INSERT INTO users (nickname, email, password, salt, register_date) VALUES ( "'.$nickname.'", "'.$email.'", "'.$password.'", "'.$salt.'", "'.time().'")');
}
else
{
echo 'invalid';
echo validation_errors();
}
}
$this->load->helper('form');
$view_data = array();
$view_data['form'] = form_open('account/access');
$view_data['input_nickname'] = form_input(array('name' => 'register_nickname', 'value' => set_value('register_nickname'), 'id' => 'register_nickname', 'class' => 'common_input', 'size' => '55'));
$view_data['input_email'] = form_input(array('name' => 'register_email_address', 'value' => set_value('register_email_address'), 'id' => 'register_email_address', 'class' => 'common_input', 'size' => '55'));
$view_data['input_confirm_email'] = form_input(array('name' => 'register_confirm_email_address', 'value' => '', 'id' => 'register_confirm_email_address', 'class' => 'common_input', 'size' => '55'));
$view_data['input_password'] = form_password(array('name' => 'register_password', 'value' => '', 'id' => 'register_password', 'class' => 'common_input', 'size' => '55'));
$view_data['input_confirm_password'] = form_password(array('name' => 'register_confirm_password', 'value' => '', 'id' => 'register_confirm_password', 'class' => 'common_input', 'size' => '55'));
$view_data['form_submit'] = form_submit('register_submit', 'Register');
$view_data['/form'] = form_close();
$view_data['validation_errors'] = validation_errors('<div class="error-box">', '</div>');
return $this->parser->parse(FCPATH.'themes/'.$this->settings->settings['system_settings']['theme'].'/widgets/'.$template.'.html', $view_data, TRUE);
}
function widget_login()
{
$this->load->helper('url');
// user is already logged in
if ($this->auth->loggedin())
{
return $this->load->view(FCPATH.'themes/'.$this->settings->settings['system_settings']['theme'].'/widgets/login/user.html', '', TRUE);
}
if($this->input->post('register'))
{
redirect('authentication/register');
}
// form submitted
if ($this->input->post('login_email_address') && $this->input->post('login_password'))
{
$this->load->library('form_validation');
$this->load->model('auth_model');
$this->form_validation->set_rules('login_email_address', 'Email Address', 'required|valid_email');
$this->form_validation->set_rules('login_password', 'Password', 'required|min_length[4]');
if($this->form_validation->run() !== false)
{
// validation passed verify from db
$remember = $this->input->post('remember') ? TRUE : FALSE;
if($remember == 'remember');
// check user exists and return user data
$user_data = $this->auth_model->user_exists($this->input->post('email_address'), TRUE);
if($user_data != FALSE)
{
// compare passwords
if ($this->auth_model->check_password($this->input->post('password'), $this->input->post('email_address')))
{
$this->auth->login($user_data->uid, $remember);
redirect('/');
}
else { $this->form_validation->set_custom_error('Incorrect password'); }
}
else { $this->form_validation->set_custom_error('There are no users with that email address'); }
}
}
// show login form
$this->load->helper('form');
$view_data = array();
$view_data['form'] = form_open();
$view_data['input_email'] = form_input('login_email_address', set_value('login_email_address'), 'id="login_email_address"');
$view_data['input_password'] = form_password('login_password', '', 'id="login_password"');
$view_data['input_remember'] = form_checkbox('remember', 'rememberme');
$view_data['form_submit'] = form_submit('login_submit', 'Login');
$view_data['register_button'] = form_submit('register', 'Register');
$view_data['/form'] = form_close();
$view_data['validation_errors'] = validation_errors('<div class="error-box">', '</div>');
return $this->parser->parse(FCPATH.'themes/'.$this->settings->settings['system_settings']['theme'].'/widgets/login/login.html', $view_data, TRUE);
}
function logout()
{
$this->load->helper('url');
$this->session->sess_destroy();
$this->load->helper('cookie');
delete_cookie('aws_session');
delete_cookie('aws_autologin_cookie');
redirect('/');
}
}
and the Template library
class Template {
private $settings;
private $_ci;
private $_controller = ''; # Controller in use
private $_method = ''; # Method in use
private $_is_mobile = FALSE; # Is the User agent a mobile?
private $cache_lifetime = '1';
private $page_output = "";
private $partials = array();
private $spts = array(); # Static page tags
function __construct()
{
$this->_ci =& get_instance();
$this->settings = $this->_ci->settings->settings;
$this->_controller = $this->_ci->router->fetch_class();
$this->_method = $this->_ci->router->fetch_method();
$this->_ci->load->library('user_agent');
$this->_is_mobile = $this->_ci->agent->is_mobile();
log_message('debug', "Template Class Initialized");
}
function build_page()
{
$page = $this->_ci->load->view(FCPATH.'themes/'.$this->settings['system_settings']['theme'].'/pages/'.$this->settings['page_settings']['template'].'.html', '', TRUE);
$this->page_output .= $page;
}
# MAIN PAGE FUNCTIONS END ------------------------------------------------------------------------------------------
public function check_static_tags()
{
if(preg_match_all('/{#[A-Z]{1,75}}/', $this->page_output, $matches))
{
$this->spts = $matches['0'];
$this->spts = array_diff($this->spts, array('{#CONTENT}')); # removes stp_content from array list
return TRUE;
}
return FALSE;
}
# Convert static tags
public function convert_static_tags()
{
foreach($this->spts as $key => $static_tag)
{
$static_tag = str_replace(array('{','}'), '', $static_tag);
$this->partials[$static_tag] = $this->build_widget($static_tag);
}
}
# Convert widget tags
function column_widget_tags()
{
if(preg_match_all('/{#COLUMN_[0-9]{1,11}}/', $this->page_output, $matches))
{
if(isset($this->settings['page_settings']['widgets']))
{
$columns = unserialize($this->settings['page_settings']['widgets']);
}
foreach($columns as $column_id => $widgets)
{
if(count($columns[$column_id]) > '0') // if the column contains widgets
{
$this->partials[''.$this->_stp.'_COLUMN_'.$column_id] = '';
foreach($widgets as $key => $widget_id)
{
// build the widget and add it to the $this->page_bits['column_id'] variable for replacing later in the compiler
$this->partials[''.$this->_stp.'_COLUMN_'.$column_id] .= $this->build_widget($widget_id);
}
}
else
{
$this->partials[''.$this->_stp.'_COLUMN_'.$column_id] = '';
}
}
}
}
# Build Widget
function build_widget($widget_id)
{
if(is_numeric($widget_id))
{
$widget_query = $this->_ci->db->query('SELECT * FROM widgets WHERE id = "'.$widget_id.'"'); # BIND STATEMENTS
}
elseif(preg_match('/#[A-Z]{1,75}/', $widget_id))
{
$widget_query = $this->_ci->db->query('SELECT * FROM widgets WHERE tag = "'.$widget_id.'"'); # BIND STATEMENTS
}
else
{
show_error('Could not get widget from database: '.$widget_id);
}
if($widget_query->num_rows() > 0)
{
$widget_info = $widget_query->row_array();
// loads widgets parent controller, builds the widget (class method) and returns it
$this->_ci->load->controller($widget_info['controller'], $widget_info['controller']);
$method_name = 'widget_'.$widget_info['method'];
$complete_widget = $this->_ci->$widget_info['controller']->$method_name($widget_info['template']);
return $complete_widget;
}
else
{
show_error('The requested widget could not be loaded: '.$widget_id);
}
}
# Replace Partials
function replace_partials()
{
$this->_ci->load->library('parser');
$this->page_output = $this->_ci->parser->parse_string($this->page_output, $this->partials, TRUE);
}
## METADATA
public function prepend_metadata($line)
{
array_unshift($this->_metadata, $line);
return $this;
}
# Put extra javascipt, css, meta tags, etc after other head data
public function append_metadata($line)
{
$this->_metadata[] = $line;
return $this;
}
# Set metadata for output later
public function set_metadata($name, $content, $type = 'meta')
{
$name = htmlspecialchars(strip_tags($name));
$content = htmlspecialchars(strip_tags($content));
// Keywords with no comments? ARG! comment them
if ($name == 'keywords' AND ! strpos($content, ','))
{
$content = preg_replace('/[\s]+/', ', ', trim($content));
}
switch($type)
{
case 'meta':
$this->_metadata[$name] = '<meta name="'.$name.'" content="'.$content.'" />';
break;
case 'link':
$this->_metadata[$content] = '<link rel="'.$name.'" href="'.$content.'" />';
break;
}
return $this;
}
# Embed page into layout wrapper
function layout()
{
$this->_ci->load->helper('html');
$this->append_metadata(link_tag('themes/'.$this->settings['system_settings']['theme'].'/css/layout.css')); # default stylesheet
$this->append_metadata('<link rel="shortcut icon" href="/favicon2.ico" />'); # default favicon
$template['template.title'] = $this->settings['page_settings']['title']; # Page title, can be overidden by the controller ?
$template['template.metadata'] = implode("\n\t\t", $this->_metadata); # Metadata
$template['template.body'] = $this->page_output; # The page
return $this->_ci->parser->parse(FCPATH.'assets/layout/L6_layout_wrapper.html', $template, TRUE);
}
# Run all functions to build page and set in output class
function compile_page($content_data = '')
{
$this->partials['#CONTENT'] = $content_data;
$this->build_page();
$this->column_widget_tags();
if($this->check_static_tags())
{
$this->convert_static_tags();
$this->replace_partials();
}
$output = $this->layout();
$this->_ci->output->set_header('Expires: Sat, 01 Jan 2000 00:00:01 GMT');
$this->_ci->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
$this->_ci->output->set_header('Cache-Control: post-check=0, pre-check=0, max-age=0');
$this->_ci->output->set_header('Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
$this->_ci->output->set_header('Pragma: no-cache');
# Let CI do the caching instead of the browser
#$this->_ci->output->cache($this->cache_lifetime);
$this->_ci->output->append_output($output);
}
}
Sorry for the incredibly long post, I'm really stumped here and didn't want to miss any code out, thanks in advance!

Resources