#!/usr/bin/perl

#############################################################
# based on Ikonboard v2.1 by Ikonboard.com
#
# расчищал и исправлял Svarga
# http://forum.ru-board.com/
#############################################################

use CGI::Carp "fatalsToBrowser";
use CGI qw(:standard);
$CGI::POST_MAX=1024 * 150;
$CGI::DISABLE_UPLOADS = 1;

# checking, if the client requests the script
if(param('client') && 1 == param('client')){

# хеш для юзверьных данных
%users=();

eval {
($0 =~ m,(.*)/[^/]+,)   && unshift (@INC, "$1");
($0 =~ m,(.*)\\[^\\]+,) && unshift (@INC, "$1");
require "cl_ikon.lib";
require "data/progs.cgi";
require "data/boardinfo.cgi";
require "data/styles.cgi";
require "data/membertitles.cgi";
};
if ($@) {
print header('text/html; charset=windows-1251'); print start_html(-title=>"$ibtxt{'0025'}");
    print "$ibtxt{'0026'} $@\n$ibtxt{'0027'}";
    print end_html; exit;
    }

$|++;

#################--- Begin the program ---###################

$thisprog = "cl_topic.cgi";

$query = new CGI;
$cookiepath     = $query->url(-absolute=>1);
$cookiepath     =~ s/$thisprog//sg;
$inforum        = $query -> param('forum');
$inforum        = &stripMETA("$inforum");
$intopic        = $query -> param('topic');
$intopic        = &stripMETA("$intopic");
$instart        = $query -> param('start');
$instart        = &stripMETA("$instart");
$jumpto         = $query -> param('jumpto');
$jumpto         = &stripMETA("$jumpto");
die "Hack attempt!" unless $inforum =~ m!\A\d{1,3}\Z!;
die "Hack attempt!" if $intopic && $intopic !~ m!\A\d{1,7}\Z!;
$inmembername   = cookie("amembernamecookie");
$inpassword     = cookie("apasswordcookie");

$client		= $query -> param('client')||0;



&forumjump;
if ($jumpto) {
    print redirect(-location=>"$jumpto"); exit;
    }
if (!$inmembername) {
    $inmembername = "$ibtxt{'0043'}";
    }
    else {
        &getmember("$inmembername");
        if ($allowedentry{$inforum} eq "yes") { $allowed = "yes"; }
            else { $allowed  = "no"; }
        &getmemberstime("$inmembername");
        &getlastvisit;
        $forumlastvisit = $lastvisitinfo{$inforum};
        $currenttime = time;
        &setlastvisit("$inforum,$currenttime");
        }

    print header(-cookie=>[$tempvisitcookie, $permvisitcookie]);

    &getforum($inforum);


    $filetoopen = "$ikondir" . "forum$inforum/list.cgi";
    $filetoopen = &stripMETA($filetoopen);
    if (-e $filetoopen) {
        open(FILE, $filetoopen) or &error("$ibtxt{'3001'}&$ibtxt{'3002'}$inforum/list.cgi");
        flock FILE, 1;
        @allthreads = <FILE>;
        close FILE;
        $totalthreadcount = @allthreads;
        $count = 0;
        foreach $line (@allthreads) { #start foreach @threads
            ($tempno, $trash) = split(/\|/, $line);
            chomp $line;
            push (@numbercounter, $tempno);
            if ($intopic eq $tempno) {
                ($topicid, $topictitle, $topicdescription, $threadstate, $threadposts ,$threadviews, $startedby, $startedpostdate, $lastposter, $lastpostdate) = split(/\|/,$line);
                $threadviews++; $keepcounter = $count;
                $linetokeep = "$topicid|$topictitle|$topicdescription|$threadstate|$threadposts|$threadviews|$startedby|$startedpostdate|$lastposter|$lastpostdate";
                chomp $linetokeep;
		$threadstate='open' eq $threadstate ?1:0;
		$output .= "$topicid|$topictitle|$topicdescription|$threadstate|$threadposts|$startedby|$startedpostdate|$lastposter|$lastpostdate\n\n";
                $processed_data .= "$linetokeep\n";
                }
                else { $processed_data .= "$line\n"; }
            $count++;
            }
        if (($processed_data eq "") || ($processed_data !~ m!\|!)) { &error("{Missing Data&Data as corrupted on the server. Please go back and try again}"); }
        open FILE, ">$filetoopen";
        flock FILE, 2;
        print FILE $processed_data;
        close FILE;
        undef $processed_data;
        my $file = "$ikondir" . "forum$inforum/$intopic.pl";
        open(MSG, ">$file");
        flock MSG, 2;
        print MSG $linetokeep;
        close(MSG);
        }

    $totalthreadcount = @numbercounter; $totalthreadcount--;

    if ($intopic eq $numbercounter[0]) { undef $nextlink; }
        else {
            $nexttopic = $keepcounter - 1;
            $threadnext = $numbercounter[$nexttopic];
            $nextlink = qq~<a href="$threadprog?forum=$inforum&topic=$threadnext"> $ibtxt{'3003'} >></a>~;
            }

    if ($intopic eq $numbercounter[$totalthreadcount]) { undef $backlink; }
        else {
            $backtopic = $keepcounter + 1;
            $threadback = $numbercounter[$backtopic];
            $backlink = qq~<a href="$threadprog?forum=$inforum&topic=$threadback"><< $ibtxt{'3004'} </a>~;
            }

    $nexttopiclinks = "$ibtxt{'3019'}<br>"; $nexttopiclinks .= "$backlink" if $backlink; $nexttopiclinks .= "$nextlink" if $nextlink;


    if($client){&whosonline("$inmembername|$inforum|$intopic|$topictitle|$forumname") if ($privateforum ne "yes");}
    {
    &whosonline("$inmembername|$ibtxt{'3020'} <a href=\"$threadprog?forum=$inforum&topic=$intopic\"><b>$topictitle</b></a> $ibtxt{'2028'} <a href=\"$forumsprog?forum=$inforum\"><b>$forumname</b></a>|$ibtxt{'1602'}") if ($privateforum ne "yes");
    }
    &moderator;
    $filetoopen = "$ikondir" . "forum$inforum/$intopic.thd";
    $filetoopen = &stripMETA($filetoopen);
        if (-e $filetoopen) {
	#дата редактирования файла с данными о постах
	$output .= (stat($filetoopen))[9]."\n\n";
	#$output .= (join ':', stat($filename))."\n\n";

	open(FILE, $filetoopen) or &error("$ibtxt{'3005'}&$ibtxt{'3006'}");
        @threads = <FILE>;
        close(FILE);
        }

    ($trash, $topictitle) = split(/\|/,$threads[0]);

    $numberofitems = @threads;
    $numberofpages = $numberofitems / $maxthreads;

    if ($numberofitems > $maxthreads) {
        $showmore = "yes";
        if ((!$instart) or ($instart < 0)) { $instart = 0; }
        if ($instart > 0) { $startarray = $instart; } else { $startarray = 0; }
        $endarray = $instart + $maxthreads - 1;
        if ($endarray < ($numberofitems - 1)) { $more = "yes"; }
        if (($endarray > ($maxthreads - 1)) and ($more ne "yes")) { $endarray = $numberofitems - 1; }
        }
        else {
             $showmore = "no";
             $startarray = 0;
             $pages = qq~<font face="$font" color=$menufontcolor size=$dfontsize1>$ibtxt{'3007'}</font>~;
             $endarray = $numberofitems - 1;
             }

     if ($showmore eq "yes") {
     if ($maxthreads < $numberofitems) {
        ($integer,$decimal) = split(/\./,$numberofpages);
        if ($decimal > 0) { $numberofpages = $integer + 1; }
            $pagestart = 0; $counter = 0;
            while ($numberofpages > $counter) {
                $counter++;
                if ($instart ne $pagestart) { $pages .= qq~<a href="$thisprog?forum=$inforum&topic=$intopic&start=$pagestart"><font face="$font" color=$fonthighlight size=$dfontsize1><b>$counter</b></font></a> ~; }
                else { $pages .= qq~<a href="$thisprog?forum=$inforum&topic=$intopic&start=$pagestart"><font face="$font" color=$menufontcolor size=$dfontsize1>$counter</font></a> ~; }
            $pagestart = $pagestart + $maxthreads;
            }
        }
     $pages = qq~<font face="$font" color=$menufontcolor size=$dfontsize1><b>$ibtxt{'3008'}</b> [ $pages ]~;
     }

    if (("$privateforum" eq "yes" && "$allowed" ne "yes")) { &error("{$ibtxt{'1606'}&$ibtxt{'1607'}}"); }
    $printpageicon = qq~<a href="$printpageprog?forum=$inforum&topic=$intopic"><img src="$imagesurl/images/$printpage" border=0></a>~;
    if ($privateforum ne "yes") { $sendtofriendicon = qq~<a href="$ikonfriendprog?forum=$inforum&topic=$intopic"><img src="$imagesurl/images/$emailtofriend" border=0></a>~; }



    $editpostnumber = $startarray; $editpostnumber++; $postcountnumber = 0;

    foreach (@threads[$startarray .. $endarray]) {

        ($membername, $topictitle, $postipaddress, $showemoticons, $showsignature, $postdate, $post) = split(/\|/,$_);


	$postdate = $postdate + ($timedifferencevalue*3600) + ($timezone*3600);
        $postdate = &dateformat("$postdate");

        &getmember("$membername");
        $mname=$membername;
        $m_membername = $membername;
        $m_membername =~ y! !_!; &set_up_guest() unless (-e $ikondir . 'members/'.$m_membername.'.cgi');

        if ($membername eq "$ibtxt{'0043'}") { $joineddate = "Never"; }
		elsif ($joineddate) {
            $joineddate = $joineddate + ($timedifferencevalue*3600) + ($timezone*3600);
            $joineddate = &joineddate("$joineddate");
            }
            else { $joineddate =$client ? '': "$ibtxt{'3009'}"; }

        $numberofposts ='' if !$numberofposts or ($membername eq "$ibtxt{'0043'}");

        if (($post =~ /#Moderation Mode/i) and ($membercode eq 'mo' || $membercode eq 'ad') && !$client) {
            $post =~ s/&lt;/</g; $post =~ s/&gt;/>/g; $post =~ s/&quot;/\"/g;
            }

         if ($htmlstate eq 'on') {
            $post =~ s/&lt;/</g; $post =~ s/&gt;/>/g; $post =~ s/&quot;/\"/g;
            }


        if ($count eq 1) {
                $postbackcolor = "$postcolorone"; $postfontcolor = "$postfontcolorone"; $count++;
                }
                else {
                    $postbackcolor = "$postcolortwo"; $postfontcolor = "$postfontcolortwo"; $count = 1;
                    }

        if (($emoticons eq 'on') && ($showemoticons eq 'yes')) {
            $post =~ s/\:\)/<img src=\"$imagesurl\/emoticons\/smile.gif\" border=\"0\">/g;
            $post =~ s/\;\)/<img src=\"$imagesurl\/emoticons\/wink.gif\" border=\"0\">/g;
            $post =~ s/\:\(/<img src=\"$imagesurl\/emoticons\/sad.gif\" border=\"0\">/g;
            $post =~ s/\:o/<img src=\"$imagesurl\/emoticons\/shocked.gif\" border=\"0\">/g;
            }


	    $signature = $signature || '';
	    chomp $signature;
	    chomp $post;

        if    ($numberofposts > $mpostmark5) { $mtitle = "$mtitle5";  $membergraphic = "$mgraphic5"; }
        elsif ($numberofposts > $mpostmark4) { $mtitle = "$mtitle4";  $membergraphic = "$mgraphic4"; }
        elsif ($numberofposts > $mpostmark3) { $mtitle = "$mtitle3";  $membergraphic = "$mgraphic3"; }
        elsif ($numberofposts > $mpostmark2) { $mtitle = "$mtitle2";  $membergraphic = "$mgraphic2"; }
        else { $mtitle = "$mtitle1"; $membergraphic = "$mgraphic1"; }

      if (($pips eq 'on') && ($membergraphic)) { $membergraphic =$client ? "$membergraphic|": "<img src=\"$imagesurl/images/$membergraphic\" border=\"0\">"; }
      else { undef $membergraphic;}

        if (($avatars eq "on") && ($useravatar) && ($useravatar ne "noavatar")) {
            $useravatar =$client ? "$useravatar.gif": qq(<br><img src="$imagesurl/avatars/$useravatar.gif" border=0 width="32" height="32">);
            }
            else { undef $useravatar; }


        $memberfilename = $membername;
        $memberfilename =~ y/ /_/;

        if ($threadstate ne "closed") {
           if ($text_menu ne "yes"){$replygraphic = $client?'':qq~<a href="$postprog?action=replyquote&forum=$inforum&topic=$intopic&postno=$editpostnumber"><img src="$imagesurl/images/$reply" border=0></a>~;}
           else{$replygraphic = $client?'':qq~| <a href="$postprog?action=replyquote&forum=$inforum&topic=$intopic&postno=$editpostnumber">Цитата</a>~;}
            }
            else {
                 undef $replygraphic;
                }
        if ($text_menu ne "yes"){
            $privatemessagegraphic =$client?'': qq~<a href="javascript:openScript('$messengerprog?action=new&touser=$memberfilename',600,400)"><img src="$imagesurl/images/$message" border=0></a>~;

            $profilegraphic =$client?'':  qq~<a href="$profileprog?action=show&member=$memberfilename"><img src="$imagesurl/images/$profile" border=0></a>~;
            $editgraphic    =$client?'':  qq~<a href="$postingsprog?action=edit&forum=$inforum&topic=$intopic&postno=$editpostnumber"><img src="$imagesurl/images/$edit" border=0></a>~;
            $partition      =$client?'':  qq~<img src="$imagesurl/images/$part" border=0>~;
        } else  {

            $privatemessagegraphic =$client?'':  qq~ | <a href="javascript:openScript('$messengerprog?action=new&touser=$memberfilename',600,400)">Сообщение</a>~;
            $profilegraphic =$client?'':  qq~ | <a href="$profileprog?action=show&member=$memberfilename">Профиль</a>~;
            $editgraphic    =$client?'':  qq~<a href="$postingsprog?action=edit&forum=$inforum&topic=$intopic&postno=$editpostnumber">Правка</a>~;
          }


        if($showemail eq "yes") {
           if ($text_menu ne "yes"){
              $emailgraphic =$client? "$emailaddress": qq~<a href="mailto:$emailaddress"><img src="$imagesurl/images/$email" border=0></a>~; }
           else {$emailgraphic = $client? "$emailaddress": qq~ | <a href="mailto:$emailaddress">E-mail</a>~; }
        }
        else { undef $emailgraphic; }

        $homepage =~ s/http\:\/\///sg;
        if($homepage) {
           if ($text_menu ne "yes"){
              $homepagegraphic =$client? "$homepage":  qq~<a href="http://$homepage" target="_blank"><img src="$imagesurl/images/$homepagepic" border=0></a>~; }
           else {$homepagegraphic =$client? "$homepage":  qq~ | <a href="http://$homepage" target="_blank">WWW</a>~; }
        }
        else { undef $homepagegraphic; }


        if ($aolname) {
            if ($text_menu ne "yes"){
              $aolgraphic =$client? "$aolname":  qq~<a href="javascript:openScript('$miscprog?action=aim&aimname=$aolname',450,200)"><img src="$imagesurl/images/$aol" border=0></a>~; }
           else {
            $aolgraphic = $client? "$aolname": qq~ | <a href="javascript:openScript('$miscprog?action=aim&aimname=$aolname',450,200)">AOL</a>~; }
        }
         else { undef $aolgraphic; }

        if (($icqnumber) && ($icqnumber =~ /[0-9]/)) {
            if ($text_menu ne "yes"){
              $icqgraphic = $client? "$icqnumber": qq~<a href="javascript:openScript('$miscprog?action=icq&UIN=$icqnumber',450,300)"><img src="http://wwp.icq.com/scripts/online.dll?icq=$icqnumber&img=5" border=0><img src="$imagesurl/images/$icq" border=0></a>~;  }
           else {
            $icqgraphic = $client? "$icqnumber": qq~ | <a href="javascript:openScript('$miscprog?action=icq&UIN=$icqnumber',450,300)">ICQ</a>~; }
         }
         else { undef $icqgraphic; }


        if ($membercode eq "ad") {
            $posterfontcolor = "$adminnamecolor";
            if ($team){
            $membername =$client? $membername : "$membername <img src=\"$imagesurl/images/$team\" border=0>";}
          if ($pips eq 'on'){
            $membergraphic =$client? '' :  "<img src=\"$imagesurl/images/$admingraphic\" border=\"0\">";}
            else { undef $membergraphic;}
            if ($membertitle eq "") { $membertitle = "$ibtxt{'1874'}"; }
            }
            elsif ($membercode eq "mo") {
                   $posterfontcolor = "$teamnamecolor";
                   $membername = $client? $membername : "$membername <img src=\"$imagesurl/images/team.gif\" border=0>";
                if ($membertitle eq "") { $membertitle = "$ibtxt{'0007'}"; }
                }
                elsif ($membercode eq "banned") {
                    $posterfontcolor = "$posternamecolor";
                    $membergraphic = "";
                    $membertitle = "$ibtxt{'3010'}";
                    }
                    else { $posterfontcolor = "$posternamecolor"; }


     if ($locations_in_topic eq 'on') {
            if ($location){

            if (length($location) > $char_locat_in_topic) {
            $location = substr($location, 0, $char_locat_in_topic-1);
            $location .= ' ...';
            }

            $locat = qq~<br>Откуда: $location<p>~;
            }
            else {undef $locat;}
            }

    $membertitle =~ s/&lt;/</g; $membertitle =~ s/&gt;/>/g; $membertitle =~ s/&quot;/"/g;

    $post =~ s/\($ibtxt{'1537'}(.+?)\)/\<font size=$dfontsize1>\($ibtxt{'1537'}$1\)\<\/font\>/isg;

    $post = &Truncate("$post");

    if ($iplog eq 'lnk'){$view_ip = qq~ | <a href="$viewipprog?forum=$inforum&topic=$intopic&postno=$editpostnumber">$ibtxt{'3013'}</a>~;}
    elsif ($iplog eq 'on'){$view_ip = qq~ | $postipaddress~;}
    else {undef $view_ip;}

#------- HTML
	chomp $post;
	$showemoticons = 'yes' eq $showemoticons ? 1:0;
	$showsignature = 'yes' eq $showsignature ? 1:0;
	$output .= "$membername|$post|$postdate|$showsignature|$showemoticons\n";


	#набиваем юзерный хеш
	if(!$users{$membername}){
		$users{$membername}="$useravatar|$membertitle|$homepagegraphic $emailgraphic $privatemessagegraphic $aolgraphic $icqgraphic|$numberofposts|$joineddate|$signature";
		}

    $editpostnumber++; $postcountnumber++; undef $membercode;

    }

$tmp='';
# готовим юзверей к выводу :)
foreach $user (keys %users){
	$tmp .= "$user|$users{$user}\n";
	}
$output = "$tmp\n$output";


# Номер страницы на многостраничных темах Shurik & DimoN
if ($numberofitems > $maxthreads) {
if ($instart == 0) {$pagenumber = 1;}
else {$pagenumber = ($instart/$maxthreads)+1;}

    &output($output);
} else {

    &output($output);
}

}
# if the script is requested without parameter client=1, open a non-client
# version of the script:
else{
	require 'forums.cgi' or die "Content-Type: text/html; charset=windows-1251\n\nБеда какая-то с forums.cgi: $!\n:(";
	}

1;
