How to create a category and add an image programatically - magento-1.7

I've written a script that creates a category and adds a thumbnail image. It is inserted in the database but the thumbnail is not displayed.
When I upload from the backend it works fine.
This is my code.
<?php
require_once 'businessclasses.php';
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(1); // Mage_Core_Model_App::ADMIN_STORE_ID
$count = 0;
importRootCategories('us', '1/31/32', 4);
function importRootCategories($language, $path, $storeID)
{
$data = new getCSV();
$rows = $data->getRootCategories(); // Gets the list of root categories.
foreach($rows as $row) {
$categoryName = utf8_decode(iconv('ISO-8859-1','UTF-8',strip_tags(trim($row[$language])))); // Name of Category
if($language == "us") {
if($row[$language] == "")
$categoryName = utf8_decode(iconv('ISO-8859-1','UTF-8',strip_tags(trim($row["en"])))); // Name of Category
}
// Create category object
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeID); // 'US-Store' store is assigned to this category
$rootCategory['name'] = $categoryName;
$rootCategory['path'] = $path; // this is the catgeory path - 1 for root category
$rootCategory['display_mode'] = "PRODUCTS";
$rootCategory['include_in_menu'] = 1;
$rootCategory['is_active'] = 1;
$rootCategory['is_anchor'] = 1;
$rootCategory['thumbnail'] = _getCategoryImageFile($row['catimg'].'.jpg');
$category->addData($rootCategory);
try {
$category->save();
echo $rootCategoryId = $category->getId();
}
catch (Exception $e){
echo $e->getMessage();
}
}
}
function _getCategoryImageFile($filename)
{
$filePath = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'category' . DS . $filename;
$fileUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'import/category/'. $filename;
$imageUrl=file_get_contents($imageUrl);
$file_handler=fopen($filePath,'w');
if(fwrite($file_handler,$fileUrl)==false){
Mage::log('ERROR: ', null,'error');
}
else{
Mage::log('Image Created Successfully', null, '');
}
fclose($file_handler);
return $filename;
}
?>

Related

Magento2: how to get the SKUs from the serialized condition in cart price rules

I need to get the SKUs from cart price rule to assign a specific attribute to them, but the condition is saved in the database serialized, and I want to make foreach loop to extract all the SKU's from the serialized condition :
?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/../app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$objrules = $obj->create('Magento\SalesRule\Model\RuleFactory')->create();
$rules = $objrules->getCollection()->addFieldToFilter("is_active", "1");
foreach ($rules as $rule) {
echo $rule->getConditionsSerialized() . "\n";
}
and the result of the serialized condition is:
{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Combine","attribute":null,"operator":null,"value":1,"is_value_processed":null,"aggregator":"all","conditions":[{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Product\\Subselect","attribute":"qty","operator":">=","value":"1","is_value_processed":null,"aggregator":"any","conditions":[{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Product","attribute":"sku","operator":"==","value":"100817069","is_value_processed":false,"attribute_scope":null},{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Product","attribute":"sku","operator":"==","value":"100817051","is_value_processed":false,"attribute_scope":null},{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Product","attribute":"sku","operator":"==","value":"100817561","is_value_processed":false,"attribute_scope":null},{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Product","attribute":"sku","operator":"==","value":"100817579","is_value_processed":false,"attribute_scope":null}]}]}
so, how can we extract all the SKU's from this condition.
thanks in advance.
try something like this:
<?php
ini_set('display_errors', '1');
ini_set('error_reporting', E_ALL);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/../app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$objrules = $obj->create('Magento\SalesRule\Model\RuleFactory')->create();
$rules = $objrules->getCollection()->addFieldToFilter("is_active", "1");
$skus = [];
if ($rules) {
foreach ($rules as $rule) {
$ruleData = $rule->getConditionsSerialized();
if ($ruleData) {
$ruleDataArray = json_decode($ruleData, true);
if (isset($ruleDataArray['conditions'])) {
$conditions = $ruleDataArray['conditions'];
foreach ($conditions as $condition) {
if (isset($condition['conditions'])) {
$productConditions = $condition['conditions'];
foreach ($productConditions as $productCondition) {
if (isset($productCondition['value'])) {
$skuValues = $productCondition['value'];
$skuValues = explode(",",$skuValues);
foreach ($skuValues as $skuValue) {
$skus[] = $skuValue;
}
}
}
}
}
}
}
}
}
$uniqSkus = array_unique($skus);
print_r($uniqSkus);
exit;

