Wednesday 16 July 2014

Delete Unwanted files in Magento

Delete Unwanted files in Magento


switch($_GET['clean']) {
    case 'log':
        clean_log_tables();
    break;
    case 'var':
        clean_var_directory();
    break;
}

function clean_log_tables() {
    $xml = simplexml_load_file('./app/etc/local.xml', NULL, LIBXML_NOCDATA);
   
    if(is_object($xml)) {
        $db['host'] = $xml->global->resources->default_setup->connection->host;
        $db['name'] = $xml->global->resources->default_setup->connection->dbname;
        $db['user'] = $xml->global->resources->default_setup->connection->username;
        $db['pass'] = $xml->global->resources->default_setup->connection->password;
        $db['pref'] = $xml->global->resources->db->table_prefix;
       
        $tables = array(
            'aw_core_logger',
            'dataflow_batch_export',
            'dataflow_batch_import',
            'log_customer',
            'log_quote',
            'log_summary',
            'log_summary_type',
            'log_url',
            'log_url_info',
            'log_visitor',
            'log_visitor_info',
            'log_visitor_online',
            'index_event',
            'report_event',
            'report_viewed_product_index',
            'report_compared_product_index',
            'catalog_compare_item',
            'catalogindex_aggregation',
            'catalogindex_aggregation_tag',
            'catalogindex_aggregation_to_tag'
        );
       
        mysql_connect($db['host'], $db['user'], $db['pass']) or die(mysql_error());
        mysql_select_db($db['name']) or die(mysql_error());
       
        foreach($tables as $table) {
            @mysql_query('TRUNCATE `'.$db['pref'].$table.'`');
        }
    } else {
        exit('Unable to load local.xml file');
    }
}

function clean_var_directory() {
    $dirs = array(
        'downloader/.cache/',
        'downloader/pearlib/cache/*',
        'downloader/pearlib/download/*',
        'media/css/',
        'media/css_secure/',
        'media/import/',
        'media/js/',
        'var/cache/',
        'var/locks/',
        'var/log/',
        'var/report/',
        'var/session/',
        'var/tmp/'
    );
   
    foreach($dirs as $dir) {
        exec('rm -rf '.$dir);
    }
}

Wednesday 28 May 2014

Creating a Magento custom model

In this tutorial, we will create a custom model that uses a different name than the Module name. The Module tree will look like as shown in below:

-Pixafy/
    -Block/
    -controllers/
    -Model/
        -Resource/
            -Custommodel/
                -Collection.php
            -Custommodel.php
        -Custommodel.php
    -etc/
        -config.xml
    -sql/

In config.xml, we will set up our custom Model configuration. There are three things that we need to setup for a Model in the config.xml.
1. Enable Models in our Module.
2. Enable Model resources in our Module.
3. Add an entity table to our Model Resource.

<models>
    <pixafy>
        <class>[Frontname]_Pixafy_Model</class>
        <resourceModel>pixafy_resource</resourceModel>
    </pixafy>
</models>


The <pixafy/> tag is our Group name and should match our module name. The <class/> tag is the Base name or Class prefix, that tells all models in the pixafy group where to look for the actual model objects. [Frontname]_Pixafy_Model is equivalent to Frontname/Pixafy/Model which is the path all our models. The <resourceModel/> tag indicates which Resource Model that Pixafy group Model should use. We will have to create the <pixafy_resource/> configure the resource object that is in Pixafy/Model/Resource/Custommodel.php.

<models>
    <pixafy>
        <class>[Frontname]_Pixafy_Model</class>
                        <resourceModel>pixafy_resource</resourceModel>
    </pixafy>

     <pixafy_resource>
        <class>[Frontname]_Pixafy_Model_Resource</class>
        <entities>
            <custommodel>
                            <table>[table_name_in_database]</table>
                        </ custommodel >
        </entities>
    </pixafy_resource>
</models>



The resource model <pixafy_recource/> contains the configuration that communicates with our database. Again, we specified where the resource is located in <class/> tag. The <entities/> section tells Customemodel.php in the resource which table in the Database to connect to.
Now we have finished with Config.xml. We then have to create the Model class and Resource class. Pixafy/Model/Custommodel.php will contain the following code:


class Frontname_Pixafy_Model_Custommodel extends Mage_Core_Model_Abstract
{
    protected function _construct()
    {
        $this->_init('pixafy/custommodel');
    }
}


