Thursday, October 10, 2013

Mageno : How to programmatically get product attribute label !!

Hello friends,

Today we are going to explain you how you can get the product attribute label value using PHP code
[php]
//get load the full product using product model.
$product = Mage::getModel('catalog/product')->load(1o);
$productAttribute = $product->getResource()->getAttribute('description');
echo $productAttribute->getStoreLabel('admin');
[/php]


Hope this could help someone.

Happy Coding!!

Tuesday, September 24, 2013

Ask Google for your flights, reservations, package delivery info, and more!

http://productforums.google.com/forum/#!category-topic/websearch/how-do-iusing-google-search/8b2OyQJIyCg

Sunday, September 15, 2013

Magento how to get all parent categories

Hi.. Guys today i have learned something very interesting, which is HOW TO GET (ONLY) PARENT CATEGORIES from the category tree.

[php]
$categories = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('*')//or you can just add some attributes
->addAttributeToFilter('level', 2)//2 is actually the first level
->addAttributeToFilter('is_active', 1);//if you want only active categories
foreach ($categories as $_category){
echo $_category->getName().'<>';
}
[/php]

Hope it helps someone!!

Happy coding :-)

Saturday, September 7, 2013

PHP : Get redirect URL using cURL

Trick for retrieving the redirect URL using PHP cURL :
Ever got irritated when you trying loading a URL with PHP cURL function and its actually redirecting you to a new url and you programmatically want to find the actual URL or redirected URL so here is the function you are looking for:

[php]
function getActualURL($url){
$ch = curl_init();
$timeout = 0;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
// Getting binary data
$header = curl_exec($ch);
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach( $fields as $field ) {
if( preg_match('/([^:]+): (.+)/m', $field, $match) ) {
$match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
if( isset($retVal[$match[1]]) ) {
$retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
} else {
$retVal[$match[1]] = trim($match[2]);
}
}
}
//here is the header info parsed out
echo '<pre>';
print_r($retVal);
echo '</pre>';
//here is the redirect
if (isset($retVal['Location'])){
echo $retVal['Location'];
} else {
//keep in mind that if it is a direct link to the image the location header will be missing
echo $_GET[$urlKey];
}
curl_close($ch);
}
[/php]

Hope someone will find this helpfull,
Happy coding :-)

Thursday, September 5, 2013

PHP : Very Usefull Special Character Definitions

Collection of PHP Regular expression keywords which you often get lost from your mind:

When we come to use regular expression for performing pretty task on string or validations this is common situation that we all forget or often confused with keywords to use thats why i just found this will be helpful to post it here :

Special Character Definitions
[php]
\ Quote the next metacharacter
^ Match the beginning of the line
. Match any character (except newline)
$ Match the end of the line (or before newline at the end)
| Alternation
() Grouping
[] Character class
* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times
More Special Character Stuff
\t tab (HT, TAB)
\n newline (LF, NL)
\r return (CR)
\f form feed (FF)
\a alarm (bell) (BEL)
\e escape (think troff) (ESC)
\033 octal char (think of a PDP-11)
\x1B hex char
\c[ control char
\l lowercase next char (think vi)
\u uppercase next char (think vi)
\L lowercase till \E (think vi)
\U uppercase till \E (think vi)
\E end case modification (think vi)
\Q quote (disable) pattern metacharacters till \E
Even More Special Characters
\w Match a "word" character (alphanumeric plus "_")
\W Match a non-word character
\s Match a whitespace character
\S Match a non-whitespace character
\d Match a digit character
\D Match a non-digit character
\b Match a word boundary
\B Match a non-(word boundary)
\A Match only at beginning of string
\Z Match only at end of string, or before newline at the end
\z Match only at end of string
\G Match only where previous m//g left off (works only with /g)
[/php]

For more read through this link : Regexp Introduction

Wednesday, August 21, 2013

WAMP Openssl issue ordinal 294 could not open

Openssl
Hello guys,
I recently and randomly got tasked my self for configuring my WAMP with openSSL but in just few commands i throw i got a prompt saying that "Ordinal 296 could not be located in the dynamic link library SSLEAY32.dll" and from there i started my searching over the google for fix this and in this post i am sharing the simple solution for this problem :


1) Download the suitable version of OpenSSL for your system from here OpenSSL for windows
2) Install it and copy these three files :
a) ssleay32.dll b)libeay32.dll c)openssl.exe from OpenSSL-Win32/bin
3) Paste these files to C:\wamp\bin\apache\Apache2.2.21\bin
4) Retry your settings commands for Openssl settings in command prompt.

This solved my problem and i hope this should going to solve your problem too.
**Note : Please change the path appropriately.

Friday, August 2, 2013

How to make request with twitter 1.1 API

If you have ever got to tasked for working with twitter API here is an start up tutorial for you with twitter latest 1.1 API interface, Here i will show you how you can get user timeline using the Twitter API so tight your seat belt and get set for interesting 5 minutes journey :

1) Login to your twitter API.
2) Open this URL : Register a Twitter APP
3) Fill all the required fields

  • Name : Your Unique Application Name (Do not use twitter word in it.)

  • Description: Your application description

  • Website: Your application's publicly accessible home page, where users can go to download, make use of, or find out more information about your application.

  • Callback URL(Optional) : This should be fully qualified domain name or IP where the API will return after successful authentication.


4) The next page will land toApplication Success Page
5) Click on setting tab on this page : SettingsTab
6) Check the application type to Read and Write
Read write
and hit update button.
7) Now click on third tab which is OAuth Tool for getting necessary platform access via API,copy the

  • Consumer key:

  • Consumer secret:

  • Access token: (You need to choose)

  • Access token secret: (You need to choose)

  • Request type: select it to GET


8) Now its time to get your hands dirty with coding, Are you ready ?
9) Download the latest TwitterAPIExchange.php This uses oAuth and the Twitter v1.1 API.

[php]
require_once('TwitterAPIExchange.php');

$url = 'https://api.twitter.com/1.1/followers/list.json';
$getfield = '?username=ravisoni6262&skip_status=1';
$requestMethod = 'GET';

$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
[/php]


The echo will successfully return you the some json response for your timeline.
For more you can read at API documentation

Hope it helps some one :-)

Tuesday, July 30, 2013

Interspire or Big-Commerce how to bypass admin login

