<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');


class Mail extends CI_Controller
{
    private $data=array();
    public function __construct() 
    {
        parent::__construct();
        $this->load->model('Order_model');
        $this->load->model('Mails_model');
        $this->data['nav']='mail';
        $this->data['unseen_num']=$this->Mails_model->unseen_list();
        $this->data['condition']=$this->input->post('condition')?$this->input->post('condition'):'1';
        $this->data['nav_header'] =$this->load->view('mail/mail_header',$this->data,true);
        $this->data['page_title'] = '邮件管理';
    }

    //邮件列表
    public function index($issend='inbox',$page=1)
    {
        if ($issend=='sent') {
            $list=$this->Mails_model->get_sended_list(30,false,'',true);
        }elseif ($issend=='deleted') {
            $list=$this->Mails_model->get_deleted_list('',true);
        }else{
            $list=$this->Mails_model->get_inbox_list('',true);
        }

        $pages['total'] = count($list); //数据总条数
        $pages['pageSize'] = 30; //每页展示数量
        $pages['url'] = site_url("mail/index/$issend/"); //页码链接
        $pages['current'] = $page; //当前页码
        $this->data['pageinfo'] = show_page($pages);

        $mail_id_str = 0;
        $list = array_slice($list, $pages['pageSize'] * ($page - 1), $pages['pageSize']);
        foreach ($list as $v) {
            $mail_id_str.=',' . $v->mail_sn;
        }
        $this->data['list']=$list=$this->Mails_model->get_inbox_list($mail_id_str,false);

        $this->data['order_type']=$this->lang->line('order_type');
        $this->data['order_status']=$this->lang->line('order_status');

        $this->data['mailbox_list'] =$this->load->view('mail/mailbox_list',$this->data,true);
        $this->load->view('header', $this->data);
        $this->load->view('mail/index');
        $this->load->view('footer');
    }
    public function search_mail($page=1)
    {
        $list=$this->Mails_model->get_search_mails($this->data['condition'],$this->data['condition']);
        $pages['total'] = count($list); //数据总条数
        $pages['pageSize'] = 30; //每页展示数量
        $pages['url'] = site_url("mail/search_mail/"); //页码链接
        $pages['current'] = $page; //当前页码
        $this->data['pageinfo'] = show_page($pages);

        $mail_id_str = 0;
        $list = array_slice($list, $pages['pageSize'] * ($page - 1), $pages['pageSize']);
        foreach ($list as $v) {
            $mail_id_str.=',' . $v->mail_sn;
        }
        $this->data['list']=$list=$this->Mails_model->get_inbox_list($mail_id_str,false);

        $this->data['order_type']=$this->lang->line('order_type');
        $this->data['order_status']=$this->lang->line('order_status');

        $this->data['mailbox_list'] =$this->load->view('mail/mailbox_list',$this->data,true);
        $this->load->view('header', $this->data);
        $this->load->view('mail/index');
        $this->load->view('footer');
    }
    //邮件详情
    public function detail($mail_sn,$onlytext=0)
    {
        $mail_list=$this->Mails_model->get_mail_list($mail_sn);
        $mailinfo=$mail_list[0];
        //阅读状态
        $this->data['unseen_num']=$this->data['unseen_num'];
        if ($onlytext==0 && $mailinfo->mail_seen==0) {
            $this->Mails_model->set_read($mail_sn);
            $this->data['unseen_num']=$this->data['unseen_num']-1;
            //设置订单号
            $subject_array=explode('/', $mailinfo->mail_subject);
            if ($mailinfo->mail_o_orderno==0 && count($subject_array)>1) {
                $orderno=trim(end($subject_array));
                $this->Mails_model->update_mail($mail_sn,'mail_o_orderno',$orderno);
                $mailinfo->mail_o_orderno=$orderno;
            }
        }
        //附件处理
        $site_path=rtrim(rtrim(FCPATH,'/'),'\\');
        $mailinfo->mail_attachs=str_replace($site_path, '', $mailinfo->mail_attachs);
        $mailinfo->mail_attachs=str_replace(str_replace('\\', '/', $site_path), '', $mailinfo->mail_attachs);
        $this->data['attachments']=explode('|##|', $mailinfo->mail_attachs);
        foreach ($this->data['attachments'] as $key=>$a) {
            $attach=explode('|@@|', $a);
            if (isset($attach[4]) && $attach[4]=='inline_img') {
                $mailinfo->mail_body=str_replace('cid:'.$attach[0],$attach[2],$mailinfo->mail_body);
                unset($this->data['attachments'][$key]);
            }
        }
        if ($onlytext==1) {
            echo htmlspecialchars_decode(str_replace('#@#', "'", $mailinfo->mail_body));
            return false;
        }
        $this->data['mail_text']=$mailinfo;
        $this->data['mailbox_list'] =$this->load->view('mail/mailbox_list',$this->data,true);
        $this->load->view('header', $this->data);
        $this->load->view('mail/detail');
        $this->load->view('footer');
    }

