Message Library , My_Controller and __remap issue - php

I am creating an application and handling common things in MY_Controller. I am using Message library to display common messages.
Here is MY_Controller.php:
<?php
class MY_Controller extends CI_Controller {
public $data = array();
public $view = TRUE;
public $theme = FALSE;
public $layout = 'default';
protected $redirect;
protected $models = array();
protected $controller_model;
protected $controller_class;
protected $controller_library;
protected $controller_name;
protected $partials = array(
'meta' => 'partials/meta',
'header' => 'partials/header',
'navigation' => 'partials/navigation',
'content' => 'partials/content',
'footer' => 'partials/footer'
);
public function __construct()
{
parent::__construct();
$this->output->enable_profiler(true);
$this->load->helper('inflector');
$this->load->helper('url');
$this->controller_class = $this->router->class;
if(count($this->models)>0)
{
foreach ($this->models as $model)
{
if (file_exists(APPPATH . 'models/' . $model . '.php'))
{
$this->controller_model = $model;
$this->load->model($model);
}
}
}else{
if (file_exists(APPPATH . 'models/' . $this->controller_model . '.php'))
{
$this->load->model($this->controller_model);
}
}
$this->controller_name = $this->router->fetch_class();
$this->action_name = $this->router->fetch_method();
}
public function _remap($method, $parameters)
{
if (method_exists($this, $method))
{
$this->run_filter('before', $parameters);
$return = call_user_func_array(array($this, $method),$parameters);
$this->run_filter('after', $parameters);
}else{
show_404();
}
if($this->theme === TRUE OR $this->theme === '')
{
$this->theme = 'default';
$this->template->set_theme($this->theme);
}else if(strlen($this->theme) > 0){
$this->template->set_theme($this->theme);
}else{
}
if($this->layout === TRUE OR $this->layout === '')
{
$this->layout = 'default';
$this->template->set_layout($this->layout);
}else if(strlen($this->layout) > 0){
$this->template->set_layout($this->layout);
}else{
}
if(isset($this->partials))
{
foreach($this->partials as $key => $value)
{
$this->template->set_partial($key,$value);
}
}
if(isset($this->data) AND count($this->data)>0)
{
foreach($this->data as $key => $value)
{
if(!is_object($value))
{
$this->template->set($key,$value);
}
}
}
if($this->view === TRUE OR $this->view === '')
{
if($this->parse == TRUE)
{
$parse_string = $this->template->build($this->router->method ,'' ,$this->parse);
echo $this->parse($parse_string);
}else{
$this->_call_content($this->router->method);
$this->template->build($this->router->method,array());
}
}else if(strlen($this->view) > 0){
if($this->parse == TRUE){
$parse_string = $this->template->build($this->router->method ,'' ,$this->parse);
echo $this->parse($parse_string);
}else{
$view = $this->view;
$this->_call_content($view);
$this->template->build($view,array());
}
}else{
$checkpoint = $this->session->flashdata('exit');
if($checkpoint){
exit();
}else{
$this->session->set_flashdata('exit',TRUE);
}
$this->redirect();
}
}
public function _call_content($view)
{
$value = $this->load->view($view,$this->data,TRUE);
$this->template->set('content',$value);
}
/* Common Controller Functions */
public function index()
{
$data[$this->controller_model] = $this->{$this->controller_model}->get_all();
$this->data = $data;
$this->view = TRUE;
if($this->input->is_ajax_request() || $this->session->flashdata('ajax')){
$this->layout = FALSE;
}else{
$this->layout = TRUE;
}
}
public function form()
{
if($this->input->is_ajax_request() OR !$this->input->is_ajax_request())
{
$this->load->helper('inflector');
$id = $this->uri->segment(4,0);
if($data = $this->input->post()){
$result = $this->{$this->controller_model}->validate($data);
if($result){
if($id > 0){
}else{
$this->{$this->controller_model}->insert($data);
}
$this->message->set('message','The page has been added successfully.');
$this->view = FALSE;
$this->layout = FALSE;
$this->redirect = "index";
}else{
$this->message->set('message','The Red fields are required');
}
}
$row = $this->{$this->controller_model}->where($id)->get();
$this->data[$module_name]= $row;
}
}
public function delete()
{
$id = $this->uri->segment(3,0);
if($id != 0){
$this->{$this->controller_model}->delete($id);
}
$this->view = FALSE;
$this->layout = FALSE;
}
public function redirect()
{
redirect($this->redirect);
}
public function call_post($data)
{
foreach($data as $key => $row){
$_POST[$key] = $row;
}
}
public function query()
{
echo $this->db->last_query();
}
public function go($data = '')
{
if(isset($data)){
echo '<pre>';
print_r($data);
}else{
echo '<pre>';
print_r($this->data);
}
}
}
/**/
As you can see i am using Phil Sturgeon's template library and i am handling the layout with Jamierumbelow's techniques.
When i set a message on form insertion failure its fine. I can display it in the _remap like this
echo $this->message->display();
In the controller its working finebut when i call it in the partial navigation it does not display the message. What can possibly be the problem. I have tried on the different places in the My_Controller. Its working fine but not in the partial or even i have tried it in the failed form i am loading again.
This is the message library i am using
https://github.com/jeroenvdgulik/codeigniter-message
Here i s my navigation partial
<nav>
<div id = "navigation">
<ul id="menubar">
<li>Home</li>
<li>Downloads</li>
<li>About Us</li>
</ul>
</div>
<div id="breadcrumb">
<div class="breadcrumbs">
<!-- Here i will pull breadcrumbs dynamically-->
</div>
<!--<h3>Dashboard</h3>-->
</div>
<br clear = "all"/>
<div id="message">
<?php
$data['message'] = $message ;
$this->load->view('messages/success',$data);?>
</div>
</nav>
The message library is using session might be flashdata so i think its loosing session data somehow. Although i am using sessions correctly autoloading it.

I have found the issue. It was very simple. I was using the base url in config file as empty
$config['base_url'] = '';
I have to change it like this
$config['base_url'] = 'http://localhost/myproject/';

Related

pass multiple pages in one method in codeigniter

This is the library I have created to load views in codeigniter,
Library:
public function view($view_name, $params = array(), $layout){
$renderedview = $this->CI->load->view($view_name,$params,TRUE);
if($this->data['title'])
{
$this->data['title'] = $this->title_separator.$this->data['title'];
}
if(array_key_exists('error', $this->data)){
$error = $this->data['error'];
}
else{
$error = '';
}
$this->CI->load->view('layouts/'.$layout, array(
'content_for_layout' => $renderedview,
'title_for_layout' => $this->data['title'],
'error' => $error
));
}
Here I want to pass array (having multiple views), currently only one view is going through it.
How I am calling this method.
Controller Method:
public function __adminRegisterView()
{
$this->layouts->setTitle('Admin Register');
$this->layouts->view('pages/admin/account/register','','admin/loginregister');
}
In the View:
<body class="login-img3-body">
<?php echo $content_for_layout; ?>
</body>
You can do something like this:
public function view($view_name, $params = array(), $layout){
if(!is_array($view_name))
{
$view_name[] = $view_name;
}
$renderedview = "";
foreach($view_name as $view)
{
$renderedview .= $this->CI->load->view($view,$params,TRUE);
}
if($this->data['title'])
{
$this->data['title'] = $this->title_separator.$this->data['title'];
}
if(array_key_exists('error', $this->data)){
$error = $this->data['error'];
}
else{
$error = '';
}
$this->CI->load->view('layouts/'.$layout, array(
'content_for_layout' => $renderedview,
'title_for_layout' => $this->data['title'],
'error' => $error
));
}
Now you can call view like that:
$this->layouts->view(array('pages/admin/account/register','pages/admin/account/login','test_view'),'','admin/loginregister');
or:
$this->layouts->view('pages/admin/account/register','','admin/loginregister');

How to make custom 404 page in routing system

I want to make a 404 error page on this routing. How can this be done?
index.php
<?php
include 'route.php';
include 'control/about.php';
include 'control/home.php';
include 'control/contact.php';
$route = new route();
$route->add('/', function(){
echo 'Hello, this is home pageeees';
});
$route->add('/about', 'about');
$route->add('/contact', 'contact');
echo '<pre>';
print_r($route);
$route->submit();
?>
route.php
<?php
class route
{
private $_uri = array();
private $_method = array();
/**
*Builds a collection of internal URL's to look for
*#parameter type $uri
*/
public function add($uri, $method = null)
{
$this->_uri[] = '/' . trim($uri, '/');
if($method != null){
$this->_method[] = $method;
}
}
/**
*Makes the thing run!
*/
public function submit()
{
$uriGetParam = isset($_GET['uri'])? '/' . $_GET['uri'] : '/';
foreach ($this->_uri as $key => $value)
{
if(preg_match("#^$value$#",$uriGetParam))
{
if(is_string($this->_method[$key]))
{
$useMethod = $this->_method[$key];
new $useMethod();
}
else
{
call_user_func($this->_method[$key]);
}
}
}
}
}
?>
The regex in mind I would just add $route->add("/.+", function()...); after all your other routes.
Proof: https://3v4l.org/nk5PZ
But you could also program some logic which evaluates custom 404-Pages when not being able to find a correspondig route.
For example:
private $_notFound;
public function submit() {
$uriGetParam = isset($_GET['uri'])? '/' . $_GET['uri'] : '/';
$matched = false;
foreach ($this->_uri as $key => $value) {
if(preg_match("#^$value$#", $uriGetParam)) {
if(is_string($this->_method[$key])) {
$useMethod = $this->_method[$key];
new $useMethod();
} else {
call_user_func($this->_method[$key]);
}
$matched = true;
}
}
if(!$matched) {
if(isset($this->_notFound)) {
if(is_string($this->_notFound)) {
$action = $this->_notFound;
new $action();
} else {
call_user_func($this->_notFound);
}
}
}
}
public function notFound($callback) {
$this->_notFound = $callback;
}
Then you'll have to add the 404-action by $route->notFound(function... or "class");

