Monday, November 10, 2014

How to override Customer Account controller in Magento 1.8

I once had a requirement to change/modify or add new functionalities to the "Customer Account Controller" which is responsible for new registration, customer log in, log out, redirect to Customer dashboard, Forgot Password procedures etc. In such cases, we better not modify the core files directly. If we change the core files, all our work would get lost if Magento is upgraded to other versions. So, it is better if extend the core controllers and add our custom codes in it. This way our custom code would be there even if Magento is upgraded.

To achieve this, we would create a new module. The following points need to be remembered. 

To know how a basic 'Hello World' module is created in Magento, check this article "Building a basic Hello World module in Magento 1.8".

1. The controller which we want to override is: app/code/core/Customer/controllers/AccountController.php

2. Our new module name is "Newcustom_Customer" where "Newcustom" is the namespace name and "Customer" is our module name.

3. Next we create an xml file called "Newcustom_Customer.xml" inside app/etc/modules/Newcustom_Customer.xml 

4. So, we create a folder structure like this :: app/code/local/Newcustom/Customer and inside it, we create 2 more folders namely "etc" and "controllers".

5. Inside the app/code/local/Newcustom/Customer/etc folder, we create the configuration file for the module called config.xml

6. Inside the app/code/local/Newcustom/Customer/controllers folder, we copy paste the original app/code/core/Customer/controllers/AccountController.php

So, we need to work on mainly 3 files :: 

a. app/etc/modules/Newcustom_Customer.xml
b. app/code/local/Newcustom/Customer/etc/config.xml
c. app/code/local/Newcustom/Customer/controllers/AccountController.php

1. Let's start with the first file Newcustom_Customer.xml. It's content should be like this ::

<?xml version="1.0"?>
<config>
 <modules>
  <Newcustom_Customer>
    <active>true</active>
    <codePool>local</codePool>
  </Newcustom_Customer>
 </modules>
</config>

The above piece of XML tells Magento that this module would run from "app/code/local" codepool. 

2. Next check out the config.xml file for our module. 

<?xml version="1.0"?>
<config>
  <modules>
    <Newcustom_Customer>
      <version>0.1.0</version>
    </Newcustom_Customer>
  </modules>

  <frontend>
   <routers>
    <customer>
<use>standard</use>
     <args>
       <modules>
         <Newcustom_Customer before="Mage_Customer">Newcustom_Customer</Newcustom_Customer>
       </modules>
     </args>
    </customer>
   </routers>
  </frontend>
</config>

This XML would help to override the core Mage_Customer's controller.

3. And finally, the controller file itself (AccountController.php) needs to be modified. But it should extend the Mage_Customer's AccountController.php file's Mage_Customer_AccountController class.

<?php
// Include the Original Mage_Customer's AccountController.php file
// where the class 'Mage_Customer_AccountController' is defined
require_once Mage::getModuleDir('controllers', 'Mage_Customer').DS.'AccountController.php'; 

// Now extend the class 'Mage_Customer_AccountController'

class Newcustom_Customer_AccountController extends Mage_Customer_AccountController  
{

  // We can add more functionality

  public function test()
  {   

  }
  
  // Re-Write the Old Methods
  public function loginPostAction()
  {
        
  }      

}

?>

Now, we are done. As we have extended the original 'Mage_Customer_AccountController' class, all the original functions are automatically available to this new over-ridden controller. And we can still add some more functionality by adding our custom functions to our class.  Some points need to be noted here :

1. Check how our extended class is defined with a name "Newcustom_Customer_AccountController".
2. We are extending the original Mage_Customer's controller class 'Mage_Customer_AccountController' to get the original functionality.

Hope this helps.

Wednesday, November 05, 2014

Manual Login and Logout in WordPress

Very recently, I had a situation where I needed to take user's username and password as inputs and log him/her onto Wordpress manually. And this is how I came up with the solution. Check the code below.

<?php
// This is a very important step
// We need to get the wp object
require("wp-load.php");   

// Log Out if anyone is already logged
// in from same browser
if ( is_user_logged_in() ) 

   // Default Wordpress function 
   // to log a user out
   wp_logout(); 
}

// GET user's Inputs (username, password)
$creds = array();
$creds['user_login']    = $_POST['username'];
$creds['user_password'] = $_POST['password'];

// Extra settings, for Remember me
$creds['remember'] = false;

