<?php
/* =================================================================================
 * License: GPL-2.0 license
 * Author: 众产®  https://ciy.cn/code
 * Version: 0.1.0
 * 

====================================================================================*/

namespace ciy;

class imap {
    public $imap_server = '';
    public $user = '';
    public $pass = '';
    public $log = '';
    private $inbox = null;
    function __construct() {
    }
    function recvmail($lastuid = 0) {
        $this->log('Connect ' . $this->imap_server);
        $this->inbox = \imap_open('{' . $this->imap_server . '}INBOX', $this->user, $this->pass);
        if (!$this->inbox)
            return $this->log('connenct fail: ' . $this->imap_server);
        $ret = array();
        $ret['maxuid'] = 0;
        $ret['mails'] = array();
        $this->log('search unseen');
        $numbers = \imap_search($this->inbox, 'UNSEEN');
        if ($numbers === false) {
            \imap_close($this->inbox);
            return $ret;
        }
        $this->log('find ' . count($numbers) .'mails');
        foreach ($numbers as $number) {
            $this->log('read mail No. ' . $number);
            $uid = \imap_uid($this->inbox, $number);
            if ($uid <= $lastuid)
                continue;
            if ($ret['maxuid'] < $uid)
                $ret['maxuid'] = $uid;
            $header = \imap_headerinfo($this->inbox, $number);
            if($header === false)
                return $this->log('get headerinfo fail: ' . $number);
            $title = \mb_decode_mimeheader($header->subject);
            $content = \imap_body($this->inbox, $number);
            if($content === false)
                return $this->log('get body fail: ' . $number);
            $ret['mails'][] = ['title' => $title, 'content' => $content, 'header' => $header];
        }
        \imap_close($this->inbox);
        $this->log('Recv OK');
        return $ret;
    }
    function log($message) {
        $this->log .= $message . "\n";
        return $message;
    }
}