Hello friends today i am sharing with you an interesting hack for Interspire Shopping Cart or BigCommerce admin login hack which i got to tasked some time ago :

Note : In this hack you must have at-least valid user name this hack only bypass wrong password

Follow below instructions :
1) login to FTP
2) Navigate to admin/includes/classes
3) Locate the class class.auth.php
4) And around line number 235 you will find the this code
[php]if ($autoLogin || $userManager->verifyPassword($uid, $loginPass) == true) [/php]

Replace this with this one do not forget to save the original code

[php] if (1) [/php]

And try login with valid username and any password.

Hope this could help someone :-)

Saturday, July 27, 2013

Magento : Basic debugging steps

Enable PHP Errors


This is key to most issues. For security or other reasons, PHP error display could likely be disabled by default by your PHP configuration.

You can enable errors with a more permanent solution, or merely something more temporary.

Permanent solution



For Apache/mod_php users


In your document root's .htaccess file - just drop this at the top.

[html]
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_value error_log /home/path/public_html/var/log/system.log
[/html]

For Nginx/FastCGI users


In your Nginx virtualhost configuration, in either the final location .php { directive, or in the fastcgi_params file (if you have one specified)

[html]
fastcgi_param PHP_VALUE display_startup_errors=on;
fastcgi_param PHP_VALUE display_errors=on;
fastcgi_param PHP_VALUE html_errors=on;
fastcgi_param PHP_VALUE log_errors=on;
fastcgi_param PHP_VALUE error_log=/home/path/public_html/var/log/system.log;
[/html]

Temporary/Universal solution



For any platform



Edit the Magento bootstrap index.php in your document root and uncomment the following line:

[html]#ini_set('display_errors', 1);[/html]

Enable Developer Mode


When you've had an error and suddenly hit the "Error Report" page, and been given a seemingly useless error string like 1184257287824 - you've got a few options.

Permanent solution



For Apache/mod_php users



In your document root .htaccess file - just drop this at the top.
[html]SetEnv MAGE_IS_DEVELOPER_MODE true[/html]

For Nginx/fastcgi users


In your Nginx virtualhost configuration, in either the final location .php { directive, or in the fastcgi_params file (if you have one specified)

[html]fastcgi_param MAGE_IS_DEVELOPER_MODE true;[/html]

Temporary/Universal solution



Edit the Magento bootstrap index.php in your document root and either make the if statement always true, or enabled for your specific IP.
[html]
if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE']) || true) {
Mage::setIsDeveloperMode(true);
}
[/html]
or
[html]
if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE']) || $_SERVER['REMOTE_ADDR'] == 'my.ip.add.ress') {
Mage::setIsDeveloperMode(true);
}
[/html]

Check your permissions


Incorrect permissions will cause a wealth of problems, a lot of which are not that easy to find at first glance.

[html]
For example.
If PHP cannot write to the ./media directory and you have JS combine enabled - Magento is unable to generate the combined file and associated unique URI for the media. So instead, what you'll find in your browser source code is a full server path to the media file /home/path/public_html/media/xxx
[/html]

Otherwise, the site can appear to be functioning as normal - with no critical errors actually visible.

Please bear in mind, this practice is secure for dedicated hosting but may present security issues with shared hosting if the Apache process isn’t chroot’ed per user.

In our example, the SSH/FTP user is magegurus, the Apache user is apache and the group is apache

Add the FTP/SSH user to the Apache group


Most importantly, we need to make sure that the FTP/SSH user is part of the Apache group, in our example, its apache(but is also commonly www-data)

[html]usermod -a -G apache magegurus[/html]
Keep adding as many users to the group as you have for FTP/SSH.

Reset original permissions



So before we start, lets make sure all the permissions are correct.
[html]chown -R magegurus:apache /home/path/public_html/
find /home/path/public_html/ -type d -exec chmod 775 {} \;
find /home/path/public_html/ -type f -exec chmod 664 {} \;[/html]

Making the changes permanent



ACLs and Sticky Bits




ACLs in Linux allow us to define specific rules, in our case, what permissions files should inherit upon creation. A

sticky bit

(mentioned later) takes care of group inheritance, but does not help with the permissions, which is why we use ACLs.

Start by enabling ACL support on the active partition,

please ensure your Kernel was compiled with ACL support.



Your partition may be /, /home, /var or something else, replace as appropriate.

[html]mount -o remount,acl /home[/html]

Now ACLs are enabled, we can set the ACL rules and group sticky bits:

[html]setfacl -d -m u::rwx,g::rwx,o::rx /home/path/public_html/
chmod g+s /home/path/public_html/[/html]

But I don’t have ACL support


If your Kernel doesn’t support ACLs you can also use umask (which is a run time setting for BASH, FTP and PHP) to set the default file permissions. Magento usually sets umask(0) in index.php, however, it would be in your interests to change this.


In your index.php change the umask line to be
[html]umask(022);[/html]

And in your BASH environment for SSH, set this in either your .bashrc or .bash_profile

[html]umask 022[/html]

For your FTP server, you’ll need to read the documentation for it, but the principle is the same.



Revert theme to default


Its possible that either your theme or package is responsible for this issue. Reverting back to a vanilla Magento theme is a quick way to find out.

*This comes with the caveat that some modules may be dependent on certain theme features

Rather than change anything via the admin panel, it is much simpler to merely rename the offending directories.

Via SSH



[html]mv ./app/design/frontend/myBrokenTheme{,.tmp}
mv ./skin/frontend/myBrokenTheme{,.tmp}[/html]

Or via your FTP client, traverse and rename your package to something else. eg. myBrokenTheme.tmp

If this resolves your issue



Then you need to dig a bit deeper as to what part of the template is problematic. So restore your package and attempt the following, testing between each.

Essentially, the process is to gradually enable directories as you traverse down the file tree - until you can find the offending file.

Rename the layout directory to .tmp
Rename the template directory to .tmp
Then if either yields a fix, rename all files within the layout directory to .tmp - (for the SSH users ls | xargs -I {} mv {} {}.tmp or rename 's/^/.tmp/' *)

Then gradually enable each file 1 by 1 until resolved.

If this doesn't resolve your issue



There is potential that your base/default or enterprise/default directories have become contaminated - and are best replaced with a known clean version.

