<?php
/**
 * [BEGIN_COT_EXT]
 * Hooks=moderation.page.mfind
 * [END_COT_EXT]
 */

defined('COT_CODE') or die('Wrong URL');

if($m == 'ds_dialogs' && in_array('ds_dialogs', $moderauth)) {
  $mfind = true;
  $uid = cot_import('uid', 'G', 'INT');

  require_once cot_incfile('ds', 'module');
  require_once cot_langfile('ds', 'module');

  $maxrowsperpage = 10;
  list($pn, $d, $d_url) = cot_import_pagenav('d', $maxrowsperpage);

  $list_url_path = array('m' => 'ds_dialogs', 'uid' => $uid);

  $modersql = array();
  if($usr['maingrp'] != 5) {
    $modersql = $db->query("SELECT user_id FROM $db_users WHERE user_maingrp>3 AND (user_maingrp=".implode(' OR user_maingrp=', $cfg['moder_group_ids']).')')->fetchAll(PDO::FETCH_COLUMN);
  }

  $where = "toid>0 AND fromid>0 ".($uid > 0 ? " AND (toid=".$uid." OR fromid=".$uid.")" : '').(count($modersql) > 0 ? ' AND (toid!='.implode(' AND toid!=', $modersql).') AND (fromid!='.implode(' AND fromid!=', $modersql).')' : '');

  $totalitems = $db->query("SELECT COUNT(*) FROM $db_ds_dialog WHERE ".$where)->fetchColumn();

  $pagenav = cot_pagenav('moderation', $list_url_path, $d, $totalitems, $maxrowsperpage);

  $dialogs = $db->query("SELECT * FROM $db_ds_dialog
      WHERE ".$where."
      ORDER BY lastmsg DESC
      LIMIT $d, " . $maxrowsperpage)->fetchAll();

  $t = new XTemplate(cot_tplfile(array('moderation', 'ds_dialogs')));
  $jj=0;
  foreach ($dialogs as $row)
  {
    $jj++;
    $msgfilter = "(dialog = '".$row['id']."')";
    $msg = $db->query("SELECT * FROM $db_ds_msg WHERE $msgfilter ORDER BY id DESC LIMIT 1")->fetch();   //получаем последнее сообщение из диалога

    if($msg['text'][0] == '<' && $msg['text'][1] == 'b' && $msg['text'][2] == '>')
      $msg['text'] = preg_replace('/^(<b>(.*)<\/b>)(.*)/i', '$3', $msg['text']);

    $msg['text'] = explode('<br>', $msg['text']);
    $msg['text'][0] = trim($msg['text'][0]);
    $msg['text'] = (!empty($msg['text'][0]) ? $msg['text'][0] : $msg['text'][1]);

    $msg['text'] = strip_tags($msg['text']);

    if(empty($msg['text'])) {
      $msg['resend_arr'] = (!empty($msg['resend']) ? json_decode($msg['resend'],1) : array());
      if(count($msg['resend_arr']) > 0) {
        $msg['text'] = 'Пересылаемое сообщение';
      }
    }

    $mdata = cot_ds_get_mdata($msg['mtype'], $msg['mdata']);

    $pretext = '';
    if($msg['mtype'] == 0) {
      $pretext = cot_string_truncate($msg['text'], 65, true, false, "...");
    } else {
      if($msg['mtype'] == 5) {
        $pretext = cot_rc($cfg['ds']['mtypes_notytitle'][5], $mdata);
        $pretext = cot_string_truncate($pretext, 65, true, false, "...");
      } elseif($msg['mtype'] == 6) {
        $pretext = cot_rc($cfg['ds']['mtypes_notytitle'][6], $mdata);
        $pretext = cot_string_truncate($pretext, 65, true, false, "...");
      }else {
        $pretext = $cfg['ds']['mtypes_notytitle'][$msg['mtype']];
      }
    }

  	$t->assign(array(
    	'DS_DATE' => cot_date('datetime_medium', $msg['date']),
  		'DS_DATE_STAMP' => $msg['date'],
      'DS_TIME_AGO' => cot_build_timeago($msg['date']),
  		'DS_DIAOG_URL' => cot_url('moderation', 'm=ds_dialog_show&chat='.$msg['dialog']),   //ссылка на диалог
      'DS_STATUS' => $msg['status'],  //прочитано или нет
  		'DS_TEXT' => $pretext,
  	));
  	$t->assign(cot_generate_usertags(($msg['touser'] == $row['toid'] ? $row['toid'] : $row['fromid']), 'DS_TO_USER_'));
    $t->assign(cot_generate_usertags(($msg['touser'] == $row['toid'] ? $row['fromid'] : $row['toid']), 'DS_FROM_USER_'));

  	$t->parse('MAIN.DS_ROW');
  }

  $t->assign(array(
  	"PAGENAV_PAGES" => $pagenav['main'],
  	"PAGENAV_PREV" => $pagenav['prev'],
  	"PAGENAV_NEXT" => $pagenav['next'],
    "PAGENAV_LAST" => $pagenav['lastlink'],
  	"PAGENAV_COUNT" => $totalitems,
    'DS_DIALOGS_CNT' => $jj,
  ));

  $usersql = $db->query("SELECT user_id, user_name FROM $db_users WHERE user_maingrp>3 AND user_maingrp!=".($usr['maingrp'] != 5 ? implode(' AND user_maingrp!=', $cfg['moder_group_ids']) : '0'))->fetchAll(PDO::FETCH_KEY_PAIR);
  $t->assign('SEARCH_USERS', cot_selectbox($uid, 'uid', array_keys($usersql), array_values($usersql), true));

  $t->parse('MAIN');
  echo $t->text('MAIN');
} elseif($m == 'ds_dialog_show' && in_array('ds_dialog_show', $moderauth)) {
  $mfind = true;

  require_once cot_incfile('ds', 'module');
  require_once cot_langfile('ds', 'module');

  $chat = cot_import('chat','G','INT');

  $maxrowsperpage = 10;
  list($pn, $d, $d_url) = cot_import_pagenav('d', $maxrowsperpage);

  $list_url_path = array('m' => 'ds_dialog_show', 'chat' => $chat);

  $modersql = array();
  if($usr['maingrp'] != 5) {
    $modersql = $db->query("SELECT user_id FROM $db_users WHERE user_maingrp>3 AND (user_maingrp=".implode(' OR user_maingrp=', $cfg['moder_group_ids']).')')->fetchAll(PDO::FETCH_COLUMN);
  }

  $where = "id=".$chat." AND toid>0 AND fromid>0 ".($uid > 0 ? " AND (toid=".$uid." OR fromid=".$uid.")" : '').(count($modersql) > 0 ? ' AND (toid!='.implode(' AND toid!=', $modersql).') AND (fromid!='.implode(' AND fromid!=', $modersql).')' : '');
  $dialog = $db->query("SELECT * FROM $db_ds_dialog
      WHERE ".$where."
      LIMIT 1")->fetch();

  $totalitems = 0;
  if($dialog['id'] > 0) {
    $totags = cot_generate_usertags($dialog['toid'], 'DS_ROW_USER_');
    $fromtags = cot_generate_usertags($dialog['fromid'], 'DS_ROW_USER_');

    $t = new XTemplate(cot_tplfile(array('moderation', 'ds_dialog_show')));

    $totalitems = $db->query("SELECT COUNT(*) FROM $db_ds_msg WHERE dialog=".$chat)->fetchColumn();
    $dialog_history = $db->query("SELECT * FROM $db_ds_msg WHERE dialog=".$chat." ORDER BY id DESC LIMIT $d, " . $maxrowsperpage)->fetchAll();
    if (!empty($dialog_history))
    {
    	foreach ($dialog_history as $row)
    	{
    		$t->assign(array(
    			'DS_ROW_ID' => $row['id'],
    			'DS_ROW_DATE' => cot_date('d.m.Y H:i', $row['date']),
    			'DS_ROW_DATE_STAMP' => $row['date'],
    			'DS_ROW_TEXT' => $row['text'],
          'DS_ROW_WHODELETE' => ((!$row['act_tid'] || !$row['act_fid']) ? '<b>Удалено у '.(!$row['act_tid'] ? $totags['DS_ROW_USER_NICKNAME'].(!$row['act_fid'] ? ' и '.$fromtags['DS_ROW_USER_NICKNAME'] : '') : $fromtags['DS_ROW_USER_NICKNAME']).'</b>' : ''),
          'DS_ROW_READSTATUS' => $row['status'],
    		));

        if ($row['touser'] == $fromtags['DS_ROW_USER_ID'])
        {
          $t->assign($totags);
        }else{
    		  $t->assign($fromtags);
        }
    		$t->parse('MAIN.DS_ROW');
    	}
    }
  }

  $pagenav = cot_pagenav('moderation', $list_url_path, $d, $totalitems, $maxrowsperpage);

  $t->assign(array(
  	"PAGENAV_PAGES" => $pagenav['main'],
  	"PAGENAV_PREV" => $pagenav['prev'],
  	"PAGENAV_NEXT" => $pagenav['next'],
    "PAGENAV_LAST" => $pagenav['lastlink'],
  	"PAGENAV_COUNT" => $totalitems,
  ));

  $t->parse('MAIN');
  echo $t->text('MAIN');
}

?>