yarkov
@yarkov
Помог ответ? Отметь решением.

Где здесь ошибка?

Есть самописный класс для получения почты по IMAP. Вот отвечаю - 2 недели назад работало все так как надо. Сегодня зашел на страницу, а там синтаксическая ошибка на безобидных символах [ в 50 и 78 строке (закомментировал). Я все глаза проглядел - нет ошибки! ЧЯДНТ?
<?php

/**
 * Класс для чтения почты по протоколу IMAP
 */
class getIMAPMail{
	
	// имя сервера
	private $server = "imap.spaceweb.ru";
	// логин
	private $login = "login@randomfio.xyz";
	// пароль
	private $password = "pass";
	// порт IMAP
	private $port = 143;
	// логин юзера для которого ищем письма
	public $targetUser = false;
	// объект подключения
	public $Mail = false;
	// хранилище ID писем
	public $MailID = array();
	// хранилище массива писем из папки Входящие
	public $MailCollection = array();
	// режим отображения (2 - html, 1 - text)
	public $html = 2;
	// хранилище папок для поиска писем
	public $Folders = array("INBOX"=>"Входящие", "Spam"=>"Спам");

   
    /**
     * Открывает соединение с IMAP сервером
     */
	public function connect($folder = "INBOX"){
		$this->Mail = imap_open('{'.$this->server.':'.$this->port.'}' . $folder, $this->login, $this->password);
	}

    /**
     * Проверяет, Email на наличие писем для указанного логина
     */
	public function getMail(){
		foreach ($this->Folders as $key => $folder){
			// Открываем соединение
			$this->connect($key);
			// получаем объект папки Входящие
			$this->MailID = imap_search($this->Mail, 'TO "'.$this->targetUser.'"');

			if(count($this->MailID) > 0){
				foreach ($this->MailID as $num){
					$obj = $this->mail_header_parse($num);
					//$obj["Body"] = trim(imap_base64($this->mail_fetchparts($this->Mail, $num)[abs($this->html)]));
					$obj["Folder"] = $folder;
					$this->MailCollection[] = $obj;
				}
			}
		}
	}
	
	/**
	 * Метод парсит заголовки сообщения под номером $num и отдает массив в удобном виде
     * @return array
    */
	public function mail_header_parse($msg){
		$header = imap_fetchheader($this->Mail, $msg);
		preg_match_all("/^([^\r\n:]+)\s*[:]\s*([^\r\n:]+(?:[\r]?[\n][ \t][^\r\n]+)*)/m", $header, $matches, PREG_SET_ORDER);
		foreach($matches as $match){
			$match[2] = iconv_mime_decode($match[2], ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'utf-8');
			if(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];
			}
		}
		$hdr = array();
		$from = preg_match('/([a-z_\-\.0-9]+\[at\][a-z\-\.0-9]+)/', $headers["X-Spam-Report"], $fr);
		$hdr["From"] = str_replace("[at]", "@", $fr[0]);
		//$hdr["Date"] = date("H:i:s d-m-Y", strtotime(trim(explode(";", $headers["Received"][0])[1])));
		$hdr["To"] = $headers["To"];
		$hdr["Subject"] = $headers["Subject"];
		unset($headers);
		return $hdr;
	}


    /**
     * Закрывает соединение с IMAP сервером
     */
	public function close(){
		// закрываем соединение
		imap_close($this->Mail);
	}
	
	
	
    // get the body of a part of a message according to the
    // string in $part
    public function mail_fetchpart($mbox, $msgNo, $part) {
        $parts = $this->mail_fetchparts($mbox, $msgNo);
        
        $partNos = explode(".", $part);
        
        $currentPart = $parts;
        while(list ($key, $val) = each($partNos)) {
            $currentPart = $currentPart[$val];
        }
        
        if ($currentPart != "") return $currentPart;
          else return false;
    }

    // splits a message given in the body if it is
    // a mulitpart mime message and returns the parts,
    // if no parts are found, returns false
    public function mail_mimesplit($header, $body) {
        $parts = array();
        
        $PN_EREG_BOUNDARY = "Content-Type:(.*)boundary=\"([^\"]+)\"";

        if (eregi ($PN_EREG_BOUNDARY, $header, $regs)) {
            $boundary = $regs[2];

            $delimiterReg = "([^\r\n]*)$boundary([^\r\n]*)";
            if (eregi ($delimiterReg, $body, $results)) {
                $delimiter = $results[0];
                $parts = explode($delimiter, $body);
                $parts = array_slice ($parts, 1, -1);
            }
            
            return $parts;
        } else {
            return false;
        }    
        
        
    }

    // returns an array with all parts that are
    // subparts of the given part
    // if no subparts are found, return the body of 
    // the current part
    public function mail_mimesub($part) {
        $i = 1;
        $headDelimiter = "\r\n\r\n";
        $delLength = strlen($headDelimiter);
    
        // get head & body of the current part
        $endOfHead = strpos( $part, $headDelimiter);
        $head = substr($part, 0, $endOfHead);
        $body = substr($part, $endOfHead + $delLength, strlen($part));
        
        // check whether it is a message according to rfc822
        if (stristr($head, "Content-Type: message/rfc822")) {
            $part = substr($part, $endOfHead + $delLength, strlen($part));
            $returnParts[1] = $this->mail_mimesub($part);
            return $returnParts;
        // if no message, get subparts and call function recursively
        } elseif ($subParts = $this->mail_mimesplit($head, $body)) {
            // got more subparts
            while (list ($key, $val) = each($subParts)) {
                $returnParts[$i] = $this->mail_mimesub($val);
                $i++;
            }            
            return $returnParts;
        } else {
            return $body;
        }
    }

    // get an array with the bodies all parts of an email
    // the structure of the array corresponds to the 
    // structure that is available with imap_fetchstructure
    public function mail_fetchparts($mbox, $msgNo) {
        $parts = array();
        $header = imap_fetchheader($mbox,$msgNo);
        $body = imap_body($mbox,$msgNo, FT_INTERNAL);
        
        $i = 1;
        
        if ($newParts = $this->mail_mimesplit($header, $body)) {
            while (list ($key, $val) = each($newParts)) {
                $parts[$i] = $this->mail_mimesub($val);
                $i++;                
            }
        } else {
            $parts[$i] = $body;
        }
        return $parts;
        
    }
}

?>
  • Вопрос задан
  • 225 просмотров
Пригласить эксперта
Ответы на вопрос 1
Ivanq
@Ivanq
Знаю php, js, html, css
Старый PHP не понимает такой код:
func(a, b, c)["Something"]
Ему мешает получение элемента массива сразу после вызова ф-ии. Лечить так:
$a = func(a, b, c); $a["Something"]
В вашем коде:
/* 50: */
$fetchparts = $this->mail_fetchparts($this->Mail, $num);
$obj["Body"] = trim(imap_base64($fetchparts[abs($this->html)]));

/* 78: */
$exploded = explode(";", $headers["Received"][0]);
$hdr["Date"] = date("H:i:s d-m-Y", strtotime(trim($exploded[1])));
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы