审查视图

lib/Mail/Imap.php 37.1 KB
1  
邓超 authored
1 2 3
<?php
declare(strict_types=1);
1  
邓超 authored
4
namespace Lib\Mail;
1  
邓超 authored
5
1  
邓超 authored
6
use Lib\Mail\Body;
1  
邓超 authored
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147


/**
 * imap协议直连服务器无需 imap扩展
 * @time 2022/8/5 14:17
 * Class Imap
 * @package App\Mail\lib\socket
 */
class Imap {

    /**
     * @var resource
     */
    private $socket;

    /**
     * ssl://imap.qq.com:993
     * @var string
     */
    private $host;

    /** 邮箱
     * @var
     */
    private $username;

    /**
     * 邮箱密码,单独设置的imap密码
     * @var
     */
    private $password;

    /**
     * 请求时增加的tag
     * @var int
     */
    private $tagNum = 0;

    /**
     * 标签名称
     * @var string
     */
    private $tagName    =   'A';

    /**
     * imap服务器设置id 邮箱邮件服务器是必须的
     * @var string[]
     */
    private $imapId = [
        'name'  =>  'global so Client',
        'version'   =>  '1',
        'os'    =>  'global so',
        'os-version'    =>  '1.0'
    ];


    /**
     * 超时时间
     * @var int
     */
    private $timeout = 30;

    /**
     * 搜索字段,标题,邮件主题
     */
    const SEARCH_FILED_SUBJECT = 'SUBJECT';

    /**
     * 搜索字段,发件人
     */
    const SEARCH_FILED_FROM = 'FROM';

    /**
     * 搜索字段,收件人
     */
    const SEARCH_FILED_TO = 'TO';

//    const SEARCH_FILED_SUBJECT = 'RFC822.TEXT';


    /**
     * 邮件便签
     * @var string[]
     */
    public $flags = [
        'SEEN'      => '\\Seen', // 已读
        'DELETED'   => '\\Deleted', //删除
        'ANSWERED'  => '\\Answered',//已回复
        'DRAFT'     => '\\Draft',//草稿
        'FLAGGED'   => '\\Flagged',//星标
        'FORWARDED' => '$Forwarded',
        'MDNSENT'   => '$MDNSent',
        '*'         => '\\*',
    ];

    /**
     * 已读 标记
     */
    const FLAGS_SEEN = 'SEEN';

    /**
     * 删除 标记
     */
    const FLAGS_DELETED = 'DELETED';

    /**
     * 已回复 标记
     */
    const FLAGS_ANSWERED = 'ANSWERED';

    /**
     * 草稿 标记
     */
    const FLAGS_DRAFT = 'DRAFT';

    /**
     * 星标 标记
     */
    const FLAGS_FLAGGED = 'FLAGGED';

    /**
     * 添加邮件标签
     */
    const FLAGS_APPEND = '+';

    /**
     * 删除邮件标签
     */
    const FLAGS_REMOVE = '-';


    /**
     * 是否自动关闭
     * @var bool
     */
    private $auto_colse = true;

    /**
     * 调试模式
     * @var bool
     */
邓超 authored
148
    static bool $debug = false;
1  
邓超 authored
149 150 151 152 153

    /**
     * 调试,记录日志的目录
     * @var string
     */
邓超 authored
154
    static string $debugWritePath = '';
1  
邓超 authored
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182

    /**
     * 登录imap服务器
     * @param string $host ssl://imap.qq.com:993  imap.qq.com:143
     * @param string $username 邮箱地址 xxxxx@xx.com
     * @param string $password 密码,此密码非邮箱登录密码,是imap服务器单独设置的密码
     * @param bool $readOnly 是否以只读模式打开邮箱
     * @return bool
     * @throws \Exception
     * @author:dc
     * @time 2022/11/25 11:06
     */
    public function login(string $host,string $username,string $password,bool $readOnly=false){
        $this->host =   $host;
        $this->username =   $username;
        $this->password =   $password;

        // 查看服务器所支持的功能列表
//        $this->request('CAPABILITY');

        // 设置id,必须在登录前,163是强制的
        $strId = '';
        foreach ($this->imapId as $k=>$str){
            if(!is_array($str)){
                $strId .= '"'.str_replace(['"',"'"],'',$k).'" "'.str_replace(['"',"'"],'',$str).'" ';
            }
        }
//        "name" "测试本地 Client" "version" "1" "os" "测试本地" "os-version" "1.0"
183 184 185 186 187 188 189
        try {
            // TODO:: 有的服务器不支持id命令 这里需要try起来 有的服务器却是强制的
            $this->request('ID ('.trim($strId).')');// 这里就不处理命令返回的信箱了
        }catch (\Throwable $e){

        }
x  
邓超 authored
190
        $password = str_replace('"','\"',$password);
1  
邓超 authored
191
        // 登录
x  
邓超 authored
192
        $result = $this->request("LOGIN {$username} \"{$password}\"");
1  
邓超 authored
193 194 195

        //解析登录数据每个服务商返回的登录结果不一样,很难兼容
        if($result[0] != 'ok'){
1  
邓超 authored
196
            throw new \Exception('IMAP Login Error:'.end($result[1]),403);
1  
邓超 authored
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        }

        // 是否是只读模式
        // 只读模式不可操作邮箱任何内容,只可查看
        if($readOnly){
            $this->request('EXAMINE '.$username);
        }

        return true;
    }



