SugarCRM 6.5 How to print php template? - sugarcrm

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>';
}
}
}
?>

Related

Changed mysql to mysqli and can't connect to database

I am not very experienced in this field so this is why I am seeking help.
I recently changed hosts and a script stopped working. After moving all files the new hosts said mysql is deprecated, so after doing a bit of search I decided to change mysql with mysqli and that deprecated error was gone. But now I get a new error (error select db). I think I must make adidtional changes to the script to connect mysqli. This is the file I have
<?php
class Model{
var $conn;
public function openDb($dbhost, $dbuser, $dbpass, $dbname, $conn)
{
//echo "Se creo la conexion ";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysqli');
mysqli_select_db($dbname) or die('Error select db');
mysqli_query("SET NAMES utf8");
return $conn;
}
public function closeDb($conn)
{
mysqli_close($conn);
}
public function query($query)
{
if ($result = mysqli_query($query) or die("Error de Query: </br >" . mysqli_error()."<br/>".$query)) {
//if ($result = mysqli_query($query)) {
} else {
$result = false;
}
return $result;
}
function __construct()
{
$this->openDb(dbhost, dbuser, dbpass, dbname, $conn);
}
//insertGenerico con indedices asiciativos
function insertar($tabla, $datos)
{
$columnas = implode(", ", array_keys($datos));
$valores = implode(", ", $datos);
$query = "INSERT INTO $tabla
($columnas)
VALUES
(" . $valores . ")";
return $this -> query($query);
}
function insertarRelacionArray($tabla, $tablaRelacion, $datos)
{
foreach ($datos as $row) {
$query = "INSERT INTO $tabla
($tablaRelacion[0],$tablaRelacion[2])
VALUES
($tablaRelacion[1],$row)";
//echo '<br>'.$query;
$this -> query($query);
}
}
//getGenerico
function get($tabla, $where = false, $order = false)
{
$query = "SELECT *
FROM $tabla
$where
$order";
return $this -> query($query);
}
//deleteGenerico
function delete($tabla, $id, $idTag = false)
{
if($idTag==false)
$idTag = "id";
$query = "DELETE FROM $tabla
WHERE $idTag = $id";
return $this -> query($query);
}
//update generico
function update($tabla, $datos, $id, $idTag = false)
{
$columnas = array_keys($datos);
$SET = 'SET ';
$i = 0;
foreach ($datos as $key => $value) {
if (next($datos)) {
$SET .= "$key = $value ,";
} else {
$SET .= "$key = $value ";
}
}
if($idTag==false)
$idTag = "id";
$query = "UPDATE $tabla $SET WHERE $idTag = $id;";
return $this -> query($query);
}
}
?>
As described on http://php.net/manual/en/mysqli.select-db.php first parameter should be $link.
bool mysqli_select_db ( mysqli $link , string $dbname )
So change
mysqli_select_db($dbname) or die('Error select db');
to
mysqli_select_db($conn, $dbname) or die('Error select db');
and it should work.
I think that you need to return $conn in your _construct function too, or store it in the object ($this->conn = $conn) so you can use it again.
In addition (thanks to Ki Jéy) you should also update
mysql_query($query)
to
mysqli_query($conn, $query)
and
mysql_real_escape_string($string)
to
mysqli_real_escape_string ($conn, $string)

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.

Notification.php for Windows Azure notification hub API using PHP

