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

MiNi SheLL

Current Path : /home/vmanager/www/backend/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/backend/controllers/BannersreservationsController.php

<?php

namespace backend\controllers;

use Yii;
use common\models\BannersReservations;
use common\models\BannersReservationsVersions;
use backend\models\BannersReservationsSearch;
use backend\models\BannersReservationsVersionsSearch;
use backend\models\CompaniesSearch;
use backend\models\SendBannerReservationVersionForm;
use common\models\Users;
use common\models\types\ContactDataType;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\filters\AccessControl;
use yii\bootstrap\ActiveForm;
use yii\web\Response;

/**
 * BannersreservationsController implements the CRUD actions for BannersReservations model.
 */
class BannersreservationsController extends Controller
{
    use \backend\components\traits\ControllerFunctions;
    
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    ['allow' => true, 'actions' => ['create', 'companies-list'], 'roles' => ['createBannersReservations', 'createOwnBannersReservations']],
                    ['allow' => true, 'actions' => ['index'], 'roles' => ['indexBannersReservations']],
                    ['allow' => true, 'actions' => ['view'], 'roles' => ['viewBannersReservations']],
                    ['allow' => true, 'actions' => ['send-version'], 'roles' => ['sendBannersReservationsVersions']], 
                    ['allow' => true, 'actions' => ['update', 'delete', 'index-versions', 'create-version', 'accept-version', 'view-version', 'delete-version', 'request-publication'], 'roles' => ['@']],                    
                    ['allow' => true, 'actions' => ['create-banner'], 'roles' => ['createBanners']],
                ]
            ]
        ];
    }

    /**
     * Lists all BannersReservations models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BannersReservationsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single BannersReservations model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new BannersReservations model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BannersReservations(['scenario' => 'create']);
        
        if(Yii::$app->user->can('createBannersReservations')) {
            $model->setScenario('create');
        } elseif(Yii::$app->user->can('createOwnBannersReservations')) {
            $model->setScenario('createOwn');
            $model->id_user = Yii::$app->user->id;           
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }  
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model, ['id_user', 'id_company', 'id_portal', 'date_start', 'date_end']);
        }
        
        if(Yii::$app->request->getIsPost()) { 
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('create', ['model' => $model]);
            }
            
            $model->loadImageFile(); //plik podstawowy
                  
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('create', ['model' => $model]);
            }
            
            $newImagePath = $model->saveImageFile();
            if($newImagePath === false) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                return $this->render('create', ['model' => $model]);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $model->save(false);            
            $flag = $flag && $this->sendEmail($model);
            
            if ($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['update', 'id' => $model->id_reservation]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                if(!empty($newImagePath)) {
                    @unlink($newImagePath);
                }
            }
        }
        
        return $this->render('create', [
            'model' => $model
        ]);
    }

    /**
     * Updates an existing BannersReservations model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        
        if(Yii::$app->user->can('updateBannersReservations')) {
            $model->setScenario('update');
        } elseif(Yii::$app->user->can('updateOwnBannersReservations', ['model' => $model])) {
            $model->setScenario('updateOwn');
            $model->id_user = Yii::$app->user->id;           
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        } 
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model, ['id_user', 'id_company', 'id_portal', 'date_start', 'date_end']);
        }
        
        if(Yii::$app->request->getIsPost()) {             
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('update', ['model' => $model]);
            }
            
            $oldImagePath = $model->loadImageFile();
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('update', ['model' => $model]);
            }
            
            $newImagePath = $model->saveImageFile();
            if($newImagePath === false) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                return $this->render('update', ['model' => $model]);
            }
            
            $flag = $model->save(false);            
            $flag = $flag && $this->sendEmail($model);
            
            if ($flag) {
                if(!empty($oldImagePath)) {
                    @unlink($oldImagePath);
                }
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['update', 'id' => $model->id_reservation]);
            } else {
                if(!empty($newImagePath)) {
                    @unlink($newImagePath);
                }
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
            }
        }
        
        return $this->render('update', [
            'model' => $model
        ]);
    }

    /**
     * Deletes an existing BannersReservations model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        
        if(!Yii::$app->user->can('deleteBannersReservations', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if($model->delete() !== false) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));
        }
        else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
        }
        
        return $this->redirect((Yii::$app->request->getReferrer() && strpos(Yii::$app->request->getReferrer(), '/bannersreservations/view/') === false) ? Yii::$app->request->getReferrer() : ['bannersreservations/index']);
    }    
    
    public function actionRequestPublication($id)
    {
        $model = $this->findModel($id);
        
//        if(!Yii::$app->user->can('requestPublicationBannersReservationsVersions', ['model' => $model])) {
//            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
//        } 
        
        if(empty($model->filename)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['view', 'id' => $model->id_reservation]);
        }
            
        $mailer = Yii::$app->mailer;
        $mailer->htmlLayout = 'layouts/main-html';      
        $mailer->textLayout = 'layouts/main-text';   
        
        //wysyłamy do Łukasza informację z prośbą o opublikowanie banera (###MAIL_90###)    
        $email = \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();            
        //@todo proteza
//        $email = 'r.sobieszczyk86@gmail.com';
        
        $flag = $mailer->compose(
                [
                    'html' => 'request_publication_of_banner_reservation_for_admin_html',
                    'text' => 'request_publication_of_banner_reservation_for_admin_text'
                ],
                [
                    'model' => $model,
                ]
            )
            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
            ->setTo($email)
            ->setSubject(Yii::t('common-mails', 'Opublikuj baner dla firmy {companyName}', ['companyName' => $model->company->name]))
            ->send();        
        
        if($flag) {
            //wysyłamy do osoby zgłaszającej potwierdzenie o wysłaniu prośby o opublikowanie banera (###MAIL_91###)
            $email = \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' => Yii::$app->user->id
                    ])
                    ->scalar();
            //@todo proteza
//            $email = 'r.sobieszczyk86@gmail.com';

            $flag = $mailer->compose(
                    [
                        'html' => 'request_publication_of_banner_reservation_for_operator_html',
                        'text' => 'request_publication_of_banner_reservation_for_operator_text'
                    ],
                    [
                        'model' => $model,
                    ]
                )
                ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                ->setTo($email)
                ->setSubject(Yii::t('common-mails', 'Zlecono publikację banera dla firmy {companyName}', ['companyName' => $model->company->name]))
                ->send();
        }
        
        if($flag) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie wykonano zadanie.'));
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas wysyłania wiadomości.'));            
        }        
        
        return $this->redirect(['view', 'id' => $model->id_reservation]);
    }
    
    /**
     * Creates a new Banners model based on BannersReservations model.
     * If creation is successful, the browser will be redirected to the 'update' page.
     * @param integer $id
     * @return mixed
     */
    public function actionCreateBanner($id)
    {
        $modelReservation = $this->findModel($id);
//        if(empty($modelReservation->filename)) {
//            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
//            return $this->redirect(['index']);
//        }
        
        $modelBanner = new \common\models\Banners(['scenario' => 'createFromReservation']);
        $modelBanner->setAttributes($modelReservation->toArray());
        if(empty($modelBanner->title)) {
            $modelBanner->title = 'Tytuł';
        }  
        if(empty($modelBanner->url)) {
            $modelBanner->url = 'http://www.vertica.pl';
        }  
        if(empty($modelBanner->width)) {
            $modelBanner->width = 100;
        }  
        if(empty($modelBanner->height)) {
            $modelBanner->height = 100;
        }
        $modelBanner->status = \common\models\types\Status::INACTIVE;
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $filePath = $modelReservation->getImageUrl();
        if($filePath) {            
            $fileInfo = pathinfo($filePath); 
            $modelBanner->filename = \common\models\Banners::createFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']);            
            
            //tylko po to, aby przeszła walidacja
            $_FILES = [
                'temp_file' => [
                    'name' => $modelReservation->filename,
                    'type' => 'image/'.$fileInfo['extension'],
                    'size' => filesize($filePath),
                    'tmp_name' => $filePath,
                    'error' => 0
                ]
            ];
            
            //tylko po to, aby przeszła walidacja
            $modelBanner->file = \yii\web\UploadedFile::getInstanceByName('temp_file');
        }
        
        if(!$modelBanner->save()) {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
            return $this->redirect(['index']);
        }
        
        if($filePath) {
            $sourcePath = Yii::getAlias('@bannersReservationsImagesRealPath').'/'.$modelReservation->filename; 
            $targetPath = Yii::getAlias('@bannersImagesRealPath').'/'.$modelBanner->filename; 
            if(copy($sourcePath, $targetPath) === FALSE) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                return $this->redirect(['index']);
            }
        }
        
        $transaction->commit();
        Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
        return $this->redirect(['banners/update', 'id' => $modelBanner->id_banner]); 
    }
    
    protected function sendEmail($model)
    {
        $idsOperators = [$model->id_user => $model->id_user];
        if(!empty($model->portal->id_user)) {
            $idsOperators[$model->portal->id_user] = $model->portal->id_user;
        } 

        $modelsOperators = \common\models\Users::find()
            ->select(['id_user', 'forename', 'surname'])
            ->with([
                'contactData' => function($q) {
                    $q->where([
                        'required' => 1,
                        'data_type' => \common\models\types\ContactDataType::EMAIL
                    ]);
                }
            ])
            ->where(['id_user' => array_values($idsOperators)])
            ->indexBy('id_user')
            ->all();

        $recipientsEmails = [];
        foreach($modelsOperators as $modelOperator) {
            $recipientsEmails[] = $modelOperator->contactData[0]->data_value;
        }

        $bannersLocationsLabels = \common\models\types\BannerLocation::getValuesWithLabels();

        //wysyłamy email z informacją o nowej/zaktualizowanej rezerwacji baneru (###MAIL_78###) 
        $mailer = Yii::$app->mailer;
        $mailer->htmlLayout = 'layouts/main-html';      
        $mailer->textLayout = 'layouts/main-text';           
        $flag = $mailer->compose(
                [
                    'html' => 'notify_about_new_banner_reservation_html',
                    'text' => 'notify_about_new_banner_reservation_text'
                ],
                [
                    'modelBannerReservation' => $model,
                    'location' => $bannersLocationsLabels[$model->location],
                    'operatorForename' => $modelsOperators[$model->id_user]->forename,
                    'operatorSurname' => $modelsOperators[$model->id_user]->surname
                ]
            )
            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
            ->setTo($recipientsEmails)
//                    ->setTo('r.sobieszczyk86@gmail.com')
            ->setSubject(Yii::t('common-mails', 'Rezerwacja banera {position} na portalu {domain} w dniach {dateStart} - {dateEnd}', [
                'position' => $bannersLocationsLabels[$model->location], 
                'domain' => $model->portal->domain,
                'dateStart' => Yii::$app->formatter->asDate($model->date_start, 'php:Y-m-d'),
                'dateEnd' => Yii::$app->formatter->asDate($model->date_end, 'php:Y-m-d'),
            ]))
            ->send();
        
        return $flag;
    }
    
    /**
     * Lists all BannersReservationsVersions models.
     * @param integer $id
     * @return mixed
     */
    public function actionIndexVersions($id)
    {
        $modelReservation = $this->findModel($id);
        
        if(!Yii::$app->user->can('indexBannersReservationsVersions', ['model' => $modelReservation])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['BannersReservationsVersionsSearch']['id_reservation'] = $modelReservation->id_reservation;
        
        $searchModel = new BannersReservationsVersionsSearch();
        $dataProvider = $searchModel->search($queryParams);

        return $this->render('index_versions', [
            'modelReservation' => $modelReservation,
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    /**
     * Creates a new BannersReservationsVersions model.
     * If creation is successful, the browser will be redirected to the 'versions-index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionCreateVersion($id)
    {
        $modelReservation = $this->findModel($id);
        
        if(!Yii::$app->user->can('createBannersReservationsVersions', ['model' => $modelReservation])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $model = $this->createNewModelBannerReservationVersion($modelReservation);
        
        $outputParams = [
            'model' => $model,
            'modelReservation' => $modelReservation
        ];
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('create_version', $outputParams);
            }
            
            $model->loadFile();
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('create_version', $outputParams);
            }
            
            $newFilePath = $model->saveFile();
            if($newFilePath === false) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                return $this->conditionalRender('create_version', $outputParams);
            }
            
            
            $transaction = Yii::$app->db->beginTransaction();
              
            if($model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['bannersreservations/index-versions', 'id' => $modelReservation->id_reservation]);
                }
                else {
                    $outputParams['model'] = $this->createNewModelBannerReservationVersion($modelReservation);
                }
            } else {
                if(!empty($newFilePath)) {
                    @unlink($newFilePath);
                }
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
                
        return $this->conditionalRender('create_version', $outputParams);
    }
    
    /**
     * Deletes an existing BannersReservationsVersions model.
     * If deletion is successful, the browser will be redirected to the 'index-versions' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDeleteVersion($id)
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;       
        
        if(($model = BannersReservationsVersions::findOne($id)) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        if(!Yii::$app->user->can('deleteBannersReservationsVersions', ['model' => $model->reservation])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $idReservation = $model->id_reservation;
        
        $transaction = Yii::$app->db->beginTransaction();                
        if($model->delete()) {
            $transaction->commit();
        } else {
            $transaction->rollBack();
        }
        
        return Yii::$app->getResponse()->redirect(['bannersreservations/index-versions', 'id' => $idReservation], 302, false);
    }
    
    public function actionAcceptVersion($id)
    {
        if(($model = BannersReservationsVersions::findOne($id)) === null || $model->or_accepted === 1) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelReservation = $model->reservation;
        
        if(!Yii::$app->user->can('acceptBannersReservationsVersions', ['model' => $modelReservation])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $flag = true;
        
        $transaction = Yii::$app->db->beginTransaction();  
        
        $othersModels = $modelReservation->getVersions()->andWhere(['or_accepted' => 1])->all();
        if(!empty($othersModels)) {
            foreach($othersModels as $otherModel) {
                $otherModel->or_accepted = 0;
                if(!$otherModel->save(false)) {
                    $flag = false;
                    break;
                }
            }
        }
        
        $model->or_accepted = 1;
        $flag = $flag && $model->save(false);
        
        if($flag) {
            $oldBannerReservationFilePath = $modelReservation->getImageUrl();
            $bannerReservationVersionFilePath = $model->getUrl();
            
            list($width, $height) = getimagesize($bannerReservationVersionFilePath);
            $modelReservation->width = $width;
            $modelReservation->height = $height; 
            
            $fileInfo = pathinfo($bannerReservationVersionFilePath); 
            $modelReservation->filename = BannersReservations::createFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']);
            
            $flag = $modelReservation->save(false);
        }
                      
        if($flag) {
            $emails = \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_marcin', Yii::$app->user->identity->login]
                ])
                ->column();
            
            //@todo proteza
//            $emails = ['r.sobieszczyk86@gmail.com'];
            
            //wysyłamy emaile z informacją o zaakceptowaniu wersji baneru w rezerwacji do operatora akceptującego oraz do Marcina (###MAIL_89###) 
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = 'layouts/main-html';      
            $mailer->textLayout = 'layouts/main-text';           
            $flag = $mailer->compose(
                    [
                        'html' => 'banner_reservation_version_accepted_html',
                        'text' => 'banner_reservation_version_accepted_text'
                    ],
                    [
                        'model' => $model,
                    ]
                )
                ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                ->setTo($emails)
                ->setSubject(Yii::t('common-mails', 'Baner dla firmy {companyName} został zaakceptowany', ['companyName' => $model->reservation->company->name]))
                ->send();
        }
        
        $flag = $flag && copy(Yii::getAlias('@bannersReservationsImagesRealPath').'/'.$model->filename, Yii::getAlias('@bannersReservationsImagesRealPath').'/'.$modelReservation->filename);
        
        if($flag) {
            $transaction->commit();
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
            if(!empty($oldBannerReservationFilePath)) {
                @unlink($oldBannerReservationFilePath);
            }
        } else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));            
        }
        
        return $this->redirect(['bannersreservations/index-versions', 'id' => $model->id_reservation]);
    }
    
    public function actionSendVersion($id)
    {        
        if(($model = BannersReservationsVersions::findOne($id)) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelForm = new SendBannerReservationVersionForm(['id_version' => $model->id_version]);
        
        $outputParams = [
            'model' => $model,
            'modelForm' => $modelForm,
        ];
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($modelForm, ['id_operator', 'id_version']);
        }
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('send_version', $outputParams);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->conditionalRender('send_version', $outputParams);
            }        
                        
            $modelOperatorRecipient = Users::find()
                ->select(['id_user', 'forename', 'surname'])
                ->with([
                    'contactData' => function($q) {
                        $q->where([
                            'required' => 1,
                            'data_type' => ContactDataType::EMAIL
                        ]);
                    }
                ])
                ->where(['id_user' => $modelForm->id_operator])
                ->one();
            
            $operatorRecipientEmail = $modelOperatorRecipient->contactData[0]->data_value;

            //@todo proteza
//            $operatorRecipientEmail = 'r.sobieszczyk86@gmail.com';

            //wysyłamy email z wersją baneru dla rezerwacji (###MAIL_88###) 
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = 'layouts/main-html';      
            $mailer->textLayout = 'layouts/main-text';           
            $flag = $mailer->compose(
                    [
                        'html' => 'banner_reservation_version_for_accept_html',
                        'text' => 'banner_reservation_version_for_accept_text'
                    ],
                    [
                        'model' => $model,
                        'annotations' => $modelForm->annotations
                    ]
                )
                ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                ->setTo($operatorRecipientEmail)
                ->setSubject(Yii::t('common-mails', 'Baner do akceptacji dla firmy {companyName}', ['companyName' => $model->reservation->company->name]))
                ->send();
            
            if($flag) {    
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Wiadomość została wysłana.')); 
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas wysyłania wiadomości.'));                
            }
        }
       
        return $this->conditionalRender('send_version', $outputParams);
    }
    
    public function actionViewVersion($id)
    {        
        if(($model = BannersReservationsVersions::findOne($id)) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelReservation = $model->reservation;
        
        if(!Yii::$app->user->can('viewBannersReservationsVersions', ['model' => $modelReservation])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $outputParams = [
            'model' => $model,
        ];
        
        return $this->render('view_version', $outputParams);
    }
    
    protected function createNewModelBannerReservationVersion($modelReservation)
    {
        $model = new BannersReservationsVersions(['scenario' => 'create']);
        $model->id_reservation = $modelReservation->id_reservation;
        $model->version_number = (int)$modelReservation->getVersions()->max('version_number') + 1;
        
        return $model;
    }
    
    /**
     * Finds the BannersReservations model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return BannersReservations the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BannersReservations::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    public function actionCompaniesList()
    {
        $searchModel = new CompaniesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->renderAjax('companies_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
}

Creat By MiNi SheLL
Email: jattceo@gmail.com