    /**
     * 退出当前操作的邮箱
     * 一般情况不需要
     * @return bool
     * @throws \Exception
     * @author:dc
     * @time 2022/11/25 10:46
     */
    public function loginOut():bool {
        return $this->request('LOGOUT')[0] == 'ok';
    }

    /**
     * @param resource $socket
     */
    public function setSocket($socket,$auto_colse=true): void
    {
        $this->socket = $socket;
        // 是否自动关闭
        $this->auto_colse = $auto_colse;
    }


    /**
     * 删除带有delete标签的邮件,删除的邮件不可恢复。
     * 类似清空
     * @return bool
     * @throws \Exception
     * @author:dc
     * @time 2022/11/25 10:55
     */
    public function clearDelete():bool {
        return $this->request('EXPUNGE')[0] == 'ok';
    }

    /**
     * [
    [EXISTS] => 67 总邮件数
    [RECENT] => 1 最新的邮件
    [UIDVALIDITY] => 1
    [FLAGS] => Array 此文件夹可以操控的标签
    (
    [0] => \Answered 回复
    [1] => \Seen 已读
    [2] => \Deleted 删除
    [3] => \Draft 草稿
    [4] => \Flagged 星标
    )

    [PERMANENTFLAGS] => Array
    (
    [0] => \Answered
    [1] => \Seen
    [2] => \Deleted
    [3] => \Draft
    [4] => \Flagged
    )
    ]
     * 选择文件夹
     * @param string $folder
     * @return array
     * @throws \Exception
     * @author:dc
     * @time 2022/11/22 16:28
     */
    public function selectFolder($folder='INBOX'){
1  
邓超 authored
277 278 279 280
        if(empty($folder)){
            throw new \Exception('select folder('.$folder.') not fount');
        }
1  
邓超 authored
281 282 283
        // 选择文件夹
        $result = $this->request("SELECT \"{$folder}\"");
        if($result[0] != 'ok'){
1  
邓超 authored
284
            throw new \Exception('select folder('.$folder.') error:'.end($result[1]));
1  
邓超 authored
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
        }

        $list = [];
        foreach ($result[1] as $item){
            $item = trim($item);
            // 总数量
            if(preg_match("/^\* (\d+) EXISTS$/i",$item,$m)){
                $list['EXISTS'] = $m[1];
            }
            // 最近的
            elseif (preg_match("/^\* (\d+) RECENT$/i",$item,$m)){
                $list['RECENT'] = $m[1];
            }
            // 未读
            elseif (preg_match("/^\*.*\[UNSEEN (\d+)\]/i",$item,$m)){
                $list['UNSEEN'] = $m[1];
            }
            // tag
            elseif (preg_match("/^\* FLAGS \((.*)\)$/i",$item,$m)){
                $list['FLAGS'] = explode(' ',$m[1]);
            }
            // 其他
            elseif (preg_match("/^\*.*\[(.*)\]/i",$item,$m)){
//               是否有(),有小扩号就是数组
//               * OK [PERMANENTFLAGS (\* \Answered \Flagged \Deleted \Draft \Seen)] Permanent flags
                if(preg_match("/\((.*)\)/i",$item,$m2)){
                    $em = explode(' ',$m[1]);
                    $list[$em[0]] = explode(' ',$m2[1]);
                }else{
                    $em = explode(' ',$m[1]);
x  
邓超 authored
315
                    $list[$em[0]] = $em[1]??'';
1  
邓超 authored
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
                }
            }
        }

        return $list;
    }

    /**
     * 关闭当前打开的文件夹,
     * 使用selectFolder后才可以使用此函数
     * @return bool
     * @throws \Exception
     * @author:dc
     * @time 2022/11/25 10:40
     */
    public function closeFolder():bool{
        return $this->request('CLOSE')['0'] == 'ok';
    }

    /**
邓超 authored
336 337
     * 可参考php官方的
     * https://www.php.net/manual/en/function.imap-search.php
1  
邓超 authored
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
     * 搜索邮件,如果要获得列表,需要配合fetch使用
     * @param array $criteria 搜索[key=>value,...]
     * @param bool $return_uid 是否返回uid,默认返回邮件编号
     * @return array 返回的是搜索出来的uid,每个文件夹下面uid是唯一的
     * @throws \Exception
     * @author:dc
     * @time 2022/11/24 15:46
     */
    public function search(array $criteria,$return_uid = false):array{
        // 命令,是否返回uid
        $cmd = ($return_uid ? 'UID ' : '').'SEARCH';

        foreach ($criteria as $k=>$v){
            $v  =   addslashes($v);
            $cmd .= " {$k} \"{$v}\"";
        }

        // 获取搜索到的 uid
邓超 authored
356
        $result = $this->request(str_replace("\n","",$cmd));
1  
邓超 authored
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405

        if($result[0] != 'ok'){
            throw new \Exception('search error:'.end($result[1]));
        }

        $uids = [];
        foreach ($result[1] as $item){
            // 匹配uid
            if(preg_match("/^\* SEARCH ([0-9\s]{1,})$/i",$item,$m)){
                $uids = array_merge($uids,explode(' ',$m[1]));
            }
        }

        return $uids;
    }


    /**
     * 设置标签,删除标签
     * @param string|int|array $data 邮件的编号或者uid
     * @param array $flag 标记属性 [Imap::FLAGS_SEEN,..]
     * @param string $mod 删除或者添加 Imap::FLAGS_APPEND|Imap::FLAGS_REMOVE
     * @param bool $is_uid 是否使用uid进行标记
     * @return bool
     * @throws \Exception
     * @author:dc
     * @time 2022/11/24 16:58
     */
    public function flags($data,array $flag,string $mod = self::FLAGS_APPEND,bool $is_uid = false):bool {

        if(is_array($data)){
            $data = implode(',',$data);
        }

        // flags 标记
        foreach ($flag as $k=>$item){
            if(!isset($this->flags[$item])){
                unset($flag[$k]);
            }else{
                $flag[$k] = $this->flags[$item];
            }
        }

        // 是否是规定中的值
        if(!in_array($mod,[self::FLAGS_APPEND,self::FLAGS_REMOVE])){
            throw new \Exception('set flags error: mod');
        }

        // 请求标记
邓超 authored
406
        $result = $this->request(($is_uid?'UID ':'')."STORE {$data} {$mod}FLAGS (".implode(' ',$flag).")");
1  
邓超 authored
407 408 409 410

        return $result[0] == 'ok';
    }
x  
邓超 authored
411 412 413 414 415 416 417 418 419 420 421 422 423

    /**
     * 订阅文件夹
     * @param string $folder
     * @throws \Exception
     * @author:dc
     * @time 2024/6/14 9:30
     */
    public function subscribe(string $folder){
        $result = $this->request("SUBSCRIBE \"{$folder}\"");

    }
1  
邓超 authored
424 425 426 427 428 429 430 431 432 433 434 435 436 437
    /**
     * 获取邮箱所有文件夹
     * @return array
     * @throws \Exception
     * @author:dc
     * @time 2022/11/24 17:20
     */
    public function getFolder():array {
        // 获取数据
        $result = $this->request('LIST "" *');

        $folder = [];
        foreach ($result[1] as $item){
            // 解析源数据
邓超 authored
438
            if(preg_match('/^\*\sLIST\s\(([\\a-z\s]{0,})\)\s\"(.*)\"\s\"?(.*)\"?$/Ui',$item,$m)){
x  
邓超 authored
439 440 441 442 443 444
                $check = explode(' ',$m[1]);
                $check = array_map(function ($v){
                    $v = trim($v);
                    $v = trim($v,'\\');
                    return $v;
                },$check);
1  
邓超 authored
445 446 447
                $folder[] = [
                    'parent'    =>  $m[2],
                    // 源文件夹名称,在进行 select的时候必须用未解析的文件夹名称
邓超 authored
448
                    'folder'    =>  trim(trim($m[3]),'"'),
1  
邓超 authored
449
                    // 解析过的文件夹名称
邓超 authored
450
                    'parseFolder'    =>  mb_convert_encoding(trim(trim($m[3]),'"'), 'UTF-8', 'UTF7-IMAP'),
1  
邓超 authored
451 452
                    // 是否可选择
                    'isSelect'  =>  strpos($m[1],'NoSelect')===false,
x  
邓超 authored
453 454
                    // 这里里面包含了公共的功能文件夹 比如 草稿,发送,有些邮箱没有
                    'check'  =>  $check
1  
邓超 authored
455 456 457 458 459 460 461 462 463 464 465
                ];
            }
        }

        return $folder;
    }

    /**
     * 创建文件夹
     * $folder 目录 创建二级目录用/  a/b
     * @param string $folder
1  
邓超 authored
466
     * @return array
1  
邓超 authored
467 468
     * @throws \Exception
     * @author:dc
1  
邓超 authored
469
     * @time 2023/3/14 11:37
1  
邓超 authored
470
     */
1  
邓超 authored
471
    public function folderCreate(string $folder):array {
1  
邓超 authored
472
        // 需要转码
1  
邓超 authored
473
//        $folder = MailFun::folderEncoding($folder);
1  
邓超 authored
474 475
//        A003 CREATE owatagusiam 顶级
//        A003 CREATE owatagusiam/owatagusiam2 有上下级关系的文件夹
1  
邓超 authored
476
        $res = $this->request("CREATE \"{$folder}\"");
1  
邓超 authored
477 478

        if ($res[0] == 'ok'){
1  
邓超 authored
479
            return [true,$folder];
1  
邓超 authored
480 481
        }
1  
邓超 authored
482
        return [false,end($res[1])];
1  
邓超 authored
483 484 485 486 487 488 489

    }

    /**
     * 修改文件夹名称
     * @param string $oldFolder 久文件夹名称
     * @param string $newFolder 新文件夹名称
x  
邓超 authored
490
     * @return array
1  
邓超 authored
491 492
     * @throws \Exception
     * @author:dc
x  
邓超 authored
493
     * @time 2023/4/14 11:47
1  
邓超 authored
494 495 496 497 498 499 500 501
     */
    public function folderRename(string $oldFolder, string $newFolder){
        // 需要转码
        $newFolder  =   mb_convert_encoding($newFolder,'UTF7-IMAP','UTF-8');
//        RENAME oldfolder newfolder
        $res = $this->request("RENAME {$oldFolder} {$newFolder}");

        if ($res[0] == 'ok'){
x  
邓超 authored
502
            return [true,$newFolder];
1  
邓超 authored
503 504
        }
x  
邓超 authored
505
        return [false,end($res[1])];
1  
邓超 authored
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    }

