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 ;