read more function with codeigniter

i am trying to create a readmore function in codeigniter where the readmore link will be linked to a controller which would show all the data about that particular id....i am kind of confused on how to go about it... i tried...
<?php
$research_detail_url = site_url()."/research/research_details";
//echo json_encode($research)
if($research)
{
foreach ($research as $_research) {
$author = $_research->author;
$content = $_research->content;
$dsubmitted = $_research->dsubmitted;
echo "<div class='menu-collapse'> <h5>$author</h5>";
echo "<p>";
echo "<span class='support_text'>$content <span><br />";
echo "<span class='support_text'>$dsubmitted <span><br />";
echo "<a href='$research_detail_url' target='_blank' style='text-decoration:underline; color:#0088cc;'>
read more ยป </a>";
echo "</p> </div>";
}
}
?>
but i seem not be getting any results...i need help...
and this is my controller function.....
public function research_details($id='')
{
if(!$id)
{
echo "Project Id required";
return;
}
$_result = $this->projects_model->get_project($id);
if($_result)
{// success in fetching data hurray
$result['projects'] = $_result;
$users_ids = $this->users_model->get_user_ids(); //return available user id's
$groups_ids = $this->groups_model->get_group_ids(); //return available group id's
//echo json_encode($users_ids);
//echo json_encode($groups_ids);
$group_record = $this->map_names_to_ids($users_ids , $groups_ids );
$result['group_record'] = $group_record;
//load the view
$this->load->view('__includes__/header');
$this->load->view('__includes__/boostrap_responsive');
$this->load->view('projects/project_panel', $result);
$this->load->view('__includes__/footer_scripts');
$this->load->view('__includes__/wijmo_file_jquery');
$this->load->view('__includes__/footer');
}
else
{
exit("An Error occured in fetching the requested project");
}
}
and this is my model.....
<?php
class research_model extends CI_Model {
function add()
{
$this->db->insert('research',$_POST);
if($this->db->_error_number())
{
return $this->db->_error_number();
}
}
function update($article_id, $data_fields = NULL){
if($data_fields == NULL)
{
$this->db->where("article_id =".$article_id);
$this->db->update('research',$_POST);
}
else
{
$this->db->where("article_id =".$article_id);
$this->db->update('research',$data_fields);
}
$is_error = $this->db->_error_number();
if($is_error){
echo $is_error;
}
return TRUE;
}
function delete($id){
$this->db->where("article_id =".$id);
return $this->db->delete('research');
}
//return the research with this id
function get_research($id){
$this->db->where("article_id =".$id);
$query = $this->db->get('research');
if ($query->num_rows() > 0){
return $query->row_array();
}
else
echo $this->db->_error_message();
return FALSE;
}
//return the available research in the table
function get_research_all(){
$query = $this->db->get('research');
if ($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
$result[] = $row;
}
return $result;
}
}
}
and my entire controller.....
<?php
class Research extends Public_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('research_model');
}
function index()
{
if($this->ion_auth->is_admin())
{
$result = $this->research_model->get_research_all();
$data = array(
'main_content' => 'research/index',
'research' => $result
);
$this->load->view("loader", $data);
}
else
{
redirect('home');
}
}//END INDEX
// public view
function current()
{
$result = $this->research_model->get_research_all();
$data = array('research' => $result);
$this->load->view('__includes__/header');
$this->load->view('__includes__/navbar');
$this->load->view('research/current', $data);
$this->load->view('__includes__/footer');
}
function add()
{
if($this->ion_auth->is_admin())
{
$this->load->view("loader",array('main_content'=>"research/add_research"));
}
}//END ADD
function edit($id='')
{
if(! $id)
{
echo "research Id required";
return;
}
$result = $this->research_model->get_research($id);
if( ! $result)
{
echo "Nothing to edit";
return;
}
$result['main_content'] = "research/add_research";
$this->load->view("loader",$result);
}//END EDIT
function delete($id='')
{
if(! $id)
{
echo "Id required";
return;
}
$this->research_model->delete($id);
$this->get_research();
}//END DELETE
function submit($id='')
{
//validate form [perform validation server-side to make sure of fields]
$this->load->library('form_validation');
$this->form_validation->set_rules('author', 'Author', 'trim|required|min_length[4]');
if ($this->form_validation->run() == FALSE){
//ajax data array
$data = array(
'server_validation' => validation_errors()
);
echo str_replace('\\/', '/', json_encode($data));
}
else{
if($id){
$result = $this->research_model->update($id);
$content = "article has been UPDATED successfully";
//$retArr["content"] = $content;
//echo json_encode($retArr);
}
else{
$result = $this->research_model->add();
$content = "article has been CREATED successfully";
//$retArr["content"] = $content;
//echo json_encode($retArr);
}
//if duplicate key
if($result == 1062){
//ajax data array
$data = array();
$data['is_valid'] = 0;
echo json_encode($data);
}else{
//ajax data array
$data = array(
'is_valid' => 1,
'content' => $content
);
echo json_encode($data);
}
}//end ELSE form valid
}//END SUBMIT
public function research_details($id='')
{
if(!$id)
{
echo "Project Id required";
return;
}
$_result = $this->research_model->get_research($id);
if($_result)
{// success in fetching data hurray
$result['article'] = $_result;
//load the view
$this->load->view('__includes__/header');
$this->load->view('__includes__/boostrap_responsive');
$this->load->view('research/research_details', $Aresult);
$this->load->view('__includes__/footer_scripts');
$this->load->view('__includes__/wijmo_file_jquery');
$this->load->view('__includes__/footer');
}
else
{
exit("An Error occured in fetching the requested project");
}
}//END EDIT
}
?>
my public controller
<?php
abstract class Public_Controller extends CI_Controller
{
public $about_data;
function __construct()
{
parent::__construct();
//Making This variable availale for the whole site
$this->load->model('about_model');
$this->load->model('captcha_model');
//get your data
$this->about_data = $this->about_model->get_abouts();
}
}
?>
I see a couple of problems:
In your view, you are not closing the span tags. You need
</span>
In your view, you are creating the link, but you are not
including an ID, which you need in your controller. What I mean by this is the following:
First,you create this $research_detail_url = site_url()."/research/research_details";.
Then echo "<a href='$research_detail_url' target='_blank' style=''>read more</a>";
As you can see, your URL does not have an ID when created. What you should do is something like this: $research_detail_url = site_url()."/research/research_details/31"; where 31 is a random ID. You need to come up with the right ID needed in order to pass it to your controller. Your controller is currently assigning a blank ID since none is being passed which is why you end up with a result of "Project Id required"