    /**
     * 删除文件夹
     * @param string $folder
     * @return bool
     * @author:dc
     * @time 2022/11/25 10:25
     */
    public function folderDelete(string $folder):bool{

//        A683 DELETE blurdybloop/test
        $res = $this->request('DELETE '.$folder);

        if ($res[0] == 'ok'){
            return true;
        }
邓超 authored
523
        // 远程不存在
邓超 authored
524
        if(str_contains(strtolower(end($res[1])), 'folder not exist')){
邓超 authored
525 526
            return true;
        }
1  
邓超 authored
527
x  
邓超 authored
528
        return false;
1  
邓超 authored
529 530 531

    }
1  
邓超 authored
532
    /**
1  
邓超 authored
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
     * 复制
     * @param array $uids
     * @param string $folder
     * @return bool
     * @throws \Exception
     * @author:dc
     * @time 2023/3/22 16:35
     */
    public function copy(array $uids,string $folder){

        $uids = implode(',',$uids);

        $res = $this->request("UID COPY {$uids} \"{$folder}\"");

        if ($res[0] == 'ok'){
            return true;
        }

        throw new \Exception("copy error:".end($res[1]));
    }

    /**
1  
邓超 authored
555
     * 移动邮件
1  
邓超 authored
556 557 558 559
     * @param array $uids
     * @param string $folder
     * @return bool
     * @throws \Exception
1  
邓超 authored
560
     * @author:dc
1  
邓超 authored
561
     * @time 2023/3/22 18:06
1  
邓超 authored
562
     */
1  
邓超 authored
563 564 565 566 567 568 569 570 571
    public function move(array $uids,string $folder){

        $uids = implode(',',$uids);

        $res = $this->request("UID MOVE {$uids} \"{$folder}\"");

        if ($res[0] == 'ok'){
            return true;
        }
1  
邓超 authored
572
1  
邓超 authored
573 574 575 576
        throw new \Exception("move error:".end($res[1]));
    }

    /**
邓超 authored
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
     * 清除 已标记为删除的邮件 不可逆
     * @return bool
     * @throws \Exception
     * @author:dc
     * @time 2024/3/14 14:12
     */
    public function expunge(){

        $res = $this->request("EXPUNGE");

        if ($res[0] == 'ok'){
            return true;
        }

        throw new \Exception(end($res[1]));
    }

    /**
1  
邓超 authored
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
     * 删除邮件
     * @param array $uids
     * @author:dc
     * @time 2023/3/22 17:51
     */
    public function delete(array $uids){

//        $uids = implode(',',$uids);
//
//        $res = $this->request("UID DELETE {$uids} ");
//
//        if ($res[0] == 'ok'){
//            return true;
//        }
//
//        throw new \Exception("delete error:".end($res[1]));
1  
邓超 authored
611 612
    }
x  
邓超 authored
613 614 615 616 617 618 619 620 621 622 623 624
    /**
     * 判断邮件是否存在
     * @param $uid
     * @return bool
     * @throws \Exception
     * @author:dc
     * @time 2024/7/23 11:20
     */
    public function hasMail($uid){
        $result = $this->fetch($uid,'UID',true);
        return !empty($result);
    }
1  
邓超 authored
625 626 627 628 629 630 631 632 633 634 635 636 637 638

    /**
     * 获取邮件头,并解析
     * @param $data
     * @param false $is_uid
     * @return array
     * @throws \Exception
     * @author:dc
     * @time 2022/11/23 14:25
     */
    public function fetchHeader($data,$is_uid = false){
        $result = $this->fetch($data,'header',$is_uid);
        // 解析header字段
        foreach ($result as $key=>$item){
x  
邓超 authored
639 640 641 642
            if(empty($item['HEADER.FIELDS'])){
                unset($result[$key]);
                continue;
            }
邓超 authored
643
            $result[$key]['HEADER.FIELDS'] = $this->imap_header_parse($item['HEADER.FIELDS']);
1  
邓超 authored
644 645 646 647
            // 编码问题
            preg_match('/\("charset" "([a-z0-9\-]{3,})"\)/iU',$result[$key]['BODYSTRUCTURE'],$charset);
            // 编码
            if(!empty($charset[1])){
1  
邓超 authored
648 649 650
                $charset = [$charset[1]];
            }else{
                $charset = [];
1  
邓超 authored
651
            }
1  
邓超 authored
652 653

邓超 authored
654 655 656 657 658 659 660 661 662
//            if(!empty($result[$key]['HEADER.FIELDS']['Subject'])){
//                $result[$key]['HEADER.FIELDS']['Subject'] = MailFun::mb_coding($result[$key]['HEADER.FIELDS']['Subject'],$charset);
//            }
//            if(!empty($result[$key]['HEADER.FIELDS']['From'])){
//                $result[$key]['HEADER.FIELDS']['From'] = MailFun::mb_coding($result[$key]['HEADER.FIELDS']['From'],$charset);
//            }
//            if(!empty($result[$key]['HEADER.FIELDS']['To'])){
//                $result[$key]['HEADER.FIELDS']['To'] = MailFun::mb_coding($result[$key]['HEADER.FIELDS']['To'],$charset);
//            }
1  
邓超 authored
663
1  
邓超 authored
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
        }

        return $result;

    }

