Saturday, November 5, 2016

AngularJS With Examples – Filters

In this article, we'll create our first angularjs application. And hayy!!! its not the traditional Hello World application. :P We are gonna try to build an app which can add, delete members and filter members based on a text. Its very basic, I know.. but its good enough to start with. Lets call our application as FilterApp. We will be using bootstrap CSS for styling purpose. For small applications (especially for learning purpose), I always follow the following app skeleton. Here we will be following the same structure. Feel free to use it in your way. The directory structure will look as



The app root folder is FilterApp. It contains three subfolders
  • css : Contains bootstrap css file and styles.css file where we can add our custom styles if needed.
  • fonts : Contains the fonts for bootstrap.
  • js : Contains all the javascript files. The libraries are included in a separate lib folder within js.
Now create the following files in the folders specified.
  • An html file to describe the layout, FilterApp.html in the root (FilterApp) folder.
  • app.js and controllers.js inside js folder.
So now, we have all the files to start building our first angularjs application. Lets start... Open FilterApp.html using your favourite editor (I prefer Brackets or Notepad++) and add the basic HTML5 layout.
<!doctype html>
<html>
<head>
<title> Filter a list </title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
</head>
<body>
</body>
</html>
Since bootstrap css is our CSS framework, we need those too. Include the following lines of code within the <head> tag.
<link rel="stylesheet" href="css/bootstrap.min.css">
Add the below line of code just after closing body </body> tag to include angularjs library.
<script src="js/lib/angular.min.js"></script>
OK, now we have to bootstrap our application. ng-app directive is used for this purpose.
Use this directive to auto-bootstrap an AngularJS application. The ngApp directive designates the root element of the application and is typically placed near the root element of the page - e.g. on the <body> or<html> tags. You can have multiple apps within the same page.
In our app, we are using this inside <html> tag.
<html ng-app="FilterApp">
Open app.js and add the following line of code,
var filterApp = angular.module('FilterApp', []);
With this line of code, we actually initialize our app and register the modules on which it depends (specified inside square brackets,here none). Now we have to create a controller which will perform all our logic and initialize the $scope object. The $scope variable connects your controller and views. It holds all the data that will be used within your template. Anything you add to it will be directly accessible in your views. Open controllers.js  and add the following code
var filterAppControllers = angular.module('filterAppControllers', []);

filterAppControllers.controller('MainCtrl', function ($scope) {

});

filterAppControllers.controller('FilterCtrl', function ($scope) {
$scope.members = ['Google', 'Facebook', 'Microsoft'];

$scope.addMember = function () {
$scope.members.push($scope.newMember);
$scope.newMember = '';
};

$scope.deleteMember = function (item) {
var index = $scope.members.indexOf(item);
$scope.members.splice(index, 1);
};
});
Here we have created a module called filterAppControllers and added two controllers MainCtrl and FilterCtrl using .controller method. For FilterCtrl, we have initialised a $scope property named members and added two behaviours addMember and deleteMember to the scope object. Edit the app.js and change it to the following to inject the dependency
var filterApp = angular.module('FilterApp', ['filterAppControllers']);
Now include both app.js and controllers.js in FilterApp.html. For this, add the following line of code after angularjs library inclusion just above closing </html> tag
<script src="js/app.js"></script> <script src="js/controllers.js"></script>
Next, We attach our controller to the DOM using the ng-controller directive.
See that MainCtrl controller is attached to the <body> element. Hence all the properties and behaviour under this scope will be available within the <body>. As of now, we haven't defined anything under MainCtrl (see controllers.js). To make our app more flexible and modular, we have used FilterCtrl within the main controller. A simple header and footer is created using the navbar component provided by bootstrap. Lets divide the code and analyse each part. First of all, lets see the form to add a member.
<form class="form-inline text-center" ng-submit="addMember()">
<div class="form-group">
  <input type="text" class="form-control input-lg" id="txtMember" required="" placeholder="Enter Member Name"
  ng-model="newMember" pattern="[a-zA-Z]+" />
