<?php

if ( ! @include_once( './mainfile.php' ) ) { exit( '!! INCLUDE ERROR. ACCESS DENIED !!' ); }
error_reporting( _E_VALUE );


/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | myPHPNuke Version 188_8 RC2                                          |
// +----------------------------------------------------------------------+
// | License: GNU/GPL - http://www.gnu.org/copyleft/gpl.html              |
// +----------------------------------------------------------------------+
// | Support: http://myphpnuke.com/                                       |
// +----------------------------------------------------------------------+
// | Author: myPHPNuke Dev Team                                           |
// +----------------------------------------------------------------------+
// | Copyright: © 2001-2004 myPHPNuke Dev Team                            |
// +----------------------------------------------------------------------+
// $Id: links.php,v 1.23.2.13 2004/08/27 16:01:31 kirilt Exp $




/************************************************************************/
/* PHP-NUKE: Web Portal System                                          */
/* ===========================                                          */
/*                                                                      */
/* Copyright (c) 2001 by Francisco Burzi (fburzi@ncc.org.ve)            */
/* http://phpnuke.org                                                   */
/*                                                                      */
/* ====================================                                 */
/* Web Links Modified from the original                                 */
/* Copyright (c) 2000 by James Knickelbein                              */
/* Journey Milwaukee (http://www.journeymilwaukee.com)                  */
/*                                                                      */
/* This program is free software. You can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License.       */
/************************************************************************/

function logo()
{
    global $phpEx, $sitename, $mpn_use_opendir;

    echo "<h1>$sitename " . translate ( 'Web Links' ) . "</h1>\n";
    echo "<br />\n";

    echo "<div class='subtitle1'>\n";

    echo "<a href=links.$phpEx>".translate("Links Main")."</a>\n";
    echo ' | ';
    echo "<a href=links.$phpEx?op=AddLink>".translate("Add Link")."</a>\n";
    echo ' | ';
    echo "<a href=links.$phpEx?op=NewLinks>".translate("New")."</a>\n";
    echo ' | ';
    echo "<a href=links.$phpEx?op=MostPopular>".translate("Popular")."</a>\n";
    echo ' | ';
    echo "<a href='links.php?op=TopRated'>".translate("Top Rated")."</a>\n";
    echo ' | ';
    echo "<a href=links.$phpEx?op=RandomLink>".translate("Random")."</a>\n";

    if ( $mpn_use_opendir && ! $_SERVER['ua_sniff'] -> bot )
    {
        echo "<br /><br />\n";

        echo '<a href="./npp_ODP.php?enpp=odp" title="' . translate( 'Search Open Directory' ) . '">' . translate( 'Search Open Directory' ) . '</a>' . "\n";
    }

    echo "<br /><hr class='w80'/><br />\n";

    echo "</div>\n";
}


function SearchForm() {
        global $phpEx;

echo "
    <div class='center'>
        <center>
        <form action=links.$phpEx?op=search method=POST>

            <input type=text size=30 name=query>
            <input class='button' type=submit value=".translate("Search")."></td></tr>

        </form>
        </center>
    </div>
";
}

function linkinfomenu($lid) {
        global $phpEx;

   echo"
   <br><font size=2>
   <a href=links.$phpEx?op=viewlinkcomments&lid=$lid>".translate("Link Comments")."</a>
   | <a href=links.$phpEx?op=viewlinkdetails&lid=$lid>".translate("Additional Details")."</a>
   | <a href=links.$phpEx?op=viewlinkeditorial&lid=$lid>".translate("Editor Review")."</a>
   | <a href=links.$phpEx?op=modifylinkrequest&lid=$lid>".translate("Modify")."</a>
   | <a href=links.$phpEx?op=brokenlink&lid=$lid>".translate("Report Broken Link")."</a></font><br>";

}

function index()
{
    global $mpnTables,$phpEx;

    include("header.$phpEx");
    logo();

    OpenTable();
    SearchForm();

echo "
<table border=0 cellspacing=10 cellpadding=0><tr>";

$result=mysql_query("select cid, title, cdescription from ".$mpnTables['links_categories']." order by title");
$count = 0;
while(list($cid, $title, $cdescription) = mysql_fetch_row($result)) {

    // Kiril: Start New Sanitizer

    $sanity_ary = compact( 'title', 'cdescription' );
    $_SERVER['SAN'] -> slashIT( $sanity_ary );
    extract( $sanity_ary );
    unset( $sanity_ary );

    // End New Sanitizer


    $cresult = mysql_query("select * from ".$mpnTables['links_links']." where cid=$cid");
    $cnumrows = mysql_num_rows($cresult);
    echo "<td><font size=3><li><a href=links.$phpEx?op=viewlink&cid=$cid><b>$title</b></a> ($cnumrows)</font>";
    categorynewlinkgraphic($cid);
    if (isset($description)) {
        echo "<font size=2>$cdescription<br></font>";
    } else {
        echo "<br>";
    }
    $result2 = mysql_query("select sid, title from ".$mpnTables['links_subcategories']." where cid=$cid order by title limit 0,3");
    $space = 0;
    while(list($sid, $stitle) = mysql_fetch_row($result2))
    {
        $stitle = stripslashes( $stitle );

        if ($space>0) {
            echo ",&nbsp;";
        }
        echo "<font size=2><a href=links.$phpEx?op=viewslink&sid=$sid>$stitle</a></font>";
        $space++;
    }
    if ($count<1) {
        echo "</td><td>&nbsp;&nbsp;&nbsp;&nbsp;</td>";
    }
    $count++;
    if ($count==2) {
        echo "</td></tr><tr>";
        $count = 0;
    }
}
    echo "</td></tr></table>";
    $result=mysql_query("select * from ".$mpnTables['links_links']);
    $numrows = mysql_num_rows($result);
    echo "<br><br><center><font size=2>".translate("There are")." <b>$numrows</b> ".translate("Links in our Database")." </center>";
    echo "</font></basefont>";
    CloseTable();

    include("footer.$phpEx");
}


function AddLink($title, $url, $cat, $description, $name, $email) {
    global $links_anonaddlinklock, $mpnTables,$phpEx;
    include("header.$phpEx");
    logo();
    OpenTable();
    $mainlink = 1;

    echo "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=1 BORDER=0><TR><TD COLSPAN=2>
    <TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=8 BORDER=0><TR><TD>
    <br><br>";

    if ( _MPN_USER || $links_anonaddlinklock != 0) {
            echo "
        <LI>".translate("Submit a unique link only once.")."</li>
        <LI>".translate("All links are posted pending verification.")."</li>
        <LI>".translate("Username and IP are recorded, so please don't abuse the system.")."</li>

            <form action=\"links.$phpEx\" method=post>
            <font size=3><table width=\"80%\"><tr><td align=\"right\">
            ".translate("Page Title: ")."</td><td>";
            if (isset($title)) {
                    echo "<input type=text name=title size=50 maxlength=100 value=\"".StripSlashes($title)."\">";
            } else {
                    echo "<input type=text name=title size=50 maxlength=100>";
            }
            echo "</td></tr><tr><td align=\"right\">".translate("Page URL: ")."</td><td>";
            if (isset($url)) {
                    echo "<input type=text name=url size=50 maxlength=100 value=\"".StripSlashes($url)."\">";
            } else {
                    echo "<input type=text name=url size=50 maxlength=100 value=\"http://\">";
            }
            echo "</td></tr>";
            $result=mysql_query("select cid, title from ".$mpnTables['links_categories']." order by title");
            echo "<tr><td align=\"right\">".translate("Category: ")."</td><td><select name=cat2>";
            while(list($cid, $title) = mysql_fetch_row($result))
            {
                $title = stripslashes( $title );

                echo "<option value=$cid>$title</option>";
                $result2=mysql_query("select sid, title from ".$mpnTables['links_subcategories']." where cid=$cid order by title");
                while(list($sid, $stitle) = mysql_fetch_row($result2))
                {
                    $stitle = stripslashes( $stitle );
                    echo "<option value=$cid-$sid>$title / $stitle</option>";
                }
            }
            echo "</select></td></tr><tr><td></td><td>";
            echo "<input type=\"checkbox\" name=\"spider\" value=\"1\">" .translate("Get meta info");
            echo "</input>&nbsp;&nbsp;(" .translate("Fetches the metadata from the URL").")";
                        echo "</td></tr><tr><td></td><td>
            ".translate("Description: (255 characters max)")."</td></tr><tr><td></td><td>";
            if (isset($description)) {
                    echo "<textarea name=description cols=60 rows=5>".StripSlashes($description)."</textarea>";
            } else {
                    echo "<textarea name=description cols=60 rows=5></textarea>";
            }
            echo "</td></tr><tr><td align=\"right\">".translate("Your Name: ")."</td><td>";
            if (isset($name)) {
                    echo "<input type=text name=name size=30 maxlength=60 value=\"".StripSlashes($name)."\"></input>";
            } elseif ( _MPN_USER ) {
                    echo "<input type=text name=name size=30 maxlength=60 value=\"".$GLOBALS['uinf']['uname']."\"></input>";
            } else {
                    echo "<input type=text name=name size=30 maxlength=60></input>";
            }
            echo "</td></tr><tr><td align=\"right\">";
            echo translate("Your Email: ")."</td><td>";
            if (isset($email)) {
                    echo "<input type=text name=email size=30 maxlength=60 value=\"$email\"></input>";
            } elseif ( _MPN_USER ) {
                    echo "<input type=text name=email size=30 maxlength=60 value=\"".$GLOBALS['uinf']['email']."\"></input>";
            } else {
                    echo "<input type=text name=email size=30 maxlength=60></input>";
            }
            echo "</td></tr></table><br>\n";

            // Kiril: New Sanitizer

            echo "<input type='hidden' name='stripit_form' value='title|url|description|name|email' />\n";
            echo "<input type='hidden' name='mpn_sectype' value='2' />\n";

            // End Sanitizer

            echo "<input type=\"hidden\" name=\"op\" value=\"Add\">
            </input><center><input type=\"submit\" class=\"button\" value=\"".translate("Add URL")."\"></input></center>";
            echo "</form>";

    }else {
            echo "<center>".translate("You are not a registered user or you have not logged in.")."<br>
                      ".translate("If you were registered you could add links on this website.")."<br><br>
                          <a href=user.$phpEx>".translate("Register for an Account")."</a></center>";
    }
    echo "</TD></TR></TABLE></TD></TR></TABLE>";
    CloseTable();
    include("footer.$phpEx");
}

function Add($title, $url, $cat2, $description, $name, $email, $spider)
{
    global $mpnTables,$phpEx;


    $result = mysql_query("select url from ".$mpnTables['links_links']." where url='$url'");
    $numrows = mysql_num_rows($result);

    if ($numrows>0) {
        include("header.$phpEx");
        echo "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=1 BORDER=0><TR><TD COLSPAN=2>
        <TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=8 BORDER=ff0><TR><TD><center><br>";
        SearchForm();
        echo "<font size=3 color=Red>";
        echo "<b>".translate("ERROR: This URL is already listed in the Database!")."</b><br><br>";
        echo "</TD></TR></TABLE></TD></TR></TABLE>";
        include("footer.$phpEx");
    }
    else
    {
        $submitter = $GLOBALS['uinf']['uname'];

        // Check For Empty

        $check_ary = array( $_POST['title'], $_POST['url'], $_POST['description'] );

        $verify_check_ary = $_SERVER['SAN'] -> verifyContent( $check_ary, 3 );

        if ( in_array( (bool)FALSE, $verify_check_ary ) )
        {
            goBack( translate( 'You Failed To Include Required Information' ) );
            exit;
        }

        // Check URL

        if ( ! $_SERVER['SAN'] -> verifyContent( $_POST['url'], 1 ) )
        {
            goBack( translate( 'Invalid URL' ) );
            exit;
        }

        // Check Email

        if ( ! $_SERVER['SAN'] -> verifyContent( $_POST['email'], 2 ) )
        {
            goBack( translate( 'Invalid Email' ) );
            exit;
        }

        unset( $check_ary, $verify_check_ary );


/*// Check if Title exist
    if ($title=="") {
        include("header.$phpEx");
        echo "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=1 BORDER=0><TR><TD COLSPAN=2>
        <TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=8 BORDER=0><TR><TD><center><br>";
        SearchForm();
        echo "<font size=3 color=Red>";
        echo "<b>".translate("ERROR: You need to type a TITLE for your URL!")."</b><br><br>";
        echo "</TD></TR></TABLE></TD></TR></TABLE>";
        include("footer.$phpEx");
    }
// Check if URL exist
    if ($url=="") {
        include("header.$phpEx");
        echo "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=1 BORDER=0><TR><TD COLSPAN=2>
        <TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=8 BORDER=0><TR><TD><center><br>";
        SearchForm();
        echo "<font size=3 color=Red>";
        echo "<b>".translate("ERROR: You need to type a URL for your URL!")."</b><br><br>";
        echo "</TD></TR></TABLE></TD></TR></TABLE>";
        include("footer.$phpEx");
    }
// Check if Description exist
    if ($description=="") {
        include("header.$phpEx");
        echo "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=1 BORDER=0><TR><TD COLSPAN=2>
        <TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=8 BORDER=0><TR><TD><center><br>";
        SearchForm();
        echo "<font size=3 color=Red>";
        echo "<b>".translate("ERROR: You need to type a DESCRIPTION for your URL!")."</b><br><br>";
        echo "</TD></TR></TABLE></TD></TR></TABLE>";
        include("footer.$phpEx");
    }*/


    $cat1 = explode("-", $cat2);

    if ( ! is_array( $cat1 ) || ! isset( $cat1[1] ) || $cat1[1] == '' )
    {
        $cat1[1] = 0;
    }

    /*$title = stripslashes(FixQuotes($title));
    $url = stripslashes(FixQuotes($url));
    $description = stripslashes(FixQuotes($description));
    $name = stripslashes(FixQuotes($name));
    $email = stripslashes(FixQuotes($email));*/


    mysql_query("insert into ".$mpnTables['links_newlink']." values (NULL, '$cat1[0]', '$cat1[1]', '$title', '$url', '$description', '$name', '$email', '$submitter')");
    include("header.$phpEx");

    logo();

    echo "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=1 BORDER=0 ><TR><TD COLSPAN=2>
    <TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=8 BORDER=0><TR><TD><center><br>";
    SearchForm();
    echo "<font size=3>";
    echo "".translate("We received your Link submission. Thanks!")."<br>";
    echo "".translate("You'll receive an E-mail when it's approved.")."<br><br>";
    echo "</TD></TR></TABLE></TD></TR></TABLE>";
    include("footer.$phpEx");
    }
}


function NewLinks($newlinkshowdays) {
    global $admin,$mpnTables,$phpEx, $bgcolor2, $bgcolor3, $textcolor1, $textcolor2;
    include("header.$phpEx");
    logo();
    OpenTable();

    echo "
    <TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=8 BORDER=0><TR><TD>";

    echo "<TABLE WIDTH=\"100%\" CELLSPACING=2 CELLPADDING=2 BORDER=0 BGCOLOR=$bgcolor2><TR><TD>";
    echo "<center><font size=3><b>".translate("New Links")."</b></font></center>";
    echo "</tr></td></table><br>";

    $counter = 0;
    $allmonthlinks = $allweeklinks = 0;
    while ($counter <= 7-1){
    $newlinkdayRaw = (time()-(86400 * $counter));
    $newlinkday = date("d-M-Y", $newlinkdayRaw);
    $newlinkView = date("F d, Y", $newlinkdayRaw);
    $newlinkDB = Date("Y-m-d", $newlinkdayRaw);
    $result = mysql_query("select * FROM ".$mpnTables['links_links']." WHERE date LIKE '%$newlinkDB%'");
    $totallinks = mysql_num_rows($result);
    $counter++;
    $allweeklinks = $allweeklinks + $totallinks;
    }

    $counter = 0;
    while ($counter <=30-1){
        $newlinkdayRaw = (time()-(86400 * $counter));
        # $newlinkday = date("d-M-Y", $newlinkdayRaw);
        # $newlinkView = date("F d, Y", $newlinkdayRaw);
        $newlinkDB = Date("Y-m-d", $newlinkdayRaw);
        $result = mysql_query("select * FROM ".$mpnTables['links_links']." WHERE date LIKE '%$newlinkDB%'");
        $totallinks = mysql_num_rows($result);
        $allmonthlinks = $allmonthlinks + $totallinks;
        $counter++;
    }
    echo "<font color = $textcolor1><center>
          ".translate("Total new links: Last week")." - $allweeklinks \ ".translate("Last 30 days")." - $allmonthlinks
                  </font><br>
          ".translate("Show:")." (<a href=links.$phpEx?op=NewLinks&newlinkshowdays=7>".translate("week")."</a>, <a href=links.$phpEx?op=NewLinks&newlinkshowdays=14>2 ".translate("weeks")."</a>, <a href=links.$phpEx?op=NewLinks&newlinkshowdays=30>30 ".translate("days")."</a>)

                  </center><br>";

    //List Last VARIABLE Days of Links
    if (!isset($newlinkshowdays)) {$newlinkshowdays = 7;}
    echo "<center><br><b>".translate("Total new links for last")." $newlinkshowdays ".translate("days").":</b><br><br>";
    $counter = 0;
    $allweeklinks = 0;
    while ($counter <= $newlinkshowdays-1){
    $newlinkdayRaw = (time()-(86400 * $counter));
    $newlinkday = date("d-M-Y", $newlinkdayRaw);
    $newlinkView = date(translate("forumdatestring"), $newlinkdayRaw);
    $newlinkDB = Date("Y-m-d", $newlinkdayRaw);
    $result = mysql_query("select * FROM ".$mpnTables['links_links']." WHERE date LIKE '%$newlinkDB%'");
    $totallinks = mysql_num_rows($result);
    $counter++;
    $allweeklinks = $allweeklinks + $totallinks;
    echo "<LI><a href=links.$phpEx?op=NewLinksDate&selectdate=$newlinkdayRaw>$newlinkView</a>&nbsp;( $totallinks )";
    }
    $counter = 0;
    $allmonthlinks = 0;

    echo "</center></TD></TR></TABLE>";
    CloseTable();
    include("footer.$phpEx");
}

