Importação de produtos em CSV de fundo / cron PRESTASHOP (modificado)

Modifiquei o código de https://coderwall.com/p/2q5lcw por https://coderwall.com/croustibat

arquivo: ps_integrator.php

/* ORIGINAL CODE 
https://coderwall.com/p/2q5lcw

by https://coderwall.com/croustibat


modified by Simone "Magicianred" Paolucci

http://simone.paolucci.name */


require_once
('class.PSRequest.php'); //see class source code below

/* START Configuration */
$shopID
= "myfirstshop"; // ID or unqiue name of the target shop
$pathToWriteFile
= __DIR__."/";
$adminUrl
= 'http://prestashop.dev:8080/admin6596/';
$adminLoginEmail
= YOUR_PRESTASHOP_EMAIL;
$adminLoginPass
= YOUR_PRESTASHOP_PASS;
/* END Configuration */

ob_start
();
// your set of product object or array
$products
= array();
$products
[] = array('id'=>1,'name'=>'Giostra a pedali','reference'=>'prodotto1');
$products
[] = array('id'=>2,'name'=>'Pedalò a vela','reference'=>'prodotto2');
$products
[] = array('id'=>3,'name'=>'Idrovolante subaqueo','reference'=>'prodotto3');
$products
[] = array('id'=>4,'name'=>'Hovercraft spaziale','reference'=>'prodotto4');
$products
[] = array('id'=>5,'name'=>'Trottola stazionaria','reference'=>'prodotto5');
$products
[] = array('id'=>15,'name'=>'Trottola stazionaria','reference'=>'prodotto15');
$products
[] = array('id'=>25,'name'=>'Trottola stazionaria','reference'=>'prodotto25');
$products
[] = array('id'=>35,'name'=>'Trottola stazionaria','reference'=>'prodotto35');

// CSV first line for products
//$csv = "id;Active (0/1);Name*;Categories (x,y,z,...);Price tax excluded;Tax rules id;Wholesale price;On sale (0/1);Discount amount;Discount percent;Discount from (yyy-mm-dd);Discount to (yyy-mm-dd);Reference #;Supplier reference #;Supplier;Manufacturer;EAN13;UPC;Ecotax;Weight;Quantity;Short description;Description;Tags (x,y,z,...);Meta-title;Meta-keywords;Meta-description;URL rewritten;Text when in-stock;Text if back-order allowed;Available for order (0 = No, 1 = Yes);Product creation date;Show price (0 = No, 1 = Yes);Image URLs (x,y,z,...);Delete existing images (0 = No, 1 = Yes);Feature (Name:Value:Position);Available online only (0 = No, 1 = Yes);Condition (new,used,refurbished);ID / Name of shop".PHP_EOL;
$csv
= "id;Active (0/1);Name*;reference;price;barcode".PHP_EOL;

foreach ($products as $prod) {
// fill in the csv string with your datas
$csv
.= $prod['id'].";0;".html_entity_decode($prod['name'])."CCCC;".$prod['reference'].';1;1234567890123434'.PHP_EOL;
}

$now
=time();
$csvname
= $now."-PRODUCTS-".$shopID.".csv";
$file
= $pathToWriteFile.$csvname;

file_put_contents
($file, $csv);

echo
"Write file : ".$file.PHP_EOL;

echo
"Login on Prestashop Admin area...".PHP_EOL;
$request
= new PSRequest();
$request
->setCookiFileLocation(__DIR__.'/PScookie.txt');

$request
->setPost(array("email" => $adminLoginEmail,"passwd" => $adminLoginPass, "submitLogin" => "Connexion")); // you must be a super admin
$request
->call($adminUrl."index.php?controller=AdminLogin");

echo
"Get token...".PHP_EOL;

$request
->call($adminUrl."index.php?controller=AdminImport");

list
(,$response) = explode(PHP_EOL.PHP_EOL, $request->_webpage, 2);
preg_match
("/token=([a-z0-9]+)/", $response, $matches);
$token
= $matches[1];

echo
"Token : ".$token.PHP_EOL;

// START Carico il file tramite AJAX
srand
((double)microtime()*1000000);
$rand
= rand(0,9999999999999999);
$rand
= str_pad($rand, 14, "0", STR_PAD_BOTH);

$handle
= fopen($file, "r");
$fileSize
= filesize($file);
$fileContent
= fread($handle, $fileSize);
fclose
($handle);