You can do this by downloading a clean build of Magento and replacing your directories as necessary. Via SSH you can do this:

[html]cd /home/path/public_html/
mkdir clean_mage
cd clean_mage
MAGENTO_VERSION=1.7.0.0
wget -O magento.tgz http://www.magentocommerce.com/downloads/assets/$MAGENTO_VERSION/magento-$MAGENTO_VERSION.tar.gz
tar xvfz magento.tgz
cd /home/path/public_html/app/design/frontend
mv base{,.tmp}
cp -par /home/path/public_html/clean_mage/magento/app/design/frontend/base .
cd /home/path/public_html/skin/frontend
mv base{,.tmp}
cp -par /home/path/public_html/clean_mage/magento/skin/frontend/base .[/html]

You can also take the opportunity to diff the two directories if you want to verify any changes.

[html]diff -r base base.tmp[/html]

NB. This method will cause more errors during the process, as module dependency dictates the existence of specific files. Unfortunately, its par for the course.




Disable local modules


By default, Magento defines the PHP include path to load classes in the following order

[html]Local > Community > Core[/html]

[html]If a file is in Local - load it and do no more.
If a file is in community - load it and do no more.
If a file can't be found anywhere else - load it from the core.[/html]

Again, rather than disable modules via the Magento admin panel, it is more practical to do this at a file level.

Typically, to disable a module the "proper" way, you would edit the respective ./app/etc/modules/MyModule.xml file and set false - however, this doesn't actually prevent a class from loading.

If another class extends a given class in a module (ignoring any Magento dependency declarations), it will still be loaded - regardless of whether the extension is disabled or not.

So again, the best means to disable an extension is to rename the directory.

Begin by disabling local



Just rename the directory via FTP, or use the following SSH command

[html]mv ./app/code/local{,.tmp}[/html]

Then disable community

[html]mv ./app/code/community{,.tmp}[/html]

If the issue is resolved from either



Then it is a case of understanding which module in particular the error stemmed from. As with the example given above for the package diagnosis, the same process applies.

So restore the X directory and attempt the following, testing between each.

Essentially, the process is to gradually enable directories (modules) one-by-one until the error re-occurs

1) Rename all the modules in the directory to .tmp (for the SSH users ls | xargs -I {} mv {} {}.tmp or rename 's/^/.tmp/' *)
2) Gradually enable each module one-by-one, by removing .tmp from the file name

If the issue is not resolved



Then it is possible the core itself is contaminated. The main Magento PHP core consists of

[html]./app/code/core./lib[/html]

So again, rename these directories and copy in a clean variant. Assuming you already downloaded a clean version of Magento as above, via SSH, you can do this:


[html]cd /home/path/public_html/app/code
mv core{,.tmp}
cp -par /home/path/public_html/clean_mage/magento/app/code/core .[/html]

Then if the issue still isn't resolved, replace the lib directory too

[html]cd /home/path/public_html
mv lib{,.tmp}
cp -par /home/path/public_html/clean_mage/magento/lib .[/html]

At this point, your Magento store will be nothing more than a vanilla installation with a modified database.

Some models are actually still stored in the database (Eg. order increment) - so at this point, it becomes a case of manually making those edits. So far, all the steps above have been reversible with no lasting damage. But if we were in import a clean Magento database too - it could prove irreversible (short of restoring a backup).

The guide above serves to get you on your way to identifying an error; not to fixing the resultant error.

Hope it helps some one :-)

Monday, July 15, 2013

Magento : How to add custom options programmatically

Here guys i am here with another interesting post on magento for creating product custom options programmatically.

[php]
$option = array(
'title' => 'Your custom option title',
'type' => 'radio', // could be drop_down ,checkbox , multiple
'is_require' => 1,
'sort_order' => 0,
'values' => getOptions()
);

function getOptions(){
return array(
array(
'title' => 'Option Value 1',
'price' =>100,
'price_type' => 'fixed',
'sku' => 'any sku for 1',
'sort_order' => '1'
),
array(
'title' => 'Option Value 2',
'price' =>100,
'price_type' => 'fixed',
'sku' => 'any sku for 2',
'sort_order' => '1'
),
array(
'title' => 'Option Value 3',
'price' =>100,
'price_type' => 'fixed',
'sku' => 'any sku for 3',
'sort_order' => '1'
)
);
}

//Suppose we are creating a new product.
$product = Mage::getModel('catalog/product');
$product->setProductOptions(array($option));
$product->setCanSaveCustomOptions(true);

//Or if we are adding the options to a already created product.
$product = Mage::getModel('catalog/product')->load($id);
$product->setProductOptions(array($option));
$product->setCanSaveCustomOptions(true);

//Do not forget to save the product
$product->save();
[/php]

Hope it helps some one :-)

Saturday, July 13, 2013

Magento : Get Product info from Order

Hi guys,
Today i am going to share with you a interesting bit of code that will help you finding the product order info from the order created in the admin.

For version 1.7 :

[php]
$orders = Mage::getResourceModel('sales/order_collection')
->addAttributeToSelect('*')
->addFieldToFilter('status', array("in" => array(
'complete', // If you want to get all orders just remove these filters.
'closed')
))
->addAttributeToFilter('store_id', Mage::app()->getStore()->getId())
->addAttributeToSort('created_at', 'asc')
->load();

foreach($orders as $order){
$items = $order->getAllVisibleItems();
foreach($items as $item){
$orderId = $order->getIncrementId();
$productid = $item->getSku();
$QtyOrdered = $item->getQtyOrdered();
$Price = $item->getPrice();
$Name = $item->getName();

}
}

[/php]

PHP : How to get external site cookies using php curl functions

If you work with PHP aggressively you may be came to think some time how you can get the cookies from the external site i.e. cookies from google.com or from your favorite site here is bit of code i want to share with you for this.
[php]
// open a site
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.com");
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0');
curl_setopt($ch, CURLOPT_HEADER ,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$content = curl_exec($ch);

// get cookies
$cookies = array();
preg_match_all('/Set-Cookie:(?<cookie>\s{0,}.*)$/im', $content, $cookies);

print_r($cookies['cookie']);

[/php]


Hope it helps someone. :-)

Monday, July 1, 2013

Magento : Remove prices from drop -down custom options

Hi.. guys here is a simple javascript code for removing prices from the custom options drop down text.

