Thursday, December 29, 2011

Upload image through iframe magento

Upload image through iframe magento

My phtml file

<form id="file_upload_form" method="post" enctype="multipart/form-data" action="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).'catalog/product/myupload';?>">
<input name="file" id="file" size="27" type="file" /><br />
<input type="submit" name="action" value="Upload" /><br />
<iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
 <div id="image_details"></div>
<script type="text/javascript">
function init() {
    document.getElementById('file_upload_form').onsubmit=function() {
        document.getElementById('file_upload_form').target = 'upload_target'; //'upload_target' is the name of the iframe
        document.getElementById("upload_target").onload = uploadDone; //This function should be called when the iframe has compleated loading
            // That will happen when the file is completely uploaded and the server has returned the data we need.
    }
}
function uploadDone() { //Function will be called when iframe is loaded
    var ret = frames['upload_target'].document.getElementsByTagName("body")[0].innerHTML;
    document.getElementById("uploadaddtocart").disabled = false;
    document.getElementById("deleteimage").style.display = "block";
   
    jQuery("#image_details").html("<img src='http://xaprio.com/Client/demos/tfasigns/media/customertemplates/" + ret + "' />");
    }
window.onload=init;
</script>


My controller action


 public function myuploadAction()
    {
    /*echo "hello";   
    print_r($_POST);
    print_r($_FILES);*/
    $path = '/home/xaprioc/public_html/Client/demos/tfasigns/media/customertemplates';
   
    $imgarr = $this->upload('file',$path,'txt,jpg,jpeg,gif,png');
    echo $imgarr[0];
    $imagewithpath = $path."/".$imgarr[0];
    Mage::getSingleton('core/session')->setUploadimage($imagewithpath);       
    }
   
   
   
    public function upload($file_id, $folder="", $types="")
    {
    if(!$_FILES[$file_id]['name']) return array('','No file specified');

    $file_title = $_FILES[$file_id]['name'];
    //Get file extension
    $ext_arr = split("\.",basename($file_title));
    $ext = strtolower($ext_arr[count($ext_arr)-1]); //Get the last extension

    //Not really uniqe - but for all practical reasons, it is
    $uniqer = substr(md5(uniqid(rand(),1)),0,5);
    $file_name = $uniqer . '_' . $file_title;//Get Unique Name

    $all_types = explode(",",strtolower($types));
    if($types) {
        if(in_array($ext,$all_types));
        else {
            $result = "'".$_FILES[$file_id]['name']."' is not a valid file."; //Show error if any.
            return array('',$result);
        }
    }

    //Where the file must be uploaded to
    if($folder) $folder .= '/';//Add a '/' at the end of the folder
    $uploadfile = $folder . $file_name;

    $result = '';
    //Move the file from the stored location to the new location
    if (!move_uploaded_file($_FILES[$file_id]['tmp_name'], $uploadfile)) {
        $result = "Cannot upload the file '".$_FILES[$file_id]['name']."'"; //Show error if any.
        if(!file_exists($folder)) {
            $result .= " : Folder don't exist.";
        } elseif(!is_writable($folder)) {
            $result .= " : Folder not writable.";
        } elseif(!is_writable($uploadfile)) {
            $result .= " : File not writable.";
        }
        $file_name = '';
       
    } else {
        if(!$_FILES[$file_id]['size']) { //Check if the file is made
            @unlink($uploadfile);//Delete the Empty file
            $file_name = '';
            $result = "Empty file found - please use a valid file."; //Show the error message
        } else {
            chmod($uploadfile,0777);//Make it universally writable.
        }
    }

    return array($file_name,$result);
    }


Monday, December 19, 2011

Magento : Add or create new product magento through code with custom options

<?php 
//  Add or create  new product magento through code with custom options, image and manage stock
// mmoves image and assigns to all three types image, small_image and thumbnail_image
require_once 'app/Mage.php';
umask(0);
$app = Mage::app();
$session = Mage::getSingleton('customer/session', array('name'=>'frontend'));