$request
->setFileToUpload($file,$csvname,'application/csv');

$request
->call($adminUrl."index.php?controller=AdminImport&token=".$token."&ajax=1&action=uploadCsv&rand=".$rand);
list
(,$response) = explode(PHP_EOL.PHP_EOL, $request->_webpage, 2);
preg_match
('/"filename":"(.*?)"/', $response, $matches);
$returnFilename
= $matches[1];
// END Carico il file tramite AJAX

unset
($request);
$request
= new PSRequest();
$request
->setCookiFileLocation(__DIR__.'/PScookie.txt');

// Send POST datas just like the admin form would do it, those datas depends on what you want to do : check the import admin page.
$request
->setPost(array(
"controller" => "AdminImport",
"token" => $token,
"skip" => 1,
"csv" => $returnFilename,
"convert" => '',
"regenerate" => '',
"entity" => 1, //1 is for products import
"iso_lang" => "it",
"truncate" => 1,
"forceIDs" => 1,
"match_ref" => 0,
"separator" => ";",
"multiple_value_separator" => ",",
"import" => 1,
"type_value" => array( 0 => 'id', 1 => 'active', 2 => 'name', 3 => 'reference', 4 => 'price_tex', 5 => 'ean13')
//"type_value" => array( 0 => 'id', 1 => 'active', 2 => 'name', 3 => 'category', 4 => 'price_tex', 5 => 'id_tax_rules_group', 6 => 'wholesale_price', 7 => 'on_sale', 8 => 'reduction_price', 9 => 'reduction_percent', 10 => 'reduction_from', 11 => 'reduction_to', 12 => 'reference', 13 => 'supplier_reference', 14 => 'supplier', 15 => 'manufacturer', 16 => 'ean13', 17 => 'upc', 18 => 'ecotax', 19 => 'weight', 20 => 'quantity', 21 => 'description_short', 22 => 'description', 23 => 'tags', 24 => 'meta_title', 25 => 'meta_keywords', 26 => 'meta_description', 27 => 'link_rewrite', 28 => 'available_now', 29 => 'available_later', 30 => 'available_for_order', 31 => 'date_add', 32 => 'show_price', 33 => 'image', 34 => 'delete_existing_images', 35 => 'features', 36 => 'online_only', 37 => 'condition', 38 => 'shop')
)
);

echo
"call AdminImport and POST datas...".PHP_EOL;
$returnDanger
= ''; $returnWarning = '';
$request
->call($adminUrl."index.php?controller=AdminImport&token=".$token);
list
(,$response) = explode(PHP_EOL.PHP_EOL, $request->_webpage, 2);

// recupero gli warning
$warning_pattern
= '/<div class="alert alert-warning">([sS]*)</div>/';
preg_match
($warning_pattern, $response, $warning_matches);
if(isset($warning_matches[1])) $returnWarning = $warning_matches[1];
if(strpos($returnWarning,"<h4>")) { $returnWarning = substr($returnWarning,strpos($returnWarning,"<h4>")-4,strlen($returnWarning)); }
if(strpos($returnWarning,"</div>")) { $returnWarning = substr($returnWarning,0,strpos($returnWarning,"</div>",2)); }

// recupero gli errori
$danger_pattern
= '/<div class="alert alert-danger">([sS]*)</div>/';
preg_match
($danger_pattern, $response, $danger_matches);
if(isset($danger_matches[1])) $returnDanger = $danger_matches[1];
if(strpos($returnDanger,"<h4>")) { $returnDanger = substr($returnDanger,strpos($returnDanger,"<h4>")-4,strlen($returnDanger)); }
if(strpos($returnDanger,"</div>")) { $returnDanger = substr($returnDanger,0,strpos($returnDanger,"</div>",2)); }
$returnResponse
= $returnDanger . $returnWarning;
//echo PHP_EOL.PHP_EOL."RESPONSE: ".PHP_EOL.PHP_EOL. $returnResponse;

echo $request
->_webpage;
echo
"-- END --".PHP_EOL;

$request
= null;

$content
= ob_get_contents();
ob_end_clean
();
$contentHtml
= str_replace(PHP_EOL,'<br>',$content);
echo $content
;

$f
= fopen($now."-log-import.txt", "w");
fwrite
($f, $content);
fclose
($f);