    //新建邮件
    public function send($mail_o_orderno=false,$email='',$tp_sn=-1)
    {
        $this->data['orderno']=$mail_o_orderno;
        $this->data['email']=$email;
        $this->data['mailbox_list'] =$this->load->view('mail/mailbox_list',$this->data,true);
        
        $this->load->model('Templates_model');
        $this->data['template'] = $this->Templates_model->detail($tp_sn);

        $this->load->view('header', $this->data);
        $this->load->view('mail/send');
        $this->load->view('footer');
    }

    //回复、全部答复、转发邮件
    public function reply($mail_sn,$reply_all=0)
    {
        $mail_list=$this->Mails_model->get_mail_list($mail_sn);
        $this->data['mailinfo']=$mail_list[0];
        $this->data['reply_all']=$reply_all;
        //订单号
        $this->data['orderno']=$mail_list[0]->mail_o_orderno;
        //收件人为上一次邮件的发件人发件人
        $this->data['email']=$mail_list[0]->mail_from;
        //全部答复的话，原抄送email继续抄送，收件人则是原收件人email中除了本人的email列表
        if ($reply_all==1) {
            $this->data['email']=$mail_list[0]->mail_from.';'.$mail_list[0]->mail_to;
            $this->data['cs_emaillist']=$mail_list[0]->mail_cc;
        }
        $mail_to_list=explode(';', $this->data['email']);
        foreach ($mail_to_list as $m) {
            $mail_to_array[]=trim($m);
        }
        $mail_to_array=array_flip(array_flip($mail_to_array));
        $this->data['email']=implode(';', $mail_to_array);

        //上一封邮件的主题
        $mail_list[0]->mail_subject=str_replace('/'.$mail_list[0]->mail_o_orderno, '', $mail_list[0]->mail_subject);
        if ($reply_all==2) {
            $this->data['mail_subject']='转发: '.$mail_list[0]->mail_subject;
        }else{
            $this->data['mail_subject']='RE: '.$mail_list[0]->mail_subject;
        }

        //附件处理
        $mailinfo=$mail_list[0];
        $mailinfo->mail_attachs=str_replace(FCPATH, '/', $mailinfo->mail_attachs);
        $mailinfo->mail_attachs=str_replace(str_replace('\\', '/', FCPATH), '/', $mailinfo->mail_attachs);
        $this->data['attachments']=explode('|##|', $mailinfo->mail_attachs);
        foreach ($this->data['attachments'] as $key=>$a) {
            $attach=explode('|@@|', $a);
            if (isset($attach[4]) && $attach[4]=='inline_img') {
                $mailinfo->mail_body=str_replace('cid:'.$attach[0],'http://'.$_SERVER['HTTP_HOST'].$attach[2],$mailinfo->mail_body);
                unset($this->data['attachments'][$key]);
            }elseif ($reply_all!=2) {
                unset($this->data['attachments'][$key]);
            }
        }
        
        //上一封邮件的内容
        $this->data['mail_body']='<p><br><br><br><br></p><hr style="border-color:#aaa;"/><p><strong>发件人：</strong>'.$mail_list[0]->mail_from.'</p><p> <strong>时　间：</strong>'.date('m/d/Y h:i:s',strtotime($mail_list[0]->mail_date)).'</p><p><strong>收件人：</strong>'.$mail_list[0]->mail_to.'</p><p><strong>主题：</strong>'.$mail_list[0]->mail_subject.'</p><p><br></p>'.$mail_list[0]->mail_body;
        
        $this->data['mailbox_list'] =$this->load->view('mail/mailbox_list',$this->data,true);
        $this->load->view('header', $this->data);
        $this->load->view('mail/send');
        $this->load->view('footer');
    }