</div>
<button type="submit" class="btn btn-primary btn-lg">Add member</button>
</form>
The input textbox is binded to the newMember property on the scope of FilterCtrl controller using ng-model directive. It is a two way binding. Basically, ng-model directive binds an input,select, textarea (or custom form control) to a property on the scope. The pattern is an HTML5 attribute, which specifies a regular expression that the <input> element's value is checked against. In this case the input can only contain alphabets. On submitting this form, addMember behaviour on the scope of FilterCtrl controller is triggered. This is achieved using ng-submit directive. This happens only if the form does not contain action, data-action, or x-action attributes. As you can clearly understand from the addMember method, it adds an item to the members array on the scope. Now let us analyse the table used to display the members.
<table class="table table-striped">
  <thead>
 <tr>
   <th>Name</th>
   <th>Delete</th>
 </tr>
  </thead>
  <tbody>
 <tr ng-repeat="member in members">
   <td>{{member}}</td>
   <td><button class="btn btn-default" ng-click="deleteMember(member)"><span class="glyphicon glyphicon-trash"></span></button></td>
 </tr>
  </tbody>
</table>
The first thing you’ll notice in this template is the use of expressions (“{{“ and “}}”) to return variable values. In AngularJS, expressions allow you to execute some computation in order to return a desired value. Some valid expressions would be:
  • {{ 1 + 4 }}
  • {{ username }}
The next thing you’ll notice is the use of ng-repeat and ng-click directives. The ng-repeat directive is one of the most commonly used and serves to define your template scope when looping through collections. In the example above, it replicates a line in the table for each member in members. The ng-click directive binds an expression to onclick events. Here it call the deleteMember function on scope of the FilterCtrl controller.

Filtering the members

Adding extra functionality is always fun. So lets add a filtering functionality to our app. This will help us to filter the members list based on a text we feed. For this replace the below line
///For filtering view///
with the below line of codes
<table class="table table-striped">
  <tr>
 <td><input type="text" class="form-control" ng-model="filterTxt" placeholder="Enter filter text"/></td>
  </tr>
  <tr ng-repeat="member in members | filter : filterTxt">
 <td>{{member}}</td>
  </tr>
</table>
AngularJS filters are used for this purpose. In this code, the data that a user types into the input box (named filterTxt) is immediately available as a filter input in the list repeater (member in members | filter:filterTxt). When changes to the data model cause the repeater's input to change, the repeater efficiently updates the DOM to reflect the current state of the model. So your first angularjs application is ready to test. Always use modern browsers. Hope you enjoy this tutorial. :)

Tuesday, October 13, 2015

AngularJS With Examples - Introduction

What is AngularJS?
According to wikipedia, AngularJS (commonly referred to as "Angular") is an open-source web application framework maintained by Google and by a community of individual developers and corporations to address many of the challenges encountered in developing single-page applications.
Why we need AngularJS?
AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.
How does it work?
The AngularJS library works by first reading the HTML page, which has embedded into it additional custom tag attributes. Angular interprets those attributes as directives to bind input or output parts of the page to a model that is represented by standard JavaScript variables. The values of those JavaScript variables can be manually set within the code, or retrieved from static or dynamic JSON resources.
Who uses AngularJS?
According to Wikipedia,  AngularJS is used on the websites of NBC, Intel, ABC News, and approximately 8,400 other sites. Moreover it is used as frontend in MEAN stack.
These are the basic FAQs when it comes to AngularJS. Please stay tuned to learn angularjs with examples.

Friday, May 25, 2012

Flexible hovering effect for images

Here we are going to create a flexible hovering effect using CSS3 opacity property.
opacity is a CSS3 property that allows you to specify how opaque a given element
is. Coupled with the RGBA, opacity offers
another method to add transparency to the designs we create
for the web.
One of the ways to use opacity is to create simple and
flexible hover states for hyperlinked graphics, using the variation
in transparency .
We’re going to use the opacity property to not only control
the :hover and :focus treatment, but also to set the initial
level of transparency.

Before we start ,we need the graphics to be used as hyperlinks.
So open your graphics editor and create an icon as fully-white PNG
image with transparent background.

