Commit c4da20f01cf2dcb0a7429577c38d9e607c51b419

Authored by Mihail
1 parent 8f043ab6

temp commit - testing mail parser

backend/components/base/BaseActiveRecord.php
... ... @@ -9,4 +9,17 @@
9 9 namespace backend\components\base;
10 10  
11 11  
12   -class BaseActiveRecord extends \yii\db\ActiveRecord {}
13 12 \ No newline at end of file
  13 +use yii\base\ErrorException;
  14 +
  15 +class BaseActiveRecord extends \yii\db\ActiveRecord {
  16 +
  17 + public function throwStringErrorException(){
  18 +
  19 + $errors_str = '';
  20 + foreach ($this->getErrors() as $error) {
  21 + $errors_str .= implode( array_values($error) );
  22 + }
  23 + throw new ErrorException( $errors_str );
  24 + }
  25 +
  26 +}
14 27 \ No newline at end of file
... ...
backend/controllers/ParserController.php
1 1 <?php
2 2 namespace backend\controllers;
3 3  
  4 +use common\components\archives\ArchiveCreator;
  5 +use common\components\mail\ImapMailReader;
  6 +use common\components\mail\MailAttachmentsSaver;
4 7 use common\components\parsers\MailParser;
5 8 use Yii;
6 9 use yii\data\ActiveDataProvider;
... ... @@ -53,8 +56,8 @@ class ParserController extends BaseController
53 56  
54 57 public function actionIndex($mode = 0)
55 58 {
  59 + $this->mailTest();
56 60 $model = new UploadFileParsingForm();
57   - // $mail = new MailParser();
58 61 // установим режим, 0 - ручная загрузка, 1 - автозагрузка
59 62 $model->mode = $mode;
60 63 return $this->render('index', ['model' => $model]);
... ... @@ -126,11 +129,12 @@ class ParserController extends BaseController
126 129  
127 130 } else {
128 131 // не прошла валидация форма загрузки файлов
129   - $errors_str = '';
130   - foreach ($model->getErrors() as $error) {
131   - $errors_str .= implode( array_values($error) );
132   - }
133   - throw new ErrorException( $errors_str );
  132 +// $errors_str = '';
  133 +// foreach ($model->getErrors() as $error) {
  134 +// $errors_str .= implode( array_values($error) );
  135 +// }
  136 +// throw new ErrorException( $errors_str );
  137 + $model->throwStringErrorException();
134 138 }
135 139 // листаем пагинатором, или повторно вызываем - считываем из кеша отпрасенные данные
136 140 } else if (Yii::$app->getCache()->get('parser_data')) {
... ... @@ -287,5 +291,71 @@ class ParserController extends BaseController
287 291 // $csv->actionParseCsv();
288 292 }
289 293  
  294 + private function mailTest(){
  295 +
  296 + $mail_reader = new ImapMailReader( '{imap.gmail.com:993/imap/ssl/novalidate-cert}', 'tsurkanovm@gmail.com', 'Wtvr@2000' );
  297 + $mailboxes = $mail_reader->getListMailboxes();
  298 + $files = [];
  299 + foreach ( $mailboxes as $custom_label ) {
  300 + $words = explode(" ",str_replace( array($mail_reader->getHostname(),"!"),"",imap_utf7_decode($custom_label)) );
  301 + $importer_id = (int)preg_replace("/[^A-Z0-9]+/","", strtoupper($words[0]));
  302 +
  303 + $mail_reader->reOpen( $custom_label );
  304 + $saver = new MailAttachmentsSaver( $mail_reader );
  305 + if ( $importer_id ) {
  306 + $saver->setFileNamePrefix( $importer_id . '~!~' );
  307 + }
  308 +
  309 + if( $saver->saveAttachmentsTo(\Yii::getAlias('@temp_upload'), 'UNSEEN') ){
  310 + $files = array_merge( $files, $saver->getSavedFilesArr() );
  311 + }else{
  312 + continue;
  313 + }
  314 +
  315 + }
  316 +
  317 + if ( !$files ) {
  318 + return;
  319 + }
  320 +
  321 + $arch_creator = new ArchiveCreator();
  322 + $arch_extensions = $arch_creator->getHandleExtension();
  323 + $arch_files = array_intersect( $files , $arch_extensions );
  324 + foreach ($arch_files as $arch_name => $arch_ext) {
  325 + $arch_reader = $arch_creator->create( $arch_name, $arch_ext );
  326 + $arch_reader->extractTo(\Yii::getAlias('@temp_upload'));
  327 + unset( $files[$arch_name] );
  328 + $files = array_merge( $files, $arch_reader->getExtractedFiles());
  329 + }
  330 +
  331 + $new_destination = \Yii::getAlias('@auto_upload') . '/';
  332 + foreach ( $files as $name => $ext ) {
  333 +
  334 + $file_name = pathinfo($name, PATHINFO_FILENAME) . '.' . $ext;
  335 + if( $ext = 'csv' ){
  336 + $files_model = new ImportersFiles();
  337 + $files_model->importer_id = $importer_id;
  338 + if ($files_model->save()) {
  339 +
  340 + $file_name = \Yii::$app->db->getLastInsertID() . '.csv';
  341 +
  342 + } else{
  343 +
  344 + $files_model->throwStringErrorException();
  345 + }
  346 +
  347 + }
  348 + $new_destination .= $file_name;
  349 + if( rename( $name, $new_destination ) ){
  350 +
  351 + CustomVarDamp::dump('1111111');
  352 +
  353 + } else{
  354 + new \ErrorException("Нет возможности переписать файл {$name}");
  355 + }
  356 +
  357 + }
  358 +
  359 + }
290 360  
291 361 }
... ...
common/components/archive_reader/ArchiveCreator.php deleted
1   -<?php
2   -/**
3   - * Created by PhpStorm.
4   - * User: Tsurkanov
5   - * Date: 03.11.2015
6   - * Time: 14:51
7   - */
8   -
9   -namespace common\components\archive_reader;
10   -
11   -
12   -class ArchiveCreator {
13   -
14   - protected $handleExtension = [];
15   -
16   - public function create( $file, $ext ){
17   - if ( isHandableExtension( $ext )) {
18   - $arh_class = ucfirst( $ext ) . 'ArchiveReader';
19   - if ( class_exists( $arh_class ) ) {
20   -
21   - $arh_reader = new $arh_class();
22   -
23   - if ($arh_reader instanceof ArchiveReader ) {
24   - $arh_reader->open($file);
25   - return $arh_reader;
26   - }
27   -
28   - }
29   -
30   - }
31   - // не найден подходящий обработчик
32   - throw new \Exception( "Для расширения {$ext} не найден подходящий распаковщик" );
33   - }
34   -
35   - protected function isHandableExtension( $ext ){
36   -
37   - $this->setHandleExtension( );
38   - return (bool) array_search( $ext, $this->handleExtension);
39   - }
40   -
41   - protected function setHandleExtension( ){
42   - if ( !$this->handleExtension ) {
43   - foreach (get_declared_classes() as $class) {
44   - if (is_subclass_of( $class, ArchiveReader::class ))
45   -
46   - $this->handleExtension[] = $class::getExtension();
47   -
48   - }
49   - }
50   - }
51   -
52   - public function getHandleExtension( ){
53   -
54   - return $this->handleExtension;
55   -
56   - }
57   -
58   -
59   -}
60 0 \ No newline at end of file
common/components/archives/ArchiveCreator.php 0 → 100644
  1 +<?php
  2 +/**
  3 + * Created by PhpStorm.
  4 + * User: Tsurkanov
  5 + * Date: 03.11.2015
  6 + * Time: 14:51
  7 + */
  8 +
  9 +namespace common\components\archives;
  10 +
  11 +
  12 +class ArchiveCreator {
  13 +
  14 + protected $handleExtension = ['rar', 'zip'];
  15 +
  16 + public function create( $file, $ext ){
  17 +// if ( $this->isHandleableExtension( $ext )) {
  18 +// $arh_class = ucfirst( $ext ) . 'ArchiveReader';
  19 +// if ( class_exists( $arh_class ) ) {
  20 +//
  21 +// $arh_reader = new $arh_class();
  22 +//
  23 +// if ($arh_reader instanceof ArchiveReader ) {
  24 +// $arh_reader->open($file);
  25 +// return $arh_reader;
  26 +// }
  27 +//
  28 +// }
  29 +//
  30 +// }
  31 + if ( $ext = 'zip' ) {
  32 + $arh_reader = new ZipArchiveReader();
  33 + }else{
  34 + $arh_reader = new RarArchiveReader();
  35 + }
  36 +
  37 + $arh_reader->open($file);
  38 + return $arh_reader;
  39 + // не найден подходящий обработчик
  40 + throw new \Exception( "Для расширения {$ext} не найден подходящий распаковщик" );
  41 + }
  42 +
  43 + protected function isHandleableExtension( $ext ){
  44 +
  45 + // $this->setHandleExtension( );
  46 + return (bool) array_search( $ext, $this->handleExtension);
  47 + }
  48 +
  49 +// protected function setHandleExtension( ){
  50 +// if ( !$this->handleExtension ) {
  51 +// foreach (get_declared_classes() as $class) {
  52 +// if (is_subclass_of( $class, ArchiveReader::class ))
  53 +//
  54 +// $this->handleExtension[] = $class::getExtension();
  55 +//
  56 +// }
  57 +// }
  58 +// }
  59 +
  60 + public function getHandleExtension( ){
  61 +
  62 + // $this->setHandleExtension( );
  63 + return $this->handleExtension;
  64 +
  65 + }
  66 +
  67 +
  68 +}