function NewLinksDate($selectdate) {
    global $admin, $mpnTables,$phpEx, $bgcolor2, $bgcolor3, $textcolor1, $textcolor2, $locale;
    $dateDB = (date("d-M-Y", $selectdate));
    $dateView = (date(translate("forumdatestring"), $selectdate));
    include("header.$phpEx");
     logo();
    OpenTable();

    $newlinkDB = Date("Y-m-d", $selectdate);
    $result = mysql_query("select * FROM ".$mpnTables['links_links']." WHERE date LIKE '%$newlinkDB%'");
    $totallinks = mysql_num_rows($result);

    echo "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=8 BORDER=0><TR><TD><center>";
    echo "<TABLE WIDTH=\"100%\" CELLSPACING=2 CELLPADDING=2 BORDER=0 BGCOLOR=$bgcolor2><TR><TD>";
    echo "<FONT SIZE=3><b>$dateView - $totallinks ".translate("New Links")."</b>";
    echo "</TD></TR></TABLE></center><font size=2>";

    $result=mysql_query("select lid, cid, sid, title, description, date, hits, linkratingsummary, totalvotes, totalcomments from ".$mpnTables['links_links']." where date LIKE '%$newlinkDB%' order by title ASC");
    echo "<table width=\"100%\" cellspacing=0 cellpadding=10 border=0><tr><td><font size=2>";
    while(list($lid, $cid, $sid, $title, $description, $time, $hits, $linkratingsummary, $totalvotes, $totalcomments)=mysql_fetch_row($result)) {
//        $linkratingsummary = number_format($linkratingsummary, $mainvotedecimal);
        $linkratingsummary = number_format($linkratingsummary);

        // Kiril: Start New Sanitizer

        $sanity_ary = compact( 'title', 'url', 'description' );
        $_SERVER['SAN'] -> slashIT( $sanity_ary );
        extract( $sanity_ary );
        unset( $sanity_ary );

        // End New Sanitizer

        //$title = stripslashes($title); $description = stripslashes($description);
        echo "<a href=links.$phpEx?op=visit&lid=$lid target=new>$title</a>";

        if (!isset($datetime))
        {
            $datetime = null;
        }

        newlinkgraphic($datetime, $time);
        popgraphic($hits);
        echo "<br>";

        echo "<font color=777777>".translate("Description: ")."<font color=$textcolor1>$description<br>";

        setlocale (LC_TIME, $locale);
        // INSERT code for *editor review* here
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime);
        $datetime = strftime("".translate("linksdatestring")."", mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
        $datetime = ucfirst($datetime);
        echo "<font color=$textcolor2>".translate("Added on: ")."<font color=$textcolor1><b>$datetime</b><font color=$textcolor2> ".translate("Hits: ")."<font color=$textcolor1>$hits";
        $transfertitle = str_replace (" ", "_", $title);
        //voting & comments stats
        if ($totalvotes == 1) $votestring = "".translate("vote")."";
                else $votestring = "".translate("votes")."";
        if ($linkratingsummary!="0" || $linkratingsummary!="0.0") echo "<font color=$textcolor1> ".translate("Rating").":<font color=$textcolor2> $linkratingsummary ($totalvotes $votestring)";
        echo "<br><a href=links.$phpEx?op=ratelink&lid=$lid>".translate("Rate this Site")."</a>
               | <a href=links.$phpEx?op=modifylinkrequest&lid=$lid>".translate("Modify")."</a>
                | <a href=links.$phpEx?op=brokenlink&lid=$lid>".translate("Report Broken Link")."</a>";
        if ($totalvotes != 0) echo "&nbsp;|&nbsp;<a href=\"links.$phpEx?op=viewlinkdetails&lid=$lid\">".translate("Details")."</a>";
        if ($totalcomments != 0) echo "&nbsp;|&nbsp;<a href=\"links.$phpEx?op=viewlinkcomments&lid=$lid\">".translate("Comments")." ($totalcomments)</a>";
        $result2=mysql_query("select title from ".$mpnTables['links_categories']." where cid=$cid");
        detecteditorial($lid, $transfertitle);
        echo "<br>";
        list($ctitle) = mysql_fetch_row($result2);
        $ctitle = stripslashes( $ctitle );

        echo "<font color=$textcolor2>".translate("Category: ")."<font color=$textcolor1>$ctitle";
        $result3=mysql_query("select title from ".$mpnTables['links_subcategories']." where sid=$sid");
        while(list($stitle) = mysql_fetch_row($result3)) {
            $stitle = stripslashes( $stitle );
            echo " / <font color=$textcolor1>$stitle";
        }
        echo "<br><br>";
    }
    echo "</TD></TR></TABLE></TD></TR></TABLE>";
    CloseTable();
    include("footer.$phpEx");
}

function TopRated($ratenum, $ratetype) {
    global $admin, $toplinks,$mpnTables,$phpEx, $bgcolor2, $bgcolor3, $textcolor1, $textcolor2, $locale;

    // trini0 [09-17-2003]: Couldn't find a value for this in the config so hardcoding it.
    $linkvotemin = 5;

    include("header.$phpEx");
    logo();
    OpenTable();

    if ($ratenum != "" && $ratetype != "") {
            $toplinks = $ratenum;
            if ($ratetype == "percent") $toplinkspercentrigger = 1;
    }
    if ($ratenum == "") {
        $toplinks = 10;
    }
    if (isset($toplinkspercentrigger) && $toplinkspercentrigger == 1) {
            $toplinkspercent = $toplinks;
            $result=mysql_query("select * from ".$mpnTables['links_links']." where linkratingsummary != 0");
            $totalratedlinks = mysql_num_rows($result);
            $toplinks = $toplinks / 100;
            $toplinks = $totalratedlinks * $toplinks;
            $toplinks = round($toplinks);
    }
    echo "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=8 BORDER=0><TR><TD>";
    echo "<TABLE WIDTH=\"100%\" CELLSPACING=2 CELLPADDING=2 BORDER=0 BGCOLOR=$bgcolor2><TR><TD>";
    if (isset($toplinkspercentrigger) && $toplinkspercentrigger == 1) { echo "<FONT SIZE=3><b><center>".translate("Best Rated Links - Top")." $toplinkspercent% (".translate("of")." $totalratedlinks ".translate("total rated links").")</center></b></font>";}
            else {echo "<FONT SIZE=3><b><center>".translate("Best Rated Links - Top")." $toplinks </center></b></font>";}
    echo "</TR></TD></table>";

    echo "<tr><td><FONT COLOR=$textcolor2><center>".translate("Note").": $linkvotemin ".translate("total votes requirement")."<br>".translate("Show Top").": (<a href=links.$phpEx?op=TopRated&ratenum=10&ratetype=num>10</a>,
                    <a href=links.$phpEx?op=TopRated&ratenum=25&ratetype=num>25</a>,
                    <a href=links.$phpEx?op=TopRated&ratenum=50&ratetype=num>50</a> |
                    <a href=links.$phpEx?op=TopRated&ratenum=1&ratetype=percent>1%</a>,
                    <a href=links.$phpEx?op=TopRated&ratenum=5&ratetype=percent>5%</a>,
                    <a href=links.$phpEx?op=TopRated&ratenum=10&ratetype=percent>10%</a>)</center></font><br><br></td></tr>";

    $result=mysql_query("select lid, cid, sid, title, description, date, hits, linkratingsummary, totalvotes, totalcomments from ".$mpnTables['links_links']." where linkratingsummary != 0 and totalvotes >= '$linkvotemin' order by linkratingsummary DESC limit 0,$toplinks");
    echo "<tr><td>";
    while(list($lid, $cid, $sid, $title, $description, $time, $hits, $linkratingsummary, $totalvotes, $totalcomments)=mysql_fetch_row($result))
    {
//        $linkratingsummary = number_format($linkratingsummary, $mainvotedecimal);
        $linkratingsummary = number_format($linkratingsummary);

        // Kiril: Start New Sanitizer

        $sanity_ary = compact( 'title', 'url', 'description' );
        $_SERVER['SAN'] -> slashIT( $sanity_ary );
        extract( $sanity_ary );
        unset( $sanity_ary );

        // End New Sanitizer

       // $title = stripslashes($title); $description = stripslashes($description);
        echo "<a href=links.$phpEx?op=visit&lid=$lid target=new>$title</a>";
        if (!isset($datetime))
        {
            $datetime = null;
        }

        newlinkgraphic($datetime, $time);
        popgraphic($hits);
        echo "<br>";
        echo "<font color=$textcolor1>".translate("Description: ")."<font color=$textcolor2>$description<br>";
        setlocale (LC_TIME, $locale);
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime);
        $datetime = strftime("".translate("linksdatestring")."", mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
        $datetime = ucfirst($datetime);
        echo "<font color=$textcolor1>".translate("Added on: ")."<font color=$textcolor1>$datetime<font color=$textcolor2> ".translate("Hits: ")."<font color=$textcolor1>$hits";

        $transfertitle = str_replace (" ", "_", $title);
        //voting & comments stats
        if ($totalvotes == 1) $votestring = "".translate("vote")."";
                else $votestring = "".translate("votes")."";
        if ($linkratingsummary!="0" || $linkratingsummary!="0.0") echo "<font color=$textcolor2> ".translate("Rating").":<font color=$textcolor1><b> $linkratingsummary </b>($totalvotes $votestring)";
        echo "<br><a href=links.$phpEx?op=ratelink&lid=$lid>".translate("Rate this Site")."</a>
               | <a href=links.$phpEx?op=modifylinkrequest&lid=$lid>".translate("Modify")."</a>
                | <a href=links.$phpEx?op=brokenlink&lid=$lid>".translate("Report Broken Link")."</a>";
        if ($totalvotes != 0) echo "&nbsp;|&nbsp;<a href=\"links.$phpEx?op=viewlinkdetails&lid=$lid\">".translate("Details")."</a>";
                if ($totalcomments != 0) echo "&nbsp;|&nbsp;<a href=\"links.$phpEx?op=viewlinkcomments&lid=$lid\">".translate("Comments")." ($totalcomments)</a>";
        detecteditorial($lid, $transfertitle);
        echo "<br>";
        $result2=mysql_query("select title from ".$mpnTables['links_categories']." where cid=$cid");
        list($ctitle) = mysql_fetch_row($result2);
        $ctitle = stripslashes( $ctitle );
        echo "<font color=$textcolor2>".translate("Category: ")."<font color=$textcolor1>$ctitle";
        $result3=mysql_query("select title from ".$mpnTables['links_subcategories']." where sid=$sid");
        while(list($stitle) = mysql_fetch_row($result3)) {
            $stitle = stripslashes( $stitle );
            echo " / <font color=$textcolor1>$stitle";
        }
        echo "<br><br>";


    }
    echo "</tr></td>";
    echo "</TD></TR></TABLE>";
    CloseTable();
    include("footer.$phpEx");
}

function MostPopular($ratenum, $ratetype) {
    global $admin, $toplinks,$mpnTables,$phpEx, $bgcolor2, $bgcolor3, $textcolor1, $textcolor2, $locale;
    include("header.$phpEx");
    logo();
    OpenTable();

    if ($ratenum != "" && $ratetype != "") {
            $mostpoplinks = $ratenum;
        if ($ratetype == "percent") $mostpoplinkspercentrigger = 1;
    }
    if ($ratenum == "") {
        $mostpoplinks = $toplinks;
    }
    if (isset($mostpoplinkspercentrigger) && $mostpoplinkspercentrigger == 1) {
            $toplinkspercent = $mostpoplinks;
            $result=mysql_query("select * from ".$mpnTables['links_links']);
            $totalmostpoplinks = mysql_num_rows($result);
            $mostpoplinks = $mostpoplinks / 100;
            $mostpoplinks = $totalmostpoplinks * $mostpoplinks;
            $mostpoplinks = round($mostpoplinks);
    }
    echo "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=8 BORDER=0><TR><TD>";
    echo "<TABLE WIDTH=\"100%\" CELLSPACING=2 CELLPADDING=2 BORDER=0 BGCOLOR=$bgcolor2><TR><TD>";
    if (isset($mostpoplinkspercentrigger) && $mostpoplinkspercentrigger == 1) {echo "<FONT SIZE=3><b><center>".translate("Most Popular - Top")." $toplinkspercent% (".translate("of all")." $totalmostpoplinks ".translate("links").")</center></b>";}
            else {echo "<FONT SIZE=3><b><center>".translate("Most Popular - Top")." $mostpoplinks </center></b>";}
    echo "</TD></TR></TABLE></center><FONT SIZE=2>";
    echo "<tr><td><FONT COLOR=$textcolor1><center>".translate("Show Top").": (<a href=links.$phpEx?op=MostPopular&ratenum=10&ratetype=num>10</a>,
                    <a href=links.$phpEx?op=MostPopular&ratenum=25&ratetype=num>25</a>,
                    <a href=links.$phpEx?op=MostPopular&ratenum=50&ratetype=num>50</a> |
                    <a href=links.$phpEx?op=MostPopular&ratenum=1&ratetype=percent>1%</a>,
                    <a href=links.$phpEx?op=MostPopular&ratenum=5&ratetype=percent>5%</a>,
                    <a href=links.$phpEx?op=MostPopular&ratenum=10&ratetype=percent>10%</a>)</font></center><br><br></td></tr>";

    $result=mysql_query("select lid, cid, sid, title, description, date, hits, linkratingsummary, totalvotes, totalcomments from ".$mpnTables['links_links']." order by hits DESC limit 0,$mostpoplinks");
    echo "<tr><td>";
    while(list($lid, $cid, $sid, $title, $description, $time, $hits, $linkratingsummary, $totalvotes, $totalcomments)=mysql_fetch_row($result))
    {
//        $linkratingsummary = number_format($linkratingsummary, $mainvotedecimal);
        // Kiril: Start New Sanitizer

        $sanity_ary = compact( 'title', 'url', 'description' );
        $_SERVER['SAN'] -> slashIT( $sanity_ary );
        extract( $sanity_ary );
        unset( $sanity_ary );

        // End New Sanitizer

        $linkratingsummary = number_format($linkratingsummary);
        //$title = stripslashes($title); $description = stripslashes($description);
        echo "<a href=links.$phpEx?op=visit&lid=$lid target=new>$title</a>";

        if (!isset($datetime))
        {
            $datetime = null;
        }

        newlinkgraphic($datetime, $time);
        popgraphic($hits);

        echo "<br>";
        echo "<font color=$textcolor2>".translate("Description: ")."<font color=$textcolor1>$description<br>";
        setlocale (LC_TIME, $locale);
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime);
        $datetime = strftime("".translate("linksdatestring")."", mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
        $datetime = ucfirst($datetime);
        echo "<font color=$textcolor2>".translate("Added on: ")."<font color=$textcolor1>$datetime<font color=$textcolor2> ".translate("Hits: ")."<font color=$textcolor1><b>$hits</b>";

        $transfertitle = str_replace (" ", "_", $title);
        //voting & comments stats
        if ($totalvotes == 1) $votestring = "".translate("vote")."";
                else $votestring = "".translate("votes")."";
        if ($linkratingsummary!="0" || $linkratingsummary!="0.0") echo "<font color=$textcolor2> ".translate("Rating").":<font color=$textcolor1> $linkratingsummary ($totalvotes $votestring)";
        echo "<br><a href=links.$phpEx?op=ratelink&lid=$lid>".translate("Rate this Site")."</a>
               | <a href=links.$phpEx?op=modifylinkrequest&lid=$lid>".translate("Modify")."</a>
                | <a href=links.$phpEx?op=brokenlink&lid=$lid>".translate("Report Broken Link")."</a>";
        if ($totalvotes != 0) echo "&nbsp;|&nbsp;<a href=\"links.$phpEx?op=viewlinkdetails&lid=$lid\">".translate("Details")."</a>";
                if ($totalcomments != 0) echo "&nbsp;|&nbsp;<a href=\"links.$phpEx?op=viewlinkcomments&lid=$lid\">".translate("Comments")." ($totalcomments)</a>";
        detecteditorial($lid, $transfertitle);
        echo "<br>";
        $result2=mysql_query("select title from ".$mpnTables['links_categories']." where cid=$cid");
        list($ctitle) = mysql_fetch_row($result2);
        $ctitle = stripslashes( $ctitle );
        echo "<font color=$textcolor2>".translate("Category: ")."<font color=$textcolor1>$ctitle";
        $result3=mysql_query("select title from ".$mpnTables['links_subcategories']." where sid=$sid");
        while(list($stitle) = mysql_fetch_row($result3)) {
            $stitle = stripslashes( $stitle );
            echo " / <font color=$textcolor1>$stitle";
        }
        echo "<br><br>";
    }
    echo "</tr></td>";
    echo "</TD></TR></TABLE>";
    CloseTable();
    include("footer.$phpEx");
}

