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;
    }
}


Tuesday, March 12, 2013

Back To Top on Webpage

1.html
<div id="scroll-to-top" style="display:none">Back to Top</div>

2. JS
<script language="javascript">
jQuery(function() {
    jQuery(window).scroll(function() {
        if(jQuery(this).scrollTop() != 0) {
            jQuery('#scroll-to-top').fadeIn();  
        } else {
            jQuery('#scroll-to-top').fadeOut();
        }
    });

    jQuery('#scroll-to-top').click(function() {
        jQuery('body,html').animate({scrollTop:0},800);
    });  
});
</script> 

3.CSS

#scroll-to-top {
display:none;
position:fixed;
width:50px;
height:50px;
bottom:30px;
right:30px;
z-index:9999;
text-indent:-9999px;
border-radius:50%;
background-color: #e5e5e5;
}
#scroll-to-top:hover {
background-position:-200px -150px;
background-color:#333;
}

Tuesday, March 5, 2013

How to add a "Tweet" button to a webpage?

1. HTML
<a href="javascript:poptastic('http://twitter.com/intent/tweet?text=<?php echo $message; ?>&url=<?php echo $url ?>');" title="Share With Twitter">Tweet</a>

2. JS
function poptastic(url) {
      var newWindow = window.open(url, 'name', 'height=600,width=450,top=100,left=500');
      if (window.focus) {
        newWindow.focus();
      }
     
 }

Monday, February 25, 2013

MAgento : Add custom action to Sales Order Grid

Here we use an event core_block_abstract_prepare_layout_before
1. Add following script in config.xml
<events>
<core_block_abstract_prepare_layout_before>
        <observers>
                <bdaction_block_abstract_prepare_layout_before>
                        <type>singleton</type>
                        <class>Bd_Test_Model_Observer</class>
                        <method>addMassCustomAction</method>
                </bdaction_block_abstract_prepare_layout_before>
        </observers>
</core_block_abstract_prepare_layout_before>
</events>
2.Create a observer class like Bd_Test_Model_Observer
then add a method
public static function addMassCustomAction($observer)
{
    $block = $observer->getEvent()->getBlock();
    if(get_class($block) =='Mage_Adminhtml_Block_Widget_Grid_Massaction'
        && $block->getRequest()->getControllerName() == 'sales_order')
    {
        $block->addItem('customaction', array(
        'label' => 'Custom Action',
        'url' => Mage::helper('adminhtml')->getUrl('module/controller/action'),
        ));
    }
}
3.At last create that controller and action method

Sunday, February 24, 2013

Magento : Session Storage


Typically, database servers are less utilised than web servers. Performance can usually be improved by moving session handling from the web server filesystem into the database server. Magento asks you whether you prefer a file or database session save type, but this is very easy to change in the XML. Open up /var/www/app/etc/local.xml, locate the <session_save> tags, and change the value so it looks like this (the default is <![CDATA[files]]>):

<session_save><![CDATA[db]]></session_save>
Another alternative is to use memcache for storing the sessions - this isn’t as persistent as the database store, but may be faster:

<session_save><![CDATA[memcache]]></session_save>
You can add details of your memcache server in the session save path:

<session_save_path><![CDATA[tcp://127.0.0.1:20?persistent=1&weight;=2&timeout;=10&retry;_interval=10]]></session_save_path>

Magento : Changing the Admin URL


We can improve security by changing the default URL from 'admin' to something more obscure, such as 'bdadmin'. This will decrease the probability that a malicious user will hit upon your admin log-in page by guessing that the admin site is located at domain.com/admin/, or that automated scripts scanning for Magento admin pages will find it.
To change the admin address you first need to stop Apache and clear the cache:
root# /etc/init.d/apache2 stop
root# rm -rf /var/www/var/cache/*
root# rm -rf /var/www/var/session/*
Then open up the /var/www/app/etc/local.xml file, locate the <frontName> tag, and change the 'admin' part it to something a lot more random,
eg:  <frontName><![CDATA[gJpf2VK5]]></frontName>
Then set Apache running again (bearing in mind your site will be down for the duration of this operation!):
root# /etc/init.d/apache2 start