Create an html file and name as hover.html.
Now add your image in your html file with following line of code.
<a href="#"><img src="img/logo.png" alt="My logo" /></a>
Place the image inside a dark background ( here I have used #222 ).
<div id='container'>
<a href="#"><img src="img/logo.png" alt="My logo" /></a>
</div>
Now its time to add some styles.
<style>
#container {
background:#222;
width:100px;
height:100px;
text-align:center;
}
</style>
let’s add the opacity values that will dim the icons in
their default state, brightening them up a bit when hovered or
focused.
#container a img {
opacity: 0.25;
}
#container a:hover img,
#container a:focus img {
opacity: 0.7;
}
Here we’re showing the images at 25% opacity, then bringing
them up to 70% opacity when hovered or focused .
Note that the opacity property doesn’t require vendor prefixes,
and will work in Safari, Chrome, Firefox, and Opera.
IE8 and below don’t support opacity, but there is a hack to achieve this.

The IE opacity hack

Opacity is supported in Internet Explorer 9
Beta, but we can also mimic the same result for older versions
of IE by using the proprietary Microsoft filter property.
use of the filter property can bring increased performance
overhead depending on where or how often it’s used.
It’s a hack—but it provides a means to an end.
Here’s how it works:
#container a img {
border: none;
opacity: 0.25;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=25)"; /* IE 8 hack */
filter: alpha(opacity = 25); /* IE 5-7 hack */
}
#container a:hover img,
#container a:focus img {
opacity: 0.7;
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=70)"; /* IE 8 hack */
filter: alpha(opacity = 70); /* IE 5-7 hack */
}
The syntax is similar, with a value of opacity passed through
IE’s alpha filter. Note that IE8 ignores the filter property
and requires the vendor-prefixed –ms-filter with some additional
(ugly) values.

Adding a transition to the opacity swap will smooth
out that value change, and provide a bit of animated richness
that’ll tie this whole technique together.
We’ll make the transition rather quick (just 0.2 seconds) and ease it in and
then out again.
#container a img {
opacity: 0.25;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=25)"; /* IE 8 hack */
filter: alpha(opacity = 25); /* IE 5-7 hack */
-webkit-transition: opacity 0.2s ease-in-out;
-moz-transition: opacity 0.2s ease-in-out;
-o-transition: opacity 0.2s ease-in-out;
transition: opacity 0.2s ease-in-out;
}
#container a:hover img,
#container a:focus img {
opacity: 0.7;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=70)"; /* IE 8 hack */
filter: alpha(opacity = 70); /* IE 5-7 hack */
}
With the transition in place, we now have a simple technique
for using opacity to craft a flexible hover experience using a
single set of images.

Download source files from here...

Monday, May 21, 2012

Glowing text effect using CSS3

We have seen websites containing texts which glows on hovering over it.
In this post,we will take a quick look on how this effect is achieved.
For this technique to see in action, you need a modern browser which supports CSS3.
We will be using CSS3 shadows for this effect.
  • Create an html file and name it as glow.html
  • Create an anchor with class name glow-text inside a div with id container .
<div id="container">
<a href="#" class="glow-text">I'm glowing</a>
</div>
Now its time to add some styles.
<style>
#container {
 width:300px;
 height:100px;
 background:blue;
 margin:auto;
}
a.glow-text {
 font-size: 3em;
 line-height: 1.4em;
 color: white;
 font-style: italic;
 font-family: Georgia, times, serif;
 color: #fff;
 text-shadow: 0px 2px 5px rgba(0, 0, 0, 0.5);
 text-decoration: none;
  padding: 10px 15px;
 cursor:pointer;
}
a.glow-text:hover {
 text-shadow: 0px 0px 10px #fff;
}
</style>
 What is text-shadow

A CSS2 property (dropped in 2.1 then reintroduced in CSS3)
that adds a shadow to hypertext, with options for the direction,
amount of blur, and color of the shadow.
 text-shadow: 0px 0px 10px #fff;
What is RGBA