    /**
     * 解析header字段
     * @param $header
     * @return array
     * @author:dc
     * @time 2022/11/23 14:54
     */
    public function parseHeader($header){
        /****** 把数据中的 : 转换一下 *******/
        $header = explode("\n",$header);
        foreach ($header as $k=>$str){
            $first_str = '';
            if(substr_count($str,':') > 1){
                $str = explode(':',$str);
                $first_str = $str[0];
                if($first_str){
                    unset($str[0]);
                }
                $str = implode('_(_(_(_0_)_)_)_',$str);
                if($first_str) $str = $first_str.':'.$str;
            }
            $header[$k] = empty($first_str) ? $str : ltrim($str);
        }
        $header = implode("\n",$header);
        /******end*******/

        preg_match_all(
            "/^([^\r\n:]+)\s*[:]\s*([^\r\n:]+(?:[\r]?[\n][ \t][^\r\n]+)*)/m",
            $header,
            $matches,
            PREG_SET_ORDER
        );
        $headers = [];
        foreach($matches as $match){
            $match[2] = str_replace(['_(_(_(_0_)_)_)_'],[':'],$match[2]);
            if(strpos($match[2],'=?')!==false){
1  
邓超 authored
706 707 708
                $match[2] = mb_decode_mimeheader($match[2]);
//                $match2=iconv_mime_decode($match[2],ICONV_MIME_DECODE_CONTINUE_ON_ERROR,'utf-8');
//                if($match2) $match[2]   =   $match2;
1  
邓超 authored
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
            }

            if(isset($headers[$match[1]]) && is_array($headers[$match[1]])){
                $headers[$match[1]][]=$match[2];
            }elseif(isset($headers[$match[1]])){
                $headers[$match[1]]=array($headers[$match[1]],$match[2]);
            }else{
                $headers[$match[1]]=$match[2];
            }
        }
        return $headers;

    }

邓超 authored
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750

    /**
     * 其中的一种解法,不知有没有什么bug
     * 解析原始 header 头信息
     * @param string $header
     * @return array
     * @author:dc
     * @time 2023/6/25 17:48
     */
    public function imap_header_parse(string $header){
        $newArr = [];
        // 分割组成 每一行
        foreach (explode("\n",$header) as $item){
            if(str_starts_with($item,' ') || str_starts_with($item,"\t")){
                $newArr[count($newArr)-1][] = $item;
            }else{
                $newArr[][] = $item;
            }
        }
        // 新的数组
        // 新的数组
        foreach ($newArr as $k=>$item){
            $item = implode("\n",$item);
            $item = explode(':',$item);
            // 剔除key的值
            $item_str = ltrim(implode(':',$item),$item[0].':');
            // 解析编码
邓超 authored
751
            $item_str = $item_str?MailFun::mb_coding($item_str):$item_str;
邓超 authored
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773

//            $key = str_replace('-','_',strtolower($item[0]));
            $key = $item[0];

            // 可能出现重复的,且值不一样
            if(isset($newArr[$key])){
                if(is_string($newArr[$key])){
                    $newArr[$key] = [$newArr[$key]];
                }
                $newArr[$key][] = $item_str;
            }else{
                $newArr[$key] = $item_str;
            }

            unset($newArr[$k]);
        }

        return $newArr;
    }


1  
邓超 authored
774 775 776 777 778 779 780 781 782 783
    /**
     * 获取邮件内容,包括附件
     * @param mixed $data 1,1:10,[1,2,3]
     * @param string $saveFilePath 保存附件的目录
     * @param bool $is_uid 是否是UID查询
     * @throws \Exception
     * @author:dc
     * @time 2022/11/23 17:01
     */
    public function fetchBody($data,$saveFilePath=__DIR__,$is_uid = false){
x  
邓超 authored
784
1  
邓超 authored
785 786
        // 取得body
        $result = $this->fetch($data,'body',$is_uid);
1  
邓超 authored
787
        foreach ($result as $key=>$item){
邓超 authored
788 789 790 791 792 793
            // 兼容 有的邮箱 不支持 RFC822.TEXT
            if (empty($item['RFC822.TEXT']) && !empty($item['RFC822'])){
                $item['RFC822.TEXT'] = $item['RFC822'];
                $item['RFC822.TEXT'] = explode("\r\n\r\n",$item['RFC822.TEXT']);
                unset($item['RFC822.TEXT'][0]);
                $item['RFC822.TEXT'] = implode("\r\n\r\n",$item['RFC822.TEXT']);
邓超 authored
794
                unset($item['RFC822']);
邓超 authored
795 796
            }
1  
邓超 authored
797
            if (!empty($item['RFC822.TEXT'])){
x  
邓超 authored
798 799 800
                $header = $this->fetchHeader($item['UID'],1);
                $header = array_values($header);
                $header = $header[0]['HEADER.FIELDS']??[];
1  
邓超 authored
801
                // 解析
x  
邓超 authored
802
                $result[$key]['RFC822.TEXT'] = (new Body($item['RFC822.TEXT'],$saveFilePath,$header))->getItem();
1  
邓超 authored
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
            }
        }

        return $result;
    }