[js]
<script type="text/javascript">
//<![CDATA[
var $j = jQuery.noConflict();
$j(document).ready(function(e) {
$j("select.product-custom-option option:first-child").html("Select");

checkoptions();

$j("select.product-custom-option").change(function(){
checkoptions();
});
});

function checkoptions(){
$j("select.product-custom-option option").each(function(){
var optiontext = jQuery(this).text();
var addsignpos = optiontext.indexOf('+');
var subtractsignpos = optiontext.indexOf('-');
if(addsignpos>0){
var result = optiontext.substring(0,addsignpos-1);
$j(this).html(result);
}

if(subtractsignpos>0){
var result = optiontext.substring(0,subtractsignpos-1);
$j(this).html(result);
}
});
}
//]]>
</script>
[/js]


Hope it helps some one. enjoy :-)

Saturday, June 8, 2013

Magento : How to check if the store is running on secure url

Hi... guys today i am sharing with you a little useful code for checking is the current store is running on secure url or not .

You can check this by just this simple line of code :
[php]$isSecure = Mage::app()->getStore()->isCurrentlySecure();[/php]

And you can get the secure url using the following code :
[php]Mage::getStoreConfig(Mage_Core_Model_Store::XML_PATH_SECURE_BASE_URL)[/php]

Wednesday, June 5, 2013

Magento : Solution of the 'Cache_dir' must be directory

Today i am sharing with you the solution for most common issue with magento store which is the Exception : cache_dir must be a directory.

To solve this problem follow these steps :

1) Open the php file at the path lib/Zend/Cache/Backend/File.php

2) Go to around line : 91
[php]
protected $_options = array(
'cache_dir' => 'temp/',
'file_locking' => true,
'read_control' => true,
'read_control_type' => 'crc32',
'hashed_directory_level' => 0,
'hashed_directory_umask' => 0700,
'file_name_prefix' => 'zend_cache',
'cache_file_umask' => 0600,
'metadatas_array_max_size' => 100
);
[/php]

3) Replace the above code with this one :

[php]
protected $_options = array(
'cache_dir' => 'path/from/root/var/cache/',
'file_locking' => true,
'read_control' => true,
'read_control_type' => 'crc32',
'hashed_directory_level' => 0,
'hashed_directory_umask' => 0700,
'file_name_prefix' => 'zend_cache',
'cache_file_umask' => 0600,
'metadatas_array_max_size' => 100
);
[/php]

This would definately solve your problem, Hope this will help some one
Happy coding :-)

Wednesday, May 29, 2013

Magento : Adding a Yes/No type custom category attribute

Hello, Here is the another magento code snippet that i have got to share with you.

[php]
<?php
require_once("app/Mage.php");
Mage::app('default');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$entityTypeId = $installer->getEntityTypeId('catalog_category');
$attributeSetId = $installer->getDefaultAttributeSetId($entityTypeId);
$attributeGroupId = $installer->getDefaultAttributeGroupId($entityTypeId, $attributeSetId);

$installer->addAttribute('catalog_category', 'left_nav', array(
'group' => 'General Information',
'type' => 'int',
'label' => 'Show in left navigation',
'input' => 'select',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'visible' => true,
'required' => false,
'user_defined' => false,
'default' => 0,
'source' => 'eav/entity_attribute_source_boolean'
));
?>
[/php]

After running this script and refreshing the admin end you will find the added attribute at end of General Information tab.

Hope this helps some one
Thanks.

Magento : How to remove any attribute from category programatically

Here is the simple code for deleting any category attribute using the simple lines of code.
[php]

require_once("app/Mage.php");
Mage::app('default');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$entityTypeId = $setup->getEntityTypeId('catalog_category');

$setup->removeAttribute($entityTypeId,'display_mode');

[/php]

This could be usefull if you added some custom attribute and want to remove them back.

Happy coding :-)

Monday, May 13, 2013

Magento : Get products from category order by product ID

Here is the very simple code for getting products from a particular category and order them using product ID in decending order.

[php]
error_reporting(1);
ini_set('display_errors','1');
require_once('app/Mage.php');
Mage::app('default');


$products = Mage::getModel('catalog/category')->load(3345) //3345 : Category ID
->getProductCollection()
->addAttributeToSelect('*')->setOrder('entity_id','DESC'); //Order the collection in decending order.

foreach ($products as $p) {
echo $p->getSku().'<br/>';

}

[/php]

Hope it helps some one.

Happy coding.

Thursday, April 18, 2013

Magento : Too many database connections problem

Has an magento store which is getting busy into his business day by day and start throwing some performance related errors like this this one.
Yes this is Too many database connections problem when your store start getting attention of your visitors this could be obvious problem because you don't have took any developer care about the future of you store, so here is some tips about getting up and running your store smoothly.

This error comes when you try to connect to your mysql server and all available connections are in use by some other visitors.the number of connections is controlled by max_connections system variable this is set to 151 by default for MYSQL 5.5 and you can increase its values by following this simple steps :

1) Open your mysql configuration file located at /etc/my.cnf

2) Locate this variable max_connections

3) Set your desire number of available connection number for avoiding future error
max_connections = 250

4) Restart you mysql server and this will surely off your headache.


Thanks
If you found this post helpful and enjoyable please comment and share. :-)

Wednesday, April 17, 2013

Solution for just host hosting error : an error occurred while processing this directive

Phew!! one day i was working with justhost joomla installation and after making the site live i have seen following error on the site .
[an error occurred while processing this directive]

So here is i am sharing the solution for this issue : Basically this file permission issue which could be solve by just changing all folders permission to 755 and files permission to 644.

Screen for changing all files permissions to 644 :

Apply to all files and folder screen

Tuesday, April 16, 2013

Magento : Importing large databases using mysql CLI on localhost

In one of my project i need to set up my client project on local computer with a very large database aroun ~1.6 GB in size and this gave me headache of importing via phpmyadmin GUI, so here is a quick way of importing large databases using Command promt, just follow the given steps :

1) Open the CMD(DOS) and open your mysql folder from wamp folder on my pc this is
C:\> cd C:\wamp\bin\mysql\mysql5.5.0\bin

2) After this write this command for firing up the mysql
C:\> cd C:\wamp\bin\mysql\mysql5.5.0\bin>mysql.exe -use youdbname -u username -p password

