Advertisement
Guest User

Threads.php

a guest
Dec 13th, 2018
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 80.63 KB | None | 0 0
  1. <?php
  2. namespace Prodigy\Respond;
  3.  
  4. class Threads extends Respond
  5. {
  6.     public function Display($request, $response, $service, $app)
  7.     {
  8.         $GET = $request->paramsGet();
  9.         $SERVER = $request->server();
  10.         $namedParams = $request->paramsNamed();
  11.         $currentboard = $namedParams->get('board');
  12.         $threadid = $namedParams->get('thread');
  13.         $page = $namedParams->get('page');
  14.         $startmsg = $namedParams->get('startmsg');
  15.         $start = $namedParams->get('start', 0);
  16.        
  17.         $service->thread = $threadid;
  18.         $service->board = $currentboard;
  19.        
  20.         $service->videoTypes = array('ogm', 'ogv', 'webm', 'mp4');
  21.         $service->audioTypes = array('ogg', 'mp3', 'opus', 'm4a', 'aac', 'wav', 'flac');
  22.         $service->imageTypes = array('jpg', 'jpeg', 'gif', 'png', 'webp');
  23.        
  24.         if(!empty($page)) {
  25.             $start = $page;
  26.         }
  27.         elseif(!empty($startmsg)) {
  28.             $start = "msg$startmsg";
  29.         }
  30.        
  31.         $service->viewResults = $GET->get('viewResults');
  32.        
  33.         if ($currentboard == 0 || empty($currentboard))
  34.             return $this->findBoard($currentboard, $threadid);
  35.        
  36.         $service->board_moderators = $app->user->LoadBoardModerators($currentboard);
  37.        
  38.         $db_prefix = $app->db->prefix;
  39.         $db = $app->db;
  40.        
  41.         // If someone arrived here via a previous or next link, we must determine
  42.         // the appropriate ID_TOPIC.  If no such topic exists, we must present
  43.         // the user with an appropriate warning.
  44.         if ($start === 'prev' || $start === 'next' )
  45.         {
  46.             // Just prepare some variables that are used in the query
  47.             $gt_lt = ($start === 'prev') ? '>' : '<';
  48.             $order = ($start === 'prev') ? 'ASC' : 'DESC';
  49.             //$error = ($start === 'prev') ? $app->locale->txt['a1'] : $app->locale->txt['a2'];
  50.            
  51.             $query = "SELECT t2.ID_TOPIC FROM {$db_prefix}topics as t, {$db_prefix}topics as t2, {$db_prefix}messages as mes, {$db->db_prefix}messages as mes2
  52.                WHERE (mes.ID_MSG=t.ID_LAST_MSG && t.ID_BOARD=$currentboard && t.ID_TOPIC=$threadid && ((mes2.posterTime $gt_lt mes.posterTime && t2.isSticky $gt_lt= t.isSticky) || t2.isSticky $gt_lt t.isSticky) && t2.ID_LAST_MSG=mes2.ID_MSG && t2.ID_BOARD=t.ID_BOARD)
  53.                ORDER BY t2.isSticky $order, mes2.posterTime $order LIMIT 1";
  54.  
  55.             $dbrq = $db->query($query, false);
  56.             if ($dbrq->num_rows > 0){
  57.                 list ($threadid) = $dbrq->fetch_row();
  58.                 return $service->redirect("/b$currentboard/t$threadid/");
  59.             }
  60.             elseif($dbrq->num_rows == 0)
  61.                 return $app->errors->abort('', 'You have reached the end of the topic list');
  62.         }
  63.        
  64.         // at this point it is certain that $threadid holds the correct ID_TOPIC
  65.         // for the topic the user wants to view
  66.         //$viewnum = $threadid;
  67.        
  68.         //check for blog board
  69.         $dbrq = $db->query("SELECT ID_BOARD FROM {$db_prefix}boards WHERE ID_BOARD=$currentboard AND isBlog=1;", false);
  70.         $service->isBlog = ($dbrq->num_rows > 0) ? true : false;
  71.         if ($service->isBlog && $app->conf->blogmod_newblogontop)
  72.             $app->conf->viewNewestFirst = 1;
  73.  
  74.         $dbrq = $db->query("SELECT b.ID_CAT,b.name,c.name,c.memberGroups FROM {$db_prefix}boards as b,{$db_prefix}categories as c WHERE (b.ID_BOARD=$currentboard && b.ID_CAT=c.ID_CAT)", false);
  75.         list($curcat,$boardname,$cat,$temp2) = $dbrq->fetch_row();
  76.         $memgroups = explode(',',$temp2);
  77.        
  78.         $service->curcat = $curcat;
  79.         $service->boardname = $boardname;
  80.         $service->catname = $cat;
  81.  
  82.         if (!(in_array($app->user->group, $memgroups) || $memgroups[0] == null || $app->user->accessLevel() > 2 ))
  83.             return $app->errors->abort($app->locale->txt[106], $app->locale->txt[1]);
  84.        
  85.         $ID_MEMBER = $app->user->id;
  86.        
  87.         //Redirect to page & post with new messages -- Omar Bazavilvazo
  88.         if ($start === 'new')
  89.         {
  90.             // Check if a log exists, so we can go to next unreaded message page
  91.             $dbrq = $db->query("
  92.                SELECT GREATEST(IFNULL(lt.logTime, 0), IFNULL(lmr.logTime,0)) AS logtime, COUNT(m.ID_MSG), MAX(m.ID_MSG)
  93.                FROM {$db_prefix}topics AS t
  94.                LEFT JOIN {$db_prefix}log_topics AS lt ON (lt.ID_TOPIC=t.ID_TOPIC AND lt.ID_MEMBER=$ID_MEMBER)
  95.                LEFT JOIN {$db_prefix}log_mark_read AS lmr ON (lmr.ID_BOARD=t.ID_BOARD AND lmr.ID_MEMBER=$ID_MEMBER)
  96.                LEFT JOIN {$db_prefix}messages AS m ON (m.ID_TOPIC=t.ID_TOPIC)
  97.                WHERE (t.ID_TOPIC = $threadid)
  98.                GROUP BY t.ID_TOPIC", false);
  99.            
  100.             list($ltLastRead, $numMessages, $newestMessage) = $dbrq->fetch_row();
  101.            
  102.             if ($dbrq->num_rows == 0)
  103.                 return $app->errors->abort($app->locale->txt[106], $app->locale->txt[472]);
  104.            
  105.             $dbrq = $db->query("
  106.                SELECT COUNT(*)
  107.                FROM {$db_prefix}messages
  108.                WHERE ID_TOPIC = $threadid
  109.                AND posterTime <= $ltLastRead", false);
  110.            
  111.             list($numReadMessages) = $dbrq->fetch_row();
  112.             $numUnreadMessages = $numMessages - $numReadMessages;
  113.            
  114.             if ($app->conf->viewNewestFirst)
  115.                 $Page2Show = floor(($numUnreadMessages == 0 ? 0 : $numUnreadMessages - 1) / $app->conf->maxmessagedisplay) * $app->conf->maxmessagedisplay;
  116.             else
  117.                 $Page2Show = floor(($numReadMessages  == $numMessages ? $numReadMessages - 1 : $numReadMessages) / $app->conf->maxmessagedisplay) * $app->conf->maxmessagedisplay;
  118.            
  119.             if ($numUnreadMessages > 0)
  120.             {
  121.                 $dbrq = $db->query("
  122.                    SELECT MIN(ID_MSG)
  123.                    FROM {$db_prefix}messages
  124.                    WHERE ID_TOPIC = $threadid
  125.                    AND posterTime > $ltLastRead");
  126.                 list($firstUnreadMessage) = $dbrq->fetch_row();
  127.                 $newMsgID = "#msg$firstUnreadMessage";
  128.             }
  129.             elseif ($app->conf->viewNewestFirst)
  130.                 $newMsgID = "#msg$newestMessage";
  131.             else
  132.                 $newMsgID = '#lastPost';
  133.            
  134.             if (!$app->user->guest)
  135.             {
  136.                 // mark board as seen if we came using notification
  137.                 $db->query("
  138.                    REPLACE INTO {$db->db_prefix}log_boards (logTime, ID_MEMBER, ID_BOARD)
  139.                    VALUES (" . time() . ", $ID_MEMBER, $currentboard)", false);
  140.             }
  141.             return $service->redirect("/b$currentboard/t$threadid/$Page2Show/$newMsgID");
  142.         } // if start = new
  143.         elseif (substr($start, 0, 3) == 'msg')
  144.         {
  145.             $msg = (int) substr($start, 3);
  146.             $dbrq = $db->query("SELECT COUNT(*) FROM {$db_prefix}messages WHERE (ID_MSG < $msg && ID_TOPIC=$threadid)", false);
  147.             list($start) = $dbrq->fetch_row();
  148.         }
  149.        
  150.         // do the previous next stuff
  151.         // Create a previous next string if the selected theme has it
  152.         // as a selected option
  153.         $previousNext = $app->conf->enablePreviousNext ? '<a href="' . SITE_ROOT . "/b$currentboard/t$threadid/prev/\">{$app->conf->PreviousNext_back}</a> <a href=\"" . SITE_ROOT . "/b$currentboard/t$threadid/prev/\">{$app->conf->PreviousNext_forward}</a>" : '';
  154.        
  155.         // Load membrgroups.
  156.         $service->membergroups = $app->user->memberGroups();
  157.        
  158.         // get all the topic info
  159.         $dbrq = $db->query("
  160.            SELECT t.numReplies, t.numViews, t.locked, ms.subject, t.isSticky, ms.posterName, ms.ID_MEMBER, t.ID_POLL, t.ID_MEMBER_STARTED, tr.POSITIVE AS topicPosRating, tr.NEGATIVE AS topicNegRating
  161.            FROM {$db_prefix}topics as t
  162.            JOIN {$db_prefix}messages as ms ON (t.ID_FIRST_MSG = ms.ID_MSG)
  163.            LEFT JOIN {$db_prefix}topic_ratings AS tr ON (t.ID_TOPIC = tr.TOPIC_ID)
  164.            WHERE t.ID_BOARD = $currentboard
  165.                AND t.ID_TOPIC = $threadid
  166.                AND ms.ID_MSG = t.ID_FIRST_MSG", false);
  167.  
  168.         if ($dbrq->num_rows == 0) {
  169.             return $this->findBoard($currentboard, $threadid);
  170.         }
  171.        
  172.         $topicinfo = $dbrq->fetch_assoc();
  173.        
  174.         // read topic rating
  175.         $service->topicPosRating = !isset($topicinfo['topicPosRating']) ? 0 : $topicinfo['topicPosRating'];
  176.         $service->topicNegRating = !isset($topicinfo['topicNegRating']) ? 0 : $topicinfo['topicNegRating'];
  177.        
  178.         if (!$app->user->guest)
  179.         {
  180.             // mark the topic as read :)
  181.             $db->query("
  182.                REPLACE INTO {$db->db_prefix}log_topics (logTime, ID_MEMBER, ID_TOPIC, notificationSent,unreadComments,otherComments,subscribedComments)
  183.                VALUES (" . time() . ", $ID_MEMBER, $threadid, 0,0,0,0)", false);
  184.            
  185.             $referer = $SERVER->get('HTTP_REFERER');
  186.             // mark board as seen if we came using last post link from BoardIndex
  187.             //if (isset($boardseen))
  188.             if ($referer == "{$service->siteurl}/") {
  189.                 // if came from main page
  190.                 $db->query("
  191.                    REPLACE INTO {$db->db_prefix}log_boards (logTime, ID_MEMBER, ID_BOARD)
  192.                    VALUES (" . time() . ", $ID_MEMBER, $currentboard)", false);
  193.             }
  194.            
  195.             // Add 1 to the number of views of this thread.
  196.             $db->query("
  197.                UPDATE {$db->db_prefix}topics
  198.                SET numViews = numViews + 1
  199.                WHERE ID_TOPIC = $threadid");
  200.         }
  201.        
  202.         // Check to make sure this thread isn't locked.
  203.         $noposting = $topicinfo['locked'];
  204.         $mreplies = $topicinfo['numReplies'];
  205.         $mstate = $topicinfo['locked'];
  206.         $msubthread = $topicinfo['subject'];
  207.         $yytitle = str_replace("\$", "&#36;", $topicinfo['subject']);
  208.        
  209.         // Get the class of this thread, based on lock status and number of replies.
  210.         $threadclass = '';
  211.         if ($mstate == 1 || $mstate == 2)
  212.             $threadclass = 'locked';
  213.         elseif ($mreplies > 24)
  214.             $threadclass = 'veryhotthread';
  215.         elseif ($mreplies > 14)
  216.             $threadclass = 'hotthread';
  217.         elseif ($mstate == 0)
  218.             $threadclass = 'thread';
  219.        
  220.         if ($app->conf->enableStickyTopics && $topicinfo['isSticky'] == 1)
  221.             $threadclass = 'sticky';
  222.        
  223.         if (($mstate == 1 || $mstate == 2) && ($app->conf->enableStickyTopics && $topicinfo['isSticky'] == '1'))
  224.             $threadclass = 'lockedsticky';
  225.  
  226.         $service->msubthread = $app->subs->CensorTxt($msubthread);
  227.         $service->title = $app->subs->CensorTxt($yytitle);
  228.         $service->mstate = $mstate;
  229.         $service->threadclass = $threadclass;
  230.        
  231.         // Build a list of this board's moderators.
  232.         $showmods = '';     // create an empty string
  233.         $tmp = array();     // used to temporarily store the list
  234.        
  235.         if (sizeof($service->board_moderators) > 0)
  236.         {
  237.             if (sizeof($service->board_moderators) == 1)    // if only one mod - use a different string
  238.                 $showmods = "({$app->locale->txt[298]}: ";
  239.             else
  240.                 $showmods = "({$app->locale->txt[299]}: ";
  241.            
  242.             foreach ($service->board_moderators as $modername => $moderinfo)
  243.             {
  244.                 $euser = urlencode($modername);
  245.                 $tmp[] = '<a href="' . SITE_ROOT . '/people/' . $euser . '/"><acronym title="' . $app->locale->txt[62] . '">' . $service->esc($moderinfo['realName']) . '</acronym></a>';
  246.             }
  247.  
  248.             $showmods .= implode(", ", $tmp) . ')'; // stitch the list together
  249.         }
  250.        
  251.         $service->showmods = $showmods;
  252.        
  253.         $service->jumptoform = $this->prepareJumptoForm($currentboard);
  254.        
  255.         // Build the page links list.
  256.         $max = $mreplies + 1;
  257.         $start = (($start > $max) ? $max : $start);
  258.         $start = (floor($start / $app->conf->maxmessagedisplay)) * $app->conf->maxmessagedisplay;
  259.        
  260.         $service->start = $start;
  261.        
  262.         $maxmessagedisplay = ($start === 'all' ? $mreplies + 1 : $app->conf->maxmessagedisplay);
  263.         error_log("__DEBUG__: STARTNUM: $start, $maxmessagedisplay,". $app->conf->maxmessagedisplay);
  264.         if ($app->conf->compactTopicPagesEnable == 0)
  265.         {
  266.             $tmpa = $start - $maxmessagedisplay;
  267.             $pageindex = (($start == 0) ? '' : '<a href="' . SITE_ROOT . "/b$currentboard/t$threadid/$tmpa/\">&#171;</a>");
  268.             $tmpa = 1;
  269.             for ($counter = 0; $counter < $max; $counter += $maxmessagedisplay)
  270.             {
  271.                 $pageindex .= (($start == $counter) ? ' <b>' . $tmpa . '</b>' : ' <a href="' . SITE_ROOT . "/b$currentboard/t$threadid/$counter/\">$tmpa</a>");
  272.                 $tmpa++;
  273.             }
  274.             $tmpa = $start + $maxmessagedisplay;
  275.             $tmpa = ($tmpa > $mreplies ? $mreplies : $tmpa);
  276.             if ($start != $counter-$maxmessagedisplay)
  277.                 $pageindex .= (($tmpa > $counter - $maxmessagedisplay) ? ' ' : ' <a href="' . SITE_ROOT . "/b$currentboard/t$threadid/$tmpa/\">&#187;</a> ");
  278.         }
  279.         else
  280.         {
  281.             $pageindex = '';
  282.             if (($app->conf->compactTopicPagesContiguous % 2) == 1)    //1,3,5,...
  283.                 $PageContiguous = (int)(($app->conf->compactTopicPagesContiguous - 1) / 2);
  284.             else
  285.                 $PageContiguous = (int)($app->conf->compactTopicPagesContiguous / 2);  //invalid value, but let's deal with it
  286.            
  287.             if ($start > $maxmessagedisplay * $PageContiguous)  // first
  288.                 $pageindex.= '<a class="navPages" href="' . SITE_ROOT . "/b$currentboard/t$threadid/\">1</a> ";
  289.            
  290.             if ($start > $maxmessagedisplay * ($PageContiguous + 1))  // ...
  291.                 $pageindex.= '<b> ... </b>';
  292.            
  293.             for ($nCont=$PageContiguous; $nCont >= 1; $nCont--)  // 1 & 2 before
  294.                 if ($start >= $maxmessagedisplay * $nCont)
  295.                 {
  296.                     $tmpStart = $start - $maxmessagedisplay * $nCont;
  297.                     $tmpPage = $tmpStart / $maxmessagedisplay + 1;
  298.                     if ($app->conf->viewNewestFirst)
  299.                         $tmpStart = floor($max / $maxmessagedisplay) * $maxmessagedisplay - $tmpStart;
  300.                     $pageindex .= '<a class="navPages" href="' . SITE_ROOT . "/b$currentboard/t$threadid/$tmpStart/\">$tmpPage</a> ";
  301.                 }
  302.            
  303.             $tmpPage = $start / $maxmessagedisplay + 1;  // page to show
  304.             $pageindex .= ' <span class="pageindex-bracket">[</span><b class="pageindex-current">' . $tmpPage . '</b><span class="pageindex-bracket">]</span> ';
  305.  
  306.             $tmpMaxPages = (int)(($max - 1) / $maxmessagedisplay) * $maxmessagedisplay;  // 1 & 2 after
  307.             for ($nCont=1; $nCont <= $PageContiguous; $nCont++)
  308.             {
  309.                 if ($start + $maxmessagedisplay * $nCont <= $tmpMaxPages)
  310.                 {
  311.                     $tmpStart = $start + $maxmessagedisplay * $nCont;
  312.                     $tmpPage = $tmpStart / $maxmessagedisplay + 1;
  313.                     if ($app->conf->viewNewestFirst)
  314.                         $tmpStart = floor($max / $maxmessagedisplay) * $maxmessagedisplay - $tmpStart;
  315.                         $pageindex .= '<a class="navPages" href="' . SITE_ROOT . "/b$currentboard/t$threadid/$tmpStart/\">$tmpPage</a> ";
  316.                 }
  317.             }
  318.                
  319.             if ($start + $maxmessagedisplay * ($PageContiguous + 1) < $tmpMaxPages) // ...
  320.                 $pageindex .= '<b> ... </b>';
  321.            
  322.             if ($start + $maxmessagedisplay * $PageContiguous < $tmpMaxPages)   //  last
  323.             {
  324.                 $tmpPage = $tmpMaxPages / $maxmessagedisplay + 1;
  325.                 $pageindex .= '<a class="navPages" href="' . SITE_ROOT . "/b$currentboard/t$threadid/$tmpMaxPages/\">$tmpPage</a> ";
  326.             }
  327.         } // building pageindex
  328.         error_log("__DEBUG__: STARTNUM: $start, $maxmessagedisplay");
  329.         // view all mod
  330.         if ($maxmessagedisplay < $mreplies)
  331.             $pageindex .= '<a class="navPages" href="' . SITE_ROOT . "/b$currentboard/t$threadid/all/\">{$app->locale->txt[190]}</a> ";
  332.        
  333.         $service->pageindex = $pageindex;
  334.        
  335.         //topics locked by a user should get the same icon as topics locked by a moderator
  336.         $topicinfo['locked'] = ($topicinfo['locked'] == 2 ? 1 : $topicinfo['locked']);
  337.        
  338.         $service->topicinfo = $topicinfo;
  339.        
  340.         //chatWall mod by dig7er
  341.         if ($app->conf->boardBillsEnabled)
  342.         {
  343.             $dbrq = $db->query("SELECT chatWall, chatWallMsgAuthor FROM {$db->db_prefix}boards WHERE ID_BOARD = $currentboard;");
  344.             $row = $dbrq->fetch_assoc();
  345.             $row['chatWall'] = $service->unicodeentities($row['chatWall']);
  346.            
  347.             $dbrq = $db->query("SELECT billboard, billboardAuthor, realName, gender FROM {$db_prefix}topics AS t LEFT JOIN {$db_prefix}members AS m ON (t.billboardAuthor = m.memberName) WHERE ID_TOPIC = $threadid;");
  348.             $row2 = $dbrq->fetch_assoc();
  349.             $row['topicBillboard'] = stripslashes($row2['billboard']);
  350.             $row['topicBillboardAuthor'] = $row2['billboardAuthor'];
  351.             $row['topicBillboardAuthorName'] = $row2['realName'];
  352.             $row['topicBillboardAuthorGender'] = $row2['gender'];
  353.             $service->billboard = $row;
  354.         }
  355.        
  356.         $service->showTopicBillboard = !empty($row['topicBillboard']);
  357.         $service->showTopicRating = false;  //$ID_MEMBER != -1;
  358.        
  359.         if ($topicinfo['ID_POLL'] != '-1' && $app->conf->pollMode)
  360.         {
  361.             $dbrq = $db->query("
  362.                SELECT question, votingLocked, votedMemberIDs, option1, option2, option3, option4, option5, option6, option7, option8, option9, option10, option11, option12, option13, option14, option15, option16, option17, option18, option19, option20, votes1, votes2, votes3, votes4, votes5, votes6, votes7, votes8, votes9, votes10, votes11, votes12, votes13, votes14, votes15, votes16, votes17, votes18, votes19, votes20
  363.                FROM {$db_prefix}polls
  364.                WHERE ID_POLL = '$topicinfo[ID_POLL]'
  365.                LIMIT 1", false);
  366.            
  367.             $pollinfo = $dbrq->fetch_assoc();
  368.             $pollinfo['image'] = ($pollinfo['votingLocked'] != '0' )?'locked_poll':'poll';
  369.            
  370.             $pollinfo['totalvotes'] = 0;
  371.            
  372.             for ($i=0; $i<20; $i++) {
  373.               $pollinfo['totalvotes'] += $pollinfo["votes$i"];
  374.             }
  375.             $pollinfo['divisor'] = (($pollinfo['totalvotes'] == 0) ? 1 : $pollinfo['totalvotes']);
  376.                        
  377.             $service->pollinfo = $pollinfo;
  378.         }
  379.        
  380.         # Load background color list.
  381.        $bgcolors = array($app->conf->color['windowbg'], $app->conf->color['windowbg2']);
  382.         $bgcolornum = sizeof($bgcolors);
  383.         $cssvalues = array('windowbg', 'windowbg2');
  384.         $cssnum = sizeof($bgcolors);
  385.        
  386.         if ($app->conf->MenuType == 0)
  387.             $sm = 1;
  388.        
  389.         $counter = $start;
  390.    
  391.         # For each post in this thread
  392.        $dbrq = $db->query("
  393.            SELECT ID_MSG
  394.            FROM {$db_prefix}messages
  395.            WHERE ID_TOPIC=$threadid
  396.            ORDER BY ID_MSG " . ($app->conf->viewNewestFirst ? 'DESC' : '') . "
  397.            LIMIT $start,$maxmessagedisplay");
  398.  
  399.         $messages = array();
  400.        
  401.         while ($row = $dbrq->fetch_assoc())
  402.             $messages[] = $row['ID_MSG'];
  403.        
  404.         if (count($messages))
  405.             $dbrq = $db->query("
  406.                SELECT m.ID_MSG, m.subject, m.posterName, m.posterEmail, m.posterTime, m.ID_MEMBER, m.icon, m.posterIP, m.body, m.smiliesEnabled, m.modifiedTime, m.modifiedName, m.attachmentFilename, m.attachmentSize, m.nowListening, m.multinick, IFNULL(mem.realName, m.posterName) AS posterDisplayName, IFNULL(lo.logTime, 0) AS isOnline, m.comments, mem.blockComments POST_COMMENTS_BLOCKED, m.closeComments CLOSED_COMMENTS, m.agent, qpolls.POLL_TITLE, cs.notify
  407.                FROM {$db->db_prefix}messages AS m
  408.                LEFT JOIN {$db->db_prefix}members AS mem ON (mem.ID_MEMBER=m.ID_MEMBER)
  409.                LEFT JOIN {$db->db_prefix}log_online AS lo ON (lo.identity=mem.ID_MEMBER)
  410.                LEFT JOIN {$db->db_prefix}quickpolls AS qpolls ON (m.ID_MSG = qpolls.ID_MSG)
  411.                LEFT JOIN {$db->db_prefix}comment_subscriptions AS cs ON (m.ID_MSG = cs.messageID AND cs.memberID = {$ID_MEMBER})
  412.                WHERE m.ID_MSG IN (" . implode(',', $messages) . ")
  413.                ORDER BY ID_MSG " . ($app->conf->viewNewestFirst ? 'DESC' : ''), false);
  414.        
  415.         $messages = array();
  416.        
  417.         while ($message = $dbrq->fetch_array())
  418.         {
  419.             if ($app->conf->hard_ignore && $app->user->inIgnore($message['posterName'])) {
  420.                 // Skip ignored
  421.                 continue;
  422.             }
  423.            
  424.             $msgID = $message['ID_MSG'];
  425.            
  426.             if (!empty($message['POLL_TITLE']))
  427.             {
  428.                 $message['quickpoll'] = array();
  429.                 $message['quickpoll']['title'] = $message['POLL_TITLE'];
  430.                 $message['quickpoll']['voters'] = array();
  431.                 $message['quickpoll']['voters']['yes'] = array();
  432.                 $message['quickpoll']['voters']['no'] = array();
  433.                 $message['quickpoll']['voters']['neutral'] = array();
  434.                
  435.                 $req = $db->query("SELECT qvotes.POLL_OPTION, qvotes.MEMBER_NAME, m.memberName, m.realName FROM {$db_prefix}quickpoll_votes AS qvotes LEFT JOIN {$db_prefix}members AS m ON (qvotes.ID_USER = m.ID_MEMBER) WHERE qvotes.ID_MSG = $msgID", false);
  436.                
  437.                 while ($vote = $req->fetch_assoc())
  438.                 {
  439.                     if (!empty($vote['memberName']))
  440.                         $voter = array($vote['memberName'], $vote['realName']);
  441.                    else
  442.                         $voter = $vote['MEMBER_NAME'];
  443.                    
  444.                    if ($vote['POLL_OPTION'] == "yes")
  445.                        $message['quickpoll']['voters']['yes'][] = $voter;
  446.                    else if ($vote['POLL_OPTION'] == "no")
  447.                        $message['quickpoll']['voters']['no'][] = $voter;
  448.                    else if ($vote['POLL_OPTION'] == "neutral")
  449.                        $message['quickpoll']['voters']['neutral'][] = $voter;
  450.                 }
  451.             }
  452.            
  453.             if ($msgID == 1068850)
  454.                 $message['ID_MSG'] = -1;
  455.            
  456.             $message['windowbg'] = $bgcolors[($counter % $bgcolornum)];
  457.             $message['css'] = $cssvalues[($counter % $cssnum)];
  458.            
  459.             # Should we show "last modified by?"
  460.            if ($app->conf->showmodify && !empty($message['modifiedTime']) && !empty($message['modifiedName']))
  461.             {
  462.                 $message['lastmodified'] = true;
  463.             }
  464.            
  465.             $message['subject'] = (isset($message['subject']) ? $message['subject'] : $app->locale->txt[24]);
  466.            
  467.             $message['posterIP'] = ($app->user->accessLevel() > 2 ? $message['posterIP'] : $app->locale->txt[511]);
  468.            
  469.             $message['guest'] = true;
  470.            
  471.             if ($message['ID_MEMBER'] != -1)
  472.             {
  473.                 # If user is not in memory, s/he must be loaded.
  474.                $userset = $app->user->loadDisplay($message['posterName']);
  475.                 if($userset['found'])
  476.                 {
  477.                     $message['userset'] = $userset;
  478.                     $message['guest'] = false;
  479.                    
  480.                     if($app->conf->check_avatar_size)
  481.                     {
  482.                         preg_match("/\<img src\=\"(\S+)\"/", $userset['avatar'], $matches);
  483.                         if (remote_file_size($matches[1]) > 30720)
  484.                         $message['avatar'] = "Размер аватара превышает 30 Кб";
  485.                     }
  486.                     else
  487.                         $message['avatar'] = $userset['avatar'];
  488.                    
  489.                 }
  490.             }
  491.            
  492.             if ($app->user->inIgnore($message['posterName']))
  493.                     $message['body'] = $app->locale->ignore_user1;
  494.             else
  495.                 $message['body'] = $app->subs->CensorTxt($message['body']);
  496.            
  497.             $message['subject'] = $app->subs->CensorTxt($message['subject']);
  498.             $message['counter'] = $counter;
  499.            
  500.             // add watch-karma-modifiers link
  501.             if (false)
  502.             {
  503.                 $message['karmaModifiers'] = array();
  504.                 $namesQuery = $db->query("SELECT k.user1, m.realName, k.action FROM {$db_prefix}karmawatch as k LEFT JOIN {$db_prefix}members as m ON (k.user1 = m.memberName) WHERE k.ID_MSG = {$message['ID_MSG']}", false);
  505.                 if ($namesQuery->num_rows > 0)
  506.                 {
  507.                     while( $row = $namesQuery->fetch_assoc() )
  508.                     {
  509.                         $message['karmaModifiers'][] = $row;
  510.                     }
  511.                 }
  512.             }
  513.            
  514.             // Preparing for  LJ sharing buttons
  515.             $ljMessage = (strlen($message['body']) > 512) ? substr($message['body'], 0, 512) . "..." : $message['body'];
  516.             $message['LJSubject'] = mb_convert_encoding($message['subject'], "UTF-8", "CP1251");
  517.             $shareMessage = $ljMessage . '<br><br>Источник: <a href="' . $service->siteurl . '/' .$msgID.'" target="_blank">forum.theprodigy.ru/'.$msgID.'</a>';
  518.             $message['LJMessage'] = mb_convert_encoding($shareMessage, "UTF-8", "CP1251");
  519.            
  520.             // Blog Mod
  521.             if($service->isBlog)
  522.             {
  523.                 $requestBlog = $db->query("SELECT m.ID_MEMBER_LAST_COMMENT, m.numComments, IFNULL(lbc.logTime, 0) AS logTime,
  524.                        bc.postedTime AS lastPosterTime, bc.posterName, IFNULL(mem.realName, bc.posterName) AS displayName
  525.                    FROM {$db_prefix}messages AS m, {$db_prefix}blog_comments AS bc
  526.                    LEFT JOIN {$db->db_prefix}log_blog_comments AS lbc ON (lbc.ID_MSG=m.ID_MSG AND lbc.ID_MEMBER=$ID_MEMBER)
  527.                    LEFT JOIN {$db->db_prefix}members AS mem ON (mem.ID_MEMBER = m.ID_MEMBER_LAST_COMMENT)
  528.                    WHERE m.ID_MSG=$msgID
  529.                    AND m.ID_LAST_COMMENT=bc.ID_COMMENT LIMIT 1;", false);
  530.                 $messsage['blog'] = $requestBlog->fetch_assoc();
  531.             }
  532.            
  533.            
  534.             // Karma
  535.             $karmaQuery = $db->query("SELECT karmaGood, karmaBad, karmaGoodExecutors, karmaBadExecutors FROM `messages` WHERE ID_MSG = {$msgID} LIMIT 1;");
  536.             $karma = $karmaQuery->fetch_array();
  537.             if ($karma)
  538.             {
  539.                 $karma['actions'] = false;
  540.                
  541.                 $KarmaGoodIDs = explode(",", $karma['karmaGoodExecutors']);
  542.                 $KarmaBadIDs = explode(",", $karma['karmaBadExecutors']);
  543.                
  544.                 if (($app->user->group == 'Administrator') or (($app->user->posts >= $app->conf->karmaMinPosts) && ($app->user->name != 'Guest') && ($message['ID_MEMBER'] != $app->user->id) && !(in_array($app->user->id, $KarmaGoodIDs)) && !(in_array($app->user->id, $KarmaBadIDs))))
  545.                     $karma['actions'] = true;
  546.                
  547.                 $karma['css'] = ($karma['karmaGood'] > 0 or $karma['karmaBad'] > 0) ? 'table-row' : 'none';
  548.  
  549.                 $message['karma'] = $karma;
  550.             }
  551.            
  552.             $message['attachment'] = false;
  553.             // attachments
  554.             if ($app->conf->attachmentShowImages && $app->conf->attachmentEnable && !empty($message['attachmentFilename']))
  555.             {
  556.                 $message['attachment'] = true;
  557.                 $message['attachmentExtension'] = strtolower(substr(strrchr($message['attachmentFilename'], '.'), 1));
  558.                 if (in_array($message['attachmentExtension'], $service->imageTypes))
  559.                     $message['attachmentType'] = 'image';
  560.                 elseif (in_array($message['attachmentExtension'], $service->audioTypes))
  561.                 {
  562.                     $message['attachmentType'] = 'audio';
  563.                     $app->conf->mediaplayer = true;
  564.                 }
  565.                 elseif (in_array($message['attachmentExtension'], $service->videoTypes))
  566.                 {
  567.                     $message['attachmentType'] = 'video';
  568.                     $app->conf->mediaplayer = true;
  569.                 }
  570.                 else
  571.                     $message['attachmentType'] = null;
  572.             } // attachments
  573.            
  574.             if (stripos($message['body'], '[/audio]') !== false || stripos($message['body'], '[/video]') !== false || stripos($message['comments'], '[/audio]') !== false)
  575.             {
  576.                 // message contains audio/video player,
  577.                 // we should include media player js and css code in the footer
  578.                 $app->conf->mediaplayer = true;
  579.             }
  580.  
  581.             $message['cmnt_display'] = $message['CLOSED_COMMENTS'] == 1 ? 'none' : 'inline';
  582.             $message['comments'] = $app->comments->prepare($message['comments'], $message['posterName'], $message['notify']);
  583.                        
  584.             $message['agent'] = explode(' #|# ', $message['agent']);
  585.            
  586.             $messages[$message['ID_MSG']] = $message;
  587.             $counter ++;
  588.         } // while messages from DB
  589.        
  590.         $service->messages = $messages;
  591.        
  592.         $service->allow_locking = false;
  593.         if ($app->user->accessLevel() > 1 || ($app->user->name == $topicinfo['posterName'] && $app->user->name != 'Guest' && $app->conf->enableUserTopicLocking))
  594.             $service->allow_locking = true;
  595.        
  596.         //topics locked by a user should get the same icon as topics locked by a moderator.
  597.         $service->img_locked_thread = ($topicinfo['locked'] == 2 ? 'lockthread1' : 'lockthread'.$topicinfo['locked']);
  598.        
  599.         $service->calendar_enabled = false;
  600.         if ($app->conf->cal_enabled && ($app->user->accessLevel() > 1 || ($app->user->name == $topicinfo['posterName'] && $app->user-name != 'Guest')))
  601.         {
  602.             if ($app->calendar->CanPost())
  603.                 $service->calendar_enabled = true;
  604.         }
  605.        
  606.         if($currentboard == 16)
  607.         {
  608.             $app->locale->applause = 'плюс пицот';
  609.             $app->locale->smite = 'иди нах';
  610.             $app->locale->applauses = 'плюспицотов';
  611.             $app->locale->smites = 'идинахов';
  612.         }
  613.         else
  614.         {
  615.             $app->locale->applause = 'поощрить';
  616.             $app->locale->smite = 'покарать';
  617.             $app->locale->applauses = 'поощрений';
  618.             $app->locale->smites = 'покараний';
  619.         }
  620.        
  621.         if($app->conf->QuickReply && $app->user->QuickReply && (!$mstate || $app->user->accessLevel() > 1))
  622.             $service->quickReplyForm = true;
  623.         else
  624.             $service->quickReplyForm = false;
  625.        
  626.         if($app->conf->QuickReplyExtended && $app->user->accessLevel() > 1)
  627.             $service->quickReplyExtendedForm = true;
  628.         else
  629.             $service->quickReplyExtendedForm = false;
  630.        
  631.         $service->boardviewers = $this->getBoardViewersList($currentboard);
  632.            
  633.         $this->render('templates/thread/thread.template.php');
  634.        
  635.     } // Display()
  636.    
  637.     public function findBoard($prevboard, $threadid) {
  638.         $dbrq = $this->app->db->query(
  639.             "SELECT ID_BOARD FROM {$this->app->db->prefix}topics AS board WHERE ID_TOPIC = $threadid", false
  640.         );
  641.         if ($dbrq->num_rows == 0)
  642.             $this->app->errors->abort($this->app->locale->txt[106], $this->app->locale->txt[472]);
  643.         else {
  644.             list($board) = $dbrq->fetch_row();
  645.            
  646.             $request_uri = $this->request->uri();
  647.             $new_uri = str_replace("/b$prevboard/", "/b$board/", $request_uri);
  648.            
  649.            
  650.             $this->app->errors->log("__DEBUG__: redirecting to $new_uri.");
  651.             return $this->service->redirect($new_uri);
  652.         }
  653.     } // findBoard()
  654.    
  655.     public function reply($request, $response, $service, $app)
  656.     {
  657.         $GET = $request->paramsGet();
  658.         $SERVER = $request->server();
  659.         $COOKIE = $request->cookies();
  660.         $POST = $request->paramsPost();
  661.         $namedParams = $request->paramsNamed();
  662.         $service->board = $namedParams->get('board');
  663.         $service->thread = $namedParams->get('thread');
  664.         $service->quotemsg = $namedParams->get('quotemsg');
  665.        
  666.         if(!isset($service->action))
  667.             $service->action = 'reply';
  668.        
  669.         $service->cValue=(((date('YmdH')%113)*107)%113)+113;
  670.        
  671.         if ($app->user->name == 'Guest')
  672.         {
  673.             if ($app->conf->enable_guestposting)
  674.             {
  675.                 // show confirm dialog if not confirmed before
  676.                 if (!$app->session->get('guestRulesConfirmed', false) && intval($POST->get('cconfirm')) != $service->cValue)
  677.                     return $this->render('templates/thread/confirm.template.php');
  678.                 // remember confirmation
  679.                 if ($POST->get('cconfirm') == $service->cValue) {
  680.                     $app->session->check('post');
  681.                     $app->session->store('guestRulesConfirmed', true);
  682.                 }
  683.             }
  684.             else
  685.             {
  686.                 // guest posting disabled, show error
  687.                 return $this->error($app->locale->txt[165]);
  688.             }
  689.         }
  690.        
  691.         if ($POST->get('naztem') != null) {
  692.             // A post was submitted
  693.             return $this->postReply($request, $response, $service, $app);
  694.         }
  695.        
  696.         if ($GET->get('linkcalendar') != null)
  697.         {
  698.             $app->calendar->ValidatePost();
  699.         }
  700.        
  701.         $threadinfo = array('locked' => 0, 'ID_MEMBER_STARTED'=>'-1');
  702.         $mstate = 0;
  703.        
  704.         $db_prefix = $app->db->prefix;
  705.        
  706.         //check for blog board
  707.         $blogmod_groups = explode(',', $app->conf->blogmod_groups);
  708.         $requestBlog = $app->db->query("SELECT ID_BOARD FROM {$db_prefix}boards WHERE ID_BOARD={$service->board} AND isBlog=1", false);
  709.         $isBlog = ($requestBlog->num_rows > 0) ? true : false;
  710.         $requestBlog = $app->db->query("SELECT posts FROM {$db_prefix}members WHERE ID_MEMBER={$app->user->id}", false);
  711.         $post_count = $requestBlog->fetch_row();
  712.        
  713.         //check posting permission
  714.         if ($isBlog && $app->user->accessLevel() < 2)
  715.         {
  716.         //check for new topic post
  717.             if ($service->thread == '')
  718.             {
  719.                 //if postcount not enough and membergroup isn't allowed, show error message
  720.                 if ( ($post_count[0] < $app->conf->blogmod_minpost) && ($app->conf->blogmod_groups == '' || ($app->conf->blogmod_groups != '' && !in_array($app->user->group, $blogmod_groups))) )
  721.                     return $app->errors->abort('', $app->locale->blogmod11);
  722.                 $requestBlog = $app->db->query("SELECT COUNT(*) FROM {$db_prefix}topics WHERE ID_BOARD={$service->board} AND ID_MEMBER_STARTED={$app->user->id}", false);
  723.                 $blog_total = $requestBlog->fetch_row();
  724.                 if ($blog_total[0] >= $app->conf->blogmod_maxblogsperuser)
  725.                     return $app->errors->abort('', $app->locale->blogmod12);
  726.             }
  727.             //check for post reply
  728.             else
  729.             {
  730.                 $requestBlog = $app->db->query("SELECT ID_TOPIC FROM {$db_prefix}topics WHERE ID_BOARD={$service->board} AND ID_MEMBER_STARTED={$app->user->id}", false);
  731.                 if ($requestBlog->num_rows == 0)
  732.                     return $this->error($app->locale->blogmod13);
  733.             }
  734.         }
  735.        
  736.         if ($service->thread != '')
  737.         {
  738.             $dbrq = $app->db->query("SELECT * FROM {$db_prefix}topics WHERE ID_TOPIC={$service->thread}");
  739.             $threadinfo = $dbrq->fetch_array();
  740.             $mstate = $threadinfo['locked'];
  741.         }
  742.         else if ($service->action != 'newthread')
  743.             return $app->errors->abort('', $app->locale->txt[472] . ' Error ' . $service->action);
  744.        
  745.         if ($threadinfo['locked'] != 0 && $app->user->accessLevel() < 2)  // don't allow a post if it's locked
  746.             return $app->errors->abort('', $app->locale->txt[90]);
  747.        
  748.         # Determine what category we are in.
  749.        $dbrq = $app->db->query("
  750.            SELECT b.ID_BOARD as bid, b.name as bname, c.ID_CAT as cid, c.memberGroups, c.name as cname, b.isAnnouncement
  751.            FROM {$db_prefix}boards as b, {$db_prefix}categories as c
  752.            WHERE (b.ID_BOARD = {$service->board}
  753.                AND b.ID_CAT=c.ID_CAT)", false);
  754.         if ($dbrq->num_rows == 0)
  755.             return $app->errors->abort('', $app->locale->yse232);
  756.         $bcinfo = $dbrq->fetch_array();
  757.         $service->cat = $bcinfo['cid'];
  758.         $service->catname = $bcinfo['cname'];
  759.         $service->board = $bcinfo['bid'];
  760.         $service->boardname = $bcinfo['bname'];
  761.        
  762.         if ($bcinfo['isAnnouncement'] && $service->thread == '' && $app->user->accessLevel() < 2)
  763.             return $app->errors->abort('', $app->locale->announcement1);
  764.        
  765.         $memgroups = explode(',', $bcinfo['memberGroups']);
  766.         if (!(in_array($app->user->group, $memgroups) || $memgroups[0] == null || $app->user->accessLevel() > 2))
  767.             return $app->errors->abort('', $app->locale->txt[1]);
  768.        
  769.         if ($service->action == 'newthread')
  770.             $service->title = $app->locale->txt[33];
  771.         elseif ($service->action == 'reply')
  772.             $service->title = $app->locale->txt[25];
  773.        
  774.         $service->msubject = $service->mname = $service->memail = $service->mdate = $service->musername = $service->micon = $service->mip = $service->mmessage = $service->mns = $service->mid = '';
  775.         $service->form_message = '';
  776.         $service->form_subject = '';
  777.        
  778.         if ($service->thread != '' && $service->quotemsg != '')
  779.         {
  780.             $app->session->check('get');
  781.            
  782.             $dbrq = $app->db->query("
  783.                SELECT m.subject, m.posterName, m.posterEmail, m.posterTime, m.icon, m.posterIP, m.body, m.smiliesEnabled, m.ID_MEMBER, m.comments
  784.                FROM {$db_prefix}messages as m, {$db_prefix}topics as t, {$db_prefix}boards as b, {$db_prefix}categories as c
  785.                WHERE (m.ID_MSG = {$service->quotemsg}
  786.                    AND m.ID_TOPIC = t.ID_TOPIC
  787.                    AND t.ID_BOARD = b.ID_BOARD
  788.                    AND b.ID_CAT = c.ID_CAT
  789.                    AND (FIND_IN_SET('{$app->user->group}', c.memberGroups) != 0 || c.memberGroups = '' || '{$app->user->group}' LIKE 'Administrator' || '{$app->user->group}' LIKE 'Global Moderator')
  790.                )", false);
  791.  
  792.             list($service->msubject, $service->mname, $service->memail, $service->mdate, $service->micon, $service->mip, $service->mmessage, $service->mns, $service->mi, $service->mcomments) = $dbrq->fetch_row();
  793.            
  794.             if ($service->mi != '-1')
  795.             {
  796.                 $dbrq = $app->db->query("
  797.                    SELECT realName
  798.                    FROM {$db_prefix}members
  799.                    WHERE ID_MEMBER='{$service->mi}'
  800.                    LIMIT 1", false);
  801.                 if ($request->num_rows != 0)
  802.                     list($service->mname) = $dbrq->fetch_row();
  803.             }
  804.            
  805.             $service->form_message = $service->un_html_entities(preg_replace("|<br( /)?[>]|","\n",$service->mmessage));
  806.             $service->form_message = $app->subs->CensorTxt($service->form_message);
  807.            
  808.             if ($app->conf->removeNestedQuotes)
  809.             {
  810.                 $service->form_message = preg_replace("-\n*\[quote([^\\]]*)\]((.|\n)*?)\[/quote\]([\n]*)-", "\n", $service->form_message);
  811.                 $service->form_message = preg_replace("/\n*\[\/quote\]\n*/", "\n", $service->form_message);
  812.             }
  813.            
  814.             $service->form_message = "[quote author={$service->mname} msg={$service->quotemsg} date={$service->mdate}]\n{$service->form_message}\n[/quote]\n";
  815.            
  816.             if (!empty($service->postcommentquote))
  817.             {
  818.                 $csvdata = explode("\r\n", $mcomments);
  819.                 $csvline = $csvdata[$service->postcommentquote-1];
  820.                 $postComment = explode("#;#", $csvline);
  821.    
  822.                 $service->form_message = "[quote author={$postComment[0]} msg={$service->quotemsg}-{$service->postcommentquote} date={$postComment[2]}]\n{$service->form_message}\n\n" . stripslashes($postComment[3]) . "\n[/quote]\n";
  823.             }
  824.        
  825.              // Replace embedded media with links
  826.             $find_tags = array(
  827.                 "/\[url\=.*?\]\[img\]/si",
  828.                 "/\[\/img\]\[\/url\]/si",
  829.                 "/\[img.*?\]/si",
  830.                 "/\[\/img\]/si",
  831.                 "/\[media.*?\]/si",
  832.                 "/\[\/media\]/si",
  833.                 "/\[youtube.*?\]/si",
  834.                 "/\[\/youtube\]/si",
  835.                 "/\[y\](.+?)\[\/y\]/si",
  836.                 "/(?<=^|\s)(https?:\/\/youtu.be\/.+?)(?=\s|$)/",
  837.                 "/(?<=^|\s)(https?:\/\/www.youtube.com\/watch\?.+?)(?=\s|$)/"
  838.             );
  839.             $replacement_tags = array(
  840.                 "[url class=img]",
  841.                 "[/url]",
  842.                 "[url class=img]",
  843.                 "[/url]", "[url]",
  844.                 "[/url]",
  845.                 "[url class=img]",
  846.                 "[/url]",
  847.                 "[url class=img]\\1[/url]",
  848.                 "[url class=img]\\1[/url]",
  849.                 "[url class=img]\\1[/url]"
  850.             );
  851.             $service->form_message = preg_replace($find_tags, $replacement_tags, $service->form_message);
  852.            
  853.             $service->form_subject = $app->subs->CensorTxt($service->msubject);
  854.            
  855.             if (!stristr(substr($service->msubject, 0, 3), 're:'))
  856.                 $service->form_subject = '' . $service->form_subject;
  857.            
  858.             if (!empty($service->quickreplyquote))
  859.                 return $this->ajax(str_replace(array('&quot;', '&lt;', '&gt;'), array('"', '<', '>'), $service->form_message), 'txt');
  860.         }
  861.         else if ($service->thread != '' && $service->quotemsg == '')
  862.         {
  863.             $dbrq = $app->db->query("SELECT subject, posterName, posterEmail, posterTime, icon, posterIP, body, smiliesEnabled, ID_MEMBER
  864.                FROM {$db_prefix}messages
  865.                WHERE ID_TOPIC={$service->thread}
  866.                ORDER BY ID_MSG
  867.                LIMIT 1", false);
  868.            
  869.             list($service->msubject, $service->mname, $service->memail, $service->mdate, $service->micon, $service->mip, $service->mmessage, $service->mns, $service->mi) = $dbrq->fetch_row();
  870.  
  871.             $service->form_subject = $app->subs->CensorTxt($service->msubject);
  872.            
  873.             if (!stristr(substr($service->msubject, 0, 3),'re:'))
  874.                 $service->form_subject = '' . $service->form_subject;
  875.         }
  876.        
  877.         if (!$service->form_subject)
  878.             $service->sub = '<i>' . $service->esc($app->locale->txt[33]) . '</i>';
  879.         else
  880.             $service->sub = $service->esc($service->form_subject);
  881.        
  882.         if ($isBlog)
  883.             $service->form_subject = '';
  884.        
  885.         $service->guestname = $COOKIE->get('guestname', '');
  886.         $service->guestemail = $COOKIE->get('guestemail', '');
  887.        
  888.         if ($app->conf->attachmentEnable)
  889.             $service->attachment_fields = true;
  890.        
  891.         if ($app->user->name == 'Guest' && $app->conf->attachmentEnableGuest == 0)
  892.             $service->attachment_fields = false;
  893.        
  894.         if (!(in_array($app->user->group, explode(',', trim($app->conf->attachmentMemberGroups))) || $app->user->accessLevel() > 2))
  895.             $service->attachment_fields = false;
  896.        
  897.         $service->ses_id = $app->session->id;
  898.        
  899.         if ($service->thread > 0)
  900.             $service->thread_summary = $this->thread_summary($service->thread);
  901.        
  902.         $this->render('templates/thread/reply.template.php');
  903.     } // reply()
  904.    
  905.     public function thread_summary($thread) {
  906.         // how many messages to show
  907.         $limitString = ($this->app->conf->topicSummaryPosts < 0) ? '' : (' LIMIT ' . (!is_numeric($this->app->conf->topicSummaryPosts) ? '0' : $this->app->conf->topicSummaryPosts));
  908.        
  909.         $db_prefix = $this->app->db->prefix;
  910.         $usergroup = $this->app->user->group;
  911.         $dbrq = $this->app->db->query("
  912.            SELECT m.posterName, m.posterTime, m.body, m.smiliesEnabled
  913.            FROM {$db_prefix}messages AS m, {$db_prefix}topics as t, {$db_prefix}boards as b, {$db_prefix}categories as c
  914.            WHERE m.ID_TOPIC='$thread'
  915.                AND t.ID_TOPIC=m.ID_TOPIC
  916.                AND b.ID_BOARD=t.ID_BOARD
  917.                AND c.ID_CAT=b.ID_CAT
  918.                AND (FIND_IN_SET('$usergroup', c.memberGroups) != 0 OR c.memberGroups = '' OR '$usergroup' LIKE 'Administrator' OR '$usergroup' LIKE 'Global Moderator')
  919.            ORDER BY ID_MSG DESC
  920.            $limitString", false);
  921.        
  922.         $messages = array();
  923.         while($row = $dbrq->fetch_assoc()) {
  924.             if ($this->app->user->inIgnore($row['posterName']))
  925.                 continue;
  926.            
  927.             $messages[] = array(
  928.                 'userinfo' => $this->app->user->loadDisplay($row['posterName']),
  929.                 'time' => $this->app->subs->timeformat($row['posterTime']),
  930.                 'body' => $this->app->subs->CensorTxt($row['body']),
  931.                 'smilies' => $row['smiliesEnabled']
  932.             );
  933.         }
  934.        
  935.         return $messages;
  936.     } // thread_summary()
  937.    
  938.     public function postReply($request, $response, $service, $app)
  939.     {
  940.         $app->session->check('post');
  941.         $POST = $request->paramsPost();
  942.         $PARAMS = $request->paramsNamed();
  943.         $COOKIES = $request->cookies();
  944.         $SERVER = $request->server();
  945.         $REMOTE_ADDR = $SERVER->get('REMOTE_ADDR');
  946.        
  947.         $input_waction = $POST->get('waction');
  948.         $input_name = $POST->get('name');
  949.         $input_message = $POST->get('message');
  950.         $input_serial = $POST->get('serial');
  951.         $input_subject = $POST->get('naztem');
  952.         $input_lock = $POST->get('lock');
  953.         $input_ns = $POST->get('ns');
  954.        
  955.         $service->thread = $PARAMS->get('thread');
  956.        
  957.         $mreplies = 0;
  958.  
  959.         $app->board->load($PARAMS->get('board'));
  960.        
  961.         if ($app->user->posts < 100 && $app->security->isTOR()){
  962.             $app->im->notifyAdmins("предотвращён постинг через TOR", "Пользователь: {$service->siteurl}/people/" . urlencode($username) . '/');
  963.             return $app->errors->abort('', "Вам запрещено отвечать в этом разделе Форума!");
  964.         }
  965.        
  966.         if ($app->security->containsBannedNickPart($app->user->realname))
  967.         {
  968.             $app->im->notifyAdminsLater("Nick contains banned parts", var_export($_SERVER, true));
  969.             return $app->errors->abort('', 'Ошибка размещения сообщения.');
  970.         }
  971.        
  972.         $waction = $POST->get('waction');
  973.        
  974.         if ($waction == 'preview')
  975.             return $this->preview($request, $response, $service, $app);
  976.        
  977.         if ($app->security->containsForbiddenText($input_message))
  978.             return $app->errors->abort('', "Вам запрещено отвечать на Форуме! Обратитесь к администраторам за разъяснением!");
  979.        
  980.         if ($input_serial != $app->conf->serial)
  981.         {
  982.             $app->im->notifyAdminsLater("Возможный спам: " . $input_subject, "Введён неверный серийный номер:\r\n" . $input_message . "\r\n" . $input_name . ", " . $app->user->realname . " (" . $app->user->username . "), $REMOTE_ADDR\r\n" . $request->uri());
  983.             return $this->error("Неверный серийный ключ! Обратитесь к администратору за разъяснением!");
  984.         }
  985.        
  986.         if ($POST->get('linkcalendar') != null)
  987.         {
  988.             $app->calendar->ValidatePost();
  989.         }
  990.        
  991.         if ($app->user->name == 'Guest' && $app->conf->enable_guestposting == 0)
  992.             return $this->error($txt[165]);
  993.        
  994.         $db = $app->db;
  995.         $db_prefix = $app->db->prefix;
  996.        
  997.         if ($service->thread != '' && $app->user->accessLevel() < 2)
  998.         {
  999.             $dbrq = $app->db->query("
  1000.                SELECT locked
  1001.                FROM {$db_prefix}topics
  1002.                WHERE ID_TOPIC={$service->thread}", false);
  1003.             list($tmplocked) = $dbrq->fetch_array();
  1004.             if ($tmplocked != 0)
  1005.                 return $this->error($txt[90]); // don't allow a post if it's locked
  1006.         }
  1007.        
  1008.         if (empty($service->thread))
  1009.             $dbrq = $app->db->query("
  1010.                SELECT b.ID_BOARD
  1011.                FROM {$db_prefix}boards AS b, {$db_prefix}categories AS c
  1012.                WHERE b.ID_BOARD={$service->board}
  1013.                AND c.ID_CAT=b.ID_CAT
  1014.                AND (FIND_IN_SET('{$app->user->group}', c.memberGroups) != 0 OR c.memberGroups = '' OR '{$app->user->group}' LIKE 'Administrator' OR '{$app->user->group}' LIKE 'Global Moderator')", false);
  1015.         else
  1016.             $dbrq = $app->db->query("
  1017.                SELECT t.ID_TOPIC
  1018.                FROM {$db_prefix}topics AS t, {$db_prefix}boards AS b, {$db_prefix}categories AS c
  1019.                WHERE t.ID_TOPIC={$service->thread}
  1020.                AND b.ID_BOARD={$service->board}
  1021.                AND b.ID_BOARD=t.ID_BOARD
  1022.                AND c.ID_CAT=b.ID_CAT
  1023.                AND (FIND_IN_SET('{$app->user->group}', c.memberGroups) != 0 OR c.memberGroups = '' OR '{$app->user->group}' LIKE 'Administrator' OR '{$app->user->group}' LIKE 'Global Moderator')", false);
  1024.        
  1025.         if ($dbrq->num_rows == 0)
  1026.             return $this->error($txt[1]);
  1027.        
  1028.         // If poster is a Guest then evaluate the legality of name and email
  1029.         if ($app->user->name == 'Guest')
  1030.         {
  1031.             //now make sure that guestname is not containing banned nicknames
  1032.             if ($app->security->containsBannedNickPart($input_name))
  1033.                 return $this->error("Вам не разрешено отвечать на форуме! Обратитесь к администраторам за разъяснением!");
  1034.            
  1035.             $input_name = trim($input_name);
  1036.            
  1037.             $service->validate($input_name, $app->locale->txt[75])->isAlnum();
  1038.             $service->validate($input_name, $app->locale->txt[568])->isLen(1, 25);
  1039.            
  1040.             if ($input_name == '_')
  1041.                 return $this->error($txt[75]);
  1042.            
  1043.             if (empty($input_email))
  1044.                 return $this->error($txt[76]);
  1045.  
  1046.             $service->validate($input_email, $app->locale->txt[243])->isRegex("/^[0-9A-Za-z@\._\-]+$/");
  1047.         }
  1048.        
  1049.         // did they toggle lock topic after post?
  1050.         $locked = ($app->user->accessLevel() > 1 && $input_lock == 'on')? 1 : 0 ;
  1051.         $isLocked = ($locked ? ', locked=1' : '');
  1052.        
  1053.         $input_subject = trim($input_subject);
  1054.         $input_message = trim($input_message);
  1055.        
  1056.         if(empty($input_subject))
  1057.             return $this->error($app->locale->txt[77]);
  1058.         if($input_subject == ' ')
  1059.             return $this->error($app->locale->txt[77]);
  1060.         if(empty($input_message))
  1061.             return $this->error($app->locale->txt[78]);
  1062.         $service->validate($input_message, $app->locale->txt[499])->isLen(1, $app->conf->MaxMessLen);
  1063.        
  1064.         if ($app->user->guest && !$app->session->get('guestRulesConfirmed', false))
  1065.         { // FIXME
  1066.             //notifyAdminsLater("Попытка взлома на форуме", "Скрипт Sources/Post.php\r\n".(var_export($_SERVER, true))."\r\n\r\n".var_export($_REQUEST, true));
  1067.             //return $this->error("Попытка спама! Твой IP сохранён.");
  1068.             return $this->error($app->locale->txt['yse304']);
  1069.         }
  1070.        
  1071.         $app->security->spam_protection();
  1072.        
  1073.         if (strlen($input_subject) > 80)
  1074.         {
  1075.             $input_subject = substr($input_subject, 0, 80);
  1076.             if (substr($input_subject, -1) == '\\')
  1077.                 $input_subject = substr($input_subject, 0, 79);
  1078.         }
  1079.        
  1080.         if ($app->user->name != 'Guest') // If not guest, get name and email.
  1081.         {
  1082.             $input_name = $app->user->name;
  1083.             $input_email = $app->user->email;
  1084.         }
  1085.        
  1086.         // Preparse code (zef)
  1087.         $input_message = $app->subs->preparsecode($input_message);
  1088.        
  1089.         $e_name = $app->db->escape_string($input_name);
  1090.        
  1091.         if ($app->user->guest)
  1092.         {
  1093.             # If user is Guest, then make sure the chosen name
  1094.            # is not reserved or used by a member.
  1095.            
  1096.             $dbrq = $app->db->query("
  1097.                ELECT ID_MEMBER
  1098.                FROM {$db_prefix}members
  1099.                WHERE (memberName='$e_name' || realName='$e_name')", false);
  1100.            
  1101.             if ($dbrq->num_rows != 0)
  1102.                 $this->error(473);
  1103.            
  1104.             //now make sure that guestname is not containing banned nicknames
  1105.             if ($app->security->containsBannedNickPart($input_name))
  1106.                 return $this->error("Вам не разрешено отвечать на форуме! Обратитесь к администраторам за разъяснением!");
  1107.            
  1108.             // now make sure they arn't trying to use a reserved name
  1109.             $dbrq = $app->db->query("
  1110.                SELECT *
  1111.                FROM {$db_prefix}reserved_names
  1112.                ORDER BY setting", false);
  1113.            
  1114.             $matchword = $matchcase = $matchuser = $matchname = '';
  1115.  
  1116.             for ($i = 0; $i < 4; $i++)
  1117.             {
  1118.                 $tmp = $dbrq->fetch_row();
  1119.                 ${$tmp[0]}=$tmp[1];
  1120.             }
  1121.            
  1122.             $namecheck = $matchcase ? $name : strtolower ($name);
  1123.            
  1124.             while ($tmp = $dbrq->fetch_row())
  1125.             {
  1126.                 if ($tmp[0] == 'word')
  1127.                 {
  1128.                     $reserved = $tmp[1];
  1129.                     $reservecheck = $matchcase ? $reserved : strtolower ($reserved);
  1130.                     if ($matchname)
  1131.                     {
  1132.                         if ($matchword)
  1133.                         {
  1134.                             if ($namecheck == $reservecheck)
  1135.                                 return $this->error("{$app->locale->txt[244]} $reserved");
  1136.                         }
  1137.                         else
  1138.                         {
  1139.                             if (strstr($namecheck, $reservecheck))
  1140.                                 return $this->error("{$app->locale->txt[244]} $reserved");
  1141.                         }
  1142.                     }
  1143.                 }
  1144.             }
  1145.         } // if guest
  1146.        
  1147.         // multinick check mod (by dig7er, 14 May 2008)
  1148.         $rname = !empty($app->user->realname) ? $app->user->realname : $input_name;
  1149.        
  1150.         // fix names in cookies -> make them hashed
  1151.         $notHashNameFound = false;
  1152.         $cookie_nicks = $COOKIES->get('nicks');
  1153.         if (is_array($cookie_nicks))
  1154.         {    
  1155.             foreach ($cookie_nicks as $nname => $nvalue)
  1156.             {
  1157.                 if (!is_int($nname) or abs($nname) < 1000)
  1158.                 {
  1159.                     $notHashNameFound = true;
  1160.                     break;
  1161.                 }
  1162.             }
  1163.         }
  1164.        
  1165.         if ($notHashNameFound)
  1166.         {
  1167.             $pattern = "/^\-?[0-9]+$/si";
  1168.             if (is_array($cookie_nicks))
  1169.             {
  1170.                 foreach ($cookie_nicks as $nick => $value)
  1171.                 {
  1172.                     if (preg_match($pattern, $nick, $matches) == 0)
  1173.                         $response->cookie("nicks[$nick]", null);
  1174.                     unset($cookie_nicks[$nick]);
  1175.                 }
  1176.                 $response->cookie("nicks", null);
  1177.                 //unset($cookie_nicks);
  1178.                 $cookie_nicks = null;
  1179.                 unset($app->session->userInfo);
  1180.             }
  1181.         } // if $NotHashNameFound
  1182.        
  1183.         $value = $app->user->guest ? "$rname (Гость)" : '<a href="'.SITE_ROOT.'/people/'.urlencode($app->user->name).'/">'.$service->esc($rname).'</a>';
  1184.         $value .= ", ".date("d-m-Y H:i:s"). ", $REMOTE_ADDR, <a href=\"" . SITE_ROOT . '/b' . $service->board . '/t' . $service->thread . '/">тема</a>';
  1185.         if (is_array($cookie_nicks))
  1186.         {
  1187.             if ($app->user->guest and !in_array(crc32($rname), array_keys($cookie_nicks)) and sizeof($cookie_nicks) >= 2)
  1188.             {
  1189.                 $app->in->notifyAdminsLater("Возможный мультиник", print_r($cookie_nicks, true) . "\r\n\r\n" . $rname . ", $REMOTE_ADDR");
  1190.                 return $this->error("Ты уже использовал другой ник для ответа на форуме. Пожалуйста, используй его и далее. С вопросами обращайся на <a href=\"mailto:dig7er@gmail.com\">dig7er@gmail.com</a>");
  1191.             }
  1192.         }
  1193.        
  1194.         if (isset($app->session->userInfo) and ($app->session->userInfo['name'] != $rname or $app->session->userInfo['username'] != $app->user->name))
  1195.         {
  1196.             if ($app->user->guest and !in_array(crc32($rname), array_keys($app->session->userInfo['nicks'])) and sizeof($app->session->userInfo['nicks']) >= 2)
  1197.             {
  1198.                 $app->im->notifyAdminsLater("Possible multinick", $rname . " ({$app->user->name}), $REMOTE_ADDR, ".$SERVER->get('HTTP_USER_AGENT')."\r\n\r\nЗаблокирован: ".((!in_array($rname, array_keys($app->session->userInfo['nicks'])) and sizeof($app->session->userInfo['nicks']) >= 2)?"ДА":"НЕТ")."\r\n\r\n<".SITE_ROOT."/b{$service->board}/t{$service->thread}/>\r\n\r\n" . print_r($app->session->userInfo, true) . "\r\n\r\n" . print_r($_SERVER, true) . "\r\n\r\n" . print_r($cookie_nicks, true));
  1199.                 return $this->error("Ты уже использовал другой ник для ответа на форуме. Пожалуйста, используй его и далее. С вопросами обращайся на <a href=\"mailto:dig7er@gmail.com\">dig7er@gmail.com</a>");
  1200.             }
  1201.        
  1202.             // combine cookie and session nicks arrays
  1203.             $nicks = $app->session->userInfo['nicks'];
  1204.             if (is_array($cookie_nicks))
  1205.             {
  1206.                 foreach ($cookie_nicks as $key => $value)
  1207.                     $nicks[$key] = $value;
  1208.             }
  1209.            
  1210.             // update cookie for each nick
  1211.             foreach ($nicks as $nick => $v)
  1212.             {
  1213.                 $response->cookie("nicks[$nick]", stripslashes($v), time()+60*60*24*14);
  1214.                 $cookie_nicks[$nick] = stripslashes($v);
  1215.             }
  1216.         }
  1217.        
  1218.         if ($app->user->guest)
  1219.         {
  1220.             $response->cookie("guestname", $rname, time()+60*60*24*14);
  1221.             $response->cookie("guestemail", $input_email, time()+60*60*24*14);
  1222.         }
  1223.        
  1224.         $response->cookie("nicks[".crc32($rname)."]", $value, time()+60*60*24*14);
  1225.         $cookie_nicks[crc32($rname)] = $value;
  1226.        
  1227.         $app->session->userInfo = array(
  1228.             'name' => $rname,
  1229.             'username' => $app->user->name,
  1230.             'IP' => $REMOTE_ADDR,
  1231.             'browser' => $SERVER->get('HTTP_USER_AGENT'),
  1232.             'nicks' => $cookie_nicks
  1233.         );
  1234.        
  1235.         $multinick = "";
  1236.         if (is_array($cookie_nicks)){
  1237.             foreach ($cookie_nicks as $v)
  1238.             $multinick .= "$v<br />";
  1239.         }
  1240.        
  1241.         // Store client IP behind the proxy if available
  1242.         if ($SERVER->get('HTTP_X_FORWARDED_FOR') !== null || $SERVER->get('HTTP_CLIENT_IP') !== null)
  1243.         {
  1244.             $FWD = array();
  1245.             $multinick .= 'X_Forwarded_For: ';
  1246.             if ($SERVER->get('HTTP_X_FORWARDED_FOR') !== null)
  1247.                 $FWD[] = $SERVER->get('HTTP_X_FORWARDED_FOR');
  1248.             if ($SERVER->get('HTTP_CLIENT_IP') !== null)
  1249.                 $FWD[] = $SERVER->get('HTTP_CLIENT_IP');
  1250.             $multinick .= implode(', ', $FWD) . '<br />';
  1251.         }
  1252.        
  1253.         // Validate the attachment if there is one
  1254.        
  1255.         $FILES = $request->files();
  1256.         // replace as much special characters as possible and remove all other characters
  1257.         $attachment = $FILES->get('attachment');
  1258.         if ($attachment !== null)
  1259.         {
  1260.             $attachment['name'] = preg_replace(
  1261.                 array("/\s/", "/[дегвба]/", "/[ДЕБВАГ]/", "/[цтуфхшр]/", "/[ЦШФТФХ]/", "/[йикл]/", "/[ЙКЛИ]/", "/ [ыьщъ]/", "/[ЬЫЪЩ]/", "/[помн]/", "/[НОП]/", "/[з]/", "/[с]/",  "/[С]/", "/[^\w_.-]/"),
  1262.                 array('_', 'a', 'A', 'o', 'O', 'e', 'E', 'u', 'U', 'i', 'I', 'c', 'n', 'N', ''),
  1263.                 $attachment['name']);
  1264.             $FILES->set('attachment', $attachment);
  1265.            
  1266.             if ($attachment['name'] != '' && $app->conf->attachmentEnable > 0 && ($app->conf->attachmentMemberGroups == "" || in_array($app->user->group, explode(',', trim($app->conf->attachmentMemberGroups))) || $app->user->accessLevel() > 2))
  1267.             {
  1268.                 if ($attachment['size'] > $app->conf->attachmentSizeLimit * 1024)
  1269.                     return $this->error("{$app->locale->txt['yse122']} {$app->conf->attachmentSizeLimit} {$app->locale->txt['yse211']}.");
  1270.                
  1271.                 if ($app->conf->attachmentCheckExtensions == '1')
  1272.                     if (!in_array(strtolower(substr(strrchr($attachment['name'], '.'), 1)), explode(',', strtolower($app->conf->attachmentExtensions))))
  1273.                     {
  1274.                         $failed = $attachment['name'];
  1275.                         return $this->error("$failed.<br />{$app->locale->txt['yse123']} {$app->conf->attachmentExtensions}.");
  1276.                     }
  1277.                
  1278.                 // make sure they aren't trying to upload a nasty file
  1279.                 $disabledFiles = array('CON','COM1','COM2','COM3','COM4','PRN','AUX','LPT1');
  1280.                 if (in_array(strtoupper(substr(strrchr($attachment['name'], '.'), 1)), $disabledFiles))
  1281.                 {
  1282.                     $failed = $attachment['name'];
  1283.                     return $this->error("$failed.<br />{$app->locale->txt['yse130b']}.");
  1284.                 }
  1285.                
  1286.                 if (file_exists($app->conf->attachmentUploadDir . "/" . $attachment['name']))
  1287.                     return $this->error('yse125');
  1288.                
  1289.                 $dirSize = '0';
  1290.                 $dir = opendir($app->conf->attachmentUploadDir);
  1291.                 while ($file = readdir($dir))
  1292.                     $dirSize = $dirSize + filesize($app->conf->attachmentUploadDir . '/' . $file);
  1293.                
  1294.                 if ($attachment['size'] + $dirSize > $app->conf->attachmentDirSizeLimit * 1024)
  1295.                     return $this->error('yse126');
  1296.                
  1297.                 $parts = ($attachment !== null) ? preg_split("~(\\|/)~", $_FILES['attachment']['name']) : array();
  1298.                 $destName = array_pop($parts);
  1299.                
  1300.                 if (!move_uploaded_file($attachment['tmp_name'], $app->conf->attachmentUploadDir . '/' . $destName))
  1301.                     return $this->error("yse124");
  1302.                 $attachment_size = $attachment['size'];
  1303.                
  1304.                 chmod ("{$app->conf->attachmentUploadDir}/$destName",0644) || $chmod_failed = 1;
  1305.             }
  1306.             else
  1307.             {
  1308.                 $attachment['name'] = 'NULL';
  1309.                 $attachment_size = 0;
  1310.             }
  1311.         } // if attachment not null
  1312.        
  1313.         // If no thread specified, this is a new thread.
  1314.         // Find a valid random ID for it.
  1315.         $newtopic = ($service->thread == '') ? true : false;
  1316.         $time = time();
  1317.         $se = ($input_ns ? 0 : 1);
  1318.        
  1319.         $agent_fp = array();
  1320.         $agent_fp[] = $SERVER->get('HTTP_USER_AGENT');
  1321.         $agent_fp[] = ($POST->get('tfp') === null) ? 'none' : $POST->get('tfp');
  1322.         $agent_fp[] = ($POST->get('bfp') === null) ? 'none' : $POST->get('bfp');
  1323.         $agent_fp = implode(' #|# ', $agent_fp);
  1324.        
  1325.         $naztem = $db->escape_string($input_subject);
  1326.         $message = $db->escape_string($input_message);
  1327.         $nowListening = $db->escape_string($POST->get('nowListening'));
  1328.         $agent_fp = $db->escape_string($agent_fp);
  1329.         $multinick = $db->escape_string($multinick);
  1330.         $e_email = $db->escape_string($input_email);
  1331.         $icon = $db->escape_string($POST->get('icon'));
  1332.         $quickPollTitle = $POST->get('quickPoll');
  1333.         $quickPollTitle = $db->escape_string($quickPollTitle);
  1334.                
  1335.         // Guest Rules Confirmation mod, by dig7er
  1336.         $app->session->store('guestRulesConfirmed', true);
  1337.        
  1338.         if ($newtopic)        // This is a new topic. Save it.
  1339.         {
  1340.             if ($app->board->isAnnouncement() && $app->user->accessLevel() < 2)
  1341.                 return $this->error('announcement1');
  1342.            
  1343.             $tmpname = ($attachment['name'] == 'NULL') ? 'NULL' : "'" . $db->escape_string($attachment['name']) . "'";
  1344.             $dbrq = $db->query("
  1345.                INSERT INTO {$db_prefix}messages (ID_MEMBER, subject, posterName, posterEmail, posterTime, posterIP, smiliesEnabled, body, icon, attachmentSize, attachmentFilename, nowListening, multinick, closeComments, agent)
  1346.                VALUES ({$app->user->id}, '$naztem', '$e_name', '$e_email', $time, '$REMOTE_ADDR', $se, '$message', '$icon', '$attachment_size', $tmpname, '$nowListening', '$multinick', ".($app->user->guest?0:$app->user->closeCommentsByDefault).", '$agent_fp')", false);
  1347.                
  1348.             $ID_MSG = $db->insert_id;
  1349.             if ($ID_MSG > 0)
  1350.             {
  1351.                 $dbrq = $db->query("
  1352.                    INSERT INTO {$db_prefix}topics (ID_BOARD, ID_MEMBER_STARTED, ID_MEMBER_UPDATED, ID_FIRST_MSG, ID_LAST_MSG, locked, numViews)
  1353.                    VALUES ({$service->board}, {$app->user->id}, {$app->user->id}, $ID_MSG, $ID_MSG, $locked, 0)", false);
  1354.                
  1355.                 if ($db->insert_id > 0)
  1356.                 {
  1357.                     $threadid = $db->insert_id;
  1358.                     $dbrq = $db->query("
  1359.                        UPDATE {$db_prefix}messages
  1360.                        SET ID_TOPIC = $threadid
  1361.                        WHERE (ID_MSG = $ID_MSG)", false);
  1362.                    
  1363.                     $dbrq = $db->query("
  1364.                        UPDATE {$db_prefix}boards
  1365.                        SET numPosts = numPosts + 1, numTopics = numTopics + 1
  1366.                        WHERE (ID_BOARD = {$service->board})", false);
  1367.                    
  1368.                     $mreplies = 0;
  1369.                    
  1370.                     if ($app->conf->trackStats)
  1371.                     {
  1372.                         $date = getdate(time() + $app->conf->timeoffset * 3600);
  1373.                         $statsquery = $db->query("
  1374.                            UPDATE {$db_prefix}log_activity
  1375.                            SET topics = topics + 1, posts = posts + 1
  1376.                            WHERE month = {$date['mon']}
  1377.                            AND day = {$date['mday']}
  1378.                            AND year = {$date['year']}", false);
  1379.                        
  1380.                         if ($db->affected_rows == 0)
  1381.                         $statsquery = $db->query("
  1382.                            INSERT INTO {$db_prefix}log_activity
  1383.                            (month, day, year, topics, posts)
  1384.                            VALUES ($date[mon], $date[mday], $date[year], 1, 1)", false);
  1385.                     }
  1386.                    
  1387.                     if ($POST->get('linkcalendar') !== null)
  1388.                         $app->calendarInsertEvent($service->board, $threadid, $POST->get('evtitle'), $app->user->id, $POST->get('month'), $POST->get('day'), $POST->get('year'), $POST->get('span'));
  1389.                    
  1390.                     if ($app->board->isAnnouncement())
  1391.                     {
  1392.                         $reqAnn = $db->query("
  1393.                            SELECT b.notifyAnnouncements
  1394.                            FROM {$db_prefix}boards as b, {$db_prefix}categories as c
  1395.                            WHERE (b.ID_BOARD = {$service->board}
  1396.                            AND b.ID_CAT = c.ID_CAT)", false);
  1397.                        
  1398.                         $rowAnn = $reqAnn->fetch_array();
  1399.                        
  1400.                         if ($rowAnn['notifyAnnouncements'])
  1401.                             $this->NotifyUsersNewAnnouncement();
  1402.                     }
  1403.                    
  1404.                     $app->subs->updateStats('topic');
  1405.                     $app->subs->updateStats('message');
  1406.                     $app->subs->UpdateLastMessage($service->board);
  1407.                 }
  1408.                
  1409.                 // quick poll mod by dig7er, 14.04.2010
  1410.                 if ($quickPollTitle !== null)
  1411.                 {
  1412.                     $request = $db->query("REPLACE INTO {$db_prefix}quickpolls
  1413.                        (ID_MSG, POLL_TITLE)
  1414.                        VALUES ($ID_MSG, '$quickPollTitle')", false);
  1415.                 }
  1416.             } // $ID_MSG > 0
  1417.         } // if $newtopic
  1418.         else
  1419.         {    // This is an old thread. Save it.
  1420.             // QuickReplyExtended
  1421.             if($app->conf->QuickReply && $app->conf->QuickReplyExtended && $app->user->accessLevel() > 1)
  1422.             {
  1423.                 $csubject = $POST->get('csubject');
  1424.                 if(strlen($csubject) >= 3)
  1425.                 {
  1426.                     $naztem = $db->escape_string($csubject);
  1427.                     $changesubject = $db->query("UPDATE {$db_prefix}messages SET subject='{$naztem}' WHERE ID_TOPIC='{$service->thread}'");
  1428.                 }
  1429.                 $modaction = $POST->get('modaction');
  1430.                 if($modaction != 1)
  1431.                 {
  1432.                     if($modaction == 2)
  1433.                     {
  1434.                         $dbrq = $db->query("
  1435.                            SELECT locked
  1436.                            FROM {$db_prefix}topics
  1437.                            WHERE ID_TOPIC={$service->threadid}", false);
  1438.                         $row = $dbrq->fetch_row();
  1439.                        
  1440.                         $quicklock = ($row[0] != 0) ? 0 : 1;
  1441.                         $dbrq = $db->query("UPDATE {$db_prefix}topics SET locked='{$quicklock}' WHERE ID_TOPIC='{$threadid}'");
  1442.                     }
  1443.                     elseif($modaction == 3)
  1444.                     {
  1445.                         $dbrq = $db->query("
  1446.                            SELECT isSticky
  1447.                            FROM {$db_prefix}topics
  1448.                            WHERE ID_TOPIC={$service->thread}", false);
  1449.                         $row = $dbrq->fetch_row();
  1450.                        
  1451.                         $quicksticky = ($row[0] != 0) ? 0 : 1;
  1452.                         $dbrq = $db->query("UPDATE {$db_prefix}topics SET isSticky='{$quicksticky}' WHERE ID_TOPIC='{$service->thread}'", false);
  1453.                     }
  1454.                     elseif($modaction == 4)
  1455.                     {
  1456.                         $dbrq = $db->query("
  1457.                            SELECT locked,isSticky
  1458.                            FROM {$db_prefix}topics
  1459.                            WHERE ID_TOPIC=$threadid") or database_error(__FILE__, __LINE__, $db);
  1460.                         $row = $dbrq->fetch_row();
  1461.                        
  1462.                         $quicklock = ($row[0] != 0) ? 0 : 1;
  1463.                         $quicksticky = ($row[1] != 0) ? 0 : 1;
  1464.                         $dbrq = $db->query("
  1465.                            UPDATE {$db_prefix}topics SET locked='{$quicklock}',isSticky='{$quicksticky}' WHERE ID_TOPIC='{$service->thread}'", false);
  1466.                     }
  1467.                 }
  1468.                
  1469.                 $movethread = $POST->get('movethread');
  1470.                 if ($movethread != '' && substr($movethread, 0, 1) != '#' && $movethread != $service->board)
  1471.                 {
  1472.                     $dbrq = $db->query("
  1473.                        SELECT numReplies,ID_BOARD FROM {$db_prefix}topics WHERE ID_TOPIC='{$service->thread}'", false);
  1474.                     $row = $dbrq->fetch_row();
  1475.                     $numReplies = $row[0]+1;
  1476.                     $boardid = $row[1];
  1477.                     $updateboards = $db->query("
  1478.                        UPDATE {$db_prefix}boards SET numPosts=numPosts-'{$numReplies}',numTopics=numTopics-1 WHERE ID_BOARD='{$boardid}'");
  1479.                     $newboard = $db->escape_string($movethread);
  1480.                     $updateboards2 = $db->query("
  1481.                        UPDATE {$db_prefix}boards SET numPosts=numPosts+'{$numReplies}',numTopics=numTopics+1 WHERE ID_BOARD='{$newboard}'", false);
  1482.                     $movethread = $db->query("
  1483.                        UPDATE {$db_prefix}topics SET ID_BOARD='{$newboard}' WHERE ID_TOPIC='{$service->thread}'", false);
  1484.                    
  1485.                     $app->subs->updateStats('topic');
  1486.                     $app->subs->updateStats('message');
  1487.                     $app->subs->updateLastMessage($board);
  1488.                     $app->subs->updateLastMessage($newboard);
  1489.                    
  1490.                     $db->query("
  1491.                         UPDATE {$db_prefix}calendar SET id_board='$newboard' WHERE id_topic='{$service->thread}'", false);
  1492.                    
  1493.                     $service->board = $newboard;
  1494.                 }
  1495.             }
  1496.            
  1497.             // QuickReplyExtended
  1498.             $tmpname = ($attachment['name'] == 'NULL') ? 'NULL' : "'" . $db->escape_string($attachment['name']) . "'";
  1499.             //--- Unite two posts if they're last in the topic and made by the same user (by Dig7er)
  1500.             $um = false;
  1501.             // don't unite messages if we upload an attachment
  1502.             if ($attachment['name'] == 'NULL')
  1503.             {
  1504.                 $query = $db->query("SELECT * FROM `messages` WHERE ID_TOPIC = {$service->thread} ORDER BY ID_MSG DESC LIMIT 1");
  1505.                 $lastPost = $query->fetch_array();
  1506.                 // return $this->error($lastPost['ID_MEMBER'].' '.$app->user->id);
  1507.                 $lineBreak = "\n\n";
  1508.                 if ($lastPost['ID_MEMBER'] == $app->user->id && $lastPost['posterIP'] == $REMOTE_ADDR && (strlen($lastPost['body']) + strlen($message))<65356 && ((time() - $lastPost['posterTime']) < 600))
  1509.                 {
  1510.                     $lastMsgEditQuery = $db->query("UPDATE `messages` SET body = CONCAT(body, \"$lineBreak\", \"$message\") WHERE ID_MSG = {$lastPost['ID_MSG']}", false);
  1511.                     $ID_MSG = $lastPost['ID_MSG'];
  1512.                     $um = true;
  1513.                 }
  1514.             }
  1515.             if (!$um)
  1516.             {
  1517.                 // if not uniting messages
  1518.                 $app->user->closeCommentsByDefault = empty($app->user->closeCommentsByDefault) ? 0 : $app->user->closeCommentsByDefault;
  1519.                 $dbrq = $db->query("
  1520.                    INSERT INTO {$db_prefix}messages (ID_TOPIC, ID_MEMBER, subject, posterName, posterEmail, posterTime, posterIP, smiliesEnabled, body, icon, attachmentSize, attachmentFilename, nowListening, multinick, closeComments, agent)
  1521.                    VALUES ({$service->thread}, {$app->user->id}, '$naztem', '$e_name', '$e_email', $time, '$REMOTE_ADDR', $se, '$message', '$icon', '$attachment_size', $tmpname, '$nowListening', '$multinick', {$app->user->closeCommentsByDefault}, '$agent_fp')", false);
  1522.                 $ID_MSG = $db->insert_id;
  1523.             }
  1524.            
  1525.             if ($ID_MSG > 0)
  1526.             {
  1527.                 if (!$um) // united message (dig7er)
  1528.                     $dbrq = $db->query("
  1529.                        UPDATE {$db_prefix}topics
  1530.                        SET ID_MEMBER_UPDATED = {$app->user->id}, ID_LAST_MSG = $ID_MSG, numReplies = numReplies + 1 $isLocked
  1531.                        WHERE (ID_TOPIC = {$service->thread})", false);
  1532.                
  1533.                 if (!$um) // united message (dig7er)
  1534.                     $dbrq = $db->query("
  1535.                        UPDATE {$db_prefix}boards
  1536.                        SET numPosts = numPosts + 1
  1537.                        WHERE (ID_BOARD = {$service->board})", false);
  1538.                
  1539.                 if (!$um) // united message (dig7er)
  1540.                     $mreplies++;
  1541.                
  1542.                 if ($app->conf->trackStats == 1 and !$um)
  1543.                 {
  1544.                     $date = getdate(time() + $app->conf->timeoffset * 3600);
  1545.                     $statsquery = $db->query("
  1546.                        UPDATE {$db_prefix}log_activity
  1547.                        SET posts = posts + 1
  1548.                        WHERE month = {$date['mon']}
  1549.                        AND day = {$date['mday']}
  1550.                        AND year = {$date['year']}", false);
  1551.                    
  1552.                     if ($db->affected_rows == 0)
  1553.                         $statsquery = $db->query("
  1554.                            INSERT INTO {$db_prefix}log_activity
  1555.                            (month, day, year, posts)
  1556.                            VALUES ({$date['mon']}, {$date['mday']}, {$date['year']}, 1)", false);
  1557.                 }
  1558.                
  1559.                 $app->subs->updateStats('message');
  1560.                 $app->subs->UpdateLastMessage($service->board);
  1561.                
  1562.                 // quick poll mod by dig7er, 14.04.2010
  1563.                 if (!empty($quickPollTitle))
  1564.                     $dbrq = $db->query("
  1565.                        REPLACE INTO {$db_prefix}quickpolls
  1566.                        (ID_MSG, POLL_TITLE)
  1567.                        VALUES ($ID_MSG, '$quickPollTitle')", false);
  1568.             } // if $ID_MSG > 0
  1569.         } // if not $newtopic
  1570.        
  1571.         if (!$app->user->guest)
  1572.     {
  1573.             $dbrq = $db->query("
  1574.                SELECT * FROM {$db_prefix}boards
  1575.                WHERE ID_BOARD = '{$service->board}'", false);
  1576.            
  1577.             $pcount = $dbrq->fetch_array();
  1578.             $pcounter = $pcount['count'];
  1579.            
  1580.             if ($pcounter != 1 and !$um) // united message (dig7er)
  1581.             {
  1582.                 ++$app->user->posts;
  1583.                 $dbrq = $db->query("
  1584.                    UPDATE {$db_prefix}members
  1585.                    SET posts = posts + 1
  1586.                    WHERE ID_MEMBER = {$app->user->id}
  1587.                ", false);
  1588.             }
  1589.            
  1590.             # Mark thread as read for the member.
  1591.            $dbrq = $db->query("
  1592.                REPLACE INTO {$db_prefix}log_topics
  1593.                (logTime, ID_MEMBER, ID_TOPIC)
  1594.                VALUES (" . time() . ", {$app->user->id}, {$service->thread})", false);
  1595.         }
  1596.        
  1597.         # The thread ID, regardless of whether it's a new thread or not.
  1598.        $thread = $service->thread;
  1599.        
  1600.         # Notify any members who have notification turned on for this thread.
  1601.        $app->im->NotifyUsers();
  1602.        
  1603.         $notify = $POST->get('notify');
  1604.         // turn notification on
  1605.         if (!empty($notify))
  1606.         {
  1607.             //include_once("$sourcedir/Notify.php");
  1608.             //Notify2(); FIXME
  1609.         }
  1610.        
  1611.         # Let's figure out what page number to show
  1612.        $start = (floor($mreplies / $app->conf->maxmessagedisplay)) * $app->conf->maxmessagedisplay;
  1613.        
  1614.         //  Remove this comment and comment out the other SetLocation so that you are returned
  1615.         //  to the same thread after posting.
  1616.         if ($app->conf->returnToPost == '1')
  1617.             $yySetLocation = "/b{$service->board}/t$thread/new/";
  1618.         else
  1619.             $yySetLocation = "/b{$service->board}/";
  1620.        
  1621.         return $this->redirect($yySetLocation);
  1622.        
  1623.     } // postReply()
  1624.    
  1625.     public function preview($request, $response, $service, $app)
  1626.     {
  1627.         $app->session->check('post');
  1628.         $POST = $request->paramsPost();
  1629.         $message = $POST->get('message');
  1630.        
  1631.         if(empty($message))
  1632.             return $app->errors->abort('', 'Empty message');
  1633.        
  1634.         $message = $service->unicodeentities($message);
  1635.         $message = $service->doubbc($message);
  1636.         return $this->ajax_response($message, 'html');
  1637.     }
  1638. }
  1639.  
  1640. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement