Friday, August 28, 2015

Make base url relative in magento

app/code/local/Maglife/Core/etc/config.xml

<?xml version="1.0"?>
<config>
    <global>
        <models>
            <core>
                <rewrite>
                    <store>Maglife_Core_Model_Store</store>
                </rewrite>
            </core>
        </models>
    </global>
</config>
 
app/code/local/Maglife/Core/Model/Store.php 
<?php

class Maglife_Core_Model_Store extends Mage_Core_Model_Store
{

    protected function _processConfigValue($fullPath, $path, $node)
    {
        if (isset($this->_configCache[$path])) {
            return $this->_configCache[$path];
        }

        if ($node->hasChildren()) {
            $aValue = array();
            foreach ($node->children() as $k => $v) {
                $aValue[$k] = $this->_processConfigValue($fullPath . '/' . $k, $path . '/' . $k, $v);
            }
            $this->_configCache[$path] = $aValue;
            return $aValue;
        }

        $sValue = (string) $node;
        if (!empty($node['backend_model']) && !empty($sValue)) {
            $backend = Mage::getModel((string) $node['backend_model']);
            $backend->setPath($path)->setValue($sValue)->afterLoad();
            $sValue = $backend->getValue();
        }

        if (is_string($sValue) && strpos($sValue, '{{') !== false) {
            if (strpos($sValue, '{{unsecure_base_url}}') !== false) {
                $unsecureBaseUrl = $this->getConfig(self::XML_PATH_UNSECURE_BASE_URL);
                $sValue = str_replace('{{unsecure_base_url}}', $unsecureBaseUrl, $sValue);
            } elseif (strpos($sValue, '{{secure_base_url}}') !== false) {
                $secureBaseUrl = $this->getConfig(self::XML_PATH_SECURE_BASE_URL);
                $sValue = str_replace('{{secure_base_url}}', $secureBaseUrl, $sValue);
            } elseif (strpos($sValue, '{{base_url}}') !== false) {
                $sValue = Mage::getConfig()->substDistroServerVars($sValue);
            }
        }
        if(in_array($path,array('web/unsecure/base_url','web/secure/base_url','{{unsecure_base_url}}','{{secure_base_url}}'))){
       
        $sValue = $_SERVER[HTTP_REFERER].str_replace($_SERVER[HTTP_REFERER],'',$sValue);
 
        }
        $this->_configCache[$path] = $sValue;

        return $sValue;
    }

}

?>
 

Friday, May 8, 2015

How to create your custom API in Magento

Creating Custom API is very easy in Magento.
Just create api.xml file in your etc folder

<?xml version="1.0"?>
<config>
    <api>
        <resources>          
            <!-- START GUSTOMER GROUP RESOURCES -->
          <mycustom_productupload translate="title" module="package_module">
                <model>package_module/productupload_api</model>
                <title> My API</title>
                <acl>custom_data</acl>
                <methods>
                    <list translate="title" module="package_module">
                        <title>custom product upload</title>
                        <method>bulkuploadproduct</method>
                    </list>
                </methods>
            </mycustom_productupload>
            <!-- END CUSTOMER GROUP RESOURCES -->
        </resources>
         
       
       
        <acl>
            <resources>
                <custom_data translate="title" module="package_module">
                    <title>Custom data</title>
                    <sort_order>3</sort_order>
                </custom_data>
            </resources>
        </acl>
    </api>
</config>

Now create a folder under model Productupload because you have define it under the model tag
and create a file api.php under Productupload. (Productupload /api.php)

api.php

class Package_Module_Model_Productupload_Api extends Mage_Customer_Model_Group_Api
{
   
    public function bulkuploadproduct($productListArr){
       your code....
    }

}


this bulkuploadproduct is the function which will automatically call when when you call the api.
Please find the following example to call this API.

$client = new SoapClient(SOAP_WSDL);
$session = $client->login(SOAP_USER, SOAP_PASS);
$client->call($session, 'mycustom_productupload.list',array($productList));

Create a magento admin module & put link to magento menu with user role (ACL resources)

If you know how to create Magento module then create it first. After then you need to create a Magento controller for admin area.

class Package_Module_MycustomController extends Mage_Adminhtml_Controller_Action
{
    public function indexAction()
    {
         your code here.......
    }
}