Not a CSS property, but rather a new color model introduced
in CSS3, adding the ability to specify a level of opacity along
with an RGB color value.
rgba(0, 0, 0, 0.5) /* black at 50% opacity */
Enjoy using glowing text-effect in your website.

Download glow.html

Thursday, May 17, 2012

Create your own CMS-Part 14

Before creating our blog module,just make sure to do the following modifications.
  • In engine.php ,add the following line to start all the enabled modules before the line $theme->load_css();
$module->start_all_enabled_modules();
  • Update show_msg function in functions.php in main folder.
/**************************************
showing a message
EG:-  show_msg('TITLE OF YOUR MESSAGE','CONTENT');
******************************************/
function show_msg($title,$msg)
{
echo '<script type="text/javascript" src="'.BASE.'/jquery.js"></script>
 <script type="text/javascript" src="'.BASE.'/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>
';
}
  • Add some more function to work with modules and themes.
/***************************
Get the list of modules present in the cms
returns both installed and uninstalled modules
****************************/
function get_modules_list()
{
global $module;
$modules_list=$module->get_modules_list();
return $modules_list;
}
/***************************
Get the list of themes in the cms
****************************/
function get_themes_list()
{
global $theme;
$themes_list=$theme->get_themes_list();
return $themes_list;
}
/************************
checks whether a module is enabled
**************************/
function is_module_enabled($module_name)
{
global $module;
return $module->is_active($module_name);
}
function register_module($name)
{
global $module;
$module->register_module($name);
}
/************************
checks whether a module is installed
**************************/
function is_module_installed($module_name)
{
global $module;
return $module->is_module_installed($module_name);
}
/*************************************
get the details of a module from its
manifest file.
************************************/
function get_module_details($name)
{
$module_details=xml2array(MODULESPATH.'/'.$name.'/manifest.xml');
$module_details['picture']=BASE.'/'.MODULESPATH.'/'.$name.'/pic.png';
return $module_details;
}
The function register module is to add the module to the database.The description and details of a module will be present in the manifest.xml file inside the directory of corresponding module.So we need a function to parse the xml file.

The function will be provided in the upcoming tutorial.

As we are advancing a little bit,the default theme will have to be modified very much.Instead ,You can download the 'fbtheme' for next stage.

Download fbtheme

Wednesday, May 16, 2012

Learn CSS transitions in easy way

In this post,we are going to learn a few tips regarding css transitions.Before we start ,take a look at how
W3C explains CSS transitions.
CSS Transitions allow property changes in CSS values to occur
smoothly over a specified duration.
This smoothing animates the changing of a CSS value when triggered by a mouse click, focus or active state, or any changes
to the element (including even a change on the element’s class attribute).

Let’s start with a simple example, where we’ll add a transition
to the background color swap of a link. When hovered over,
the link’s background color will change, and we’ll use a transition
to smooth out that change—an effect with a
few simple lines of CSS.The markup is a simple hyperlink, like so:
<a href="#" class="sample">Hover me!</a>
Next, we’ll add a declaration for the normal link state with a
little padding and a light background colour, followed by the
background swap to another colour on hover
a.sample {
padding: 5px 10px;
background: #1991fc;
}
a.sample:hover {
color: #030;
background:  #2fc;
}
Now let’s add a transition to that background color change.
This will smooth out and animate the difference over a specified
period of time
a.sample {
padding: 5px 10px;
background: #1991fc;
text-decoration:none;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
-o-border-radius: 20px;
border-radius: 20px;
-webkit-transition: background 0.3s ease;
-moz-transition: background 0.3s ease;
-o-transition: background 0.3s ease;
transition: background 0.3s ease;
}
a.sample:hover {
color: #030;
background:  #2fc;
}
You’ll notice the three parts of a transition in the declaration:
  • transition-property: The property to be transitioned (in this case,
    the background property)
  • transition-duration: How long the transition should last (0.3
    seconds)
  • transition-timing-function: How fast the transition happens over
    time (ease)
The timing function value allows the speed of the transition
to change over time by defining one of six possibilities: ease,
linear, ease-in, ease-out, ease-in-out, and cubic-bezier
(which allows you to define your own timing curve).