// The Wordpress function which Logs
// the user in
$user = wp_signon( $creds, false );

// Track ERROR if any
if ( is_wp_error($user) )
{
  echo $user->get_error_message(); 
}
// Login Success
else
{
  echo "You have logged in successfully";
}
?>

The code above is quite self-explanatory. Some points to be noted : 

1. wp_signon() -- It logs any user in with username and passwords passed to it in Array. This function takes a 2nd parameter to mention whether secured cookies are to be used.
2. wp_logout() -- It logs out if any user is logged in
3. The array $cred must be built with the keys ('user_login' and 'user_password') shown above.

Thursday, October 30, 2014

Number summation problem

Very recently, I have come across an interesting programming problem which is shown below.

Problem :: We have an array of various numbers. From that array we need to find those numbers which can be written as sum of 2 or more consecutive numbers existing within the same array.

Say for example, in an array of numbers (5,1,3,2,4,6), the first number "5" can be written as "3+2" but not "1+4" as "1" and "4" are not appearing consecutively. Similarly "6" can be written as "5+1" and "2+4" etc. 

So, we need to find out all the numbers which are sum of other consecutive numbers and print them.

1. So, will be requiring a loop which would inspect every number in the array (starting from 5,1 and so on). Let's examine the case of "5".

2. Inside the above loop, we start with adding-numbers (which would be added to produce "5") "1" and start checking if consecutive numbers "3", "2" (i.e 1+3+2+...) and so on can produce the sum "5".
   So, we need a second loop for this. This would find the starting point of adding-numbers. A successful series may be "1+3+..." or "3+2+.." or "2+4+.." etc. So, 1,3,2 etc are starting numbers from which we start to add consecutive numbers.

3. Now, let's consider a case where we have such a starting number say "1". We need a third loop which would run through rest of the array to add consecutive numbers "3", "2" etc  to "1" and produce a sum of "5". This third loop will produce the actual sum.

4. We keep a track whether minimum 2 numbers are added to produce the final result "5" through a counter.

Let's check the code part to understand our approach to solve the problem. The inspection of number "5" have been discussed in comments in the code below.

<?php
// Define the array
$arr = array(5,1,3,2,4,6);

// Here we have the FIRST loop to inspect 
// each number in the array
for($i=0;$i<count($arr);$i++)
{
  // Store the Current number we are inspecting
  // Let's examine the case of 5
  $current_number = $arr[$i];
  
  // Second Loop
  for($j=0;$j<count($arr);$j++)
  {
      // Set $sum variable to hold SUM
      $sum = 0;
      $str = "";
 
      // $count variable makes sure that minimum
      // two numbers are added
      $count = 0;
 
      // We would ignore the Number we are inspecting
      // while Addint. We won't add "5" to $sum 
      // (initially set to 0) to product "5". 
      // Hence we just ignore the situation
      if($j == $i) continue;  
 
      // Otherwise, We move ahead
      if($j != $i) 
      {
  
        // Third Loop, it keeps on Adding to $sum from 
        // the starting point say "1" or "3" or "2" and so on.
        for( $k=$j;$k<count($arr);$k++)
{

          // Avoid the chance of adding the Number
           // which is being inspected (5 in our test case)
          if($k == $i) break;
 
       // Add to SUM ($sum variable)
          $sum += $arr[$k];
  
   // When we add, we increase the counter
   // We need to make sure that minimum 2 numbers
   // are added to produce "5"
   $count++;
  
   // We build a String of numbers we are adding
   $str .= $arr[$k] . ",";
  
    // If summation is already higher than 
           // the Number being inspected, we discard 
           // that combination. This way we can 
           // discard "1+3+2" resulting 6 etc and 
    // save some precious CPU time
    if($sum>$current_number) 
           { 
              break; 
           }
  
          // If minimum 2 digits are added
           // and Sum is "5" let's PRINT the result 
           // and break. This means if we find that 
           // "3+2" is acceptable, then we need to 
           // move to next starting point say "2" and                          // check combinations like "2+4+..." etc
          if($count >= 2 && $sum == $current_number) 
          { 
            // Show Result
            echo "<br> ($i position)" .
                 " $current_number is summation" .
                 " of numbers ". rtrim($str,","); 
            break; 
          } 
      } // Third Loop Ends
    
     }// If ends
 
  } // Second Loop ends

} // First Loop Ends

?>

The above code is explained within the accompanied comments. 