function RandomLink() {
        global $mpnTables;
    $result = mysql_query("select * from ".$mpnTables['links_links']);
    $numrows = mysql_num_rows($result);
    srand((double)microtime()*1000000);
    $random = rand(1,$numrows);
    $result2 = mysql_query("select url from ".$mpnTables['links_links']." where lid='$random'");
    list($url) = mysql_fetch_row($result2);
    if (is_null($url))
    {
        $_SERVER['F_LIB'] -> redirectRequest( 'links.php' );
        exit;
    }

    mysql_query("update ".$mpnTables['links_links']." set hits=hits+1 where lid=$random");
    $_SERVER['F_LIB'] -> redirectRequest( $url );
}

function viewlink($cid, $min, $orderby, $show) {
    global $admin, $perpage, $mpnTables,$phpEx, $bgcolor2, $bgcolor3, $textcolor1, $textcolor2, $locale;
    include("header.$phpEx");
    logo();
    OpenTable();
    if (!isset($min)) $min=0;
    if (!isset($max)) $max=$min+$perpage;
    if(isset($orderby)) $orderby = convertorderbyin($orderby);
    else $orderby = "title ASC";
    if ($show!="") $perpage = $show;
            else $show=$perpage;

    echo "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=3 BORDER=0><TR><TD>";
    echo "<CENTER>";
    echo "<TABLE WIDTH=\"100%\" CELLSPACING=2 CELLPADDING=2 BORDER=0 BGCOLOR=$bgcolor2><TR><TD>";
    $result=mysql_query("select title, cdescription from ".$mpnTables['links_categories']." where cid=$cid");
    list($title, $cdescription) = mysql_fetch_row($result);
    echo "<font size=3><b><center>".translate("Category: ")."$title</center></b></font><br>$cdescription";
    $carrytitle = $title;
    echo "</TD></TR></TABLE>";
//    $subresult=mysql_query("select sid, title from ".$mpnTables['links_subcategories']." where cid=$cid");
// 20040430 - AvW: present the subcategory titles sorted by title instead of unsorten
    $subresult=mysql_query("select sid, title from ".$mpnTables['links_subcategories']." where cid=$cid order by title asc");
    $numrows = mysql_num_rows($subresult);
    if ($numrows != 0) {
       $scount = 0;
            echo "<center><font size=2>".translate("Links also available in")." $title ".translate("SubCategories").":</font><br>
            <table align=center>
              <tr>";

                while(list($sid, $title) = mysql_fetch_row($subresult)) {
                    $title = stripslashes( $title );
                    $result2 = mysql_query("select * from ".$mpnTables['links_links']." where sid=$sid");
                    $numrows = Mysql_num_rows($result2);
                        echo "<td><a href=links.$phpEx?op=viewslink&sid=$sid>$title</a> ($numrows)&nbsp;&nbsp;</td>";
                        $scount++;
                        if ($scount==6) {
                                echo "</tr><tr>";
                                $scount = 0;
                        }
                }
              echo "
              </tr>
              <tr>
                <td colspan=5></td>
              </tr>
            </table>
            <table width=\"100%\" height=1><tr><td><img src=" . _MPN_ROOT_URI . "images/blackpixel.gif height=1 width=\"100%\"></tr></td>
            </table>
            </center>";

    }
    $orderbyTrans = convertorderbytrans($orderby);
    echo "<center><br><font size=2>".translate("Sort links by").":&nbsp;&nbsp;
          ".translate("Title")." (<a href=links.$phpEx?op=viewlink&cid=$cid&orderby=titleA>A</a>\<a href=links.$phpEx?op=viewlink&cid=$cid&orderby=titleD>D</a>)
          ".translate("Date")." (<a href=links.$phpEx?op=viewlink&cid=$cid&orderby=dateA>A</a>\<a href=links.$phpEx?op=viewlink&cid=$cid&orderby=dateD>D</a>)
          ".translate("Rating")." (<a href=links.$phpEx?op=viewlink&cid=$cid&orderby=ratingA>A</a>\<a href=links.$phpEx?op=viewlink&cid=$cid&orderby=ratingD>D</a>)
          ".translate("Popularity")." (<a href=links.$phpEx?op=viewlink&cid=$cid&orderby=hitsA>A</a>\<a href=links.$phpEx?op=viewlink&cid=$cid&orderby=hitsD>D</a>)
          </font>";
    echo "<b><br><font color=$textcolor2 size=2>".translate("Sites currently sorted by").": $orderbyTrans</font></b></center><br><br>";

    $result=mysql_query("select lid, title, description, date, hits, linkratingsummary, totalvotes, totalcomments from ".$mpnTables['links_links']." where cid=$cid AND sid=0 order by $orderby limit $min,$perpage ");
    $fullcountresult=mysql_query("select lid, title, description, date, hits, linkratingsummary, totalvotes, totalcomments from ".$mpnTables['links_links']." where cid=$cid AND sid=0");
    $totalselectedlinks = Mysql_num_rows($fullcountresult);

    echo "<table width=\"100%\" cellspacing=0 cellpadding=10 border=0><tr><td><font size=2>";
    $x=0;

    while(list($lid, $title, $description, $time, $hits, $linkratingsummary, $totalvotes, $totalcomments)=mysql_fetch_row($result))
    {
//        $linkratingsummary = number_format($linkratingsummary, $mainvotedecimal);
        $linkratingsummary = number_format($linkratingsummary);

        // Kiril: Start New Sanitizer

        $sanity_ary = compact( 'title', 'url', 'description' );
        $_SERVER['SAN'] -> slashIT( $sanity_ary );
        extract( $sanity_ary );
        unset( $sanity_ary );

        // End New Sanitizer

        //$title = stripslashes($title); $description = stripslashes($description);


        if ($admin != "") echo "<a href=admin.$phpEx?op=LinksModLink&lid=$lid><img src=images/links/editicon.gif border=0 Alt=\"".translate("Edit This Link")."\"></a>  ";
        echo "<a href=links.$phpEx?op=visit&lid=$lid target=new>$title</a>";

        if (!isset($datetime))
        {
            $datetime = null;
        }

        newlinkgraphic($datetime, $time);
        popgraphic($hits);
        // INSERT code for *editor review* here
        echo "<br>";
        echo "<font color=$textcolor2>".translate("Description: ")."<font color=$textcolor1>$description<br>";
        setlocale (LC_TIME, $locale);
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime);
        $datetime = strftime("".translate("linksdatestring")."", mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
        $datetime = ucfirst($datetime);
        echo "<font color=$textcolor2>".translate("Added on: ")."<font color=$textcolor1>$datetime<font color=$textcolor2> ".translate("Hits: ")."<font color=$textcolor1>$hits";

        $transfertitle = str_replace (" ", "_", $title);
        //voting & comments stats
        if ($totalvotes == 1) $votestring = "".translate("vote")."";
                else $votestring = "".translate("votes")."";
        if ($linkratingsummary!="0" || $linkratingsummary!="0.0") echo "<font color=$textcolor2> ".translate("Rating").":<font color=$textcolor1> $linkratingsummary ($totalvotes $votestring)";
        echo "<br><a href=links.$phpEx?op=ratelink&lid=$lid>".translate("Rate this Site")."</a>
               | <a href=links.$phpEx?op=modifylinkrequest&lid=$lid>".translate("Modify")."</a>
                | <a href=links.$phpEx?op=brokenlink&lid=$lid>".translate("Report Broken Link")."</a>";
        if ($totalvotes != 0) echo "&nbsp;|&nbsp;<a href=\"links.$phpEx?op=viewlinkdetails&lid=$lid\">".translate("Details")."</a>";
        if ($totalcomments != 0) echo "&nbsp;|&nbsp;<a href=\"links.$phpEx?op=viewlinkcomments&lid=$lid\">".translate("Comments")." ($totalcomments)</a>";
        detecteditorial($lid, $transfertitle);
        echo "<br><br>";

        $x++;
    }

    $orderby = convertorderbyout($orderby);

    //Calculates how many pages exist.  Which page one should be on, etc...

    # echo "Count Result:  $totalselectedlinks<br>";                        # testing lines
    $linkpagesint = ($totalselectedlinks / $perpage);
    $linkpageremainder = ($totalselectedlinks % $perpage);

    if ($linkpageremainder != 0) {
            $linkpages = ceil($linkpagesint);
            if ($totalselectedlinks < $perpage) {
                    $linkpageremainder = 0;
            }
    }
    else {
            $linkpages = $linkpagesint;
    }
    //Page Numbering
    if ($linkpages!=1 && $linkpages!=0) {
        echo "<br><br>";
              echo "".translate("Select page").":&nbsp;&nbsp;";
             $prev=$min-$perpage;
             if ($prev>=0) {
                    echo "&nbsp;<a href=links.$phpEx?op=viewlink&cid=$cid&min=$prev&orderby=$orderby&show=$show>";
                    echo "<b>[&lt;&lt; ".translate("Previous")." ]</b></a>&nbsp;";
          }
            $counter = 1;
         $currentpage = ($max / $perpage);
               while ($counter<=$linkpages ) {
                      $cpage = $counter;
                      $mintemp = ($perpage * $counter) - $perpage;
                      if ($counter == $currentpage) echo "<b>$counter</b>&nbsp;";
                      else echo "<a href=links.$phpEx?op=viewlink&cid=$cid&min=$mintemp&orderby=$orderby&show=$show>$counter</a>&nbsp;";
                           $counter++;

            }
             $next=$min+$perpage;
             if ($x>=$perpage) {
                    echo "&nbsp;<a href=links.$phpEx?op=viewlink&cid=$cid&min=$max&orderby=$orderby&show=$show>";
                    echo "<b>[ ".translate("Next")." &gt;&gt;]</b></a>";
             }
    }
    /*
    echo "<font color=BBBBBB size=2><br><br>
    ".translate("Total links in category")." - $carrytitle (".translate("not including subcategories")."): $totalselectedlinks<br>
    ".translate("Set links per page (current:")." $perpage):&nbsp;
    <a href=links.$phpEx?op=viewlink&cid=$cid&orderby=$orderby&show=5>5</a>&nbsp;
    <a href=links.$phpEx?op=viewlink&cid=$cid&orderby=$orderby&show=10>10</a>&nbsp;
    <a href=links.$phpEx?op=viewlink&cid=$cid&orderby=$orderby&show=15>15</a>&nbsp;
    <a href=links.$phpEx?op=viewlink&cid=$cid&orderby=$orderby&show=25>25</a>&nbsp;
    <a href=links.$phpEx?op=viewlink&cid=$cid&orderby=$orderby&show=50>50</a>&nbsp;
    <a href=links.$phpEx?op=viewlink&cid=$cid&orderby=$orderby&show=75>75</a>&nbsp;
    <a href=links.$phpEx?op=viewlink&cid=$cid&orderby=$orderby&show=10000>".translate("Show All")."</a></font>";
    */


    echo "</TD></TR></TABLE></TD></TR></TABLE>";
    CloseTable();
    include("footer.$phpEx");
}