Now if you want to create top menu in your magento admin, which can be enable or disable from admin role management area (ACL resources).

config.xml
<adminhtml>
   
        <menu>
            <package_module translate="title" module="package_module">
                <title>Manage Portal</title>
                <sort_order>9999</sort_order>
                <action>mycustom/userauth/index</action>               
            </package_module>
        </menu>
        <acl>
        <resources>
            <admin>
                <children>
                    <package_module translate="title" module="package_module">
                        <title>Manage Portal</title>
                        <sort_order>9999</sort_order>
                        <action>mycustom/userauth/index</action>   
                    </package_module>
                </children>
            </admin>
        </resources>
    </acl>
   
    </adminhtml>
 

Wednesday, April 29, 2015

Magento Maximum Allowed Order QTY

ake a look @ Magento Maximum Allowed Order Amount, you would have to create a custom module to add this feature.
Create an observer for sales_quote_save_before

<config>
    <frontend>
        <events>
            <sales_quote_save_before>
                <observers>
                    <mymodule_custom>
                        <class>Mymodule_Custom_Model_Observer</class>
                        <method>LimitOrderqty</method>
                    </mymodule_custom>
                </observers>
            </sales_quote_save_before>
        </events>
    </frontend>
</config>
 
In your observer
 
<?php  
class Mymodule_Custom_Model_Observer {
 
public function LimitOrderqty(Varien_Event_Observer $observer){ 
   $cart = Mage::getModel('checkout/cart')->getQuote();
   $customer = Mage::getSingleton('customer/session')->getCustomer();
   $allowQTY = $customer->getLastsaleqty() + (int)($customer->getLastsaleqty()*$customer->getGreaseqty()/100);
  if ($cart->getItemsQty() > $allowQTY) {
            Mage::getSingleton('checkout/session')->addError('You are not allow to add that QTY in your cart. Your Approved QTY limit '.$allowQTY);
   
   Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl('checkout/cart'));
            Mage::app()->getResponse()->sendResponse();
            exit;
        }
 }
   
} 

Tuesday, April 28, 2015

How to create user concurrency in Magento

I had a requirement where my client was looking on user login concurrency. By default Magento don't have this feature. So i have created a module which will handle user concurrency. Please follow the code to do it.


Go to the following site and create your module in a quick way.
http://www.silksoftware.com/magento-module-creator/#.UvHRXfuMA3h

