CodeIgniter source code of the post model, controller and view

Code of Post model in CodeIgniter
[code language=”PHP”]
<?php if (!defined(‘BASEPATH’)) exit(‘No direct script access allowed’);

/**
* Post
*
* This model represents post data. It operates the following tables:
* – post data
*
*/
class MPost extends CI_Model
{
public $rules = array(
array(
‘field’ => ‘title’,
‘label’ => ‘title’,
‘rules’ => ‘trim|required|xss_clean|max_length[255]’
),
array(
‘field’ => ‘body’,
‘label’ => ‘Body’,
‘rules’ => ‘trim|required|xss_clean’
)
);

private $table_name = ‘post’; // blog table name

function __construct()
{
parent::__construct();
$this->load->database();
}
/**
* Create new blog record
*
* @param $data array
* @return array
*/
function create($data)
{
$data[‘permalink’] = url_title($data[‘title’]);
if ($this->db->insert($this->table_name, $data)) {
return True;
}
return False;
}

function get_post_by_id($id)
{
$query = $this->db->get_where(
$this->table_name,
array(‘id’ => $id)
);
if ($query->num_rows() == 1) return $query->row_array();
return NULL;
}

function get_post($permalink)
{
$query = $this->db->get_where(
$this->table_name,
array(‘permalink’ => $permalink)
);
if ($query->num_rows() == 1) return $query->row_array();
return NULL;
}

function total_posts(){
return $this->db->count_all($this->table_name);
}

function get_posts($per_page, $offset=0)
{
$this->db->limit($per_page, $offset);
$this->db->order_by(‘posted_on’,’desc’);
$query = $this->db->get($this->table_name);

if ($query->num_rows() > 0) return $query->result_array();
return NULL;
}

function get_posts_by_blog_id($blog_id)
{
$this->db->order_by(‘posted_on’,’desc’);
$query = $this->db->get_where(
$this->table_name,
array(‘blog_id’ => $blog_id)
);
if ($query->num_rows() > 0) return $query->result_array();
return NULL;
}

function get_post_author_by_blog_id($blog_id)
{
$this->load->model(‘mblog’);

$blog = $this->mblog->get_blog_by_id($blog_id);
$user = $this->users->get_user_by_id($blog[‘user_id’]);

return $user[‘username’];
}

function update($id, $data){
$this->db->where(‘id’, $id);
return $this->db->update($this->table_name, $data);
}

function delete($id)
{
$this->db->where(‘id’, $id);
$this->db->delete($this->table_name);
if ($this->db->affected_rows() > 0) {
return TRUE;
}
return FALSE;
}

function get_total_posts_which_contains($text)
{
$this->db->or_like(‘title’, $text);
$this->db->or_like(‘body’, $text);
$this->db->from($this->table_name);
return $this->db->count_all_results();
}

function get_posts_which_contains($text,$per_page,$offset=0)
{
$this->db->limit($per_page, $offset);
$this->db->order_by(‘posted_on’,’desc’);

$this->db->or_like(‘title’, $text);
$this->db->or_like(‘body’, $text);

$query = $this->db->get($this->table_name);

if ($query->num_rows() > 0) return $query->result_array();
return NULL;
}

function delete_posts_from_blog_id($blog_id)
{
$this->db->where(‘blog_id’, $blog_id);
$this->db->delete($this->table_name);
if ($this->db->affected_rows() > 0) {
return TRUE;
}

return FALSE;
}

}

[/code]