Check if admin has logged in

If there's someone logged in, this code checks the sessions and I can successfully view the page, but now I'd like to check if the user is admin. I tried checking in the model by Below is what I have tried and its not working.
method that checks session and if its an admin
public function index()
{
$this->load->library('authlib');
$loggedin = $this->authlib->is_loggedin();
///$admin = $this->auth->admin();
if ($loggedin === false) {
$this->load->helper('url');
redirect('/auth/login');
}
if ($this->auth->admin() === false) {
$message ['msg'] = "You are not an admin!";
$this->load->view('homeview', $message);
}
else
{
$this->load->view('add_view');
}
}
Auth Controller
public function authenticate()
{
$username = $this->input->post('uname');
$password = $this->input->post('pword');
$user = $this->authlib->login($username,$password);
**>> $this->admin($username,$password); << passes the posted in values**
if ($user !== false) {
$this->load->view('homeview',array('name' => $user['name']));
}
else {
$data['errmsg'] = 'Unable to login - please try again';
$this->load->view('login_view',$data);
}
}
public function admin($username,$password){
//$this->load-model('usermodel');
$admin = $this->authlib->adminlib($username,$password);
if ($admin == false){
return false;
//if ($res->num_rows() != 1){
//return false;
}
}
library authlib
public function adminlib($user,$pwd)
{
return $this->ci->usermodel->chkadmn($user,$pwd);
}
the model
function chkadmn($username,$password)
{
$this->db-where(array('username' => $username,'password' => sha1($password)));
$res = $this->db->get('users',array('type'));
if ($res->num_rows() != 1) {
return false;
}
}
Made some changes and now I get "Call to undefined function where() in C:\xampp\htdocs\ecwm604\application\models\usermodel.php on line 54"
personally i will replace all your if statments and i would test it as shown:
public function index()
{
$this->load->library('authlib');
$loggedin = $this->authlib->is_loggedin();
///$admin = $this->auth->admin();
if (!$loggedin) {
$this->load->helper('url');
redirect('/auth/login');
}
if (!$this->auth->admin()) {
$message ['msg'] = "You are not an admin!";
$this->load->view('homeview', $message);
}
else
{
$this->load->view('add_view');
}
}
public function admin(){
$this->load-model('usermodel');
$admin = $this->usermodel->chkadmn($username,$password);
if (!$admin){
return false;
//if ($res->num_rows() !== 1){
//return false;
}
}
function chkadmn($username,$password)
{
$this->db-where(array('username' => $username,'password' => sha1($password)));
$res = $this->db->get('users',array('type'));
if ($res->num_rows() !== 1) {
return false;
}
}