//create a new product
try {          
    
  $serverurl = $_SERVER['DOCUMENT_ROOT'].'/Client/demos/tfasigns/img_output_.jpg';
  $product = Mage::getModel('catalog/product');
  $stockData = $product->getStockData();
        $stockData['qty'] = 10;
        $stockData['is_in_stock'] = 1;
        $stockData['manage_stock'] = 1;
        $stockData['use_config_manage_stock'] = 0;
   $options = array();
        $options = array(
            'title' => 'Option Title',
            'type' => 'radio',
            'is_require' => 1,
            'sort_order' => 0,
            'values' => array()
        );
        $options['values'][] = array(
            'title' => 'Option Value 1',
            'price' => 0.00,
            'price_type' => 'fixed',
            'sku' => '',
            'sort_order' => '1'
        );
        $options['values'][] = array(
            'title' => 'Option Value 2',
            'price' => 89.00,
            'price_type' => 'fixed',
            'sku' => '',
            'sort_order' => '1'
        );
 
    $product->setStoreId('default')
    ->setTypeId('simple')  
    ->setAttributeSetId(4)
    ->setName('4You banner5')
    ->setDescription("This widget will give you years of trouble-free widgeting.")
    ->setShortDescription("High-end widget.")
    ->setSku('4you5')
    ->setWeight(1.0)
    ->setStatus(1)
    ->setVisibility(4)
    ->setPrice(15.49)
    ->addImageToMediaGallery($serverurl,array('thumbnail','small_image','image'),true,false)
    ->setTaxClassId(0)
    ->setStockData($stockData)
    ->setCategoryIds('3')
    ->setHasOptions(1)
    ->setProductOptions(array($options))
    ->setCanSaveCustomOptions(true)
    ->save();  
 
  echo 'OK Product ID: '.$product->getId();
 
      $cache = Mage::getSingleton('core/cache');
      $cache->flush();
}
catch (Mage_Core_Exception $e) {
  echo $e->getMessage();
}
catch (Exception $e) {
  echo $e;
}


?>

Magento admin notice "Your web server is configured ......... hosting provider."

Here is solution to the issue, which comes in magento admin dashboard.
"Your web server is configured incorrectly. As a result, configuration files with sensitive information are accessible from the outside. Please contact your hosting provider."

Issue Explanation :-
The issue relates with easy access to configuration file by web, i.e.,  
http://sitename/app/etc/local.xml
And this should be made unreadable by web.

Solution :- 
Depending on server apache settings any of the following solution may work.
1. Try changing permissions of  app/etc/local.xml to 660. Then check if http://sitename/app/etc/local.xml shows forbidden(or access denied or any error) & then test magento admin dashboard if that error is gone.
2. In case 1 fails, then 
 Try changing permissions of  app/etc/local.xml to 600. Then check if http://sitename/app/etc/local.xml shows forbidden & then test magento admin dashboard if that error is gone. 
3. In case, 1 & 2 both fails then lets discuss it further with me, as there might any other security loophole that too has to be fixed.

Thursday, December 15, 2011

Magento delete test orders , invoices, customers from magento 1.5

When all development works are done and site is ready for
live, we need to delete all orders from magento database and
reset all id's before making it live.
Just run the following queries in database,
and you are done.
 
SET FOREIGN_KEY_CHECKS=0;
 
TRUNCATE `sales_flat_order`;
TRUNCATE `sales_flat_order_address`;
TRUNCATE `sales_flat_order_grid`;
TRUNCATE `sales_flat_order_item`;
TRUNCATE `sales_flat_order_status_history`;
TRUNCATE `sales_flat_quote`;
TRUNCATE `sales_flat_quote_address`;
TRUNCATE `sales_flat_quote_address_item`;
TRUNCATE `sales_flat_quote_item`;
TRUNCATE `sales_flat_quote_item_option`;
TRUNCATE `sales_flat_order_payment`;
TRUNCATE `sales_flat_quote_payment`;
TRUNCATE `sales_flat_shipment`;
TRUNCATE `sales_flat_shipment_item`;
TRUNCATE `sales_flat_shipment_grid`;
TRUNCATE `sales_flat_invoice`;
TRUNCATE `sales_flat_invoice_grid`;
TRUNCATE `sales_flat_invoice_item`;
TRUNCATE `sendfriend_log`;
TRUNCATE `tag`;
TRUNCATE `tag_relation`;
TRUNCATE `tag_summary`;
TRUNCATE `wishlist`;
TRUNCATE `log_quote`;
TRUNCATE `report_event`;
 