Now, Check the output below :

(0 position) 5 is summation of numbers 3,2
(4 position) 4 is summation of numbers 1,3
(5 position) 6 is summation of numbers 5,1
(5 position) 6 is summation of numbers 1,3,2
(5 position) 6 is summation of numbers 2,4

Wednesday, October 29, 2014

Find longest substring inside a string

Very recently I have seen a small programming problem given on a site, which is shown below.

Find the length of the longest substring without repeating characters within a given string.

Take the string 'immediate' for example. The longest non-repeating letters would be "mediate". We can't accept "mmediate" because 'm' is repeating. 

In the string "borough", there are longest substring (non-repeating characters) will be "rough".

In the string "xxxxxx", the longest substring without non-repeating characters is "x".

So, we are going to write a program in PHP which would find the longest substring. And we are following this process ..

1. We would run a loop to examine the given string, reading character from 0th position, 1st position and so on.
2. We would pick up non-matching characters and store them in a character array. That array of characters will be converted to sub-strings.
3. Such sub-strings will be stored in a final array.
4. If we have a list of substrings, easily we can make out which is the longest substring among them using the strlen() function and a for loop.

Let's check out the final code :: 

<?php

// The given string is here
$str = "aksjdhiquywenqmneqkjosiqioueyqwemndfgppoiuytrewqasdfghyujikolrvcxzvbybnuimklopoiui";

// This is the final array where substrings will be stored
$subs = array();

// The main LOOP which reads the string
// So when $i is 0, the $str is read from 0th position
// When $i is 1, the $str is read from 1st position
for($i=0;$i<strlen($str);$i++)
{
  
  // A small array where picked-up characters will be stored
  $k = array();
  
  // Another loop which picks up characters from given string
  // and adds to the array $k  
  for($j=$i; $j<strlen($str); $j++)
  {
    // The array $k will be built with characters which are
    // not repeated earlier. So, we used in_array() to check
    // if this picked-up character is already existing in array $k
    if(!in_array( $str[$j], $k))
    {
       $k[] = $str[$j];
    }  
    else
    {
      // So we found a repeating character
      // So, BREAK to build the Substring
      break; 
    }
  }
  
  // When $k holds the series of characters
  // now build the substring and put it in the
  // array $subs
  $subs[] = implode("",$k);
}

// So, now $subs array holds all the possible substrings
// existing in the given string. Now is the time, we 
// find the longest among them
$max = 0; 
$final_str = "";

// Loop and scan
for($i=0; $i< count($subs); $i++)
{
  if(strlen($subs[$i]) > $max) 
  { 
      $max = strlen($subs[$i]); 
      $final_str = $subs[$i]; 
  }
}

// Finally print the result
echo "Max Length : $max, String : [$final_str]";
?>

The above code is quite self-explanatory. Each simply tries to create/extract substrings from the given string. For that we need to run a loop scanning from 0th position in the string $str. 

So, in the first pass, characters are picked up from 0th position in $str and kept in array $k till a non-matching character is found. Next the array $k is converted to a string (read substring) and put in the final array $subs.

In the 2nd pass, characters are picked up from 1st position in $str and kept in array $k and a substring is built eventually and kept in array $subs

This way, we build an array of all the possible substrings (made with non-repeating charaters) exist inside the string $str. 

And finally we simply decide which is the longest among them and print the result.

The above program displayed the output to be ::
Max Length : 21, String : [ewqasdfghyujikolrvcxz]

Monday, September 01, 2014

Serialization / Unserialization in PHP - III

We have already discussed how we can serialize/unserialize objects in PHP. Here we would see how we can achieve the same thing using the interface Serializable. 

To use this interface, we have to do away with the __wakeup() and __sleep() magic methods. So, the class implementing this interface does not need these magical functions to be defined. The Serializable interface has 2 abstract functions declared ( without their content body ) which means we must define their content body inside the class which implements this interface. These function have the following signatures :: 

// To get the String representation of our Object
abstract public string serialize ( void ) 

// To Construct our object back from the string

abstract public void unserialize ( string $serialized_data )

When the object needs to be serialized, the serialize() method is called. Similarly, when a new object ( of a particluar Class, and that Class Name is known as it (class name) was stored in the String Representation ) needs to be restored, the constructor __construct() is not automatically called; instead the unserialize() function is called as a working constructor. If we need to run the __construct(), we may call it explicitly ( self::__construct(); ) inside the unserialize() function.

So, let's check an example :

<?php
// Our class is implementing the
// Interface Serializable
class MyClass implements Serializable 
{
// Private Data
private $data1;
private $data2;

// Protected Data
protected $data3;
protected $data4;

// Public Data
public $data5;
public $data6;


// Constructor called
public function __construct()
{
   echo "<br> Constructor called";
 $this->data1 = "100";  
   $this->data2 = "200";  
   $this->data3 = "300";  
 $this->data4 = "400";  
 $this->data5 = "500";  
 $this->data6 = "600";  
 
 }

// Serialize function
public function serialize()
{
 echo "<br>Serialize called";
 
 // Return the serialized data
 return serialize(
    array( "data10" => $this->data1,
   "data20" => $this->data2,
"data30" => $this->data3,
"data40" => $this->data4,
"data50" => $this->data5,
"data60" => $this->data6,
 ));
}

// Unserialize function
public function unserialize($data)
{
 // We can call __construct explicitly
 // self::__construct();
 
 echo "<br>unSerialize called";
 
 // Unserialize
 $d = unserialize($data);
 
 // Re-Construct the Object
 $this->data1 = $d['data10'];
 $this->data2 = $d['data20'];
 $this->data3 = $d['data30'];
 $this->data4 = $d['data40'];
 $this->data5 = $d['data50'];
 $this->data6 = $d['data60'];
}

// display() function
function display()
{
  for($i=1;$i<=6;$i++)
    {
      echo "<br>" . $this->{"data$i"} ;
    }
 }

}

// Create a new Object

$obj = new MyClass;

// Serialize the Object

$ser = serialize($obj);

// Check the Serialize Data

var_dump($ser);

// Create new Object from Serialized data

$p   = unserialize($ser);

// Check the Object

var_dump($p);

// Call Public method on Object

$p->display();
?>

The code above is quite self-explanatory through its comments. Let's check out the output of the above code.

Constructor called
Serialize called
string 'C:7:"MyClass":144:{a:6:{s:6:"data10";s:3:"100";s:6:"data20";s:3:"200";s:6:"data30";s:3:"300";s:6:"data40";s:3:"400";s:6:"data50";s:3:"500";s:6:"data60";s:3:"600";}}' (length=164)

unSerialize called

object(MyClass)[2]
  private 'data1' => string '100' (length=3)
  private 'data2' => string '200' (length=3)
  protected 'data3' => string '300' (length=3)
  protected 'data4' => string '400' (length=3)
  public 'data5' => string '500' (length=3)
  public 'data6' => string '600' (length=3)

100

200
300
400
500
600

Let's analyse the output.

1. When $obj object was created, the respective constructor was called printing "Constructor called" on screen.
2. Next, when serialize() function is called upon the object $obj, the member method serialize() is called generating the message "Serialize called". 
3. The 3rd line in the output is the result of serialization of object properties. 
4. Next, we issue the statement $p = unserialize($ser); to unserialize the serialized data and create our new object $p. Hence "unSerialize called" message is displayed on screen.
5. var_dump( $p ) generates the couple of lines next, showing all the properties (and their values) within the object $p.
6. Next, when we call a public display() method in object $p, it iterates through all the properties inside the object and prints their values.

Wednesday, August 27, 2014

Serialization / Unserialization in PHP - II

We have seen serialization/unserialization of common types in article : Serialization / Unserialization in PHP - I

Here, we would see object serialization. When objects are serialized, PHP looks for a member function __sleep() within the object before it actually does the serialization. So, we can write various clean-up jobs ( like close file pointers, close DB connections, close any open sockets, close any streams, free any used memory, free unused variables, destroy other related objects etc ) inside this function __sleep(). We need to remember that all the private and public properties inside object are serialized.

Similarly, when the serialized format is restored to Object through the function unserialize(), PHP calls __wakeup() member function (if exists) after it is finished with re-constructing the object. We can write various jobs ( restore DB connections, open files which the object works with etc ) inside this function __wakeup()

Let's check a code where object is serialized. 

<?php
// Define a Class
class MyClass  
{
    // private properties
    private $data1;
    private $data2;

    // protected properties
    protected $data3;
    protected $data4;

    // public properties
    public $data5;
    public $data6;

