<?php
/**
* @author moufer<moufer@163.com>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');

class MessageModel {

    function & read($uid, $pmid) {
        global $db,$dbpre,$timestamp;
        $msg = $db->get_one("SELECT * FROM {$dbpre}pmsgs WHERE pmid='$pmid'");
        if(!$msg) { 
            $msg = false;
            return $msg;
        }
        $msg['subject_enc'] = rawurlencode($msg['subject']); 
        $msg['content'] = strip_textarea($msg['content']);
        if($msg['new'] && !empty($msg['recvuid']) && $uid==$msg['recvuid']) {
            $db->update("UPDATE {$dbpre}pmsgs SET new=0 WHERE pmid='$pmid'");
            $db->update("UPDATE {$dbpre}members SET newmsg=newmsg-1 WHERE uid='{$msg['recvuid']}'");
        }
        return $msg;
    }

    // delflag=1 收件箱删除（outbox），delflag=2 发件箱删除（inbox）
    function delete($uid, $folder, $ids) {
        global $db,$dbpre;
        if(!is_array($ids) || count($ids)==0) return;
        $where = $folder=='inbox'?"recvuid='$uid'":"senduid='$uid'";
        $ids = "'".implode("','", $ids)."'";
        $where .= " AND pmid IN ($ids)";
        $query = $db->query("SELECT pmid,new,recvuid,senduid,delflag FROM {$dbpre}pmsgs WHERE $where");
        $newmsg = 0;
        $delids = $flagids = array();
        while($row=$db->fetch_array($query)) {
            // delflag 非零时，说明一方已经删除这个邮件，则物理删除，特殊的系统发布信息则物理删除
            if($row['delflag']>0||empty($row['senduid'])) {
                $delids[]=$row['pmid'];
            } else {
                $flagids[]=$row['pmid'];
            }
            // 新邮件 且 删除的收件箱 则计入一个新邮件，以便最后更新会员的消息表
            if($row['new'] && $folder=='inbox') $newmsg++;
        }
        $db->free_result($query);
        // 删除收件箱，则更新该会员的最新邮件数量
        if($folder=='inbox' && $newmsg>0) {
            $db->query("UPDATE {$dbpre}members SET newmsg=newmsg-$newmsg WHERE uid='$uid'");
        }
        // 物理删除邮件
        if(count($delids)>0) {
            $ids = "'".implode("','", $delids)."'";
            $db->query("DELETE FROM {$dbpre}pmsgs WHERE pmid IN ($ids)");
        }
        // 删除一方的邮箱,更新字段
        if(count($flagids)>0) {
            $ids = "'".implode("','", $flagids)."'";
            $delflag = $folder=='inbox'?1:2;
            $db->query("UPDATE {$dbpre}pmsgs SET delflag=$delflag WHERE pmid IN ($ids)");
        }
    }

    function send($senduid, $recvuid, $subject, $message, $isusername = false) {
        global $db,$dbpre,$timestamp;
        if(empty($recvuid)) {
            return false;
        }
        $inids = "'".str_replace(",", "','", $recvuid)."'";
        $where = $isusername ? "username IN ($inids)" : "uid IN ($inids)";
        $query = $db->query("SELECT uid,username FROM {$dbpre}members WHERE $where GROUP BY uid");
        $uids = array();
        while($row=$db->fetch_array($query)) {
            $uids[]=$row['uid'];
            $db->query("INSERT INTO {$dbpre}pmsgs (senduid,recvuid,subject,content,posttime,new,delflag) VALUES ('$senduid','{$row['uid']}','$subject','$message','$timestamp','1','0')");
        }
        $db->free_result($query);
        if(count($uids)>0) {
            $ids = "'".implode("','", $uids)."'";
            $db->update("UPDATE {$dbpre}members SET newmsg=newmsg+1 WHERE uid IN ($ids)");
        }
        unset($inids,$where,$row,$ids);
        return $uids; // 返回发送的用户 uid 列表
    }

    function getMessagesTotal($uid, $folder) {
        global $db,$dbpre;
        if($folder=='inbox') {
            $where="recvuid='$uid' AND delflag!=1";
        } else {
            $where="senduid='$uid' AND delflag!=2";
        }
        return $db->get_value("SELECT COUNT(*) FROM {$dbpre}pmsgs WHERE $where");
    }

    function & getMessages($uid, $folder, $limit) {
        global $db, $dbpre;
        if($folder=='inbox') {
            $select="senduid as uid";
            $joinon="p.senduid=m.uid";
            $where="recvuid='$uid' AND delflag!=1";
        } else {
            $select="recvuid as uid";
            $joinon="p.recvuid=m.uid";
            $where="senduid='$uid' AND delflag!=2";
        }
        $query = $db->query("SELECT $select,pmid,subject,new,posttime,username FROM {$dbpre}pmsgs p LEFT JOIN {$dbpre}members m ON($joinon) WHERE $where ORDER BY posttime DESC LIMIT $limit");
        $result = array();
        while($row=$db->fetch_array($query)) {
            $result[] = $row;
        }
        $db->free_result($query);
        unset($select,$joinon,$where,$row);
        return $result;
    }

    function & getNewMessages($uid) {
        global $db, $dbpre;
        $query = $db->query("SELECT $select,subject,new,posttime,username FROM {$dbpre}pmsgs p LEFT JOIN {$dbpre}members m ON($joinon) WHERE recvuid='$uid' AND new=1 AND delflag!=1 ORDER BY posttime DESC LIMIT $limit");
        $result = array();
        while($row=$db->fetch_array($query)) {
            $result[] = $row;
        }
        $db->free_result($query);
        unset($row);
        return $result;
    }

}
?>