function viewslink($sid, $min, $orderby, $show) {
    global $admin, $perpage, $mpnTables,$phpEx, $bgcolor2, $bgcolor3, $textcolor1, $textcolor2;
    include("header.$phpEx");
    logo();
    OpenTable();

    if (!isset($min)) $min=0;
    if (!isset($max)) $max=$min+$perpage;
    if(isset($orderby)) $orderby = convertorderbyin($orderby);
    else $orderby = "title ASC";
    if ($show!="") $perpage = $show;
            else $show=$perpage;

    echo "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=3 BORDER=0><TR><TD>";
    echo "<CENTER>";
    echo "<TABLE WIDTH=\"100%\" CELLSPACING=2 CELLPADDING=2 BORDER=0 BGCOLOR=$bgcolor2><TR><TD>";

    $result = mysql_query("select cid, title from ".$mpnTables['links_subcategories']." where sid=$sid");
    list($cid, $stitle) = mysql_fetch_row($result);

    $result2 = mysql_query("select cid, title from ".$mpnTables['links_categories']." where cid=$cid");
    list($cid, $title) = mysql_fetch_row($result2);

    echo "<font size=3><b><a href=links.$phpEx><center>".translate("Main")."</a> / <a href=links.$phpEx?op=viewlink&cid=$cid>$title</a> / $stitle</center></b>";
    echo "</TD></TR></TABLE>";

    $orderbyTrans = convertorderbytrans($orderby);
        echo "</center><br><font size=2><center>".translate("Sort links by").":&nbsp;&nbsp;
              ".translate("Title")." (<a href=links.$phpEx?op=viewslink&sid=$sid&orderby=titleA>A</a>\<a href=links.$phpEx?op=viewslink&sid=$sid&orderby=titleD>D</a>)
              ".translate("Date")." (<a href=links.$phpEx?op=viewslink&sid=$sid&orderby=dateA>A</a>\<a href=links.$phpEx?op=viewslink&sid=$sid&orderby=dateD>D</a>)
              ".translate("Rating")." (<a href=links.$phpEx?op=viewslink&sid=$sid&orderby=ratingA>A</a>\<a href=links.$phpEx?op=viewslink&sid=$sid&orderby=ratingD>D</a>)
              ".translate("Popularity")." (<a href=links.$phpEx?op=viewslink&sid=$sid&orderby=hitsA>A</a>\<a href=links.$phpEx?op=viewslink&sid=$sid&orderby=hitsD>D</a>)
              </font>";
    echo "<b><br><font color=$textcolor2 size=2>".translate("Sites currently sorted by").": $orderbyTrans</font></b></center><br><br>";

    $result=mysql_query("select lid, url, title, description, date, hits, linkratingsummary, totalvotes, totalcomments from ".$mpnTables['links_links']." where sid=$sid order by $orderby limit $min,$perpage");
    $fullcountresult=mysql_query("select lid, title, description, date, hits, linkratingsummary, totalvotes, totalcomments from ".$mpnTables['links_links']." where sid=$sid");
    $totalselectedlinks = Mysql_num_rows($fullcountresult);

    echo "<table width=\"100%\" cellspacing=0 cellpadding=10 border=0><tr><td><font size=2>";
    $x=0;

    if (!isset( $mainvotedecimal ))
    {
        $mainvotedecimal = null;
    }

    if (!isset( $datetime ))
    {
        $datetime = null;
    }

    while(list($lid, $url, $title, $description, $time, $hits, $linkratingsummary, $totalvotes, $totalcomments)=mysql_fetch_row($result))
    {
        $linkratingsummary = number_format($linkratingsummary, $mainvotedecimal);

        // Kiril: Start New Sanitizer

        $sanity_ary = compact( 'title', 'url', 'description' );
        $_SERVER['SAN'] -> slashIT( $sanity_ary );
        extract( $sanity_ary );
        unset( $sanity_ary );

        // End New Sanitizer

        //$title = stripslashes($title); $description = stripslashes($description);

                if ($admin != "") echo "<a href=admin.$phpEx?op=LinksModLink&lid=$lid><img src=images/links/editicon.gif border=0 Alt=\"".translate("Edit This Link")."\"></a>  ";
        echo "<a href=links.$phpEx?op=visit&lid=$lid target=new>$title</a>";
        newlinkgraphic($datetime, $time);
        popgraphic($hits);
        // code for *editor review* insert here
        echo "<br>";
        echo "<font color=$textcolor2>".translate("Description: ")."<font color=$textcolor1>$description<br>";
        setlocale (LC_TIME, "$locale");
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime);
        $datetime = strftime("".translate("linksdatestring")."", mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
        $datetime = ucfirst($datetime);
        echo "<font color=$textcolor2>".translate("Added on: ")."<font color=$textcolor1>$datetime<font color=$textcolor2> ".translate("Hits: ")."<font color=$textcolor1>$hits";

        $transfertitle = str_replace(" ", "_", $title);
        //voting & comments stats
        if ($totalvotes == 1) $votestring = "".translate("vote")."";
                else $votestring = "".translate("votes")."";
        if ($linkratingsummary!="0" || $linkratingsummary!="0.0") echo "<font color=$textcolor2> ".translate("Rating").":<font color=$textcolor1> $linkratingsummary ($totalvotes $votestring)";
        echo "<br><a href=links.$phpEx?op=ratelink&lid=$lid>".translate("Rate this Site")."</a>
               | <a href=links.$phpEx?op=modifylinkrequest&lid=$lid>".translate("Modify")."</a>
                | <a href=links.$phpEx?op=brokenlink&lid=$lid>".translate("Report Broken Link")."</a>";
        if ($totalvotes != 0) echo "&nbsp;|&nbsp;<a href=\"links.$phpEx?op=viewlinkdetails&lid=$lid\">".translate("Details")."</a>";
        if ($totalcomments != 0) echo "&nbsp;|&nbsp;<a href=\"links.$phpEx?op=viewlinkcomments&lid=$lid\">".translate("Comments")." ($totalcomments)</a>";
        detecteditorial($lid, $transfertitle);
        echo "<br><br>";

        $x++;
    }

     $orderby = convertorderbyout($orderby);

    //Calculates how many pages exist.  Which page one should be on, etc...

        # echo "Count Result:  $totalselectedlinks<br>";                        # testing lines
        $linkpagesint = ($totalselectedlinks / $perpage);
        $linkpageremainder = ($totalselectedlinks % $perpage);

        if ($linkpageremainder != 0) {
                $linkpages = ceil($linkpagesint);
                if ($totalselectedlinks < $perpage) {
                        $linkpageremainder = 0;
                }
        }
        else {
                $linkpages = $linkpagesint;
        }
        //Page Numbering
        if ($linkpages!=1 && $linkpages!=0) {
            echo "<br><br>";
                  echo "".translate("Select page").":&nbsp;&nbsp;";
                 $prev=$min-$perpage;
                 if ($prev>=0) {
                        echo "&nbsp;<a href=links.$phpEx?op=viewslink&sid=$sid&min=$prev&orderby=$orderby&show=$show>";
                        echo "<b>[&lt;&lt; ".translate("Previous")." ]</b></a>&nbsp;";
              }

                $counter = 1;
                $currentpage = ($max / $perpage);
                   while ($counter<=$linkpages ) {
                          $cpage = $counter;
                          $mintemp = ($perpage * $counter) - $perpage;
                          if ($counter == $currentpage) echo "<b>$counter</b>&nbsp;";
                          else echo "<a href=links.$phpEx?op=viewslink&sid=$sid&min=$mintemp&orderby=$orderby&show=$show>$counter</a>&nbsp;";
                               $counter++;
                }
                 $next=$min+$perpage;
                 if ($x>=$perpage) {
                        echo "&nbsp;<a href=links.$phpEx?op=viewslink&sid=$sid&min=$max&orderby=$orderby&show=$show>";
                        echo "<b>[ ".translate("Next")." &gt;&gt;]</b></a>";
                 }
        }

    /*
    echo "<font color=BBBBBB size=2><br><br>
    ".translate("Total links in subcategory")." - $stitle: $totalselectedlinks<br>
    ".translate("Set links per page (current:")." $perpage):&nbsp;
    <a href=links.$phpEx?op=viewslink&sid=$sid&orderby=$orderby&show=5>5</a>&nbsp;
    <a href=links.$phpEx?op=viewslink&sid=$sid&orderby=$orderby&show=10>10</a>&nbsp;
    <a href=links.$phpEx?op=viewslink&sid=$sid&orderby=$orderby&show=15>15</a>&nbsp;
    <a href=links.$phpEx?op=viewslink&sid=$sid&orderby=$orderby&show=25>25</a>&nbsp;
    <a href=links.$phpEx?op=viewslink&sid=$sid&orderby=$orderby&show=50>50</a>&nbsp;
    <a href=links.$phpEx?op=viewslink&sid=$sid&orderby=$orderby&show=75>75</a>&nbsp;
    <a href=links.$phpEx?op=viewslink&sid=$sid&orderby=$orderby&show=10000>".translate("Show All")."</a></font>";
    */

    echo "</TD></TR></TABLE></TD></TR></TABLE>";
    CloseTable();
    include("footer.$phpEx");
}

function newlinkgraphic($datetime, $time) {
        global $locale;

        echo "&nbsp;";
        setlocale (LC_TIME, $locale);
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime);
        $datetime = strftime("".translate("linksdatestring")."", mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
        $datetime = ucfirst($datetime);
        $startdate = time();
        $count = 0;
        while ($count <= 7) {
                    $daysold = date("d-M-Y", $startdate);
                   if ("$daysold" == "$datetime") {
                           if ($count<=1) echo "<img src = images/links/newred.gif alt=\"".translate("New Today")."\">";
                           if ($count<=3 && $count>1) echo "<img src = images/links/newgreen.gif alt=\"".translate("New last 3 days")."\">";
                           if ($count<=7 && $count>3) echo "<img src = images/links/newblue.gif alt=\"".translate("New this week")."\">";
                   }
                   $count++;
                   $startdate = (time()-(86400 * $count));
        }
}

function categorynewlinkgraphic($cat) {
        global $mpnTables, $locale;
        $newresult = mysql_query("select date from ".$mpnTables['links_links']." where cid=$cat order by date desc limit 1");
        list($time)=mysql_fetch_row($newresult);
        echo "&nbsp;";
        setlocale (LC_TIME, $locale);
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime);
        $datetime = strftime("".translate("linksdatestring")."", mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
        $datetime = ucfirst($datetime);
        $startdate = time();
        $count = 0;
        while ($count <= 7) {
                    $daysold = date("d-M-Y", $startdate);
                   if ("$daysold" == "$datetime") {
                           if ($count<=1) echo "<img src = images/links/newred.gif alt=\"".translate("New Links in this Category Added Today")."\">";
                           if ($count<=3 && $count>1) echo "<img src = images/links/newgreen.gif alt=\"".translate("New Links in this Category Added in the last 3 days")."\">";
                           if ($count<=7 && $count>3) echo "<img src = images/links/newblue.gif alt=\"".translate("New Links in this Category Added this week")."\">";
                   }
                   $count++;
                   $startdate = (time()-(86400 * $count));
        }
}

function popgraphic($hits) {
        global $popular;
        if ($hits>=$popular) {
        echo "&nbsp;<img src = images/links/pop.gif alt=\"".translate("Popular")."\">";
        }
}

//Reusable Link Sorting Functions
function convertorderbyin($orderby) {
        if ($orderby == "titleA")                        $orderby = "title ASC";
        if ($orderby == "dateA")                        $orderby = "date ASC";
        if ($orderby == "hitsA")                        $orderby = "hits ASC";
        if ($orderby == "ratingA")                        $orderby = "linkratingsummary ASC";
        if ($orderby == "titleD")                        $orderby = "title DESC";
            if ($orderby == "dateD")                        $orderby = "date DESC";
            if ($orderby == "hitsD")                        $orderby = "hits DESC";
        if ($orderby == "ratingD")                        $orderby = "linkratingsummary DESC";
        return $orderby;
}

function convertorderbytrans($orderby) {
        if ($orderby == "hits ASC")                        $orderbyTrans = "".translate("Popularity (Least to Most Hits)")."";
        if ($orderby == "hits DESC")                        $orderbyTrans = "".translate("Popularity (Most to Least Hits)")."";
        if ($orderby == "title ASC")                        $orderbyTrans = "".translate("Title (A to Z)")."";
        if ($orderby == "title DESC")                        $orderbyTrans = "".translate("Title (Z to A)")."";
        if ($orderby == "date ASC")                        $orderbyTrans = "".translate("Date (Old Links Listed First)")."";
        if ($orderby == "date DESC")                        $orderbyTrans = "".translate("Date (New Links Listed First)")."";
        if ($orderby == "linkratingsummary ASC")        $orderbyTrans = "".translate("Rating (Lowest Scores to Highest Scores)")."";
        if ($orderby == "linkratingsummary DESC")        $orderbyTrans = "".translate("Rating (Highest Scores to Lowest Scores)")."";
        return $orderbyTrans;
}

function convertorderbyout($orderby) {
               if ($orderby == "title ASC")                        $orderby = "titleA";
               if ($orderby == "date ASC")                        $orderby = "dateA";
               if ($orderby == "hits ASC")                        $orderby = "hitsA";
               if ($orderby == "linkratingsummary ASC")        $orderby = "ratingA";
               if ($orderby == "title DESC")                        $orderby = "titleD";
             if ($orderby == "date DESC")                        $orderby = "dateD";
             if ($orderby == "hits DESC")                        $orderby = "hitsD";
               if ($orderby == "linkratingsummary DESC")        $orderby = "ratingD";
        return $orderby;
}

function visit($lid) {
        global $mpnTables;
    mysql_query("update ".$mpnTables['links_links']." set hits=hits+1 where lid=$lid");
    $result = mysql_query("select url from ".$mpnTables['links_links']." where lid=$lid");
    list($url) = mysql_fetch_row($result);
    $_SERVER['F_LIB'] -> redirectRequest( $url );
}

function searchlink($query, $min, $orderby, $show) {
    global $admin, $perpage, $show, $linksresults, $mpnTables,$phpEx, $bgcolor2, $bgcolor3, $textcolor1, $textcolor2;
    if (!isset($min)) $min=0;
    if (!isset($max)) $max=$min+$linksresults;
    if(isset($orderby)) $orderby = convertorderbyin($orderby);
    else $orderby = "title ASC";
    if ($show!="") $linksresults = $show;
            else $show=$linksresults;

    $query = stripslashes($query);

    $result = mysql_query("select lid, cid, sid, title, url, description, date, hits, linkratingsummary, totalvotes, totalcomments from ".$mpnTables['links_links']." where title LIKE '%$query%' OR description LIKE '%$query%' ORDER BY $orderby LIMIT $min,$linksresults");

    $nrows  = mysql_num_rows($result);

    $fullcountresult=mysql_query("select lid, title, description, date, hits, linkratingsummary, totalvotes, totalcomments from ".$mpnTables['links_links']." where title LIKE '%$query%' OR description LIKE '%$query%' ");

    $totalselectedlinks = Mysql_num_rows($fullcountresult);

    $resultx = mysql_query("select * from ".$mpnTables['links_subcategories']." where title LIKE '%$query%' ORDER BY title DESC");

    $nrowsx  = mysql_num_rows($resultx);

    $x=0;

    include("header.$phpEx");
    logo();
    OpenTable();

    echo "
    <TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=8 BORDER=0><TR><TD><font size=2>
    <CENTER>";
    if ($query != "") {
            if ($nrows>0 OR $nrowsx>0) {

                $result2 = mysql_query("select cid, sid, title from ".$mpnTables['links_subcategories']." where title LIKE '%$query%' ORDER BY title DESC");
                echo "<font size=3>".translate("Search Results for: ")."<font color=$textcolor2>$query<font color=$textcolor1 size=2><br><br>";
                echo "</center><table width=\"100%\" bgcolor=$bgcolor2><tr><td><font size=3><b>".translate("SubCategories")."</b></td></tr></table>";
                while(list($cid, $sid, $stitle) = mysql_fetch_row($result2))
                {
                    $cate = mysql_query("select title from ".$mpnTables['links_categories']." where cid=$cid");
                    list($ctitle) = mysql_fetch_row($cate);

                    $ctitle = stripslashes( $ctitle );
                    $stitle = stripslashes( $stitle );

                    $res = mysql_query("select * from ".$mpnTables['links_links']." where sid=$sid");
                    $numrows = mysql_num_rows($res);
                    $ctitle = ereg_replace($query, "<b>$query</b>", $ctitle);
                    $stitle = ereg_replace($query, "<b>$query</b>", $stitle);
                    echo "<li><a href=links.$phpEx?op=viewslink&sid=$sid>$ctitle / $stitle</a> ($numrows)<br>";
                }

                echo "<br><table width=\"100%\" bgcolor=$bgcolor2><tr><td><font size=3><b>".translate("Links")."</b></td></tr></table>";
            $orderbyTrans = convertorderbytrans($orderby);
                echo "</center><br><font size=2>".translate("Sort links by").":&nbsp;&nbsp;
                      ".translate("Title")." (<a href=links.$phpEx?op=search&query=$query&orderby=titleA>A</a>\<a href=links.$phpEx?op=search&query=$query&orderby=titleD>D</a>)
                      ".translate("Date")." (<a href=links.$phpEx?op=search&query=$query&orderby=dateA>A</a>\<a href=links.$phpEx?op=search&query=$query&orderby=dateD>D</a>)
                      ".translate("Rating")." (<a href=links.$phpEx?op=search&query=$query&orderby=ratingA>A</a>\<a href=links.$phpEx?op=search&query=$query&orderby=ratingD>D</a>)
                      ".translate("Popularity")." (<a href=links.$phpEx?op=search&query=$query&orderby=hitsA>A</a>\<a href=links.$phpEx?op=search&query=$query&orderby=hitsD>D</a>)
                      </font>";
            echo "<b><br><font color=$textcolor2 size=2>".translate("Sites currently sorted by").": $orderbyTrans</font></b><br><br>";
                $result = mysql_query("select lid, cid, sid, title, url, description, date, hits, linkratingsummary, totalvotes, totalcomments from ".$mpnTables['links_links']." where title LIKE '%$query%' OR description LIKE '%$query%' ORDER BY $orderby LIMIT $min,$linksresults");

                if (!isset( $mainvotedecimal ))
                {
                    $mainvotedecimal = null;
                }

                if (!isset( $datetime ))
                {
                    $datetime = null;
                }

                while(list($lid, $cid, $sid, $title, $url, $description, $time, $hits, $linkratingsummary, $totalvotes, $totalcomments) = mysql_fetch_row($result))
                {
                    $linkratingsummary = number_format($linkratingsummary, $mainvotedecimal);

                    // Kiril: Start New Sanitizer

                    $sanity_ary = compact( 'title', 'url', 'description' );
                    $_SERVER['SAN'] -> slashIT( $sanity_ary );
                    extract( $sanity_ary );
                    unset( $sanity_ary );

                    // End New Sanitizer

                    //$title = stripslashes($title); $description = stripslashes($description);

                    $transfertitle = str_replace (" ", "_", $title);
                    $title = ereg_replace($query, "<b>$query</b>", $title);
                                if ($admin != "") echo "<a href=admin.$phpEx?op=LinksModLink&lid=$lid><img src=images/links/editicon.gif border=0 Alt=\"".translate("Edit This Link")."\"></a>  ";
                    echo "<a href=links.$phpEx?op=visit&lid=$lid target=new>$title</a>";
                    newlinkgraphic($datetime, $time);
                    popgraphic($hits);
                    echo "<br>";
                    $description = ereg_replace($query, "<b>$query</b>", $description);
                    echo "<font color=$textcolor2>".translate("Description: ")."<font color=$textcolor1>$description<br>";
                    setlocale (LC_TIME, "$locale");
                    ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime);
                    $datetime = strftime("".translate("linksdatestring")."", mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
                    $datetime = ucfirst($datetime);
                    echo "<font color=$textcolor2>".translate("Added on: ")."<font color=$textcolor1>$datetime<font color=$textcolor2> ".translate("Hits: ")."<font color=$textcolor1>$hits";

                //voting & comments stats
                if ($totalvotes == 1) $votestring = "".translate("vote")."";
                        else $votestring = "".translate("votes")."";
                if ($linkratingsummary!="0" || $linkratingsummary!="0.0") echo "<font color=$textcolor2> ".translate("Rating").":<font color=$textcolor1> $linkratingsummary ($totalvotes $votestring)";
                echo "<br><a href=links.$phpEx?op=ratelink&lid=$lid>".translate("Rate this Site")."</a>
                               | <a href=links.$phpEx?op=modifylinkrequest&lid=$lid>".translate("Modify")."</a>
                                | <a href=links.$phpEx?op=brokenlink&lid=$lid>".translate("Report Broken Link")."</a>";
                if ($totalvotes != 0) echo "&nbsp;|&nbsp;<a href=links.$phpEx?op=viewlinkdetails&lid=$lid>".translate("Details")."</a>";
                if ($totalcomments != 0) echo "&nbsp;|&nbsp;<a href=links.$phpEx?op=viewlinkcomments&lid=$lid>".translate("Comments")." ($totalcomments)</a>";
                detecteditorial($lid, $transfertitle);
                echo "<br>";
                    $result3 = mysql_query("select title from ".$mpnTables['links_categories']." where cid=$cid");
                    $result4 = mysql_query("select title from ".$mpnTables['links_subcategories']." where sid=$sid");
                    list($ctitle) = mysql_fetch_row($result3);
                    list($stitle) = mysql_fetch_row($result4);

                    $ctitle = stripslashes( $ctitle );
                    $stitle = stripslashes( $stitle );

                    if ($stitle=="") {
                        $slash = "";
                    } else {
                        $slash = "/";
                    }
                    echo "<font color=$textcolor2>".translate("Category: ")."<font color=$textcolor1>$ctitle $slash $stitle<br><br>";
                    $x++;

                }
                $orderby = convertorderbyout($orderby);

            } else {
                echo "<center><font color=$textcolor2 size=3>".translate("No matches found to your query")."</font></center><br><br>";
            }


    //Calculates how many pages exist.  Which page one should be on, etc...

        # echo "Count Result:  $totalselectedlinks<br>";                        # testing lines
        $linkpagesint = ($totalselectedlinks / $linksresults);
        $linkpageremainder = ($totalselectedlinks % $linksresults);

        if ($linkpageremainder != 0) {
                $linkpages = ceil($linkpagesint);
                if ($totalselectedlinks < $linksresults) {
                        $linkpageremainder = 0;
                }
        }
        else {
                $linkpages = $linkpagesint;
        }
        //Page Numbering
        if ($linkpages!=1 && $linkpages!=0) {
            echo "<br><br>";
                  echo "Select page:&nbsp;&nbsp;";
                 $prev=$min-$linksresults;
                 if ($prev>=0) {
                        echo "&nbsp;<a href=links.$phpEx?op=search&query=$query&min=$prev&orderby=$orderby&show=$show>";
                        echo "<b>[&lt;&lt; ".translate("Previous")." ]</b></a>&nbsp;";
              }

                $counter = 1;
                $currentpage = ($max / $linksresults);
                   while ($counter<=$linkpages ) {
                          $cpage = $counter;
                          $mintemp = ($perpage * $counter) - $linksresults;
                          if ($counter == $currentpage) echo "<b>$counter</b>&nbsp;";
                          else echo "<a href=links.$phpEx?op=search&query=$query&min=$mintemp&orderby=$orderby&show=$show>$counter</a>&nbsp;";
                               $counter++;
                }
                 $next=$min+$linksresults;
                 if ($x>=$perpage) {
                        echo "&nbsp;<a href=links.$phpEx?op=search&query=$query&min=$max&orderby=$orderby&show=$show>";
                        echo "<b>[ ".translate("Next")." &gt;&gt;]</b></a>";
                 }
        }

    echo "<br><br><center><font size=2>
    ".translate("Try to search")." \"$query\" ".translate("in others Search Engines")."<br>
    <a target=\"_blank\" href=\"http://www.altavista.com/cgi-bin/query?pg=q&sc=on&hl=on&act=2006&par=0&q=$query&kl=XX&stype=stext\">Alta Vista</a> -
    <a target=\"_blank\" href=\"http://www.hotbot.com/?MT=$query&DU=days&SW=web\">HotBot</a> -
    <a target=\"_blank\" href=\"http://www.dejanews.com/dnquery.xp?QRY=$query\">Deja News</a> -
    <a target=\"_blank\" href=\"http://www.lycos.com/cgi-bin/pursuit?query=$query&maxhits=20\">Lycos</a> -
    <a target=\"_blank\" href=\"http://search.yahoo.com/bin/search?p=$query\">Yahoo</a>
    <br>
    <a target=\"_blank\" href=\"http://search.1stlinuxsearch.com/compass?scope=$query&ui=sr\">1stLinuxSearch</a> -
    <a target=\"_blank\" href=\"http://www.google.com/search?q=$query\">Google</a> -
    <a target=\"_blank\" href=\"http://freshmeat.net/search/?q=$query&section=projects&x=7&y=4\">Freshmeat</a> -
    <a target=\"_blank\" href=\"http://www.justlinux.com/forum/search.php\">JustLinux</a>
    </font>";


    } else {
         echo "<center><font color=$textcolor2 size=3>".translate("No matches found to your query")."</font></center><br><br>";
    }

    echo "</td></tr></table>\n";
    CloseTable();
    include("footer.$phpEx");

}

