Programmer wannable attitude

Well, Grasshopper, or Unschooled Acolyte, or whatever your title of choice may be…

You did not hear this from me.

But most developers belong to the Church of Pain and we pride ourselves on our arcane talents, strange cryptic mumblings and most of all, the rewards due the High Priesthood to which we strive to belong.

Let me put it bluntly. Some of this very complicated logic is complicated because it’s very complicated. And pretty little tools would do both the complexity and us injustice, as high priests or priests-in-training of these magical codes.

One day we will embrace simple graphical tools. But only when we grow bored and decide to move on to higher pursuits of symbolic reasoning; then and not a moment before will we leave you to play in the heretofore unimaginable sandbox of graphical programming tools. Or maybe we’ll just design some special programs that can program on our behalf instead, and you can blurt out a few human-friendly (shiver) incantations, and watch them interpret and build your most likely imprecise instructions into most likely unworkable derivative codes. Or you can just take up LOGO like they told you to when you were but a school child in the… normal classes.

Does that answer your impertinent question?

Comes from http://ask.slashdot.org/comments.pl?sid=4766093&cid=46191783

procedural MVC in php

Well I am reading some question on http://programmers.stackexchange.com/questions/184664/mvc-pattern-on-procedural-php regarding procedural MVC in php. Then I am thinking why it should not be possible? After all MVC is about architecture, You can make good architecture also in procedural programming. You just need to design proper architecture. As I checkout on MVC Frameworks, their are some common terms like

  • Bootstrap script, which initializing system, core services, routers.
  • Controllers
  • Models
  • Views

Also library, helpers are available depend on project wise.

Now I am giving you some light on, How a MVC (very basic of course ) can be built on following style.

Architecture

Project Root
    config
        config.php
    lib
        core.php
    controllers 
        UserController.php
        BaseController.php
    models
        User.php
    views
        user 
            index.php
        base 
            welcome.php
    resources
        css
            style.css

config.php Sample Code :

define('MODEL_DIR', 'models');
define('VIEW_DIR', 'views');

$config = array (
    'default_module' => 'base', 
    'default_action' => 'index',
);

lib/core.php Sample Code :

function safe($param) {
    return addslashes($param);
}

function render($file, $data)
{
    $layout_file = VIEW_DIR.'/layouts/layout.php';
    ob_start();
    include_once($file);
    $content = ob_get_clean();
    include_once($layout_file);
}

Bootstrap index.php Sample Code :

Let Request url is like /index.php?module=user&action=index

require_once('config/config.php');
require_once('lib/core.php'); // For some core functions like render
//require_once('lib/db.php');   // For DB Abstraction [ Later Improvement ] 

$module = isset($_REQUEST['module'])?safe($_REQUEST['module']):$config['default_module'];
$action = isset($_REQUEST['action'])?safe($_REQUEST['action']):$config['default_action'];

$controller_file = 'controllers/'.ucfirst($module).'Controller.php';
if(!file_exists($controller_file))
{
    trigger_error('Invalid Controller');
    exit;
}
require_once($controller_file);
$function = strtolower($module).'_controller_'.$action;
if(!function_exists($function))
{
    trigger_error('Invalid Controller Action');
    exit;
}
call_user_func($function, $_REQUEST);

BaseController.php Sample Code :

function base_controller_index($request)
{
    render(VIEW_DIR.'/base/welcome.php', array());
}

UserController.php Sample Code :

function user_controller_index($request)
{
    require_once(MODEL_DIR.'/User.php');
    $data = user_model_list($request);
    render(VIEW_DIR.'/user/index.php', $data);
}

function user_controller_add($request)
{
}

function user_controller_edit($request)
{
}

function user_controller_view($request)
{
}

Model User.php Sample Code :

function user_model_list($request)
{
    return array(
        array('name' => 'test', 'sname' => 'test1', 'city' => 'testc'),
        array('name' => 'abc', 'sname' => 'xyz', 'city' => 'mno'),
    ); 
}

function user_model_add($request)
{
}

function user_model_edit($request)
{
}

function user_model_view($request)
{
}

Layout file views/layouts/layout.php Sample Code :

<html>
<head>
<link rel=’stylesheet’ href=’resources/css/style.css’ type=’text/css’ media=’all’ />
<head>
<body>
<div><h1>Logo</h1></div>
<div><h2>Heading</h2></div>
<div class=”content”>
<?php echo $content ?>
</div>
<body>
</html>

View views/base/welcome.php Sample Code :

<i>Welcome</i>
<p>
<a href=”?module=user&action=index”>User Listing Page</a>
</p>

View views/user/index.php Sample Code :