this line will connect with your given database

3) I prefered to copy the sql under the same folder where mysql.exe resides, and then run this

mysql> source yourlargesql.sql;


This will surely import your large sql file.

Thanks and happy coding.

Monday, April 15, 2013

Magento : Solution for The PDO extension is required for this adapter but the extension is not loaded

Add this lines to your php.ini placed at the root of you installation

extension=pdo.so
extension=pdo_mysql.so
extension=php_pdo_mysql.dll


This should solve your problem
Thanks

How to prevent spam without using captcha

Using captcha's on your website form to prevent spam there a plenty of reasons of not using CAPTCHA'S

  • It creates a barrier to users by with giving a frustrating images or text

  • Need extra effort to work upon, because they are annoying and disturb your visitor attention

  • CAPTCHAs Can Consume A Lot Of Hosting Resources : CAPTCHAs requires additional CPU memory as they generate random text based images which may slow down a shared server.

  • CAPTCHAs Can Be Broken : CAPTCHAs can be bypassed and broken, attackers can have outsourced human workers who can easily deCAPTCHA your security. Another, much more rare way that CAPTCHAs can be broken, is through computer algorithms that are capable of cracking even the most sophisticated CAPTCHA systems.


Here is some examples of simple methods to prevent spam without using captcha :

1) Using css :
We can declare some additional fields and hide them using css and upon form submission check those fields on server side if some robot script try to fill out the fields they will also populate those hidden fields.

Example :
Your HTML would be
[html]
<label>Leave this blank: <input class="hidethis" type="text" name="leaveblank" /></label>

<label>Do not change this: <input class="hidethis" type="text" name="dontchange" value="http://" /></label>
[/html]
Your css
[css]
.hidethis{ display:none; }
[/css]

Your server side php
[php]
if ($_POST['leaveblank'] != '' or $_POST['dontchange'] != 'http://') {
// display message that the form submission was rejected
}
else {
// accept form submission
}
[/php]

2) Use php to change input field names periodically : We can use the date() function to change field names, use the daily date parameter.

[php]
$date = date('d');
$html = "<input type='text' name='abc$date'>\n";

if ( !isset($_POST["abc$date"] ) {
// do not accept the request
}
[/php]

Tuesday, April 9, 2013

Magento : Updating a customer password from phpmyadmin

Here is simple password reset trick for those who don't know their customer password or some developer trying to access some customer account in magneto so here we go,

1) You should have the customer Id from the magento admin or from some where else for query with tables

2) Open phpmyadmin and load the table <b>customer_entity_varchar</b>
Magento get customer id from admin

3) In the customer_entity_varchar seacrh for customer id

Magento query the table

4) Edit the row which has attribute_id 12, this row contains the MD5 password hash

5) Enter your password which you will generate from Magento Password Hash
Generate Magento Password Hash

6) Save the row and that's it try login with new password this should work.

Happy coding :-)

Magento : Solution for bogus URL is not showing Not found page

Here is quick admin setting for those who are battling with a problem that when you enter a bogus or unidentified URL for your site the 404 not found page is not coming up,

Just login to your admin panel and follow these steps

'System -> Configuration -> Web -> Default Pages -> CMS No Route Page'

Here is quick screen shot :

Magento : Setting not found page

 

 

Friday, March 29, 2013

Magento : Usefull Region/ID array

Here is a big array of all USA states and their magento Id.

[php]
$rionnarr = array("Alabama"=>1,"Alaska"=>2,"American Samoa"=>3,"Arizona"=>4,"Arkansas"=>5,"Armed Forces Africa"=>6,"Armed Forces Americas"=>7,"Armed Forces Canada"=>8,"Armed Forces Europe"=>9,"Armed Forces Middle East"=>10,"Armed Forces Pacific"=>11,"California"=>12,"Colorado"=>13,"Connecticut"=>14,"Delaware"=>15,"District of Columbia"=>16,"Federated States Of Micronesia"=>17,"Florida"=>18,"Georgia"=>19,"Guam"=>20,"Hawaii"=>21,"Idaho"=>22,"Illinois"=>23,"Indiana"=>24,"Iowa"=>25,"Kansas"=>26,"Kentucky"=>27,"Louisiana"=>28,"Maine"=>29,"Marshall Islands"=>30,"Maryland"=>31,"Massachusetts"=>32,"Michigan"=>33,"Minnesota"=>34,"Mississippi"=>35,"Missouri"=>36,"Montana"=>37,"Nebraska"=>38,"Nevada"=>39,"New Hampshire"=>40,"New Jersey"=>41,"New Mexico"=>42,"New York"=>43,"North Carolina"=>44,"North Dakota"=>45,"Northern Mariana Islands"=>46,"Ohio"=>47,"Oklahoma"=>48,"Oregon"=>49,"Palau"=>50,"Pennsylvania"=>51,"Puerto Rico"=>52,"Rhode Island"=>53,"South Carolin"=>54,"South Dakota"=>55,"Tennessee"=>56,"Texas"=>57,"Utah"=>58,"Vermont"=>59,"Virgin Islands"=>60,"Virginia"=>61,"Washington"=>62,"West Virginia"=>63,"Wisconsin"=>64,"Wyoming"=>65);
[/php]

 

Wednesday, March 27, 2013

Magento: Difference between Mage::getSingleton() and Mage::getModel()

You may be in thinking sometime what is the difference between magento getSingleton and getModel method so here is a explanation of the difference

The Mage::getModel('module/model') create a instance of model object each time method is got called this approach is resource consuming require separate memory for each object instance.

[php] Mage::getModel('catalog/product'), it will create new instance of the object product each time. [/php]

[php]
e.g.
$obj1 = Mage::getModel('catalog/product');
$obj2 = Mage::getModel('catalog/product');
Then $obj1 is a one instance of product and $obj is another instance of product.
[/php]

While Mage::getSingleton('catalog/product') will create reference of an existing object if any reference is not exists then this method will create an instance using Mage::getModel() and returns reference to it.
So, if
$obj1 = Mage::getSingleton('catalog/product');
$obj2 = Mage::getSingleton('catalog/product');

Then $obj1 and $obj2 both refer to the same instance of product.

Magento : Solution for SQL Integrity constraint violation