    //删除邮件
    public function delete($mail_sn)
    {
        if ($this->Mails_model->update_mail($mail_sn,'mail_deleted',1)) {
            echo json_encode(array('status'=>'ok_go','msg'=>'删除成功!','url'=>site_url('mail/index')));
        }else{
            echo json_encode(array('status'=>'no','msg'=>'删除失败!'));
        }
        return false;
    }

    //邮件关联订单
    public function link_orderno($mail_sn,$mail_o_orderno=0)
    {
        $data['mail_o_orderno'] ='';
        if ($mail_o_orderno!=0 || !empty($mail_o_orderno)) {
            $data['mail_o_orderno'] =$mail_o_orderno;
        }
        $data['mail_sn'] =$mail_sn;
        $this->load->view('mail/link_orderno',$data);
    }
    public function mail_do_link_order($mail_sn)
    {
        $data=json_encode(array('status'=>'no','msg'=>'关联失败!'));
        if($this->Mails_model->update_mail($mail_sn,'mail_o_orderno',$this->input->post('mail_o_orderno'))){
            $data=json_encode(array('status'=>'ok','msg'=>'关联成功!'));
        }
        echo $data;
        return false;
    }

    public function save_mail()
    {
        $mail_adress=$this->input->post('emaillist');
        if (trim($mail_adress)=='') {
            echo json_encode(array('status'=>'no','msg'=>'收件人不能为空!'));
            return false;
        }
        $mail_user=$this->lang->line('mail_user');
        $mail_o_orderno=$this->input->post('mail_o_orderno');
        $from_email=$mail_user['user'];
        $subject=$this->input->post('mail_subject').'/'.$mail_o_orderno;
        $mailbody=$this->input->post('mail_content');

        //处理附件
        $mail_attachs='';
        $attachment=array();
        if ($this->input->post('attachments')) {
            foreach ($this->input->post('attachments') as $attach_id => $attach) {
                $tmp_attach=explode('|', $attach);
                $mail_attachs.='FILES_'.$attach_id.'|@@|'.$tmp_attach[3].'|@@|'.$tmp_attach[0].'|@@|'.$tmp_attach[2].'|@@|attachment|##|';
                $file_name=$tmp_attach[3];
                $file_name=explode(':', $tmp_attach[3]);
                $file_name=$file_name[0];
                $attachment[$file_name]=$tmp_attach[0];
            }
        }
        //处理正文中的嵌套的图片
        $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
        preg_match_all($pattern,$mailbody,$EmbeddedImage);
        $embedded_attachs=!empty($EmbeddedImage[1])?$EmbeddedImage[1]:array();
        $embedded_attachs_arr=array();
        foreach ($embedded_attachs as $img_id => $img) {
            if (stripos($img, $_SERVER['HTTP_HOST'])===false) {
                continue;
            }
            $minitype=explode('.', $img);
            $minitype=end($minitype);
            $name_arr=explode('/', $img);
            $imgname=end($name_arr);
            $img_path_arr=explode('attachs/',$img,2);
            $img_path=FCPATH.'attachs/'.$img_path_arr[1];
            $mail_attachs.='IMAGE_'.$img_id.'|@@|'.$imgname.'|@@|'.$img_path.'|@@|image/'.$minitype.'|@@|'.'inline_img'.'|##|';
            $mailbody=str_replace($img,'cid:IMAGE_'.$img_id,$mailbody);
            $embedded_attachs_arr[]=array($img_path,'IMAGE_'.$img_id,$imgname,$minitype);
        }

        $to_string=$this->input->post('emaillist');
        $cs_emaillist=$this->input->post('cs_emaillist');
        $mail_date=date('Y-m-d h:i:s');
        $org_mailbody=$mailbody;
        $mailbody=htmlspecialchars($mailbody);

        $tolist_array=array();
        $to_list=explode(';', $to_string);
        foreach ($to_list as $touser) {
            $tolist_array[]=trim($touser);
        }

        $cc_list_array=array();
        $cc_list=explode(';', $this->input->post('cs_emaillist'));
        foreach ($cc_list as $cc_user) {
            $cc_list_array[]=trim($cc_user);
        }
        //发送邮件
        $MessageID=$this->Mails_model->sendmail($from_email,$tolist_array,$cc_list_array,$subject,$org_mailbody,$attachment,$embedded_attachs_arr);
        if (strpos($MessageID, 'error')!==false) {
            $error=$MessageID;
            $MessageID='';
        }
        //保存邮件
        $mail_sendstate=$MessageID!==false?1:0;
        $mail_cols="(0,'$mail_o_orderno','0','$MessageID','$from_email','$to_string','$cs_emaillist','$from_email','$to_string','$subject','$mailbody',1,'$mail_date',0,0,'SENT','$mail_attachs',$mail_sendstate),";
        $mail_cols=trim($mail_cols,',');
        $result=$this->Mails_model->save_mail($mail_cols);

        if (!empty($MessageID)) {
            echo json_encode(array('status'=>'ok','msg'=>'发送成功!'));
        }else{
            echo json_encode(array('status'=>'no','msg'=>$error));
        }
    }