Code of Post controller in CodeIgniter
[code language=”PHP”]
class Post extends CI_Controller
{

function __construct()
{
parent::__construct();

$this->load->helper(array(‘form’, ‘url’, ‘array’, ‘html’, ‘post’));
$this->load->library(‘form_validation’);
$this->load->library(‘tank_auth’);
$this->load->model(‘mpost’);
$this->load->model(‘mblog’);
$this->load->model(‘mcomment’);
}
function create()
{
$this->tank_auth->logged_in_or_redirect();
$data[‘title’] = ‘Create a Post’;

$this->form_validation->set_rules($this->mpost->rules); //set rules

if ($this->form_validation->run())
{

$user_id = $this->tank_auth->get_user_id();//always to the crrent user
$blog = $this->mblog->get_blog_by_user_id($user_id); //get current blog

$post = elements(array(‘title’, ‘body’), $this->input->post());
$post[‘blog_id’] = $blog[‘id’];

if ($this->mpost->create($post))
{
$this->session->set_flashdata(‘message’, ‘Post successfully created’);
//TODO REDIRECT TO POST
redirect(‘/’.$this->tank_auth->get_username());

}else{ //some error

}
}

$this->load->view(‘templates/header’, $data);
$this->load->view(‘post/create’, $data);
}

function index()
{
$data[‘title’] = ‘My blog’;

$this->load->library(‘pagination’);
$config[‘base_url’] = ‘http://localhost/index.php?’ ; //had to do this, no other way
$config[‘per_page’] = 2;
$config[‘page_query_string’] = TRUE;

$offset = $this->input->get(‘per_page’);

$this->form_validation->set_rules(array(
array(
‘field’ => ‘search’,
‘label’ => ‘search’,
‘rules’ => ‘trim|xss_clean|max_length[1000]’
)));

if ($search = $this->input->get(‘search’))
{
$data[‘search’] = $search;
$data[‘posts’] = $this->mpost->get_posts_which_contains($search,$config[‘per_page’],$offset);
$config[‘total_rows’] = $this->mpost->get_total_posts_which_contains($search);
$config[‘base_url’] .= ‘search=’.$search;
}else{
$data[‘posts’] = $this->mpost->get_posts($config[‘per_page’], $offset);
$config[‘total_rows’] = $this->mpost->total_posts();
}

$this->pagination->initialize($config);

$data[‘pagination’] = $this->pagination->create_links();

// In case user is logged in , his posts must be loaded
if ($this->tank_auth->is_logged_in()){
$this->load->model(‘mblog’);
$user = $this->tank_auth->current_user();
$blog = $this->mblog->get_blog_by_user_id($user[‘id’]);

$data[‘his_posts’] = $this->mpost->get_posts_by_blog_id($blog[‘id’]);
}

$this->load->view(‘templates/header’, $data);
$this->load->view(‘post/index’, $data);
}

function show($permalink)
{

if ( $post = $this->mpost->get_post($permalink))
{
$data[‘post’] = elements(array(‘title’,’body’,’posted_on’,’permalink’,’blog_id’,’id’), $post);
$data[‘comments’] =
$this->mcomment->get_comments_by_post_id($post[‘id’]);

$comment = array();
if ($this->tank_auth->is_logged_in() AND
$_SERVER[‘REQUEST_METHOD’] == "POST")
{
$user = $this->tank_auth->current_user();
$userprofile = $this->tank_auth->current_profile();
$comment[‘user_id’] = $user[‘id’];
$_POST[’email’] = $user[’email’];
if (isset($userprofile[‘website’])){
$_POST[‘website’] = $userprofile[‘website’];
}
$_POST[‘username’] = $user[‘username’];
}

$this->form_validation->set_rules($this->mcomment->rules); //set rules

if ($this->form_validation->run()){

$comment += elements(
array(‘username’, ‘website’, ’email’, ‘body’),
$this->input->post()
);
$comment[‘post_id’] = $post[‘id’];

if ($this->mcomment->create($comment))
{
$this->session->set_flashdata(‘message’, ‘Comment successfully created’);

redirect($this->uri->uri_string());

}else{ //some error

}
}

$this->load->view(‘templates/header’, $data);
$this->load->view(‘post/show’, $data);
}else{//does not exists
show_404();
}

}

function update($permalink)
{

$this->tank_auth->logged_in_or_redirect();

if ( $post = $this->mpost->get_post($permalink))
{
$user = $this->tank_auth->current_user();
if ( $this->mpost->get_post_author_by_blog_id($post[‘blog_id’])
!= $user[‘username’] )
show_error( "Not authorized" ); //not authorized

$data = elements(array(‘title’,’body’,’posted_on’,’permalink’), $post);

$this->form_validation->set_rules($this->mpost->rules); //set rules

if ($this->form_validation->run())
{
$new_values = elements(
array(‘title’, ‘body’),
$this->input->post());

if ($this->mpost->update($post[‘id’],$new_values))
{
$this->session->set_flashdata(‘message’, ‘Post successfully updated’);
redirect(‘/post/update/’.$permalink);

}else{ //some error
}
}

$this->load->view(‘templates/header’, $data);
$this->load->view(‘post/update’, $data);
}else{//does not exists
show_404();
}

}

function delete($permalink)
{
$this->tank_auth->logged_in_or_redirect();
if ( $post = $this->mpost->get_post($permalink))
{
$user = $this->tank_auth->current_user();
if ( $this->mpost->get_post_author_by_blog_id($post[‘blog_id’])
!= $user[‘username’] )
show_error( "Not authorized" ); //not authorized

if ($this->mpost->delete($post[‘id’]))
{
$this->session->set_flashdata(‘message’, ‘Post successfully deleted’);
redirect(‘/’.$user[‘username’]);
}else{
$this->session->set_flashdata(‘message’, ‘There was some error trying to delete it, please contact an administrator’);
redirect(‘/’);
}
}else{
show_404();
}
}
}