I was working on client project with a special requirement which says product prices should update daily but after some time i have started getting this error in magento admin while trying to add new products
[php]
QLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`irciycom_magento/weee_discount`, CONSTRAINT `FK_CATALOG_PRODUCT_ENTITY_WEEE_DISCOUNT_PRODUCT_ENTITY` FOREIGN KEY (`entity_id`) REFERENCES `catalog_product_entity` (`entity_id`) ON DELETE CASC).
[/php]

The solution to problem is open the file Url.php located at app/code/core/Mage/Catalog/Model/Resource and edit the function public function getProductModel() located at around line 113
[php]
public function getProductModel()
{
return Mage::getSingleton('catalog/product');
}
[/php]
to
[php]
public function getProductModel()
{
return Mage::getModel('catalog/product');
}
[/php]

And that's it, solved the error gone.

Alternatively if you don't want to edit the core files just follow this steps
1. Create these folders under the app/code/local , Mage/Catalog/Model/Resource
2. Copy the file Url.php from core to Resource folder and do the changes to Url.php and save it
3. You are done won battle with magento.

You could be in thinking what does getSingleton and getModel do. so you need to read this post.
Enjoy :-)

Saturday, March 23, 2013

Magento : Godady hosting installation error "No input file specified".

I was working on a project and i need to work on godady hosting after uploading all the magento files to godady folder i have access the site for installation but got this message No input file specified. which i have't heard before, it was completely new for me so i tried finding it on google and found some useful links here i am sharing my experience that helped me.

1. Edit the .htaccess file and add this
[php]
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^.+.php$ /bogusfile
[/php]
Access your site if this still doesn't work try out the second solution

2. If your have magento on root add this to your .htaccess
[php]RewriteBase /[/php]
Or have it other folder add this
[php]RewriteBase /youfolder/[/php]

3. Try accessing your site if still no luck with this try renaming the php.ini file to php5.ini , you will find this under your root directory.

4. If all the three steps did't worked try adding this line to your php5.ini you don't find your php.ini or php5.ini you can create and add this line
[php]cgi.fix_pathinfo = 1[/php]

5. And if you are getting the error try add the below line to very top your magento .htaccess
[php]Options -MultiViews[/php]

Keep your changes wait for about 30 min to 1 hrs

The above tricks worked for me but you if it did't worked for you then its your bad luck with hosting and you should contact the support immediately .

Thanks.

Wednesday, March 20, 2013

Magento : Error while adding a shopping cart price rule

While developing a project i have ran into a weird situation and this sucks me for complete two days, the problem was when i got to admin click shopping cart price rules under promotions and add new rule Or edit the previously created rule an error comes and the reports was saying ....

[php]
Wrong tab configuration
Mage_Adminhtml_Block_Widget_Tabs->addTab('coupons_section', 'promo_quote_edi...')
[/php]


and found this solution to the problem ,
1) create a file Coupons.php at this path
[php]app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab[/php]

2) Put all the code given below in Coupons.php
[php]
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to hide@address.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Adminhtml
* @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/

/**
* "Manage Coupons Codes" Tab
*
* @category Mage
* @package Mage_Adminhtml
* @author Magento Core Team <hide@address.com>
*/
class Mage_Adminhtml_Block_Promo_Quote_Edit_Tab_Coupons
extends Mage_Adminhtml_Block_Text_List
implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
/**
* Prepare content for tab
*
* @return string
*/
public function getTabLabel()
{
return Mage::helper('salesrule')->__('Manage Coupons Codes');
}

/**
* Prepare title for tab
*
* @return string
*/
public function getTabTitle()
{
return Mage::helper('salesrule')->__('Manage Coupons Codes');
}

/**
* Returns status flag about this tab can be shown or not
*
* @return bool
*/
public function canShowTab()
{
return $this->_isEditing();
}

/**
* Returns status flag about this tab hidden or not
*
* @return bool
*/
public function isHidden()
{
return !$this->_isEditing();
}

/**
* Check whether we edit existing rule or adding new one
*
* @return bool
*/
protected function _isEditing()
{
$priceRule = Mage::registry('current_promo_quote_rule');
return !is_null($priceRule->getRuleId());
}
}
[/php]
3) And refresh

This solved my error i was on magento version 1.6.2
Happy coding :-)

Sunday, March 17, 2013

10 Best WordPress Themes For Free Download

ascetica





Demo
| Download
A very elegant and any responsive wordpress theme best for creating online portfolio.

Key Features :
Genre : Portfolio
Responsive : Yes
Localization : Yes
Custom Elements : Custom page templates
USP : Hybrid Core framework




buttercream



Demo | Download
Looking for a cool,funky and casual theme for your wordpress this theme is designed for you.

Key Features :
1. Suitable for both blog or website.
2. Supports all post formats
3. Optional responsive design for smaller screens (perfect for iPhone, iPad and other mobile devices)
4. Custom backgrounds, a custom pop-up menu and three widget-ready sidebars in the footer.




launcher



Demo | Download
Key Features :
1. Responsive.
2. Subscription Box.
3. Countdown Timer.
4. Twitter Integration.
5. Rocket Launching Effect.
6. Social Media Integration.
7. Options Panel.




prospect free wordpress theme


Demo | Download
Bursting with bold, vibrant colors and clean styling, Prospect is the perfect choice for any business site. It's sure to make a lasting impression on your visitors, turning them into return customers over time.

Key Features :
1. DRAG & DROP FORMS.
2. CUSTOM LOGO UPLOAD.
3. SOCIAL MEDIA.
4. BEAUTIFUL DESIGN.
5. Extensive Admin Panel.
6. Home Content Boxes.
7. Custom Portfolio Templates.





workality wordpress free theme


Demo | Download
Free WordPress Theme for Creative People

Key Features :
1. Custom Post Types.
2. 4 Portfolio Layouts.
3. Responsive Design.
4. Localization Support.
5. Archive + 404 Pages.
6. Browser Support.
7. SEO & Valid HTML.




veecard free wordpress theme



Demo | Download
Simple and responsive theme, suitable as a vCard website.

Key Features :
1. Multiple Color Styles.
2. Responsive Design.
3. HTML5 and CSS3.
4. Always Up to Date.
5. Detailed Documentation.
6. Localization Ready.




photo free wordpress



Demo | Download
Photo Free Responsive Gallery WordPress Theme