I want to send the notification, using windows azure notification hub api in PHP.
You have to interface directly with REST (http://msdn.microsoft.com/en-us/library/dn495827.aspx).
The code you will have to write is basically this one:
class Notification {
public $format;
public $payload;
# array with keynames for headers
# Note: Some headers are mandatory: Windows: X-WNS-Type, WindowsPhone: X-NotificationType
# Note: For Apple you can set Expiry with header: ServiceBusNotification-ApnsExpiry in W3C DTF, YYYY-MM-DDThh:mmTZD (for example, 1997-07-16T19:20+01:00).
public $headers;
function __construct($format, $payload) {
if (!in_array($format, ["template", "apple", "windows", "gcm", "windowsphone"])) {
throw new Exception('Invalid format: ' . $format);
}
$this->format = $format;
$this->payload = $payload;
}
}
class NotificationHub {
const API_VERSION = "?api-version=2013-10";
private $endpoint;
private $hubPath;
private $sasKeyName;
private $sasKeyValue;
function __construct($connectionString, $hubPath) {
$this->hubPath = $hubPath;
$this->parseConnectionString($connectionString);
}
private function parseConnectionString($connectionString) {
$parts = explode(";", $connectionString);
if (sizeof($parts) != 3) {
throw new Exception("Error parsing connection string: " . $connectionString);
}
foreach ($parts as $part) {
if (strpos($part, "Endpoint") === 0) {
$this->endpoint = "https" . substr($part, 11);
} else if (strpos($part, "SharedAccessKeyName") === 0) {
$this->sasKeyName = substr($part, 20);
} else if (strpos($part, "SharedAccessKey") === 0) {
$this->sasKeyValue = substr($part, 16);
}
}
}
private function generateSasToken($uri) {
$targetUri = strtolower(rawurlencode(strtolower($uri)));
$expires = time();
$expiresInMins = 60;
$expires = $expires + $expiresInMins * 60;
$toSign = $targetUri . "\n" . $expires;
$signature = rawurlencode(base64_encode(hash_hmac('sha256', $toSign, $this->sasKeyValue, TRUE)));
$token = "SharedAccessSignature sr=" . $targetUri . "&sig="
. $signature . "&se=" . $expires . "&skn=" . $this->sasKeyName;
return $token;
}
public function broadcastNotification($notification) {
$this->sendNotification($notification, "");
}
public function sendNotification($notification, $tagsOrTagExpression) {
if (is_array($tagsOrTagExpression)) {
$tagExpression = implode(" || ", $tagsOrTagExpression);
} else {
$tagExpression = $tagsOrTagExpression;
}
# build uri
$uri = $this->endpoint . $this->hubPath . "/messages" . NotificationHub::API_VERSION;
$ch = curl_init($uri);
if (in_array($notification->format, ["template", "apple", "gcm"])) {
$contentType = "application/json";
} else {
$contentType = "application/xml";
}
$token = $this->generateSasToken($uri);
$headers = [
'Authorization: '.$token,
'Content-Type: '.$contentType,
'ServiceBusNotification-Format: '.$notification->format
];
if ("" !== $tagExpression) {
$headers[] = 'ServiceBusNotification-Tags: '.$tagExpression;
}
# add headers for other platforms
if (is_array($notification->headers)) {
$headers = array_merge($headers, $notification->headers);
}
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $notification->payload
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
throw new Exception(curl_error($ch));
}
$info = curl_getinfo($ch);
if ($info['http_code'] <> 201) {
throw new Exception('Error sending notificaiton: '. $info['http_code'] . ' msg: ' . $response);
}
}
}
And use it this way: initialize your Notification Hubs client (substitute the connection string and hub name as instructed in the Get started tutorial):
$hub = new NotificationHub("connection string", "hubname");
Then add the send code depending on your target mobile platform.
Windows Store and Windows Phone 8.1 (non-Silverlight)
$toast = '<toast><visual><binding template="ToastText01"><text id="1">Hello from PHP!</text></binding></visual></toast>';
$notification = new Notification("windows", $toast);
$notification->headers[] = 'X-WNS-Type: wns/toast';
$hub->sendNotification($notification);
iOS
$alert = '{"aps":{"alert":"Hello from PHP!"}}';
$notification = new Notification("apple", $alert);
$hub->sendNotification($notification);
Android
$message = '{"data":{"msg":"Hello from PHP!"}}';
$notification = new Notification("gcm", $message);
$hub->sendNotification($notification);
Windows Phone 8.0 and 8.1 Silverlight
$toast = '<?xml version="1.0" encoding="utf-8"?>' .
'<wp:Notification xmlns:wp="WPNotification">' .
'<wp:Toast>' .
'<wp:Text1>Hello from PHP!</wp:Text1>' .
'</wp:Toast> ' .
'</wp:Notification>';
$notification = new Notification("mpns", $toast);
$notification->headers[] = 'X-WindowsPhone-Target : toast';
$notification->headers[] = 'X-NotificationClass : 2';
$hub->sendNotification($notification);
Kindle Fire
$message = '{"data":{"msg":"Hello from PHP!"}}';
$notification = new Notification("adm", $message);
$hub->sendNotification($notification);
For registration management you have to follow the content formats shown in the MSDN topic linked above, and probably do some nasty xml parsing... Be warned that element order is important and things will not work if the element are out of order.

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 create a category and add an image programatically

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;
}
?>