How to write an img path to MySQL using the file Uploader class and user model

I'm trying to add a final field to my project that contains a URL of the files that have been uploaded, if anyone could point me in the write direction for extending my model ?
I have included my codeIgniter Model & Controller code.
controller:
class Canvas extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index() {
$vars = array();
//$this->load->library('ChromePhp');
//$this->ChromePhp->log('test');
//$this->ChromePhp->log($_SERVER);
// using labels
// foreach ($_SERVER as $key => $value) {
// $this->ChromePhp->log($key, $value);
// }
// warnings and errors
//$this->ChromePhp->warn('this is a warning');
//$this->ChromePhp->error('this is an error');
$this->load->library('FacebookConnect');
$facebook=$this->facebookconnect->connect();
$vars['facebook'] = $facebook;
$user = $vars['user'] = $facebook->getUser();
$this->load->model('Users_Model');
// user already set up. Show thank you page
if($user != 0 && sizeof($_POST)>0) {
$this->do_upload();
$this->iterate_profile ($vars['user'],false,$_POST);
$this->load->view('canvas',$vars);
} else {
// user not set, show welcome message
$this->load->view('canvas',$vars);
}
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '20048';
$config['max_width'] = '10624';
$config['max_height'] = '10268';
$config['file_name'] = date("Y_m_d H:i:s");
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
function thank_you() {
$this->load->view('thank_you',$vars);
}
function remove() {
$vars = array();
$this->load->library('FacebookConnect');
$facebook=$this->facebookconnect->connect();
$vars['facebook'] = $facebook;
$vars['user'] = $facebook->getUser();
$this->load->model('Users_Model');
if($vars['user'] == 0) {
// user not set, redirect
redirect('/', 'refresh');
} else {
// user already set up. Remove
$this->load->model('Users_Model');
$this->Users_Model->remove($vars['user']);
}
$this->load->view('removed',$vars);
}
protected function iterate_profile ($user,$breadcrumb,$item) {
foreach($item as $key => $value) {
if(is_array($value)) {
$this->iterate_profile($user,$key,$value);
}
else {
if($breadcrumb) {
//echo '[' . $breadcrumb . '_' . $key . ']= ' . $value . ' <br />';
$key = $breadcrumb . '_' . $key;
}
if( ! $this->Users_Model->exists($user,$key)) {
// does not exist in the database, insert it
$this->Users_Model->add($user,$key,$value);
} else {
$this->Users_Model->update($user,$key,$value);
}
}
}
}
}
Model:
class Users_Model extends CI_Model {
protected $_name = 'users';
function add($id,$key,$value) {
$data = array(
'id' => $id,
'name' => $key,
'value' => $value
);
return $this->db->insert($this->_name, $data);
}
function update($id,$key,$value) {
$data = array(
'value' => $value
);
$this->db->where(array(
'id' => $id,
'name' => $key
));
return $this->db->update($this->_name, $data);
}
function exists($id,$key=null) {
if($key == null) {
$this->db->where(array(
'id' => $id
));
} else {
$this->db->where(array(
'id' => $id,
'name' => $key
));
}
$query = $this->db->get($this->_name);
if($query->num_rows() > 0) {
return true;
}
return false;
}
function remove($id) {
$data = array(
'id' => $id,
);
return $this->db->delete($this->_name, $data);
}
function all() {
$query = $this->db->get($this->_name);
$results = array();
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$results[]=$row;
}
}
return $results;
}
}
I don't think the question is very clear. But to me it seems you need to store the image path in the db. Otherwise you will need to perform a read directory on the upload path and then do something with the images.

Categories