<?php

/*
 * @name        JMY CMS
 * @link        https://jmy.su/
 * @copyright   Copyright (C) 2012-2025 JMY LTD
 * @license     LICENSE.txt (see attached file)
 * @version     VERSION.txt (see attached file)
 * @author      Komarov Ivan
 * @edited      Orlov Alexsey
 */

if (!defined('ACCESS')) {
    header('Location: /');
    exit;
}
loadConfig('user');
loadConfig('email');
global $db, $config, $core, $url, $user, $email_conf, $lang;
set_title(array($lang['pm']));
if ($core->auth->isUser) {
    $mod = $url[0] ?? '';
    function menu($matches = array())
    {
        global $core, $user, $lang;
        $title = $lang['pm'];
        $prlim = 0;
        if (isset($matches[1])) $title = $matches[1];
        $core->tpl->loadFile('pm/menu');
        $core->tpl->setVar('TITLE', $title);
        $core->tpl->setVar('URL_WRITE', '<a href="{%MOD_NAME%}/write">');
        $core->tpl->setVar('URL_INBOX', '<a onclick="ajaxSimple(\'index.php?url={%MOD_NAME%}/inbox&set_title=pm_in\', \'pm_content\', true)"  href="javascript:void(0)">');
        $core->tpl->setVar('URL_SENTBOX', '<a onclick="ajaxSimple(\'index.php?url={%MOD_NAME%}/sentbox&set_title=pm_out\', \'pm_content\', true)"  href="javascript:void(0)">');
        $core->tpl->setVar('URL_DRAFTCOPY', '<a onclick="ajaxSimple(\'index.php?url={%MOD_NAME%}/draftcopy&set_title=pm_draft\', \'pm_content\', true)"  href="javascript:void(0)">');
        $core->tpl->setVar('URL_BASKET', '<a onclick="ajaxSimple(\'index.php?url={%MOD_NAME%}/basket&set_title=pm_basket\', \'pm_content\', true)"  href="javascript:void(0)">');
        $core->tpl->setVar('URL_PM_MAIN', '<script type="text/javascript">ajaxSimple(\'index.php?url=pm/inbox&set_title=pm_in\', \'pm_content\', true)</script>');
        if (!empty($core->auth->user_info['id']) && $user['pm_limit'] == 1) {
            $num_pm = $core->sum_data('pm', 'pm.fromid ="' . $core->auth->user_info['id'] . '" AND pm.status !=4', 'time DESC', 'pm.*, u.nick', 'as pm LEFT JOIN ' . DB_PREFIX . '_users as u on (pm.toid = u.id)');
            $prlim = intval($num_pm / $user['max_pm'] * 100);
            $residue = intval($user['max_pm'] - $num_pm);
            if ($prlim > 100) $prlim = 100;
            $core->tpl->setVar('PROC-PM-LIMIT', $prlim);
            $core->tpl->setVar('LIMIT', $user['max_pm']);
            $core->tpl->setVar('RESIDUE', $residue);
        } else {
            $core->tpl->setVar('PROC-PM-LIMIT', $prlim);
            $core->tpl->setVar('LIMIT', $lang['no_pm_limit']);
        }
        $core->tpl->setVar('PM-PROGRESS-BAR', "<div class=\"pm_progress_bar\" title=\"" . $lang['pm_progress_bar'] . $prlim . "%\"><span style=\"width:" . $prlim . "%\">" . $prlim . "%</span></div>");
        $core->tpl->setVar('URL_END', '</a>');
        return $core->tpl->return_end();
    }

    switch ($url[1] ?? null) {
        default:
            $core->tpl->loadFile('pm/main');
            $core->tpl->setVar('LOCATION', $lang['pm_in']);
            $core->tpl->sources = preg_replace_callback("#\\[menu:(.*?)]#is", "menu", $core->tpl->sources);
            $core->tpl->end();
            break;
        case 'inbox':
            $result = $core->select_data('pm', 'pm.toid ="' . $core->auth->user_id . '" AND pm.status !=2 AND pm.status !=3 AND pm.status !=4', 'time DESC', 'pm.*, u.nick', 'as pm LEFT JOIN ' . DB_PREFIX . '_users as u on (pm.fromid = u.id)');
            $messNo = $lang['pm_ins'];
            $th1 = $lang['pm_sender'];
            $init = 'fromid';
        case 'sentbox':
            if (!isset($messNo)) {
                $result = $core->select_data('pm', 'pm.fromid ="' . $core->auth->user_id . '" AND pm.status !=2 AND pm.status !=3 AND pm.status !=4', 'time DESC', 'pm.*, u.nick', 'as pm LEFT JOIN ' . DB_PREFIX . '_users as u on (pm.toid = u.id)');
                $messNo = $lang['pm_outs'];
                $th1 = $lang['pm_receiver'];
                $init = 'toid';
            }
        case 'basket':
            if (!isset($messNo)) {
                $result = $core->select_data('pm', 'pm.fromid ="' . $core->auth->user_id . '" AND pm.status=3', 'time DESC', 'pm.*, u.nick', 'as pm LEFT JOIN ' . DB_PREFIX . '_users as u on (pm.toid = u.id)');
                $messNo = $lang['pm_basket'];
                $th1 = $lang['pm_receiver'];
                $init = 'toid';
            }
        case 'draftcopy':
            if (!isset($messNo)) {
                $result = $core->select_data('pm', 'pm.fromid ="' . $core->auth->user_id . '" AND pm.status=2', 'time DESC', 'pm.*, u.nick', 'as pm LEFT JOIN ' . DB_PREFIX . '_users as u on (pm.toid = u.id)');
                $messNo = $lang['pm_drafts'];
                $th1 = $lang['pm_receiver'];
                $init = 'toid';
            }
            ajaxInit();
            $no_head = true;
            $numRes = $db->numRows($result);
            $_GET['set_title'] = $_GET['set_title'] ?? 'error';
            $core->tpl->loadFile('pm/list');
            $core->tpl->setVar('TH1', $th1);
            $core->tpl->setVar('LOCATION', $lang[$_GET['set_title']]);
            $core->tpl->setVar('MESSNO', $messNo);
            $core->tpl->sources = preg_replace_callback("#\\[initfrom](.*?)\\[/initfrom]#is", function ($matches) use ($init) {
                if ($init == 'fromid') return $matches[1];
            }, $core->tpl->sources);
            $core->tpl->sources = preg_replace_callback("#\\[reply](.*?)\\[/reply]#is", function ($matches) use ($init) {
                if ($init == 'fromid') return $matches[1];
            }, $core->tpl->sources);
            preg_match("#\\[list](.*?)\\[/list]#is", $core->tpl->sources, $matches);
            $list = $matches[1] ?? '';
            preg_match("#\\[messEmpty](.*?)\\[/messEmpty]#is", $core->tpl->sources, $matchEmpty);
            $messEmpty = $matchEmpty;
            $messList = '';
            if ($numRes > 0) {
                while ($message = $db->getRow($result)) {
                    $from = $core->row_data('users', 'id ="' . $message[$init] . '"');
                    $replace = array(
                        '@{%AVATAR%}@' => avatar($message[$init]),
                        '@{%NICK%}@' => $message['nick'],
                        '@{%FROM%}@' => $from['nick'],
                        '@{%MESSID%}@' => $message['id'],
                        '@{%MOD_NAME%}@' => $mod,
                        '@{%DATE%}@' => formatDate($message['time'], true),
                        '@{%TOPIC%}@' => $core->bbDecode($message['topic']),
                        '@{%MESSAGE%}@' => $core->bbDecode($message['message']),
                        '@{%DELETE%}@' => '<span id="msgNo' . $message['id'] . '"><a href="javascript://" onclick="ajaxSimple(\'index.php?url=pm/into_basket/' . $message['id'] . '/\', \'msgNo' . $message['id'] . '\', true)">' . $lang['delete_pm'] . '</a></span>',
                        '@{%LETTER%}@' => '<span id="msgNo' . $message['id'] . '"> <a href="pm/letter/' . $from['nick'] . '/' . $message['id'] . '">' . $lang['send_pm'] . '</a> ',
                        '@{%CLEAN%}@' => '<span id="msgNo' . $message['id'] . '"><a href="javascript://" onclick="ajaxSimple(\'index.php?url=pm/del_pm/' . $message['id'] . '/\', \'msgNo' . $message['id'] . '\', true)">' . $lang['clear'] . '</a></span>',
                        '@{%BASKET%}@' => '<span id="msgNo' . $message['id'] . '"><a href="javascript://" onclick="ajaxSimple(\'index.php?url=pm/into_basket/' . $message['id'] . '/\', \'msgNo' . $message['id'] . '\', true)">' . $lang['rash_pm'] . '</a></span>',
                        '@{%DRAFTCOPY%}@' => '<span id="msgNo' . $message['id'] . '"><a href="javascript://" onclick="ajaxSimple(\'index.php?url=pm/into_draftcopy/' . $message['id'] . '/\', \'msgNo' . $message['id'] . '\', true)">' . $lang['draft_pm'] . '</a></span>',
                        '@{%UNREAD%}@' => '<span id="msgNo' . $message['id'] . '"><a href="javascript://" onclick="ajaxSimple(\'index.php?url=pm/unread/' . $message['id'] . '/\', \'msgNo' . $message['id'] . '\', true)">' . $lang['mark_unread'] . '</a></span>',
                        "@\\[menu:(.*?)\\]@is" => ("menu('\\1')"),
                        "@\\[status\=0\\](.*?)\\[else\\](.*?)\\[/status\\]@is" => ($message['status'] == 0 ? '\\1' : '\\2'),
                        "@\\[unread\\](.*?)\\[/unread\\]@is" => ($lang[$_GET['set_title']] != $lang['pm_draft'] || $lang[$_GET['set_title']] != $lang['pm_basket'] && $message['toid'] == $core->auth->user_id ? '\\1' : '\\2'),
                        "@\\[draftcopy\\](.*?)\\[/draftcopy\\]@is" => ($lang[$_GET['set_title']] == $lang['pm_basket'] || $message['fromid'] == $core->auth->user_id && $message['status'] == 0 ? '\\1' : '\\2'),
                        "@\\[basket\\](.*?)\\[/basket\\]@is" => ($lang[$_GET['set_title']] != $lang['pm_basket'] && $message['fromid'] == $core->auth->user_id && $message['status'] == 2 ? '\\1' : '\\2'),
                        "@\\[clean\\](.*?)\\[/clean\\]@is" => ($lang[$_GET['set_title']] == $lang['pm_draft'] || $lang[$_GET['set_title']] == $lang['pm_basket'] && $message['fromid'] == $core->auth->user_id && $message['status'] == 3 ? '\\1' : '\\2'),
                        "@\\[delete\\](.*?)\\[/delete\\]@is" => ($lang[$_GET['set_title']] == $lang['pm_out'] || $lang[$_GET['set_title']] != $lang['pm_draft'] && $lang[$_GET['set_title']] != $lang['pm_basket'] && $message['toid'] == $core->auth->user_id ? '\\1' : '\\2'),
                        "@\\[letter\\](.*?)\\[/letter\\]@is" => ($lang[$_GET['set_title']] != $lang['pm_basket'] || $message['toid'] == $core->auth->user_id ? '\\1' : '\\2'),
                    );
                    $tpl = preg_replace(array_keys($replace), array_values($replace), $list);
                    $messList .= $tpl;
                    unset($tpl);
                    $core->tpl->setVar('REPLY', '<a href="pm/letter/' . $from['nick'] . '/' . $message[$init] . '">' . $lang['quick_answer'] . '</a> ');
                }
            } else {
                $core->tpl->info($lang['nothing_found']);
            }
            $core->tpl->sources = preg_replace_callback("#\\[messEmpty](.*?)\\[/messEmpty]#is", function ($matches) use ($numRes) {
                if ($numRes == 0) return $matches[1];
            }, $core->tpl->sources);
            $core->tpl->sources = preg_replace_callback("#\\[list](.*?)\\[/list]#is", function ($matches) use ($messList) {
                if ($messList) return $messList; else return $matches[1];
            }, $core->tpl->sources);
            $core->tpl->end();
            break;
        case 'write':
            set_title(array($lang['pmprivate'], $lang['write']));
            $nick = $url[2] ?? '';
            $topic = '';
            $message = '';
            if (!empty($nick)) $result = $core->row_data('users', 'nick ="' . $db->safesql($nick) . '"');
            if (!empty($nick) && !empty($result) && isset($url[3])) {
                $q = $core->row_data('pm', 'id ="' . intval($url[3]) . '" AND fromid ="' . intval($result['id']) . '" AND toid ="' . intval($core->auth->user_info['id']) . '"');
                $message = '[quote]' . $q['message'] . '[/quote]';
                $topic = $lang['answer_to'] . $q['topic'];
            }
            $write = '<form enctype="multipart/form-data" action="' . $mod . '/sent" method="post">
   <table style="width=:100%; border: 0; border-spacing: 1px; border-collapse: separate; text-align:center;">
      <tr>
         <td style="vertical-align: top;">' . $lang['usersname'] . ':</td>
         <td>
            <input type="text" class="field prepend-icon" name="author" id="author" value="' . (isset($result) ? $nick : '') . '" onkeyup="checkLogin(gid(\'author\').value, \'check_result\', \'author\')">
            <div id="check_result" class="results" style="display:none;"></div>
            <br/><br/><a class="ln"><span>' . $lang['r_user_nick'] . '</span></a>
         </td>
      </tr>';
            if ($user['userFriends'] == 1) {
                $uid = $core->auth->user_info['id'];
                $fq = $core->select_data('users', 'WHERE (f.who_invite ="' . $uid . '" OR f.whom_invite ="' . $uid . '") AND u.id !="' . $uid . '" AND f.confirmed = 1', false, 'u.id as uuid, u.nick, u.last_visit, f.*', 'as u LEFT JOIN ' . DB_PREFIX . '_user_friends as f on(u.id = f.who_invite OR u.id = f.whom_invite)');
                $friends = '';
                $yourFriends = array();
                if ($db->numRows($fq) > 0) {
                    while ($frows = $db->getRow($fq)) {
                        $friends .= '<option value="' . $frows['nick'] . '">' . $frows['nick'] . '</option>';
                        $yourFriends[] = $frows['uuid'];
                        initDir('messages', 'users_' . $core->auth->user_info['id'], $frows['nick'] . '_' . $frows['uuid']);
                    }
                    $write .= '<tr>
         <td>' . $lang['choose_from_friends'] . '</td>
         <td>
            <select class="date_selection" name="friend">
               <option value="">' . $lang['no'] . '</option>
               ' . $friends . '
            </select>
         </td>
      </tr>';
                }
            }
            $write .= '<tr>
         <td style="vertical-align: top;">' . $lang['topic'] . ':</td>
         <td><input type="text" class="field prepend-icon" name="topic"  value=' . $topic . ' ><br/></td>
      </tr>';
            $write .= '<tr>
         <td>' . $lang['text'] . ':</td>
         <td><br/>';
            $write .= bb_area('message', html2bb($message), 5, 'textarea', null, true);
            $write .= '<br/>';
            $write .= '<input type="checkbox" name="status" class="poiskk" value="2">' . $lang['save_draft'];
            $write .= '</td>
      </tr>';
            $write .= '<tr>
         <td colspan="2" style="text-align:center"><br/>
         <input type="hidden" name="id" value=""><input type="submit" class="submit" value="' . $lang['send'] . '">
         <button name="nview" onclick="preview()" class="submit" type="reset"><span>' . $lang['clear'] . '</span></button></td>
      </tr>
</form>
</table>';
            $core->tpl->loadFile('pm/write');
            $core->tpl->setVar('LOCATION', $lang['sending_p_messages']);
            $core->tpl->sources = preg_replace_callback("#\\[menu:(.*?)]#is", "menu", $core->tpl->sources);
            $core->tpl->setVar('WRITE', $write);
            $core->tpl->end();
            break;
        case 'letter':
            set_title(array($lang['pmprivate'], $lang['write']));
            $nick = $url[2] ?? '';
            $topic = '';
            $message = '';
            if (!empty($nick)) $result = $core->row_data('users', 'nick ="' . $db->safesql($nick) . '"');
            if (!empty($nick) && !empty($result) && isset($url[3])) {
                $q = $core->row_data('pm', 'id ="' . intval($url[3]) . '" AND fromid ="' . intval($result['id']) . '" AND toid ="' . intval($core->auth->user_info['id']) . '"');
                $message = $q['message'];
                $topic = $lang['letter_from'] . $core->auth->user_info['nick'];
            }
            if ($core->auth->user_info['nick'] == $nick) {
                $core->tpl->info($lang['yourself_cant_write']);
                header("refresh: 5; url=" . $config['url'] . "/profile");
            } else {
                $letter = '<form enctype="multipart/form-data" action="' . $mod . '/sent" method="post">
   <table style="width=:100%; border: 0; border-spacing: 1px; border-collapse: separate; text-align:center;">
      <tr>
         <td style="vertical-align: top;"></td>
         <td>
            <input type="text" class="field prepend-icon" name="author" id="author" value="' . (isset($result) ? $nick : '') . '" onkeyup=\"checkLogin(gid(\'author\').value, \'check_result\', \'author\')">
            <div id="check_result" class="results" style="display:none;"></div>
            <br/><br/><a class="ln"><span>' . $lang['r_user_nick'] . '</span></a>
         </td>
      </tr>';
                initDir('messages', 'users_' . $core->auth->user_info['id'], $nick . '_' . $result['id']);
                $letter .= '<tr>
         <td class="in_conf_input" style="vertical-align: top;">' . $lang['topic'] . ':</td>
         <td><input type="text" class="field prepend-icon" name="topic"  value="' . $topic . '"/><br/></td>
      </tr>';
                $letter .= '<tr>
         <td>' . $lang['text'] . ':</td>
         <td><br/>';
                $letter .= bb_area('message', html2bb($message), 5, 'textarea', null, true);
                $letter .= '<br/>';
                $letter .= '<input type="checkbox" name="status" class="poiskk" value="2">' . $lang['save_draft'];
                $letter .= '</td>
      </tr>';
                $letter .= '<tr>
         <td colspan="2" style="text-align:center"><br/>
         <input type="hidden" name="id" value=""><input type="submit" class="submit" value="' . $lang['send'] . '">
         <button name="nview" onclick="preview()" class="submit" type="reset"><span>' . $lang['clear'] . '</span></button></td>
      </tr>
</form>
</table>';
                $core->tpl->loadFile('pm/write');
                $core->tpl->setVar('LOCATION', $lang['send_pmprivate']);
                $core->tpl->sources = preg_replace_callback("#\\[menu:(.*?)]#is", "menu", $core->tpl->sources);
                $core->tpl->setVar('WRITE', $letter);
                $core->tpl->end();
            }
            break;
        case 'notaut':
            set_title(array($lang['notification_author'], $lang['write']));
            $nick = $url[2] ?? '';
            $nid = $url[3] ?? '';
            $url = $core->row_data('langs', 'postid ="' . $nid . '"');
            $message = '';
            if (!empty($nick)) $result = $core->row_data('users', 'nick ="' . $db->safesql($nick) . '"');
            if (!empty($nick) && !empty($result) && isset($url[3])) {
                $q = $core->row_data('pm', 'id ="' . intval($url[3]) . '" AND fromid ="' . intval($result['id']) . '" AND toid ="' . intval($core->auth->user_info['id']) . '"');
                $message = $q['message'];
                $topic = $lang['notification_from'] . $core->auth->user_info['nick'];
            }
            if ($core->auth->user_info['nick'] == $nick) {
                $core->tpl->info($lang['yourself_cant_write']);
                header("refresh: 5; url=" . $config['url'] . "/profile");
            } else {
                $topic = $lang['notification_from'] . $core->auth->user_info['nick'];
                $message .= $lang['respected'];
                $message .= (isset($result) ? $nick : '');
                $message .= ', <br/><br/> ';
                $message .= $lang['your_article'];
                $message .= $nid;
                $message .= '  ';
                $message .= '"';
                $message .= $url['title'];
                $message .= '"';
                $message .= $lang['number_violations'];
                $message .= '<br/><br/>';
                $message .= '--------------------------------------------------------------------------------';
                $message .= '<br/><br/>';
                $message .= '<br/><br/>';
                $message .= '<br/><br/>';
                $letter = '<form enctype="multipart/form-data" action="' . $mod . '/sent" method="post">
   <table style="width=:100%; border: 0; border-spacing: 1px; border-collapse: separate; text-align:center;">
      <tr>
         <td style="vertical-align: top;">' . $lang['username'] . ':</td>
         <td>
            <input type="text" class="field prepend-icon" name="author" id="author" value="' . (isset($result) ? $nick : '') . '" onkeyup=\"checkLogin(gid(\'author\').value, \'check_result\', \'author\')">
            <div id="check_result" class="results" style="display:none;"></div>
            <br/><br/><a class="ln"><span>' . $lang['r_user_nick'] . '</span></a>
         </td>
      </tr>';
                initDir('messages', 'users_' . $core->auth->user_info['id'], $nick . '_' . $result['id']);
                $letter .= '<tr>
         <td style="vertical-align: top;">' . $lang['topic'] . ':</td>
         <td><input type="text" class="field prepend-icon" name="topic"  value="' . $topic . '" ><br/></td>
      </tr>';
                $letter .= '<tr>
         <td>' . $lang['text'] . ':</td>
         <td>';
                $letter .= bb_area('message', html2bb($message), 5, 'textarea', null, true);
                $letter .= '<br/>';
                $letter .= '<input type="checkbox" name="status" class="poiskk" value="2">' . $lang['save_draft'] . '';
                $letter .= '</td>
      </tr>';
                $letter .= '<tr>
         <td colspan="2" style="text-align:center"><br/><input type="hidden" name="id" value="' . $result['id'] . '"><input type="submit" class="form-button-tt" value="' . $lang['send'] . '" ></td>
      </tr>
</form>
</table>';
                $core->tpl->loadFile('pm/write');
                $core->tpl->setVar('LOCATION', $lang['notification_author']);
                $core->tpl->sources = preg_replace_callback("#\\[menu:(.*?)]#is", "menu", $core->tpl->sources);
                $core->tpl->setVar('WRITE', $letter);
                $core->tpl->end();
            }
            break;
        case 'sent':
            global $config;
            echo menu();
            if (!empty($_POST['topic']) && !empty($_POST['message'])) {
                echo '<div id="pm_content">' . "\n";
                $id = isset($_POST['id']) ? intval($_POST['id']) : '';
                $friend = isset($_POST['friend']) ? filter($_POST['friend'], 'nick') : '';
                $author = isset($_POST['author']) ? filter($_POST['author'], 'nick') : '';
                $status = (isset($_POST['status']) != 2 ? 0 : $_POST['status']);
                $to = empty($friend) ? $author : $friend;
                if ($core->auth->user_info['nick'] != $to) {
                    $result = $core->row_data('users', 'nick ="' . $db->safesql($to) . '"');
                    if ($result) {
                        if ($core->ins_data('pm', 'id,toid,fromid,topic,message,time,users_delete,users_del_data,status', 'NULL,"' . $result['id'] . '","' . $core->auth->user_id . '","' . $db->safesql(parseBB(processText(filter($_POST['topic'], 'html')))) . '","' . $db->safesql(parseBB(processText(filter($_POST['message'], 'html')))) . '","' . time() . '", 0, 0,"' . $status . '"')) {
                            if ($email_conf['new_pm'] == 1) {
                                $query = $core->select_data('email', false, 'id ASC');
                                $from = $core->row_data('users', 'id ="' . $id . '"');
                                while ($result = $db->getRow($query)) {
                                    $message = $result['html_new_pm'] > 0 ? str_replace(array('&lt;', '&gt;', '{%username%}', '{%date%}', '{%fromusername%}', '{%text%}', '{%url%}'), array('<', '>', $db->safesql($to), formatDate(time(), true), $core->auth->user_info['nick'], $db->safesql(parseBB(processText(filter($_POST['message'], 'html')))), $config['url']), $result['new_pm_text']) : str_replace(array('\p', '\n', '\r', '<br>', '<br/>', '&nbsp;', '{%username%}', '{%date%}', '{%fromusername%}', '{%text%}', '{%url%}'), array('""', '""', '""', '\n', '\n', '\n', $db->safesql($to), formatDate(time(), true), $core->auth->user_info['nick'], $db->safesql(parseBB(processText(filter($_POST['message'], 'html')))), $config['url']), $result['new_pm_text']);
                                    $userInfo = $core->row_data('users', 'nick ="' . $author . '"');
                                    if ($userInfo['no_mail'] == 1) {
                                        if (isset($author) && !empty($message) || isset($friend) && !empty($message)) {
                                            mailSMTP($from['email'], $result['html_new_pm'], $lang['mail_pm'], $message);
                                        } else {
                                            $core->tpl->info($lang['sendfalse'] . ' <strong><a href="javascript:history.go(-1)"><b>' . $lang['go_back'] . '</b></a></strong>');
                                        }
                                    }
                                }
                            }
                            location('pm/sent_ok');
                        } else {
                            $core->tpl->info($lang['error_sending']);
                        }
                    } else {
                        $core->tpl->info($lang['users_found']);
                        header("refresh: 5; url=" . $config['url'] . "/pm/write");
                    }
                } else {
                    $core->tpl->info($lang['yourself_cant_pm']);
                    header("refresh: 5; url=" . $config['url'] . "/pm/write");
                }
                echo '</div>';
            } else {
                $core->tpl->info($lang['error_fill']);
                header("refresh: 5; url=" . $config['url'] . "/pm/write");
            }
            break;
        case 'sent_ok':
            echo menu();
            echo '<div id="pm_content">' . "\n";
            $core->tpl->info($lang['successfully_sent']);
            header("refresh: 5; url=" . $config['url'] . "/pm");
            echo '</div>';
            break;
        case 'view':
            $id = intval($url[2]);
            set_title(array($lang['pmprivate'], $lang['pmview']));
            $result = $core->row_data('pm', 'pm.id ="' . $id . '" AND pm.status !=4', false, 'pm.*, u.nick', 'as pm LEFT JOIN ' . DB_PREFIX . '_users as u on(pm.toid=u.id)');
            if ($result) {
                if ($result['toid'] == $core->auth->user_id && $result['status'] == 0) $core->upd_data('pm', 'status = 1', 'id ="' . $id . '"');
                $from = $core->row_data('users', 'id ="' . $result['fromid'] . '"');
                $core->tpl->loadFile('pm/view');
                $core->tpl->setVar('LOCATION', $lang['viewing_message']);
                $core->tpl->setVar('TOPIC', $core->bbDecode($result['topic']));
                $core->tpl->setVar('MESSAGE', $core->bbDecode($result['message']));
                $core->tpl->setVar('AVATAR', ($result['toid'] == $core->auth->user_id ? avatar($result['fromid']) : avatar($result['toid'])));
                $core->tpl->setVar('FROM', $from['nick'] ?? '');
                $core->tpl->setVar('TO', $result['nick'] ?? '');
                $core->tpl->setVar('ID', $result['id'] ?? '');
                $core->tpl->setVar('DATE', formatDate($result['time'], true));
                $core->tpl->setVar('ACTIONS', '<span id="msgNo' . $result['id'] . '"><a href="javascript://" onclick="ajaxSimple(\'index.php?url=pm/into_basket/' . $result['id'] . '/\', \'msgNo' . $result['id'] . '\', true)">' . $lang['delete_pm'] . '</a></span> <a href="pm/letter/' . $from['nick'] . '/' . $result['id'] . '">' . $lang['send_pm'] . '</a> ');
                $core->tpl->setVar('CLEAN', '<span id="msgNo' . $result['id'] . '"><a href="javascript://" onclick="ajaxSimple(\'index.php?url=pm/del_pm/' . $result['id'] . '/\', \'msgNo' . $result['id'] . '\', true)">' . $lang['clear'] . '</a></span>');
                $core->tpl->setVar('BASKET', '<span id="msgNo' . $result['id'] . '"><a href="javascript://" onclick="ajaxSimple(\'index.php?url=pm/into_basket/' . $result['id'] . '/\', \'msgNo' . $result['id'] . '\', true)">' . $lang['rash_pm'] . '</a></span>');
                $core->tpl->setVar('DRAFTCOPY', '<span id="msgNo' . $result['id'] . '"><a href="javascript://" onclick="ajaxSimple(\'index.php?url=pm/into_draftcopy/' . $result['id'] . '/\', \'msgNo' . $result['id'] . '\', true)">' . $lang['draft_pm'] . '</a></span>');
                $core->tpl->setVar('UNREAD', '<span id="msgNo' . $result['id'] . '"><a href="javascript://" onclick="ajaxSimple(\'index.php?url=pm/unread/' . $result['id'] . '/\', \'msgNo' . $result['id'] . '\', true)">' . $lang['mark_unread'] . '</a></span>');
                $core->tpl->sources = preg_replace_callback("#\\[menu:(.*?)]#is", "menu", $core->tpl->sources);
                $core->tpl->sources = preg_replace_callback("@\\[status=0](.*?)\\[else](.*?)\\[/status]@is", function ($matches) use ($result) {
                    if ($result['status'] == 0) return $matches[1]; else return $matches[2];
                }, $core->tpl->sources);
                $core->tpl->sources = preg_replace_callback("@\\[actions](.*?)\\[/actions]@is", function ($matches) use ($result) {
                    if ($result['toid'] == 0) return $matches[1];
                }, $core->tpl->sources);
                $core->tpl->sources = preg_replace_callback("@\\[clean](.*?)\\[/clean]@is", function ($matches) use ($result, $core) {
                    if ($result['fromid'] == $core->auth->user_id && $result['status'] == 3) return $matches[1];
                }, $core->tpl->sources);
                $core->tpl->sources = preg_replace_callback("@\\[basket](.*?)\\[/basket]@is", function ($matches) use ($result, $core) {
                    if ($result['fromid'] == $core->auth->user_id && $result['status'] == 2) return $matches[1];
                }, $core->tpl->sources);
                $core->tpl->sources = preg_replace_callback("@\\[draftcopy](.*?)\\[/draftcopy]@is", function ($matches) use ($result, $core) {
                    if ($result['fromid'] == $core->auth->user_id && $result['status'] == 0) return $matches[1];
                }, $core->tpl->sources);
                $core->tpl->sources = preg_replace_callback("@\\[unread](.*?)\\[/unread]@is", function ($matches) use ($result, $core) {
                    if ($result['toid'] == $core->auth->user_id) return $matches[1];
                }, $core->tpl->sources);
                $core->tpl->end();
            } else {
                location('pm');
            }
            break;
        case 'del_pm':
            ajaxInit();
            $no_head = true;
            $users_delete = $lang['pm_autor_deleted'] . $core->auth->user_info['nick'];
            $users_del_data = time();
            if (!empty($url[2])) {
                $core->upd_data('pm', 'status = 4, users_delete ="' . $db->safesql(processText($users_delete)) . '", users_del_data ="' . $users_del_data . '"', 'id ="' . $db->safesql($url[2]) . '" AND status = 3 OR status = 2 ');
                $core->tpl->info($lang['message_delete_trash']);
                header("refresh: 0; url=" . $config['url'] . "/pm");
            }
            break;
        case 'unread':
            ajaxInit();
            $no_head = true;
            if (!empty($url[2])) {
                $core->upd_data('pm', '`status` = 0', 'id ="' . $db->safesql($url[2]) . '" AND `status` = 1 ');
                $core->tpl->info($lang['marked_unread']);
                header("refresh: 0; url=" . $config['url'] . "/pm");
            }
            break;
        case 'into_draftcopy':
            ajaxInit();
            $no_head = true;
            if (!empty($url[2])) {
                $core->upd_data('pm', '`status` = 2', 'id ="' . $db->safesql($url[2]) . '"');
                $core->tpl->info($lang['message_drafts']);
                header("refresh: 0; url=" . $config['url'] . "/pm");
            }
            break;
        case 'into_basket':
            ajaxInit();
            $no_head = true;
            if (!empty($url[2])) {
                $core->upd_data('pm', '`status` = 3', 'id ="' . $db->safesql($url[2]) . '"');
                $core->tpl->info($lang['message_placed_trash']);
                header("refresh: 0; url=" . $config['url'] . "/pm");
            }
            break;
        case 'del':
            ajaxInit();
            $no_head = true;
            if (!empty($url[2])) {
                $core->del_data('pm', 'id ="' . $db->safesql($url[2]) . '" AND toid ="' . $core->auth->user_id . '"');
                $core->tpl->info($lang['message_succes_delete']);
                header("refresh: 3; url=" . $config['url'] . "/pm");
            }
            break;
        case 'action':
            $checks = $_POST['checks'] ?? '';
            if (!empty($checks)) {
                if (isset($_POST['read'])) {
                    foreach ($checks as $id) {
                        $id = intval($id);
                        if ($id > 0) $core->upd_data('pm', '`status` = 1', 'id ="' . $id . '" AND `toid` ="' . $core->auth->user_id . '"');
                    }
                } elseif (isset($_POST['del'])) {
                    foreach ($checks as $id) {
                        $id = intval($id);
                        if ($id > 0) $core->del_data('pm', 'id ="' . $id . '" AND (toid ="' . $core->auth->user_id . '" OR fromid ="' . $core->auth->user_id . '")');
                    }
                }
            }
            location('pm');
            break;
    }
} else {
    location();
}