Sunday, April 14, 2013

Magento : Import Gmail Contact

1. Define a link in any phtml file as
<?php
    $client_id=  '';                  
    $redirect_uri='test/test/gooledata';
    $scope = "https://www.google.com/m8/feeds/"; //google scope to access
    $state = "profile"; //optional                   
    $loginUrl = sprintf("https://accounts.google.com/o/oauth2/auth?scope=%s&state=%s&redirect_uri=%s&response_type=code&client_id=%s",$scope,$state,$redirect_uri,$client_id);
?>
Import E-mail Addresses From:<br />
<a href="javascript:poptastic('<?php echo $loginUrl; ?>');">Import</a>



<script>
function poptastic(url) {
      var newWindow = window.open(url, 'name', 'height=600,width=450,top=100,left=500');
      if (window.focus) {
        newWindow.focus();
      }
     
 }
function showGmailData(){
       //location.reload();
       jQuery("#gmailloader").css('display', 'block');
            jQuery.ajax({
                    type: "POST",
                    data : jQuery("#form-validate").serialize(),
                    url: '/invitation/index/showgmaildata',
                    success: function(data) {
                    jQuery("#gmailloader").css('display', 'none');
                    result = jQuery.parseJSON(data);
                    if(!result.success) {
                    }
                    else    {

                    }
              }
            });
 }
</script>

2. Define Redirect action in controller
public function googledataAction(){        
              
        $authcode= $this->getRequest()->getParam('code');
        $importcontacts = array();
        if(isset($authcode) && $authcode != ''){
           $importcontacts = Mage::helper('test')->importGmailContacts($authcode);
           //print_r($importcontacts);
           //Mage::getSingleton('core/session')->setImportcontacts($importcontacts);
           echo '<html><body>Please wait....<script type="text/javascript">window.opener.showGmailData(); window.close();</script></body></html>';
           die();
          
        }       
    }

3. Define importGmailContacts() method in helper
public function importGmailContacts($authcode){       
            try{
            $clientid='';
            $clientsecret='';
            $redirecturi='test/test/googledata';
            $fields=array(
            'code'=>  urlencode($authcode),
            'client_id'=>  urlencode($clientid),
            'client_secret'=>  urlencode($clientsecret),
            'redirect_uri'=>  urlencode($redirecturi),
            'grant_type'=>  urlencode('authorization_code')
            );
            $fields_string='';
            foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
            $fields_string=rtrim($fields_string,'&');
            //open connection
            $ch = curl_init();
            //set the url, number of POST vars, POST data
            curl_setopt($ch,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
            curl_setopt($ch,CURLOPT_POST,5);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
            // Set so curl_exec returns the result instead of outputting it.
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            //to trust any ssl certificates
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            //execute post
            $result = curl_exec($ch);
            //close connection
            curl_close($ch);
            //extracting access_token from response string
            $response   =  json_decode($result);
            $accesstoken= $response->access_token;
            if( $accesstoken!='')
           
            $xmlresponse=  file_get_contents('https://www.google.com/m8/feeds/contacts/default/full?max-results=100&oauth_token='. $accesstoken);
            //reading xml using SimpleXML
            $xml=  new SimpleXMLElement($xmlresponse);
            $xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
            $result = $xml->xpath('//gd:email');
            foreach ($result as $title) {
                $importcontact[] = (string)$title->attributes()->address;
            }
            Mage::getSingleton('core/session')->setImportcontacts($importcontact);
            //return $importcontact;
            }  catch (Exception $e){ echo $e->getMessage();}
    }

4.Then use according to requirement in following action
public function showGmailDataAction(){
        $result = array(
                'success' => false,
                'message' => false,
                'count' => false,
            );
$importcontacts = Mage::getSingleton('core/session')->getImportcontacts();
$this->getResponse()->setBody(Zend_Json::encode($result));
        return;
    }
               

Magento : Custom router in Magento

Suppose, we need to create a custom url like 'abc' for test/test/index

1. Define an event in config.xml
<events>
            <controller_front_init_routers>
                <observers>
                    <test>
                        <class>Bd_Test_Controller_Router</class>
                        <method>initControllerRouters</method>
                    </test>
                </observers>
            </controller_front_init_routers>
 </events>

2. Then define router class in Controller folder
<?php

class Bd_Test_Controller_Router extends Mage_Core_Controller_Varien_Router_Abstract
{
    /**
     * Initialize Controller Router
     *
     * @param Varien_Event_Observer $observer
     */
    public function initControllerRouters($observer)
    {
        /* @var $front Mage_Core_Controller_Varien_Front */
        $front = $observer->getEvent()->getFront();

        $front->addRouter('test', $this);
    }

    /**
     * Validate and Match Cms Page and modify request
     *
     * @param Zend_Controller_Request_Http $request
     * @return bool
     */
    public function match(Zend_Controller_Request_Http $request)
    {
        if (!Mage::isInstalled()) {
            Mage::app()->getFrontController()->getResponse()
                ->setRedirect(Mage::getUrl('install'))
                ->sendResponse();
            exit;
        }

        $identifier = trim($request->getPathInfo(), '/');

        $condition = new Varien_Object(array(
            'identifier' => $identifier,
            'continue'   => true
        ));
       
       
      
        if ($condition->getRedirectUrl()) {
            Mage::app()->getFrontController()->getResponse()
                ->setRedirect($condition->getRedirectUrl())
                ->sendResponse();
            $request->setDispatched(true);
            return true;
        }

        if (!$condition->getContinue()) {
            return false;
        }

      
        if ($identifier!='abc') {
            return false;
        }

        $request->setModuleName('test')
            ->setControllerName('test')
            ->setActionName('index');
          
        $request->setAlias(
            Mage_Core_Model_Url_Rewrite::REWRITE_REQUEST_PATH_ALIAS,
            $identifier
        );       

        return true;
    }
}