[/code]


Code of post view in CodeIgniter

[code language=”PHP”]
<?php

$username = array(
‘name’ => ‘username’,
‘id’ => ‘username’,
‘value’ => set_value(‘username’),
‘maxlength’ => 255,
‘size’ => 30
);

$website = array(
‘name’ => ‘website’,
‘id’ => ‘website’,
‘value’ => set_value(‘website’),
‘size’ => 30
);

$email = array(
‘name’ => ’email’,
‘id’ => ’email’,
‘value’ => set_value(’email’),
‘size’ => 30
);

$body = array(
‘name’ => ‘body’,
‘id’ => ‘body’,
‘value’ => set_value(‘body’),
‘rows’ => 10,
‘cols’ => 39,
);

?>

<? echo show_post($post) ?>

<?php echo form_open($this->uri->uri_string()); ?>
<h3> New comment </h3>
<table>
<? if (!$this->tank_auth->is_logged_in()) { ?>
<tr>
<td><?php echo form_label(‘username’, $username[‘id’]); ?></td>
<td><?php echo form_input($username); ?></td>
<td style="color: red;"><?php echo form_error($username[‘name’]); ?><?php echo isset($errors[$username[‘name’]])?$errors[$username[‘name’]]:”; ?></td>
</tr>

<tr>
<td><?php echo form_label(‘website’, $website[‘id’]); ?></td>
<td><?php echo form_input($website); ?></td>
<td style="color: red;"><?php echo form_error($website[‘name’]); ?><?php echo isset($errors[$website[‘name’]])?$errors[$website[‘name’]]:”; ?></td>
</tr>

<tr>
<td><?php echo form_label(’email’, $email[‘id’]); ?></td>
<td><?php echo form_input($email); ?></td>
<td style="color: red;"><?php echo form_error($email[‘name’]); ?><?php echo isset($errors[$email[‘name’]])?$errors[$email[‘name’]]:”; ?></td>
</tr>
<? }?>
<tr>
<td><?php echo form_label(‘body’, $body[‘id’]); ?></td>
<td><?php echo form_textarea($body); ?></td>
<td style="color: red;"><?php echo form_error($body[‘name’]); ?><?php echo isset($errors[$body[‘name’]])?$errors[$body[‘name’]]:”; ?></td>
</tr>

</table>
<?php echo form_submit(‘create comment’, ‘Create comment’); ?>
<?php echo form_close(); ?>

<? if (isset($comments)) foreach ($comments as $comment){ ?>

<? if (isset($comment[‘user_id’])) { ?>
<? $comment_user =
$this->users->get_user_by_id($comment[‘user_id’]);
$comment_userprofile =
$this->users->get_user_profile($comment[‘user_id’]);
?>
<p> user : <b> <?= $comment_user[‘username’] ?> </b> </p>
<p> website : <b> <?= $comment_userprofile[‘website’]?> </b> </p>
<p>email : <b> <?= $comment_user[’email’] ?> </b> </p>

<? }else{ ?>
<p>user : <b> <?= $comment[‘username’] ?> </b> </p>
<p>website : <b> <?= isset($comment[‘website’])? $comment[‘website’] : ”?> </b> </p>
<p>email : <b> <?= $comment[’email’] ?> </b> </p>
<? } ?>

<p> <?= isset($comment[‘body’]) ? $comment[‘body’] : ” ?> </p>
<? $current_user = $this->tank_auth->current_user(); ?>
<? $author = $this->mpost->get_post_author_by_blog_id($post[‘blog_id’]); ?>
<? if ( $current_user[‘username’] == $author ) { //show button options only to the owners of the post ?>

<?= form_open(‘comment/delete/’.$comment[‘id’]); ?>
<?= form_submit(‘delete’, ‘Delete comment’); ?>
<?= form_close(); ?>
<? } ?>
<? } ?>

[/code]