    /**
     * @param $data
     * @param false $is_uid
     * @return array
     * @throws \Exception
     * @author:dc
     * @time 2022/11/23 10:46
     */
    public function fetch($data,$header2Body='header',$is_uid = false):array{
        // string 必须是 0:99  开始:结束
        if(is_numeric($data)){
            $data = intval($data);
        }
        elseif(is_string($data)){
            if(!preg_match("/^\d+:\d+$/",$data)){
                $data = '';
            }
        }elseif (is_array($data)){
            foreach ($data as $k=>$v){
                if(!is_numeric($v)){
                    unset($data[$k]);
                }
            }
            $data = array_unique(array_values($data));
x  
邓超 authored
835
            $data = trim(implode(',',$data));
1  
邓超 authored
836 837 838 839 840 841 842 843 844 845 846 847 848
        }

        if(empty($data)){
            throw new \Exception('fetch data error');
        }

        // (UID RFC822.SIZE RFC822.HEADER FLAGS INTERNALDATE BODYSTRUCTURE BODY.PEEK[HEADER.FIELDS (DATE FROM TO SUBJECT CONTENT-TYPE CC REPLY-TO LIST-POST DISPOSITION-NOTIFICATION-TO X-PRIORITY CONTENT-TRANSFER-ENCODING BCC IN-REPLY-TO MAIL-FOLLOWUP-TO MAIL-REPLY-TO MESSAGE-ID REFERENCES RESENT-BCC RETURN-PATH SENDER X-DRAFT-INFO)])
        // 指定字段 BODY.PEEK[HEADER.FIELDS (DATE FROM TO ...)]
        // 所有header字段 RFC822.HEADER
        // RFC822.TEXT 内容包括附件
        // body字段必须放最后
        if($header2Body=='header'){
//            BODY.peek必须放最后
x  
邓超 authored
849
            $filed = 'UID FLAGS INTERNALDATE RFC822.SIZE BODYSTRUCTURE BODY.PEEK[HEADER.FIELDS (DATE FROM TO SUBJECT CONTENT-TYPE CC REPLY-TO LIST-POST DISPOSITION-NOTIFICATION-TO X-PRIORITY CONTENT-TRANSFER-ENCODING BCC IN-REPLY-TO MAIL-FOLLOWUP-TO MAIL-REPLY-TO MESSAGE-ID REFERENCES RESENT-BCC RETURN-PATH SENDER X-DRAFT-INFO AICC-HOT-MAIL)]';
1  
邓超 authored
850 851 852
        }elseif($header2Body=='body'){
            $filed = 'RFC822.TEXT';
        }else{
邓超 authored
853
            $filed = $header2Body;
1  
邓超 authored
854 855 856 857 858 859
        }

        // 读取数据
        $result = $this->request(($is_uid?'UID ':'')."FETCH {$data} ($filed)");

        if($result[0] != 'ok'){
m  
邓超 authored
860
            throw new \Exception('fetch error:'.end($result[1])."==>".($is_uid?'UID ':'')."FETCH {$data} ($filed)");
1  
邓超 authored
861 862
        }
x  
邓超 authored
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
        if ($header2Body=='body'){
            $result[1] = array_values($result[1]);

            foreach ($result[1] as $k=>$item){
                if(!isset($result[1][$k+1])){
                    break;
                }
                // * 564 FETCH (
                if(!preg_match("/^\*\s\d+\sFETCH\s\(/",$item)){
                    $result[1][$k-1] .= $item;
                    unset($result[1][$k]);
                }
            }
        }
1  
邓超 authored
878 879 880 881 882 883 884 885
        // 开始解析数据
        $list = [];
        foreach ($result[1] as $item){
            $item = trim($item);
            // 匹配出id和数据
            if(preg_match("/\* (\d+) FETCH \(([\w\s\d\r\n\W]{1,})\)$/i",$item,$line)){
                $list[$line[1]] = $this->parseFetch($line[2]);
            }
x  
邓超 authored
886
            $line = null;
1  
邓超 authored
887
        }
x  
邓超 authored
888
        $result = null;
1  
邓超 authored
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
        // 返回结果
        return $list;

    }

