Jump to content

Script to import csv using the tab AdminImport on admin panel


novalab

Recommended Posts

Hello

i'm writing a script to execute import of a csv using the admin panel: AdminImport.

 

The script execute a login into the admin panel and post csv with opportune parameters to import the file.

 

I've founded this class on web:

<?php
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 );

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

    }
?>

This is the main script:

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

debug( "Login..." );

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

    $response = $request->_webpage;
    preg_match( "/&token=([a-z0-9]+)/", $response, $matches );

//    $token = Tools::getAdminTokenLite( 'AdminImport' );
    $token = $matches[ 1 ];

debug( "Token: ".$token );

    $csvname = $upload_dir . 'prestashop_products.csv';

    // 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"                      => $csvname,
        "convert"                  => '',
        "regenerate"               => '',
        "entity"                   => 1, //1 is for products import
        "iso_lang"                 => "it",
        "truncate"                 => 0,
        "forceIDs"                 => 1,
        "match_ref"                => 1,
        "separator"                => ";",
        "multiple_value_separator" => ",",
        "import"                   => 1,
        "type_value" => array( 1 => 'active', 2 => 'reference', 3 => 'name', 4 => 'category', 5 => 'price_tex', 6 => 'supplier', 7 => 'weight', 8 => 'quantity', 9 => 'description' )
        )
    );

debug( "call AdminImport and POST datas..." );

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

The script initially works: i can get the admin panel and i succesfully get token!!

 

but when i POST data, the request fails due to 'token invalid'!!

 

But the token is ok!!

 

I've tryed to use the function:

Tools::getAdminTokenLite( 'AdminImport' )

the token is different to the token i get from page, but also not work!!

 

I think problem regardling php sessions but i don't know hot to resolve it!!

 

someone can help me?

 

 

 

 

Link to comment
Share on other sites

  • 8 months later...

Hello everyone i'm new in this forum.

I have a problem:

I'm trying to import product with csv format in prestashop, i found a cron by corderwall and i'm trying to work it on my website.

I can access to prestashop with token but when i launch my script it reminds me an error "invalid security token prestashop"  and then  when i click on "I note serious risks" button  it leads me directly to AdminImport page.

How can i bypass the error if invalid security token? my version of prestashop is 1.6.1.1.

Thank in advance

Best regards

Ela

post-1134441-0-22831200-1467018030_thumb.jpg

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...