    public function __construct()
    {
      // Initialize private properties
      $this->data1 = "\r\n";  
      $this->data2 = NULL;  
      
      // Initialize protected properties
      $this->data3 = NULL;  
      $this->data4 = "400";  
 
      // Initialize public properties
      $this->data5 = "500";  
      $this->data6 = "600";  
    }

    // __sleep() 
    public function __sleep()
    {
echo "__Sleep called";
 
        // within __sleep(), all the clean-up jobs
        // can be included. Along with that, it also
        // needs to return name of the properties 
        // to be serialized in an array format
return array("data1", "data2", "data3", "data4", "data5", "data6");
    
    }

    // __wakeup
    public function __wakeup()
    {
       echo "__wakeup called";
    }

    public function display()
    {
        // Display all the properties
        // We used a simple Loop
for($i=1;$i<=6;$i++)
{
         echo "<br>" . $this->{"data$i"} ;
}

    }
}

// Create Object
$obj = new MyClass;

// Serialize it
$ser = serialize($obj);

// See what happened after serialization
echo "$ser";

// Unserialize it to restore the 
// data/properties in a new object
$p   = unserialize($ser);

// $p is the new Object, hence
// call a member function
$p->display();
?>

The above code defines a class called "MyClass", which includes 3 private and 3 public properties and __wakeup(), __sleep() methods. It also includes a method called display() which shows the values in all the properties. The __wakeup() method should return all the properties which need to be serialized within an array. The __wakeup() function does not have such restrictions.

The above program can run without the __sleep() and __wakeup() methods. In that case the clean-up jobs etc can't be defined and we can't define/select properties which need to be serialized. In that case PHP serializes all the properties within that object.

When serializing the private properties within the object, the class name is  prepended to the property name. Protected properties get an asterisk '*' prepended to their names. Such prepended values have Null bytes padded on both sides.

The code above produces 2 outputs, first is the serialized text of the object, second a list of property values in object $p which is created during the unserialization process of the stored representation we generated when $obj was serialized. Let's check the first output rendered on browser.

O:7:"MyClass":6:{s:14:"MyClassdata1";s:2:" ";s:14: "MyClassdata2";N;s:8:"*data3";N;s:8:"*data4";s:3:"400"; s:5:"data5";s:3:"500";s:5:"data6";s:3:"600";}

O:7:"MyClass":6: means Object having name "MyClass" (length:7) with 6 properties

s:14:"MyClassdata1";s:2:" "; means private property "MyClassdata1" (string, length:14) holds a string (length:2) value " ". Class name "MyClass" is prepended to Private properties. The value " " is text representation rendered on browser, actually it contains '\r\n'. As class name "\0MyClass\0" (padded by Null bytes on both side) was prepended to "data1" making it to "\0MyClass\0data1", the length of the new string is 14 ( 12 of "MyClassdata1" + 2 NULL bytes ) .

s:14:"MyClassdata2";N;        means private property "MyClassdata2" (string length 14) holds a NULL value;
s:8:"*data3";N;                          means protected property "*data3" (string length 8 including NULL bytes on both side) holds NULL value
s:8:"*data4";s:3:"400";      means protected property "*data4" holds string (length:3) value "400
s:5:"data5";s:3:"500";         means public property "data5" holds string (length:3) value "500
s:5:"data6";s:3:"600";         means public property "data6" holds string (length:3) value "600

Next part of the program is the unserialization part where we call the unserialize() function to restore an object from the stored representation $ser. And as a result, we create new object $p of type "MyClass" (The serialized data starts with "O:7:"MyClass"). Hence the call $p->display() calls the member function display() which iterates through all the properties inside the $p object and prints them on screen.

In such cases where object of undefined class to be created during unserialization, it creates object of "stdClass". Check the example below :

<?php
// an Array is being converted to Object
$o = (object) array("name" => "chandan");

// Serialize 
$ser = serialize($o);

// Unserialize would instatiate
// Object of class PHP default 'stdClass'
$po = unserialize( $ser );

// Print the new object details
var_dump($po);

// Access member properties
echo "Hello {$po->name}";
?>

The above code is quite self-explanatory. It produces the following output :: 

object(stdClass)[2]
  public 'name' => string 'chandan' (length=7)

Hello chandan

$po is an object of PHP built-in class 'stdClass' with a public member "name" and this property holds a string value "chandan". So, when $po->name is referred, it prints the correct value as unserialize() correctly re-constructed object from stored representation.