    /**
     * 解析头部信息,只能解析固定字段的属性
     * @param string $line
     * @return array
     * @author:dc
     * @time 2022/11/22 18:06
     */
    public function parseFetch($line):array{
        $result = [];
        $line = ltrim($line);
        $header = explode(' ',$line);
        do{

            switch ($header[0]){
                case 'UID':{
                    $result['UID'] = $header[1];
                    array_splice($header,0,2);
                    break;
                }
                case 'FLAGS':{
                    // 标记,标签
                    $result['FLAGS'] = $this->pregFiled(
                        $header,
                        "/^\(([\\a-z\s]{0,})\)/Ui"
                    );
                    $result['FLAGS'] = $result['FLAGS'] ? explode(' ',$result['FLAGS']) : [];
                    break;
                }
                case 'INTERNALDATE':{
                    // 内部时间
                    $result['INTERNALDATE'] = $this->pregFiled(
                        $header,
                        "/^\"([\\a-z\d\s]{0,})\"/Ui"
                    );
                    break;
                }
                case 'RFC822.SIZE':{
                    $result['RFC822.SIZE'] = $header[1];
                    array_splice($header,0,2);
                    break;
                }
                case 'BODYSTRUCTURE':{
                    array_shift($header);
                    $result['BODYSTRUCTURE']    =   '';
                    $leftNum = $RightNum = 0;
                    foreach ($header as $key=>$str){
                        // 还有括号不对等的情况,无语了
                        if($str == 'BODY[HEADER.FIELDS'){
                            break;
                        }
                        // 找出现的次数
                        $leftNum += substr_count($str,'(');
                        $RightNum += substr_count($str,')');
                        // 拼接起来
                        $result['BODYSTRUCTURE'] .= ' '.$str;
                        unset($header[$key]);
                        // 说明找到结束了
                        if($leftNum===$RightNum){
                            break;
                        }
                    }
                    $header = array_values($header);
                    break;
                }
                // RFC822.TEXT不能和 BODY[HEADER.FIELDS 同时存在,否则解析失败
                case 'RFC822.TEXT':{
                    array_shift($header);
邓超 authored
961
                    $result['RFC822.TEXT'] = trim(implode(' ',$header));
1  
邓超 authored
962
                    $header = [];
邓超 authored
963 964 965 966 967 968 969 970
                    // 微软的邮箱有毛病
                    $endLine = explode("\n",$result['RFC822.TEXT']);
                    $endLine = trim(end($endLine));
                    if(preg_match("/^UID\s\d+\sFLAGS\s\(.*\)$/iU",$endLine)){
                        $arr = $this->parseFetch($endLine);
                        $result = array_merge($result,$arr);
                        $result['RFC822.TEXT'] = mb_substr($result['RFC822.TEXT'],0,-mb_strlen($endLine));
                    }
1  
邓超 authored
971 972
                    break;
                }
邓超 authored
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
                // 这个是整体 包含了邮件头 RFC822.HEADER 和 RFC822.TEXT body内容
                case 'RFC822':{
                    array_shift($header);
                    $result['RFC822'] = trim(implode(' ',$header));
                    $header = [];
                    // 微软的邮箱有毛病
                    $endLine = explode("\n",$result['RFC822']);
                    $endLine = trim(end($endLine));
                    if(preg_match("/^UID\s\d+\sFLAGS\s\(.*\)$/iU",$endLine)){
                        $arr = $this->parseFetch($endLine);
                        $result = array_merge($result,$arr);
                        $result['RFC822'] = mb_substr($result['RFC822'],0,-mb_strlen($endLine));
                    }
                    break;
                }
1  
邓超 authored
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
                case 'RFC822.HEADER':{
                    array_shift($header);
                    $result['RFC822.HEADER'] = implode(' ',$header);
                    $header = [];
                    break;
                }
                case 'BODY[HEADER.FIELDS':{
                    // header
                    $header = implode(' ',$header);
                    preg_match("/^BODY\[HEADER.FIELDS.*\]/Ui",$header,$m);
                    // 结果,提出掉字段字符
                    $result['HEADER.FIELDS'] = ltrim(mb_substr($header,mb_strlen($m[0]),mb_strlen($header)));
                    $header = [];//表示结束了
                    break;
                }
                default:{
                    array_shift($header);
                    break;
                }
            }
        }while($header);

        return $result;
    }

    /**
     * 匹配字段中的值
     * @param $header
     * @param $preg
     * @return mixed|string
     * @author:dc
     * @time 2022/11/23 14:38
     */
    private function pregFiled(&$header,$preg){
        array_shift($header);
        // 组成字符串
        $header = implode(' ',$header);
        // 找flags,非贪婪模式
        if(preg_match($preg,$header,$m)){
            $header = mb_substr($header,mb_strlen($m[0]),mb_strlen($header));
        }
        // 打散成数组
        $header =   explode(' ',$header);

        return $m[1]??'';
    }

    /**
     * imap服务器设置的id
     * @param array|string $id
     * @author:dc
     * @time 2022/11/22 11:53
     */
    public function setImapId($id){
        if(is_array($id)){
            $this->imapId = array_merge($this->imapId,$id);
        }else{
            $this->imapId['name'] = $id;
        }
    }


    /**
     * 打开socket链接
     * @param int $timeout
     * @throws \Exception
     * @author:dc
     * @time 2022/11/22 14:13
     */
    private function socketOpen(int $timeout = 30){
        if(!is_resource($this->socket)){
            $this->timeout = $timeout ? : 30;
x  
邓超 authored
1060 1061

            // 是否验证证书
x  
邓超 authored
1062
//            $isssl = in_array(parse_url($this->host)['host']??'1-1',['mail.laser-tech.com.cn']);
x  
邓超 authored
1063
1  
邓超 authored
1064
            // 链接服务器
邓超 authored
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
            try {
                $this->socket = stream_socket_client($this->host, $errno, $error, $this->timeout,STREAM_CLIENT_CONNECT,stream_context_create([
                    'ssl' => [
                        'verify_peer' => false, // 有的证书和域名不匹配,这里关闭认证
                        'verify_peer_name' => false,// 有的证书和域名不匹配,这里关闭认证
                    ]
                ]));
            }catch (\Throwable $e){
                $this->socket = stream_socket_client($this->host, $errno, $error, $this->timeout);
            }
1  
邓超 authored
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138

            if($error){
                throw new \Exception("socket error: {$error}");
            }

            if (!$this->socket) {
                throw new \Exception("{$this->host} connection fail.");
            }

            stream_set_timeout($this->socket, $this->timeout);
        }else{
            // 是否超时,超时关闭
            $meta = stream_get_meta_data($this->socket);
            if (isset($meta['timed_out']) && $meta['timed_out'] !== false) {
                $this->socketClose();
                // 重新链接
                $this->socketOpen();
            }
        }
    }


    /**
     * 最后一次执行时候的tag
     * @return string
     * @author:dc
     * @time 2022/11/22 13:54
     */
    protected function getLastTag(){
        return sprintf('%s%d', $this->tagName, $this->tagNum);
    }

