Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /* ORIGINAL CODE
- https://coderwall.com/p/2q5lcw
- by https://coderwall.com/croustibat
- modified by Simone "Magicianred" Paolucci
- http://simone.paolucci.name
- modified by s3v for 1.6.1.7 (2016-10-06)
- */
- require_once('class.PSRequest.php');
- /* START Configuration */
- $shopID = "0"; // ID or unqiue name of the target shop 0 default.
- $pathToWriteFile = __DIR__ . "/";
- $adminUrl = 'http://example.com/admin345aflrih/';
- $adminLoginEmail = 'demo@demo.com';
- $adminLoginPass = 'demodemo';
- /* END Configuration */
- ob_start();
- /*
- // your set of product object or array
- $products = array();
- $products[] = array('id'=>1,'name'=>'Giostra a pedali','reference'=>'prodotto1');
- // 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;
- 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;
- */
- $now = time();
- $csvname = "test.csv";
- $file = $pathToWriteFile . $csvname;
- 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;
- list(, $response) = explode(PHP_EOL . PHP_EOL, $request->_webpage, 2); // \r\n\r\n PHP_EOL.PHP_EOL
- $request->call($adminUrl . "index.php?controller=AdminImport");
- #preg_match("/token=([a-z0-9]+)/", $response, $matches);
- preg_match("/AdminImport&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');
- echo 'Random: ' . $rand . PHP_EOL;
- $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);
- preg_match('/"filename":"(.*)"/', $request, $matches);
- $returnFilename = $matches[1];
- // END Carico il file tramite AJAX
- echo 'Filename: ' . $returnFilename . '<br>';
- 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, // Lines to skip header from csv
- "csv" => $returnFilename,
- "convert" => '', // ISO 8859-1 encoded file?
- "regenerate" => '', // Skip thumbnails regeneration
- "entity" => 1, //1 is for products import
- "iso_lang" => "de",
- "truncate" => '', // Delete all producs before import
- "forceIDs" => 0, // Force all ID numbers
- "match_ref" => 1, // Use product reference as key
- "separator" => ";", // Field separator
- "multiple_value_separator" => ",", // Multiple value separator
- "import" => 1,
- // Prestashop 1.6.1.7
- "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 => 'height',
- 21 => 'depth',
- 22 => 'weight',
- 23 => 'quantity',
- 24 => 'minimal_quantity',
- 25 => 'visibility',
- 26 => 'additional_shipping_cost',
- 27 => 'unity',
- 28 => 'unit_price',
- 29 => 'description_short',
- 30 => 'description',
- 31 => 'tags',
- 32 => 'meta_title',
- 33 => 'meta_keywords',
- 34 => 'meta_description',
- 35 => 'link_rewrite',
- 36 => 'available_now',
- 37 => 'available_later',
- 38 => 'available_for_order',
- 39 => 'available_date',
- 40 => 'date_add',
- 41 => 'show_price',
- 42 => 'image',
- 43 => 'delete_existing_images',
- 44 => 'features',
- 45 => 'online_only',
- 46 => 'condition',
- 47 => 'customizable',
- 48 => 'uploadable_files',
- 49 => 'text_fields',
- 50 => 'out_of_stock',
- 51 => 'shop',
- 52 => 'advanced_stock_management',
- 53 => 'depends_on_stock',
- 54 => 'warehouse'
- )
- )
- );
- 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">([\s\S]*)\<\/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">([\s\S]*)\<\/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);
- ?>
- file: class.PSRequest.php
- <?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 = "\r\n";
- 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);
- curl_setopt($this->ch,CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($this->ch,CURLOPT_COOKIESESSION, true );
- curl_setopt($this->ch,CURLOPT_COOKIEJAR,$this->_cookieFileLocation);
- curl_setopt($this->ch,CURLOPT_COOKIEFILE,$this->_cookieFileLocation);
- if ($this->authentication == 1) {
- curl_setopt($this->ch, CURLOPT_USERPWD, $this->auth_name.':'.$this->auth_pass);
- }
- if ($this->_multipart) {
- curl_setopt($this->ch,CURLOPT_POST,true);
- if($this->_file) {
- $this->_postFields .= $this->add_multipart_build_file('file',$this->_file_name,$this->_file_content_type);
- $this->_postFields .= "--".$this->_eol;
- curl_setopt($this->ch,CURLOPT_INFILESIZE, $this->_file_to_upload_size);
- curl_setopt($this->ch, CURLOPT_BINARYTRANSFER, 1);
- }
- } else if ($this->_post) {
- curl_setopt($this->ch,CURLOPT_POST,true);
- }
- curl_setopt($this->ch,CURLOPT_POSTFIELDS,$this->_postFields);
- if ($this->_includeHeader) {
- curl_setopt($this->ch,CURLOPT_HEADER,true);
- }
- if ($this->_noBody) {
- curl_setopt($this->ch,CURLOPT_NOBODY,true);
- }
- /* if ($this->_file_to_upload_size > 0 && !is_null($this->_file_to_upload)) {
- curl_setopt($this->ch, CURLOPT_READFUNCTION, 'uploadFileCall');
- } */
- curl_setopt($this->ch,CURLOPT_USERAGENT,$this->_useragent);
- curl_setopt($this->ch,CURLOPT_REFERER,$this->_referer);
- $this->_webpage = curl_exec($this->ch);
- /*if (curl_errno($this->ch)) {
- print "<hr><hr>Error: ". curl_error($this->ch) ."<hr><hr>";
- }*/
- $this->_status = curl_getinfo($this->ch,CURLINFO_HTTP_CODE);
- return $this->_webpage;
- }
- public function getHttpStatus()
- {
- return $this->_status;
- }
- public function __tostring(){
- return $this->_webpage;
- }
- /*function uploadFileCall($ch, $data){
- return fread($this->_file_to_upload, $this->_file_to_upload_size);
- }*/
- function multipart_build_query($fields){
- $retval = '';
- foreach($fields as $key => $value){
- $retval .= "--".$this->_boundary.$this->_eol."Content-Disposition: form-data; name=\"".$key."\"".$this->_eol.$this->_eol.$value.$this->_eol;
- }
- //$retval .= "--". $this->_boundary ."--".$this->_eol;
- $retval .= "--". $this->_boundary .$this->_eol;
- return $retval;
- }
- function add_multipart_build_file($key,$filename='file.csv',$contentType ="application/csv") {
- $retval = '';
- $retval .= "Content-Disposition: form-data; name=\"$key\"; filename=\"$filename\"".$this->_eol;
- $retval .= "Content-Type: $contentType ".$this->_eol.$this->_eol;
- if($this->_file_transfer_codebase == true) {
- $retval .= 'Content-Transfer-Encoding: base64'.$this->_eol.$this->_eol;
- $retval .= chunk_split(base64_encode($this->_file_to_upload));
- } else {
- $retval .= $this->_file_to_upload;
- }
- $retval .= "--". $this->_boundary; // ."--".$this->_eol;
- return $retval;
- }
- }
- ?>
Add Comment
Please, Sign In to add comment