For longer animations, the
timing function you choose becomes more of an important
piece of the puzzle, as there’s time to notice the speed changes
over the length of the animation.
Default value is ease.

DELAYING THE TRANSITION

For example, let’s
say we wanted the background transition to happen half a
second after the link is hovered over. We can do that using the
transition-delay property.
The following example adds the same background switch to
the :focus state. This enables triggering the transition from
either hovering over or focusing the link (via the keyboard, for
example).
a.sample {
padding: 5px 10px;
background: #1991fc;
text-decoration:none;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
-o-border-radius: 20px;
border-radius: 20px;
-webkit-transition: background 0.3s ease;
-moz-transition: background 0.3s ease;
-o-transition: background 0.3s ease;
transition: background 0.3s ease;
}
a.sample:hover,
a.sample:focus {
background:  #2fc;
}

TRANSITIONING MULTIPLE PROPERTIES

Let’s say that along with the background color, we also want
to change the link’s text color and transition that as well. We
can do that by stringing multiple transitions together, separated
by a comma. Each can have their varying duration and
timing functions .
Eg:
-o-transition: background .3s ease, color 0.2s linear;

TRANSITIONING ALL POSSIBLE PROPERTIES

An alternative to listing multiple properties is using the all
value. This will transition all available properties.
Let’s drop all into our simple example instead of listing
background and color separately. They’ll now share the
same duration and timing function.
a.foo {
padding: 5px 10px;
background: #1991fc;
text-decoration:none;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
-o-border-radius: 20px;
border-radius: 20px;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
a.foo:hover,
a.foo:focus {
color: #030;
background:  #2fc;
}
This is a convenient way of catching all the changes that happen
on :hover, :focus, or :active events without having to
list each property you’d like to transition.

Saturday, May 12, 2012

Create your own CMS-Part 13

Now look at the two url given below
  • http://localhost/stupid/index.php?module=blogs&sub=editblog&action=save
  • http://localhost/stupid/blogs/editblog/save
The second url looks more readable and pretty.We can achieve this by url rewriting using htaccess or using php.In our cms we will be using htaccess.Also we will deny access for direct viewing of files in htaccess file.All the files can only be viewed through index.php or index1.php and soon....
  • Create a file in the root directory of your website (in our case 'stupid' directory)
  • Name it as '.htaccess'.Edit the file using notepad.
<FilesMatch "\.php$">   
 Order Allow,Deny  
 Deny from all
</FilesMatch>
<FilesMatch "index[0-9]?\.php$">  
 Order Allow,Deny   
 Allow from all
</FilesMatch>
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)\=([a-zA-Z0-9_-]+)$ index.php?module=$1&sub=$2&action=$3&$4=$5
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/$ index.php?module=$1&sub=$2&action=$3
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)\=([a-zA-Z0-9_-]+)$ index.php?module=$1&sub=$2&$3=$4
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/$ index.php?module=$1&sub=$2
RewriteRule ^action\=([A-Za-z0-9\_\-\/]+)$ index.php?u_action=$1
RewriteRule ^([A-Za-z0-9\_\-\/]+)/$ index.php?module=$1
In order to distinguish the action parameter within a module from user actions like login,register etc,the url variable 'action' previously used in actions.php in actions folder will be replaced by 'u_action'.
So kindly replace the first 6 lines in actions.php with the following lines.
global $user;
if(isset($_GET['u_action']))
{
$action=$_GET['u_action'];
switch($action)
Now you can set the action of login form as
<?=BASE?>/action=login
So we are done with url rewriting.In the next post we will be creating a blog module.

Sunday, April 29, 2012

Create your own CMS-Part 12

So far we have coded all the necessary class files.
Here we will create our first module 'home'.Before creating our first module,let us add two more functions in 'functions.php' in 'main' folder.
/***************************
Builds menu (left)
$menu argument must be an array
****************************/
function build_menu($menu)
{
foreach ($menu as $name=>$link)
{
 show_menu($name,BASE.$link);
}
}
build_menu function is used to build a menu for navigation.It accepts an array $menu as parameter with key indicating the name of the menu and value indicating the link.
Now add another function to show the menu.
/***************************
Shows the menu
****************************/
function show_menu($name,$link)
{
echo '<a href="'.$link.'" class="left_menu">'.$name.'</a>';
}
Creating the homepage
The homepage of our site will contain a register form and login form.
Homepage is theme based .
Open the 'default' themes folder and create 'homepage.php'.
Edit this file with your contents.
Homepage should be simple and attractive.
Download the theme with new homepage from the link below as an example.

Download default theme

Creating the first module

Home module doesn't require the necessary files to be valid.
It is valid by default.The home module, we are going to create will have only two files.
  • view.php              -      content in app_block area.
  • left_menu.php      -      menu for navigation.
Open modules folder.
Create a folder and name it as 'home'.
Create two files as mentioned above.

view.php

You can write whatever here to meet your requirements.

You might love this quote!!!

<div class="content_wrapper">
<h3>
"We've demonstrated a strong track record of being very disciplined with the use of our cash. We don't let it burn a hole in our pocket, we don't allow it to motivate us to do stupid acquisitions. And so I think that we'd like to continue to keep our powder dry, because we do feel that there are one or more strategic opportunities in the future." 
--
</h3>
</div>
<h2>
<a href="http://www.blogger.com/blogger.g?blogID=5175690629178451362">Steve Jobs </a></h2>

left_menu.php

<div id="left_menu">
$menu = array('Photos'=>'/#','Videos'=>'/#');
build_menu($menu);
if(is_admin())
{
echo '<a class="left_menu" href="http://www.blogger.com/'.BASE.'/admin/">Admin</a>';
}

?>
Navigation is created using the two functions we created in the begining of this post.



Thursday, April 26, 2012

Create your own CMS-Part 11

Sorry for the delay!
We are getting into advanced features from this post onwards.
In this post we will learn to create a custom module class.So lets begin...
  • Before we begin to create the class file , let us see the structure of a module directory.The structure given below is created by taking 'blog' module as reference.


The following files are necessary for a module to be valid.
  • 'start.php'
  • 'manifest.xml'
  • 'install.php'
The module class will contain various methods to control a module.The page to be executed (called as base file) depends on the query string in the url.The structure of our url is
http://localhost/stupid/index.php?module=val1&sub=val2&action=val3
val1 =====> any valid module  eg: blog,photos etc
val2 =====> name of sub module  eg: editblog ,viewblog,deleteblog etc
val3 =====> action filename for actions like save,edit etc

Let us create our modules class
  • Open stupid >> include directory.
  • Create a file named 'module_class.php'.
  • Open the file in an editor and write the following code.
<?php
/*
THE STRUCTURE OF OUR MODULE IS AS FOLLOWS.
FOR BETTER UNDERSTANDING BLOG MODULE IS USED AS
A REFERENCE.
NOTE: FILES WITH PREFIX * ARE ESSENTIALLY REQUIRED.

modules/
blog/
extras/
editblog.php
createblog.php
viewblog.php
actions/
save.php
create.php
delete.php
*install.php
*start.php
view.php
menu_left.php
*manifest.xml
image.png

*/

/*
The module class will contain various methods for 
controlling a module.
The structure of our url will be

"http://localhost/stupid/module=val1&sub=val2&action=val3"

val1 =====> any valid module  eg: blog,photos etc
val2 =====> name of sub module  eg: editblog ,viewblog,deleteblog etc
val3 =====> action filename for actions like save,edit etc

*/
?>

<?php
class Modules
{
    
    /**
    $module     : An array with keys name,sub and action.The values is obtained from url through $_GET method.
    $module_dir   : The path of current module  eg: modules/blogs , modules/photos.
    $module_data  : An array used to store the details of the module (obtained from database) .
    $base_file   : The file to fetch and execute .
    $logged_out_menu : The menu for a anonymous user.This will be present in the theme.
    **/
    
    var $module = array();
    var $module_dir;
    var $module_data = array();
    var $module_menu;
    var $base_file;
    var $logged_out_menu;
    
    /**
    Constructor for the modules class.
    The value of base file changes with the values in the query string.
    Have a look at the if else statement for better understanding. 
    **/
    
    function __construct()
    {
        global $theme;
        if (isset($_GET['module'])) {
            $this->module['name'] = $_GET['module'];
        } else {
            $this->module['name'] = 'home';
        }
        $this->module_dir = MODULESPATH . '/' . $this->module['name'];
        if (isset($_GET['sub'])) {
            $this->module['sub'] = $_GET['sub'];
            if (isset($_GET['action'])) {
                $this->module['action'] = $_GET['action'];
                $this->base_file        = $this->module_dir . '/extras/actions/' . $this->module['action'] . '.php';
            } else {
                $this->base_file = $this->module_dir . '/extras/' . $this->module['sub'] . '.php';
            }
        } else {
            $this->module['sub'] = NULL;
            $this->base_file     = $this->module_dir . '/view.php';
        }
        $this->module_data     = $this->get_module_data();
        $this->logged_out_menu = $theme->active_theme . '/menu.php';
    }
    
    /********************************************
    This method is used to get the data of the 
    current module.
    ********************************************/
    
    function get_module_data()
    {
        global $db;
        $res = $db->query("SELECT * FROM `modules` WHERE `name` = '" . $this->module['name'] . "' LIMIT 1");
        return $db->fetch_array($res);
    }
    
    /********************************************
    Returns true if the module is enabled
    $name : The name of the module.
    *********************************************/
    
    function is_active($name)
    {
        global $db;
        $res  = $db->query("SELECT * FROM `modules` WHERE `name` = '" . $name . "' LIMIT 1");
        $data = $db->fetch_array($res);
        if ($data['active'] == 1)
            return true;
        else
            return false;
    }
    
    /******************************************
    Checks whether the module is installed or not
    $name : The name of the module.
    ********************************************/
    
    function is_module_installed($name)
    {
        global $db;
        $res = $db->query("SELECT * FROM `modules` WHERE `name` = '" . $name . "'");
        if ($db->fetch_num($res) == 1)
            return true;
        else
            return false;
    }
    
    /******************************************
    Returs an array of all enabled modules
    ******************************************/
    
    function get_all_enabled_modules()
    {
        global $db;
        $res = $db->query("SELECT * FROM `modules` WHERE `active` = 1");
        while ($all = $db->fetch_array($res)) {
            $enabled_modules[] = $all['name'];
        }
        return $enabled_modules;
    }
    
    /*****************************************
    This is the starter for all enabled modules.
    start.php file from every enabled modules is
    included by this method.
    ******************************************/
    
    function start_all_enabled_modules()
    {
        global $db;
        $enabled_modules = $this->get_all_enabled_modules();
        foreach ($enabled_modules as $e) {
            if ($e != 'admin' && $e != 'home')
                include_once MODULESPATH . '/' . $e . '/start.php';
        }
    }
    
    /*
    This method will be called in engine.php.
    Used to view the module content by building 
    menu.
    */
    
    function view_module()
    {
        if ($this->is_module_installed($this->module['name']) && $this->is_active($this->module['name'])) {
            $this->build_menu();
            $this->view_app();
        } else {
            redirect_to(BASE);
        }
    }
    
    /**
    Builds the necessary menu for the module.
    Includes the menu_left.php
    */
    
    function build_menu()
    {
        if (file_exists($leftmenufile = $this->module_dir . '/menu_left.php')) {
            $this->module_menu = $leftmenufile;
        } else {
            $this->module_menu = MODULESPATH . '/home/menu_left.php';
        }
        
    }
    
    /*
    Views the app in the app block.
    */
    
    function view_app()
    {
        if (is_logged_in()) {
            echo '<div id="canvas">';
            echo '<div id="left">';
            include_once $this->module_menu;
            echo '</div>';
            echo '<div id="app_block">';
            include_once $this->base_file;
            echo '</div>';
            echo '<div class="clear"></div>';
            echo '</div>';
            
        } else {
            if ($this->module['name'] == 'home') {
                global $theme;
                include_once $theme->active_theme . '/homepage.php';
            } else {
                echo '<div id="canvas">';
                echo '<div id="app_block">';
                include_once $this->base_file;
                echo '</div>';
                echo '<div id="left">';
                include_once $this->logged_out_menu;
                echo '</div>';
                echo '<div class="clear"></div>';
                echo '</div>';
            }
        }
    }
    
    /********************************************
    Returns an array of all modules ( enabled and disabled ).
    Obtained by reading the modules directory.
    *********************************************/
    
    function get_modules_list()
    {
        $plugins = array();
        if ($handle = opendir(MODULESPATH)) {
            while ($mod = readdir($handle)) {
                // must be directory and not begin with a .
                if (substr($mod, 0, 1) !== '.' && is_dir(MODULESPATH . "/" . $mod)) {
                    $plugins[] = $mod;
                }
            }
        }
        sort($plugins);
        return $plugins;
    }
    
    // to activate a module
    
    function activate($name)
    {
        global $db;
        $sql = "UPDATE modules SET active='1' WHERE name = '" . $name . "'";
        $db->query($sql);
    }
    
    // to deactivate a module
    
    function deactivate($name)
    {
        global $db;
        $sql = "UPDATE modules SET active='0' WHERE name = '" . $name . "'";
        $db->query($sql);
    }
    
    /*
    To install a module.
    Before installing the installing module is checked for validity.
    */
    
    function install_module($name)
    {
        $valid = $this->check_module($name);
        if ($valid) {
            include_once MODULESPATH . '/' . $name . '/install.php';
        } else {
            show_msg('Invalid', 'This module is not valid');
        }
    }
    
    // To uninstall a module
    
    function uninstall_module($name)
    {
        global $db;
        $sql = 'DROP TABLE IF EXISTS ' . $name . '';
        $db->query($sql);
        $sql = "DELETE FROM modules WHERE name = '" . $name . "'";
        $db->query($sql);
        $sql = "DELETE FROM module_settings WHERE module_name = '" . $name . "'";
        $db->query($sql);
    }
    
    /*
    This method inserts the module into modules table in the database.
    */
    
    function register_module($name)
    {
        global $db;
        $sql = "INSERT INTO modules(name) VALUES('" . $name . "')";
        $db->query($sql);
    }
    
    /**
    Returns true if module is valid.
    A module is valid if it contains the 
    required files.
    **/
    
    function check_module($name, $valid = false)
    {
        if (file_exists(MODULESPATH . '/' . $name . '/install.php') && file_exists(MODULESPATH . '/' . $name . '/view.php') && file_exists(MODULESPATH . '/' . $name . '/manifest.xml'))
            $valid = true;
        return $valid;
    }
    
    // to enable a module
    
    function enable_module($name)
    {
        $this->activate($name);
    }
    
    // to disable module
    
    function disable_module($name)
    {
        $this->deactivate($name);
    }
    
}
?>  
All the methods are named in such way that you can specify the function it does easily.
Also the functions can be easily understood from the comments in the file.So I am skiiping the explanation of each methods specifically.You can just comment below if you need an explanation of any methods.
So we have created our class file successfully.Now its time to create an object of the class.As usual class instantiation is done in 'engine.php' in 'main' folder.The modified 'engine.php' looks like below

<?php
include_once('functions.php');
include_once('config/base.php');
include_once(CLASSPATH . '/database_class.php');
include_once(CLASSPATH . '/session_class.php');
include_once(CLASSPATH . '/user_class.php');
include_once(CLASSPATH . '/theme_class.php');
include_once(CLASSPATH . '/module_class.php');
global $db, $ss, $user, $theme, $module;

$db     = new Database();
$ss     = new Session();
$user   = new User();
$theme  = new Theme();
$module = new Modules();

/**********************************/

/*******************************/
$theme->load_css();
$theme->load_index();

/******************************
to view the module
*******************************/

$module->view_module();
$theme->load_footer();

/*******************************
 *******************************/
include_once('/actions/actions.php');
?>

In the next post , we will be creating our first module 'home'.



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-&gt;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.