Now Create the following table
CREATE TABLE IF NOT EXISTS 'customer_login_tracking' (
  'email' varchar(100) NOT NULL,
  'session_id' varchar(200) NOT NULL,
  'login_time' int(11) NOT NULL,
  UNIQUE KEY 'customer_id' ('email')
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now add the following code in your etc/config.xml (where my module name space is Mymodule and module is Custom)
  <frontend>     
         <routers>
          <custom>
            <use>standard</use>
              <args>
                <module>Mymodule_Custom</module>
                <frontName>newpassword</frontName>
              </args>             
          </custom>
          <customer>
            <args>
                <modules>
                    <Mymodule_Custom before="Mage_Customer_AccountController">Mymodule_Custom</Mymodule_Custom>
                </modules>
            </args>
          </customer>
        </routers>
 </frontend>

 Now i have created 2 controllers
Custom\controllers\AccountController.php

<?php

require_once(Mage::getModuleDir('controllers','Mage_Customer').DS.'AccountController.php');

class Mymodule_Custom_AccountController extends Mage_Customer_AccountController
{
   

    /**
     * Login post action
     */
    public function loginPostAction()
    {
       
        if (!$this->_validateFormKey()) {
            $this->_redirect('*/*/');
            return;
        }

        if ($this->_getSession()->isLoggedIn()) {
            $this->_redirect('*/*/');
            return;
        }
        $session = $this->_getSession();

        if ($this->getRequest()->isPost()) {
            $login = $this->getRequest()->getPost('login');
            if (!empty($login['username']) && !empty($login['password'])) {
                try {
                       $resource = Mage::getSingleton('core/resource');
                       $readConnection = $resource->getConnection('core_read');
                       $writeConnection = $resource->getConnection('core_write');
                                             
                       $tableName2 = $resource->getTableName('customer_login_tracking');
                      
                       $login_check = $readConnection->fetchRow('SELECT * FROM ' . $tableName2.' WHERE email="'.$login['username'].'"');
                      
                       if(isset($login_check['session_id'])){
                           $value = Mage::getUrl('custom/index/Clearcustomersession/us/'.base64_encode($login['username']));
                           $message = $this->_getHelper('customer')->__('You are already login from other place. <a href="%s">Click here</a> to clear the session.', $value);
                           Mage::getSingleton('core/session')->addError($message);
                       }else{
                          if($session->login($login['username'], $login['password'])){
                              $query = 'INSERT INTO '.$tableName2.' SET email="'.$login['username'].'", session_id="'.$session->getEncryptedSessionId().'", login_time="'.time().'"';
                              $writeConnection->query($query); 
                          }
                          if ($session->getCustomer()->getIsJustConfirmed()) {                               
                                $this->_welcomeCustomer($session->getCustomer(), true);                                                                       
                          }
                       }
                   
                } catch (Mage_Core_Exception $e) {
                    switch ($e->getCode()) {
                        case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
                            $value = $this->_getHelper('customer')->getEmailConfirmationUrl($login['username']);
                            $message = $this->_getHelper('customer')->__('This account is not confirmed. <a href="%s">Click here</a> to resend confirmation email.', $value);
                            break;
                        case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
                            $message = $e->getMessage();
                            break;
                        default:
                            $message = $e->getMessage();
                    }
                    $session->addError($message);
                    $session->setUsername($login['username']);
                } catch (Exception $e) {
                    // Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
                }
            } else {
                $session->addError($this->__('Login and password are required.'));
            }
        }

        $this->_loginPostRedirect();
    }
   
     /**
     * Customer logout action
     */
    public function logoutAction()
    {
        $resource = Mage::getSingleton('core/resource');
        $tableName2 = $resource->getTableName('customer_login_tracking');
        $readConnection = $resource->getConnection('core_read');   
        $readConnection->query('DELETE FROM '.$tableName2.' WHERE email="'.$this->_getSession()->getCustomer()->getEmail().'"');
       
        $this->_getSession()->logout()
            ->renewSession();

        $this->_redirect('*/*/logoutSuccess');
    }

  
}


Custom\controllers\IndexController.php

<?php
class Mymodule_Custom_IndexController extends Mage_Core_Controller_Front_Action{
public function ClearcustomersessionAction(){       
         $email = base64_decode($this->getRequest()->getParam('us'));
         $resource = Mage::getSingleton('core/resource');
         $readConnection = $resource->getConnection('core_read');
         $tableName = $resource->getTableName('customer_login_tracking');       
         $result = $readConnection->fetchRow('SELECT * FROM ' . $tableName.' WHERE email="'.$email.'"');
         unlink(Mage::getBaseDir('session').'\sess_'.$result['session_id']);
         $readConnection->query('DELETE FROM '.$tableName.' WHERE email="'.$email.'"');
         Mage::getSingleton('core/session')->addSuccess('Your previous session has been remove. Please login again.');
         Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl('customer/account'));
     }
}

  

Sunday, April 12, 2015

Magento redirect to login page while user not login on landing

$redirect_url = Mage::getUrl('customer/account/login/');
$current_url = Mage::helper('core/url')->getCurrentUrl();
if((!$this->helper('customer')->isLoggedIn()) && ($current_url != $redirect_url)){
    Mage::app()->getFrontController()->getResponse()->setRedirect($redirect_url);
}

Friday, April 10, 2015

How to create new attributes for customer

Hello Friend,
I have found some small and Quick solution for creating attribute for customer.
Login your Admin and follow the stapes.
Catalog -> Attribute -> Manage Attributes
Now create an attribute. It might be text box or drop down
Now open your phpmyadmin & find out eav_attribute table Now find out your attribute with your attribute_code and change entity_type_id with 1. Because 1 stand for customer attribute.
Now from any controller just run the following code


$oAttribute = Mage::getSingleton('eav/config')->getAttribute('customer', 'your attribute code');
$oAttribute->setData('used_in_forms', array('customer_account_edit','customer_account_create','adminhtml_customer','checkout_register'));
$oAttribute->save();