Sunday, 27 November 2011

CakePHP url rewriting problem?

If you are facing url rewriting problem in cakephp even though you have enabled rewrite module.....Here is the solution....



- Just go to the httpd.conf file.

- Find the following text groups

  <Directory />
       Options FollowSymLinks
       AllowOverride None
       Order deny,allow
       Deny from all
  </Directory>

and

  # AllowOverride controls what directives may be placed in .htaccess files.
  # It can be "All", "None", or any combination of the keywords:
 # Options FileInfo AuthConfig Limit
 AllowOverride None.

- Replace 'AllowOverride None' with 'AllowOverride All' on both places.

- Save file and Restart Apache

Refresh Page and the problem is resolved. :)

Saturday, 26 November 2011

SMS Gateway Integration in PHP

To Integrate SMS Gateway in PHP you have to signup for an account with SMS service providers. To find any one out of them just google for it and you will get a list of providers.

All of them are paid service providers and some of them provide you just few free credits so that you can test their service.

Following is the example of such a provider http://www.clickatell.com/

After logged in it provides us an API that we would have to use for sending sms.

You can connect to the gateway using HTTP/s, SMPP, SMTP, FTP, XML, SOAP etc...

I have opted for HTTP/s

Following are the step to connect via HTTP:

    1) When you sign up for an HTTP/S account, you will be given a username, password and api_id: keep these at hand!

    2) Once your registration has been activated you will receive 10 free credits with which to test our service.

    3) Have the number you wish to send to ready in international format e.g. 448311234567.

    4)Open your browser (e.g. Internet Explorer), and type in your info in the address bar in the following sequence:
        http://api.clickatell.com/http/sendmsg?user=xxxxx&amp;password=xxxxx&amp;api_id=xxxxx&
        amp;to=448311234567&amp;text=Meet+me+at+home
 
      Press 'Enter' on your keyboard and your message will be sent.

                                                or

      In PHP you can use Curl and HttpRequest class to make HTTP requests. For example in curl you can do that as following.

<?php 

   $url = "http://api.clickatell.com/http/sendmsg?user=xxxxx&amp;password=xxxxx&amp;api_id=xxxxx&amp;to=448311234567&amp;text=Meet+me+at+home"; 
   $ch = curl_init(); 
   curl_setopt($ch, CURLOPT_URL, $url); 
   curl_setopt($ch, CURLOPT_HEADER, TRUE); 
   curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body 
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
   $head = curl_exec($ch); 
   $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
   curl_close($ch);

   if($httpCode == 200)
           echo "Message Sent Successfully"; 
   else 
           echo "There is some problem"; 
   die; 

?>

     The text of your message must be formatted so that '+' signs replace spaces between words as above.

Sunday, 20 November 2011

How to access remote server using PHP SSH?

To remotely access a server in PHP provides a full library of functions called SSH2 functions. You can get the manual from the link. You'll get most of the information from the manual itself but it also leaves the user with some questions which are unanswered. Here i am just trying to explain the same in some better way..

Simple Example : 

<?php
    if (!function_exists("ssh2_connect"))
        die("function ssh2_connect doesn't exist");
    if(!($con = ssh2_connect("www.example.com", 22(port number)))){
        echo "fail: unable to establish connection\n";
    } else {
        if(!ssh2_auth_password($con, "username", "password")) {
            echo "fail: unable to authenticate\n";
        } else {
            echo "okay: root logged in...\n";
            $stream = shell_exec("mkdir /var/www/shiv");
        }
    }

?>

Important Notes :

1) If you are logged in as a normal user(not root user) then you can't change user and login to the root or super user using these function. You can use su as a command but can't enter password as a command because server only allow the user to enter password through standard input device. For example if you are trying like this:

$stream = shell_exec("su; superuser password");

then it won't work.

2) If you want to run multiple commands then you have to use single shell_exec() function for that. For example :

$stream = shell_exec("mkdir /var/www/shiv; mkdir /var/www/modi");

It would create two sub-directories named 'shiv' and 'modi' in /var/www/ directory.


while


$stream = shell_exec("mkdir /var/www/shiv");
$stream = shell_exec("mkdir /var/www/modi");

commands won't work, because command n shell environment will not be remembered during the execution of command n+1.If you want the shell commands to be working while depending on each other in terms of environment, you should put several commands in a unique ssh2_exec().


Now you can run any number of commands on remote server. You can also use ssh php function to download, upload files etc....

Saturday, 19 November 2011

CakePHP-MultivalidatableBehavior: Using many validation rulesets per model.

If you are looking for action specific validation on a model then here it goes like that :

Following code examples are based on the following scenario:

1) We have a model Member.

2) We wanna two type of validation sets on that.

     a) First in case of Login (default)
     b) Second in case editing Profile. 

3) How to use these validation sets in action.