arquivo: class.PSRequest.php

/* ORIGINAL CODE
https://coderwall.com/p/2q5lcw

by https://coderwall.com/croustibat


modified by Simone "Magicianred" Paolucci

http://simone.paolucci.name

*/


class PSRequest {
protected $_eol = "rn";
protected $_useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2';
protected $_cookieFileLocation = './cookie.txt';
protected $_referer = "http://www.google.com";

protected $_url;
protected $_followlocation;
protected $_timeout;
protected $_maxRedirects;
protected $_post = false;
protected $_multipart = false;
protected $_file = false;
protected $_postFields;
protected $_postFile;

protected $_session;
protected $_includeHeader;
protected $_noBody;
protected $_status;
protected $_binaryTransfer;
protected $_file_to_upload = null;
protected $_file_to_upload_size = 0;
protected $_file_name = '';
protected $_file_transfer_codebase = false;
protected $_file_content_type = '';
protected $_boundary = 'boundaryAAAbbb';

public $_webpage;
public $authentication = 0;
public $auth_name = '';
public $auth_pass = '';

protected $ch; // curl handler

public function __construct($url = '', $followlocation = true, $timeOut = 30, $maxRedirecs = 4, $binaryTransfer = false, $includeHeader = true, $noBody = false)
{
$this
->_url = $url;
$this
->_followlocation = $followlocation;
$this
->_timeout = $timeOut;
$this
->_maxRedirects = $maxRedirecs;
$this
->_noBody = $noBody;
$this
->_includeHeader = $includeHeader;
$this
->_binaryTransfer = $binaryTransfer;

$this
->_cookieFileLocation = dirname(__FILE__).'/cookie.txt';

$this
->ch = curl_init();
}

public function __destruct() {
curl_close
($this->ch);
}

public function useAuth($use){
$this
->authentication = 0;
if($use == true) $this->authentication = 1;
}

public function setEndOfLine($chars) {
$this
->_eol = $chars;
}

public function setName($name){
$this
->auth_name = $name;
}

public function setPass($pass){
$this
->auth_pass = $pass;
}

public function setBoundary($boundary) {
$this
->_boundary = $boundary;
}

public function setReferer($referer){
$this
->_referer = $referer;
}

public function setCookiFileLocation($path)
{
$this
->_cookieFileLocation = $path;
}

public function setFileToUpload($filePath, $filename, $contentType='plain/text')
{
$this
->setPostMultipart(array('post'=>'true'));
$this
->_file = true;

$this
->_file_name = $filename;
$this
->_file_content_type = $contentType;
//$this->_file_to_upload = fopen($filePath,'r');
$handle
= fopen($filePath, "r");
$this
->_file_to_upload_size = filesize($filePath);
$this
->_file_to_upload = fread($handle, $this->_file_to_upload_size);
fclose
($handle);
}

public function setPostMultipart($postFields)
{
$this
->_post = true;
$this
->_multipart = true;

if (is_array($postFields)) {
$fields_string
= $this->multipart_build_query($postFields);
}
else {
$fields_string
= $postFields;
}
$this
->_postFields = $fields_string;
}

public function setPost($postFields)
{
$this
->_post = true;

if (is_array($postFields)) {
$fields_string
= http_build_query($postFields);
}
else {
$fields_string
= $postFields;
}
$this
->_postFields = $fields_string;
}

public function setUserAgent($userAgent)
{
$this
->_useragent = $userAgent;
}

public function call($url = null, $header = null)
{
if(is_null($header)) {
if($this->_multipart == true) {
$header
= array("Content-Type: multipart/form-data; boundary=".$this->_boundary);
} else {
$header
= array('Content-Type: application/x-www-form-urlencoded');
}
}

if ($url) {
$this
->_url = $url;
}

if (!$url) {
throw new Exception('You should set an URL to call.');
}

curl_setopt
($this->ch,CURLOPT_URL,$this->_url);
curl_setopt
($this->ch,CURLOPT_HTTPHEADER, $header);
curl_setopt
($this->ch,CURLOPT_TIMEOUT,$this->_timeout);
curl_setopt
($this->ch,CURLOPT_MAXREDIRS,$this->_maxRedirects);
curl_setopt
($this->ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt
($this->ch,CURLOPT_FOLLOWLOCATION,$this->_followlocation