    //用于定时发送邮件
    public function send_mail()
    {
        $mail_info=$this->data['list']=$this->Mails_model->get_sended_list(1,0);
        if (empty($mail_info)) {
            return true;
        }
        $mail_info=$mail_info[0];

        $from_email=$mail_info->mail_from;

        $tolist_array=array();
        $to_list=explode(';', $mail_info->mail_to);
        foreach ($to_list as $touser) {
            $tolist_array[]=trim($touser);
        }
        $cc_list_array=array();
        $cc_list=explode(';', $mail_info->mail_cc);
        foreach ($cc_list as $cc_user) {
            $cc_list_array[]=trim($cc_user);
        }

        $subject=$mail_info->mail_subject;
        $mailbody=htmlspecialchars_decode($mail_info->mail_body);

        $embedded_attachs_arr=array();
        $attachment=array();
        if (!empty($mail_info->mail_attachs)) {
            $attachments=explode('|##|', trim($mail_info->mail_attachs,'|##|'));
            foreach ($attachments as $attach) {
                if (empty($attach)) {
                    continue;
                }
                $attach_array=explode('|@@|', $attach);
                if ($attach_array[4]=='inline_img') {
                    $embedded_attachs_arr[]=array($attach_array[2],$attach_array[0],$attach_array[1],$attach_array[3]);
                }else{
                    $file_name=$attach_array[1];
                    $file_path=$attach_array[2];
                    $attachment[$file_name]=$file_path;
                }
            }
        }

        $mail_user=$this->lang->line('mail_user');
        $SentMIMEMessage=$this->Mails_model->sendmail($mail_user['user'],$tolist_array,array(),$subject,$mailbody,$attachment,$embedded_attachs_arr);
        $this->Mails_model->set_sent($mail_info->mail_sn);
    }