<table class=”listing”>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>City</th>
</tr>
<thead>
<tbody>
<?php foreach($data as $row) { ?>
<tr>
<td><?php echo $row['name'] ?></td>
<td><?php echo $row['sname'] ?></td>
<td><?php echo $row['city'] ?></td>
</tr>
<?php } ?>
<tbody>
</table>

Sample code could be found at https://github.com/kuldeep-k/procMVC

chat box effects by css

It is something strange for CSS effects article from a programmer. But yes today I am sitting on PC and check out some CSS effects after some explore I get the cute box can be used for a chat box.

These is generated after some css3 special effects like shadow, radius, transform. The css can be applied like that.

<style>
    .box {
        width: 300px;
        min-height: 50;
        border-radius: 5px;
        box-shadow: 3px 3px 5px 6px #ccc;
        padding: 15px;
        margin: 10px;
        font-family: arial;
        font-size: 13px;
        transform: skew(-10deg);
        -webkit-transform: skew(-10deg);
              
    }

</style>

Screenshot for resulted box is 

Image

While all effects work on FF20 on without using -moz prefix, While for strange reason Chrome 25 still need -webkit prefix to apply transform effects.

You can check the demo from http://jsfiddle.net/RqQbp/

Some Quotes

I think he knows what Rome is. Rome is the mob. Conjure magic for them and they’ll be distracted. Take away their freedom and still they’ll roar. The beating heart of Rome is not the marble of the senate, it’s the sand of the coliseum. He’ll bring them death – and they will love him for it. (From Gladiator Movie, Ref Mob mentality)

Working with subversion – II

In previous article, I discuss some basic functions of svn. Now i will discuss some more handful features for svn.

But first one disclaimer I will only show some basic example for svn commands. They are very powerful and can be used with variety of parameter to achieve required results.

First sometimes we need to know about our svn setup. So svn info comes as handy here.

$ svn info
URL: https://svn.yourdomain.com/project123/branches/dev
Repository Root: https://svn.yourdomain.com
Repository UUID: 3aaa9e22-3660-1222-1111-ccca444822
Revision: 10
Node Kind: directory
Schedule: normal
Last Changed Author: User1
Last Changed Rev: 10
Last Changed Date: 2013-03-13 01:23:12 +0530 (Wed, 13 Mar 2013)

As you see it gives information like SVN url total revision last commited revision info etc.
Some times we will need to analyze the changes log. For that svn log command is very handful.
Syntax : svn log <File Path>

$ svn log test.php
------------------------------------------------------------------------
r2 | user2 | 2013-03-13 01:23:12 +0530 (Wed, 13 Mar 2013) | 2 lines
some changes
------------------------------------------------------------------------
r1 | user1 | 2013-03-13 01:14:14 +0530 (Wed, 13 Mar 2013) | 1 line
First code commit

This is helpful to check which user commited which version. You can also track down the previous version file contents through svn cat command
Ex. for check test.php for version 123

Syntax : svn cat -r<revision> <File Path>

Example

$ svn cat -r123 test.php

For save into file to analyze, use bash stdout like that

$ svn cat -r123 test.php > test-prev.php

One more command is very much used for track down changes between versions and that is svn  diff

Syntax : svn diff <File Path>

Example

$ svn diff test.php

Above command returns the difference between latest commited version and uncommited changes for test.php. You also can check difference from any particular revision by pass revision.

Syntax : svn diff -r<revision> <File Path>

Example for Changes in test.php after version 4.

$ svn diff -r4 test.php

Their are times when you need structure without svn footprints (folders/files related to svn ) Example to upload somewhere. You need svn export command.

Syntax : svn export <Folder Path to export structure >

Example

$ svn export /home/user/backups/

It will create project123 folder into /home/user/backups/. Remember it will create folder, you should not create folder at that path with same name.

I hope these cheat sheet for svn is usable for readers

Working with subversion – I

Their are many version control software available in market. Subversion/svn can be said market leader atleast for centralized systems. Today I can discuss some most used svn client commands for better project handling.

First you need to install subversion, So fire apt-get command on your shell window.

$ apt-get install subversion
Now subversion is installed on your system.

First command you need is cloning the repository into your local system. So you need to take svn checkout for that repository.

Ex.
$ svn checkout https://svn.yourdomain.com/project123/branches/dev

you can also use short word co instead of checkout.

After checkout we need some work. So let create a file test.php and put some code into it. Now if we analyze through following command we see output like this

$ svn status
? test.php

? mark says that it is still not part of your svn repository. You need to add it by
$ svn add test.php