SugarCRM 6.5 How to print php template?

I am newly SugarCRM 6.5 developer, I have write view.detail.php file and controller file. How to print template controller action json data php template. please help me. I have create controller and view.details code below.
Controller
protected function action_printinvoice(){
global $current_user, $db, $region;
$db = DBManagerFactory::getInstance();
$id = $_POST['record'];
$sql = "select gn.client_name, gn.client_address, gn.client_address_city, gn.client_address_state, gn.client_address_country, gn.client_address_postalcode, gn.id, gn.recipient_name, gn.recipient_address_city, gn.recipient_address_state, gn.recipient_address_country, gn.recipient_address_postalcode, gn.recipient_address, gn.recipient_vat_id, gn.recipient_tax_no, gn.recipient_name, gn.invoice_number as ginvo_client_invoice_id, "
. " gcstm.* "
. "from ginvo_client_invoice as gn "
. " inner join ginvo_client_invoice_cstm as gcstm on gn.id=gcstm.id_c "
. "where "
. " gn.deleted=0 and gn.id='".$id."' limit 1 ";
$result = $db->query($sql);
$ginv_invoice_ary=array();
while($row = $db->fetchByAssoc($result) ) {
$ginv_invoice_ary[]=$row;
}
if ($ginv_invoice_ary[0]['region_c'] == 'non_eu_client_and_freelancer_provider') {
$region = 'Non EU client and freelancer provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'non_eu_client_and_employed_provider'){
$region = 'Non EU client and employed provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'german_client_and_freelancer_provider'){
$region = 'German client and freelancer provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'german_client_and_employed_provider'){
$region = 'German client and employed provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'eu_client_and_freelancer_provider'){
$region = 'EU client and freelancer provider';
}else if ($ginv_invoice_ary[0]['region_c'] == 'eu_client_and_employed_provider') {
$region = 'EU client and employed provider';
}else {
$region = '';
}
echo json_encode($ginv_invoice_ary);
$this->view = 'invoiceprint';
//$this->view = 'custom/modules/ginvo_client_invoice/metadata/ClientInvoice.php';
exit;
}
View.detail.php
<?php
require_once('include/MVC/View/views/view.detail.php');
// require_once('modules/ginvo_client_invoice/view/invoice.php');
class ginvo_client_invoiceViewDetail extends ViewDetail {
function ginvo_client_invoiceViewDetail(){
parent::ViewDetail();
}
function display(){
echo $ginv_invoice_ary;
//$this->populateQuoteTemplates();
$this->displayPopupHtml();
parent::display();
}
function populateQuoteTemplates(){
global $app_list_strings, $current_user;
$inv_id = $this->bean->id;
$sql = "SELECT * FROM ginvo_client_invoice WHERE deleted=0 AND id='$inv_id'";
$res = $this->bean->db->query($sql);
$app_list_strings[] = array();
while($row = $this->bean->db->fetchByAssoc($res)){
if($row){
$app_list_strings[$row] = $row;
}
}
}
function displayPopupHtml(){
global $app_list_strings,$app_strings, $mod_strings;
$templates = array_keys($app_list_strings);
if($templates){
echo '
<script>
function showPopup(task){
var record = \''.$this->bean->id.'\';
var fdata = {\'record\':record};
var params = jQuery.param(fdata);
$.ajax({
type:\'post\',
data: fdata,
// dataType: "json",
// url:\'custom/client_invoice.php?\'+params,
//url:\'custom/modules/ginvo_client_invoice/ClientInvoice.php?\'+params,
url:\'index.php?module=ginvo_client_invoice&action=printinvoice\',
error:function(resp){},
success:function(resp){
console.log(resp);
// location.reload(true);
}
});
// var w = window.open(\'custom/ClientInvoice.php\');
//
// $(w).ready(function(){
// w.print();
// });
}
</script>';
}
else{
echo '<script>
function showPopup(task){
alert(\''.$current_user.'\');
}
</script>';
}
}
}
?>

EnvelopeID Changed after correction?

I have 2 signature document and the first signer already signed. The document is still in process. So I went to correct the second signer. I realised the envelopeID changed after the correction.
What will it happen to the old envelope? Voided?
function getDocuments($pdfbytes) {
$documents = array();
$id = 1;
$d = new Document();
$d->PDFBytes = $pdfbytes;
$d->Name = "Demo Document";
$d->ID = $id++;;
$d->FileExtension = "pdf";
array_push($documents, $d);
return $documents;
}
function buildEnvelope($pdfbytes) {
$envelope = new Envelope();
$envelope->Subject = $_SESSION["Taskmaster"];
$envelope->EmailBlurb = "Please Sign by logining ";
$envelope->AccountId = $_SESSION["AccountID"];
$envelope->Recipients = constructRecipients();
$envelope->Tabs = addTabs(count($envelope->Recipients));
$envelope = processOptions($envelope);
$envelope->Documents = getDocuments($pdfbytes);
return $envelope;
}
function constructRecipients() {
$recipients = array();
$r = new Recipient();
$r->UserName =$_SESSION["Secretaryname"];
$r->Email = $_SESSION["Secretaryemail"];
$r->RequireIDLookup = false;
$r->ID = 1;
$r->Type = RecipientTypeCode::Signer;
$r->RoutingOrder = "2";
// if(!isset($_POST['RecipientInviteToggle'][$i])){
$r->CaptiveInfo = new RecipientCaptiveInfo();
$r->CaptiveInfo->ClientUserId = 2;
$r->CaptiveInfo->embeddedRecipientStartURL=SIGN_AT_DOCUSIGN;
// }
array_push($recipients, $r);
if(empty($recipients)){
$_SESSION["errorMessage"] = "You must include at least 1 Recipient";
//header("Location: error.php");
exit;
}
return $recipients;
}
function sendNow($envelope) {
$api = getAPI();
$csParams = new CreateAndSendEnvelope();
$csParams->Envelope = $envelope;
//print_r($csParams);
try {
$status = $api->CreateAndSendEnvelope($csParams)->CreateAndSendEnvelopeResult;
//echo "Result for Create and Send <br>";
//print_r($status);
if ($status->Status == EnvelopeStatusCode::Sent) {
addEnvelopeID($status->EnvelopeID);
$correct = new Correction;
$correct->EnvelopeID = $status->EnvelopeID;
$correct->RecipientCorrections = addRecipientCorrection();
$correctparams = new CorrectAndResendEnvelope();
$correctparams->Correction = $correct;
//print_r($correctparams);
//Send
$response = $api->CorrectAndResendEnvelope($correctparams);
//print_r($response);
//exit;
$_SESSION["EnvelopeID"]=null;
$_SESSION["Direct"]="Yes";
header("Location: getstatusanddocs.php?envelopid=" . $status->EnvelopeID .
"&accountID=" . $envelope->AccountId . "&source=Document");
}
} catch (SoapFault $e) {
$_SESSION["errorMessage"] = $e;
header("Location: error.php");
}
}
function addRecipientCorrection(){
$correction = new RecipientCorrection();
$correction->PreviousUserName = "xxxxxx";
$correction->PreviousEmail = "xxxxxxx";
$correction->PreviousSignerName = $correction->PreviousUserName;
$correction->PreviousRoutingOrder = "2";
$correction->CorrectedUserName = $_SESSION["Secretaryname"];
$correction->CorrectedEmail = $_SESSION["Secretaryemail"];
$correction->CorrectedSignerName = $correction->CorrectedUserName;
return $correction;
}
//========================================================================
// Main
//========================================================================
loginCheck();
if($_SESSION["Taskmaster"]=="xxxxx"){
$api = getAPI();
$RequestPDFParam = new RequestPDF();
$RequestPDFParam->EnvelopeID = $_SESSION["EnvelopeID"];
$result = $api->RequestPDF($RequestPDFParam);
$envPDF = $result->RequestPDFResult;
//file_put_contents("./Cert/".$_SESSION["EnvelopeID"].".pdf", $envPDF->PDFBytes);
//echo "Stop here";
//exit;
$envelope = buildEnvelope($envPDF->PDFBytes);
sendNow($envelope);
}else{
echo "You have no power";
}
EnvelopeId does not change after correction. The envelopeID never changes. New envelopes can be created, but the original GUID that was used will keep living in the system.

Magento - Upload file in contact form

I have to create a new field in contact form to upload file.
I followed tuts and this is what i did :
in form.phtml :
<form action="<?php echo $this->getFormAction(); ?>" id="contactForm" method="post" enctype="multipart/form-data">
Then i added the field in the contact form :
<li>
<label for="attachment"><?php echo Mage::helper('contacts')->__('Attachment') ?></label>
<div class="input-box">
<input name="MAX_FILE_SIZE" type="hidden" value="2000000" />
<input name="attachment" id="attachment" class="input-text" type="file" />
</div>
I modified the IndexController.php in : /www/app/code/core/Mage/Contacts/controllers as :
<?php
/**
* Contacts index controller
*
* #category Mage
* #package Mage_Contacts
* #author Magento Core Team <core#magentocommerce.com>
*/
class Mage_Contacts_IndexController extends Mage_Core_Controller_Front_Action
{
const XML_PATH_EMAIL_RECIPIENT = 'contacts/email/recipient_email';
const XML_PATH_EMAIL_SENDER = 'contacts/email/sender_email_identity';
const XML_PATH_EMAIL_TEMPLATE = 'contacts/email/email_template';
const XML_PATH_ENABLED = 'contacts/contacts/enabled';
public function preDispatch()
{
parent::preDispatch();
if( !Mage::getStoreConfigFlag(self::XML_PATH_ENABLED) ) {
$this->norouteAction();
}
}
public function indexAction()
{
$this->loadLayout();
$this->getLayout()->getBlock('contactForm')
->setFormAction( Mage::getUrl('*/*/post') );
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('catalog/session');
$this->renderLayout();
}
public function postAction()
{
$post = $this->getRequest()->getPost();
if ( $post ) {
$translate = Mage::getSingleton('core/translate');
/* #var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
$error = false;
if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['comment']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
$error = true;
}
if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
$error = true;
}
/**************************************************************/
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$fileName = $_FILES['attachment']['name'];
$fileExt = strtolower(substr(strrchr($fileName, ".") ,1));
$fileNamewoe = rtrim($fileName, $fileExt);
$fileName = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'contacts';
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path . DS, $fileName );
} catch (Exception $e) {
$error = true;
}
}
/**************************************************************//**************************************************************/
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$fileName = $_FILES['attachment']['name'];
$fileExt = strtolower(substr(strrchr($fileName, ".") ,1));
$fileNamewoe = rtrim($fileName, $fileExt);
$fileName = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf', 'jpg', 'jpeg', 'png', 'bmp', 'gif'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'contacts';
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path . DS, $fileName );
} catch (Exception $e) {
$error = true;
}
}
/**************************************************************/
if ($error) {
throw new Exception();
}
$mailTemplate = Mage::getModel('core/email_template');
/* #var $mailTemplate Mage_Core_Model_Email_Template */
/**************************************************************/
//sending file as attachment
$attachmentFilePath = Mage::getBaseDir('media'). DS . 'contacts' . DS . $fileName;
if(file_exists($attachmentFilePath)){
$fileContents = file_get_contents($attachmentFilePath);
$attachment = $mailTemplate->getMail()->createAttachment($fileContents);
$attachment->filename = $fileName;
}
/**************************************************************/
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $postObject)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later'));
$this->_redirect('*/*/');
return;
}
} else {
$this->_redirect('*/*/');
}
}
}
I created a contacts directory in medias with 777 rights
The contact form is correctly shown in my page, i can choose a file, but it isnt uploaded. In medias/contacts/ no file, and in my email i have a attached file called noname
Impossible to use it. Im sure i did something wrong but i cant find what exactly is wrong.
Im not a pro Magento admin, so if you can explain me in details that will be cool :)
Thanks all
i have tried recreating your scenario in my local installation and changed your contoller file uploader code with one of my working modules.
/**************************************************************/
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf'));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'contacts' . DS ;
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path, $_FILES['attachment']['contacts'] );
$newFilename = $uploader->getUploadedFileName();
} catch (Exception $e) {
$error = true;
}
}
/**************************************************************/
This is working 100% correctly i have tested this for pdf also.
Please try changing once.
Replace
if(file_exists($attachmentFilePath)){
With this
if(file_exists($attachmentFilePath) && is_file($attachmentFilePath)){
Because file_exists results to TRUE if the file OR the directory exists. My email being sent out would send a blank "Mail Attachment" file because the file upload input on my contact form was optional.

How to get my zend script picture filename into a hidden field

OK, I am stumped here. I'm using a Zend script that helps me to upload pictures. It works great, but I am trying to capture the pictures name into a hidden field for a form. I'd like to note that the name changes, so I'd need to get whichever it ends up being put into the hidden field. Here is the Zend script:
<?php
if (isset($_POST['upload'])) {
require_once('scripts/library.php');
try {
$destination = 'xxxxxxxx';
$uploader = new Zend_File_Transfer_Adapter_Http();
$uploader->setDestination($destination);
$filename = $uploader->getFileName(NULL, FALSE);
$uploader->addValidator('Size', FALSE, '90kB');
$uploader->addValidator('ImageSize', FALSE, array('minheight' => 100, 'minwidth' => 100));
if (!$uploader->isValid()) {
$messages = $uploader->getMessages();
} else {
$no_spaces = str_replace(' ', '_', $filename, $renamed);
$uploader->addValidator('Extension', FALSE, 'gif, png, jpg');
$recognized = FALSE;
if ($uploader->isValid()) {
$recognized = TRUE;
} else {
$mime = $uploader->getMimeType();
$acceptable = array('jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif');
$key = array_search($mime, $acceptable);
if (!$key) {
$messages[] = 'Unrecognized image type';
} else {
$no_spaces = "$no_spaces.$key";
$recognized = TRUE;
$renamed = TRUE;
}
}
$uploader->clearValidators();
if ($recognized) {
$existing = scandir($destination);
if (in_array($no_spaces, $existing)) {
$dot = strrpos($no_spaces, '.');
$base = substr($no_spaces, 0, $dot);
$extension = substr($no_spaces, $dot);
$i = 1;
do {
$no_spaces = $base . '_' . $i++ . $extension;
} while (in_array($no_spaces, $existing));
$renamed = TRUE;
}
$uploader->addFilter('Rename', array('target' => $no_spaces));
$success = $uploader->receive();
if (!$success) {
$messages = $uploader->getMessages();
} else {
$uploaded = "$filename uploaded successfully";
$pic = $filename;
if ($renamed) {
$uploaded .= " and renamed $no_spaces";
}
$messages[] = "$uploaded";
}
}
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
Here I am trying to make the $pic variable not to throw an error for now (on the form page)
if (isset($_POST['upload'])) { } else { $pic = "unknown";}
The $pic variable is what I was trying to have the filename from the zend script copied into. Any feedback is greaaaatly appreciated :)