<?php 

/**
* Класс для работы с аттачами сообщений
*/
class Attachments 
{
    // Массив с прикрепленными файлами в сессии 
    public $files = array();
    
    public function __construct() {
        if (isset($_SESSION['mail']['attachments'])) {
            $this->files = $_SESSION['mail']['attachments'];
        }
    }
    
    /**
    * Создает тело письма с вложениями
    * Callback метод для работы с типами файлов
    */
    public function get_attachments($boundary) {
        $list = array();
        foreach($this->files AS $type => $files) {
             $list[$type] = call_user_func(array(&$this, 'get_attachments_' . $type), $boundary);
        }
        return implode('', $list);
    }
    
    protected function get_attachments_photo($boundary) {
        $message_part = array();
        
        foreach($this->files['photo'] AS $key => $photo) {
            $fp = fopen($photo['filePatch'], "r"); 
            
            if ($fp) { 
                $file = fread($fp, $photo['fileSize']); 
                fclose($fp); 
                
                $file_part = "--$boundary\r\n"; 
                $file_part .= "Content-Type: $photo[fileType]; name=\"$photo[fileNameSend]\"\r\n";  
                $file_part .= "Content-Transfer-Encoding: base64\r\n"; 
                $file_part .= "Content-Disposition: attachment; filename=\"$photo[fileNameSend]\"\r\n"; 
                $file_part .= "\r\n";
                $file_part .= chunk_split(base64_encode($file)) . "\r\n";

                $message_part[] = $file_part;
            } 
        }
        
        if ($message_part) {
            $message_part[] = "--$boundary--\r\n";
        }
        
        
        return implode("", $message_part);
    }
    
    /**
    * Метод для вывода списка прикрепленных файлов
    * Callback nипа файла
    * @return
    */
    public function get_list() {
        $list = array();
        foreach($this->files AS $type => $files) {
             $list[$type] = call_user_func(array(&$this, 'get_list_' . $type));
        }
        
        $list = implode('', $list);
        
        if ($list) {
          return '<div class="attachments">' . $list . '</div>';
        }
    }
    
    protected function get_list_photo() {
        $html = array();
        
        foreach($this->files['photo'] AS $key => $file) {
            $html[] = '<div class="attachments-list">';
            $html[] = '<a href="' . $file['fileUrl'] . '">';
            $html[] = '<img src="' . $file['screenPatch'] . '" title="' . text($file['fileName']) . '" />';
            $html[] = '</a>';
            $html[] = '<a class="attachments-delete" href="attachments.php?type=photo&amp;delete=' . $key . '"><img src="style/icons/cross.png" /></a>';
            $html[] = '</div>';
        }
        
        if ($html) {
          return '<div class="attachments-photo">'. implode('', $html) . '</div>';
        }
    }
}