All basic Models that interact with the database should extend the Mage_Core_Model_Abstract class. This abstract class forces you to implement a single method named _construct (NOTE: this is not PHP’s constructor__construct). This method should call the class’s _init method with the same identifying URI you’ll be using in the Mage::getModel method call.
Pixafy/Model/Resource/Custommodel.php will contain the following code:

class Frontname_Pixafy_Model_Resource_Custommodel extends Mage_Core_Model_Resource_Db_Abstract{
    protected function _construct()
    {
        $this->_init('pixafy/custommodel', 'custommodel_id');
    }
}


Again, the first parameter of the init method is the URL used to identify the Model. The second parameter is the database field that uniquely identifies any particular column. In most cases, this should be the primary key.
So, having a single Model is useful, but sometimes we want to grab a list of Models. Rather than returning a simple array of Models, each Magento Model type has a unique collection object associated with it. These objects implement the PHP IteratorAggregate and Countable interfaces, which means they can be passed to the countfunction, and used in for each constructs. Let’s create the Collection class.
Pixafy/Model/Resource/Custommodel/Collection.php should contain the following code:

class Frontname_Pixafy_Model_Resource_Custommodel_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract {
    protected function _construct()
    {
            $this->_init('pixafy/custommodel');
    }
}

 And that’s it; our model is ready to be used. Let’s test our model by calling model:

$model = Mage::getModel('pixafy/custommodel');
 
 
To query a collection, we will call:
 
$collections = Mage::getModel('pixafy/custommodel')->getCollection();
 
After clear cache all are working
 
 
 
 
Thanks to : http://www.pixafy.com/blog/2013/04/creating-a-magento-custom-model/







 

Monday 14 April 2014

Solve “This account is locked.” problem in Magento


If your user has been locked out from the backend, you can reset the lock with one simple query:
UPDATE `admin_user` SET `failures_num` = 0, `first_failure` = NULL, `lock_expires` = NULL WHERE `user_id` = 1;

You can find your user_id with this query:

SELECT `user_id` FROM `admin_user` WHERE `username` = 'admin'

Tuesday 8 April 2014

Using PHP CURL XML Request and get XML Response

<?php
$xml = '<ProductProvisionRequest>
    <requisitionID>4183</requisitionID>
    <orderExternalReferenceID>200000353</orderExternalReferenceID>
    <submissionDate>1395393241</submissionDate>
    <shopperPassword></shopperPassword>
    <shopperInfo>
        <userKey>
            <userID>test@nonesbservice-pro-21-3-2015-2.com</userID>
            <externalReferenceID></externalReferenceID>
            <companyID>Rosetta Stone</companyID>
            <loginID>test@snonesbservice-pro-21-3-2015-2.com</loginID>
            <siteID>rstUS</siteID>
        </userKey>
    </shopperInfo>
    <orderExtendedAttributes>
        <item>
            <name></name>
            <value></value>
            <datatype></datatype>
        </item>
    </orderExtendedAttributes>
    <lineItemLevelRequest>
       
    </lineItemLevelRequest>
</ProductProvisionRequest>';
$ch = curl_init();
$url = 'www.abc.com';
curl_setopt($ch, CURLOPT_URL, $url); //set to url to post to
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // tell curl to return data in a variable
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml","header-tocken"));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); // post the xml
//curl_setopt($ch, CURLOPT_TIMEOUT, (int)3000000); // set timeout in seconds
$xmlResponse = curl_exec($ch);
echo "<pre>";
print_r($xmlResponse);
curl_close($ch); 
?>

Tuesday 25 March 2014

PHP XML Creation

Create one .xml named as ofi.xml

<Productxxxxxxxxxxx>
    <ID></ID>
    <orderExternalReferenceID/>
    <submissionDate></submissionDate>
    <shopperPassword/>   
    <shopperInfo>
       
    </shopperInfo>
    <orderExtendedAttributes>
       
    </orderExtendedAttributes>
    <lineItemLevelRequest>
   
    </lineItemLevelRequest>
   
</Productxxxxxxxxxxx>


Then create php file abc.php

<?php

error_reporting(E_ALL);
$user_key_array = array('userID' => 'sdfsdfsdfs', 'externalReferenceID' => 'JD(234234', 'companyID' => 'TESTID',
    'loginID' => 'RSUSER', 'siteID' => 'rs.com');

$item_Value = array('item' => array('name' => '', 'value' => '', 'datatype' => ''));
$order_item_values = array('name' => '', 'value' => '', 'datatype' => '');

$shippingAddress = array('addressID' => '111', 'city' => '111', 'countryA2' => '111', 'country' => 'US', 'countryName' => 'United States', 'line1' => '1', 'line2' => 2, 'line3' => 3,
    'locationCode' => '454', 'name1' => '', 'name2' => '', 'phoneNumber' => '', 'postalCode' => '', 'state' => '', 'email' => '', 'faxPhone' => '',
    'companyName' => '', 'phoneNumber2' => '', 'countyName' => '', 'extendedAttributes' => $item_Value);

$billingAddress = array('addressID' => '111', 'city' => '111', 'countryA2' => '111', 'country' => 'US', 'countryName' => 'United States', 'line1' => '1', 'line2' => 2, 'line3' => 3,
    'locationCode' => '454', 'name1' => '', 'name2' => 'sdfsdf', 'phoneNumber' => 'sdfsdf', 'postalCode' => 'sdfsdf', 'state' => '', 'email' => '', 'faxPhone' => 'sdfasdfas',
    'companyName' => '', 'phoneNumber2' => 'sdfsdf', 'countyName' => 'sdfsdf', 'extendedAttributes' => $item_Value);


$productKey = array('productID' => 2222, 'externalReferenceID' => 32324234, 'companyID' => 'RER343', 'locale' => 'en');

$productInfo = array('productDataID' => 23423, 'mfrPartNumber' => '', 'shipperPartNumber' => 'sdfsd',
    'sku' => 23423, 'name' => '', 'platform' => '', 'year' => '', 'seats' => '', 'companyID' => '', 'exportCountry' => '', 'manufactureCountry' => '',
    'harmonizeCode' => '', 'eccn' => '', 'licenseException' => '', 'ccats' => '', 'extendedAttributes' => $item_Value);

$common_lineItem = array('currencyCode' => '','amount' => '');

$lineItemLevelPricing = array('unitPrice' => $common_lineItem, 'listPrice' => $common_lineItem, 'distributorPrice' => $common_lineItem, 'pricePerQty' => $common_lineItem, 'tax' => $common_lineItem, 'productTax' => $common_lineItem, 'shippingTax' => $common_lineItem,
    'shipping' => $common_lineItem, 'handling' => $common_lineItem, 'incentive' => $common_lineItem, 'reqLevelIncentivePerQuantity' => $common_lineItem, 'lineItemLevelIncentivePerQuantity' => $common_lineItem,
    'taxableFees' => $common_lineItem, 'taxOnTaxableFees' => $common_lineItem, 'nonTaxableFees' => $common_lineItem, 'recurringFee' => $common_lineItem, 'shippingBeforeDiscount' => $common_lineItem);

$lineItem = array('lineItemID' => '', 'lineItemExternalReferenceID' => '',
    'quantity' => '', 'preOrder' => '', 'preOrderReleaseDate' => '', 'RSITInfoArray' => '',
    'replacementInfo' => '', 'productKey' => $productKey, 'productInfo' => $productInfo, 'lineItemLevelPricing' => $lineItemLevelPricing,
    'lineItemExtendedAttributes' => $item_Value);


$master_array = array(
    array('shopperInfo' => array(
            array('userKey' => $user_key_array, 'firstName' => 'John', 'lastName' => 'Wiliam',
                'email' => 'john@rs.com', 'locale' => 'en', 'homePhone' => '343-34343-34343',
                'faxPhone' => '343-34343-34343', 'shippingAddress' => $shippingAddress,
                'billingAddress' => $billingAddress)
        )
    ),
    array('orderExtendedAttributes' => array(
            array('item' => $order_item_values)
        )
    ),
    array('lineItemLevelRequest' => array(
            array('lineItemID' => 'dfsdf', 'lineItemExternalReferenceID' => '', 'quantity' => '', 'preOrder' => '', 'preOrderReleaseDate' => '', 'RSITInfoArray' => '',
                'replacementInfo' => '', 'productKey' => $productKey, 'productInfo' => $productInfo, 'lineItemLevelPricing' => $lineItemLevelPricing,
                'lineItemExtendedAttributes' => $item_Value)
        )
    )
);

$tmmFile = 'ofi.xml';
$_xmlDoc = new DOMDocument('1.0', 'UTF-8');
$_xmlDoc->load($tmmFile);

function createCustomXml($xmlDoc, $master_array) {
     foreach ($master_array as $value_array) {
          foreach ($value_array as $key => $values) {
               $parent = $xmlDoc;
               $parentElement = $parent->getElementsByTagName($key)->item(0);
                   if(!is_array($values)) {
         $parentElement->nodeValue = $values;
          } else {
         foreach ($values as $value) {
          foreach ($value as $key => $value1) {
           recursiveElementCreation($key, $value1, $xmlDoc, $parentElement);
          }
         }
        }
          }
     }
}

function recursiveElementCreation($key, $value, $xmlDoc, $parentElement) {
     if (!is_array($value)) {
          $parentElement->appendChild($xmlDoc->createElement($key, $value));
     } else {
          $parentForChild = $parentElement->appendChild($xmlDoc->createElement($key));
          foreach ($value as $key1 => $value1) {
               recursiveElementCreation($key1, $value1, $xmlDoc, $parentForChild);
          }
     }
}

createCustomXml($_xmlDoc, $master_array);
$_xmlDoc->formatOutput = true;

print_r($_xmlDoc->saveXML());
exit;

Wednesday 29 January 2014

Dispatch Event Creation in magento



You can create an event with the Mage::dispatchEvent method. If you have an object like the order then you have to define a parameterlist as Array. array( 'order' => $order)
Just implement following line to your extension class:
Mage::dispatchEvent('the_event_name',array( 'order' => $order));


To observe an event, specify the observer in the config.xml at /app/(codepool)/Extensionname/ .
<config>
  <global>
    <events>
      <the_event_name>
        <observers>
          <extensionname>
            <type>singleton</type>
            <class>Extensionname_Model_Observer</class>
            <method>methodName</method>
          </extensionname>
        </observers>
      </the_event_name>
    </events>
  </global>
</config>

Create an Extension and a model (Observer.php): /app/(codepool)/Extensionname/Model/Observer.php

class Extensionname_Model_Observer
{
    public function methodName($event)
    {
        $order = $event->getOrder();
        //for example send a new order mail to customer
        $order->sendNewOrderEmail()->setEmailSent(true)->
        save();
        //do something else ....
    }
}

Magento useful functions



General functions

Function Description
$this->getRequest()->getServer(‘HTTP_REFERER’);              Get the referer URL

 

Product related functions

Function Description
$product->getName() Get product name.
$product->getSku() Get product sku
Mage::getModel(‘cataloginventory/stock_item’)->loadByProduct($_product)->getQty() Get product stock
$product->getResource()->getAttribute(‘color’)->getFrontend()->getValue($product) Get a product attribute value (like color/size)
$product->isSaleable() checks if a product is salable
$product->isisAvailable() checks if a product type is salable
Mage::getModel(‘catalogrule/rule’)->calcProductPriceRule($product,$product->getPrice()) Gets the product final price after all catalog rules have been applied
$product->getTierPrice(1) Gets the product tier price if can be applied to the customer

Newsletter related functions

Function                    Description
$subscriber = Mage::getModel(‘newsletter/subscriber’);
$subscriber->subscribe($user_mail);
                          Add mail to subscribers list

 

Cache

Function Description
$tags = array(Mage_Catalog_Model_Category::CACHE_TAG); //Category block tag
Mage::app()->cleanCache($tags)
Clean specific cache tag (in this case the category list block)

Product images

Function Description
$_product->getMediaGalleryImages()->getItemByColumnValue(‘label’, ‘LABEL_NAME’)->getUrl() Get the url of a specific produc image given its label

Customer related functions

Function Description
$this->helper(‘customer’)->isLoggedIn() Checks if the customer is logged

Tuesday 28 January 2014

Displaying Currency Symbol after Price in Magento


 Change Price Symbol after Price

There is a one Trick for changing position of Currency Symbol from LEFT to RIGHT in Magento.

For that you have to do Minor changes in your Language File. Following is the Directory Structure of File.

=> root/lib/Zend/Locale/Data/en.xml (For English Language)

=> around line 2611 you can see following code.
<currencyFormat>
<pattern>¤#,##0.00;(¤#,##0.00)</pattern>
</currencyFormat>

=> Now Change above code with Following code.

  <currencyFormat>
<pattern>#,##0.00 ¤;(#,##0.00 ¤)</pattern>
</currencyFormat>

Note: The little square ( ¤ ) sets the currency symbol position after Price in magento.

=> Now clear Cache of your store and You can see changes.