You can use bash expression like test.* or folder/*php or similar to add multiple files/folder into svn.

now if you use svn status, output is different then previous

$ svn status
A test.php

This changes is local till now, And we need to commit the changes on server.

$ svn commit test.php -m 'ADD MESSAGE'

If you skip message part through line a default shell editor (like nano/vim) opened to fill message, You entered and save/exit through editor Then file is commited as previous command

$ svn commit test.php

You can also remove the any file in svn by using svn delete command. It works on local copy like svn add does and requires svn commit after it to done actually on server.

$ svn delete test.php
$ svn commit test.php -m 'DELETE MESSAGE'

Now Let if you added a file, remove a file or make changes in any of file, But not commited that file on server. You can revert your changes using revert command.

$ svn revert test.php

Afte verify on svn status you will found that,
This command removed the A flag and Add ? on previously svn added file
This command removed the D flag on previously svn deleted file
This command removed the U flag on previously updated file

NOTE : In any case commited changes can not be reverted through revert command.

For take latest changes from server, we need update command. This is little tricky as It will involve merge your changes with updates comes from server. And most challenging part of svn is to take care of it.

$ svn update
A test.php
D test1.php
U test2.php
G test3.php
C test4.php

These are most common updates return from server.

  • A denotes any newly added file on server added to your local structure.
  • D denotes any any file is deleted on your local structure as that file is rmeoved on svn serve too .
  • U denotes simple update on any file when you have not any local changes.
  • G denotes simple update on any file when you have any local changes but not on same line.
  • C denotes simple update on any file when you have any local changes on same line.

There are chances when update comes on file where you have any local changes on same line. Then their would be a prompt for conflict management with options p – postpone, df – diff, mc – mine-conflict, tc – their conflict. More

  • df option show the diff of both version.
  • mc option merge updations with the case that in case of same line conflict, local changes will be taken.
  • tc option merge updations with the case that in case of same line conflict, remote changes will be taken.
  • p option merge both version with conflict lines/part will be shown as <<< >>> block. That need to resolved first to commit. It also create some more files like test.php.mine, test.php.r101, test.php.r104. Where test.php.mine is local file before potpone merging. test.php.r104 or test.php.r<remote version> file having remote changes. test.php.r101 or test.php.r<remote previous version> file having previous remote commited version  changes.

After using postpone options and creating required changes, You need to resove conflict by

$ svn resolve test.php

There are two options available but not shown in  prompt.

  • mf option discard remote file changes and take local file as verify version.
  • tf option discard local file changes file and take remote file as verify version.

NOTE 1 : You need to commit changes in case of svn update file status G and C.
NOTE 2 : You may need to enter svn username/password in case of svn checkout/update/commit

That all for this article, We will discuss some more interesting features of svn in next article.

Basic Ejabberd install/setup on ubuntu (External Script Authentication)

In first article, I discussed the installation and normal chat with users registered internally. Now i am going to discuss the external authentication through a php script.

If you want to authenticate users via your database. their are two alternatives.
1. Using odbc, It have one restriction as its internal database have and that is password must be stored plain. (Latest version may not have this restriction.)
2. Using external authentication script. In this way you can authenticate user via a custom script. Here one good php script can be found there. https://github.com/deceze/ejabberd-extauth-PHP. Now download an extract in some location of your system (not necesarily on apache document root as it will working as cli script ).

Now first create a php script in same folder. I name it auth.php. This file should have similar code suggested at github page. I am updating it using some real query.



#!/usr/bin/php
require 'ejabberd_external_auth.php';
class Auth extends EjabberdExternalAuth {
    protected function authenticate($user, $server, $password) {
        $stmt = $this->db()->prepare("SELECT user_id FROM user WHERE username = ? AND password = ? ");
        $stmt->execute(array($user, password));
        if($stmt->rowCount() >= 0 )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    protected function exists($user, $server) {
        $stmt = $this->db()->prepare("SELECT user_id FROM user WHERE username = ? ");
        $stmt->execute(array($user));
        if($stmt->rowCount() >= 0 )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
$pdo = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'user', 'password');
new Auth($pdo, 'auth.log');

I skipped $server argument in query check as If you need only users for one chat server. If you need to handle multiple servers then you may need to change code to reflect server too in query.

Now comment internal auth_method by

%%{auth_method, internal}.

And uncomment, change the line

{auth_method, external}.
{extauth_program, "/path/to/auth.php"}.

gave executing permission to auth.php by chmod 0755 auth.php.

NOTE – As this script executed by ejabberd user created at time of ejabberd installation. So this script need execute permission for ejabberd. You may add ejabberd to your user’s group and gave group to execute permission or gave other to execute permission. In both case it is advisable to check execute file after login through other user.

Add chat users in your user table. You will also need admin user to add into your DB with same password to run admin console.

Now restart ejabberd. and verify by adding user at you jabber client. if it going failed. Then verify log file var/log/ejabberd.log. If file have error to not connecting. check php script again for any error.

Ejabberd default enabled MUC (multi user chat or several other modules ), So you can verify/use also this functionality too.

That’s all for this article, In next article I will discuss message logging.