    /**
     * 获取下一次执行的tag
     * @return string
     * @author:dc
     * @time 2022/11/22 13:52
     */
    protected function getNextTag(){
        $this->tagNum   +=  1;
        return sprintf('%s%d', $this->tagName, $this->tagNum);
    }

    /**
     * 向服务器发送一个noop消息,表示什么也不做,
     * 只是用来保持通信,避免长久没有操作,丢失掉连接
     * @throws \Exception
     * @author:dc
     * @time 2022/11/25 11:15
     */
    public function noop():bool {
        $status = $this->request('NOOP');
        return $status[0] == 'ok';
    }

    /**
     * debug模式
     * @param bool $debug
     * @param string $logPath
     * @author:dc
     * @time 2022/12/6 11:10
     */
    public function debug($debug=true,$logPath=''){
邓超 authored
1139 1140
        $this::$debug = $debug;
        $this::$debugWritePath = $logPath ? $logPath : LOG_PATH;
1  
邓超 authored
1141 1142 1143 1144 1145 1146 1147 1148 1149
    }

    /**
     * 记录日志
     * @param string $message
     * @author:dc
     * @time 2022/12/6 11:13
     */
    private function log(string $message){
邓超 authored
1150 1151 1152 1153 1154 1155 1156 1157
        if($this::$debug){
            if($this::$debugWritePath == 'echo'){
                echo $message."\n";
            }else{
                if(!is_dir($this::$debugWritePath)){
                    @mkdir($this::$debugWritePath,0775,true);
                }
                @file_put_contents($this::$debugWritePath.'/imap.log',date('Y-m-d H:i:s  ').$message.PHP_EOL,FILE_APPEND);
1  
邓超 authored
1158
            }
邓超 authored
1159
1  
邓超 authored
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
        }
    }

    /**
     * 获取数据集
     * @param $cmd
     * @return array
     * @throws \Exception
     * @author:dc
     * @time 2022/11/22 11:41
     */
    public function request($cmd){
        // 链接
        $this->socketOpen();

        $tag = $this->getNextTag();

        // 命令行必须要结束换行
邓超 authored
1178
        $cmd = str_replace("\n","",trim($tag.' '.$cmd));
1  
邓超 authored
1179 1180 1181 1182 1183 1184 1185 1186

        // 记录日志
        $this->log($cmd);

        // 写入数据
        $r = fwrite($this->socket, $cmd."\r\n");
        if (!$r) {
            $this->socketClose();
x  
邓超 authored
1187
            logs($cmd . $this->username);
1  
邓超 authored
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
            throw new \Exception("request error write");
        }

        // 读取数据
        $result =   []; // 返回数据
        $status = 'no'; // 状态
        $i = 1;
        while ($i) {
            $append = false;// 是否追加到上一个元素值里面
            // 这里不指定长度,读取一行
            $line = @fgets($this->socket);
            if ($line === false || !mb_strlen($line)) {
                $end = true;
            }else{


                // 是否有其他的固定串
                preg_match("/\{(\d+)\}\r\n$/",$line,$number);
                if($number[1]??0){
                    // 获取到固定字符串
                    $appendLine = fread($this->socket, intval($number[1]));
                    // 替换 {123}
                    $line   =   str_replace($number[0],$appendLine,$line);
                }

                // 记录日志
                $this->log($line);

                // 是否结束了,到了最后一行
                if(strpos($line,$tag.' ') === 0){
                    $end = true;
                    $status = strtolower(explode(' ',$line)[1]??'');
                    // 脚本异常
                    if($status == 'bad'){
x  
邓超 authored
1222
//                        logs($cmd);
1  
邓超 authored
1223
                        throw new \Exception('request bad:'.$line);
邓超 authored
1224
                    }elseif($status == 'no'){
x  
邓超 authored
1225
//                        logs($cmd);
x  
邓超 authored
1226
                        throw new \Exception('命令('.trim($cmd).')失败 NO:'.$line);
1  
邓超 authored
1227 1228
                    }
                }else{
x  
邓超 authored
1229
                    if(!preg_match("/^\*\s\w/",$line)){
1  
邓超 authored
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
                        $append = true;
                    }
                }

                // 结果数组
                if($append){
                    $result[$i-1] .= $line;
                }else{
                    $result[$i] = $line;
                    $i++;
                }

            }
            // 结束了
            if(!empty($end)){
                $i = false;
            }
        }

//        print_r($result);

        return [$status,$result];

    }

    /**
     * 是否读取结束
     * @return bool
     * @author:dc
     * @time 2022/11/22 14:14
     */
    protected function socketEof()
    {
        if (!is_resource($this->socket)) {
            return true;
        }

        // If a connection opened by fsockopen() wasn't closed
        // by the server, feof() will hang.
        $start = microtime(true);

        if (feof($this->socket) ||
            ($this->timeout && (microtime(true) - $start > $this->timeout))
        ) {
            $this->socketClose();
            return true;
        }

        return false;
    }

    /**
     * 关闭socket链接
     * @author:dc
     * @time 2022/11/22 10:45
     */
    protected function socketClose(){
        if(is_resource($this->socket)){
            fclose($this->socket);
        }
        $this->socket   =   false;
    }




    public function __construct()
    {
    }

    public function __destruct()
    {
        if($this->auto_colse){
            //        echo '关闭';
            // TODO: Implement __destruct() method.
            $this->socketClose();
        }

    }



}