0 69 \ No newline at end of file
... ...
common/components/archive_reader/ArchiveReader.php renamed to common/components/archives/ArchiveReader.php
... ... @@ -5,7 +5,7 @@
5 5 * Date: 03.11.2015
6 6 * Time: 14:48
7 7 */
8   -namespace common\components\archive_reader;
  8 +namespace common\components\archives;
9 9 abstract class ArchiveReader
10 10 {
11 11  
... ...
common/components/archive_reader/RarArchiveReader.php renamed to common/components/archives/RarArchiveReader.php
... ... @@ -6,19 +6,31 @@
6 6 * Time: 15:12
7 7 */
8 8  
9   -namespace common\components\archive_reader;
  9 +namespace common\components\archives;
10 10  
11 11  
12 12 class RarArchiveReader extends ArchiveReader {
13 13  
  14 + protected $resource;
14 15 public function open( $file, $password = '' ){
15   - $rar_arch = \RarArchive::open( $file, $password );
16   - if ($rar_arch === FALSE)
17   - die("Failed opening file");
  16 +
  17 + $this->resource = rar_open( $file, $password );
  18 + if ($this->resource === FALSE)
  19 + throw new \Exception("Failed opening rar file");
18 20 }
19 21  
20 22 public function extractTo( $destination){
  23 + $list = rar_list($this->resource);
  24 +
  25 + foreach($list as $file) {
  26 + $entry = rar_entry_get($this->resource, $file);
  27 + $entry->extract($destination);
  28 +
  29 + $this->setExtractedFiles($entry->getName(), pathinfo($entry->getName(), PATHINFO_EXTENSION));
  30 +
  31 + }
21 32  
  33 + rar_close($this->resource);
22 34 }
23 35 public static function getExtension(){
24 36 return 'rar';
... ...
common/components/archives/ZipArchiveReader.php 0 → 100644
  1 +<?php
  2 +/**
  3 + * Created by PhpStorm.
  4 + * User: Tsurkanov
  5 + * Date: 03.11.2015
  6 + * Time: 15:12
  7 + */
  8 +
  9 +namespace common\components\archives;
  10 +
  11 +
  12 +class ZipArchiveReader extends ArchiveReader {
  13 +
  14 + protected $resource;
  15 + public function open( $file, $password = '' ){
  16 + $zip = new \ZipArchive;
  17 + $this->resource = $zip->open( $file );
  18 + if ($this->resource === FALSE)
  19 + throw new \Exception("Failed opening zip file");
  20 + }
  21 +
  22 + public function extractTo( $destination){
  23 +
  24 + $this->resource->extractTo($destination);
  25 +
  26 + for ($i = 0; $i < $this->resource->numFiles; $i++) {
  27 + $filename = $this->resource->getNameIndex($i);
  28 + $this->setExtractedFiles($filename, pathinfo($filename, PATHINFO_EXTENSION));
  29 + }
  30 +
  31 + $this->resource->close();
  32 + }
  33 + public static function getExtension(){
  34 + return 'rar';
  35 + }
  36 +
  37 +
  38 +
  39 +
  40 +}
0 41 \ No newline at end of file
... ...
common/components/mail/MailAttachmentsSaver.php
... ... @@ -38,23 +38,33 @@ class MailAttachmentsSaver
38 38 /**
39 39 * @var - префикс который будет прибавлен к оригинальному имени сохраняемого файла
40 40 */
41   - public $file_name_prefix;
  41 + protected $file_name_prefix;
42 42  
43   - public function __construct(MailReader $mail_reader, $massage_type)
  43 +
  44 +
  45 + public function __construct(MailReader $mail_reader)
44 46 {
45 47 $this->mail_reader = $mail_reader;
46   - $this->massage_type = $massage_type;
  48 +
47 49 $this->saved_files_arr = [];
48 50  
49 51 }
50 52  
  53 + /**
  54 + * @param mixed $file_name_prefix
  55 + */
  56 + public function setFileNamePrefix($file_name_prefix)
  57 + {
  58 + $this->file_name_prefix = $file_name_prefix;
  59 + }
51 60  
52   - public function saveAttachmentsTo( $destination )
  61 + public function saveAttachmentsTo( $destination, $massage_type )
53 62 {
  63 + $this->massage_type = $massage_type;
54 64 $emails = $this->mail_reader->getEmails($this->massage_type);
55 65  
56 66 /* if emails are returned, cycle through each... */
57   -
  67 + $result = false;
58 68 if ($emails) {
59 69  
60 70 /* begin output var */
... ... @@ -116,6 +126,7 @@ class MailAttachmentsSaver
116 126 mb_internal_encoding("UTF-8");
117 127 file_put_contents($name, $val['attachment']);
118 128 $this->setSavedFile( $name , $ext );
  129 + $result = true;
119 130 }
120 131  
121 132 }
... ... @@ -127,6 +138,7 @@ class MailAttachmentsSaver
127 138  
128 139 }
129 140  
  141 + return $result;
130 142 }
131 143  
132 144 /**
... ...
console/controllers/ParserController.php
... ... @@ -150,12 +150,18 @@ class ParserController extends Controller
150 150 $files = array_merge( $files, $arch_reader->getExtractedFiles());
151 151 }
152 152  
153   - foreach ( $files as $file => $key ) {
  153 + foreach ( $files as $name => $ext ) {
  154 + $file_name = '';
  155 + if( $ext = 'csv' ){
  156 + $files_model = new ImportersFiles();
  157 + $files_model->importer_id = $importer_id;
  158 + if ($files_model->save()) {
  159 + $file_name = \Yii::$app->db->getLastInsertID();
  160 + } // обработчик ошибки !!!!!
154 161  
  162 + }
155 163  
156   - // $files_model = new ImportersFiles();
157   -// $files_model->importer_id = $importer_id;
158   - // $db->lastInsertId()
  164 + // переписываем файл в автолоад папку, и переименовываем если указано имя
159 165 }
160 166  
161 167 }
... ...