Guest User

s3vddl

a guest
Oct 5th, 2016
1,355
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 18.47 KB | None | 0 0
  1. <?php
  2.  
  3. /* ORIGINAL CODE
  4.      https://coderwall.com/p/2q5lcw
  5.      by https://coderwall.com/croustibat
  6.  
  7.      modified by Simone "Magicianred" Paolucci
  8.      http://simone.paolucci.name
  9.  
  10.      modified by s3v for 1.6.1.7 (2016-10-06)
  11. */
  12.  
  13. require_once('class.PSRequest.php');
  14.  
  15. /* START Configuration */
  16. $shopID          = "0"; // ID or unqiue name of the target shop 0 default.
  17. $pathToWriteFile = __DIR__ . "/";
  18. $adminUrl        = 'http://example.com/admin345aflrih/';
  19. $adminLoginEmail = 'demo@demo.com';
  20. $adminLoginPass  = 'demodemo';
  21. /* END Configuration */
  22.  
  23. ob_start();
  24. /*
  25. // your set of product object or array
  26. $products = array();
  27. $products[] = array('id'=>1,'name'=>'Giostra a pedali','reference'=>'prodotto1');
  28.  
  29. // CSV first line for products
  30. //$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;
  31.  
  32. foreach ($products as $prod) {
  33.     // fill in the csv string with your datas
  34.     $csv .= $prod['id'].";0;".html_entity_decode($prod['name'])."CCCC;".$prod['reference'].';1;1234567890123434'.PHP_EOL;
  35. }
  36.  
  37. $now=time();
  38. $csvname = $now."-PRODUCTS-".$shopID.".csv";
  39. $file = $pathToWriteFile.$csvname;
  40.  
  41. file_put_contents($file, $csv);
  42.  
  43. echo "Write file : ".$file.PHP_EOL;
  44. */
  45.  
  46. $now     = time();
  47. $csvname = "test.csv";
  48. $file    = $pathToWriteFile . $csvname;
  49.  
  50.  
  51. echo "Login on Prestashop Admin area..." . PHP_EOL;
  52. $request = new PSRequest();
  53. $request->setCookiFileLocation(__DIR__ . '/PScookie.txt');
  54.  
  55. $request->setPost(array("email" => $adminLoginEmail, "passwd" => $adminLoginPass, "submitLogin" => "Connexion")); // you must be a super admin
  56.  
  57.  
  58.  
  59. $request->call($adminUrl . "index.php?controller=AdminLogin");
  60.  
  61.  
  62. echo "Get token..." . PHP_EOL;
  63. list(, $response) = explode(PHP_EOL . PHP_EOL, $request->_webpage, 2); // \r\n\r\n  PHP_EOL.PHP_EOL
  64. $request->call($adminUrl . "index.php?controller=AdminImport");
  65. #preg_match("/token=([a-z0-9]+)/", $response, $matches);
  66. preg_match("/AdminImport&amp;token=([a-z0-9]+)/", $response, $matches);
  67.  
  68. $token = $matches[1];
  69. echo "Token : " . $token . PHP_EOL;
  70.  
  71.  
  72. // START Carico il file tramite AJAX
  73. srand((double)microtime() * 1000000);
  74. $rand = rand(0, 9999999999999999);
  75. $rand = str_pad($rand, 14, "0", STR_PAD_BOTH);
  76.  
  77. $handle      = fopen($file, "r");
  78. $fileSize    = filesize($file);
  79. $fileContent = fread($handle, $fileSize);
  80. fclose($handle);
  81.  
  82.  
  83. $request->setFileToUpload($file, $csvname, 'application/csv');
  84.  
  85.  
  86. echo 'Random: ' . $rand . PHP_EOL;
  87. $request->call($adminUrl . "index.php?controller=AdminImport&token=" . $token . "&ajax=1&action=uploadCsv&rand=" . $rand);
  88. #list(, $response) = explode(PHP_EOL.PHP_EOL, $request->_webpage, 2);
  89. #preg_match('/"filename":"(.*)"/', $response, $matches);
  90. preg_match('/"filename":"(.*)"/', $request, $matches);
  91. $returnFilename = $matches[1];
  92. // END Carico il file tramite AJAX
  93.  
  94. echo 'Filename: ' . $returnFilename . '<br>';
  95.  
  96. unset($request);
  97. $request = new PSRequest();
  98. $request->setCookiFileLocation(__DIR__ . '/PScookie.txt');
  99.  
  100. // 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.
  101. $request->setPost(array(
  102.         "controller"               => "AdminImport",
  103.         "token"                    => $token,
  104.         "skip"                     => 1, // Lines to skip header from csv
  105.         "csv"                      => $returnFilename,
  106.         "convert"                  => '', // ISO 8859-1 encoded file?
  107.         "regenerate"               => '', // Skip thumbnails regeneration
  108.         "entity"                   => 1, //1 is for products import
  109.         "iso_lang"                 => "de",
  110.         "truncate"                 => '', // Delete all producs before import
  111.         "forceIDs"                 => 0, // Force all ID numbers
  112.         "match_ref"                => 1, // Use product reference as key
  113.         "separator"                => ";", // Field separator
  114.         "multiple_value_separator" => ",", // Multiple value separator
  115.         "import"                   => 1,
  116.  
  117.         // Prestashop 1.6.1.7
  118.         "type_value" => array(0 => 'id',
  119.                               1 => 'active',
  120.                               2 => 'name',
  121.                               3 => 'category',
  122.                               4 => 'price_tex',
  123.                               5 => 'id_tax_rules_group',
  124.                               6 => 'wholesale_price',
  125.                               7 => 'on_sale',
  126.                               8 => 'reduction_price',
  127.                               9 => 'reduction_percent',
  128.                               10 => 'reduction_from',
  129.                               11 => 'reduction_to',
  130.                               12 => 'reference',
  131.                               13 => 'supplier_reference',
  132.                               14 => 'supplier',
  133.                               15 => 'manufacturer',
  134.                               16 => 'ean13',
  135.                               17 => 'upc',
  136.                               18 => 'ecotax',
  137.                               19 => 'weight',
  138.                               20 => 'height',
  139.                               21 => 'depth',
  140.                               22 => 'weight',
  141.                               23 => 'quantity',
  142.                               24 => 'minimal_quantity',
  143.                               25 => 'visibility',
  144.                               26 => 'additional_shipping_cost',
  145.                               27 => 'unity',
  146.                               28 => 'unit_price',
  147.                               29 => 'description_short',
  148.                               30 => 'description',
  149.                               31 => 'tags',
  150.                               32 => 'meta_title',
  151.                               33 => 'meta_keywords',
  152.                               34 => 'meta_description',
  153.                               35 => 'link_rewrite',
  154.                               36 => 'available_now',
  155.                               37 => 'available_later',
  156.                               38 => 'available_for_order',
  157.                               39 => 'available_date',
  158.                               40 => 'date_add',
  159.                               41 => 'show_price',
  160.                               42 => 'image',
  161.                               43 => 'delete_existing_images',
  162.                               44 => 'features',
  163.                               45 => 'online_only',
  164.                               46 => 'condition',
  165.                               47 => 'customizable',
  166.                               48 => 'uploadable_files',
  167.                               49 => 'text_fields',
  168.                               50 => 'out_of_stock',
  169.                               51 => 'shop',
  170.                               52 => 'advanced_stock_management',
  171.                               53 => 'depends_on_stock',
  172.                               54 => 'warehouse'
  173.         )
  174.     )
  175. );
  176.  
  177. echo "call AdminImport and POST datas..." . PHP_EOL;
  178. $returnDanger  = '';
  179. $returnWarning = '';
  180. $request->call($adminUrl . "index.php?controller=AdminImport&amp;token=" . $token);
  181. list(, $response) = explode(PHP_EOL . PHP_EOL, $request->_webpage, 2);
  182.  
  183. // recupero gli warning
  184. $warning_pattern = '/\<div class="alert alert-warning">([\s\S]*)\<\/div>/';
  185. preg_match($warning_pattern, $response, $warning_matches);
  186. if (isset($warning_matches[1])) $returnWarning = $warning_matches[1];
  187. if (strpos($returnWarning, "<h4>")) {
  188.     $returnWarning = substr($returnWarning, strpos($returnWarning, "<h4>") - 4, strlen($returnWarning));
  189. }
  190. if (strpos($returnWarning, "</div>")) {
  191.     $returnWarning = substr($returnWarning, 0, strpos($returnWarning, "</div>", 2));
  192. }
  193.  
  194. // recupero gli errori
  195. $danger_pattern = '/\<div class="alert alert-danger">([\s\S]*)\<\/div>/';
  196. preg_match($danger_pattern, $response, $danger_matches);
  197. if (isset($danger_matches[1])) $returnDanger = $danger_matches[1];
  198. if (strpos($returnDanger, "<h4>")) {
  199.     $returnDanger = substr($returnDanger, strpos($returnDanger, "<h4>") - 4, strlen($returnDanger));
  200. }
  201. if (strpos($returnDanger, "</div>")) {
  202.     $returnDanger = substr($returnDanger, 0, strpos($returnDanger, "</div>", 2));
  203. }
  204. $returnResponse = $returnDanger . $returnWarning;
  205. //echo PHP_EOL.PHP_EOL."RESPONSE: ".PHP_EOL.PHP_EOL.  $returnResponse;
  206.  
  207. echo $request->_webpage;
  208. echo "-- END --" . PHP_EOL;
  209.  
  210. $request = null;
  211.  
  212. $content = ob_get_contents();
  213. ob_end_clean();
  214. $contentHtml = str_replace(PHP_EOL, '<br>', $content);
  215. echo $content;
  216.  
  217. $f = fopen($now . "-log-import.txt", "w");
  218. fwrite($f, $content);
  219. fclose($f);
  220.  
  221. ?>
  222.  
  223.  
  224. file: class.PSRequest.php
  225.  
  226. <?php
  227. /* ORIGINAL CODE
  228.       https://coderwall.com/p/2q5lcw
  229.       by https://coderwall.com/croustibat
  230.  
  231.       modified by Simone "Magicianred" Paolucci
  232.       http://simone.paolucci.name
  233.       */
  234.  
  235. class PSRequest {
  236.         protected $_eol = "\r\n";
  237.         protected $_useragent          = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2';
  238.         protected $_cookieFileLocation = './cookie.txt';
  239.         protected $_referer            = "http://www.google.com";
  240.  
  241.         protected $_url;
  242.         protected $_followlocation;
  243.         protected $_timeout;
  244.         protected $_maxRedirects;
  245.         protected $_post = false;
  246.         protected $_multipart = false;
  247.         protected $_file = false;
  248.         protected $_postFields;
  249.         protected $_postFile;
  250.  
  251.         protected $_session;
  252.         protected $_includeHeader;
  253.         protected $_noBody;
  254.         protected $_status;
  255.         protected $_binaryTransfer;
  256.         protected $_file_to_upload = null;
  257.         protected $_file_to_upload_size = 0;
  258.         protected $_file_name = '';
  259.         protected $_file_transfer_codebase = false;
  260.         protected $_file_content_type = '';
  261.         protected $_boundary = 'boundaryAAAbbb';
  262.  
  263.         public $_webpage;
  264.         public $authentication = 0;
  265.         public $auth_name      = '';
  266.         public $auth_pass      = '';
  267.  
  268.         protected $ch; // curl handler
  269.  
  270.         public function __construct($url = '', $followlocation = true, $timeOut = 30, $maxRedirecs = 4, $binaryTransfer = false, $includeHeader = true, $noBody = false)
  271.         {
  272.             $this->_url                = $url;
  273.             $this->_followlocation     = $followlocation;
  274.             $this->_timeout            = $timeOut;
  275.             $this->_maxRedirects       = $maxRedirecs;
  276.             $this->_noBody             = $noBody;
  277.             $this->_includeHeader      = $includeHeader;
  278.             $this->_binaryTransfer     = $binaryTransfer;
  279.  
  280.             $this->_cookieFileLocation = dirname(__FILE__).'/cookie.txt';
  281.  
  282.             $this->ch = curl_init();
  283.         }
  284.  
  285.         public function __destruct() {
  286.             curl_close($this->ch);
  287.         }
  288.  
  289.         public function useAuth($use){
  290.             $this->authentication = 0;
  291.             if($use == true) $this->authentication = 1;
  292.         }
  293.  
  294.         public function setEndOfLine($chars) {
  295.                         $this->_eol = $chars;
  296.                 }
  297.  
  298.         public function setName($name){
  299.             $this->auth_name = $name;
  300.         }
  301.  
  302.         public function setPass($pass){
  303.             $this->auth_pass = $pass;
  304.         }
  305.  
  306.         public function setBoundary($boundary) {
  307.                     $this->_boundary = $boundary;
  308.                 }
  309.  
  310.         public function setReferer($referer){
  311.             $this->_referer = $referer;
  312.         }
  313.  
  314.         public function setCookiFileLocation($path)
  315.         {
  316.             $this->_cookieFileLocation = $path;
  317.         }
  318.  
  319.         public function setFileToUpload($filePath, $filename, $contentType='plain/text')
  320.         {
  321.             $this->setPostMultipart(array('post'=>'true'));
  322.             $this->_file = true;
  323.  
  324.             $this->_file_name = $filename;
  325.             $this->_file_content_type = $contentType;
  326.             //$this->_file_to_upload = fopen($filePath,'r');
  327.             $handle = fopen($filePath, "r");
  328.             $this->_file_to_upload_size = filesize($filePath);
  329.                         $this->_file_to_upload = fread($handle, $this->_file_to_upload_size);
  330.                         fclose($handle);
  331.         }
  332.  
  333.         public function setPostMultipart($postFields)
  334.         {
  335.             $this->_post = true;
  336.             $this->_multipart = true;
  337.  
  338.             if (is_array($postFields)) {
  339.                 $fields_string = $this->multipart_build_query($postFields);
  340.             }
  341.             else {
  342.                 $fields_string = $postFields;
  343.             }
  344.             $this->_postFields = $fields_string;
  345.         }
  346.  
  347.         public function setPost($postFields)
  348.         {
  349.             $this->_post = true;
  350.  
  351.             if (is_array($postFields)) {
  352.                 $fields_string = http_build_query($postFields);
  353.             }
  354.             else {
  355.                 $fields_string = $postFields;
  356.             }
  357.             $this->_postFields = $fields_string;
  358.         }
  359.  
  360.         public function setUserAgent($userAgent)
  361.         {
  362.             $this->_useragent = $userAgent;
  363.         }
  364.  
  365.         public function call($url = null, $header = null)
  366.         {
  367.                     if(is_null($header)) {
  368.                         if($this->_multipart == true) {
  369.                             $header = array("Content-Type: multipart/form-data; boundary=".$this->_boundary);
  370.                         } else {
  371.                             $header = array('Content-Type: application/x-www-form-urlencoded');
  372.                         }
  373.                     }
  374.  
  375.             if ($url) {
  376.                 $this->_url = $url;
  377.             }
  378.  
  379.             if (!$url) {
  380.                 throw new Exception('You should set an URL to call.');
  381.             }
  382.  
  383.             curl_setopt($this->ch,CURLOPT_URL,$this->_url);
  384.             curl_setopt($this->ch,CURLOPT_HTTPHEADER, $header);
  385.             curl_setopt($this->ch,CURLOPT_TIMEOUT,$this->_timeout);
  386.             curl_setopt($this->ch,CURLOPT_MAXREDIRS,$this->_maxRedirects);
  387.             curl_setopt($this->ch,CURLOPT_RETURNTRANSFER,true);
  388.             curl_setopt($this->ch,CURLOPT_FOLLOWLOCATION,$this->_followlocation);
  389.             curl_setopt($this->ch,CURLOPT_SSL_VERIFYPEER, false);
  390.             curl_setopt($this->ch,CURLOPT_COOKIESESSION, true );
  391.             curl_setopt($this->ch,CURLOPT_COOKIEJAR,$this->_cookieFileLocation);
  392.             curl_setopt($this->ch,CURLOPT_COOKIEFILE,$this->_cookieFileLocation);
  393.  
  394.             if ($this->authentication == 1) {
  395.                 curl_setopt($this->ch, CURLOPT_USERPWD, $this->auth_name.':'.$this->auth_pass);
  396.             }
  397.  
  398.                         if ($this->_multipart) {
  399.                 curl_setopt($this->ch,CURLOPT_POST,true);
  400.                 if($this->_file) {
  401.                                     $this->_postFields .= $this->add_multipart_build_file('file',$this->_file_name,$this->_file_content_type);
  402.                                     $this->_postFields .= "--".$this->_eol;
  403.                                     curl_setopt($this->ch,CURLOPT_INFILESIZE, $this->_file_to_upload_size);
  404.                                     curl_setopt($this->ch, CURLOPT_BINARYTRANSFER, 1);
  405.                                 }
  406.             } else if ($this->_post) {
  407.                             curl_setopt($this->ch,CURLOPT_POST,true);
  408.                         }
  409.                         curl_setopt($this->ch,CURLOPT_POSTFIELDS,$this->_postFields);
  410.  
  411.  
  412.  
  413.             if ($this->_includeHeader) {
  414.                 curl_setopt($this->ch,CURLOPT_HEADER,true);
  415.             }
  416.  
  417.             if ($this->_noBody) {
  418.                 curl_setopt($this->ch,CURLOPT_NOBODY,true);
  419.             }
  420.  
  421.          /*   if ($this->_file_to_upload_size > 0 && !is_null($this->_file_to_upload)) {
  422.                 curl_setopt($this->ch, CURLOPT_READFUNCTION, 'uploadFileCall');
  423.             } */
  424.  
  425.             curl_setopt($this->ch,CURLOPT_USERAGENT,$this->_useragent);
  426.             curl_setopt($this->ch,CURLOPT_REFERER,$this->_referer);
  427.  
  428.             $this->_webpage = curl_exec($this->ch);
  429.                         /*if (curl_errno($this->ch)) {
  430.                             print "<hr><hr>Error: ". curl_error($this->ch) ."<hr><hr>";
  431.                         }*/
  432.             $this->_status = curl_getinfo($this->ch,CURLINFO_HTTP_CODE);
  433.  
  434.             return $this->_webpage;
  435.         }
  436.  
  437.         public function getHttpStatus()
  438.         {
  439.             return $this->_status;
  440.         }
  441.  
  442.         public function __tostring(){
  443.             return $this->_webpage;
  444.         }
  445.  
  446.  
  447.                 /*function uploadFileCall($ch, $data){
  448.                      return fread($this->_file_to_upload, $this->_file_to_upload_size);
  449.                 }*/
  450.  
  451.                 function multipart_build_query($fields){
  452.                     $retval = '';
  453.                     foreach($fields as $key => $value){
  454.                             $retval .= "--".$this->_boundary.$this->_eol."Content-Disposition: form-data; name=\"".$key."\"".$this->_eol.$this->_eol.$value.$this->_eol;
  455.                     }
  456.                     //$retval .= "--". $this->_boundary ."--".$this->_eol;
  457.                     $retval .= "--". $this->_boundary .$this->_eol;
  458.                     return $retval;
  459.                 }
  460.  
  461.                 function add_multipart_build_file($key,$filename='file.csv',$contentType ="application/csv") {
  462.                     $retval = '';
  463.                     $retval .= "Content-Disposition: form-data; name=\"$key\"; filename=\"$filename\"".$this->_eol;
  464.                     $retval .= "Content-Type: $contentType ".$this->_eol.$this->_eol;
  465.                     if($this->_file_transfer_codebase == true) {
  466.                         $retval .= 'Content-Transfer-Encoding: base64'.$this->_eol.$this->_eol;
  467.                         $retval .= chunk_split(base64_encode($this->_file_to_upload));
  468.                     } else {
  469.                         $retval .= $this->_file_to_upload;
  470.                     }
  471.                     $retval .= "--". $this->_boundary; // ."--".$this->_eol;
  472.                     return $retval;
  473.                 }
  474.  
  475.     }
  476. ?>
Add Comment
Please, Sign In to add comment