//POSSIBLY split file here (rating stuff in new file?)

function viewlinkeditorial($lid) {

    global $admin, $mpnTables,$phpEx, $bgcolor2, $bgcolor3, $textcolor1, $textcolor2;

    $ttitle = getTitle( $lid , translate( 'Editorial For' ) );

    include("header.$phpEx");
    logo();
    OpenTable();


    $result=mysql_query("SELECT adminid, editorialtimestamp, editorialtext, editorialtitle FROM ".$mpnTables['links_editorials']." WHERE linkid = $lid");
    $recordexist = Mysql_num_rows($result);

    echo "<table align=center border=0 cellspacing=0 cellpadding=2 width=98%>";
    $transfertitle = ereg_replace ("_", " ", $ttitle);
    $displaytitle = $transfertitle;
    echo "

          <tr><td>
            <TABLE WIDTH=\"100%\" CELLSPACING=2 CELLPADDING=2 BORDER=0 BGCOLOR=$bgcolor2><TR><TD>
               <center><FONT SIZE=3><b>".translate("Link Profile").":  $displaytitle</b></font></center>
            </tr></td></table>
          </td></tr>
          <tr><td>";
    echo "<center>";
    linkinfomenu($lid);
    echo "</center><br>
          </td><tr>
          <tr><td>";

    if ($recordexist != 0) {
            while(list($adminid, $editorialtimestamp, $editorialtext, $editorialtitle)=mysql_fetch_row($result)) {
                    $editorialtitle = stripslashes($editorialtitle); $editorialtext = stripslashes($editorialtext);
                    ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $editorialtimestamp, $editorialtime);
                $editorialtime = strftime("%F",mktime($editorialtime[4],$editorialtime[5],$editorialtime[6],$editorialtime[2],$editorialtime[3],$editorialtime[1]));
                $date_array = explode("-", $editorialtime);
                $timestamp = mktime(0, 0, 0, $date_array["1"], $date_array["2"], $date_array["0"]);
                       $formatted_date = date("F j, Y", $timestamp);
                    echo "<tr><td>
                          <table align=center border=1 bordercolor=$bgcolor3 cellpadding=7 cellspacing=0 width=400>
                          <tr><td>
                          <center><font size=3><b>'$editorialtitle'</b></font></center>
                          <center><font size=1>".translate("Editorial by")." $adminid - $formatted_date</font></center><br><br>
                          $editorialtext
                          <br><br>
                          </td></tr></table>
                      </td></tr>";
            }
    }
    else {
            echo "<br><br><center>".translate("No editorial is currently available for this website.")."</center><br>";
    }
    echo "</table><br><br>";
    linkfooter($lid);
    CloseTable();
    include("footer.$phpEx");

}

function detecteditorial($lid) {
        global $mpnTables,$phpEx;
    $resulted2 = mysql_query("select adminid from ".$mpnTables['links_editorials']." where linkid=$lid");
    $recordexist = Mysql_num_rows($resulted2);
    // if returns 'bad query' status 0 (add editorial)
    if ($recordexist != 0) echo " | <a href=links.$phpEx?op=viewlinkeditorial&lid=$lid>Editorial</a>";

}

function viewlinkcomments($lid) {
    global $admin, $mpnTables,$phpEx, $bgcolor2, $bgcolor3, $textcolor1, $textcolor2;

    $ttitle = getTitle( $lid , translate( 'Comments For' ) );

    include("header.$phpEx");
    logo();
    OpenTable();


    $result=mysql_query("SELECT ratinguser, rating, ratingcomments, ratingtimestamp FROM ".$mpnTables['links_votedata']." WHERE ratinglid = $lid AND ratingcomments != '' ORDER BY ratingtimestamp DESC");
    $totalcomments = Mysql_num_rows($result);

    echo "<table align=center border=0 cellspacing=0 cellpadding=2 width=98%>";

    $transfertitle = ereg_replace ("_", " ", $ttitle);
    $displaytitle = $transfertitle;
    echo "

          <tr><td>
            <TABLE WIDTH=\"100%\" CELLSPACING=2 CELLPADDING=2 BORDER=0 BGCOLOR=$bgcolor2><TR><TD>
               <center><FONT SIZE=3><b>".translate("Link Profile").":  $displaytitle</b></font></center>
            </tr></td></table>
          </td></tr>
          <tr><td>";
    echo "<center>";
    linkinfomenu($lid);
    echo "</center><br>
          </td><tr>
          <tr><td>";
    echo "<br><center>".translate("Total of")." $totalcomments ".translate("comments")."</center></font><br>";
    echo "<table align=center border=0 cellspacing=0 cellpadding=2 width=450>";

    $x=0;
    while(list($ratinguser, $rating, $ratingcomments, $ratingtimestamp)=mysql_fetch_row($result)) {
            $ratingcomments = stripslashes($ratingcomments);
            $ratinguser = stripslashes($ratinguser);

        $formatted_date = $datetime = strftime( translate( 'datestring4' ) , strtotime( $ratingtimestamp ) );

        //Individual user information

        $result2=mysql_query("SELECT rating FROM ".$mpnTables['links_votedata']." WHERE ratinguser = '$ratinguser'");
        $usertotalcomments = Mysql_num_rows($result2);
        $useravgrating = 0;
        while(list($rating2)=mysql_fetch_row($result2))        $useravgrating = $useravgrating + $rating2;
        $useravgrating = $useravgrating / $usertotalcomments;
        $useravgrating = number_format($useravgrating, 1);


            echo "<tr>
                    <td bgcolor=$bgcolor2>
                           <font size=2><B> ".translate("User").":  </b><a href=" . _MPN_ROOT_URI . "user.$phpEx?op=userinfo&uname=$ratinguser>$ratinguser</a></font>
                </td>
                <td bgcolor=$bgcolor2>
                <font size=2><B>".translate("Rating").":  </b>$rating</font>
                </td>
                <td bgcolor=$bgcolor2 align=right>
                           <font size=2>$formatted_date</font>
                </td>
              </tr>
              <tr height=1>
                <td valign=top>
                       <font size=1 color=$textcolor2>".translate("User's Average Rating").": $useravgrating</font>
                </td>
                <td valign=top height=1 colspan=2>
                <font size=1 color=$textcolor2>".translate("# of Ratings").": $usertotalcomments</font>
                </td>
              </tr>

              <tr>
                <td colspan=3>
                <font size=2>";
        if ($admin !="") echo "<a href=admin.$phpEx?op=LinksModLink&lid=$lid><img src=images/links/editicon.gif border=0 Alt=\"".translate("Edit This Link")."\"></a>";
        echo" $ratingcomments</font>";

        echo "  <br><br><br>
                </td>
              </tr>";
        $x++;
    }

    echo "</table></table><br><br>";
    linkfooter($lid);
    CloseTable();
    include("footer.$phpEx");

}

