Thursday, February 4, 2016

Magento: Delete All Products Using PhpMyAdmin

Deleting all products on magento via the admin panel can be almost imposible when you have more than 10.000 products.

A quick way to do this would be thru phpmyadmin.

Before running this code please make sure you have a backup of the entire database.

This code worked fine on magento 1.7.0.2

Copy and paste this code @ phpmyadmin under SQL tab and run it.

SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE TABLE `catalog_product_bundle_option`;
TRUNCATE TABLE `catalog_product_bundle_option_value`;
TRUNCATE TABLE `catalog_product_bundle_selection`;
TRUNCATE TABLE `catalog_product_entity_datetime`;
TRUNCATE TABLE `catalog_product_entity_decimal`;
TRUNCATE TABLE `catalog_product_entity_gallery`;
TRUNCATE TABLE `catalog_product_entity_int`;
TRUNCATE TABLE `catalog_product_entity_media_gallery`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
TRUNCATE TABLE `catalog_product_entity_text`;
TRUNCATE TABLE `catalog_product_entity_tier_price`;
TRUNCATE TABLE `catalog_product_entity_varchar`;
TRUNCATE TABLE `catalog_product_link`;
TRUNCATE TABLE `catalog_product_link_attribute`;
TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
TRUNCATE TABLE `catalog_product_link_type`;
TRUNCATE TABLE `catalog_product_option`;
TRUNCATE TABLE `catalog_product_option_price`;
TRUNCATE TABLE `catalog_product_option_title`;
TRUNCATE TABLE `catalog_product_option_type_price`;
TRUNCATE TABLE `catalog_product_option_type_title`;
TRUNCATE TABLE `catalog_product_option_type_value`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_attribute_pricing`;
TRUNCATE TABLE `catalog_product_super_attribute`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_enabled_index`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_category_product_index`;
TRUNCATE TABLE `catalog_category_product`;
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;
TRUNCATE TABLE `cataloginventory_stock`;
INSERT INTO `catalog_product_link_type`(`link_type_id`,`code`) VALUES (1,'relation'),(2,'bundle'),(3,'super'),(4,'up_sell'),(5,'cross_sell');
INSERT INTO `catalog_product_link_attribute`(`product_link_attribute_id`,`link_type_id`,`product_link_attribute_code`,`data_type`) VALUES (1,2,'qty','decimal'),(2,1,'position','int'),(3,4,'position','int'),(4,5,'position','int'),(6,1,'qty','decimal'),(7,3,'position','int'),(8,3,'qty','decimal');
INSERT INTO `cataloginventory_stock`(`stock_id`,`stock_name`) VALUES (1,'Default');
TRUNCATE TABLE `catalog_product_entity`;
SET FOREIGN_KEY_CHECKS = 1;

Thursday, March 21, 2013

Magento quantity increments – jQuery edition

jQuery("div.quantity").append('<input type="button" value="+" id="add1" class="plus" />').prepend('<input type="button" value="-" id="minus1" class="minus" />');
        jQuery(".plus").click(function()
        {
            var currentVal = parseInt(jQuery(this).prev(".qty").val());
            
            if (!currentVal || currentVal=="" || currentVal == "NaN") currentVal = 0;
             
            jQuery(this).prev(".qty").val(currentVal + 1);
        });
     
        jQuery(".minus").click(function()
        {
            var currentVal = parseInt(jQuery(this).next(".qty").val());
            if (currentVal == "NaN") currentVal = 0;
            if (currentVal > 0)
            {
                jQuery(this).next(".qty").val(currentVal - 1);
            }
        });
 
 
 Simply wrap this line inside a div like so;
 
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="<?php echo $this->getMinimalQty($_product) ?>" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />
</div> <!-- /.quantity -->
 

Wednesday, March 20, 2013

How to create custom system configuration in magento

Magento allow us to configure and tweak the behavior of the site in the admin panel via system configuration. We can extend and use this feature in our custom modules too. This article describes the steps to achieve custom configuration in magento admin panel In this article We create and save our custom configuration message in our module. This module creates a custom tab and allows us to configure our own settings.

Step 1: First we start with the modules config.xml.
app/code/local/Mydons/Configdemo/etc/config.xml
<?xml version="1.0"?>
<config>
<modules>
<mydons_customconfig>
<version>0.1.0</version>
</mydons_customconfig>
</modules>
<global>
<helpers>
<customconfig>
<class>Mydons_Customconfig_Helper</class>
</customconfig>
</helpers>
</global>
<adminhtml>
<acl>
<resources>
<admin>
<children>
<system>
<children>
<config>
<children>
<mydons translate="title" module="customconfig">
</mydons>
</children>
</config>
</children>
</system>
</children>
</admin>
</resources>
</acl>
</adminhtml>
</config>
Step 2: Create a Helper class as specified in the config.xml. app/code/local/Mydons/Configdemo/Helper/Data.php
<?php
class Mydons_Customconfig_Helper_Data extends Mage_Core_Helper_Abstract
{
Step 3: To Create our own configuration setting, system.xml file needs to be created as shown below.

<config>
<tabs>
<mydons translate="label" module="customconfig">
<label>Mydons</label>
<sort_order>100</sort_order>
</mydons>
</tabs>
<sections>
<mydons translate="label" module="customconfig">
<label>Mydons Config Demo</label>
<tab>mydons</tab>
<frontend_type>text</frontend_type>
<sort_order>100</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<groups>
<mydonsconfigdemo translate="label">
<label>Mydons Config Demo</label>
<frontend_type>text</frontend_type>
<sort_order>10</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<fields>
<mydons_message translate="label">
<label>Mydons Message</label>
<frontend_type>text</frontend_type>
<sort_order>10</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</mydons_message>
</fields>
</mydonsconfigdemo>
</groups>
</mydons>
</sections>
</config>
Step 4: Now finally our module activation file
Mydons_Configdemo.xml needs to be placed in
app/etc/modules/Mydons_Configdemo.xml
<?xml version="1.0"?>
<config>
<modules>
<mydons_customconfig>
<active>true</active>
<codepool>local</codepool>
</mydons_customconfig>
</modules>
</config>
Step 5: Now to Retrieve the Configuration file drop a file name configtest.php in magento root directory.
http://example.com/configtest.php
Execute the file in the URL

<?php
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app();
echo "<p style="color:green">";
echo Mage::getStoreConfig('mydons/mydonsconfigdemo/mydons_message');
echo "</p>";

Magento remove SEO-terms and advanced search from footer links

I’ve seen many solutions for this on the internet, but none of them seems to be complete, considering upward compatibility in Magento.

I’d like to remove the “Popular search terms” and “Advanced search” links from thefooter_links reference.
Since I want my site to be ready for upgrades, I want to do this through local.xml, not by duplicating catalogsearch.xml to a local version, since I believe this is not upward compatible.
I have seen some changes for the associated .phtml files, but I also believe this is not the right way to tackle this, it should be possible through local.xml right?
There’s no “name” attribute in the blocks in catalogsearch.xml, like here:
 <reference name="footer_links">
 <action method="addLink" translate="label title"
 module="catalogsearch" ifconfig="catalog/seo/search_terms"> 
<label>Search Terms</label> 
<url helper="catalogsearch/getSearchTermUrl" /> 
<title>Search Terms</title> </action> 
<action method="addLink" translate="label title" module="catalogsearch">
 <label>Advanced Search</label> 
<url helper="catalogsearch/getAdvancedSearchUrl" />
 <title>Advanced Search</title> </action> </reference> 

Increase session cookie timeout for admin in Magento

It becomes very frustating when you are working on frontend as well as admin, and after every hour of inactive you are again and again asked to enter username and password to login into Magento admin. Also, it takes time to log you in and go to your required page, it’s really headache. With below settings, you will able to increase your admin auto logout (session timeout) to anything like 4 hours / 1 day / 1 week or anything as per your wish.
Go to admin panel:

System > Configuration > General > Web > Session Cookie management > Cookie Lifetime
Change this to 86400 (1 day, because 86400 seconds makes one day)
Also, through SQL script directly to database you can increase this:
UPDATE core_config_data SET value = ’86400′ WHERE path = ‘web/cookie/cookie_lifetime’;

customize magento packing slip using zend pdf

you need to change in 3 pages
1)app/code/local/mage/sales/model/order/pdf/abstract.php
2)app/code/local/mage/sales/model/order/pdf/shipment.php
3)app/code/local/mage/sales/model/order/pdf/Items/Shipment/Default.php
and also i used arial font. for this we need to upload “arial” font folder into “lib” folder which is in root of magento.
app/code/local/mage/sales/model/order/pdf/abstract.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_Sales
* @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Sales Order PDF abstract model
*
* @category Mage
* @package Mage_Sales
* @author Magento Core Team
*/
abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
{
/**
* Y coordinate
*
* @var int
*/
public $y;
/**
* Item renderers with render type key
*
* model => the model name
* renderer => the renderer model
*
* @var array
*/
protected $_renderers = array();
/**
* Predefined constants
*/
const XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID = ‘sales_pdf/invoice/put_order_id’;
const XML_PATH_SALES_PDF_SHIPMENT_PUT_ORDER_ID = ‘sales_pdf/shipment/put_order_id’;
const XML_PATH_SALES_PDF_CREDITMEMO_PUT_ORDER_ID = ‘sales_pdf/creditmemo/put_order_id’;
/**
* Zend PDF object
*
* @var Zend_Pdf
*/
protected $_pdf;
/**
* Default total model
*
* @var string
*/
protected $_defaultTotalModel = ‘sales/order_pdf_total_default’;
/**
* Retrieve PDF
*
* @return Zend_Pdf
*/
abstract public function getPdf();
/**
* Returns the total width in points of the string using the specified font and
* size.
*
* This is not the most efficient way to perform this calculation. I’m
* concentrating optimization efforts on the upcoming layout manager class.
* Similar calculations exist inside the layout manager class, but widths are
* generally calculated only after determining line fragments.
*
* @param string $string
* @param Zend_Pdf_Resource_Font $font
* @param float $fontSize Font size in points
* @return float
*/
public function widthForStringUsingFontSize($string, $font, $fontSize)
{
$drawingString = ‘”libiconv”‘ == ICONV_IMPL ?
iconv(‘UTF-8′, ‘UTF-16BE//IGNORE’, $string) :
@iconv(‘UTF-8′, ‘UTF-16BE’, $string);
$characters = array();
for ($i = 0; $i < strlen($drawingString); $i++) {
$characters[] = (ord($drawingString[$i++]) << 8) | ord($drawingString[$i]);
}
$glyphs = $font->glyphNumbersForCharacters($characters);
$widths = $font->widthsForGlyphs($glyphs);
$stringWidth = (array_sum($widths) / $font->getUnitsPerEm()) * $fontSize;
return $stringWidth;
}
/**
* Calculate coordinates to draw something in a column aligned to the right
*
* @param string $string
* @param int $x
* @param int $columnWidth
* @param Zend_Pdf_Resource_Font $font
* @param int $fontSize
* @param int $padding
* @return int
*/
public function getAlignRight($string, $x, $columnWidth, Zend_Pdf_Resource_Font $font, $fontSize, $padding = 5)
{
$width = $this->widthForStringUsingFontSize($string, $font, $fontSize);
return $x + $columnWidth – $width – $padding;
}
/**
* Calculate coordinates to draw something in a column aligned to the center
*
* @param string $string
* @param int $x
* @param int $columnWidth
* @param Zend_Pdf_Resource_Font $font
* @param int $fontSize
* @return int
*/
public function getAlignCenter($string, $x, $columnWidth, Zend_Pdf_Resource_Font $font, $fontSize)
{
$width = $this->widthForStringUsingFontSize($string, $font, $fontSize);
return $x + round(($columnWidth – $width) / 2);
}
/**
* Insert logo to pdf page
*
* @param Zend_Pdf_Page $page
* @param null $store
*/
protected function insertLogo(&$page, $store = null)
{
$this->y = $this->y ? $this->y : 815;
$image = Mage::getStoreConfig(‘sales/identity/logo’, $store);
if ($image) {
$image = Mage::getBaseDir(‘media’) . ‘/sales/store/logo/’ . $image;
if (is_file($image)) {
$image = Zend_Pdf_Image::imageWithPath($image);
$top = 830; //top border of the page
$widthLimit = 270; //half of the page width
$heightLimit = 270; //assuming the image is not a “skyscraper”
$width = $image->getPixelWidth();
$height = $image->getPixelHeight();
//preserving aspect ratio (proportions)
$ratio = $width / $height;
if ($ratio > 1 && $width > $widthLimit) {
$width = $widthLimit;
$height = $width / $ratio;
} elseif ($ratio < 1 && $height > $heightLimit) {
$height = $heightLimit;
$width = $height * $ratio;
} elseif ($ratio == 1 && $height > $heightLimit) {
$height = $heightLimit;
$width = $widthLimit;
}
$y1 = $top – $height;
$y2 = $top;
$x1 = 25;
$x2 = $x1 + $width;
//coordinates after transformation are rounded by Zend
$page->drawImage($image, $x1, $y1, $x2, $y2);
$this->y = $y1 – 10;
}
}
}
/**
* Insert address to pdf page
*
* @param Zend_Pdf_Page $page
* @param null $store
*/
protected function insertAddress(&$page, $store = null)
{
$page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
$font = $this->_setFontRegular($page, 9);
$page->setLineWidth(0);
$this->y = $this->y ? $this->y : 815;
$top = 815;
$this->_setFontRegular($page, 16);
$page->drawText(Mage::helper(‘sales’)->__(‘Sender’), 25, ($top -= 30), ‘UTF-8′);
$this->_setFontRegular($page, 9);
foreach (explode(“\n”, Mage::getStoreConfig(‘sales/identity/address’, $store)) as $value){
if ($value !== ”) {
$value = preg_replace(‘/]*>/i’, “\n”, $value);
$page->drawText($value, 25, ($top -= 15), ‘UTF-8′);
//$page->drawText($value, 25, ($top -= 10), ‘UTF-8′);
}
}
$this->y = ($this->y > $top) ? $top : $this->y;
}
/**
* Format address
*
* @param string $address
* @return array
*/
protected function _formatAddress($address)
{
$return = array();
foreach (explode(‘|’, $address) as $str) {
foreach (Mage::helper(‘core/string’)->str_split($str, 45, true, true) as $part) {
if (empty($part)) {
continue;
}
$return[] = $part;
}
}
return $return;
}
/**
* Calculate address height
*
* @param array $address
* @return int Height
*/
protected function _calcAddressHeight($address)
{
$y = 0;
foreach ($address as $value){
if ($value !== ”) {
$text = array();
foreach (Mage::helper(‘core/string’)->str_split($value, 55, true, true) as $_value) {
$text[] = $_value;
}
foreach ($text as $part) {
$y += 15;
}
}
}
return $y;
}
/**
* Insert order to pdf page
*
* @param Zend_Pdf_Page $page
* @param Mage_Sales_Model_Order $obj
* @param bool $putOrderId
*/
protected function insertOrder(&$page, $obj, $putOrderId = true)
{
if ($obj instanceof Mage_Sales_Model_Order) {
$shipment = null;
$order = $obj;
} elseif ($obj instanceof Mage_Sales_Model_Order_Shipment) {
$shipment = $obj;
$order = $shipment->getOrder();
}
$this->y = $this->y ? $this->y : 815;
$top = $this->y+10;
$page->setFillColor(new Zend_Pdf_Color_GrayScale(0.45));
$page->setLineColor(new Zend_Pdf_Color_GrayScale(0.45));
//$page->drawRectangle(25, $top, 270, $top – 55);
//$page->setFillColor(new Zend_Pdf_Color_GrayScale(1));
$this->setDocHeaderCoordinates(array(25, $top, 570, $top – 55));
if ($putOrderId) {
$this->_setFontRegular($page, 14);
$page->drawText(
Mage::helper(‘sales’)->__(‘Packing Slip for Order ‘) . $order->getRealOrderId(), 300, ($top + 40), ‘UTF-8′
);
}
$page->setLineWidth(1);
$page->drawLine(300, 800, 570, 800);
/* $page->drawRectangle(25, $this->y, 100, $this->y-25);
$page->drawRectangle(100, $this->y, 175, $this->y-25);
*/
$this->_setFontRegular($page, 8);
$page->setFillColor(new Zend_Pdf_Color_Rgb(1, 1, 1));
$page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
$page->setLineWidth(1);
$page->drawRectangle(300, $top+15, 570, ($top +30));
$page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
$page->drawText(Mage::helper(‘sales’)->__(‘Checked By: Total Weight:0′), 315, ($top + 20), ‘UTF-8′);
$top -= 20;
$page->setFillColor(new Zend_Pdf_Color_Rgb(1, 1, 1));
$page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
$page->setLineWidth(1);
/* Shipping Address and Method */
if (!$order->getIsVirtual()) {
/* Shipping Address */
$shippingAddress = $this->_formatAddress($order->getShippingAddress()->format(‘pdf’));
$shippingMethod = $order->getShippingDescription();
}
$addressesHeight = $this->_calcAddressHeight($billingAddress);
if (isset($shippingAddress)) {
$addressesHeight = max($addressesHeight, $this->_calcAddressHeight($shippingAddress));
}
$page->drawRectangle(25, $top, 290, ($top – ($addressesHeight+60)));
$page->drawRectangle(300, $top, 570, ($top – ($addressesHeight+60)));
/* Calculate blocks info */
/* Billing Address */
$billingAddress = $this->_formatAddress($order->getBillingAddress()->format(‘pdf’));
/* Payment */
$paymentInfo = Mage::helper(‘payment’)->getInfoBlock($order->getPayment())
->setIsSecureMode(true)
->toPdf();
$paymentInfo = htmlspecialchars_decode($paymentInfo, ENT_QUOTES);
$payment = explode(‘{{pdf_row_separator}}’, $paymentInfo);
foreach ($payment as $key=>$value){
if (strip_tags(trim($value)) == ”) {
unset($payment[$key]);
}
}
reset($payment);
$page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
$this->_setFontRegular($page, 16);
$page->drawText(Mage::helper(‘sales’)->__(‘Delivery Address:’), 35, ($top – 15), ‘UTF-8′);
if (!$order->getIsVirtual()) {
$page->drawText(Mage::helper(‘sales’)->__(‘Billing Address:’), 305, ($top – 15), ‘UTF-8′);
} else {
$page->drawText(Mage::helper(‘sales’)->__(‘Payment Method:’), 285, ($top – 15), ‘UTF-8′);
}
$this->y = $top – 40;
$addressesStartY = $this->y;
$this->_setFontRegular($page, 12);
foreach ($shippingAddress as $value){
if ($value!==”) {
$text = array();
foreach (Mage::helper(‘core/string’)->str_split($value, 45, true, true) as $_value) {
$text[] = $_value;
}
foreach ($text as $part) {
$page->drawText(strip_tags(ltrim($part)), 35, $this->y, ‘UTF-8′);
$this->y -= 15;
}
}
}
$addressesEndY = $this->y;
if (!$order->getIsVirtual()) {
$this->y = $addressesStartY;
foreach ($billingAddress as $value){
if ($value !== ”) {
$text = array();
foreach (Mage::helper(‘core/string’)->str_split($value, 45, true, true) as $_value) {
$text[] = $_value;
}
foreach ($text as $part) {
$page->drawText(strip_tags(ltrim($part)), 305, $this->y, ‘UTF-8′);
$this->y -= 15;
}
}
}
$addressesEndY = min($addressesEndY, $this->y);
$this->y = $addressesEndY-25;
$page->setFillColor(new Zend_Pdf_Color_Html(‘#626E73′));
$page->setLineWidth(0.9);
$page->drawRectangle(25, $this->y, 570, $this->y-25);
$this->y -= 15;
$this->_setFontRegular($page, 10);
$page->setFillColor(new Zend_Pdf_Color_GrayScale(1));
$page->drawText(Mage::helper(‘sales’)->__(‘Invoice Number: Date Ordered: Payment Method: Shipping Method:’), 35, $this->y, ‘UTF-8′);
$this->y -=10;
$page->setFillColor(new Zend_Pdf_Color_GrayScale(1));
$this->_setFontRegular($page, 8);
$page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
$paymentLeft = 235;
$yPayments = $this->y – 15;
}
else {
$yPayments = $addressesStartY;
$paymentLeft = 285;
}
$page->drawText($order->getRealOrderId(), 35, $yPayments, ‘UTF-8′);
$page->drawText($order->getCreatedAtDate(), 120, $yPayments, ‘UTF-8′);
foreach ($payment as $value){
if (trim($value) != ”) {
//Printing “Payment Method” lines
$value = preg_replace(‘/]*>/i’, “\n”, $value);
foreach (Mage::helper(‘core/string’)->str_split($value, 45, true, true) as $_value) {
$page->drawText(strip_tags(trim($_value)), $paymentLeft, $yPayments, ‘UTF-8′);
$yPayments -= 15;
}
}
}
if ($order->getIsVirtual()) {
// replacement of Shipments-Payments rectangle block
$yPayments = min($addressesEndY, $yPayments);
$page->drawLine(25, ($top – 25), 25, $yPayments);
$page->drawLine(570, ($top – 25), 570, $yPayments);
$page->drawLine(25, $yPayments, 570, $yPayments);
$this->y = $yPayments – 15;
} else {
$topMargin = 15;
$methodStartY = $this->y;
$this->y -= 15;
foreach (Mage::helper(‘core/string’)->str_split($shippingMethod, 45, true, true) as $_value) {
$page->drawText(strip_tags(trim($_value)), 405, $this->y, ‘UTF-8′);
$this->y -= 15;
}
$yShipments = $this->y;
$totalShippingChargesText = “(” . Mage::helper(‘sales’)->__(‘Total Shipping Charges’) . ” ”
. $order->formatPriceTxt($order->getShippingAmount()) . “)”;
$page->drawText($totalShippingChargesText, 405, $yShipments – $topMargin, ‘UTF-8′);
$yShipments -= $topMargin + 10;
$tracks = array();
if ($shipment) {
$tracks = $shipment->getAllTracks();
}
if (count($tracks)) {
$page->setFillColor(new Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
$page->setLineWidth(0.5);
$page->drawRectangle(285, $yShipments, 510, $yShipments – 10);
$page->drawLine(400, $yShipments, 400, $yShipments – 10);
//$page->drawLine(510, $yShipments, 510, $yShipments – 10);
$this->_setFontRegular($page, 8);
$page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
//$page->drawText(Mage::helper(‘sales’)->__(‘Carrier’), 290, $yShipments – 7 , ‘UTF-8′);
$page->drawText(Mage::helper(‘sales’)->__(‘Title’), 290, $yShipments – 7, ‘UTF-8′);
$page->drawText(Mage::helper(‘sales’)->__(‘Number’), 405, $yShipments – 7, ‘UTF-8′);
$yShipments -= 20;
$this->_setFontRegular($page, 7);
foreach ($tracks as $track) {
$CarrierCode = $track->getCarrierCode();
if ($CarrierCode != ‘custom’) {
$carrier = Mage::getSingleton(‘shipping/config’)->getCarrierInstance($CarrierCode);
$carrierTitle = $carrier->getConfigData(‘title’);
} else {
$carrierTitle = Mage::helper(‘sales’)->__(‘Custom Value’);
}
//$truncatedCarrierTitle = substr($carrierTitle, 0, 35) . (strlen($carrierTitle) > 35 ? ‘…’ : ”);
$maxTitleLen = 45;
$endOfTitle = strlen($track->getTitle()) > $maxTitleLen ? ‘…’ : ”;
$truncatedTitle = substr($track->getTitle(), 0, $maxTitleLen) . $endOfTitle;
//$page->drawText($truncatedCarrierTitle, 285, $yShipments , ‘UTF-8′);
$page->drawText($truncatedTitle, 292, $yShipments , ‘UTF-8′);
$page->drawText($track->getNumber(), 405, $yShipments , ‘UTF-8′);
$yShipments -= $topMargin – 5;
}
} else {
$yShipments -= $topMargin – 5;
}
$currentY = min($yPayments, $yShipments);
// replacement of Shipments-Payments rectangle block
$page->drawLine(25, $methodStartY, 25, $currentY); //left
$page->drawLine(25, $currentY, 570, $currentY); //bottom
$page->drawLine(570, $currentY, 570, $methodStartY); //right
$this->y = $currentY+30;
$this->y -= 25;
}
}
/**
* Insert title and number for concrete document type
*
* @param Zend_Pdf_Page $page
* @param string $text
* @return void
*/
public function insertDocumentNumber(Zend_Pdf_Page $page, $text)
{
$page->setFillColor(new Zend_Pdf_Color_GrayScale(1));
$this->_setFontRegular($page, 9);
$docHeader = $this->getDocHeaderCoordinates();
$page->drawText($text, 35, $docHeader[1] – 15, ‘UTF-8′);
}
/**
* Sort totals list
*
* @param array $a
* @param array $b
* @return int
*/
protected function _sortTotalsList($a, $b) {
if (!isset($a['sort_order']) || !isset($b['sort_order'])) {
return 0;
}
if ($a['sort_order'] == $b['sort_order']) {
return 0;
}
return ($a['sort_order'] > $b['sort_order']) ? 1 : -1;
}
/**
* Return total list
*
* @param Mage_Sales_Model_Abstract $source
* @return array
*/
protected function _getTotalsList($source)
{
$totals = Mage::getConfig()->getNode(‘global/pdf/totals’)->asArray();
usort($totals, array($this, ‘_sortTotalsList’));
$totalModels = array();
foreach ($totals as $index => $totalInfo) {
if (!empty($totalInfo['model'])) {
$totalModel = Mage::getModel($totalInfo['model']);
if ($totalModel instanceof Mage_Sales_Model_Order_Pdf_Total_Default) {
$totalInfo['model'] = $totalModel;
} else {
Mage::throwException(
Mage::helper(‘sales’)->__(‘PDF total model should extend Mage_Sales_Model_Order_Pdf_Total_Default’)
);
}
} else {
$totalModel = Mage::getModel($this->_defaultTotalModel);
}
$totalModel->setData($totalInfo);
$totalModels[] = $totalModel;
}
return $totalModels;
}
/**
* Insert totals to pdf page
*
* @param Zend_Pdf_Page $page
* @param Mage_Sales_Model_Abstract $source
* @return Zend_Pdf_Page
*/
protected function insertTotals($page, $source){
$order = $source->getOrder();
$totals = $this->_getTotalsList($source);
$lineBlock = array(
‘lines’ => array(),
‘height’ => 15
);
foreach ($totals as $total) {
$total->setOrder($order)
->setSource($source);
if ($total->canDisplay()) {
$total->setFontSize(10);
foreach ($total->getTotalsForDisplay() as $totalData) {
$lineBlock['lines'][] = array(
array(
‘text’ => $totalData['label'],
‘feed’ => 475,
‘align’ => ‘right’,
‘font_size’ => $totalData['font_size'],
‘font’ => ‘bold’
),
array(
‘text’ => $totalData['amount'],
‘feed’ => 565,
‘align’ => ‘right’,
‘font_size’ => $totalData['font_size'],
‘font’ => ‘bold’
),
);
}
}
}
$this->y -= 20;
$page = $this->drawLineBlocks($page, array($lineBlock));
return $page;
}
/**
* Parse item description
*
* @param Varien_Object $item
* @return array
*/
protected function _parseItemDescription($item)
{
$matches = array();
$description = $item->getDescription();
if (preg_match_all(‘/ (.*?)<\/li>/i’, $description, $matches)) {
return $matches[1];
}
return array($description);
}
/**
* Before getPdf processing
*/
protected function _beforeGetPdf() {
$translate = Mage::getSingleton(‘core/translate’);
/* @var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
}
/**
* After getPdf processing
*/
protected function _afterGetPdf() {
$translate = Mage::getSingleton(‘core/translate’);
/* @var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(true);
}
/**
* Format option value process
*
* @param array|string $value
* @param Mage_Sales_Model_Order $order
* @return string
*/
protected function _formatOptionValue($value, $order)
{
$resultValue = ”;
if (is_array($value)) {
if (isset($value['qty'])) {
$resultValue .= sprintf(‘%d’, $value['qty']) . ‘ x ‘;
}
$resultValue .= $value['title'];
if (isset($value['price'])) {
$resultValue .= ” ” . $order->formatPrice($value['price']);
}
return $resultValue;
} else {
return $value;
}
}
/**
* Initialize renderer process
*
* @param string $type
*/
protected function _initRenderer($type)
{
$node = Mage::getConfig()->getNode(‘global/pdf/’ . $type);
foreach ($node->children() as $renderer) {
$this->_renderers[$renderer->getName()] = array(
‘model’ => (string)$renderer,
‘renderer’ => null
);
}
}
/**
* Retrieve renderer model
*
* @param string $type
* @throws Mage_Core_Exception
* @return Mage_Sales_Model_Order_Pdf_Items_Abstract
*/
protected function _getRenderer($type)
{
if (!isset($this->_renderers[$type])) {
$type = ‘default’;
}
if (!isset($this->_renderers[$type])) {
Mage::throwException(Mage::helper(‘sales’)->__(‘Invalid renderer model’));
}
if (is_null($this->_renderers[$type]['renderer'])) {
$this->_renderers[$type]['renderer'] = Mage::getSingleton($this->_renderers[$type]['model']);
}
return $this->_renderers[$type]['renderer'];
}
/**
* Public method of protected @see _getRenderer()
*
* Retrieve renderer model
*
* @param string $type
* @return Mage_Sales_Model_Order_Pdf_Items_Abstract
*/
public function getRenderer($type)
{
return $this->_getRenderer($type);
}
/**
* Draw Item process
*
* @param Varien_Object $item
* @param Zend_Pdf_Page $page
* @param Mage_Sales_Model_Order $order
* @return Zend_Pdf_Page
*/
protected function _drawItem(Varien_Object $item, Zend_Pdf_Page $page, Mage_Sales_Model_Order $order)
{
$type = $item->getOrderItem()->getProductType();
$renderer = $this->_getRenderer($type);
//echo “
";

  //print_r($renderer);die;
        $renderer->setOrder($order);

        $renderer->setItem($item);

        $renderer->setPdf($this);
$renderer->setPage($page); $renderer->setRenderedModel($this);
$renderer->draw(); return $renderer->getPage(); }
/** * Set font as regular * * @param Zend_Pdf_Page $object * @param int $size * @return Zend_Pdf_Resource_Font */ protected function _setFontRegular($object, $size = 7) { $font = Zend_Pdf_Font::fontWithPath(Mage::getBaseDir() . '/lib/Arial/Arial.ttf'); $object->setFont($font, $size); return $font; }
/** * Set font as bold * * @param Zend_Pdf_Page $object * @param int $size * @return Zend_Pdf_Resource_Font */ protected function _setFontBold($object, $size = 7) { $font = Zend_Pdf_Font::fontWithPath(Mage::getBaseDir() . '/lib/LinLibertineFont/LinLibertine_Bd-2.8.1.ttf'); $object->setFont($font, $size); return $font; }
/** * Set font as italic * * @param Zend_Pdf_Page $object * @param int $size * @return Zend_Pdf_Resource_Font */ protected function _setFontItalic($object, $size = 7) { $font = Zend_Pdf_Font::fontWithPath(Mage::getBaseDir() . '/lib/LinLibertineFont/LinLibertine_It-2.8.2.ttf'); $object->setFont($font, $size); return $font; }
/** * Set PDF object * * @param Zend_Pdf $pdf * @return Mage_Sales_Model_Order_Pdf_Abstract */ protected function _setPdf(Zend_Pdf $pdf) { $this->_pdf = $pdf; return $this; }
/** * Retrieve PDF object * * @throws Mage_Core_Exception * @return Zend_Pdf */ protected function _getPdf() { if (!$this->_pdf instanceof Zend_Pdf) { Mage::throwException(Mage::helper('sales')->__('Please define PDF object before using.')); }
return $this->_pdf; }
/** * Create new page and assign to PDF object * * @param array $settings * @return Zend_Pdf_Page */ public function newPage(array $settings = array()) { $pageSize = !empty($settings['page_size']) ? $settings['page_size'] : Zend_Pdf_Page::SIZE_A4; $page = $this->_getPdf()->newPage($pageSize); $this->_getPdf()->pages[] = $page; $this->y = 800;
return $page; }
/** * Draw lines * * draw items array format: * lines array;array of line blocks (required) * shift int; full line height (optional) * height int;line spacing (default 10) * * line block has line columns array * * column array format * text string|array; draw text (required) * feed int; x position (required) * font string; font style, optional: bold, italic, regular * font_file string; path to font file (optional for use your custom font) * font_size int; font size (default 7) * align string; text align (also see feed parametr), optional left, right * height int;line spacing (default 10) * * @param Zend_Pdf_Page $page * @param array $draw * @param array $pageSettings * @throws Mage_Core_Exception * @return Zend_Pdf_Page */ public function drawLineBlocks(Zend_Pdf_Page $page, array $draw, array $pageSettings = array()) { foreach ($draw as $itemsProp) { if (!isset($itemsProp['lines']) || !is_array($itemsProp['lines'])) { Mage::throwException(Mage::helper('sales')->__('Invalid draw line data. Please define "lines" array.')); } $lines = $itemsProp['lines']; $height = isset($itemsProp['height']) ? $itemsProp['height'] : 10;
if (empty($itemsProp['shift'])) { $shift = 0; foreach ($lines as $line) { $maxHeight = 0; foreach ($line as $column) { $lineSpacing = !empty($column['height']) ? $column['height'] : $height; if (!is_array($column['text'])) { $column['text'] = array($column['text']); } $top = 0; foreach ($column['text'] as $part) { $top += $lineSpacing; }
$maxHeight = $top > $maxHeight ? $top : $maxHeight; } $shift += $maxHeight; } $itemsProp['shift'] = $shift; }
if ($this->y - $itemsProp['shift'] < 15) { $page = $this->newPage($pageSettings); }
foreach ($lines as $line) { $maxHeight = 0; foreach ($line as $column) { $fontSize = empty($column['font_size']) ? 10 : $column['font_size']; if (!empty($column['font_file'])) { $font = Zend_Pdf_Font::fontWithPath($column['font_file']); $page->setFont($font, $fontSize); } else { $fontStyle = empty($column['font']) ? 'regular' : $column['font']; switch ($fontStyle) { case 'bold': $font = $this->_setFontBold($page, $fontSize); break; case 'italic': $font = $this->_setFontItalic($page, $fontSize); break; default: $font = $this->_setFontRegular($page, $fontSize); break; } }
if (!is_array($column['text'])) { $column['text'] = array($column['text']); }
$lineSpacing = !empty($column['height']) ? $column['height'] : $height; $top = 0; foreach ($column['text'] as $part) { if ($this->y - $lineSpacing < 15) { $page = $this->newPage($pageSettings); }
$feed = $column['feed']; $textAlign = empty($column['align']) ? 'left' : $column['align']; $width = empty($column['width']) ? 0 : $column['width']; switch ($textAlign) { case 'right': if ($width) { $feed = $this->getAlignRight($part, $feed, $width, $font, $fontSize); } else { $feed = $feed - $this->widthForStringUsingFontSize($part, $font, $fontSize); } break; case 'center': if ($width) { $feed = $this->getAlignCenter($part, $feed, $width, $font, $fontSize); } break; } $page->drawText($part, $feed, $this->y-$top, 'UTF-8'); $top += $lineSpacing; }
$maxHeight = $top > $maxHeight ? $top : $maxHeight; } $this->y -= $maxHeight; } }
return $page; } }
app/code/local/mage/sales/model/order/pdf/shipment.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_Sales
* @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Sales Order Shipment PDF model
*
* @category Mage
* @package Mage_Sales
* @author Magento Core Team
*/
class Mage_Sales_Model_Order_Pdf_Shipment extends Mage_Sales_Model_Order_Pdf_Abstract
{
/**
* Draw table header for product items
*
* @param Zend_Pdf_Page $page
* @return void
*/
protected function _drawHeader(Zend_Pdf_Page $page)
{
/* Add table head */
$this->y -= 25;
$this->_setFontRegular($page, 8);
$page->setFillColor(new Zend_Pdf_Color_Html('#626E73'));
$page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
$page->setLineWidth(0.8);
$page->drawRectangle(25, $this->y, 570, $this->y-15);
$this->y -= 10;
$page->setFillColor(new Zend_Pdf_Color_RGB(1, 1, 1));
//columns headers
$lines[0][] = array(
'text' => Mage::helper('sales')->__('Products'),
'feed' => 110,
);
$lines[0][] = array(
'text' => Mage::helper('sales')->__('Qty'),
'feed' => 35
);
$lines[0][] = array(
'text' => Mage::helper('sales')->__('Reference no'),
'feed' => 500
);
// $lines[0][] = array(
// 'text' => Mage::helper('sales')->__('Weight(Kgs)'),
// 'feed' => 360,
// );
// $lines[0][] = array(
// 'text' => Mage::helper('sales')->__('Check'),
// 'feed' => 440,
// );
$lineBlock = array(
'lines' => $lines,
'height' => 10
);
$this->drawLineBlocks($page, array($lineBlock), array('table_header' => true));
$page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
$this->y -= 6;
}
/**
* Return PDF document
*
* @param array $shipments
* @return Zend_Pdf
*/
public function getPdf($shipments = array())
{
$this->_beforeGetPdf();
$this->_initRenderer('shipment');
$pdf = new Zend_Pdf();
$this->_setPdf($pdf);
$style = new Zend_Pdf_Style();
$this->_setFontRegular($style, 10);
foreach ($shipments as $shipment) {
if ($shipment->getStoreId()) {
Mage::app()->getLocale()->emulate($shipment->getStoreId());
Mage::app()->setCurrentStore($shipment->getStoreId());
}
$page = $this->newPage();
$page->setLineWidth(6);
$page->drawLine(5, 835, 590, 835);
$order = $shipment->getOrder();
/* Add image */
$this->insertLogo($page, $shipment->getStore());
/* Add address */
$this->insertAddress($page, $shipment->getStore());
/* Add head */
$this->insertOrder(
$page,
$shipment,
Mage::getStoreConfigFlag(self::XML_PATH_SALES_PDF_SHIPMENT_PUT_ORDER_ID, $order->getStoreId())
);
/* Add document text and number */
/*$this->insertDocumentNumber(
$page,
Mage::helper('sales')->__('Packingslip # ') . $shipment->getIncrementId()
);*/
/* Add table */
$this->_drawHeader($page);
/* Add body */
foreach ($shipment->getAllItems() as $item) {
if ($item->getOrderItem()->getParentItem()) {
continue;
}
/* Draw item */
//echo $this->y;die;
$this->_drawItem($item, $page, $order);
$page = end($pdf->pages);
$page->drawLine(25, $this->y+60, 25, $this->y+10);
$page->drawLine(80, $this->y+50, 80, $this->y+10);
$page->drawLine(460,$this->y+50, 460, $this->y+10);
$page->drawLine(570, $this->y+60, 570, $this->y+10);
//$page->drawLine(360, $i, 360, $i+75);
//$page->drawLine(420, $i, 420, $i+75);
$page->drawLine(25, $this->y+10, 570,$this->y+10);
}
$reqHeight = 20;
$page->drawText(Mage::helper('sales')->__("Please contact the Customer Service department at 0121 308 0842 with any questions or concerns."), 25, $reqHeight, 'UTF-8');
$page->setLineWidth(2);
//$page->drawLine(5, 830, 590, 830);
$page->drawLine(5,$reqHeight-15, 590,$reqHeight-15);
}
$this->_afterGetPdf();
if ($shipment->getStoreId()) {
Mage::app()->getLocale()->revert();
}
return $pdf;
}
/**
* Create new page and assign to PDF object
*
* @param array $settings
* @return Zend_Pdf_Page
*/
public function newPage(array $settings = array())
{
/* Add new table head */
$page = $this->_getPdf()->newPage(Zend_Pdf_Page::SIZE_A4);
$this->_getPdf()->pages[] = $page;
$this->y = 800;
if (!empty($settings['table_header'])) {
$this->_drawHeader($page);
}
return $page;
}
}
app/code/local/mage/sales/model/order/pdf/Items/Shipment/Default.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_Sales
* @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Sales Order Shipment Pdf default items renderer
*
* @category Mage
* @package Mage_Sales
* @author Magento Core Team
*/
class Mage_Sales_Model_Order_Pdf_Items_Shipment_Default extends Mage_Sales_Model_Order_Pdf_Items_Abstract
{
/**
* Draw item line
*/
public function draw()
{
$item = $this->getItem();
$pdf = $this->getPdf();
$page = $this->getPage();
$lines = array();
$fontSize = 8;
// draw Product name
$lines[0] = array(array(
'text' => Mage::helper('core/string')->str_split($item->getName(), 100, true, true),
'feed' => 100,
'font_size' => $fontSize
));
// draw QTY
$lines[0][] = array(
'text' => $item->getQty()*1,
'feed' => 35,
'font_size' => $fontSize,
);
// draw SKU
$lines[0][] = array(
'text' => Mage::helper('core/string')->str_split($this->getSku($item),25),
'feed' => 460,
'align' => 'left',
'font_size' => $fontSize
);
// Custom options
$options = $this->getItemOptions();
if ($options) {
foreach ($options as $option) {
// draw options label
if ($option['label'])
{
$lines[][] = array(
'text' => Mage::helper('core/string')->str_split(strip_tags($option['label'].' - '.$option['value']), 170, true, true),
'feed' => 100,
'font_size' => $fontSize
);
}
}
// draw options value
// if ($option['value']) {
// $_printValue = isset($option['print_value'])
// ? $option['print_value']
// : strip_tags($option['value']);
// $values = explode(', ', $_printValue);
// foreach ($values as $value) {
//
// $lines[][] = array(
// 'text' => Mage::helper('core/string')->str_split($value, 50, true, true),
// 'feed' => 115
// );
// }
// }
}
else {
$lines[][] = array(
'text' => Mage::helper('core/string')->str_split('-', 170, true, true),
'feed' => 100
);
}
$lineBlock = array(
'lines' => $lines,
'height' => 20
);
$page = $pdf->drawLineBlocks($page, array($lineBlock), array('table_header' => true));
$this->setPage($page);
}
}

Delete pending_payment order status from magento

Here is the code for delete pending_payment orders from orders grid.
<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
Varien_Profiler::enable();
umask(0);
Mage::app('default');
Mage::register('isSecureArea', 1);
//until here you gained access to the Magento models. The rest is custom code
$orderCollection = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter(‘status’,'pending_payment’);
$orderIds = array();
$IncrementIds = array();
foreach($orderCollection as $order) {
$orderIds[] = $order->getEntityId();
$IncrementIds[] = $order->getIncrementId();
}
$flag = false;
$write = Mage::getSingleton(‘core/resource’)->getConnection(‘core_write’);
$query=”show tables”;
$rsc_table=$write->fetchCol($query);
$table_sales_flat_order = Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_order’);
$table_sales_flat_creditmemo_comment= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_creditmemo_comment’);
$table_sales_flat_creditmemo_item= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_creditmemo_item’);
$table_sales_flat_creditmemo= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_creditmemo’);
$table_sales_flat_creditmemo_grid= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_creditmemo_grid’);
$table_sales_flat_invoice_comment= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_invoice_comment’);
$table_sales_flat_invoice_item= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_invoice_item’);
$table_sales_flat_invoice= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_invoice’);
$table_sales_flat_invoice_grid= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_invoice_grid’);
$table_sales_flat_quote_address_item= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_quote_address_item’);
$table_sales_flat_quote_item_option= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_quote_item_option’);
$table_sales_flat_quote= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_quote’);
$table_sales_flat_quote_address= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_quote_address’);
$table_sales_flat_quote_item= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_quote_item’);
$table_sales_flat_quote_payment= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_quote_payment’);
$table_sales_flat_shipment_comment= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_shipment_comment’);
$table_sales_flat_shipment_item= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_shipment_item’);
$table_sales_flat_shipment_track= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_shipment_track’);
$table_sales_flat_shipment= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_shipment’);
$table_sales_flat_shipment_grid= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_shipment_grid’);
$table_sales_flat_order_address= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_order_address’);
$table_sales_flat_order_item= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_order_item’);
$table_sales_flat_order_payment= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_order_payment’);
$table_sales_flat_order_status_history= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_order_status_history’);
$table_sales_flat_order_grid= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_order_grid’);
$table_log_quote= Mage::getSingleton(‘core/resource’)->getTableName(‘log_quote’);
$quoteId=”;
if (!empty($orderIds)) {
$i=0;
foreach ($orderIds as $orderId) {
$query=null;
if($orderId){
///@jbn group order checking whether it is canceled or not//////
$mk_order = Mage::getModel(‘sales/order’)->loadByIncrementId($IncrementIds[$i]);
$mk_items = $mk_order->getAllVisibleItems();
foreach ($mk_items as $mk_itemId => $mk_item)
{ //echo $mk_item->getSku();
//echo $mk_item->getStatus();
if($mk_item->getStatus()==”Ordered”)
{
$mk_product_sku = $mk_item->getSku();
$mk_product_ordered_qty = $mk_item->getQtyToInvoice();
$mk_product = Mage::getModel(‘catalog/product’)->loadByAttribute(‘sku’,$mk_product_sku);
if ($mk_product)
{
$mk_stockItem =Mage::getModel(‘cataloginventory/stock_item’)->loadByProduct($mk_product->getId());
$mk_stockItem->setData(‘qty’, $mk_stockItem->getQty() + $mk_product_ordered_qty);
$mk_stockItem->setData(‘is_in_stock’,1);
$mk_stockItem->save();
}
}
}
/////end order checking////////////////////////////////
/*$query=”show tables like ‘sales_flat_order’”;
$rs=$write->fetchAll($query);*/
$incId=$IncrementIds[$i];
if(in_array($table_sales_flat_order,$rsc_table)){
$query=’SELECT entity_id FROM ‘.$table_sales_flat_order.’ WHERE increment_id=”‘.mysql_escape_string($incId).’”‘;
$rs=$write->fetchAll($query);
$query=’SELECT quote_id FROM ‘.$table_sales_flat_order.’ WHERE entity_id=”‘.mysql_escape_string($orderId).’”‘;
$rs1=$write->fetchAll($query);
$quoteId=$rs1[0]['quote_id'];
}
$query=’SET FOREIGN_KEY_CHECKS=1′;
$rs3=$write->query($query);
//print_r($rsc_table);
////echo $table_sales_flat_creditmemo_comment;
if(in_array($table_sales_flat_creditmemo_comment,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_creditmemo_comment.” WHERE parent_id IN (SELECT entity_id FROM “.$table_sales_flat_creditmemo.” WHERE order_id=”.$orderId.”)”;
//die;
$write->query(“DELETE FROM “.$table_sales_flat_creditmemo_comment.” WHERE parent_id IN (SELECT entity_id FROM “.$table_sales_flat_creditmemo.” WHERE order_id=’”.mysql_escape_string($orderId).”‘)”);
}
//die;
if(in_array(‘sales_flat_creditmemo_item’,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_creditmemo_item.” WHERE parent_id IN (SELECT entity_id FROM “.$table_sales_flat_creditmemo.” WHERE order_id=’”.mysql_escape_string($orderId).”‘)”;
$write->query(“DELETE FROM “.$table_sales_flat_creditmemo_item.” WHERE parent_id IN (SELECT entity_id FROM “.$table_sales_flat_creditmemo.” WHERE order_id=’”.mysql_escape_string($orderId).”‘)”);
}
if(in_array($table_sales_flat_creditmemo,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_creditmemo.” WHERE order_id=’”.mysql_escape_string($orderId).”‘”;
$write->query(“DELETE FROM “.$table_sales_flat_creditmemo.” WHERE order_id=’”.mysql_escape_string($orderId).”‘”);
}
if(in_array($table_sales_flat_creditmemo_grid,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_creditmemo_grid.” WHERE order_id=’”.mysql_escape_string($orderId).”‘”;
$write->query(“DELETE FROM “.$table_sales_flat_creditmemo_grid.” WHERE order_id=’”.mysql_escape_string($orderId).”‘”);
}
if(in_array($table_sales_flat_invoice_comment,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_invoice_comment.” WHERE parent_id IN (SELECT entity_id FROM “.$table_sales_flat_invoice.” WHERE order_id=’”.mysql_escape_string($orderId).”‘)”;
$write->query(“DELETE FROM “.$table_sales_flat_invoice_comment.” WHERE parent_id IN (SELECT entity_id FROM “.$table_sales_flat_invoice.” WHERE order_id=’”.mysql_escape_string($orderId).”‘)”);
}
if(in_array($table_sales_flat_invoice_item,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_invoice_item.” WHERE parent_id IN (SELECT entity_id FROM “.$table_sales_flat_invoice.” WHERE order_id=’”.mysql_escape_string($orderId).”‘)”;
$write->query(“DELETE FROM “.$table_sales_flat_invoice_item.” WHERE parent_id IN (SELECT entity_id FROM “.$table_sales_flat_invoice.” WHERE order_id=’”.mysql_escape_string($orderId).”‘)”);
}
if(in_array($table_sales_flat_invoice,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_invoice.” WHERE order_id=’”.mysql_escape_string($orderId).”‘”;
$write->query(“DELETE FROM “.$table_sales_flat_invoice.” WHERE order_id=’”.mysql_escape_string($orderId).”‘”);
}
if(in_array($table_sales_flat_invoice_grid,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_invoice_grid.” WHERE order_id=’”.mysql_escape_string($orderId).”‘”;
$write->query(“DELETE FROM “.$table_sales_flat_invoice_grid.” WHERE order_id=’”.mysql_escape_string($orderId).”‘”);
}
if($quoteId){
if(in_array($table_sales_flat_quote_address_item,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_quote_address_item.” WHERE parent_item_id IN (SELECT address_id FROM “.$table_sales_flat_quote_address.” WHERE quote_id=”.$quoteId.”)”;
$write->query(“DELETE FROM “.$table_sales_flat_quote_address_item.” WHERE parent_item_id IN (SELECT address_id FROM “.$table_sales_flat_quote_address.” WHERE quote_id=”.$quoteId.”)”);
}
$table_sales_flat_quote_shipping_rate= Mage::getSingleton(‘core/resource’)->getTableName(‘sales_flat_quote_shipping_rate’);
if(in_array($table_sales_flat_quote_shipping_rate,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_quote_shipping_rate.” WHERE address_id IN (SELECT address_id FROM “.$table_sales_flat_quote_address.” WHERE quote_id=”.$quoteId.”)”;
$write->query(“DELETE FROM “.$table_sales_flat_quote_shipping_rate.” WHERE address_id IN (SELECT address_id FROM “.$table_sales_flat_quote_address.” WHERE quote_id=”.$quoteId.”)”);
}
if(in_array($table_sales_flat_quote_item_option,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_quote_item_option.” WHERE item_id IN (SELECT item_id FROM “.$table_sales_flat_quote_item.” WHERE quote_id=”.$quoteId.”)”;
$write->query(“DELETE FROM “.$table_sales_flat_quote_item_option.” WHERE item_id IN (SELECT item_id FROM “.$table_sales_flat_quote_item.” WHERE quote_id=”.$quoteId.”)”);
}
if(in_array($table_sales_flat_quote,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_quote.” WHERE entity_id=”.$quoteId;
$write->query(“DELETE FROM “.$table_sales_flat_quote.” WHERE entity_id=”.$quoteId);
}
if(in_array($table_sales_flat_quote_address,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_quote_address.” WHERE quote_id=”.$quoteId;
$write->query(“DELETE FROM “.$table_sales_flat_quote_address.” WHERE quote_id=”.$quoteId);
}
if(in_array($table_sales_flat_quote_item,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_quote_item.” WHERE quote_id=”.$quoteId;
$write->query(“DELETE FROM “.$table_sales_flat_quote_item.” WHERE quote_id=”.$quoteId);
}
if(in_array(‘sales_flat_quote_payment’,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_quote_payment.” WHERE quote_id=”.$quoteId;
$write->query(“DELETE FROM “.$table_sales_flat_quote_payment.” WHERE quote_id=”.$quoteId);
}
}
if(in_array($table_sales_flat_shipment_comment,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_shipment_comment.” WHERE parent_id IN (SELECT entity_id FROM “.$table_sales_flat_shipment.” WHERE order_id=’”.mysql_escape_string($orderId).”‘)”;
$write->query(“DELETE FROM “.$table_sales_flat_shipment_comment.” WHERE parent_id IN (SELECT entity_id FROM “.$table_sales_flat_shipment.” WHERE order_id=’”.mysql_escape_string($orderId).”‘)”);
}
if(in_array($table_sales_flat_shipment_item,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_shipment_item.” WHERE parent_id IN (SELECT entity_id FROM “.$table_sales_flat_shipment.” WHERE order_id=’”.mysql_escape_string($orderId).”‘)”;
$write->query(“DELETE FROM “.$table_sales_flat_shipment_item.” WHERE parent_id IN (SELECT entity_id FROM “.$table_sales_flat_shipment.” WHERE order_id=’”.mysql_escape_string($orderId).”‘)”);
}
if(in_array($table_sales_flat_shipment_track,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_shipment_track.” WHERE order_id IN (SELECT entity_id FROM “.$table_sales_flat_shipment.” WHERE order_id=’”.mysql_escape_string($orderId).”‘)”;
$write->query(“DELETE FROM “.$table_sales_flat_shipment_track.” WHERE order_id IN (SELECT entity_id FROM “.$table_sales_flat_shipment.” WHERE order_id=’”.mysql_escape_string($orderId).”‘)”);
}
if(in_array($table_sales_flat_shipment,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_shipment.” WHERE order_id=’”.mysql_escape_string($orderId).”‘”;
$write->query(“DELETE FROM “.$table_sales_flat_shipment.” WHERE order_id=’”.mysql_escape_string($orderId).”‘”);
}
if(in_array($table_sales_flat_shipment_grid,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_shipment_grid.” WHERE order_id=’”.mysql_escape_string($orderId).”‘”;
$write->query(“DELETE FROM “.$table_sales_flat_shipment_grid.” WHERE order_id=’”.mysql_escape_string($orderId).”‘”);
}
if(in_array($table_sales_flat_order,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_order.” WHERE entity_id=’”.mysql_escape_string($orderId).”‘”;
$write->query(“DELETE FROM “.$table_sales_flat_order.” WHERE entity_id=’”.mysql_escape_string($orderId).”‘”);
}
if(in_array($table_sales_flat_order_address,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_order_address.” WHERE parent_id=’”.mysql_escape_string($orderId).”‘”;
$write->query(“DELETE FROM “.$table_sales_flat_order_address.” WHERE parent_id=’”.mysql_escape_string($orderId).”‘”);
}
if(in_array($table_sales_flat_order_item,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_order_item.” WHERE order_id=’”.mysql_escape_string($orderId).”‘”;
$write->query(“DELETE FROM “.$table_sales_flat_order_item.” WHERE order_id=’”.mysql_escape_string($orderId).”‘”);
}
if(in_array($table_sales_flat_order_payment,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_order_payment.” WHERE parent_id=’”.mysql_escape_string($orderId).”‘”;
$write->query(“DELETE FROM “.$table_sales_flat_order_payment.” WHERE parent_id=’”.mysql_escape_string($orderId).”‘”);
}
if(in_array($table_sales_flat_order_status_history,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_order_status_history.” WHERE parent_id=’”.mysql_escape_string($orderId).”‘”;
$write->query(“DELETE FROM “.$table_sales_flat_order_status_history.” WHERE parent_id=’”.mysql_escape_string($orderId).”‘”);
}
if($incId&&in_array($table_sales_flat_order_grid,$rsc_table)){
//echo “
DELETE FROM “.$table_sales_flat_order_grid.” WHERE increment_id=’”.mysql_escape_string($incId).”‘”;
$write->query(“DELETE FROM “.$table_sales_flat_order_grid.” WHERE increment_id=’”.mysql_escape_string($incId).”‘”);
}
$query=”show tables like ‘%”.$table_log_quote.”‘”;
//echo $query;
$rsc_table_l=$write->fetchCol($query);
if($quoteId&&$rsc_table_l){
//echo “
DELETE FROM “.$table_log_quote.” WHERE quote_id=”.$quoteId;
$write->query(“DELETE FROM “.$table_log_quote.” WHERE quote_id=”.$quoteId);
}
$write->query(“SET FOREIGN_KEY_CHECKS=1″);
}
$i++;}
}
///////////end
?>

How to create a custom grid from scratch

 inchoo orders
http://inchoo.net/ecommerce/magento/how-to-create-a-custom-grid-from-scratch/