ALTER TABLE `sales_flat_order` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_address` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_grid` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_status_history` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_address` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_address_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_item_option` AUTO_INCREMENT=1;
ALTER TABLE `sendfriend_log` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_payment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_payment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_invoice` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_invoice_grid` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_invoice_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment_grid` AUTO_INCREMENT=1;
ALTER TABLE `tag` AUTO_INCREMENT=1;
ALTER TABLE `tag_relation` AUTO_INCREMENT=1;
ALTER TABLE `tag_summary` AUTO_INCREMENT=1;
ALTER TABLE `wishlist` AUTO_INCREMENT=1;
ALTER TABLE `log_quote` AUTO_INCREMENT=1;
ALTER TABLE `report_event` AUTO_INCREMENT=1;
 
-- lets reset customers
TRUNCATE `customer_address_entity`;
TRUNCATE `customer_address_entity_datetime`;
TRUNCATE `customer_address_entity_decimal`;
TRUNCATE `customer_address_entity_int`;
TRUNCATE `customer_address_entity_text`;
TRUNCATE `customer_address_entity_varchar`;
TRUNCATE `customer_entity`;
TRUNCATE `customer_entity_datetime`;
TRUNCATE `customer_entity_decimal`;
TRUNCATE `customer_entity_int`;
TRUNCATE `customer_entity_text`;
TRUNCATE `customer_entity_varchar`;
TRUNCATE `log_customer`;
TRUNCATE `log_visitor`;
TRUNCATE `log_visitor_info`;
 
ALTER TABLE `customer_address_entity` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_datetime` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_decimal` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_int` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_text` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_varchar` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_datetime` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_decimal` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_int` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_text` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_varchar` AUTO_INCREMENT=1;
ALTER TABLE `log_customer` AUTO_INCREMENT=1;
ALTER TABLE `log_visitor` AUTO_INCREMENT=1;
ALTER TABLE `log_visitor_info` AUTO_INCREMENT=1;
 
-- Now, lets Reset all ID counters
TRUNCATE `eav_entity_store`;
ALTER TABLE `eav_entity_store` AUTO_INCREMENT=1;
 
SET FOREIGN_KEY_CHECKS=1;

Tuesday, December 13, 2011

Monday, December 12, 2011

Magento Prototype Tutorial and Ajax

 Magento Prototype Ajax
http://www.prototypejs.org/learn/introduction-to-ajax
http://particletree.com/features/quick-guide-to-prototype/

Tuesday, December 6, 2011

Creating after insert trigger in my sql


Creating after insert  trigger for table b  after inserting values in table a


DELIMITER $$

CREATE TRIGGER b_Trigger
     AFTER insert ON a
     FOR EACH ROW
     BEGIN
     insert into b(`my_name`) values(new.name);
END;
$$
DELIMITER ;

Friday, December 2, 2011

Free Magento extensions

http://visionwidget.com/inspiration/web/374-free-magento-extensions.html

Jquery check if a radio button is checked

If you want to know whether a checkbox is checked or not just replace checkboxid with yours
and you are done.
$('#checkboxid').is(':checked');

Thursday, November 24, 2011

Magento SQLSTATE[23000] error

Magento error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`LittleDickyBird`.`catalog_category_product_index`, CONSTRAINT `FK_CATALOG_CATEGORY_PROD_IDX_CATEGORY_ENTITY` FOREIGN KEY (`category_id`) REFERENCES `catalog_category_entity` (`entity_id`) ON 
Solution: 
Replace the line: $newproduct->setWebsiteIDs(array(0)); should be:$newproduct->setWebsiteIDs(array(1)); 
Enjoy 

Wednesday, November 16, 2011

Saturday, October 22, 2011

Magento disable rating and reviews

If you are tired of disabling reviews from modules in admin , here is a quircky trick for that .
Comment the codes in these three files and you are done

  =>template/rating/empty.phtml
  =>template/review/helper/summary.phtml
  =>template/review/helper/summary_short.phtml.

Friday, October 21, 2011

Change shipment title based on country

Change shipment title based on country


For example :



We want to get shipment text as follows
Netherlands: TNT02

Belgium: TAX02

Others: DHL01