function viewlinkdetails($lid) {
    global $admin, $anonymus, $mpnTables,$phpEx, $bgcolor2, $bgcolor3, $textcolor1, $textcolor2;

    $ttitle = getTitle( $lid , translate( 'Details For' ) );

    include("header.$phpEx");
    logo();
    OpenTable();


    $voteresult = mysql_query("select rating, ratinguser, ratingcomments FROM ".$mpnTables['links_votedata']." WHERE ratinglid = $lid");
        $totalvotesDB = mysql_num_rows($voteresult);
        $anonvotes = 0;
        $anonvoteval = 0;
        $outsidevotes = 0;
        $outsidevoteeval = 0;
        $regvoteval = 0;
        $topanon = 0;
        $bottomanon = 11;
        $topreg = 0;
        $bottomreg = 11;
        $topoutside = 0;
        $bottomoutside = 11;
        $avv = array(0,0,0,0,0,0,0,0,0,0,0);
        $rvv = array(0,0,0,0,0,0,0,0,0,0,0);
        $ovv = array(0,0,0,0,0,0,0,0,0,0,0);

        if ( ! isset( $useoutsidevoting ) ) { $useoutsidevoting = 0; }
        if ( ! isset( $anonweight ) ) { $anonweight = 1; }
        if ( ! isset( $outsideweight ) ) { $outsideweight = 1; }
        if ( ! isset( $impactAU ) ) { $impactAU = 0; }
        if ( ! isset( $impactOU ) ) { $impactOU = 0; }
        if ( ! isset( $anonvote ) ) { $anonvote = 0; }
        if ( ! isset( $anonvotes ) ) { $anonvotes = 0; }
        if ( ! isset( $regvotes ) ) { $regvotes = 0; }
        if ( ! isset( $detailvotedecimal ) ) { $detailvotedecimal = 0; }



        $truecomments = $totalvotesDB;
        while(list($ratingDB, $ratinguserDB, $ratingcommentsDB)=mysql_fetch_row($voteresult)) {
                 if ($ratingcommentsDB=="") $truecomments--;
                if ($ratinguserDB==$anonymous) {
                               $anonvotes++;
                        $anonvoteval += $ratingDB;
                }
                if ($useoutsidevoting == 1) {
                        if ($ratinguserDB=='outside') {
                               $outsidevotes++;
                                $outsidevoteval += $ratingDB;
                        }
                }
                else { $outsidevotes = 0; }

                     if ($ratinguserDB!=$anonymous && $ratinguserDB!="outside") { $regvoteval += $ratingDB; }

                     if ($ratinguserDB!=$anonymous && $ratinguserDB!="outside") {
                             if ($ratingDB > $topreg) $topreg = $ratingDB;
                             if ($ratingDB < $bottomreg) $bottomreg = $ratingDB;
                             for ($rcounter=1; $rcounter<11; $rcounter++) if ($ratingDB==$rcounter) $rvv[$rcounter]++;
                     }
                     if ($ratinguserDB==$anonymous) {
                             if ($ratingDB > $topanon) $topanon = $ratingDB;
                             if ($ratingDB < $bottomanon) $bottomanon = $ratingDB;
                             for ($rcounter=1; $rcounter<11; $rcounter++) if ($ratingDB==$rcounter) $avv[$rcounter]++;
                     }
                     if ($ratinguserDB=="outside") {
                             if ($ratingDB > $topoutside) $topoutside = $ratingDB;
                             if ($ratingDB < $bottomoutside) $bottomoutside = $ratingDB;
                             for ($rcounter=1; $rcounter<11; $rcounter++) if ($ratingDB==$rcounter) $ovv[$rcounter]++;
                     }
         }
         $regvotes = $totalvotesDB - $anonvotes - $outsidevotes;
         if ($totalvotesDB == 0) $finalrating = 0;
                      else if ($anonvotes == 0 && $regvotes == 0) {
                              // Figure Outside Only Vote
                              $finalrating = $outsidevoteval / $outsidevotes;
                              $finalrating = number_format($finalrating, $detailvotedecimal);
                          $avgOU = $outsidevoteval / $totalvotesDB;
                          $avgOU = number_format($avgOU, $detailvotedecimal);
                      }
                      else if ($outsidevotes == 0 && $regvotes == 0) {
                              // Figure Anon Only Vote
                              $finalrating = $anonvoteval / $anonvotes;
                              $finalrating = number_format($finalrating, $detailvotedecimal);
                          $avgAU = $anonvoteval / $totalvotesDB;
                          $avgAU = number_format($avgAU, $detailvotedecimal);
                      }
                      else if ($outsidevotes == 0 && $anonvotes == 0) {
                              // Figure Reg Only Vote
                              $finalrating = $regvoteval / $regvotes;
                              $finalrating = number_format($finalrating, $detailvotedecimal);
                          $avgRU = $regvoteval / $totalvotesDB;
                          $avgRU = number_format($avgRU, $detailvotedecimal);
                      }
                  else if ($regvotes == 0 && $useoutsidevoting == 1 && $outsidevotes != 0 && $anonvotes != 0 ) {
                  // Figure Reg and Anon Mix

                          $avgAU = $anonvoteval / $anonvotes;
                          $avgOU = $outsidevoteval / $outsidevotes;

                         if ($anonweight > $outsideweight ) {
                                 // Anon is 'standard weight'
                                $newimpact = $anonweight / $outsideweight;
                                $impactAU = $anonvotes;
                                $impactOU = $outsidevotes / $newimpact;

                                 $finalrating = ((($avgOU * $impactOU) + ($avgAU * $impactAU)) / ($impactAU + $impactOU));
                                 $finalrating = number_format($finalrating, $detailvotedecimal);
                         }
                         else {
                                 // Outside is 'standard weight'
                                $newimpact = $outsideweight / $anonweight;
                                 $impactOU = $outsidevotes;
                                 $impactAU = $anonvotes / $newimpact;

                                 $finalrating = ((($avgOU * $impactOU) + ($avgAU * $impactAU)) / ($impactAU + $impactOU));
                                 $finalrating = number_format($finalrating, $detailvotedecimal);

                         }
                  }
                  else
                  {

                         //REG User vs. Anonymous vs. Outside User Weight Calutions

                         $impact = $anonweight;                                  // REG users are weighted by the impact.
                         $outsideimpact = $outsideweight;
                         if ($regvotes == 0) { $avgRU = 0; }
                                 else { $avgRU = $regvoteval / $regvotes; }
                         if ($anonvotes == 0) { $avgAU = 0; }
                                 else { $avgAU = $anonvoteval / $anonvotes; }
                         if ($outsidevotes == 0 ) { $avgOU = 0; }
                                 else { $avgOU = $outsidevoteval / $outsidevotes; }
                         $impactRU = $regvotes;

// Division by zero?
                        if ($anonvote>=1 && $impact>=1) {
                            $impactAU = $anonvotes / $impact;
                        }
                        if ($outsidevotes>=1 && $outsideimpact>=1) {
                             $impactOU = $outsidevotes / $outsideimpact;
                         }


                        $finalrating = (($avgRU * $impactRU) + ($avgAU * $impactAU) + ($avgOU * $impactOU)) / ($impactRU + $impactAU + $impactOU);
                         $finalrating = number_format($finalrating, $detailvotedecimal);
                  }

    if ($avgOU == 0 || $avgOU == "") { $avgOU = ""; }
            else { $avgOU = number_format($avgOU, $detailvotedecimal); }
    if ($avgRU == 0 || $avgRU == "") { $avgRU = ""; }
            else { $avgRU = number_format($avgRU, $detailvotedecimal); }
    if ($avgAU == 0 || $avgAU == "") { $avgAU = ""; }
            else { $avgAU = number_format($avgAU, $detailvotedecimal); }


    if ($topanon == 0) $topanon = "";
    if ($bottomanon == 11) $bottomanon = "";
    if ($topreg == 0) $topreg = "";
    if ($bottomreg == 11) $bottomreg = "";
    if ($topoutside == 0) $topoutside = "";
    if ($bottomoutside == 11) $bottomoutside = "";
    $totalchartheight = 70;
    $chartunits = $totalchartheight / 10;

    $avvper                = array(0,0,0,0,0,0,0,0,0,0,0);
    $rvvper                 = array(0,0,0,0,0,0,0,0,0,0,0);
    $ovvper                 = array(0,0,0,0,0,0,0,0,0,0,0);
    $avvpercent         = array(0,0,0,0,0,0,0,0,0,0,0);
    $rvvpercent         = array(0,0,0,0,0,0,0,0,0,0,0);
    $ovvpercent         = array(0,0,0,0,0,0,0,0,0,0,0);
    $avvchartheight         = array(0,0,0,0,0,0,0,0,0,0,0);
    $rvvchartheight         = array(0,0,0,0,0,0,0,0,0,0,0);
    $ovvchartheight         = array(0,0,0,0,0,0,0,0,0,0,0);
    $avvmultiplier = 0;
    $rvvmultiplier = 0;
    $ovvmultiplier = 0;

    for ($rcounter=1; $rcounter<11; $rcounter++) {
            if ($anonvotes != 0) $avvper[$rcounter] = $avv[$rcounter] / $anonvotes;
            if ($regvotes != 0) $rvvper[$rcounter] = $rvv[$rcounter] / $regvotes;
            if ($outsidevotes != 0) $ovvper[$rcounter] = $ovv[$rcounter] / $outsidevotes;
            $avvpercent[$rcounter] = number_format($avvper[$rcounter] * 100, 1);
            $rvvpercent[$rcounter] = number_format($rvvper[$rcounter] * 100, 1);
            $ovvpercent[$rcounter] = number_format($ovvper[$rcounter] * 100, 1);
            if ($avv[$rcounter] > $avvmultiplier) $avvmultiplier = $avv[$rcounter];
            if ($rvv[$rcounter] > $rvvmultiplier) $rvvmultiplier = $rvv[$rcounter];
            if ($ovv[$rcounter] > $ovvmultiplier) $ovvmultiplier = $ovv[$rcounter];
    }
    if ($avvmultiplier != 0) $avvmultiplier = 10 / $avvmultiplier;
    if ($rvvmultiplier != 0) $rvvmultiplier = 10 / $rvvmultiplier;
    if ($ovvmultiplier != 0) $ovvmultiplier = 10 / $ovvmultiplier;

    for ($rcounter=1; $rcounter<11; $rcounter++) {

        $avvchartheight[$rcounter] = ($avv[$rcounter] * $avvmultiplier) * $chartunits;
            $rvvchartheight[$rcounter] = ($rvv[$rcounter] * $rvvmultiplier) * $chartunits;
            $ovvchartheight[$rcounter] = ($ovv[$rcounter] * $ovvmultiplier) * $chartunits;
        if ($avvchartheight[$rcounter]==0) $avvchartheight[$rcounter]=1;
            if ($rvvchartheight[$rcounter]==0) $rvvchartheight[$rcounter]=1;
            if ($ovvchartheight[$rcounter]==0) $ovvchartheight[$rcounter]=1;
    }

    echo "<table align=center border=0 cellspacing=0 cellpadding=2 width=98%>";
    $transfertitle = ereg_replace ("_", " ", $ttitle);
    $displaytitle = $transfertitle;

    echo "<tr><td>
            <TABLE WIDTH=\"100%\" CELLSPACING=2 CELLPADDING=2 BORDER=0 BGCOLOR=$bgcolor2><TR><TD>
               <center><FONT SIZE=3><b>".translate("Link Profile").":  $displaytitle</b></font></center>
            </tr></td></table>
          </td></tr>
          <tr><td>";
    echo "<center>";
    linkinfomenu($lid);
    echo "</center><br>
          </td><tr>
          <tr><td>";
    echo "<center>
    ".translate("Link Rating Details")."<br>
          $totalvotesDB ".translate("total votes")."<br>
          ".translate("Overall Rating").":  $finalrating</font></center><br><br>";
    echo "<table align=center border=0 cellspacing=0 cellpadding=2 width=455>";
    echo "<tr>
                <td colspan=2 bgcolor=$bgcolor3>
                <font size=2><B>".translate("Registered Users")."</b></font>
            </td>
          <tr>
          <tr height=1 bac>
            <td bgcolor=$bgcolor2>
            <font size=2>".translate("Number of Ratings").":  $regvotes</font>
            </td>
            <td rowspan=5 width=200>";
               if ($regvotes==0) echo "<center><font size=-2>".translate("No Registered User Votes")."</font></center>";
                       else {
                       echo "
               <table border=1 width=200 height=100%>
                 <tr>
                   <td valign=top align=center colspan=10 bgcolor=$bgcolor2><font size=-2>".translate("Breakdown of Ratings by Value")."</font></td>
                 </tr>
                 <tr>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$rvv[1] ".translate("votes")." ($rvvpercent[1]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$rvvchartheight[1]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$rvv[2] ".translate("votes")." ($rvvpercent[2]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$rvvchartheight[2]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$rvv[3] ".translate("votes")." ($rvvpercent[3]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$rvvchartheight[3]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$rvv[4] ".translate("votes")." ($rvvpercent[4]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$rvvchartheight[4]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$rvv[5] ".translate("votes")." ($rvvpercent[5]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$rvvchartheight[5]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$rvv[6] ".translate("votes")." ($rvvpercent[6]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$rvvchartheight[6]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$rvv[7] ".translate("votes")." ($rvvpercent[7]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$rvvchartheight[7]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$rvv[8] ".translate("votes")." ($rvvpercent[8]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$rvvchartheight[8]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$rvv[9] ".translate("votes")." ($rvvpercent[9]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$rvvchartheight[9]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$rvv[10] ".translate("votes")." ($rvvpercent[10]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$rvvchartheight[10]></td>
                 </tr>
                 <tr><td colspan=10>
                    <table cellspacing=0 cellspacing=0 border=0 height=5 width=200><tr></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>1</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>2</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>3</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>4</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>5</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>6</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>7</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>8</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>9</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>10</font></td>
                    </td><tr></table>
                 </td></tr>
               </table>
               ";
               }
               echo "
            </td>
          </tr>
          <tr><td bgcolor=$bgcolor2><font size=2>".translate("Link Rating").": $avgRU</font></td></tr>
          <tr><td bgcolor=$bgcolor3><font size=2>".translate("High Rating").": $topreg</font></td></tr>
          <tr><td bgcolor=$bgcolor2><font size=2>".translate("Low Rating").": $bottomreg</font></td></tr>
          <tr><td bgcolor=$bgcolor3><font size=2>".translate("Number of Comments").": $truecomments</font></td></tr>
          <tr><td></td></tr>
          <tr><td valign=top colspan=2><font size=1><br><br>";
          if ($anonweight) {
             echo "* ".translate("Note: This website weighs Registered vs. Unregistered user's ratings")." $anonweight ".translate("to")." 1.";
          }
          echo "</font></td></tr>
          <tr><td colspan=2 bgcolor=$bgcolor3><font size=2><B>".translate("Unregistered Users")."</b></font></td></tr>
          <tr height=1><td bgcolor=$bgcolor2><font size=2>".translate("Number of Ratings").": $anonvotes</font></td>
            <td rowspan=5 width=200>
                ";
                if ($anonvotes==0) echo "<center><font size=-2>".translate("No Unregistered User Votes")."</font></center>";
                       else {
                       echo "
               <table border=1 width=200 height=100%>
                 <tr>
                   <td valign=top align=center colspan=10 bgcolor=$bgcolor2><font size=-2>".translate("Breakdown of Ratings by Value")."</font></td>
                 </tr>
                 <tr>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$avv[1] ".translate("votes")." ($avvpercent[1]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$avvchartheight[1]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$avv[2] ".translate("votes")." ($avvpercent[2]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$avvchartheight[2]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$avv[3] ".translate("votes")." ($avvpercent[3]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$avvchartheight[3]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$avv[4] ".translate("votes")." ($avvpercent[4]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$avvchartheight[4]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$avv[5] ".translate("votes")." ($avvpercent[5]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$avvchartheight[5]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$avv[6] ".translate("votes")." ($avvpercent[6]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$avvchartheight[6]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$avv[7] ".translate("votes")." ($avvpercent[7]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$avvchartheight[7]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$avv[8] ".translate("votes")." ($avvpercent[8]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$avvchartheight[8]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$avv[9] ".translate("votes")." ($avvpercent[9]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$avvchartheight[9]></td>
                   <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$avv[10] ".translate("votes")." ($avvpercent[10]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$avvchartheight[10]></td>
                 </tr>
                 <tr><td colspan=10>
                    <table cellspacing=0 cellpadding=0 border=0 height=5 width=200><tr></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>1</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>2</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>3</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>4</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>5</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>6</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>7</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>8</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>9</font></td>
                    <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>10</font></td>
                    </td><tr></table>
                 </td></tr>
               </table>
               ";
                }
               echo "
            </td>
          </tr>
          <tr><td bgcolor=$bgcolor2><font size=2>".translate("Link Rating").": $avgAU</font></td></tr>
          <tr><td bgcolor=$bgcolor3><font size=2>".translate("High Rating").": $topanon</font></td></tr>
          <tr><td bgcolor=$bgcolor2><font size=2>".translate("Low Rating").": $bottomanon</font></td></tr>
          <tr><td bgcolor=$bgcolor3><font size=2>&nbsp;</font></td></tr>";

          if ($useoutsidevoting == 1) {
                  echo "
                  <tr><td valign=top colspan=2><font size=\"1\"><br><br>";
                  if ($outsideweigth) {
                    echo "* ".translate("Note: This website weighs Registered vs. Outside voter's ratings")." $outsideweight ".translate("to")." 1.";
                  }
                    echo "</font></td></tr>
                    <tr><td colspan=2 bgcolor=$bgcolor3><font size=2><B>".translate("Outside Voters")."</b></font></td></tr>
                    <tr height=1><td bgcolor=$bgcolor2><font size=2>".translate("Number of Ratings").": $outsidevotes</font></td>
                      <td rowspan=5 width=200>
                          ";
                          if ($outsidevotes==0) echo "<center><font size=-2>".translate("No Outside Votes")."</font></center>";
                                 else {
                                 echo "
                         <table border=1 width=200 height=100%>
                           <tr>
                             <td valign=top align=center colspan=10 bgcolor=$bgcolor2><font size=-2>".translate("Breakdown of Ratings by Value")."</font></td>
                           </tr>
                           <tr>
                             <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$ovv[1] ".translate("votes")." ($ovvpercent[1]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$ovvchartheight[1]></td>
                             <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$ovv[2] ".translate("votes")." ($ovvpercent[2]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$ovvchartheight[2]></td>
                             <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$ovv[3] ".translate("votes")." ($ovvpercent[3]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$ovvchartheight[3]></td>
                             <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$ovv[4] ".translate("votes")." ($ovvpercent[4]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$ovvchartheight[4]></td>
                             <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$ovv[5] ".translate("votes")." ($ovvpercent[5]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$ovvchartheight[5]></td>
                             <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$ovv[6] ".translate("votes")." ($ovvpercent[6]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$ovvchartheight[6]></td>
                             <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$ovv[7] ".translate("votes")." ($ovvpercent[7]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$ovvchartheight[7]></td>
                             <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$ovv[8] ".translate("votes")." ($ovvpercent[8]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$ovvchartheight[8]></td>
                             <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$ovv[9] ".translate("votes")." ($ovvpercent[9]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$ovvchartheight[9]></td>
                             <td bgcolor=$bgcolor3 valign=bottom><img border=0 alt=\"$ovv[10] ".translate("votes")." ($ovvpercent[10]% ".translate("total votes").")\" src=images/blackpixel.gif width=15 height=$ovvchartheight[10]></td>
                           </tr>
                           <tr><td colspan=10>
                              <table cellspacing=0 cellpadding=0 border=0 height=5 width=200><tr></td>
                              <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>1</font></td>
                              <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>2</font></td>
                              <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>3</font></td>
                              <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>4</font></td>
                              <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>5</font></td>
                              <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>6</font></td>
                              <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>7</font></td>
                              <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>8</font></td>
                              <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>9</font></td>
                              <td bgcolor=$bgcolor3 width=10% valign=bottom align=center><font size=-2>10</font></td>
                              </td><tr></table>
                           </td></tr>
                         </table>
                         ";
                          }
                         echo "
                      </td>
                    </tr>
                    <tr><td bgcolor=$bgcolor2><font size=2>".translate("Link Rating").": $avgOU</font></td></tr>
                    <tr><td bgcolor=$bgcolor3><font size=2>".translate("High Rating").": $topoutside</font></td></tr>
                    <tr><td bgcolor=$bgcolor2><font size=2>".translate("Low Rating").": $bottomoutside</font></td></tr>
                    <tr><td bgcolor=$bgcolor3><font size=2>&nbsp;</font></td></tr>";
          }

    echo "</table></table><br><br>";
    linkfooter($lid);
    CloseTable();
    include("footer.$phpEx");

}

function linkfooter($lid) {
        global $phpEx;
    //$ttitle = ereg_replace(" ", "_", $ttitle);
    echo "
    <a href=links.$phpEx?op=visit&lid=$lid target=_blank>".translate("Visit this Website")."</a>  |  <a href=links.$phpEx?op=ratelink&lid=$lid>".translate("Rate this Website")."</a><br><br>";
    linkfooterchild($lid);
}

function linkfooterchild($lid) {
    global $sitename, $phpEx;
    if ($useoutsidevoting = 1) { echo "<br><center><hr size=1 noshade><font size=-1>".translate("Is this your resource?")." <a href=links.$phpEx?op=outsidelinksetup&lid=$lid>".translate("Allow users to rate your script from your web site!")."</center></a></font>"; }

}

function outsidelinksetup($lid) {
    global $sitename, $phpEx, $bgcolor2, $bgcolor3, $textcolor1, $textcolor2;
    include("header.$phpEx");
    logo();
    OpenTable();

    echo "<center><font size=3><br><b>".translate("Promote Your Website")."</b></font></center><br><br>";
    echo "
    <table width=\"90%\">

    ".translate("If the resource you were rating at the time you clicked on the 'remote rate' link was your own, you may be interested in several of the remote 'Rate a Website' options we have available. These allow you to place an image (or even a rating form) on your script's web site in order to increase the number of votes your website receive. Please choose from one of the options listed below if this is something you are interested in:")."<br><br>

    <b>".translate("Please, no cheating...")."</b><br><br>"
    . translate("We have had several cases where a website has been removed from the directory due to cheating involved with our rating system.") . " "
    . translate("We usually find these, even when they are very obscure, either from user reportings or routine checks by staff.") . " "
    . translate("By being removed from the directory, you'll lose more accesses than you ever would by falsely bolstering your rating value.")
    . "<br><br>

    <b>".translate("1. Text Links")."</b><br><br>

    ".translate("One way to link to the rating form is through a simple text link, such as:")."<br><br>


    <center><a href=" . _MPN_ROOT_URI . "links.$phpEx?op=ratelink&lid=$lid>".translate("Rate this Website @")." $sitename</a></center><br><br>
    <center>".translate("The HTML code you should use in this case, is the following:")."</center><br>
    <center><textarea rows=4 name=S1 cols=50><a href=\"" . _MPN_ROOT_URI . "links.$phpEx?op=ratelink&lid=$lid\">".translate("Rate this Website @")." $sitename</a></textarea></center>
    <br><br>
    ".translate("The number")." '$lid' ".translate("in the HTML source references is the resource id number in or link directory database. You should make sure you link to the correct website.")."<br><br>

    <b>".translate("2. Small Image Links")."</b><br><br>

    ".translate("If you're looking for a little more than a basic text link, you may wish for one of our smaller image links to the rating form:")."<br><br>

    <center><a href=" . _MPN_ROOT_URI . "links.$phpEx?op=ratelink&lid=$lid><img src=" . _MPN_ROOT_URI . "images/rate.gif></a></center><br>
    <center>".translate("Right click on image and 'Save Image'.")."  <b>".translate("Do NOT link this image from our site!")."</b>  ".translate("Copy the image to your website and change the links as appropriate")."</center><br><br>
    <center><textarea rows=4 name=S1 cols=50><a href=\"" . _MPN_ROOT_URI . "links.$phpEx?op=ratelink&lid=$lid\"><img src=\"" . _MPN_ROOT_URI . "images/rate.gif\"></a></textarea></center>
    <br><br>

    <b>".translate("3. Remote Rating Forms")."</b><br><br>

    ".translate("Our policies on the use of a remote rating form on your web site are very strict. If we find a web site in violation of the acceptable terms, we have the right to block all incoming votes from the offending web site or remove your listing from").
    " $sitename ".translate("entirely. The only voting mechanisms required on a remote site are the form types shown below, unless you get permission to use a different rating form scheme. Basically, we want the default vote set to -- and the user must be able to freely choose from 1 - 10. Any site that we find that is attempting to submit all 10s or something similar when a user simply hits submit will be in violation of the remote rating rules.")."<br><br>
    ".translate("Having said that, here is what the current remote rating form looks like. If we get significant user feedback, we will create others. If you wish to have something custom made on your site, feel free, but make sure you get it approved by us and that it follows the basic guidelines set forth above.")."<br><br>

  <table align=center border=0 width=175 cellspacing=0 cellpadding=0 bordercolor=$bgcolor2 bgcolor=$bgcolor3>
    <tr>
      <td width=\"100%\"><a href=" . _MPN_ROOT_URI . "><img border=0 src=" . _MPN_ROOT_URI . "images/ratesitetop.gif width=175 height=34></a></td>
    </tr>
    <tr>
      <td width=\"100%\">
        <table border=0 width=\"100%\" cellspacing=0 cellpadding=0 height=23>
          <tr>
            <td width=\"100%\" height=23>
              <form method=POST action=" . _MPN_ROOT_URI . "links.$phpEx>
                <input type=hidden name=ratinglid value=\"$lid\">
                <input type=hidden name=ratinguser value=\"outside\">
                <table border=0 width=\"100%\" background=" . _MPN_ROOT_URI . "images/ratesitebottom.gif cellspacing=0 cellpadding=0>
                  <tr>
                    <td width=53% valign=top>
                      <p align=right>
                     <select name=rating>
                     <option selected>--
                                       <option>10
                                  <option>9
                                           <option>8
                                                <option>7
                                                <option>6
                                                <option>5
                                                <option>4
                                                <option>3
                                                <option>2
                                                <option>1
                                  </select>&nbsp;&nbsp; </td>

                    <td width=47% valign=top>
                      <p align=right><input type=image src=" . _MPN_ROOT_URI . "images/ratebutton.gif name=op value=addrating width=63 height=17 alt=\"Rate Link at $sitename\"></td>
                  </tr>
                </table>
              </form>
            </td>
          </tr>
        </table>
        </td></tr></table></center>
   <table width=90% align=center>
   <br><br>
   ".translate("Using this form will allow users to rate your website directly from your site and the rating will be recorded. The above form is disabled, but the following source code will work if you simply cut and paste it into your web page, copy the images (top, bottom, and button), and change image paths to your site. The source code is shown below:")."<br><br>
    <center><textarea rows=30 name=S1 cols=70>  <table align=center border=0 width=175 cellspacing=0 cellpadding=0 bordercolor=$bgcolor2 bgcolor=$bgcolor3>
    <tr>
      <td width=\"100%\"><a href=\"" . _MPN_ROOT_URI . "\"><img border=\"0\" src=\"" . _MPN_ROOT_URI . "images/ratesitetop.gif\" width=\"175\" height=\"34\"></a></td>
    </tr>
    <tr>
      <td width=\"100%\">
        <table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" height=\"23\">
          <tr>
            <td width=\"100%\" height=\"23\">
              <form method=POST action=\"" . _MPN_ROOT_URI . "links.$phpEx\">
                <input type=hidden name=ratinglid value=\"$lid\">
                <input type=hidden name=ratinguser value=\"outside\">
                <table border=\"0\" width=\"100%\" background=\"" . _MPN_ROOT_URI . "images/ratesitebottom.gif\" cellspacing=\"0\" cellpadding=\"0\">
                  <tr>
                    <td width=\"53%\" valign=top>
                      <p align=right>
                     <select name=rating>
                     <option selected>--
                     <option>10
                     <option>9
                     <option>8
                     <option>7
                     <option>6
                     <option>5
                     <option>4
                     <option>3
                     <option>2
                     <option>1
                     </select>&nbsp;&nbsp; </td>

                    <td width=\"47%\" valign=\"top\">
                      <p align=right><input type=image src=\"" . _MPN_ROOT_URI . "images/ratebutton.gif\" name=op value=addrating width=\"63\" height=\"17\" alt=\"Rate Link at $sitename\"></td>
                  </tr>
                </table>
              </form>
           </td>
          </tr>
        </table>
        </td></tr></table></textarea>
    </center><br><br>
    ".translate("Thanks! Let us know if you have any questions or concerns.")."<br><br>
    - $sitename ".translate("Staff")."
    <br><br>
    </table>";
    CloseTable();
    include("footer.$phpEx");
}

function brokenlink($lid) {
        global $phpEx;
    include("header.$phpEx");
    logo();
    OpenTable();

    $ratinguser = $GLOBALS['uinf']['uname'];

    echo "<center><font size=3><b><center>".translate("Report Broken Link")."</center></b><br><br><br><font size=2>";
    echo "<form action=links.$phpEx method=post>";
    echo "<input type=hidden name=lid value=$lid>";
    echo "<input type=hidden name=modifysubmitter value=$ratinguser>";
    echo "<center>
          ".translate("Thank you for helping to maintain this directory's integrity.")."
          <br>
          ".translate("For security reasons your user name and IP address will also be temporarily recorded.")."
          </center><br><br>";

    echo "</select><center>\n";

    // Kiril: New Sanitizer

    echo "<input type='hidden' name='stripit_form' value='modifysubmitter' />\n";
    echo "<input type='hidden' name='mpn_sectype' value='2' />\n";

    // End Sanitizer

    echo "<input type=hidden name=op value=brokenlinkS><input class='button' type=submit value=\"".translate("Report Broken Link")."\"></center></form><br>";
    CloseTable();
    include("footer.$phpEx");
}

function brokenlinkS($lid, $modifysubmitter)
{
    global $mpnTables,$phpEx;

    $ratinguser = $GLOBALS['uinf']['uname'];

    mysql_query("insert into ".$mpnTables['links_modrequest']." values (NULL, '$lid', '0', '0', '', '', '', '$ratinguser', '1')");
    include("header.$phpEx");
    echo "<br><br><center>".translate("Thanks for the information. We'll look into your request shortly.")."</center>";
    include("footer.$phpEx");

}

function modifylinkrequest($lid) {
        global $phpEx, $mpnTables, $bgcolor2, $bgcolor3, $textcolor1, $textcolor2, $blockunregmodify;
    include("header.$phpEx");
    logo();
    OpenTable();

    $ratinguser = $GLOBALS['uinf']['uname'];

    echo "<table width=450 align=center>";
    $blocknow = 0;
    if ($blockunregmodify == 1 && $ratinguser=="$anonymous") {
    echo "<br><br><center>".translate("Only registered users can suggest link modifications. Please register or login.")."</center>";
    $blocknow = 1;
    }

    if ($blocknow != 1) {
            $result = mysql_query("select cid, sid, title, url, description from ".$mpnTables['links_links']." where lid=$lid");
            echo "
            </center><font size=3><b>Request Link Modification</b><br><br><font size=2>";
            while(list($cid, $sid, $title, $url, $description) = mysql_fetch_row($result))
            {
                   /* $title = stripslashes($title);
                    $description = stripslashes($description);*/

                // Kiril: Start New Sanitizer

                $sanity_ary = compact( 'title', 'url', 'description' );
                $_SERVER['SAN'] -> slashIT( $sanity_ary );
                extract( $sanity_ary );
                unset( $sanity_ary );

                // End New Sanitizer


                    echo "<form action=links.$phpEx method=post>";
                echo "<font color=Blue>".translate("Link ID: ")."<font color=$textcolor1><b>$lid</b><br>";
                echo "".translate("Page Title: ")."<input class=textbox type=text name=title value=\"$title\" size=50 maxlength=100></input><br>";
                echo "".translate("Page URL: ")."<input class=textbox type=text name=url value=$url size=50 maxlength=100></input>&nbsp;<br>";
                echo "".translate("Description: ")."<br><textarea name=description cols=60 rows=10>$description</textarea><br>";
                $result2=mysql_query("select cid, title from ".$mpnTables['links_categories']." order by title");
                echo "<input type=hidden name=lid value=$lid></input>";
                echo "<input type=hidden name=modifysubmitter value=$ratinguser></input>";
                echo "".translate("Category: ")."<select name=\"cat2\">";
                while(list($ccid, $ctitle) = mysql_fetch_row($result2)) {
                    $ctitle = stripslashes( $ctitle );
                    $sel = "";
                    if ($cid==$ccid AND $sid==0) {
                        $sel = "selected";
                    }
                    echo "<option value=\"$ccid\" $sel>$ctitle</option>";
                    $result3=mysql_query("select sid, title from ".$mpnTables['links_subcategories']." where cid=$ccid order by title");
                    while(list($ssid, $stitle) = mysql_fetch_row($result3)) {
                        $stitle = stripslashes( $stitle );
                            $sel = "";
                        if ($sid==$ssid) {
                            $sel = "selected";
                        }
                        echo "<option value=\"$ccid"."-"."$ssid\" $sel>$ctitle / $stitle</option>";
                    }
                }

                // Kiril: New Sanitizer

                echo "<input type='hidden' name='stripit_form' value='title|url|description|modifysubmitter' />\n";
                echo "<input type='hidden' name='mpn_sectype' value='2' />\n";

                // End Sanitizer

            echo "</select><input type=hidden name=\"op\" value=\"modifylinkrequestS\"></input><input class='button' type=submit value=\"".translate("Send Request")."\"></input></form><br>";
            }

    }
    echo "</table>";
    CloseTable();
    include("footer.$phpEx");
}

function modifylinkrequestS($lid, $cat2, $title, $url, $description, $modifysubmitter) {
    global $mpnTables,$phpEx;

    $ratinguser = $GLOBALS['uinf']['uname'];

    $blocknow = 0;

    if ($blockunregmodify == 1 && ! _MPN_USER )
    {
        include("header.$phpEx");
        echo "<br><br><center>".translate("Only registered users can suggest link modifications. Please register or login.")."</center>";
        include("footer.$phpEx");
        exit;
    }

    $cat1 = explode("-", $cat2);

    if ( ! is_array( $cat1 ) || ! isset( $cat1[1] ) || $cat1[1] == '' )
    {
        $cat1[1] = 0;
    }

    mysql_query("insert into ".$mpnTables['links_modrequest']." values (NULL, '$lid', '$cat1[0]', '$cat1[1]', '$title', '$url', '$description', '$ratinguser', '0')");
    include("header.$phpEx");
    echo "<br><br><center>".translate("Thanks for the information. We'll look into your request shortly.")."</center>";
    include("footer.$phpEx");
}

function rateinfo($lid) {
        global $mpnTables;
    mysql_query("update ".$mpnTables['links_links']." set hits=hits+1 where lid=$lid");
    $result = mysql_query("select url from ".$mpnTables['links_links']." where lid=$lid");
    list($url) = mysql_fetch_row($result);
    $_SERVER['F_LIB'] -> redirectRequest( $url );
}


function addrating($ratinglid, $ratinguser, $rating, $ratinghost_name, $ratingcomments) {
    global $anonymous, $mpnTables,$phpEx;
    $referer = getenv("HTTP_REFERER");
    $passtest = "yes";
    include("header.$phpEx");
    OpenTable();

    completevoteheader();

    $ratinguser = ( ! _MPN_USER && ( $ratinguser == "outside" || ! eregi( "^" . _MPN_ROOT_URI . "", $referer ) ) )
                ? ( 'outside' )
                : ( $GLOBALS['uinf']['uname'] );

    $results3 = mysql_query("SELECT title FROM ".$mpnTables['links_links']." WHERE lid=$ratinglid");
    while(list($title)=mysql_fetch_row($results3)) { $ttitle = stripslashes( $title ); }

    //Make sure only 1 anonymous from an IP in a single day.
    $anonwaitdays = 1;
    $ip = getenv("REMOTE_ADDR");

    // Check if Rating is Null
        if ($rating=="--") {
                $error = "nullerror";
            completevote($error);
            $passtest = "no";
        }

    // Check if Link POSTER is voting (UNLESS Anonymous users allowed to post)
    if ($ratinguser != $anonymous && $ratinguser != "outside") {
            $result=mysql_query("select submitter from ".$mpnTables['links_links']." where lid=$ratinglid");
            while(list($ratinguserDB)=mysql_fetch_row($result)) {
                $ratinguserDB = stripslashes( $ratinguserDB );
                if ($ratinguserDB==$ratinguser) {
                        $error = "postervote";
                    completevote($error);
                    $passtest = "no";
                }
           }
    }

    // Check if REG user is trying to vote twice.
    if ($ratinguser!=$anonymous && $ratinguser != "outside") {
            $result=mysql_query("select ratinguser from ".$mpnTables['links_votedata']." where ratinglid=$ratinglid");
            while(list($ratinguserDB)=mysql_fetch_row($result)) {
                $ratinguserDB = stripslashes( $ratinguserDB );
                    if ($ratinguserDB==$ratinguser) {
                            $error = "regflood";
                        completevote($error);
                        $passtest = "no";
                }

        }
    }

     // Check if ANONYMOUS user is trying to vote more than once per day.
    if ($ratinguser==$anonymous){
            $yesterdaytimestamp = (time()-(86400 * $anonwaitdays));
            $ytsDB = Date("Y-m-d H:i:s", $yesterdaytimestamp);
            $result=mysql_query("select * FROM ".$mpnTables['links_votedata']." WHERE ratinglid=$ratinglid AND ratinguser='$anonymous' AND ratinghostname = '$ip' AND TO_DAYS(NOW()) - TO_DAYS(ratingtimestamp) < $anonwaitdays");
        $anonvotecount = mysql_num_rows($result);
            if ($anonvotecount >= 1) {
                    $error = "anonflood";
                completevote($error);
                    $passtest = "no";
            }
    }

     // Check if OUTSIDE user is trying to vote more than once per day.
    if ($ratinguser=="outside"){
            $yesterdaytimestamp = (time()-(86400 * $outsidewaitdays));
            $ytsDB = Date("Y-m-d H:i:s", $yesterdaytimestamp);
            $result=mysql_query("select * FROM ".$mpnTables['links_votedata']." WHERE ratinglid=$ratinglid AND ratinguser='outside' AND ratinghostname = '$ip' AND TO_DAYS(NOW()) - TO_DAYS(ratingtimestamp) < $outsidewaitdays");
        if ($result) $outsidevotecount = mysql_num_rows($result);
            if ($outsidevotecount >= 1) {
                    $error = "outsideflood";
                completevote($error);
                    $passtest = "no";
            }
    }


    // Passed Tests
    if ($passtest == "yes")
    {
            //$comment = stripslashes(FixQuotes($comment));

            //All is well.  Add to Line Item Rate to DB.
         mysql_query("INSERT into ".$mpnTables['links_votedata']." values (NULL, '$ratinglid', '$ratinguser', '$rating', '$ip', '$ratingcomments', now())");

        //All is well.  Calculate Score & Add to Summary (for quick retrieval & sorting) to DB.
        //NOTE:  If weight is modified, ALL links need to be refreshed with new weight.
        //         Running a SQL statement with your modded calc for ALL links will accomplish this.

        $voteresult = mysql_query("select rating, ratinguser, ratingcomments FROM ".$mpnTables['links_votedata']." WHERE ratinglid = $ratinglid");
        $totalvotesDB = mysql_num_rows($voteresult);
        include ("voteinclude.$phpEx");
        mysql_query("UPDATE ".$mpnTables['links_links']." SET linkratingsummary=$finalrating,totalvotes=$totalvotesDB,totalcomments=$truecomments WHERE lid = $ratinglid");
        $error = "none";
        completevote($error);
    }
    completevotefooter($ratinglid, $ttitle, $ratinguser);
    CloseTable();
    include("footer.$phpEx");
}




function completevoteheader()
{
    global $sitename;
    logo();
    echo "<br>
    <table border=0 width=450>
      <tr>
        <td>";
}

function completevotefooter($lid, $ttitle, $ratinguser) {
    global $sitename, $mpnTables, $bgcolor2, $bgcolor3, $textcolor1, $textcolor2;
    $result=mysql_query("select url FROM ".$mpnTables['links_links']." WHERE lid=$lid");
    list($url)=mysql_fetch_row($result);
    echo "
        </td>
      </tr>
      <tr>
        <td>
          <font size=2>".translate("Thank you for taking the time to rate a site here at"). " ".$sitename.". ";
          echo "".translate("Input from users such as yourself will help other visitors better decide which links to click on.")."</font><br><br><br>
        </td>
      </tr>";
     if ($ratinguser=="outside") {
     echo "
      <tr>
        <td>
          <font size=2><center>".translate("We appreciate your visit to")." $sitename</center><br><center><a href=$url>".translate("Return to")." $ttitle</a></font><center><br><br>
        </td>
      </tr>";
     $result=mysql_query("select title FROM ".$mpnTables['links_links']." where lid=$lid");
     list($title)=mysql_fetch_row($result);
     $ttitle = ereg_replace (" ", "_", $title);
     }


     echo "
     </table>
     <br><br>";
     linkinfomenu($lid);
}

function completevote($error)
{
    global $textcolor2, $anonwaitdays, $outsidewaitdays;

    $anonwaitdays = 1;
          if ($error == "none") echo "<center><b><font size=2>".translate("Your vote is appreciated.")."</font></b></center>";
          if ($error == "anonflood") echo "<font size=3 color=$textcolor2><b><center>". sprintf(translate("You have already voted for this link in the past %s day(s)."), $anonwaitdays) . "</center></b><br>";
          if ($error == "regflood") echo "<font size=3 color=$textcolor2><b><center>".translate("Vote for a link only once.<br>All votes are logged and reviewed.")."</center></b><br>";
          if ($error == "postervote") echo "<font size=3 color=$textcolor2><b><center>".translate("You cannot vote on a link you submitted.<br>All votes are logged and reviewed.")."</center></b><br>";
          if ($error == "nullerror") echo "<font size=3 color=$textcolor2><b><center>".translate("No rating selected - no vote tallied")."</center></b><br>";
          if ($error == "outsideflood") echo "<font size=3 color=$textcolor2><b><center>".translate("Only one vote per IP address allowed every")." $outsidewaitdays ".translate("day(s).")."</center></b><br>";
}

function ratelink($lid)
{
    global $phpEx;

    $ttitle = getTitle( $lid , translate( 'Rating For' ) );

    include("header.$phpEx");
     logo();
    OpenTable();

    echo "</center>";
    $transfertitle = ereg_replace ("_", " ", $ttitle);
    $displaytitle = stripslashes($transfertitle);

    global $title, $datetime, $anonymous;
    $ip = getenv("REMOTE_HOST");
    if (empty($ip)) {
       $ip = getenv("REMOTE_ADDR");
    }

    echo "
    <hr size=1 noshade>
    <font face=\"Verdana,Arial,Helvetica\"><b>$displaytitle</b>
    <UL><FONT SIZE=-1>
     <LI>".translate("Please do not vote for the same resource more than once.")."
     <LI>".translate("The scale is 1 - 10, with 1 being poor and 10 being excellent.")."
     <LI>".translate("Please be objective, if everyone receives a 1 or a 10, the ratings aren't very useful.")."
     <LI>".translate("You can view a list of the <a href='links.php?op=TopRated'>Top Rated Resources</a>.")."
     <LI>".translate("Do not vote for your own resource.")."";

    if( _MPN_USER )
    {
        echo "<LI>".translate("You are a registered user and are logged in.")."
              <LI>".translate("Feel free to add a comment about this site.")."";

        $name = $GLOBALS['uinf'][1];

    } else {
            echo "<LI>".translate("You are not a registered user or you have not logged in.")."
                  <LI>".translate("If you were registered you could make comments on this website.")."";
            $name = "$anonymous";
    }

    echo "
     </font></FONT></UL>


     <table border=0 cellpadding=1 cellspacing=0 width=\"100%\">
     <tr><td width=25 nowrap></td>
     <tr><td width=25 nowrap></td><td width=550>
     <form method=POST action=\"links.$phpEx\">
     <input type=hidden name=\"ratinglid\" value=\"$lid\">
     <input type=hidden name=\"ratinguser\" value=\"$name\">
     <input type=hidden name=\"ratinghost_name\" value=\"$ip\">
     <font face=\"Verdana,Arial,Helvetica\"><font size=+1>".translate("Rate this Website").": </font>
     <select name=\"rating\">
     <option>--
     <option>10
     <option>9
     <option>8
     <option>7
     <option>6
     <option>5
     <option>4
     <option>3
     <option>2
     <option>1
     </select> <font size=-1><input type=hidden name=op value=\"Rate this Website\"><input class='button' type=submit value=\"".translate("Rate this Website")."\"></font></font>
     <br><br>";

    if(_MPN_USER) {
        echo "
                     <b>" .translate("Comments:")."</b> <br><TEXTAREA wrap=virtual cols=50 rows=10 name=\"ratingcomments\"></TEXTAREA>
                     <br><br><br>
                     </font>
             ";
        }
        else {
                echo"<input type=hidden name=\"ratingcomments\" value=\"\">";

        }

     // Kiril: New Sanitizer

    echo "<input type='hidden' name='stripit_form' value='ratingcomments' />\n";
    echo "<input type='hidden' name='mpn_sectype' value='2' />\n";

    // End Sanitizer


    echo "
     </td></tr></form></table>";
    linkfooterchild($lid);
    CloseTable();
    include("footer.$phpEx");



}

if (isset($ratinglid) && isset ($ratinguser) && isset ($rating)) {
        $ret = addrating($ratinglid, $ratinguser, $rating, $ratinghost_name, $ratingcomments);
}


function &fetchURLInfo( $rel_url )
{
    $list = array();
    $fp = @fopen( $rel_url, "r" );
    if ( $fp )
    {
        $output = fread( $fp, 5000 ); // First 5k should be enough
        fclose( $fp );
        if ( preg_match( "#<title>([^<]+)</title>#i", $output, $regs ) )
        {
            $title = trim( $regs[1] );
            $list["title"] = $title;
        }
        if ( preg_match( "#<meta[ \t\n]+name[ \t\n]*=[ \t\n]*\"abstract\"[ \t\n]+content[ \t\n]*=[ \t\n]*\"([^\"]+)\"[ \t\n]*>#i", $output, $regs ) )
        {
            $abstract = trim( $regs[1] );
            $list["abstract"] = $abstract;
        }
        if ( preg_match( "#<meta[ \t\n]+name[ \t\n]*=[ \t\n]*\"description\"[ \t\n]+content[ \t\n]*=[ \t\n]*\"([^\"]+)\"[ \t\n]*>#i", $output, $regs ) )
        {
            $description = trim( $regs[1] );
            $list["description"] = $description;
        }
        if ( preg_match( "#<meta[ \t\n]+name[ \t\n]*=[ \t\n]*\"keywords\"[ \t\n]+content[ \t\n]*=[ \t\n]*\"([^\"]+)\"[ \t\n]*>#i", $output, $regs ) )
        {
            $keywords = trim( $regs[1] );
            $list["keywords"] = $keywords;
        }
        return $list;
    }
    else
    {
        return false;
    }
}

function get_spider($title, $url, $cat, $description, $name, $email) {
    global $phpEx;
    if ( $url ) {
        if ( !preg_match( "%^([a-z]+://)%", $url ) )
            $rel_url = "http://" . $url;
        else
            $rel_url = $url;
    if (!preg_match("/\\\$/", $rel_url)) $rel_url = $rel_url . "/";

        $metaList = fetchURLInfo( $rel_url );

        if ( $metaList == false )
        {
            // Change this to use an external message
            $title = translate("The site does not exists");
        } else if( count( $metaList ) == 0 ) {
            $title = translate("No Metadata found");
        }

        if (isset( $metaList["description"] ))
            $description = $metaList["description"];
        else
            $description = "";
        if (isset( $metaList["title"] ))
            $title = $metaList["title"];
        else if (isset( $metaList["abstract"] ))
            $title = $metaList["abstract"];
        }

        include './header.php';

        echo "<div class='center'>\n";

            echo "<h1>" . translate( 'Finished Fetching Meta Data' ) . "</h1>\n";

            echo "<form action='./links.php' method='post'>\n";

                echo "<input type='hidden' name='title' value='$title' />\n";
                echo "<input type='hidden' name='url' value='$url' />\n";
                echo "<input type='hidden' name='cat' value='$cat' />\n";
                echo "<input type='hidden' name='description' value='$description' />\n";
                echo "<input type='hidden' name='name' value='$name' />\n";
                echo "<input type='hidden' name='email' value='$email' />\n";
                echo "<input type='hidden' name='op' value='AddLink' />\n";

                echo "<input class='button' type='submit' value='" . translate( 'Continue' ) . "' />\n";

            echo "</form>\n";

        echo "</div>\n";

        include './footer.php';

        exit;
}

function getTitle( $lid, $prefix )
{
    global $mpnTables;

    $sql = "SELECT title FROM " . $mpnTables['downloads_downloads'] . " WHERE lid = '$lid'";

    $result = mysql_query( $sql );

    if ( ! ( $tmp = mysql_fetch_row( $result ) ) )
    {
        $title = $prefix . translate( 'This Download' );
    }
    else
    {
        $title = $tmp[0];
    }

    mysql_free_result( $result );

    return stripslashes( $title );
}


if (!isset($op))
{
    $op = null;
}

switch($op) {

    case "AddLink":
        if (!isset($title))
        {
            $title = null;
        }

        if (!isset($url))
        {
            $url = null;
        }

        if (!isset($cat))
        {
            $cat = null;
        }

        if (!isset($description))
        {
            $description = null;
        }

        if (!isset($name))
        {
            $name = null;
        }

        if (!isset($email))
        {
            $email = null;
        }

        if (!isset($cat))
        {
            $cat = null;
        }

        AddLink($title, $url, $cat, $description, $name, $email);
        break;

    case "NewLinks":
        if (!isset($newlinkshowdays))
        {
            $newlinkshowdays = null;
        }

        NewLinks($newlinkshowdays);
        break;

    case "NewLinksDate":
        NewLinksDate($selectdate);
        break;

    case "TopRated":
        if (!isset($ratenum))
        {
            $ratenum = null;
        }

        if (!isset($ratetype))
        {
            $ratetype = null;
        }

        TopRated($ratenum, $ratetype);
        break;

    case "MostPopular":
        if (!isset($ratenum))
        {
            $ratenum = null;
        }

        if (!isset($ratetype))
        {
            $ratetype = null;
        }

        MostPopular($ratenum, $ratetype);
        break;

    case "RandomLink":
        RandomLink();
        break;

    case "viewlink":
        if (!isset($min))
        {
            $min = null;
        }

        if (!isset($orderby))
        {
            $orderby = null;
        }

        if (!isset($show))
        {
            $show = null;
        }

        viewlink($cid, $min, $orderby, $show);
        break;

    case "viewslink":
        if (!isset($min))
        {
            $min = null;
        }

        if (!isset($orderby))
        {
            $orderby = null;
        }

        if (!isset($show))
        {
            $show = null;
        }

        viewslink($sid, $min, $orderby, $show);
        break;

    case "brokenlink":
        brokenlink($lid);
        break;

    case "modifylinkrequest":
        modifylinkrequest($lid);
        break;

    case "modifylinkrequestS":
		if (!isset($cat2))
		{
		    $cat2 = null;
		}

		if (!isset($title))
		{
		    $title = null;
		}

		if (!isset($url))
		{
		    $url = null;
		}

		if (!isset($description))
		{
		    $description = null;
		}

		if (!isset($modifysubmitter))
		{
		    $modifysubmitter = null;
		}

        modifylinkrequestS($lid, $cat2, $title, $url, $description, $modifysubmitter);
        break;

    case "brokenlinkS":
		if (!isset($modifysubmitter))
		{
		    $modifysubmitter = null;
		}

        brokenlinkS($lid, $modifysubmitter);
        break;

    case "visit":
        visit($lid);
        break;

    case "Add":
		if (!isset($spider))
		{
		    $spider = null;
		}

		if (!isset($title))
		{
		    $title = null;
		}

		if (!isset($cat))
		{
		    $cat = null;
		}

		if (!isset($description))
		{
		    $description = null;
		}

		if (!isset($name))
		{
		    $name = null;
		}

		if (!isset($email))
		{
		    $email= null;
		}

        if (isset($spider))
		{
                get_spider($title, $url, $cat, $description, $name, $email);
        } else {
            if (!isset($cat2))
            {
                $cat2 = null;
            }

            Add($title, $url, $cat2, $description, $name, $email,$spider = 0 );
        }
        break;

    case "search":
        if (!isset($min))
        {
            $min = null;
        }

        if (!isset($orderby))
        {
            $orderby = null;
        }

        if (!isset($show))
        {
            $show = null;
        }

        searchlink($query, $min, $orderby, $show);
        break;

    case "rateinfo":
        rateinfo($lid);
        break;

    case "ratelink":
        ratelink($lid);
        break;

    case "addrating":
		if (!isset($ratinguser))
		{
		    $ratinguser = null;
		}

		if (!isset($rating))
		{
		    $rating = null;
		}

		if (!isset($ratinghost_name))
		{
		    $ratinghost_name = null;
		}

		if (!isset($ratingcomments))
		{
		    $ratingcomments = null;
		}

        addrating($ratinglid, $ratinguser, $rating, $ratinghost_name, $ratingcomments);
        break;

    case "viewlinkcomments":
            viewlinkcomments($lid);
        break;

    case "outsidelinksetup":
            outsidelinksetup($lid);
            break;

    case "viewlinkeditorial":
            viewlinkeditorial($lid);
        break;

    case "viewlinkdetails":
            viewlinkdetails($lid);
        break;

    default:
        index();
        break;

}



?>