Key Features :
1. Featured homepage slider using “Soliloquy“.
2. Built-in theme options panel using Options Framework Plugin.
3. Responsive design.
4. Social options.
5. Google fonts added properly via wp_enqueue_script();.
6. Symple Shortcodes Plugin support – added responsive styles.
7. Free GPL theme!





shortnotes free wordpress theme

Demo | Download
Shortnotes is a tumblogging theme with support for custom post formats.


Key Features :
1. Responsive Design.
2. Built-in Pagination.
3. Widget Ready.
4. Theme Options Panel.
5. Web Fonts Supported.
6. Localization Ready.




western free wordpress theme

Demo | Download
Western is a premium WordPress theme for tutorial sites.





simple-corp wordpress theme
Demo | Download
SimpleCorp is a gorgeous theme meant for corporate and business websites. It features a plethora of tweak-worthy options to help you customize your site.


Key Features :
1. HTML5 and CSS3.
2. Responsive Design.
3. Multiple Color Styles.
4. Built-in Pagination.
5. Built-in Contact Form.
6. Theme Options Panel.




Tuesday, March 12, 2013

Magento : How to fetch all out of stock products and save them in a CSV file

Ever wanted to get all of the out is stock products from your magento store and save them in csv file, here is a ready made script for your help.

[php]
ini_set('memory_limit', '-1'); //in-case if we have large inventory
set_time_limit(0); //in-case if we have large inventory, it could take infinite time
require_once ('app/Mage.php'); //loading magento
Mage::app('default'); //loading default store view

//Create a test folder
$fp = fopen('test/Outofstockproducts.csv', 'w'); //this line will create Outofstockproducts.csv file under //test folder

//CSV head columns
$list = array (
array('SKU','NAME')
);

//Write the head
foreach($list as $fields){
fputcsv($fp, $fields);
}

$stockCollection = Mage::getModel('cataloginventory/stock_item')->getCollection()
->addFieldToFilter('is_in_stock', 0);

$productIds = array();

foreach ($stockCollection as $item) {
$productIds[] = $item->getOrigData('product_id');
}

$productCollection = Mage::getModel('catalog/product')->getCollection()
->addIdFilter($productIds)
->addAttributeToSelect('name');

$products = array();

foreach($productCollection as $product){
$list = array(
array($product->getData('sku'), $product->getData('name'))
);

foreach ($list as $fields) {
fputcsv($fp, $fields);
}
}
[/php]

Paste this code on php file and save it as GetOutOfStock.php place it on magento root folder run the script from the browser http://yoursite.com/GetOutOfStock.php after completing the script you will find a
csv file under test folder containing all of the out of stock products of the default store.

Hope it helps,Thanks
Happy coding

Monday, March 11, 2013

Magento : Weird url parameter on detail page

Hii.. here is another interesting issue which i have found today that i have added addthis share button on my product detail page and found that there were some weird url param like #AHb4gs1hwck was adding to the end of every product product url in the address bar, it was really weird and i want to remove this so i have google this and found a solution
It was in the add this configuration on the page, the data_track_addressbar was set to true
Before :
[js]<script type="text/javascript">var addthis_config = {"data_track_addressbar":true};</script>[/js]

After :
[js]<script type="text/javascript">var addthis_config = {"data_track_addressbar":false};</script>[/js]

And this completely remove the param from the url

Hope it helps
Happy coding

Sunday, March 10, 2013

Magento : How to get product custom option value programmatically

Magento has the power to define product variations (custom options) with each product, which allow your online customers to select an specific product from wide range of option available with each product,
Custom options are a good solution if your inventory needs are simple and you have a limited number of available SKUs.

get-product-custom-option-value
[php]
$product = Mage::getModel("catalog/product")->load(1); //product id 1
$i = 1;
echo "<pre>";
foreach ($product->getOptions() as $o) {
echo "<strong>Custom Option:" . $i . "</strong><br/>";
echo "Custom Option TITLE: " . $o->getTitle() . "<br/>"; //Colors
echo "Custom Option TYPE: " . $o->getType() . "<br/>"; //drop_down
echo "Custom Option Values: <br/>";
$values = $o->getValues();
foreach ($values as $v) {
print_r($v->getData());
}
$i++;
echo "<br/>";
}
[/php]

Hope It helps.
Happy coding

How to reset you magento password from phpmyadmin

If you ever ran into a situation where you can not reset your password using forgot password forms e.g. while working on localhost the reset password mail does not triggers, for this situation you can easily change your password from your phpmyadmin interface

Here is how to :
1. Open your phpmyadmin
2. Go to table admin_user
magento-phpmyadmin-reset-password
3. Go to this URL
4. Type your password and get hash text for that their
5. Edit the admin row under the admin_user table of phpmyadmin
6. Go to password column and paste the copied text (Password Hash) to column
7. Go to admin page and login with password for which you have generated your hash

Thanks.
Hope it helps

Magento : Illegal scheme supplied, only alphanumeric characters are permitted

If you are using magento 1.6 version and ever found this error saying that Illegal scheme supplied, only alphanumeric characters are permitted This is probably a bug in Magento 1.6.1.0, see here, full discussion on magento fourm

here is quick patch by Dan
Download it from here

Thursday, February 28, 2013

How magento works!!!

Here is some interesting Diagram about how actually magento MVC system works  (courtsey: Alan Storm)

Magento Mvc magergurus

Wednesday, February 27, 2013

How to improve your magento store performance?

magernto_permfomance


There a are few tips for getting your magento store running at much faster speed:


Sunday, February 24, 2013

How to check the remote image file is valid or not

Recently i just come across the situation to check that whether the image on the URL is valid image file or not because i was running in the situation where some images are exists but they were broken just broken files...

So here the php code to check that image file directly from the URL

[php]

$src = "http://www.yoursite.com/full/path/to/your/image.jpg";
list($width, $height, $type, $attr) = @getimagesize($src);

[/php]

The getimagesize function will determine the size of any given image then you can check with your code whether is width and height is set or not

[php]

if(!isset($width) || is_null($width)){

echo "Not a valid image";

}

else{

echo "Valid image";

}[/php]

Happy coding :-)

Saturday, February 23, 2013

Magento : How to get products for which image is added

Here is the sample code for getting all the products for which base image is added.

[php]</pre>
$collection = Mage::getModel('catalog/product')
->getCollection()->addAttributeToFilter('image', array('neq' =>'no_selection'))
->addAttributeToSelect('*');
<pre>[/php]

May be this could help some one who have some requirements like this.

Magento : Load some products which comes under products Id range

Here is simple code for filtering product collection based on the on product id range, suppose you want to filter the collection

Example you want to filter the  collection where product id comes under the range of 1 and 100

[php]
$collection = Mage::getModel('catalog/product')
->getCollection()->addAttributeToFilter('entity_id', array('lt' =>500,'gt'=>1))
->addAttributeToSelect('*');

[/php]

How to open a you tube video in custom light box

You can open a video in pop up window. Simply copy paste the html code shown below into an html file. Attached jquery library file (default jquery library). Copy paste the code for css into a css file and link that file with the html file. Copy paste the javascript code in the <head> tag in html file.

How it works?

When a user simply clicks on the image (image is under anchor tag with id="clickme"), video gets open up into lightbox. As autoplay value is true for the video, you do not need to click on play button, video starts automatically. Tested this code on mozilla firefox, google chrome, IE.

[css language="true"]

<div class="featured_video">
<div class="head_featured_video">Featured Video</div>
<a id="clickme" href="javascript:popup()"><img alt="" src="http://www.magegurus.com/wp-content/uploads/2013/02/video.jpg" /> </a>
<div id="floatingDiv">
<div id="floatinginner">
<div id="innerfloatingdiv"><a id="closing" href="javascript:popclose()"></a>

<iframe src="http://www.youtube.com/embed/lIza2Dh8o3M?wmode=transparent?&amp;autoplay=0" height="350" width="425" allowfullscreen="" frameborder="0" scrolling="no"></iframe>

</div>
</div>
</div>

</div>

[/css]
[css autolinks="false" classname="myclass" language="false"]

<style type="text/css">
#floatingDiv { display: none; position: fixed; top: 0px; left: 0px; z-index: 1005; opacity: 1; width: 100%; height: 100%;

background-image: none; background-color: transparent; }

#floatingDiv #floatinginner { width: 995px; height: 100%; position: absolute; background-color: #ffffff; }

#floatingDiv #innerfloatingdiv { position: absolute; border: 4px solid #000000; height: 350px; width: 425px; }

#innerfloatingdiv a#closing { color: #990000; width: 17px; height: 17px; background-color: #ededed; position: absolute; z-index: 9; top: 5px; right: 4px;

background-image: url(01fbf%2B3Ef4L.gif); background-repeat: no-repeat; background-position: left top; }
</style>

[/css]
[code lang="js"]
<script type="text/javascript">
function popup(){
jQuery("#floatinginner").fadeIn(3000);
jQuery("#innerfloatingdiv").css("display", "none");
var disp = document.getElementById('floatingDiv').style.display;
if(disp == 'block')
disp = 'none';
else disp = 'block';
document.getElementById('floatingDiv').style.display = disp;
var window_width = j(window).width();
var floatinginner_width = 497;
var half_win_width = window_width/2;
var leftnum = half_win_width - floatinginner_width;
var lef = Math.abs(parseInt(leftnum));
var left = parseInt(lef) + 'px';
var elemen = document.getElementById('floatinginner');
elemen.style.left=left;

setTimeout(function(){
jQuery("#innerfloatingdiv").css("display", "block");
var autoply = jQuery("#floatingDiv #innerfloatingdiv iframe").attr("src");
autoply = autoply.replace("autoplay=0","autoplay=1");
jQuery("#floatingDiv #innerfloatingdiv iframe").attr("src",autoply);
}, 3000);

var video_width = 213;
var floatinginner_full_wd = 994;
var pop_left = floatinginner_width - video_width;
var le = Math.abs(parseInt(pop_left));
//if number is negative then make it positive.
var window_height = j(window).height();
var half_window_height = window_height/2;
var half_innerfloatingdiv_height = 172;
var fromtop =  half_window_height - half_innerfloatingdiv_height;
var toppx = Math.abs(parseInt(fromtop));
var top = parseInt(toppx) + 'px';
var lee = parseInt(le) + 'px';
var elem = document.getElementById('innerfloatingdiv');
elem.style.left=lee;
elem.style.top=top;
}

function popclose() {
var clos = document.getElementById('floatingDiv').style.display;

if(clos == 'block') {
var innr = document.getElementById('floatingDiv');
if(innr) {
var m = jQuery("#floatingDiv #innerfloatingdiv iframe").attr("src");
m = m.replace("autoplay=1","autoplay=0");
jQuery("#floatingDiv #innerfloatingdiv iframe").attr("src",m);
var have;
have = innr.innerHTML; innr.innerHTML = '';
innr.innerHTML = have;
}

clos = 'none';
// document.getElementById('floatingDiv').style.display = clos;
jQuery('#innerfloatingdiv').css("display","none");
jQuery('#floatinginner').fadeOut(2000);
setTimeout(function(){ jQuery('#floatingDiv').css("display","none"); },2000); }
}
</script>
[/code]

Thursday, February 14, 2013

Magento : How to delete all images which are not exists in the directory

Here is a simple code for those who want to delete all images from the product for which images are not exists in the media/catalog/product folder

[php]
<pre><em id="__mceDel">
ini_set('memory_limit', '-1');
set_time_limit(0);
require_once ('app/Mage.php');
Mage::app('default');

$imgfolder = 'media/catalog/product';
$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*');

&nbsp;

foreach ($collection as $product) {
$img = $product->getImage();
if(!file_exists($imgfolder.$img)){
$products = Mage::getModel('catalog/product')->load($product->getId());
$entityTypeId = $products->getEntityTypeId();
$mediaGalleryAttribute = Mage::getModel('catalog/resource_eav_attribute')->loadByCode($entityTypeId, 'media_gallery');
$gallery = $products->getMediaGalleryImages();
foreach ($gallery as $image)
$mediaGalleryAttribute->getBackend()->removeImage($products, $image->getFile());
$products->save();
}

}

[/php]

Explanation of code :

1) ini_set('memory_limit', '-1');

There could be thousand of products that we can not load them in one shot.

2) set_time_limit(0);
Setting script execution time limit to no-limit as it could stop in between