Step 1 :
<?php 
    class MultivalidatableBehavior extends ModelBehavior {

    /**
     * Stores previous validation ruleset
     *
     * @var Array
     */
    var $__oldRules = array();

    /**
     * Stores Model default validation ruleset
     *
     * @var unknown_type
     */
    var $__defaultRules = array();

    function setUp(&$model, $config = array()) {
        $this->__defaultRules[$model->name] = $model->validate;
    }

    /**
     * Installs a new validation ruleset
     *
     * If $rules is an array, it will be set as current validation ruleset,
     * otherwise it will look into Model::validationSets[$rules] for the ruleset to install
     *
     * @param Object $model
     * @param Mixed $rules
     */
    function setValidation(&$model, $rules = array()) {
      
        if (is_array($rules)){
            $this->_setValidation($model, $rules);
        } elseif (isset($model->validationSets[$rules])) {
            $this->setValidation($model, $model->validationSets[$rules]);
        }
    }

    /**
     * Restores previous validation ruleset
     *
     * @param Object $model
     */
    function restoreValidation(&$model) {
        $model->validate = $this->__oldRules[$model->name];
    }

    /**
     * Restores default validation ruleset
     *
     * @param Object $model
     */
    function restoreDefaultValidation(&$model) {
        $model->validate = $this->__defaultRules[$model->name];
    }

    /**
     * Sets a new validation ruleset, saving the previous
     *
     * @param Object $model
     * @param Array $rules
     */
    function _setValidation(&$model, $rules) {
            $this->__oldRules[$model->name] = $model->validate;
            $model->validate = $rules;
    }

}

?> 

Save the file as \app\models\behaviors\multivalidatable.php

Step 2 : 

Go to Member model and make the following changes.

<?php

    class Member extends AppModel{
           
        var $primaryKey = 'member_id';
        var $actsAs     = array('Multivalidatable');
       
        var $validate   = array(
            'username'    =>    array(
                'notEmpty' => array(
                    'rule' => 'notEmpty',
                    'required' => true,
                    'message'  => 'Username/Email is Required',
                    'last' => true
                ),
                'email'    =>    array(
                    'rule' => 'email',
                    'message'=> 'Please provide valide username',
                    'last' => true
                )
            ),
            'password'    =>    array(
                    'rule' => 'notEmpty',
                    'message'=> 'Password is Required',
                    'last' => true
            )           
        );
       
        var $validationSets = array(
            'member_detail' => array(
                'first_name' =>    array(
                    'notEmpty' => array(
                        'rule' => 'notEmpty',
                        'required' => true,
                        'message'  => 'First Name is Required',
                        'last' => true
                    )
                ),
                'last_name' =>    array(
                    'notEmpty' => array(
                        'rule' => 'notEmpty',
                        'required' => true,
                        'message'  => 'Last Name is Required',
                        'last' => true
                    )
                ),
                'email'    =>    array(
                    'notEmpty' => array(
                        'rule' => 'notEmpty',
                        'required' => true,
                        'message'  => 'Email is Required',
                        'last' => true
                    ),
                    'email' =>    array(
                        'rule' => 'email',
                        'message' => 'Please provide valid email',
                        'last' => true
                    )
                )
            )
        );
    }



?> 

Step 3:

Go to the Members controller or to the controller actions where you want to validate a particular validate set. For example

<?php

  class MemberController extends AppController {

        var $name             = 'Member';
        var $helpers          = array('Html','Session','Javascript','Ajax');
        var $components  = array('Session','RequestHandler');
        var $uses             = array('Member');
              
        function beforeFilter() {
            $this->__validateLoginStatus();
        }

        ...............................................
       ....................................................

        function login() {
           
            if($this->Session->check('Member') === true) {
                $this->redirect('/member/index');
                exit;
            } else {
                if($this->params['form']) {
                    $this->Member->set($this->params['form']);
                   
                    if($this->Member->validates($this->params['form'])) { //here the default set would work
                   
                                   ...................................................
                                  ...................................................
                                                       
                    } else {
                        if($this->Member->validationErrors)
                            $this->errors = $this->Member->validationErrors;
                    }
                }
            }
            $this->set('errors',$this->errors);
            $this->set('notifications',$this->notifications);
            $this->set('form',$this->params['form']);
               
       }

       ........................................................................
       ........................................................................

      function edit($member_id) {
           
            $member= array();
            if($member_id) {
               
                if($this->params['form']) {
                   
                    ..........................................
                    ..........................................  
               
                    $this->Member->setValidation('member_detail'); // here it will use member_detail set for validation
                   
                    if($this->Member->validates()) {
                        $this->Member->save();
                        $this->Session->setFlash("Record updated successfully.");
                    } else
                        $this->errors = $this->Member->invalidFields();
                   
                }
            }

            $this->set('member',$member);
            $this->set('errors',$this->errors);
        }
 
       ........................................................................
       ........................................................................

  }

?>

So when you will call the edit action while saving profile details the 'member_detail' validation set would be called.

Here it's done...Enjoy!!!!!!!!!!!!


Sunday, 13 November 2011

Automatic Startup of Apache on Linux Server?

To start Apache automatically, follow these steps:
  • Copy Apache startup file to the startup directory:
cp /usr/local/apache/bin/apachectl /etc/init.d/

            In my case ‘apachectl’  was at location /usr/sbin/apachectl so I have used

            cp /usr/sbin/apachectl /etc/init.d/

  •  Edit /etc/init.d/apachectl by inserting these 2 lines in bold:
          
      #!/bin/sh
      #
      # chkconfig: - 345 85 15
      # description: Apache is a Web server used to serve HTML files and CGI.
      #
      # Copyright 2000-2005 The Apache Software Foundation or its licensors, as
      # applicable.
        . . .
      # Apache control script designed to allow an easy command line interface
      # to controlling Apache.  Written by Marc Slemko, 1997/08/23
      . . .

  • Enable httpd to startup automatically: 
          # chkconfig –-add httpd

  • To start mysql on startup too, use:
         # chkconfig –-add mysqld

  • Reboot Linux to verify Apache starts.

Saturday, 12 November 2011

How to Authenticate Users With Twitter OAuth ?

Best tutorial is available here.

Going through that tutorial you will learn

1) How to create twitter application.

2) How to get oauth_token, oauth_token_secret, user_id and screen_name of the authorized user.

3) How to update status using twitter API.

Sunday, 6 November 2011

Installing GUI under CentOS 6

If you installed using a text login and wish to switch to a graphical login, follow this procedure.

1) If you are not already root, switch users to the root account:

su -

Provide the administrator password when prompted.

2) If you have not already done so, install the X Window System and a graphical desktop environment. For example, to install the GNOME desktop environment, use this command:

yum groupinstall "X Window System" Desktop

To install the KDE desktop environment, use:

yum groupinstall "X Window System" "KDE Desktop"

This step may take some time as your Linux system downloads and installs additional software. You may be asked to provide the installation media depending on your original installation source.

3) Run the following command to edit the /etc/inittab file:

vi /etc/inittab

4) Press the 'i' key to enter insert mode.

5) Find the line that includes the text initdefault.

To change from a console to a graphical login, you should change the number in the line id:3:initdefault: from a 3 to a 5.

6) Type :wq and press the Enter key to save the file and exit the vi text editor.

If you want to go in graphical environment before restarting the server. Just type

#yum startx

Otherwise, Reboot the system using the reboot command. Your system will restart and present a graphical login.

Saturday, 5 November 2011

How to install Linux – CentOS 6 for Servers & Desktops

1) Set your computers BIOS to boot form CD / DVD

2) Insert the CentOS 6 CD or DVD

3) When presented with the following screen press enter on Install or upgrade an existing system.



4) You will now be presented with a CD Check, I always skip this step… I live life on the edge when it comes to media checking on Linux installs. However you might want to check the media.


5) You will now see some black and white text on your screen as your computer loads the X11 environment for the CentOS install, after 30 seconds or so you will be presented with the CentOS GUI installer, click next.


6) Select your Language, I am British (please no jokes about drinking tea on Twitter…) so I would select English (English).


7) Select your keyboard type


8) Storage type, as I am installing on my local hard drive I selected “Basic storage type” if you are using iSCSI or similar technology now would be the time to set it up.


9) As this is a clean install and the drive has never been formatted before I got the following Initialize drive warning, you might get the same if your drive (or virtual hard disk) is brand new.


10) Set the hostname for your Server


11) Set your timezone / location


12) Set your root password, something sensible please… Don’t set weak dictionary passwords or you will get hacked by a 13yr old russian super hackz0r… You might want to check out my guide on how to secure SSH.


13) You will now be set with a bunch of options for your disk partitioning, as this is a new fresh install I selected the top option “Use All Space” chose the relevant option for your setup and tick the review and modify partition layout.


14) You will now see your partition table laid out, now is the time to modify it if required. If this is a server I would suggest you create some different partitions for /home and /var. These are the two partitions that crash Linux servers, /home because users fill their home drives and causes the system to crash and /var because the log or ftp directories fill up and crash the server.


15) Format warning, click on Format (this will delete your data).


16) You will now see a warning about writing the changes to disk, click on Write changes to disk.


17) Boot loader options, I left this as default you might want to set a boot loader password.


18) The next part is important, for servers I ALWAYS select minimal, this installs a minimal setup which is ideal for servers, if you are installing for a desktop you might want to chose one of the other options. I would avoid the chose everything option as this will create a bloated system that will be more susceptible to hackers.


19) CentOS 6 will install


20) CentOS 6 has installed, congrats


21) Reboot and login as root


22) Update the system using “yum update”


Sometimes yum update doesn't work and we get error of following type

[root@centos-box ~]# yum update Loaded plugins: fastestmirror, refresh-packagekit Determining fastest mirrors Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=6&arch=i386&repo=os error was 14: PYCURL ERROR 6 - "" Error: Cannot find a valid baseurl for repo: base

In this case you have to do the following:
Manually edit /etc/sysconfig/network-scripts/ifcfg-eth0 to get networking up:

[root@centos-box ~]# vi /etc/sysconfig/network-scripts/ifcfg-eth0

BOOTPROTO=dhcp
NM_CONTROLLED=no
ON_BOOT=yes

Save the file and reboot the server.

That’s it your done! Go forth and setup your server for what ever services you require, Asterisk, LAMP etc.

Odoo 10: Close wizard and open standard form

Hi, Today we are going to learn how to open standard form after saving data in wizard. Let's say I have created an wizard to fill bas...