<?php 

/**
* Класс для работы с почтой
* Автор: alex-borisi
* ICQ:   587863132
* Сайт:  http://nasimbe.ru
*/

class Email extends ImapMailbox
{
    /**
    * Заменяет все HTML сущности
    * @return Text
    */
    
    public function getHtmlText($string) {
        
        $searchHTML = array ("'<script[^>]*?>.*?</script>'si",
                              "'<\s*br\s*([^>]*)>'si",  
                              "'<[\/\!]*?[^<>]*?>'si", 
                              "'([\r\n])[\s]+'",  
                              "'&(quot|#34);'i", 
                              "'&(amp|#38);'i",
                              "'&(lt|#60);'i",
                              "'&(gt|#62);'i",
                              "'&(nbsp|#160);'i",
                              "'&(iexcl|#161);'i",
                              "'&(cent|#162);'i",
                              "'&(pound|#163);'i",
                              "'&(copy|#169);'i",
                              "'&#(\d+);'e");
                              
        $replaceHTML = array ("",
                              "\n",
                              "",
                              "\\1",
                              "\"",
                              "&",
                              "<",
                              ">",
                              " ",
                              chr(161),
                              chr(162),
                              chr(163),
                              chr(169),
                              "chr(\\1)");
                              
        return preg_replace($searchHTML, $replaceHTML, $string);
    }
    
    /**
    * Cоздает массив со списком всех сообщений
    */
    
    public function getListMessages() {
        $mail = array();
        $list = $this->searchMailbox('ALL');
        
        foreach ($list AS $key => $value) {
            $mail[$key] = $this->getMail($value); 
            
            if ($mail[$key]->textPlain) {
                $mail[$key]->message = $mail[$key]->textPlain;
            } elseif ($mail[$key]->textHtml) {
                $mail[$key]->message = $this->getHtmlText($mail[$key]->textHtml);
            } else {
                $mail[$key]->message = '';
            }
            
            unset($mail[$key]->textPlain, $mail[$key]->textHtml);
        }
        
        return $mail;
    }
}