Go to
/app/code/core/Mage/Sales/Model/Quote/Address/Total/Shipping.php
Find
$address->setShippingDescription($rate->getCarrierTitle().' - '.$rate->getMethodTitle());
Replace with
if($address->getCountry()=='NL')
                                       {
                           $address->setShippingDescription('TNT02');
                                       }
                                       elseif($address->getCountry()=='BE')
                                       {
                                               $address->setShippingDescription('TAX02');
                                       }
                                       else
                                       {
                                               $address->setShippingDescription($rate->getMethodTitle());
                                       }

Integrate Drupal and Magento

http://drupal.org/node/468036
http://taroza.wordpress.com/2009/11/11/magento-and-drupal-integration/

Tuesday, October 11, 2011

Magento: Find subcategories for a root category

We can use the below code to find all child categories for a particular category
in Magento
 
<?php
//get category model
    $category_model = Mage::getModel('catalog/category'); 
 //$categoryid for which we have to find the child categories
    $_category = $category_model->load($categoryid); 
 //array that contains all child categories id
        $all_child_categories = $category_model->getResource()->getAllChildren($_category);
?>

Magento:Add/Edit HTML of success/failure message

Edit success/failure messages html in magento
Go to file
\app\code\core\Mage\Core\Block\Messages.php
find
public function getGroupedHtml()
    {
......................
Edit HTML here
......................
     }

Magento admin images donot show or upload

This is a common error in magento.
Product images in admin donot show or upload.
Fix:
In file
js/mage/adminhtml/product.js

replace
this.images.toJSON();
with:
Object.toJSON(this.images);

Wednesday, October 5, 2011

Redirect domain from index.php


If you are not able to redirect url(domain) from htaccess 

there is a simple solution .

Put this code at top in your index.php



<?
Header( "HTTP/1.1 301 Moved Permanently" ); 
Header( "Location: http://www.url.com" );       
?>

Secure url for cart, checkout and contacts page


In magento admin put https://domainname/  in secure url
Make "Use Secure URLs in Frontend" as Yes
Then  for checkout in  
/ app /code/core/Mage/Checkout/etc/config.xml file search <secure_url>
Just below Put
           <checkout_cart>/checkout/cart</checkout_cart>
            <checkout_onepage>/checkout/onepage</checkout_onepage>
            <checkout_multishipping>/checkout/multishipping</checkout_multishipping>


And  for contacts in  
/httpdocs/app/code/core/Mage/Contacts/etc/config.xml file
search <frontend>
Just below Put
 <frontend>
               <secure_url>
                       <contacts>/contacts</contacts>
               </secure_url>

</frontend> 
 
Further if you need more help visit the below url
More Help 

Saturday, October 1, 2011

Redirect non www to www url

It is very important from SEO point of view for a site to open from single url.
If you want that your site should only open with www preceding the url you should
just copy and paste the code below in your .htaccess file and you are done.For
example if a site opens with 'abc.com'  and  also with 'www.abc.com'  and you want
that it should always open with 'www.abc.com' and if one tries to open with
'abc.com' it should redirect it to 'www.abc.com'.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Thursday, September 8, 2011

Regular expression tutorial

Complete tutorial for custom regular expression formation
http://www.zytrax.com/tech/web/regex.htm

Magento table for moule/extension information

 Very nice link for Writing installer
http://magentocookbook.wordpress.com/2009/06/28/magento-module-sql-setup/

Wednesday, July 27, 2011

See template path hint in Magento Admin Panel

Wondering and tired to find templates for working in magento admin ?
Here is a simple solution. Just log into your database and run the 
below query and you are done.
  
 
INSERT INTO core_config_data (scope, scope_id, path, value)
VALUES ('default', 0, 'dev/debug/template_hints', 1),
('default', 0, 'dev/debug/template_hints_blocks', 1);
 
------------------E--N--j--o--y-------------------------------

Monday, July 18, 2011

Donot mesh previous session magento with current cart

If you want that the current cart items not to mesh up with previous session when you log on , replace your
app/code/core/Mage/Checkout/Model/observer.php file code with this one and you are done.
What we wanted was to prevent the cart from the old session from merging into the cart of the current session at the point when thecustomer login
<?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 license@magentocommerce.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_Checkout
 * @copyright  Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

/**
 * Checkout observer model
 *
 * @category   Mage
 * @package    Mage_Checkout
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Checkout_Model_Observer
{
    public function unsetAll()
    {
        Mage::getSingleton('checkout/session')->unsetAll();
    }

    public function loadCustomerQuote()
    {
        $lastQid = Mage::getSingleton('checkout/session')->getQuoteId(); //quote id during session before login;
        if ($lastQid) { //before login session exists means cart has items                           
            $customerQuote = Mage::getModel('sales/quote')
                ->loadByCustomer(Mage::getSingleton('customer/session')->getCustomerId()); //the cart from last login        
            //set it to the session before login and remove its items if any
            $customerQuote->setQuoteId($lastQid);
            $this->_removeAllItems($customerQuote);
           
        } else { //no session before login, so empty the cart (current cart is the old cart)
            $quote = Mage::getModel('checkout/session')->getQuote();                               
            $this->_removeAllItems($quote);
        }
    }

    protected function _removeAllItems($quote){
        //reset all custom attributes in the quote object here, eg:    
       // $quote->setDestinationCity('');
       
        foreach ($quote->getAllItems() as $item) {
            $item->isDeleted(true);
            if ($item->getHasChildren()) foreach ($item->getChildren() as $child) $child->isDeleted(true);
        }
        $quote->collectTotals()->save();       
    } //_removeAllItems
   
   
    public function salesQuoteSaveAfter($observer)
    {
        $quote = $observer->getEvent()->getQuote();
        /* @var $quote Mage_Sales_Model_Quote */
        if ($quote->getIsCheckoutCart()) {
            Mage::getSingleton('checkout/session')->getQuoteId($quote->getId());
        }
    }
}

Tuesday, May 31, 2011

Magento Import Tier Price


<?php
//Magento Import Tier Price from csv
require_once 'app/Mage.php';
umask(0);
Mage::app('default');

if(isset($_FILES["file"]) && !empty($_FILES["file"]))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
 else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

if (file_exists("var/export/" . $_FILES["file"]["name"]))
 {
 echo $_FILES["file"]["name"] . " already exists. ";
 }
else
 {
 move_uploaded_file($_FILES["file"]["tmp_name"],
 "var/export/" . $_FILES["file"]["name"]);
 echo "Stored in: " . "var/export/" . $_FILES["file"]["name"];
 }
}
$tableName = Mage::getSingleton('core/resource')
                          ->getTableName('catalog_product_entity_tier_price');
function CSVImport($table, $fields, $csv_fieldname='csv') {

$handle = fopen("var/export/".$_FILES["file"]["name"],'r');
    if(!$handle) die('Cannot open uploaded file.');
    $row_count = 0;
    $rows = array();

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $row_count++;
$records[] = $data;
        foreach($data as $key=>$value) {
            $data[$key] = "'" . addslashes($value) . "'";
        }
        $rows[] = implode(",",$data);
    }
   
    fclose($handle);

    if(count($records)) {
        foreach($records as $key=>$value)
  {
$tierprice[$value[4]][]=array(
'website_id'  => 0,
'price_qty'   => $value[8],
'price'       => $value[9]
  );
  }
foreach($tierprice as $key=>$value)
{
$productid = Mage::getModel('catalog/product')
 ->getIdBySku($key);
if($key=='sku')
{
continue;
}
foreach($value as $key1=>$val1)
{
$query = "insert into $table set
entity_id='".$productid."',
all_groups=1,
qty=$val1[price_qty],
value=$val1[price]";
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$write->query($query);
}
}
        print 'Successfully imported '.(int)($row_count-1).' record(s)';
    } else {
        print 'Cannot import data - no records found.';
    }
}
CSVImport($tableName, array('entity_id','all_groups','customer_group_id','qty', 'tier_type', 'value' ,'website_id'), "csv_file");
}
?>
<html>
<head>
<title>Import Tier Prices</title>
</head>
<body>
<div style="margin-top:200px;margin-left:250px; border:1px solid #999999;width:300px" >
<div style="color:#996600;text-decoration:underline;margin-left:80px;font-weight:bold" >Tier Price Import </div>
<div style="margin-top:20px;padding-left:5px">
<form name="importform" method="post" action="" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" name="import" value="Import" />
</form>
</div>
</div>
</body>
</html>



