Tuesday, March 6, 2012

Why dont you create your own CMS???--Part X

Let add some more functions on our 'functions.php'.
We will be looking at each functions in detail.
/***************************************
ESCAPING STRING
*************************************/

function escape($str) {
 global $db;
    $str = get_magic_quotes_gpc()?stripslashes($str):$str;
    $str = mysql_real_escape_string($str, $db->connection);
    return $str;
  }
 
/**************************************
showing a message
EG:-  show_msg('TITLE OF YOUR MESSAGE','CONTENT');
******************************************/

function show_msg($title,$msg)
{
echo '<script src="jquery.js" type="text/javascript">
</script>
 <script src="jquery.freeow.js" type="text/javascript">
</script>';
echo '<script type="text/javascript">
  (function ($) {

  $(document).ready(function() {
 
   var title, message, opts, container;
   message="'.$msg.'";
   title="'.$title.'";      
   $("#freeow-tr").freeow(title,message);
   
  });

}(jQuery));
</script>
';
}

/***************************
 To get the username of the
 logged in person

****************************/
 
function get_username()
{
global $user;
return $user-&gt;get_property('username');
}
/***************************
To get user id of the logged in person

****************************/
function get_user_id()
{
global $user;
return $user-&gt;get_property('u_id');
}
/***************************
Check whether the logged in user is admin or not
The admin has a user id 1

****************************/
function is_admin()
{
global $user;
$id=get_user_id();
if($id==1)
 return true;
else 
 return false;
}
/***************************
Get the various access level of the user

****************************/
function get_user_level()
{
global $user;
return $user-&gt;get_property('level');
}
/***************************
Checks whether user is logged in or not

****************************/
function is_logged_in()
{
global $user;
return $user-&gt;is_logged_in();
}
/***********************************
viewing area to show message
*************************************/

function message_area()
{
echo ('<div class="freeow freeow-top-right" id="freeow-tr"></div>');
}

/*************************************
draw login box
*****************************************/
function draw_login_form()
{
 echo '<div id="login_box"><h1>Login</h1><form action="index.php?action=login" method="post"></form>username: <input name="uname" />

password: <input name="pwd" type="password" />

Remember me? <input name="remember" type="checkbox" value="1" />

<input type="submit" value="login" />
 </div>';
}

/*****************************************
draw register form
*******************************************/
function draw_register_form()
{ 
    echo '<div id="register_box"><h1>Register</h1><form action="index.php?action=register" method="post"></form>username: <input name="username" />

password: <input name="pwd" type="password" />

email: <input name="email" />

<input name="register" type="submit" value="Register user" />
   </div>';
}
 
The function escape is to mysql real escape the string.
Then comes our important function 'show_msg()' function.
function show_msg($title,$msg)
{
echo '<script type="text/javascript" src="jquery.js"></script>
 <script type="text/javascript" src="jquery.freeow.js"></script>';
echo '<script type="text/javascript">
  (function ($) {
  $(document).ready(function() {
   var title, message, opts, container;
   message="'.$msg.'";
   title="'.$title.'";
   $("#freeow-tr").freeow(title,message);
  });
}(jQuery));
</script>';
We are using the free script 'freeow' for showing short messages to the user.The function will accept two arguments-the title and the message.Then we included two javascripts for our function to work.

You can download the scripts from here and copy it in 'stupid' folder.

To show the message you need a message area.Message area can easily be defined by using the message_area() function.Here I have put this below our header.

To obtain the username of the user get_username() can be used.
All other functions are self explanatory.

Now you have to add some css to work with messages.
Please download the modified theme from here

Now we have to include our newly created class files and instantiate in our 'engine.php'.
I am providing the full source code upto our development of stupid cms here..

Download stupid cms

The first registered  user will be the admin.After registering ,login and logout to see all are correct.

Saturday, March 3, 2012

Why dont you create your own CMS???--Part 9

In the previous post,we created our session class and user class.Here we will look into our 'actions.php' for handling actions like login,logout,register etc.The action to be performed will be decided from a url variable named 'action'.So whenever url variable action is set,corresponding action will be performed.

  • Open stupid >>> actions folder.
  • Create a file named 'actions.php'.
  • Open the file in an editor and write the following code.

 
<?php
global $user;
if (isset($_GET['action'])) {
    $action = $_GET['action'];
    switch ($action) {
        case 'login':
            $username = $_POST['uname'];
            $password = $_POST['pwd'];
            if (!empty($username) && !empty($password)) {
                if (!$user->login($_POST['uname'], $_POST['pwd'])) {
                    show_msg('Attention', 'Wrong username and/or password');
                } else {
                    if (is_admin()) {
                        redirect_to(BASE);
                    } else {
                        redirect_to(BASE);
                    }
                }
            } else {
                show_msg("Attention", "All fields are required ");
            }
            break;
        case 'logout':
            $user->logout();
            redirect_to(BASE);
            break;
        case 'register':
            if (!empty($_POST['username']) && !empty($_POST['pwd']) && !empty($_POST['email'])) {
                $data    = array(
                    'username' => $_POST['username'],
                    'email' => $_POST['email'],
                    'password' => $_POST['pwd'],
                    'level' => 1
                );
                $user_id = $user->insertUser($data); //The method returns the userID of the new user or 0 if the user is not added
                if ($user_id == 0)
                    show_msg('Not Registered', 'User not registered'); //user is allready registered or something like that
                else {
                    show_msg('Registered', 'User registered with user id ' . $user_id . '');
                    //redirect_to(BASE);
                }
            } else
                show_msg('Attention', 'ALL FIELDS REQUIRED');
            break;
        
        default:
            echo "no action";
    }
}
?>
Let us look into the details of the script in order.
  • Firstly,we declared the global variable $user which points to the object of the user class.
  • Checks whether the action isset using $_GET['action'] .
  • If set,the value is assigned to a variable $action.
  • Here the value can be login or logout or register.
  • We have used switch statement to perform the defined action.
Login action.

if the action to be performed is login,the post variables are checked.If the post varables are not empty,the following code is executed.
$user->login($_POST['uname'],$_POST['pwd'])
Remember the login method used in user_class.php.
The admin will be our first user i.e the user with user id 1.
BASE is our base url.
Similarly logout action as well as register action are carried out by their corresponding methods in the user_class.php.

The functions redirect_to(),is_admin(),show_message() will be added later to the functions.php.

Friday, March 2, 2012

Why dont you create your own CMS???--Part 8

From this post onwards,we are entering our second phase of our 'stupid' cms creation.
In this phase,we will
  • start using sessions.
  • create a simple user management system.
  • create some more useful functions .
  • build a small notification message system using 'freeow'.
We will be creating a session class and a user class to manage sessions and users respectively.So lets start our second phase...

Building the session class

This class will be used to create a session,set a session variable and get those session variables.
  • Open  stupid >>> include  directory.
  • create a file named  'session_class.php'.
  • Open the file in an editor and write the following code.

<?php
class Session {
 function Session() 
 {
  session_start();
 }
 
 function destroy_session()
 {
 session_unset();
 session_destroy();
 }
 
 function set_session($name,$val)
 {
  $_SESSION[$name] = $val;
 }
 
 function set_session_variable($name,$val)
 {
  $this->set_session($name,$val);
 }
 
 function get_session($name)
 {
  if(isset($_SESSION[$name]))
  return $_SESSION[$name];
 }
 
 function get_session_variable($name)
 { 
 return $this->get_session($name); 
 }
}

?> 

Since all the methods are simple , I am not elaborating each of them.
Now let us focus our attention on the user management system.

Building the user class

Our user class will have the following features
  • can check whether the user is loaded or not.
  • can check whether the user is logged in or not,active or not.
  • can insert a user when registered successfully.
  • can assign different levels for users.
  • can login and logout a user.
However you can increase the efficiency at any time by adding some more useful methods.
Before we move into the file,lets create a users table in our stupid database.
CREATE TABLE IF NOT EXISTS `users` (
            `u_id` smallint(11) NOT NULL AUTO_INCREMENT,
            `username` varchar(50) NOT NULL,
            `password` varchar(50) NOT NULL,
            `email` varchar(50) NOT NULL,
            `level` tinyint(11) NOT NULL DEFAULT '3',
            `active` tinyint(1) NOT NULL DEFAULT '1',
            PRIMARY KEY (`u_id`)
          ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 ;
The first registered user will be our admin.
Now lets code our user_class.php file.This will also be inside in our include directory.
So here is the code....

<?php

class User
{
    
    var $user_id;
    var $user_data = array();
    
    /**
     * Class Constructure
     * 
     * @param string $dbConn
     * @param array $settings
     * @return void
     */
    function __construct()
    {
        if (!empty($_SESSION['user_id'])) {
            $this->loadUser($_SESSION['user_id']);
        }
        
    }
    
    /**
     * Login function
     * @param string $uname
     * @param string $password
     * @param bool $loadUser
     * @return bool
     */
    
    function login($uname, $password, $loadUser = true)
    {
        global $db, $ss;
        $uname    = escape($uname);
        $password = $originalPassword = escape($password);
        $password = "MD5('$password')";
        $res      = $db->query("SELECT * FROM `users` 
  WHERE `username` = '$uname' AND `password` = $password LIMIT 1", __LINE__);
        if ($db->fetch_num($res) == 0)
            return false;
        if ($loadUser) {
            $this->user_data = $db->fetch_array($res);
            $this->user_id   = $this->user_data['u_id'];
            $ss->set_session_variable('user_id', $this->user_id);
            $ss->set_session_variable('username', $this->user_data['username']);
        }
        return true;
    }
    
    /**
     * Logout function
     * param string $redirectTo
     * @return bool
     */
    function logout($redirectTo = '')
    {
        global $ss;
        $ss->destroy_session();
        $this->userData = '';
        if ($redirectTo != '' && !headers_sent()) {
            header('Location: ' . $redirectTo);
            exit; //To ensure security
        }
    }
    /**
    to get a property of a user
    eg- 
    get_property('username') returns the username
    ***********************************/
    
    function get_property($property)
    {
        return $this->user_data[$property];
    }
    
    /**
     * Is the user an active user?
     * @return bool
     */
    function is_active()
    {
        return $this->user_data['active'];
    }
    
    /**
     * Is the user loaded?
     * @ return bool
     */
    function is_logged_in()
    {
        return empty($this->user_id) ? false : true;
    }
    
    function insertUser($data)
    {
        global $db;
        if (!is_array($data))
            echo ('Data is not an array');
        $password = "MD5('" . $data['password'] . "')";
        foreach ($data as $k => $v)
            $data[$k] = "'" . escape($v) . "'";
        $data['password'] = $password;
        $data_keys        = implode(',', array_keys($data));
        $data_values      = implode(',', $data);
        $db->query("INSERT INTO users (" . $data_keys . ") VALUES (" . $data_values . ")");
        return (int) mysql_insert_id($db->connection);
    }
    
    /**
     * A function that is used to load one user's data
     * @access private
     * @param string $userID
     * @return bool
     */
    function loadUser($user_id)
    {
        global $db, $ss;
        $res = $db->query("SELECT * FROM `users` WHERE `u_id` = '" . escape($user_id) . "' LIMIT 1");
        if (mysql_num_rows($res) == 0)
            return false;
        $this->user_data = mysql_fetch_array($res);
        $this->user_id   = $user_id;
        $ss->set_session_variable('user_id', $this->user_id);
        return true;
    }
    
}
?>
A brief idea of all the methods can be gained from reading the comments in the file itself.So I am skipping the description of this class file for time being.
if you have any doubts about the codes,please post comments....