    //文档上传处理
    public function editor_upload($file_type="image")
    {
        //上传配置
        $save_path=date('Y').'/'.date('m').'/'.date('d').'/'.date('H');
        $upload_id='editorfile';
        $config['upload_path'] = 'attachs/'.$save_path;
        if(!is_dir($config['upload_path'])) {
            @mkdir($config['upload_path'],0777,true);
        }
        $config['allowed_types'] = '*';
        $config['overwrite'] = false;
        $config['encrypt_name'] = true;
        //开始上传
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload($upload_id))
        {
            $error = array('error' => $this->upload->display_errors());
            var_dump($error);
        }
        //返回文件地址
        else
        {
            $data = array('upload_data' => $this->upload->data());
            $file_path='http://'.$_SERVER['HTTP_HOST'].'/'.$config['upload_path'].'/'.$data['upload_data']['file_name'];
            if ($file_type=="image") {
                echo '{"error":0, "url":"'.$file_path.'"}';
            }else{
                $file_ext=$data['upload_data']['file_ext'];
                $file_type=$data['upload_data']['file_type'];
                $file_name=$data['upload_data']['file_name'];
                $orig_name=$data['upload_data']['orig_name'];
                $file_path=$data['upload_data']['file_path'].$file_name;
                echo "<script>parent.set_attach('$file_path','$file_ext','$file_type','$file_name','$orig_name');</script>";
            }
        }
    }

    //更新邮件列表
    public function update_mail_list() {
        //获取本地最近更新的一条数据
        $mail_list=$this->Mails_model->get_mail_list(false,false,1,'mail_sn','mail_sn desc');
        //接收邮件更新
        $mail_user=$this->lang->line('mail_user');
        $this->load->library('ImapMailbox');
        $user=$mail_user['user'];
        $password=$mail_user['password'];
        $this->imapmailbox->init_imap('{imap.exmail.qq.com:995/ssl/pop3/novalidate-cert}INBOX', $user, $password, null, 'utf-8');
        $mails = array();
        $mailsIds=array();
        $mailsIds =$this->imapmailbox->searchMailbox();
        krsort($mailsIds);
        //如果没有更新过，保存到数据库
        $i=0;
        $mail_cols='';
        $html='';
        $new_mail_num=0;
        foreach ($mailsIds as $mailId) 
        {
            $mailinfo='';
            $mailinfo_temp = $this->imapmailbox->getMail($mailId);
            $message_id=$mailinfo_temp->message_id;
            //如果本地还没有邮件，则同步前30封云端邮件到本地
            if (empty($mail_list)) {
                if ($i>14) break;
                $mailinfo = $mailinfo_temp;
            }
            //如果云端邮件编号小于本地邮件编号,则需要判断是已经更新完了最新的邮件，
            //还是由于云端邮件删除了导致云端编号变小，来决定是否保存邮件到本地
            else
            {
                $is_loaded=$this->Mails_model->get_list_by_msgid($message_id);
                if (!empty($is_loaded)) {
                    break;
                }
                $mailinfo = $mailinfo_temp;
            }
            if ($mailinfo!='') {
                //附件路径,一封邮件一个文件夹: /attachs/年/月/日/邮件标识/
                $dirs=explode('application', realpath(dirname(__FILE__)));
                $attach_path= $dirs[0].'attachs/'.date('Y').'/'.date('m').'/'.date('d').'/';
                $attach_folder=str_replace(array('/','\\',':','*','?','"','<','>','|'), array(''), $message_id);
                $attach_path.=$attach_folder;
                //处理附件
                $mail_attachs='';
                $attachments=$this->imapmailbox->get_mail_attachs($mailinfo,$attach_path);

                foreach ($attachments as $attachment) {
                    $tmp_attach=explode('.', $attachment->filePath);
                    $attach_ext=end($tmp_attach);
                    if (in_array($attach_ext, array('jpg','jpeg','png','gif'))) {
                        $minitype='image/'.$attach_ext;
                    }else{
                        $minitype='undefined';
                    }
                    $attachment_type='attachment';
                    if (strpos($mailinfo->textHtml,"cid:$attachment->id")!==false) {
                        $attachment_type='inline_img';
                    }
                    $attachment->name=str_replace("'", ' ', htmlspecialchars($attachment->name));
                    $mail_attachs.=$attachment->id.'|@@|'.$attachment->name.'|@@|'.$attachment->filePath.'|@@|'.$minitype.'|@@|'.$attachment_type.'|##|';
                }
                $mail_attachs=trim($mail_attachs,'|##|');
                $mailinfo->subject=str_replace("'", '#@#', htmlspecialchars($mailinfo->subject));
                //格式化邮件正文
                $mailinfo->textHtml=str_replace("'", '#@#', htmlspecialchars($mailinfo->textHtml));
                $mail_cols.="(0,0,$mailId,'$message_id','$mailinfo->fromAddress','$mailinfo->toString','','$mailinfo->fromName','$mailinfo->toString','$mailinfo->subject','$mailinfo->textHtml',0,'$mailinfo->date',0,0,'INBOX','$mail_attachs',1),";
                
                $new_mail_num++;
                $url=site_url('mail/detail/0/'.$message_id);
                $html.='<ul class="row mail_list">
                          <a  class="unseen" href="'.$url.'">
                          <li class="col-xs-8">'.$mailinfo->fromAddress.'</li>
                          <li class="col-xs-8">'.$mailinfo->subject.'</li>
                          <li class="col-xs-8">'.$mailinfo->date.'</li>
                          </a>
                        </ul>';
            }
            $i++;
        }
        $mail_cols=trim($mail_cols,',');
        //已经最新
        if (empty($mail_cols)) {
            echo json_encode(array('status'=>'ok','msg'=>'已经是最新!','html'=>"",'new_mail_num'=>"0"));
            return;
        }
        //保存最新邮件到本地
        $result=$this->Mails_model->save_mail($mail_cols);
        //更新网页邮件列表
        if ($result) {
            echo json_encode(array('status'=>'ok','msg'=>'更新成功!','html'=>$html,'new_mail_num'=>$new_mail_num));
        }else{
            echo json_encode(array('status'=>'no','msg'=>'更新失败!'));
        }
    }
}