Magento export tier price


<?php
//Magento export tier price of all product to csv
require_once 'app/Mage.php';
umask(0);
Mage::app('default');

header("Content-type:text/octect-stream");
header("Content-Disposition:attachment;filename=data.csv");

$tableName = Mage::getSingleton('core/resource')
 ->getTableName('catalog_product_entity_tier_price');
$storeId    = Mage::app()->getStore()->getId();
$product    = Mage::getModel('catalog/product');
$products   = $product->getCollection()->addStoreFilter($storeId)->getAllIds();

$fieldname = array("store","websites","attribute_set","type","sku","name","tier_price_website","tier_price_customer_group","tier_price_qty","tier_price_price");
print stripslashes(implode(',',$fieldname)) . "\n";
foreach($products as $productid)
{
$existingTierPrice = $product ->load($productid)->tier_price;
$sku = $product->getSku();
$name = $product->getName();
foreach($existingTierPrice as $key=>$value)
{
$tierarray = array("admin","base","Default","simple",$sku,$name,"all","all",$value['price_qty'],$value['price']);
print stripslashes(implode(',',$tierarray)) . "\n";
}
}
?>

Monday, May 16, 2011

Php Code - Generate XML from database

Php code to generate XML from database.

<?php
header("Content-type: text/xml");

mysql_connect('hostname','user','password');
mysql_select_db('database_name');
$query = mysql_query("select * from table_name");

?>
<?php   

  $domtree = new DOMDocument('1.0', 'UTF-8');
  $xmlRoot = $domtree->createElement("xml");
  $xmlRoot = $domtree->appendChild($xmlRoot);
  $currentTrack = $domtree->createElement("itemset");
  $currentTrack = $xmlRoot->appendChild($currentTrack); 

 while($row = mysql_fetch_assoc($query))
    {
        $currentTrack1 = $currentTrack->appendChild($domtree->createElement("item"));
        foreach($row as $index=>$val)
            {
                $currentTrack1->appendChild($domtree->createElement($index,$val));

            }
    } 

 echo $domtree->saveXML();
?>

Saturday, April 2, 2011

php function to find Relative time in year, month, week, day etc


<?php
//function to find time passed or time left between two time.from & to are two arguments.
//to is optional and defaults to current time stamp if not given
echo time_relative("May 3, 1985 4:20 PM");
//convert time to maonth days weeks
 function time_relative($from, $to = null)
 {
  $to = (($to === null) ? (time()) : ($to));
  $to = ((is_int($to)) ? ($to) : (strtotime($to)));
  $from = ((is_int($from)) ? ($from) : (strtotime($from)));
  $output = '';

  $units = array
  (
   "year"   => 29030400, // seconds in a year   (12 months)
   "month"  => 2419200,  // seconds in a month  (4 weeks)
   "week"   => 604800,   // seconds in a week   (7 days)
   "day"    => 86400,    // seconds in a day    (24 hours)
   "hour"   => 3600,     // seconds in an hour  (60 minutes)  
   "minute" => 60,       // seconds in a minute (60 seconds)
   "second" => 1         // 1 second
  );

  $diff = abs($from - $to);
  $suffix = (($from > $to) ? ("left") : ("old"));

  foreach($units as $unit => $mult)
   if($diff >= $mult)
   {
    $and = (($mult != 1) ? ("") : ("and "));
    $output .= ", ".$and.intval($diff / $mult)." ".$unit.((intval($diff / $mult) == 1) ? ("") : ("s"));
    $diff -= intval($diff / $mult) * $mult;
   }
  $output .= " ".$suffix;
  $output = substr($output, strlen(", "));

  return $output;
 }
 ?>

Monday, March 28, 2011

wordpress plugin for assigning value to javascript variable

<?php
/*
Plugin Name: Url To Text
Plugin URI: http://www.microxsolutions.com/
Description:Plugin to replace key from url in frontend
Version: 1.0.0
Author: Afroz
Author URI: http://www.microxsolutions.com/
*/

/* Runs when plugin is activated */
register_activation_hook(__FILE__,'install_url_text');

