Monday, December 08, 2014

How to log in/out Magento user to Wordpress blog - I

This is a case where Wordpress blog is integrated inside Magento and we want a single sign-up/login/logout for users. It means the following things ::

1. Wordpress is installed in any subfolder within Magento installation.
2. When a user signs up for Magento, he is automatically signs up for Wordpress. Actually a new user needs to be created manually in Wordpress.
3. When a user logs on in Magento, he is also logs in Wordpress.
4. When a logged-in user logs out from Magento, he is also logged out from Wordpress.

As Magento user is automatically registered to Wordpress, the default Wordpress sign-up/registration should be disabled. To disable wordpress sign-up, we need to go to Settings > General in Wordpress Admin Panel and uncheck the option "Anyone Can Register".

Now, for our working, we need to know that sign-up, login and logout procedures are handled by AccountController.php inside the path app/code/core/Mage/Customer/controllers. So, the module name is Mage_Customer and the controller class name is Mage_Customer_AccountController.

We need to edit the AccountController.php and put our custom code inside it. Let's check out the registration process. There is an action called "createPostAction" which registers a Magento user. The form on registration page has an action "http://127.0.0.1/magento/customer/account/createpost/" (on my local machine), so the function createPostAction() is responsible for creating the customer account.  

First check out the final code below, then analyze it. Our Custom code is shown in blue below. Whole function is not shown below... only the section where customization is needed is shown.

<?php
public function createPostAction()
{
  ......
 
  $customer = $this->_getCustomer();

  // GET CUSTOMER PASSWORD
  $pwd = $this->getRequest()->getPost('password'); 

  try 
  {
    $errors = $this->_getCustomerErrors($customer);
         if (empty($errors)) 
    {

$customer->save();
$this->_dispatchRegisterSuccess($customer);

// PUT The password in SESSION
// So That we can LOG him in WordPress also
Mage::getSingleton('core/session')->setPwd($pwd);

$this->_successProcessRegistration($customer);
return;
    } 
    else 
    {
$this->_addSessionError($errors);
    }
  } 
  catch (Mage_Core_Exception $e) 
  {
     ...
  }

  catch (Exception $e) 
  {
     ...
  }
?>

The above piece of code accepts user inputs, processes and validates by calling other functions like _getCustomerErrors(), and finally saves the new customer (if everything is fine) information to DB through the statement $customer->save() and finally calls the _successProcessRegistration() function to show Success Message, send mails and other tasks. Now we are supposed to create a Wordpress account with an username and password; username can be created from user's first name which can be retrieved any time, it is difficult to retrieve the password. Hence we had to receive the password from the user and put it on session. Now  let's make a little changes to the function _successProcessRegistration().

<?php
protected function _successProcessRegistration(Mage_Customer_Model_Customer $customer)
{
  $session = $this->_getSession();
  if ($customer->isConfirmationRequired()) 
  {
     ...

     // at the end of existing code 
     // INSERT the USER into WORDPRESS
     $this->insertToWordpress( $customer, $c );
  } 
  else 
  {

     // before the existing code
     // INSERT the USER into WORDPRESS
     $this->insertToWordpress( $customer, $c );

     ...
  }

  $this->_redirectSuccess($url);
  return $this;
}
?>

So, we just call our custom function insertToWordpress() from within _successProcessRegistration() to create new wordpress user. Check out the code for insertToWordpress() below.

<?php
protected function insertToWordpress(Mage_Customer_Model_Customer $customer, $customer_group)
{
 
  // Create Capabilities
  $usr_typ_arr["author"] = true;
  
  $session = $this->_getSession();

  // Customer ID
  $Magento_customer_ID = $customer -> getId();  
  
  // GET Tables 
  $wp_user_table = "wp_users";
  $wp_usermeta_table = "wp_usermeta";
  
  // GET Fields which will be written to USER TABLE
  $user_login      = $customer->getFirstname();
  $user_pass       = md5( Mage::getSingleton('core/session')->getPwd() );
  $user_nicename   = $user_login;
  $user_email      = $customer->getEmail();
  $user_url        = "";
  $user_registered = date("Y-m-d h:i:s");
  $user_activation_key = "";
  $user_status     = 0;
  $display_name    = $user_login;
  
  // Unset PASSWORD from SESSION
  Mage::getSingleton('core/session')->unsPwd();
  
  // DEFINE DB Handle
  // To read from the database
  $read  = Mage::getSingleton( 'core/resource' )->getConnection( 'core_read' ); 
  // To write to the database
  $write = Mage::getSingleton( 'core/resource' )->getConnection( 'core_write' ); 
  
  // GET Table Name
  $userTable = Mage::getSingleton( 'core/resource' )->getTableName( $wp_user_table );
  
  $userMetaTable = Mage::getSingleton( 'core/resource' )->getTableName( $wp_usermeta_table );
  
  // INsert into USER Table
  $query = "INSERT into " . $userTable . " values ('', '$user_login', '$user_pass', '$user_nicename', '$user_email', '$user_url', '$user_registered', '$user_activation_key', '$user_status', '$display_name')";
  $write->query( $query );
  
  // GET Last Insert ID (user ID)
  $last_insert_id = $write->lastInsertId();
  
  // BUIL SQL for Inserting into user Meta Table
  $q = array();
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'first_name','".$customer->getFirstname()."')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'last_name','".$customer->getLastname()."')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'nickname','$user_nicename')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'description','')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'rich_editing','true')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'comment_shortcuts','false')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'admin_color', 'fresh')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'use_ssl', '0')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'show_admin_bar_front', 'true')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'wp_capabilities', '".serialize($usr_typ_arr)."')";
  
  // 2 for Author, who can manage/publish their content
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'wp_user_level', '2')"; 
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'dismissed_wp_pointers',  'wp350_media,wp360_revisions,wp360_locks,wp390_widgets')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'magento_user_id',  '$Magento_customer_ID')";
  
  // ACTUAL INSERT to User Meta Table
  for($i=0;$i<count($q);$i++) 
     $write->query( $q[$i] );

}
?>

The above function builds some values out of customer object, and then makes entries to wordpress "user" and "usermeta" tables. The "usermeta" table in Wordpres holds various information about the user including user capabilities and user level. As said earlier, we are using the customer's first name as Wordpress login name and Magento password as Wordpress password. After we create the Wordpress user, we unset the password we had put in session by calling Mage::getSingleton('core/session')->unsPwd();  

This way, we create users for both Magento and Wordpress. 

So, the Registration process is complete. For logging in/out simultaneously in Magento and Wordpress, check the part 2 of this article How to log in/out Magento user to Wordpress blog - II

No comments: