Sunday 4 October 2015

Reset admin password

Dive in the code of password validation

Open app/code/core/Mage/Admin/Model/Session.php and find the function called 'login'. And the code below should be found in the function.
$user->login($username, $password);

Open app/code/core/Mage/Admin/Model/User.php and find the login function. The following code will be spotted.
if ($this->authenticate($username, $password)) {

Follow the 'authenticate' method and you will find the code
Mage::helper('core')->validateHash($password, $this->getPassword()

Open app/code/core/Mage/Core/Helper/Data.php and move to 'validateHash' method. There is only one sentence of code:
$this->getEncryptor()->validateHash($password, $hash);

Open app/code/core/Mage/Core/Model/Encryption.php which is literally the password validation method.

$hashArr should be an array comprised of two elements. The first element is the hashed password and the last element is the random hash key, and the hash method follows the equation below:
Hashed Password = md5(Actual Password + Hash Key)

The password value in the database is a string which consist of Hashed Password as the first part and Hash Key as the second part and these two parts are delimited by a colon symbol(:)

Update the password by sql query

select password from admin_user where user_id=1; #user_id 1 should be replaced by the user_id whose password needs to be updated

A result, which is similar as ceccc111cf1c3600a7ad5d464934ea24:HH6gy344GGuoZzDm3U6dKSoXPcpuqIsQ, will be found.

If you want to use 123 as your password, execute the following sql query in the database:
select md5('ceccc111cf1c3600a7ad5d464934ea24123');# the result is 6711eaa5577250a42aefdb9c04ad90ed

Use the sql query below to update the password:
update admin_user set password='6711eaa5577250a42aefdb9c04ad90ed:HH6gy344GGuoZzDm3U6dKSoXPcpuqIsQ' where user_id=1 limit 1;

Here we are and the new password can be used to log in the admin


Tuesday 7 July 2015

Magento website SEO skills/tips

Understand your audience with google trends

In google trends, any keywords can be put into the search box and google will display the search interests, related searches etc which can help you identify your audience, the potential search keywords the contents.

Use informative URLs

Magento has the functionality of generating the informative URLs by re-indexing the catalog_url index.
But it's only helpful for English categories and products. If your website is in other languages, you might need to specify the URL keys for categories and products, and the cms pages manually in admin pane or programmatically.

Add your site to major search engines

There are some common used search engines listed as below:
1. Google
2. Bing
3. Baidu
4. Sougou
Add your site to these search engines and submit the sitemap or URLs. The methods of adding your site vary from different engines. However, what you need to do is just to follow the instructions which shouldn't be difficult.

The method of checking whether you website has been indexed by search engines

For both google and baidu, you can just type 'site:yourdomaim' and the indexed pages will show up. Since in Magento the 404 pages are easy to occur if there is anything wrong with Magento index, you need to make sure the index system is correct and check and fix the 404 pages found in the search results.




Wednesday 1 July 2015

Magento Remove firstname and lastname for registration

Set the firstname and lastname fields in database not required

SELECT * FROM `eav_entity_type`;#find the customer entity_type_id
SELECT * FROM `eav_attribute` WHERE `attribute_code` IN ('lastname','firstname') and `entity_type_id`=1; #find firstname and lastname attributes;#find firstname and lastname attributes
UPDATE `eav_attribute` SET `is_required`=0  WHERE `attribute_code` IN ('lastname','firstname') and `entity_type_id`=1; #set is_required 0 which means it's not necessary

Copy and modify template file to remove the classes related to validation

Copy \app\design\frontend\base\default\template\customer\widget\name.phtml to your theme folder
Remove the following code for firstname and lastname field:
class='required'
<?php echo $this->helper('customer/address')->getAttributeValidationClass

Create a custom extension to override Mage_Customer_Model_Customer

Create a custom extension.
Add the following xml in config.xml
     <global>
        <models>
            <customer>
              <rewrite>
               <customer>Yourcompany_Yourmodule_Model_Customer</customer>
              </rewrite>
            </customer>
        </models>
     </global>
Copy the validate method from magento core to your module and remove the validation code of firstname and lastname

Hide firstname and lastname in registration form if needed

Add the following code in less file:
//hide first name and last name in registration form by bargainoverseas dev
.customer-account-create {
    .customer-name{
         display: none;
    }
}

Magento Add a link to top links or remove a link from top links

Add a link to top links via layout xml, for instance in the theme's local.xml

   <customer_logged_out>
        <reference name="top.links">
            <action method="addLink" translate="label title" module="customer"><label>Create an Account Imediately</label><url helper="customer/getRegisterUrl"/><title>Create an Account Imediately</title><prepare/><urlParams/><position>10</position></action>
        </reference>
        <remove name="reorder"></remove>
    </customer_logged_out>
note: this is for unsigned-in user, if you search addLink in the app/design folder, there will be more for specific pages. 

Remove a link from top links via layout xml

    <customer_logged_out>
        <reference name="top.links">
            <action method="removeLinkByUrl"><url helper="customer/getAccountUrl"/></action>
        </reference>
    </customer_logged_out>

Tuesday 30 June 2015

Override Magento varien product.js in an extension

Add layout updates in the module's etc/config.xml file

    <frontend>
        <layout>
          <updates>
            <yourcompany_yourmodule>
              <file>yourcompany_yourmodule.xml</file>
            </yourcompany_yourmodule>
          </updates>
        </layout>
    </frontend>

Create a layout xml file named yourcompany_yourmodule.xml,corresponding to the file name configured at the first step, in your current package and current theme folder, and add js in the layout file

<layout>
    <yourcompany_yourmodule_handle><!-- declare a custom handle so you won't duplicate the code -->
        <reference name="head">
            <action method="addJs">
                <script>yourcompany/yourmodule/product.js</script>
            </action>
            <action method="addJs">
                <script>yourcompany/yourmodule/configurable.js</script>
            </action>
        </reference>
    </yourcompany_yourmodule_handle>
    <PRODUCT_TYPE_configurable><!-- layout handle for simple products -->
        <update handle="yourcompany_yourmodule_handle" /> <!-- include the handle you declared above -->
    </PRODUCT_TYPE_configurable>
</layout>

Create js files in js folder. In my case, there are two files that needs to be created: product.js and configurable.js

If you want to override the reload method of Product.OptionsPrice, just put the following code in product.js
Product.OptionsPrice.prototype.reload
   = Product.OptionsPrice.prototype.reload.wrap(function(){
    {
         alert('override reload');
    }
});

If you want to override the getOptionLabel method of Product.Config, just do as the code below:
Product.Config.prototype.getOptionLabel
   = Product.Config.prototype.getOptionLabel.wrap(function(parent, option, price){
    {
         alert('override getOptionLabel');
    }
});

How to make a magento directory structure for publishing a extension with JS

In Magento, if you want to publish an extension after having developed it, it's quite complicated and boring to copy the files to a separate folder and zip it as the following, but it's a have-to-do thing.

Create the extension folder: 

mkdir ~/tmp/yourcompany_yourmodule

Copy the module's php code and configuration under app/code folder

mkdir ~/tmp/yourcompany_yourmodule/app/code/local/Yourcompany -p
cp -r app/code/local/Yourcompany/Yourmodule ~/tmp/yourcompany_yourmodule/app/code/local/Yourcompany/

Copy the module's layout files under app/design folder




mkdir ~/tmp/yourcompany_yourmodule/app/design/frontend/rwd/default/layout -p
cp app/design/frontend/rwd/default/layout/yourcompany_yourmodule.xml ~/tmp/yourcompany_yourmodule/app/design/frontend/rwd/default/layout/


Copy the main configuration under app/etc folder

mkdir ~/tmp/yourcompany_yourmodule/app/etc/modules -p
cp app/etc/modules/Yourcompany_Yourmodule.xml ~/tmp/yourcompany_yourmodule/app/etc/modules/

Copy the js files under js folder

mkdir ~/tmp/yourcompany_yourmodule/js/yourcompany -p
cp -r js/yourcompany ~/tmp/yourcompany_yourmodule/js/
note: the js files should be added in the layout xml files

Thursday 25 June 2015

Magento How to change/define a new layout for category pages(Eg. change from 3 columns to 2 columns)

Changing individual category page layout

This can be done via Magento admin pane.
Go to Catalog->Manage Categories and select the category whose layout you want to change.
Click Custom Design tab on the right.
Select a value for Page Layout from the options.
Save the change by clicking save category and the layout will take effect when you visit the page of this category.

Changing category page layout for all of the pages in your theme's layout/local.xml

Go to the theme folder under the package folder, and open layout/local.xml file or create this file if not exists.
Add the configuration xml below in the file.
<catalog_category_default>
        <reference name="root">
            <action method="setTemplate"><template>page/2columns-right.phtml</template></action>
        </reference>
</catalog_category_default>
Go to System->Configuration and click Design on the left menu.
On the right,choose Themes section and change the Layout input to the theme name you are using.

Changing the page layout for all the pages which include category pages

Open layout/page.xml which might located in /app/design/frontend/base/default/layout/page.xml or your own theme layout folder.
Find the xml configuration below in the xml default node:
<block type="page/html" name="root" output="toHtml" template="page/2columns-left.phtml">.
Here you can change the template to what you want.

Changing multiple category layouts in database which comes from changing individual category page layout in admin pane

Open the table named 'eav_entity_type', and find the entity_type_id where entity_type_code  equal 'catalog_product'. In my example, the entity_type_id is 3.
Open the table named 'eav_attribute' and search the records with the entity_type_id of 3 and find the record whose attribute code is 'page_layout'. And then keep the attribute_id. It is 61 in my database.
Open the table of 'catalog_category_entity_varchar', search by attribute_id of 61. The values of the category layouts will show up. You can change the values and insert new record for categories not in this table as well.

Wednesday 24 June 2015

Magento get product custom attribute value by attribute code

Wrong way to do it

In many Magento template files, $_product, which is an instance of Mage_Catalog_Model_Product, can be found and used to obtain the product details. In some places, we can get custom attribute value by $_product->getMyCustomAttribute(), but we will get NULL if $_production is in the loop of a product collection, which is not what we expected.

Right way to do it

If $_product is in the loop of a product collection, we would have to load the product manually and then get the attribute value as below:
Mage::getModel('catalog/product')->load($_product->getId())->getMyCustomAttribute()

If $_product is obtained by Mage::getModel('catalog/product')->load($_product->getId()), we can absolutely get the attribute value by $_product->getMyCustomAttribute()

Wednesday 17 June 2015

How to re-install magento

Why do I need to re-install magento

For some reason, when I download the Magento from a server and overrode my local magento, I couldn't log in magento. What I assumed is that the salt key were different or some other reasons. So I decided to re-install magento on my local.

It's very easy to re-install magento by following the steps below:

First, delete the app/etc/local.xml which contains all of the configurations made by installation.

Second, open http://yourdomain/install.php in the browser.

And then follow the installing steps of magento, but pay attention to the database name that needs to be input when installing. You need a new database which is different from the old magento database or you need to delete the old database if you want to use the same database name.

Potential Reasons for not being able to access admin

I'm using WAMP and magento seems not working well with WAMP directory alias and it only works well with vhost. 
Magento store the domain name in the database, after I transferred to vhost from directory alias, it kept redirecting me to localhost/mydomain even if I typed the vhost mydomain.loc.com.

Thursday 11 June 2015

How to set product display/sort order

First level of the configuration of product display order

Go to System->Configuration->Catalog and click frontend on the right panel. Set the Product Listing Sort By select to one of the options comprised of 'best value' which is the same as 'position', 'name' and 'price'.

Second level of the set up

Go to Catalog->Manage Categories and click Display Setting on the right pane. You can configure both Available Product Listing Sort By, which will affect the sort-by options from which the customer can choose on the front-end, and Default Product Listing Sort By, which will be the default option on the front-end page.

Set the Position value to manually tweak the product order

Go to Catalog->Manage Categories and click Category Products on the right pane. On the following page, you can change the position of any product that belongs to to the category.
To improve Magento performance, it's better to search the products that need to be sorted and then change and save the position values for them. Note: This is a very important tip for large data website.

Wednesday 10 June 2015

Add a responsive banner slider

As most of the websites are having a banner slider, it's a required web skill of adding a responsive slider. Here I will write down how to get a slider for Magento by using some slider extensions

First, I'm going to describe how to use Magento Responsive Banner Slider extension. 

Download the extension from the URL: http://www.magentocommerce.com/magento-connect/responsive-banner-slider.html
Install it from Magento Connect Manager if your Magento version is before 1.9. Otherwise, you need to manually download the module and copy the the files to your Magento folder. Cause there is an installation bug in this extension for Magento 1.9.
Go to System->Configuration->MKS Responsive Banner and click the general settings of the extension. Fill out the banner settings form which suits your website.
Go to Responsivebannerslider->Manage Responsivebannerslider. You will be led to a page where the images of the slider can be uploaded and set and you can add as many images as you want for the slider.
Put the below block code in the CMS pages  or any template files where you want to add the slider.
{{block type="responsivebannerslider/index" name="responsivebannerslider_index" template="responsivebannerslider/index.phtml"}}


Friday 5 June 2015

Solution of Magento Common Errors

CMS: Upload Image icon doesn't show up when clicking Insert a Image icon

Since uploading image needs the permission of Media Gallery, so we need to add this permission to the user which was used to manage CMS system in order for the user to have the ability to upload and insert images.

CMS: The directory is not writable by the server

The error might occur when trying to upload images in CMS. 
The reason is that CMS is trying to upload images to media/wysiwyg folder, but the folder was not created when Magento installed. Therefore, what we need to do is just to create the folder and make sure nginx/php user has the permission of it.

Magento Connect: 404 Not found

I got some answers from the internet which were all about the permission of downloader/index.php and some folders. You can clear cache using magento-clear-cache.php.
However, the cause of my issue is that the configuration of Ngninx. In my configuration I didn't rewrite dowloader/ to dowloader/index.php which might be a common mistake if nginx is used as PHP server, because .htaccess file which is doing the rewrite in Magento won't take effect under nginx.
To figure out whether this is the one causing your 404, you just need to put index.php manually after downloader URL to see whether it will work or not. If it works, then you have the same issue as mine.
To solve the issue, you just need to adjust the nginx configuration to make the rewrite also worked for downloader folder.


Thursday 4 June 2015

Two ways to set up the default store and defaute store view

The easiest and well known of setting the default store and the store views is setting them through Magento Admin Panel

Go into System->Manage Stores.
Click the website for which you want to set up the default store and you will get the setting page where the default store can be configured.
Click the store for which you want to set up the default store view and you can set it up on the page you get.

There is another way we have to know which may cause the first way ineffective without any obvious clues to solve the issue

In the index.php file, there are two lines related to the default store and store view as shown below:

/* Store or website code */
$mageRunCode = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : '';
/* Run store or run website */
$mageRunType = isset($_SERVER['MAGE_RUN_TYPE']) ? $_SERVER['MAGE_RUN_TYPE'] : 'store';

This means we can set up the variable MAGE_RUN_CODE and MAGE_RUN_TYPE in Apache/Nginx configuration files or PHP configuration file. Here is a sample configuration snippet in nginx configuration file:

fastcgi_param  MAGE_RUN_CODE default; ## Store code is defined in administration &gt; Configuration &gt; Manage Stores
fastcgi_param  MAGE_RUN_TYPE store;

Note: remember to check whether the configuration of the second way exists when you find that the default store/store view settings in Admin Panel don't work

Magento Re-index from shell which is super-useful for large data store

Reason of re-indexing from shell

Magento do provide the functionality of re-indexing in admin pane, but it might cause some timeout failure, which may brings a somewhat failure of re-indexing procedure, because of php execution limit and nginx/apache timeout. However, the shell script can avoid the timeout and execution limit, so it's better to re-index from shell for large data stores.

How to re-index from shell

Log on the website server and go into the Magento root directory.
Run the command of php shell/indexer.php help which will show the manual of using the script.

Here are some useful commands provided by the script

Get a list of indexers: php shell/indexer.php info
Get the status of current indexes: php shell/indexer.php --status
Re-index all: php shell/indexer.php reindexall #which is not recommended especially for large data website
Run one of the indexers: php shell/indexer.php --reindex indexer #indexer is coming from the list of indexers

Magento index modes

There are two Magento index modes. The first one is 'Update on save' which means the index will be rebuilt whenever the change related to the index has been made. While the other one is 'Manual Update' which makes the re-indexing executed only when the re-indexing command is ran manually or it's operated in the admin panel.
To conclude, it's highly recommended to set the mode to 'Manually update' for large data stores.

Set up Magento index modes

Set the mode to 'Update on save': php shell/indexer.php --mode-realtime indexer #indexer is from the index list
Set the mode to 'Manually save': php shell/indexer.php --mode-manual indexer #indexer is from the index list
After it's set to 'Manually save', the re-indexing command need to be added in the Linux cron table  to make rebuilding the index took place at a specific time which is supposed to be an idle time.
Note: the index mode should be set to 'Manually save' when doing any importation or it will be very slow for the importing process.

What if the re-indexing process is stuck for some reason

Restart nginx and php-fpm to stop the process. 
Go into the root directory of Magento and check the locks under the folder of var/locks/. And delete the locks if you want to stop the stuck process.
Go into Mysql and  check the table named index_process. And set the status from working to pending if you want to stop the stuck process.
Use indexer script to check the status of indexers to make sure there is no running indexers.
Run the indexer from shell instead of from the admin panel.

What are the statuses of indexers and their meanings

In Magento there are three statuses of indexers, which are quite confusing from the names,  comprising 'pending', 'working' and 'require reindex'.
'pending' means the index has been rebuilt and there is no need to re-index it.
'working' indicates the re-indexing process of the index is running.
'require reindex' shows the index is out of date and it needs to be rebuilt.


Tuesday 2 June 2015

Sample set-up in Magento admin panel for a real website

Change the copyright of the website

Go to System->Configuration, choose Design in the left panel and choose footer in the right panel. And then you can input your copyright in the input.

Change the logo of the website

Go to System->Configuration and choose Design in the left panel. From the right form,set the current package as your design package folder name in the Package part, set the templates as your template folder name and set the skin as your skin folder which is located under the package name in the Theme part, and set the logo file name in the Header part. 

Set HTML head under System->Configuration->Design

Change the website favicon icon by uploading a new image.
Set up Default Title,Description and Keywords which will be useful for search engine optimization.
Install a stat tool like google analytics by adding the javascript snippet in the Miscellaneous Scripts input which will be inserted just before the end of html head tag. 

Create Stores and Store Views and do the settings

Go into System->Manage Stores to create the store and associated store views.
Go into System->Configuration and click General on the left panel, and then change all the settings as you want. In terms of specific settings for store views, you just need to change the Current Configuration Scope to the store view that needs to be changed and configure the options for it.
Go into Catalog->Manage Categories to distribute categories to store views.
Go into System->Manage Stores again to set the default store on the website setting page and set the default store view on the store setting page.

After all of the settings, enable Magento caches to make the website faster

Go into System->Cache Management, and refresh and enable all of the caches.
Go into System->Index Management, and re-index all of the indexers.

Set up contact us form

Before setting up the contact form, we need to set up the store email addresses first. 
Go to System->Configuration->Store Email Addresses, and then set up all of emails.
Go to System->Configuration->Contacts, enable 'contact us' form and set up the receiving email and sending email.

Customize Magento Footer Links to meet your own requirements

Go to CMS->Static Blocks, and edit the 'Footer Links' block as you need. The default Magento Footer often including About Us, Customer Service and Privacy Policy and you can add, edit or remove some links to meet your requirements.

SEO Optimization in Html Meta Title, Meta Keywords, Meta Description

Go to System->Configuration->Design. In the section of HTML Head, set the default title,suffix title, default keywords and default description.
Go to System->Web.In the section of Search Engine Optimization, set the value of Use Web Server Rewrites to yes.
Note: Default title if only for pages without a title, so if the title of home page needs to be set, we have to go to CMS->Pages to modify the title of home page. However, we can set title prefix or title suffix to set the common title which should be helpful for SEO for all of the pages.

Add product watermark

Go to System->Configuration->Design and click Product Image Watermarks on the right panel. Since there are three types of product images, there are also three kinds of watermarks that need to be set here.



Monday 1 June 2015

Disable Magento Cache for Dev Purpose

Go into admin System->Cache Management

Disable all of the caches under this menu by selecting all the check boxes and choosing disable as the option.

After some changes in Magento, the index cache might need to be cleared

Go into System->Index Management to check whether there are indexes that need to be refreshed.

Magento Compilation is disabled by default, but it's better to check it in case something cached by it.

Go into System->Tools->Compilation, and disable it if it's enabled for some reason.

The changes of admin menu may probably not show up immediately after all the cache-related functionality has been disable

After disable all of the cache, there is an essential step to do which is log-out and re-log in Magento

Tuesday 5 May 2015

Custom Layout not loaded

The cause of this issue 

The handle name is always lower-cased by magento which led my failure of loading my layouts.

An efficient way to sort it out

Magento's front-end including handles, layouts, blocks and templates. Among all of them, handles are the only kind of things that will cause failing to load the layouts without any errors or notices. So print the handles in the controller and compare it with the handles defined in the layout XML file.

Here is what I did. First, use the below code to print the handles in the controller:
var_dump($this->getLayout()->getUpdate()->getHandles());

Then, copy the handle name called 'importjson' in my case and search it case-sensitively in the layout file. The result is that 'importjson' couldn't be found in the file that only contains the string of 'importJson'.

To conclude, in Magento we should always pay attention to case-sensitive which could cause numerous issues and cost us a lot time to figure it out.

Sunday 19 April 2015

Magento userful SQL queries

Get sorted attributes for products

SELECT *
FROM  `eav_attribute` ea
LEFT JOIN  `catalog_eav_attribute` cea ON ea.attribute_id = cea.attribute_id
WHERE ea.`entity_type_id` =4
AND cea.`used_for_sort_by` =1
LIMIT 0 , 30; #the value of entity_type_id might be different, but it can be found in the table named `eav_entity_type`
Note: `eav_attribute` is the table of basic product attributes' settings, while `catalog_eav_attribute` is containing additional or advanced settings for product attributes. Most of the product attributes' settings could be found in these two tables.

Set all simple products invisible by SQL Query

update catalog_product_entity_int set value =1 where attribute_id = 102 and  entity_id in (select entity_id from `catalog_product_entity` where `type_id`= 'simple')

Set the position value for all of the products by SQL Query

update `catalog_category_product` set position=2000 where position!=1000;

Tuesday 14 April 2015

How to re-install module database

Where in database does magento record the database set-up of the module?

All of the modules and their database set-up versions are recorded in the table named 'core_resource'.

The steps of re-installing a module

1. Disable the module in the app configuration file located in the folder of 'app/etc/modules/' by changing the value of 'active' from true to false.

2. Find the module set-up record in the database table of 'core_resource' and delete the record.

3. Refresh any page of magento site and the module will be newly installed.