/* Runs on plugin deactivation*/
register_deactivation_hook( __FILE__, 'url_text_deactivate' );
function itg_admin_css_all_page() {
    /**
     * <span class="IL_AD" id="IL_AD4">Register</span> the style handle
     */
   wp_register_style($handle = 'itg-admin-css-all', $src = plugins_url('css/url_text.css', __FILE__), $deps = array(), $ver = '1.0.0', $media = 'all');

    /**
     * Now enqueue it
     */
    wp_enqueue_style('itg-admin-css-all');
}

/**
 * Finally hook the itg_admin_css_all_page to admin_print_styles
 * As it is done during the init of the admin page, so the enqueue gets executed.
 * This can also be <span class="IL_AD" id="IL_AD8">attached</span> to the admin_init, or admin_menu hook
 */
add_action('admin_print_styles', 'itg_admin_css_all_page');
add_action('admin_menu','my_plugin_menu');
function my_plugin_menu(){
   add_options_page('My Plugin Options','Manage Url to Text','1','url-text','showRecords');
   add_options_page('My Plugin Options','','1','url-text','add_records');
}
function install_url_text()
{
    global $wpdb;
    $table = $wpdb->prefix."url_text";
    $structure = "CREATE TABLE $table(
                                id INT(11) NOT NULL auto_increment,
                                key_text VARCHAR(222) NOT NULL,
                                url VARCHAR(222) NOT NULL,
                                UNIQUE KEY id (id)
                                );";  
    $wpdb->query($structure);
}
function url_text_deactivate() {
        global $wpdb;
        $table = $wpdb->prefix."url_text";    
        $wpdb->query("DROP TABLE IF EXISTS $table");
}  
$action = $_REQUEST['action'];
switch($action)
{
  case "addemp":
       $key_text = $_REQUEST['key_text'];
       $url = $_REQUEST['url'];
       if(!isset($_GET['id']) || $_GET['id']=='')
       {
           if($key_text!='' && $url!='')
           {     
               addRecords($key_text,$url);
            }
            else
            {
                header("location:".$_SERVER['PHP_SELF']."?page=url-text&er=2");
            }
        }
  break;
  case "updaterec":
       $key_text = $_REQUEST['key_text'];
       $url = $_REQUEST['url'];
       $urlid = $_GET['id'];
       updateRecords($key_text,$url,$urlid);
  break;
  case "deleterec":
       $key_text = $_REQUEST['key_text'];
       $url = $_REQUEST['url'];
       $urlid = $_GET['id'];
       deleteRecords($urlid);
  break;
  default:               
}
function showRecords()
{  
         global $wpdb;
          $table = $wpdb->prefix."url_text";      
          $myrows = $wpdb->get_results( "SELECT *  FROM $table",ARRAY_A );
        if($wpdb->num_rows>0)
        {
        ?>
        <table width="70%">
        <tr><td colspan="4" class="heading1">List of Url and Key</td></tr>
        <tr><td colspan="4"><hr /></td></tr>
        <tr>
        <td width="19%" class="heading">S.No</td>
        <td width="21%" class="heading">Key</td>
        <td width="36%" class="heading">Url</td>
        <td width="24%" class="heading">Action</td>
        </tr>
        <tr><td colspan="4"><hr /></td></tr><?php
        $i=1;
        foreach($myrows as $key =>$value)
        {
         ?><tr>
        <td><?php _e($i);$i++;?></td>
        <td><?php _e($value['key_text']);?></td>
        <td><?php _e($value['url']);?></td>
        <td><a href="<?php _e($_SERVER['PHP_SELF']);?>?page=url-text&action=addemp&id=<?php _e($value['id']);?>">Edit</a> |
            <a href="<?php _e($_SERVER['PHP_SELF']);?>?page=url-text&action=deleterec&id=<?php _e($value['id']);?>">Delete</a></td></tr><?php
        }
         ?><tr><td colspan="4"><hr /></td></tr>      
        </table><?php
        }
        else{_e('<table width="70%">
        <tr><td colspan="4" class="heading1" id="errorfield1">No record to Show.</td></tr></table>');}
}
function addRecords($key_text,$url)
{
  global $wpdb;
  $counts=0;
  $table = $wpdb->prefix."url_text";
  $myrows = $wpdb->get_results( "SELECT *  FROM $table",ARRAY_A );
  foreach($myrows as $value)
      {
         if($value['key_text'] == $key_text)
         {$counts++;}
      }
  if($counts==0)
      {
      $results = $wpdb->insert($table,array('key_text' => $key_text, 'url' => $url));
      header("location:".$_SERVER['PHP_SELF']."?page=url-text");
      }
    else
    {
    header("location:".$_SERVER['PHP_SELF']."?page=url-text&er=1");
    }
}
function updateRecords($key_text,$url,$urlid)
{
    
        if($key_text != '' && $url != '')
        {
            global $wpdb;
            $counts=0;
            $table = $wpdb->prefix."url_text";
            $row = $wpdb->get_results( "SELECT * FROM $table where id!=$urlid ",ARRAY_A );
            foreach($row as $value)
            {
                 if($value['key_text'] == $key_text)
                 {$counts++;}
            }
            if($counts==0)
            {    
                $results = $wpdb->update($table,array('key_text' => $key_text, 'url' => $url), array( 'id' => $urlid ), array( '%s', '%s' ), array( '%d' ));
                header("location:".$_SERVER['PHP_SELF']."?page=url-text");
            }
            else
            {
                header("location:".$_SERVER['PHP_SELF']."?page=url-text&action=addemp&id=".$urlid."&er=1");
            }
        }
        else
        {
            header("location:".$_SERVER['PHP_SELF']."?page=url-text&action=addemp&id=".$urlid."&er=2");          
        }
 
}
function deleteRecords($id)
{
  global $wpdb;
  $table = $wpdb->prefix."url_text";
  $wpdb->query("DELETE FROM $table WHERE id = $id");
  header("location:".$_SERVER['PHP_SELF']."?page=url-text");
}
//add_action('pre_get_posts','replacekey_text_url');
//add_action('wp_print_scripts','replacekey_text_url');
add_action('wp_head','replacekey_text_url');
function replacekey_text_url()
{
//selecting all key urls from db start
global $wpdb;
$text = '';
$table = $wpdb->prefix."url_text";
$myrows = $wpdb->get_results( "SELECT *  FROM $table",ARRAY_N );
//selecting all key urls from db end
$text.= '<script type="text/javascript">';
$text.= "var TextKey = new Array();\n";  
    foreach($myrows as $value)
    {
        $text.= "TextKey[\"$value[1]\"]";
        $text.= " = \"$value[2]\";\n";          
    }
$text.= '</script>';
_e($text);
}
function add_records(){
if(isset($_GET['id']) && $_GET['id']!='')
{
$id=$_GET['id'];
global $wpdb;
$table = $wpdb->prefix."url_text";
$row = $wpdb->get_row( "SELECT * FROM $table where id=$id",ARRAY_A );
}
?><div class="wrap">
  <h3 class="heading1"><?php if(isset($_GET['id']) && $_GET['id'] !=''){_e('Update URL and Key Values');}else{_e('Add URL and Key Values');}?></h3>
    <form action="" method="post">
         <table width="60%" class="form-table" border="0">
            <tr><td></td><td id="errorfield"><?php if(isset($_GET['er']) && $_GET['er']==1){_e("Key already Exist!");}
            elseif(isset($_GET['er']) && $_GET['er']==2){_e("Key/Url is empty!");}?></td></tr>
            <tr>
              <td class="heading"><label for="key_text"><?php _e('Key')?></label></td>
              <td><input type="text" name="key_text" value="<?php if(isset($_GET['id']) && $_GET['id']!=''){_e($row['key_text']);}?>"></td>
            </tr>
            <tr>
              <td class="heading"><label for="url"><?php _e('URL')?></label></td>
              <td><input type="text" name="url" value="<?php if(isset($_GET['id']) && $_GET['id']!=''){_e($row['url']);}?>"></td>
            </tr>
            <tr>
              <td><input type="hidden" name="action" value="<?php if(isset($_GET['id']) && $_GET['id']!=''){_e('updaterec');}else{_e('addemp');}?>" /></td>
              <td><input type="submit" name="submit"  value="<?php if(isset($_GET['id']) && $_GET['id']!=''){_e('Update');}else{_e('Insert');} ?>"/></td>
            </tr>        
         </table>  
    </form>
</div><?php
}
?>