<?PHP
/************************************************************************/
/* NPDS V : Net Portal Dynamic System !                                 */
/* ===========================                                          */
/*                                                                      */
/* Original Copyright (c) 2001 by Francisco Burzi (fburzi@ncc.org.ve)   */
/* http://phpnuke.org                                                   */
/*                                                                      */
/* This version name NPDS Copyright (c) 2001-2004 by Philippe Brunier   */
/*                                                                      */
/* ====================================                                 */
/* 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.       */
/************************************************************************/
if (!function_exists("Mysql_Connexion")) {include ("mainfile.php");}
global $pdst; $pdst=0;

function logo() {
   global $linkmainlogo;
   if ($linkmainlogo==1) {
      if ($ibid=theme_image("links/web.gif")) {$imgtmp=$ibid;} else {$imgtmp="images/links/web.gif";}
      echo "<center><BR><a href=links.php><img src=\"$imgtmp\" border=\"0\" alt=\"\" /></a></center><BR>";
   }
}

function menu($mainlink) {
   echo "<CENTER><TABLE align=center CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=000000><TR><TD COLSPAN=2>";
   echo "<TABLE align=center CELLSPACING=0 CELLPADDING=2 BORDER=0 CLASS=\"HEADER\">
   <TR><TD>";
   if ($mainlink>0) {
      echo "<a href=links.php CLASS=\"BOX\">".translate("Links Main")."</a>&nbsp|&nbsp</TD><TD>";
   }
   echo "<a href=links.php?op=AddLink CLASS=\"BOX\">".translate("Add Link")."</a></TD><TD>
   &nbsp|&nbsp<a href=links.php?op=NewLinks CLASS=\"BOX\">".translate("New")."</a></TD><TD>
   &nbsp|&nbsp<a href=links.php?op=MostPopular CLASS=\"BOX\">".translate("Popular")."</a></TD><TD>
   &nbsp|&nbsp<a href=links.php?op=TopRated CLASS=\"BOX\">".translate("Top Rated")."</a></TD><TD>
   &nbsp|&nbsp<a href=links.php?op=RandomLink CLASS=\"BOX\">".translate("Random")."</a>";
   echo "</TD></TR></TABLE>";
   echo "</tr></td></TABLE>";
}

function SearchForm() {
   echo "<center><form action=links.php?op=search&query=$query method=POST>";
   echo "<table border=0 cellspacing=0 cellpadding=0>
   <tr><td><input type=text CLASS=\"TEXTBOX_STANDARD\" size=25 name=query> <input type=submit  CLASS=\"BOUTON_STANDARD\" value=".translate("Search")."></td></tr>
   </table>";
   echo "</form></center>";
}

function mainheader() {
   $mainlink = 1;
   echo "<CENTER>
   <TABLE align=center CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=000000>
   <TR><TD COLSPAN=2>

   <TABLE align=center CELLSPACING=0 CELLPADDING=2 BORDER=0 CLASS=\"HEADER\">
   <TR><TD>";
   if ($mainlink>0) {
      echo "<a href=links.php CLASS=\"BOX\">".translate("Links Main")."</a>&nbsp;|</TD><TD>";
   }
   echo "<a href=links.php?op=AddLink CLASS=\"BOX\">".translate("Add Link")."</a></TD><TD>
   |&nbsp;<a href=links.php?op=NewLinks CLASS=\"BOX\">".translate("New")."</a></TD><TD>
   |&nbsp;<a href=links.php?op=MostPopular CLASS=\"BOX\">".translate("Popular")."</a></TD><TD>
   |&nbsp;<a href=links.php?op=TopRated CLASS=\"BOX\">".translate("Top Rated")."</a></TD><TD>
   |&nbsp;<a href=links.php?op=RandomLink CLASS=\"BOX\">".translate("Random")."</a>
   </TD></TR></table></td></tr></TABLE>";
   echo "<table width=100%><tr><td><tr><td width=50%>";
   logo();
   echo "<BR>";
   SearchForm();
   echo "</td></tr></table>";
}

function linkinfomenu($lid,$ttitle) {
   $ttitle = ereg_replace(" ", "_", $ttitle);
   echo"<BR>
   <a href=links.php?op=viewlinkcomments&lid=$lid&ttitle=$ttitle CLASS=\"NOIR\">".translate("Link Comments")."</a>
   | <a href=links.php?op=viewlinkdetails&lid=$lid&ttitle=$ttitle CLASS=\"NOIR\">".translate("Additional Details")."</a>
   | <a href=links.php?op=viewlinkeditorial&lid=$lid&ttitle=$ttitle CLASS=\"NOIR\">".translate("Editor Review")."</a>
   | <a href=links.php?op=modifylinkrequest&lid=$lid CLASS=\"NOIR\">".translate("Modify")."</a>
   <BR><a href=links.php?op=brokenlink&lid=$lid CLASS=\"NOIR\">".translate("Report Broken Link")."</a><BR>";
}

function index() {
 include("header.php");
 // Include cache manager
 global $SuperCache;
 if ($SuperCache) {
    $cache_obj = new cacheManager();
    $cache_obj->startCachingPage();
 }
 if (($cache_obj->genereting_output==1) or ($cache_obj->genereting_output==-1) or (!$SuperCache)) {
    OpenTable();
    $mainlink = 0;
    menu($mainlink);
    logo();
    SearchForm();

    echo "<table width=100% border=0 cellspacing=0 cellpadding=0><tr>";

    $result=mysql_query("select cid, title, cdescription from links_categories order by title");
    $count = 0;
    while(list($cid, $title, $cdescription) = mysql_fetch_row($result)) {
       $cresult = mysql_query("select * from links_links where cid='$cid'");
       $cnumrows = mysql_num_rows($cresult);
       echo "<td valign=top width=200><a href=links.php?op=viewlink&cid=$cid CLASS=\"NOIR\"><b>$title</b></a> <font size=1>($cnumrows)</font>";
       categorynewlinkgraphic($cid);
       if ($cdescription) {
           echo "<BR><font size=1><i>$cdescription</i><BR></font>";
       } else {
           echo "<BR>";
       }
       $result2 = mysql_query("select sid, title from links_subcategories where cid='$cid' order by title limit 0,5");
       $space = 0;
       while(list($sid, $stitle) = mysql_fetch_row($result2)) {
          if ($space>0) {
             echo "<BR>";
          }
          echo "&nbsp;<a href=links.php?op=viewslink&sid=$sid CLASS=\"NOIR\">$stitle</a>";
          $space++;
       }
       if ($count<1) {
         echo "</td><td width=20>&nbsp;</td>";
       }
       $count++;
       if ($count==2) {
          echo "</td></tr><tr><td>&nbsp;</td></tr><tr>";
          $count = 0;
       }
    }
    echo "</td></tr></table>";
    $result=mysql_query("select * from links_links");
    $numrows = mysql_num_rows($result);
    echo "<BR><BR><center><font size=1>".translate("There are")." <b>$numrows</b> ".translate("Links in our Database")."</font></center>";
    CloseTable();
 }
 if ($SuperCache) {
    $cache_obj->endCachingPage();
 }
 include("footer.php");
}

function AddLink() {
    global $links_anonaddlinklock, $user;
    include("header.php");
    OpenTable();
    $mainlink = 1;
    mainheader();
    echo "</center><TABLE WIDTH=100% CELLSPACING=0 CELLPADDING=1 BORDER=0><TR><TD COLSPAN=2>
    <TABLE WIDTH=100% CELLSPACING=0 CELLPADDING=8 BORDER=0><TR><TD>";

    if (isset($user) || $links_anonaddlinklock != 1) {
       echo "<LI>".translate("Submit a unique link only once.")."
       <LI>".translate("All links are posted pending verification.")."
       <LI>".translate("Username and IP are recorded, so please don't abuse the system.")."
       <form method=post action=links.php?op=Add  name=adminForm>
       ".translate("Page Title: ")."<BR><input type=text CLASS=\"TEXTBOX\" name=title size=50 maxlength=100><BR><BR>
       ".translate("Page URL: ")."<BR><input type=text CLASS=\"TEXTBOX\" name=url size=50 maxlength=100 value=\"http://\"><BR><BR>";
       $result=mysql_query("select cid, title from links_categories order by title");
       echo translate("Category: ")."<select CLASS=\"TEXTBOX_STANDARD\" name=cat>";
       while(list($cid, $title) = mysql_fetch_row($result)) {
          echo "<option value=$cid>$title</option>";
          $result2=mysql_query("select sid, title from links_subcategories where cid='$cid' order by title");
          while(list($sid, $stitle) = mysql_fetch_row($result2)) {
             echo "<option value=$cid-$sid>$title / $stitle</option>";
          }
       }
       echo "</select><BR><BR>
       ".translate("Description: (255 characters max)")."<br /><textarea class=\"textbox\" wrap=\"virtual\" name=\"xtext\" cols=\"70\" rows=\"10\" style=\"width: 100%;\"></textarea>";
       echo aff_editeur("xtext","false");
       echo "<br /><br />";
       echo translate("Your Name: ")."<input type=text CLASS=\"TEXTBOX_STANDARD\" name=name size=30 maxlength=60><BR>
       ".translate("Your Email: ")."<input type=text CLASS=\"TEXTBOX_STANDARD\" name=email size=30 maxlength=60><BR><BR>
       <input type=hidden name=op value=Add>
       <input type=submit CLASS=\"BOUTON_STANDARD\" value=".translate("Add URL").">
       </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.php>".translate("Register for an Account")."</a>";
    }
    echo "</TD></TR></TABLE></TD></TR></TABLE>";
    CloseTable();
    include("footer.php");
}

function Add($title, $url, $name, $cat, $xtext, $name, $email) {
    $result = mysql_query("select url from links_links where url='$url'");
    $numrows = mysql_num_rows($result);
    if ($numrows>0) {
       include("header.php");
       OpenTable();
       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>";
       echo "<font CLASS=\"ROUGE\">";
       echo "<b>".translate("ERROR: This URL is already listed in the Database!")."</b></FONT><BR><BR>";
       echo "</TD></TR></TABLE></TD></TR></TABLE>";
       closetable();
       include("footer.php");
    } else {
       if (isset($user)) {
          global $cookie;
          $submitter=$cookie[1];
       }
       // Check if Title exist
       if ($title=="") {
          include("header.php");
          OpenTable();
          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>";
          echo "<font CLASS=\"ROUGE\">";
          echo "<b>".translate("ERROR: You need to type a TITLE for your URL!")."</b></FONT><BR><BR>";
          echo "</TD></TR></TABLE></TD></TR></TABLE>";
          closetable();
          include("footer.php");
       }
       // Check if URL exist
       if ($url=="") {
          include("header.php");
          OpenTable();
          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>";
          echo "<font CLASS=\"ROUGE\">";
          echo "<b>".translate("ERROR: You need to type a URL for your URL!")."</b></FONT><BR><BR>";
          echo "</TD></TR></TABLE></TD></TR></TABLE>";
          closetable();
          include("footer.php");
       }
       // Check if Description exist
       if ($xtext=="") {
          include("header.php");
          OpenTable();
          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>";
          echo "<font CLASS=\"ROUGE\">";
          echo "<b>".translate("ERROR: You need to type a DESCRIPTION for your URL!")."</b></FONT><BR><BR>";
          echo "</TD></TR></TABLE></TD></TR></TABLE>";
          closetable();
          include("footer.php");
       }
       if ($email=="") {
          include("header.php");
          OpenTable();
          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>";
          echo "<font CLASS=\"ROUGE\">";
          echo "<b>".translate("ERROR: Invalid email")."</b></FONT><BR><BR>";
          echo "</TD></TR></TABLE></TD></TR></TABLE>";
          closetable();
          include("footer.php");
       }
       $cat = explode("-", $cat);
       if ($cat[1]=="") {
          $cat[1] = 0;
       }
       $title = stripslashes(FixQuotes($title));
       $url = stripslashes(FixQuotes($url));
       $xtext = stripslashes(FixQuotes($xtext));
       $name = stripslashes(FixQuotes($name));
       $email = stripslashes(FixQuotes($email));
       mysql_query("insert into links_newlink values (NULL, '$cat[0]', '$cat[1]', '$title', '$url', '$xtext', '$name', '$email', '$submitter','')");
       include("header.php");
       OpenTable();
       $mainlink = 1;
       menu($mainlink);
       SearchForm();
       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>";
       echo translate("We received your Link submission. Thanks!")."<BR>";
       echo translate("You'll receive and E-mail when it's approved.")."<BR><BR>";
       echo "</TD></TR></TABLE></TD></TR></TABLE>";
       closetable();
       include("footer.php");
    }
}
function NewLinks($newlinkshowdays) {
    global $admin;
    include("header.php");
    OpenTable();
    mainheader();
    echo "<TABLE WIDTH=100% CELLSPACING=0 CELLPADDING=8 BORDER=0><TR><TD>";
    echo "<TABLE WIDTH=100% CELLSPACING=2 CELLPADDING=2 BORDER=0 CLASS=\"HEADER\"><TR><TD>";
    echo "<b>".translate("New Links")."</b>";
    echo "</tr></td></table><BR>";

    $counter = 0;
    $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 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));
        $newlinkDB = Date("Y-m-d", $newlinkdayRaw);
        $result = mysql_query("select * FROM links_links WHERE date LIKE '%$newlinkDB%'");
        $totallinks = mysql_num_rows($result);
        $allmonthlinks = $allmonthlinks + $totallinks;
        $counter++;
    }
    echo translate("Total new links: Last week")." : $allweeklinks<BR>".translate("Last 30 days")." : $allmonthlinks<BR>
    ".translate("Show:")." (<a href=links.php?op=NewLinks&newlinkshowdays=7 CLASS=\"NOIR\">".translate("week")."</a>, <a href=links.php?op=NewLinks&newlinkshowdays=14 CLASS=\"NOIR\">2 ".translate("weeks")."</a>, <a href=links.php?op=NewLinks&newlinkshowdays=30 CLASS=\"NOIR\">30 ".translate("days")."</a>)
    <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));
       $masq=str_replace("H:i","",translate("dateinternal"));
       $newlinkView = date($masq, $newlinkdayRaw);
       $newlinkDB = Date("Y-m-d", $newlinkdayRaw);
       $result = mysql_query("select * FROM links_links WHERE date LIKE '%$newlinkDB%'");
       $totallinks = mysql_num_rows($result);
       $counter++;
       $allweeklinks = $allweeklinks + $totallinks;
       echo "<LI><a href=links.php?op=NewLinksDate&selectdate=$newlinkdayRaw CLASS=\"NOIR\">$newlinkView</a>&nbsp( $totallinks )";
    }
    $counter = 0;
    $allmonthlinks = 0;

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

function NewLinksDate($selectdate) {
    global $admin;
    $dateDB = (date("d-M-Y", $selectdate));
    $masq=str_replace("H:i","",translate("dateinternal"));
    $dateView = date($masq, $selectdate);

    include("header.php");
    OpenTable();
    mainheader();
    $newlinkDB = Date("Y-m-d", $selectdate);
    $result = mysql_query("select * FROM links_links WHERE date LIKE '%$newlinkDB%'");
    $totallinks = mysql_num_rows($result);

    echo "<TABLE WIDTH=100% CELLSPACING=0 CELLPADDING=8 BORDER=0><TR><TD>";
    echo "<TABLE WIDTH=100% CELLSPACING=2 CELLPADDING=2 BORDER=0 CLASS=\"HEADER\"><TR><TD>";
    echo "<b>$dateView - $totallinks ".translate("New Links")."</b>";
    echo "</TD></TR></TABLE>";

    $result=mysql_query("select lid, cid, sid, title, description, date, hits, linkratingsummary, totalvotes, totalcomments from links_links where date LIKE '%$newlinkDB%' order by title ASC");
    echo "<table width=100% cellspacing=0 cellpadding=10 border=0><tr><td>";
    while(list($lid, $cid, $sid, $title, $description, $time, $hits, $linkratingsummary, $totalvotes, $totalcomments)=mysql_fetch_row($result)) {
        $linkratingsummary = number_format($linkratingsummary, $mainvotedecimal);
        $title = stripslashes($title); $description = stripslashes($description);
        if ($ibid=theme_image("links/urlgo.gif")) {$imgtmp=$ibid;} else {$imgtmp="images/links/urlgo.gif";}
        echo "<HR NOSHADE CLASS=\"ONGL\">";
        echo "<img src=\"$imgtmp\" border=\"\" alt=\"\" /> <a href=links.php?op=visit&lid=$lid target=_blank CLASS=\"NOIR\">$title</a>";
        newlinkgraphic($datetime, $time);
        popgraphic($hits);
        echo "<BR>";
        echo translate("Description: ")."$description<BR>";
        global $locale;
        setlocale (LC_TIME, aff_langue($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]));
        if (cur_charset!="utf-8") {
           $datetime = ucfirst($datetime);
        }
        echo translate("Added on: ").$datetime.translate("Hits: ").$hits." ";
        if (strstr($title,"<img src")) {
           $pos = strpos($title, "<img src");
              $title=substr($title,0,$pos);
              $transfertitle = check_html(str_replace (" ", "_", $title),"nohtml");
        } else {
           $transfertitle = str_replace (" ", "_", $title);
        }
        if ($totalvotes == 1) $votestring=translate("vote");
        else $votestring=translate("votes");
        if ($linkratingsummary!="0" || $linkratingsummary!="0.0") echo translate("Rating")." : $linkratingsummary ($totalvotes $votestring)";
        echo "<BR><a href=links.php?op=ratelink&lid=$lid&ttitle=$transfertitle CLASS=\"NOIR\">".translate("Rate this Site")."</a>";
        if ($totalvotes != 0) echo "&nbsp|&nbsp<a href=\"links.php?op=viewlinkdetails&lid=$lid&ttitle=$transfertitle\" CLASS=\"NOIR\">".translate("Details")."</a>";
        if ($totalcomments != 0) echo "&nbsp|&nbsp<a href=\"links.php?op=viewlinkcomments&lid=$lid&ttitle=$transfertitle\" CLASS=\"NOIR\">".translate("Comments")." ($totalcomments)</a>";
        $result2=mysql_query("select title from links_categories where cid='$cid'");
        detecteditorial($lid, $transfertitle);
        echo "<BR><BR>";
        list($ctitle) = mysql_fetch_row($result2);
        echo translate("Category: ").$ctitle;
        $result3=mysql_query("select title from links_subcategories where sid='$sid'");
        while(list($stitle) = mysql_fetch_row($result3)) {
           echo " / $stitle";
        }
        echo "<HR NOSHADE CLASS=\"ONGL\"><BR>";
    }
    echo "</TD></TR></TABLE></TD></TR></TABLE>";
    CloseTable();
    include("footer.php");
}

function TopRated($ratenum, $ratetype) {
    global $admin, $toplinks;
    include("header.php");
    OpenTable();
    mainheader();
    if ($ratenum != "" && $ratetype != "") {
       $toplinks = $ratenum;
       if ($ratetype == "percent") $toplinkspercentrigger = 1;
    }
    if ($ratenum == "") {
       $toplinks = 10;
    }
    if ($toplinkspercentrigger == 1) {
       $toplinkspercent = $toplinks;
       $result=mysql_query("select * from 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 CLASS=\"HEADER\"><TR><TD>";
    if ($toplinkspercentrigger == 1) { echo "<b>".translate("Best Rated Links - Top")." $toplinkspercent% (".translate("of")." $totalratedlinks ".translate("total rated links").")</b>";}
    else {echo "<b>".translate("Best Rated Links - Top")." $toplinks </b>";}
    echo "</TR></TD></table>";

    echo "<tr><td><center>".translate("Note").": $linkvotemin ".translate("total votes requirement")."<BR>".translate("Show Top")." : (<a href=links.php?op=TopRated&ratenum=10&ratetype=num CLASS=\"NOIR\">10</a>,
          <a href=links.php?op=TopRated&ratenum=25&ratetype=num CLASS=\"NOIR\">25</a>,
          <a href=links.php?op=TopRated&ratenum=50&ratetype=num CLASS=\"NOIR\">50</a> |
          <a href=links.php?op=TopRated&ratenum=1&ratetype=percent CLASS=\"NOIR\">1%</a>,
          <a href=links.php?op=TopRated&ratenum=5&ratetype=percent CLASS=\"NOIR\">5%</a>,
          <a href=links.php?op=TopRated&ratenum=10&ratetype=percent CLASS=\"NOIR\">10%</a>)</center><BR></td></tr>";
    settype($toplinks,"integer");
    $result=mysql_query("select lid, cid, sid, title, description, date, hits, linkratingsummary, totalvotes, totalcomments from 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);
        $title = stripslashes($title); $description = stripslashes($description);
        if ($ibid=theme_image("links/urlgo.gif")) {$imgtmp=$ibid;} else {$imgtmp="images/links/urlgo.gif";}
        echo "<HR NOSHADE CLASS=\"ONGL\">";
        echo "<img src=\"$imgtmp\" border=\"\" alt=\"\" /> <a href=links.php?op=visit&lid=$lid target=_blank CLASS=\"NOIR\">$title</a>";
        newlinkgraphic($datetime, $time);
        popgraphic($hits);
        echo "<BR>";
        echo translate("Description: ").$description."<BR>";
        global $locale;
        setlocale (LC_TIME, aff_langue($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]));
        if (cur_charset!="utf-8") {
           $datetime = ucfirst($datetime);
        }
        echo translate("Added on: ").$datetime.translate("Hits: ").$hits." ";
        if (strstr($title,"<img src")) {
           $pos = strpos($title, "<img src");
              $title=substr($title,0,$pos);
              $transfertitle = check_html(str_replace (" ", "_", $title),"nohtml");
        } else {
           $transfertitle = str_replace (" ", "_", $title);
        }
        //voting & comments stats
        if ($totalvotes == 1) $votestring=translate("vote");
        else $votestring=translate("votes");
        if ($linkratingsummary!="0" || $linkratingsummary!="0.0") echo translate("Rating")." :<b> $linkratingsummary </b>($totalvotes $votestring)";
        echo "<BR><a href=links.php?op=ratelink&lid=$lid&ttitle=$transfertitle CLASS=\"NOIR\">".translate("Rate this Site")."</a>";
        if ($totalvotes != 0) echo "&nbsp|&nbsp<a href=\"links.php?op=viewlinkdetails&lid=$lid&ttitle=$transfertitle\" CLASS=\"NOIR\">".translate("Details")."</a>";
        if ($totalcomments != 0) echo "&nbsp|&nbsp<a href=\"links.php?op=viewlinkcomments&lid=$lid&ttitle=$transfertitle\" CLASS=\"NOIR\">".translate("Comments")." ($totalcomments)</a>";
        detecteditorial($lid, $transfertitle);
        echo "<BR><BR>";
        $result2=mysql_query("select title from links_categories where cid='$cid'");
        list($ctitle) = mysql_fetch_row($result2);
        echo translate("Category: ").$ctitle;
        $result3=mysql_query("select title from links_subcategories where sid='$sid'");
        while(list($stitle) = mysql_fetch_row($result3)) {
           echo " / $stitle";
        }
        echo "<HR NOSHADE CLASS=\"ONGL\"><BR>";
    }
    echo "</tr></td>";
    echo "</TD></TR></TABLE>";
    CloseTable();
    include("footer.php");
}

function MostPopular($ratenum, $ratetype) {
    global $admin, $toplinks;
    include("header.php");
    OpenTable();
    mainheader();
    if ($ratenum != "" && $ratetype != "") {
       $mostpoplinks = $ratenum;
       if ($ratetype == "percent") $mostpoplinkspercentrigger = 1;
    }
    if ($ratenum == "") {
       $mostpoplinks = $toplinks;
    }
    if ($mostpoplinkspercentrigger == 1) {
       $toplinkspercent = $mostpoplinks;
       $result=mysql_query("select * from 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 CLASS=\"HEADER\"><TR><TD>";
    if ($mostpoplinkspercentrigger == 1) {echo "<b>".translate("Most Popular - Top")." $toplinkspercent% (".translate("of all")." $totalmostpoplinks ".translate("links").")</b>";}
    else {echo "<b>".translate("Most Popular - Top")." $mostpoplinks </b>";}
    echo "</TD></TR></TABLE>";
    echo "<tr><td><center>".translate("Show Top").": (<a href=links.php?op=MostPopular&ratenum=10&ratetype=num CLASS=\"NOIR\">10</a>,
         <a href=links.php?op=MostPopular&ratenum=25&ratetype=num CLASS=\"NOIR\">25</a>,
         <a href=links.php?op=MostPopular&ratenum=50&ratetype=num CLASS=\"NOIR\">50</a> |
         <a href=links.php?op=MostPopular&ratenum=1&ratetype=percent CLASS=\"NOIR\">1%</a>,
         <a href=links.php?op=MostPopular&ratenum=5&ratetype=percent CLASS=\"NOIR\">5%</a>,
         <a href=links.php?op=MostPopular&ratenum=10&ratetype=percent CLASS=\"NOIR\">10%</a>)</center><BR></td></tr>";
    settype($mostpoplinks,"integer");
    $result=mysql_query("select lid, cid, sid, title, description, date, hits, linkratingsummary, totalvotes, totalcomments from 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);
        $title = stripslashes($title); $description = stripslashes($description);
        if ($ibid=theme_image("links/urlgo.gif")) {$imgtmp=$ibid;} else {$imgtmp="images/links/urlgo.gif";}
        echo "<HR NOSHADE CLASS=\"ONGL\">";
        echo "<img src=\"$imgtmp\" border=\"\" alt=\"\" /> <a href=links.php?op=visit&lid=$lid target=_blank CLASS=\"NOIR\">$title</a>";
        newlinkgraphic($datetime, $time);
        popgraphic($hits);

        echo "<BR>";
        echo translate("Description: ").$description."<BR>";
        global $locale;
        setlocale (LC_TIME, aff_langue($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]));
        if (cur_charset!="utf-8") {
           $datetime = ucfirst($datetime);
        }
        echo translate("Added on: ").$datetime.translate("Hits: ")."<b>$hits</b> ";
        if (strstr($title,"<img src")) {
           $pos = strpos($title, "<img src");
              $title=substr($title,0,$pos);
              $transfertitle = check_html(str_replace (" ", "_", $title),"nohtml");
        } else {
           $transfertitle = str_replace (" ", "_", $title);
        }
        //voting & comments stats
        if ($totalvotes == 1) $votestring = "".translate("vote")."";
                else $votestring = "".translate("votes")."";
        if ($linkratingsummary!="0" || $linkratingsummary!="0.0") echo translate("Rating")." : $linkratingsummary ($totalvotes $votestring)";
        echo "<BR><a href=links.php?op=ratelink&lid=$lid&ttitle=$transfertitle CLASS=\"NOIR\">".translate("Rate this Site")."</a>";
        if ($totalvotes != 0) echo "&nbsp|&nbsp<a href=\"links.php?op=viewlinkdetails&lid=$lid&ttitle=$transfertitle\" CLASS=\"NOIR\">".translate("Details")."</a>";
        if ($totalcomments != 0) echo "&nbsp|&nbsp<a href=\"links.php?op=viewlinkcomments&lid=$lid&ttitle=$transfertitle\" CLASS=\"NOIR\">".translate("Comments")." ($totalcomments)</a>";
        detecteditorial($lid, $transfertitle);
        echo "<BR><BR>";
        $result2=mysql_query("select title from links_categories where cid='$cid'");
        list($ctitle) = mysql_fetch_row($result2);
        echo translate("Category: ").$ctitle;
        $result3=mysql_query("select title from links_subcategories where sid='$sid'");
        while(list($stitle) = mysql_fetch_row($result3)) {
            echo " / $stitle";
        }
        echo "<HR NOSHADE CLASS=\"ONGL\"><BR>";
    }
    echo "</tr></td>";
    echo "</TD></TR></TABLE>";
    CloseTable();
    include("footer.php");
}
function RandomLink() {
    $result = mysql_query("select * from links_links");
    $numrows = mysql_num_rows($result);
    srand((double)microtime()*1000000);
    $random = rand(1,$numrows);
    $result2 = mysql_query("select url from links_links where lid='$random'");
    list($url) = mysql_fetch_row($result2);
    mysql_query("update links_links set hits=hits+1 where lid='$random'");
    Header("Location: $url");
}

function FooterOrderBy($cid, $sid, $orderbyTrans, $linkop) {
    echo "<center><BR><font size=1>".translate("Sort links by")." : ";
    if ($linkop=="viewlink") {
       echo translate("Title")." (<a href=links.php?op=$linkop&cid=$cid&orderby=titleA CLASS=\"NOIR\">A</a>\<a href=links.php?op=$linkop&cid=$cid&orderby=titleD CLASS=\"NOIR\">D</a>)
       ".translate("Date")." (<a href=links.php?op=$linkop&cid=$cid&orderby=dateA CLASS=\"NOIR\">A</a>\<a href=links.php?op=$linkop&cid=$cid&orderby=dateD CLASS=\"NOIR\">D</a>)
       ".translate("Rating")." (<a href=links.php?op=$linkop&cid=$cid&orderby=ratingA CLASS=\"NOIR\">A</a>\<a href=links.php?op=$linkop&cid=$cid&orderby=ratingD CLASS=\"NOIR\">D</a>)
       ".translate("Popularity")." (<a href=links.php?op=$linkop&cid=$cid&orderby=hitsA CLASS=\"NOIR\">A</a>\<a href=links.php?op=$linkop&cid=$cid&orderby=hitsD CLASS=\"NOIR\">D</a>)";
    } else {
       echo translate("Title")." (<a href=links.php?op=viewslink&sid=$sid&orderby=titleA CLASS=\"NOIR\">A</a>\<a href=links.php?op=viewslink&sid=$sid&orderby=titleD CLASS=\"NOIR\">D</a>)
       ".translate("Date")." (<a href=links.php?op=viewslink&sid=$sid&orderby=dateA CLASS=\"NOIR\">A</a>\<a href=links.php?op=viewslink&sid=$sid&orderby=dateD CLASS=\"NOIR\">D</a>)
       ".translate("Rating")." (<a href=links.php?op=viewslink&sid=$sid&orderby=ratingA CLASS=\"NOIR\">A</a>\<a href=links.php?op=viewslink&sid=$sid&orderby=ratingD CLASS=\"NOIR\">D</a>)
       ".translate("Popularity")." (<a href=links.php?op=viewslink&sid=$sid&orderby=hitsA CLASS=\"NOIR\">A</a>\<a href=links.php?op=viewslink&sid=$sid&orderby=hitsD CLASS=\"NOIR\">D</a>)";
    }
    echo "</font>";
    echo "<BR><font size=1>".translate("Sites currently sorted by").": $orderbyTrans</font></center>";
}

function viewlink($cid, $min, $orderby, $show) {
   global $admin, $perpage, $show;
   $result=mysql_query("select title from links_categories where cid='$cid'");
   list($title) = mysql_fetch_row($result);
   $carrytitle = $title;
   include("header.php");
   // Include cache manager
   global $SuperCache;
   if ($SuperCache) {
      $cache_obj = new cacheManager();
      $cache_obj->startCachingPage();
   }
   if (($cache_obj->genereting_output==1) or ($cache_obj->genereting_output==-1) or (!$SuperCache)) {
    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;
    mainheader();
    echo "<TABLE WIDTH=100% CELLSPACING=0 CELLPADDING=2 BORDER=0><TR><TD>";
    echo "<TABLE WIDTH=100% CELLSPACING=2 CELLPADDING=2 BORDER=0 CLASS=\"HEADER\"><TR><TD>";
    echo "<b>".translate("SubCategories")."</b>";
    echo "</TD></TR></TABLE>";
    $subresult=mysql_query("select sid, title from links_subcategories where cid='$cid' order by title");
    $numrows = mysql_num_rows($subresult);
    if ($numrows != 0) {
        echo "<table>";
        while(list($sid, $title) = mysql_fetch_row($subresult)) {
           $result2 = mysql_query("select * from links_links where sid='$sid'");
           $numrows = Mysql_num_rows($result2);
           echo "<tr><td><li><a href=links.php?op=viewslink&sid=$sid CLASS=\"NOIR\">$title</a> <font size=1>($numrows)</font></li></td></tr>";
        }
        echo "
        </tr>
        <tr>
        <td colspan=5></td>
        </tr>
        </table>";
    }
    $orderbyTrans = convertorderbytrans($orderby);
    settype($min,"integer");
    settype($perpage,"integer");
    $result=mysql_query("select lid, title, description, date, hits, linkratingsummary, totalvotes, totalcomments from 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 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>";
    $x=0;
    while(list($lid, $title, $description, $time, $hits, $linkratingsummary, $totalvotes, $totalcomments)=mysql_fetch_row($result)) {
        $linkratingsummary = number_format($linkratingsummary, $mainvotedecimal);
        $title = stripslashes($title); $description = stripslashes($description);
        if ($ibid=theme_image("links/urlgo.gif")) {$imgtmp=$ibid;} else {$imgtmp="images/links/urlgo.gif";}
        echo "<HR NOSHADE CLASS=\"ONGL\">";
        echo "<img src=\"$imgtmp\" border=\"\" alt=\"\" /> <a href=links.php?op=visit&lid=$lid target=_blank CLASS=\"NOIR\">$title</a>";
        newlinkgraphic($datetime, $time);
        popgraphic($hits);
        echo "<BR>";
        echo translate("Description: ").$description."<BR>";
        global $locale;
        setlocale (LC_TIME, aff_langue($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]));
        if (cur_charset!="utf-8") {
           $datetime = ucfirst($datetime);
        }
        echo translate("Added on: ").$datetime." ".translate("Hits: ").$hits." ";
        if (strstr($title,"<img src")) {
           $pos = strpos($title, "<img src");
              $title=substr($title,0,$pos);
              $transfertitle = check_html(str_replace (" ", "_", $title),"nohtml");
        } else {
           $transfertitle = str_replace (" ", "_", $title);
        }
        //voting & comments stats
        if ($totalvotes == 1) $votestring = "".translate("vote")."";
                else $votestring = "".translate("votes")."";
        if ($linkratingsummary!="0" || $linkratingsummary!="0.0") echo translate("Rating")." : $linkratingsummary ($totalvotes $votestring)";
        echo "<BR><a href=links.php?op=ratelink&lid=$lid&ttitle=$transfertitle CLASS=\"NOIR\">".translate("Rate this Site")."</a>";
        if ($totalvotes != 0) echo "&nbsp|&nbsp<a href=\"links.php?op=viewlinkdetails&lid=$lid&ttitle=$transfertitle\" CLASS=\"NOIR\">".translate("Details")."</a>";
        if ($totalcomments != 0) echo "&nbsp|&nbsp<a href=\"links.php?op=viewlinkcomments&lid=$lid&ttitle=$transfertitle\" CLASS=\"NOIR\">".translate("Comments")." ($totalcomments)</a>";
        detecteditorial($lid, $transfertitle);
        echo "<HR NOSHADE CLASS=\"ONGL\"><BR>";
        $x++;
    }

    $orderby = convertorderbyout($orderby);

    //Calculates how many pages exist.  Which page one should be on, etc...
    $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 "<center><font size=1>";
       echo translate("Select page")." :&nbsp&nbsp";
       $prev=$min-$perpage;
       $counter = 1;
       $currentpage = ($max / $perpage);
       while ($counter<=$linkpages ) {
          $mintemp = ($perpage * $counter) - $perpage;
          if ($counter == $currentpage) echo "<FONT CLASS=\"ROUGE\">$counter</FONT>&nbsp";
          else echo "<a href=links.php?op=viewlink&cid=$cid&min=$mintemp&orderby=$orderby&show=$show CLASS=\"NOIR\">$counter</a>&nbsp";
          $counter++;
       }
       echo "</font></center>";
    }
    echo "</TD></TR></TABLE>";
    FooterOrderBy($cid, $sid, $orderbyTrans, "viewlink");
    echo "</TD></TR></TABLE>";
    CloseTable();
   }
   if ($SuperCache) {
      $cache_obj->endCachingPage();
   }
   include("footer.php");
}

function viewslink($sid, $min, $orderby, $show) {
   global $admin, $perpage;
   $result = mysql_query("select cid, title from links_subcategories where sid='$sid'");
   list($cid, $stitle) = mysql_fetch_row($result);
   $title=$stitle;
   include("header.php");
   // Include cache manager
   global $SuperCache;
   if ($SuperCache) {
      $cache_obj = new cacheManager();
      $cache_obj->startCachingPage();
   }
   if (($cache_obj->genereting_output==1) or ($cache_obj->genereting_output==-1) or (!$SuperCache)) {
    OpenTable();
    mainheader();
    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 "<TABLE WIDTH=100% CELLSPACING=2 CELLPADDING=2 BORDER=0 CLASS=\"HEADER\"><TR><TD>";
    $result2 = mysql_query("select cid, title from links_categories where cid='$cid'");
    list($cid, $title) = mysql_fetch_row($result2);
    echo "<b><a href=links.php CLASS=\"BOX\">".translate("Main")."</a> / <a href=links.php?op=viewlink&cid=$cid CLASS=\"BOX\">$title</a> / $stitle</b>";
    echo "</TD></TR></TABLE>";

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

    echo "<table width=100% cellspacing=0 cellpadding=10 border=0><tr><td>";
    $x=0;
    while(list($lid, $url, $title, $description, $time, $hits, $linkratingsummary, $totalvotes, $totalcomments)=mysql_fetch_row($result)) {
        $linkratingsummary = number_format($linkratingsummary, $mainvotedecimal);
        $title = stripslashes($title); $description = stripslashes($description);
        if ($ibid=theme_image("links/urlgo.gif")) {$imgtmp=$ibid;} else {$imgtmp="images/links/urlgo.gif";}
        echo "<HR NOSHADE CLASS=\"ONGL\">";
        echo "<img src=\"$imgtmp\" border=\"\" alt=\"\" /> <a href=links.php?op=visit&lid=$lid target=_blank CLASS=\"NOIR\">$title</a>";
        newlinkgraphic($datetime, $time);
        popgraphic($hits);
        echo "<BR>";
        echo translate("Description: ").$description."<BR>";
        global $locale;
        setlocale (LC_TIME, aff_langue($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]));
        if (cur_charset!="utf-8") {
           $datetime = ucfirst($datetime);
        }
        echo translate("Added on: ").$datetime." ".translate("Hits: ").$hits." ";
        if (strstr($title,"<img src")) {
           $pos = strpos($title, "<img src");
              $title=substr($title,0,$pos);
              $transfertitle = check_html(str_replace (" ", "_", $title),"nohtml");
        } else {
           $transfertitle = str_replace (" ", "_", $title);
        }
        //voting & comments stats
        if ($totalvotes == 1) $votestring = "".translate("vote")."";
                else $votestring = "".translate("votes")."";
        if ($linkratingsummary!="0" || $linkratingsummary!="0.0") echo translate("Rating")." : $linkratingsummary ($totalvotes $votestring)";
        echo "<BR><a href=links.php?op=ratelink&lid=$lid&ttitle=$transfertitle CLASS=\"NOIR\">".translate("Rate this Site")."</a>";
        if ($totalvotes != 0) echo "&nbsp|&nbsp<a href=\"links.php?op=viewlinkdetails&lid=$lid&ttitle=$transfertitle\" CLASS=\"NOIR\">".translate("Details")."</a>";
        if ($totalcomments != 0) echo "&nbsp|&nbsp<a href=\"links.php?op=viewlinkcomments&lid=$lid&ttitle=$transfertitle\" CLASS=\"NOIR\">".translate("Comments")." ($totalcomments)</a>";
        detecteditorial($lid, $transfertitle);
        echo "<HR NOSHADE CLASS=\"ONGL\"><BR>";
        $x++;
    }

    $orderby = convertorderbyout($orderby);

    //Calculates how many pages exist.  Which page one should be on, etc...
    $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><center><font size=1>";
       echo translate("Select page")." :&nbsp&nbsp";
       $prev=$min-$perpage;
       $counter = 1;
       $currentpage = ($max / $perpage);
       while ($counter<=$linkpages ) {
          $mintemp = ($perpage * $counter) - $perpage;
          if ($counter == $currentpage) echo "<FONT CLASS=\"ROUGE\">$counter</FONT>&nbsp";
          else echo "<a href=links.php?op=viewslink&sid=$sid&min=$mintemp&orderby=$orderby&show=$show CLASS=\"NOIR\">$counter</a>&nbsp";
          $counter++;
       }
       echo "</font></center>";
    }
    echo "</TD></TR></TABLE>";
    FooterOrderBy($cid, $sid, $orderbyTrans, "viewslink");
    echo "</TD></TR></TABLE>";
    CloseTable();
   }
   if ($SuperCache) {
      $cache_obj->endCachingPage();
   }
   include("footer.php");
}

function newlinkgraphic($datetime, $time) {
   echo "&nbsp";
   global $locale;
   setlocale (LC_TIME, aff_langue($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);
   $count = round((time()- mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]))/86400,0);
   if ($ibid=theme_image("links/newred.gif")) {$imgtmp=$ibid;} else {$imgtmp="images/links/newred.gif";}
   if ($count<1) echo "<img src=\"$imgtmp\" border=\"\" alt=\"".translate("New Today")."\" />";
   if ($ibid=theme_image("links/newgreen.gif")) {$imgtmp=$ibid;} else {$imgtmp="images/links/newgreen.gif";}
   if ($count<=3 && $count>=1) echo "<img src=\"$imgtmp\" border=\"\" alt=\"".translate("New last 3 days")."\" />";
   if ($ibid=theme_image("links/newblue.gif")) {$imgtmp=$ibid;} else {$imgtmp="images/links/newblue.gif";}
   if ($count<=7 && $count>3) echo "<img src=\"$imgtmp\" border=\"\" alt=\"".translate("New this week")."\" />";
}

function categorynewlinkgraphic($cat) {
   global $OnCatNewLink;
   if ($OnCatNewLink) {
      $newresult = mysql_query("select date from links_links where cid='$cat' order by date desc limit 1");
      list($time)=mysql_fetch_row($newresult);
      echo "&nbsp";
      global $locale;
      setlocale (LC_TIME, aff_langue($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);
      $count = round((time()- mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]))/86400,0);
      if ($ibid=theme_image("links/newred.gif")) {$imgtmp=$ibid;} else {$imgtmp="images/links/newred.gif";}
      if ($count<1) echo "<img src=\"$imgtmp\" border=\"\" alt=\"".translate("New Links in this Category Added Today")."\" />";
      if ($ibid=theme_image("links/newgreen.gif")) {$imgtmp=$ibid;} else {$imgtmp="images/links/newgreen.gif";}
      if ($count<=3 && $count>=1) echo "<img src=\"$imgtmp\" border=\"\" alt=\"".translate("New Links in this Category Added in the last 3 days")."\" />";
      if ($ibid=theme_image("links/newblue.gif")) {$imgtmp=$ibid;} else {$imgtmp="images/links/newblue.gif";}
      if ($count<=7 && $count>3) echo "<img src=\"$imgtmp\" border=\"\" alt=\"".translate("New Links in this Category Added this week")."\" />";
   }
}

function popgraphic($hits) {
   global $popular;
   if ($hits>=$popular) {
      if ($ibid=theme_image("links/popular.gif")) {$imgtmp=$ibid;} else {$imgtmp="images/links/popular.gif";}
      echo "&nbsp;<img src=\"$imgtmp\" border=\"\" 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) {
   mysql_query("update links_links set hits=hits+1 where lid='$lid'");
   $result = mysql_query("select url from links_links where lid='$lid'");
   list($url) = mysql_fetch_row($result);
   Header("Location: $url");
}

function search($query, $min, $orderby, $show) {
    global $admin, $perpage, $show, $linksresults;
    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 = removeHack(stripslashes(htmlspecialchars($query, ENT_QUOTES))); // Romano et NoSP

    $fullcountresult=mysql_query("select lid, title, description, date, hits, linkratingsummary, totalvotes, totalcomments from links_links where title LIKE '%$query%' OR description LIKE '%$query%'");
    if ($fullcountresult) {
       $totalselectedlinks = Mysql_num_rows($fullcountresult);
       settype($min,"integer");
       settype($linksresults,"integer");
       $result = mysql_query("select lid from links_links where title LIKE '%$query%' OR description LIKE '%$query%' ORDER BY $orderby LIMIT $min,$linksresults");
       $nrows  = mysql_num_rows($result);
       $resultx = mysql_query("select * from links_subcategories where title LIKE '%$query%' ORDER BY title DESC");
       $nrowsx  = mysql_num_rows($resultx);
    }
    $x=0;

    include("header.php");
    OpenTable();
    mainheader();
    echo "<TABLE WIDTH=100% CELLSPACING=0 CELLPADDING=8 BORDER=0><TR><TD>";
    if ($query != "") {
       if ($nrows>0 OR $nrowsx>0) {
          $result2 = mysql_query("select cid, sid, title from links_subcategories where title LIKE '%$query%' ORDER BY title DESC");
          echo "<TABLE WIDTH=100% CELLSPACING=0 CELLPADDING=2 BORDER=0 CLASS=\"HEADER\"><tr><td><b>".translate("Categories")."</b>";
          while (list($cid, $sid, $stitle) = mysql_fetch_row($result2)) {
             $cate = mysql_query("select title from links_categories where cid='$cid'");
             list($ctitle) = mysql_fetch_row($cate);
             $res = mysql_query("select * from 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 "&nbsp;<a href=links.php?op=viewslink&sid=$sid CLASS=\"BOX\">$ctitle / $stitle</a> <font size=1>($numrows)</font>";
          }
          echo "</TD></TR></TABLE>";
          settype($min,"integer");
          settype($linksresults,"integer");
          $resultZ = mysql_query("select lid, cid, sid, title, url, description, date, hits, linkratingsummary, totalvotes, totalcomments from links_links where title LIKE '%$query%' OR description LIKE '%$query%' ORDER BY $orderby LIMIT $min,$linksresults");
          while (list($lid, $cid, $sid, $title, $url, $description, $time, $hits, $linkratingsummary, $totalvotes, $totalcomments) = mysql_fetch_row($resultZ)) {
             $linkratingsummary = number_format($linkratingsummary, $mainvotedecimal);
             $title = stripslashes($title); $description = stripslashes($description);
             if (strstr($title,"<img src")) {
                $pos = strpos($title, "<img src");
                $xtitle=substr($title,$pos);
                $title=substr($title,0,$pos);
                $transfertitle = check_html(str_replace (" ", "_", $title),"nohtml");
                $title = ereg_replace($query, "<b>$query</b>", $title)." ".$xtitle;
             } else {
                $transfertitle = str_replace (" ", "_", $title);
                $title = ereg_replace($query, "<b>$query</b>", $title);
             }
             if ($ibid=theme_image("links/urlgo.gif")) {$imgtmp=$ibid;} else {$imgtmp="images/links/urlgo.gif";}
             echo "<HR NOSHADE CLASS=\"ONGL\">";
             echo "<img src=\"$imgtmp\" border=\"\" alt=\"\" /> <a href=links.php?op=visit&lid=$lid target=_blank CLASS=\"NOIR\">$title</a>";
             newlinkgraphic($datetime, $time);
             popgraphic($hits);
             echo "<BR>";
             if (strcasecmp($description,check_html($description,"nohtml"))==0) {
                $description = ereg_replace($query, "<b>$query</b>", $description);
             }
             echo translate("Description: ").$description."<BR>";
             global $locale;
             setlocale (LC_TIME, aff_langue($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]));
             if (cur_charset!="utf-8") {
                $datetime = ucfirst($datetime);
             }
             echo translate("Added on: ").$datetime.translate("Hits: ").$hits." ";
             //voting & comments stats
             if ($totalvotes == 1) $votestring = "".translate("vote")."";
             else $votestring = "".translate("votes")."";
             if ($linkratingsummary!="0" || $linkratingsummary!="0.0") echo translate("Rating")." : $linkratingsummary ($totalvotes $votestring)";
             echo "<BR><a href=links.php?op=ratelink&lid=$lid&ttitle=$transfertitle CLASS=\"NOIR\">".translate("Rate this Site")."</a>";
             if ($totalvotes != 0) echo "&nbsp|&nbsp<a href=links.php?op=viewlinkdetails&lid=$lid&ttitle=$transfertitle CLASS=\"NOIR\">".translate("Details")."</a>";
             if ($totalcomments != 0) echo "&nbsp|&nbsp<a href=links.php?op=viewlinkcomments&lid=$lid&ttitle=$transfertitle CLASS=\"NOIR\">".translate("Comments")." ($totalcomments)</a>";
             detecteditorial($lid, $transfertitle);
             echo "<BR><BR>";
             $result3 = mysql_query("select title from links_categories where cid='$cid'");
             $result4 = mysql_query("select title from links_subcategories where sid='$sid'");
             list($ctitle) = mysql_fetch_row($result3);
             list($stitle) = mysql_fetch_row($result4);
             if ($stitle=="") {
                $slash = "";
             } else {
                $slash = "/";
             }
             echo translate("Category: ")."$ctitle $slash $stitle";
             echo "<HR NOSHADE CLASS=\"ONGL\"><BR>";
             $x++;
          }
          $orderby = convertorderbyout($orderby);
       } else {
          echo "<center><font CLASS=\"ROUGE\">".translate("No matches found to your query")."</font></center><BR>";
       }
       //Calculates how many pages exist.  Which page one should be on, etc...
       $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><center><font size=1>";
          echo translate("Select page")." :&nbsp&nbsp";
          $prev=$min-$linksresults;
          $counter = 1;
          $currentpage = ceil($max / $linksresults);
          while ($counter<=$linkpages) {
             $mintemp = ($perpage * $counter) - $perpage;
             if ($counter == $currentpage) echo "<FONT CLASS=\"ROUGE\">$counter</FONT>&nbsp";
             else echo "<a href=links.php?op=search&query=$query&min=$mintemp&orderby=$orderby&show=$show CLASS=\"NOIR\">$counter</a>&nbsp";
             $counter++;
          }
          $next=$min+$linksresults;
       }
       echo "</font></center>";
    } else {
       echo "<center><font CLASS=\"ROUGE\">".translate("No matches found to your query")."</font></center><BR>";
    }
    echo "</td></tr></table>\n";
    CloseTable();
    include("footer.php");
}

function viewlinkeditorial($lid, $ttitle) {
    global $admin;
    include("header.php");
    OpenTable();
    mainheader();
    $result=mysql_query("SELECT adminid, editorialtimestamp, editorialtext, editorialtitle FROM links_editorials WHERE linkid = '$lid'");
    $recordexist = Mysql_num_rows($result);

    echo "<table align=center border=0 cellspacing=0 cellpadding=2 width=100%>";
    if (strstr($ttitle,"<img src")) {
       $pos = strpos($ttitle, "<img src");
          $ttitle=substr($ttitle,0,$pos);
          $transfertitle = check_html(str_replace (" ", "_", $ttitle),"nohtml");
    } else {
       $transfertitle = str_replace (" ", "_", $ttitle);
    }
    $displaytitle = $transfertitle;
    echo "<tr><td>
          <TABLE WIDTH=100% CELLSPACING=2 CELLPADDING=2 BORDER=0 CLASS=\"HEADER\"><TR><TD>
          <b>".translate("Link Profile")." : $displaytitle</b>
          </tr></td></table>
          </td></tr>
          <tr><td>";
    echo "<center>";
    linkinfomenu($lid, $ttitle);
    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);
          $formatted_date=formatTimestamp($editorialtimestamp);
          echo "<tr><td>
               <table align=center border=1 bordercolor=AAAAAA cellpadding=7 cellspacing=0 width=85%>
               <tr><td>
               <center><b>'$editorialtitle'</b>
               <font size=1>".translate("Editorial by")." $adminid - $formatted_date</font><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,$ttitle);
    CloseTable();
    include("footer.php");
}

function detecteditorial($lid, $ttitle) {
    $resulted2 = mysql_query("select adminid from links_editorials where linkid='$lid'");
    $recordexist = Mysql_num_rows($resulted2);
    if ($recordexist != 0) echo " | <a href=links.php?op=viewlinkeditorial&lid=$lid&ttitle=$ttitle CLASS=\"NOIR\">Editorial</a>";
}

function viewlinkcomments($lid, $ttitle) {
    global $admin;
    include("header.php");
    OpenTable();
    mainheader();

    $result=mysql_query("SELECT ratinguser, rating, ratingcomments, ratingtimestamp FROM 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=100%>";
    if (strstr($ttitle,"<img src")) {
       $pos = strpos($ttitle, "<img src");
          $ttitle=substr($ttitle,0,$pos);
          $transfertitle = check_html(str_replace (" ", "_", $ttitle),"nohtml");
    } else {
       $transfertitle = str_replace (" ", "_", $ttitle);
    }
    $displaytitle = $transfertitle;
    echo "<tr><td>
          <TABLE WIDTH=100% CELLSPACING=2 CELLPADDING=2 BORDER=0 CLASS=\"HEADER\"><TR><TD>
          <b>".translate("Link Profile")." : $displaytitle</b>
          </tr></td></table>
          </td></tr>
          <tr><td>";
    echo "<center>";
    linkinfomenu($lid, $ttitle);
    echo "</center><BR>
          </td><tr>
          <tr><td>";
    echo "<BR><center>".translate("Total of")." $totalcomments ".translate("comments")."</center><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);
       $formatted_date=formatTimestamp($ratingtimestamp);
       //Individual user information
       $result2=mysql_query("SELECT rating FROM 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>
                <B> ".translate("User")." :  </b><a href=$nuke_url/user.php?op=userinfo&uname=$ratinguser CLASS=\"NOIR\">$ratinguser</a>
                </td>
                <td>
                <B>".translate("Rating")." :  </b>$rating
                </td>
                <td align=right>
                $formatted_date
                </td>
             </tr>
             <tr height=1>
               <td valign=top>
               <font size=1>".translate("User's Average Rating").": $useravgrating</font>
               </td>
               <td valign=top height=1 colspan=2>
               <font size=1>".translate("# of Ratings").": $usertotalcomments</font>
               </td>
             </tr>
             <tr>
               <td colspan=3>";
               if ($admin) echo "<a href=admin.php?op=LinksModLink&lid=$lid CLASS=\"NOIR\">".translate("Edit This Link")."</a>";
               echo" $ratingcomments";
         echo "<BR><BR>
               </td>
             </tr>";
       $x++;
    }

    echo "</table></table><BR><BR>";
    linkfooter($lid,$ttitle);
    CloseTable();
    include("footer.php");
}

function viewlinkdetails($lid, $ttitle) {
    global $admin, $anonymous;
    include("header.php");
    OpenTable();
    mainheader();

    $voteresult = mysql_query("select rating, ratinguser, ratingcomments FROM links_votedata WHERE ratinglid = '$lid'");
        $totalvotesDB = mysql_num_rows($voteresult);
        $anonvotes = 0;
        $anonvoteval = 0;
        $outsidevotes = 0;
        $useoutsidevoting = 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);

        $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=100%>";
    if (strstr($ttitle,"<img src")) {
       $pos = strpos($ttitle, "<img src");
          $ttitle=substr($ttitle,0,$pos);
          $transfertitle = check_html(str_replace (" ", "_", $ttitle),"nohtml");
    } else {
       $transfertitle = str_replace (" ", "_", $ttitle);
    }
    $displaytitle = $transfertitle;

    echo "<tr><td>
            <TABLE WIDTH=100% CELLSPACING=2 CELLPADDING=2 BORDER=0 CLASS=\"HEADER\"><TR><TD>
            <b>".translate("Link Profile")." : $displaytitle</b>
            </tr></td></table>
          </td></tr>
          <tr><td>";
    echo "<center>";
    linkinfomenu($lid, $ttitle);
    echo "</center><BR>
          </td><tr>
          <tr><td>";
    echo "<center>".translate("Link Rating Details")."<BR>
    $totalvotesDB ".translate("total votes")."<BR>
    ".translate("Overall Rating")." : $finalrating</center><BR><BR>";
    echo "<table align=center border=0 cellspacing=0 cellpadding=2 width=455>";
    echo "<tr>
             <td colspan=2 CLASS=\"HEADER\">
             <B>".translate("Registered Users")."</b>
            </td>
          <tr>
          <tr height=1>
            <td >
            ".translate("Number of Ratings")." : $regvotes
            </td>
            <td rowspan=5 width=200>";

    if ($ibid=theme_image("blackpixel.gif")) {$imgtmp=$ibid;} else {$imgtmp="images/blackpixel.gif";}
    if ($regvotes==0) {
       echo "<center>".translate("No Registered User Votes")."</center>";
    } else {
       echo "<table border=1 width=200 height=100%>
            <tr>
            <td valign=top align=center colspan=10>".translate("Breakdown of Ratings by Value")."</td>
            </tr>
            <tr>
            <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$rvv[1] ".translate("votes")." ($rvvpercent[1]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$rvvchartheight[1]\" /></td>
            <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$rvv[2] ".translate("votes")." ($rvvpercent[2]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$rvvchartheight[2]\" /></td>
            <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$rvv[3] ".translate("votes")." ($rvvpercent[3]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$rvvchartheight[3]\" /></td>
            <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$rvv[4] ".translate("votes")." ($rvvpercent[4]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$rvvchartheight[4]\" /></td>
            <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$rvv[5] ".translate("votes")." ($rvvpercent[5]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$rvvchartheight[5]\" /></td>
            <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$rvv[6] ".translate("votes")." ($rvvpercent[6]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$rvvchartheight[6]\" /></td>
            <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$rvv[7] ".translate("votes")." ($rvvpercent[7]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$rvvchartheight[7]\" /></td>
            <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$rvv[8] ".translate("votes")." ($rvvpercent[8]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$rvvchartheight[8]\" /></td>
            <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$rvv[9] ".translate("votes")." ($rvvpercent[9]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$rvvchartheight[9]\" /></td>
            <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$rvv[10] ".translate("votes")." ($rvvpercent[10]% ".translate("total votes").")\" src=\"$imgtmp\" 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=FFFFFF width=10% valign=bottom align=center>1</td>
               <td bgcolor=FFFFFF width=10% valign=bottom align=center>2</td>
               <td bgcolor=FFFFFF width=10% valign=bottom align=center>3</td>
               <td bgcolor=FFFFFF width=10% valign=bottom align=center>4</td>
               <td bgcolor=FFFFFF width=10% valign=bottom align=center>5</td>
               <td bgcolor=FFFFFF width=10% valign=bottom align=center>6</td>
               <td bgcolor=FFFFFF width=10% valign=bottom align=center>7</td>
               <td bgcolor=FFFFFF width=10% valign=bottom align=center>8</td>
               <td bgcolor=FFFFFF width=10% valign=bottom align=center>9</td>
               <td bgcolor=FFFFFF width=10% valign=bottom align=center>10</td>
               </td><tr></table>
            </td></tr>
            </table>";
    }
    echo "</td></tr>
         <tr><td>".translate("Link Rating")." : $avgRU</td></tr>
         <tr><td>".translate("High Rating")." : $topreg</td></tr>
         <tr><td>".translate("Low Rating")." : $bottomreg</td></tr>
         <tr><td>".translate("Number of Comments")." : $truecomments</td></tr>
         <tr><td></td></tr>
         <tr><td valign=top colspan=2><BR><BR>* ".translate("Note: This website weighs Registered vs. Unregistered user's ratings")." $anonweight ".translate("to")." 1.</td></tr>
         <tr><td colspan=2 CLASS=\"HEADER\"><B>".translate("Unregistered Users")."</b></td></tr>
         <tr height=1><td>".translate("Number of Ratings")." : $anonvotes</td>
         <td rowspan=5 width=200>";
    if ($anonvotes==0) {
       echo "<center>".translate("No Unregistered User Votes")."</center>";
    } else {
      echo "<table border=1 width=200 height=100%>
           <tr>
           <td valign=top align=center colspan=10>".translate("Breakdown of Ratings by Value")."</td>
           </tr>
           <tr>
           <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$avv[1] ".translate("votes")." ($avvpercent[1]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$avvchartheight[1]\" /></td>
           <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$avv[2] ".translate("votes")." ($avvpercent[2]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$avvchartheight[2]\" /></td>
           <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$avv[3] ".translate("votes")." ($avvpercent[3]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$avvchartheight[3]\" /></td>
           <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$avv[4] ".translate("votes")." ($avvpercent[4]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$avvchartheight[4]\" /></td>
           <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$avv[5] ".translate("votes")." ($avvpercent[5]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$avvchartheight[5]\" /></td>
           <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$avv[6] ".translate("votes")." ($avvpercent[6]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$avvchartheight[6]\" /></td>
           <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$avv[7] ".translate("votes")." ($avvpercent[7]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$avvchartheight[7]\" /></td>
           <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$avv[8] ".translate("votes")." ($avvpercent[8]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$avvchartheight[8]\" /></td>
           <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$avv[9] ".translate("votes")." ($avvpercent[9]% ".translate("total votes").")\" src=\"$imgtmp\" width=\"15\" height=\"$avvchartheight[9]\" /></td>
           <td bgcolor=FFFFFF valign=bottom><img border=\"0\" alt=\"$avv[10] ".translate("votes")." ($avvpercent[10]% ".translate("total votes").")\" src=\"$imgtmp\" 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=FFFFFF width=10% valign=bottom align=center>1</td>
              <td bgcolor=FFFFFF width=10% valign=bottom align=center>2</td>
              <td bgcolor=FFFFFF width=10% valign=bottom align=center>3</td>
              <td bgcolor=FFFFFF width=10% valign=bottom align=center>4</td>
              <td bgcolor=FFFFFF width=10% valign=bottom align=center>5</td>
              <td bgcolor=FFFFFF width=10% valign=bottom align=center>6</td>
              <td bgcolor=FFFFFF width=10% valign=bottom align=center>7</td>
              <td bgcolor=FFFFFF width=10% valign=bottom align=center>8</td>
              <td bgcolor=FFFFFF width=10% valign=bottom align=center>9</td>
              <td bgcolor=FFFFFF width=10% valign=bottom align=center>10</td>
              </td><tr></table>
           </td></tr>
           </table>";
    }
    echo "</td></tr>
    <tr><td>".translate("Link Rating")." : $avgAU</td></tr>
    <tr><td>".translate("High Rating")." : $topanon</td></tr>
    <tr><td>".translate("Low Rating")." : $bottomanon</td></tr>
    <tr><td>&nbsp</td></tr>";

    echo "</table></table><BR><BR>";
    linkfooter($lid,$ttitle);
    CloseTable();
    include("footer.php");
}

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

function brokenlink($lid) {
    include("header.php");
    OpenTable();
    global $user;
    if (isset($user)) {
       global $cookie;
       $ratinguser = $cookie[1];
    }
    else { $ratinguser = "$anonymous";}

    mainheader();
    echo "<font size=3><b>".translate("Report Broken Link")."</b></FONT><BR>";
    echo "<form action=links.php method=post>";
    echo "<input type=hidden name=lid value=$lid>";
    echo "<input type=hidden name=modifysubmitter value=$ratinguser>";
    echo 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.")."
    <BR><BR>";

    echo "<input type=hidden name=op value=brokenlinkS><input type=submit CLASS=\"BOUTON_STANDARD\" value=\"".translate("Report Broken Link")."\"></form>";
    CloseTable();
    echo "</center>";
    include("footer.php");
}

function brokenlinkS($lid, $modifysubmitter) {
    global $user, $anonymous;
    if (isset($user)) {
       global $cookie;
       $ratinguser = $cookie[1];
    }
    else { $ratinguser = $anonymous;}

    mysql_query("insert into links_modrequest values (NULL, $lid, 0, 0, '', '', '', '$ratinguser', 1,'')");
    include("header.php");
    opentable();
    echo "<BR><center>".translate("Thanks for this information. We'll look into your request shortly.")."</center><BR>";
    closetable();
    include("footer.php");
}

function modifylinkrequest($lid) {
    global $user, $anonymous;
    include("header.php");
    OpenTable();
    if (isset($user)) {
       global $cookie;
       $ratinguser = $cookie[1];
    } else { $ratinguser = $anonymous;}
    mainheader();
    echo "</center>";
    $blocknow = 0;
    if ($blockunregmodify == 1 or $ratinguser==$anonymous) {
       echo "<BR><center>".translate("Only registered users can suggest link modifications.")."<BR>".translate("Please register or login.")."</center><BR>";
       $blocknow = 1;
    }

    if ($blocknow != 1) {
       $result = mysql_query("select cid, sid, title, url, description from links_links where lid='$lid'");
       echo "<TABLE WIDTH=100% CELLSPACING=2 CELLPADDING=2 BORDER=0 CLASS=\"HEADER\"><TR><TD>";
       echo translate("Request Link Modification")." ".translate("Link ID: ")."<b>$lid</b></TD></TR></TABLE>";
       while (list($cid, $sid, $title, $url, $xtext) = mysql_fetch_row($result)) {
          $title = stripslashes($title); $xtext = stripslashes($xtext);
          echo "<form action=links.php method=post name=adminForm>";
          echo translate("Page Title: ")."<BR><input class=textbox type=text name=title value=\"$title\" size=50 maxlength=100><BR><BR>";
          echo translate("Page URL: ")."<BR><input class=textbox type=text name=url value=$url size=50 maxlength=100>&nbsp;<BR><BR>";
          echo translate("Description: (255 characters max)")."<br /><textarea class=\"textbox\" wrap=\"virtual\" name=\"xtext\" cols=\"70\" rows=\"10\" style=\"width: 100%;\">$xtext</textarea>";
          echo aff_editeur("xtext", "false");
          echo "<br /><br />";
          $result2=mysql_query("select cid, title from links_categories order by title");
          echo "<input type=hidden name=lid value=$lid>";
          echo "<input type=hidden name=modifysubmitter value=$ratinguser>";
          echo translate("Category: ")."<select CLASS=\"TEXTBOX_STANDARD\" name=cat>";
          while (list($ccid, $ctitle) = mysql_fetch_row($result2)) {
             $sel = "";
             if ($cid==$ccid AND $sid==0) {
                $sel = "selected";
             }
             echo "<option value=$ccid $sel>$ctitle</option>";
             $result3=mysql_query("select sid, title from links_subcategories where cid='$ccid' order by title");
             while (list($ssid, $stitle) = mysql_fetch_row($result3)) {
                $sel = "";
                if ($sid==$ssid) {
                   $sel = "selected";
                }
                echo "<option value=$ccid-$ssid $sel>$ctitle / $stitle</option>";
             }
          }
          echo "</select><input type=hidden name=op value=modifylinkrequestS>&nbsp;&nbsp;<input type=submit CLASS=\"BOUTON_STANDARD\" value=\"".translate("Send Request")."\"></form>";
       }
    }
    CloseTable();
    include("footer.php");
}

function modifylinkrequestS($lid, $cat, $title, $url, $xtext, $modifysubmitter) {
    global $user, $anonymous;
    if (isset($user)) {
       global $cookie;
       $ratinguser = $cookie[1];
    } else { $ratinguser = $anonymous;}
    $blocknow = 0;
    if ($blockunregmodify == 1 or $ratinguser==$anonymous) {
       include("header.php");
       opentable();
       echo "<BR><center>".translate("Only registered users can suggest link modifications.")."<BR>".translate("Please register or login.")."</center><BR>";
       $blocknow = 1;
       closetable();
       include("footer.php");
    }
    if ($blocknow != 1) {
       $cat = explode("-", $cat);
       if ($cat[1]=="") {
          $cat[1] = 0;
       }
       $title = stripslashes(FixQuotes($title));
       $url = stripslashes(FixQuotes($url));
       $xtext = stripslashes(FixQuotes($xtext));
       mysql_query("insert into links_modrequest values (NULL, $lid, $cat[0], $cat[1], '$title', '$url', '$xtext', '$ratinguser', 0,'')");
       include("header.php");
       opentable();
       echo "<BR><center>".translate("Thanks for this information. We'll look into your request shortly.")."</center><BR>";
       closetable();
       include("footer.php");
    }
}

function rateinfo($lid) {
    mysql_query("update links_links set hits=hits+1 where lid='$lid'");
    $result = mysql_query("select url from links_links where lid='$lid'");
    list($url) = mysql_fetch_row($result);
    Header("Location: $url");
}

function addrating($ratinglid, $ratinguser, $rating, $ratinghost_name, $ratingcomments) {
    global $user,$anonymous;
    $passtest = "yes";
    include ("header.php");
    OpenTable();
    completevoteheader();
    if (isset($user)) {
       global $cookie;
       $ratinguser = $cookie[1];
    }
    else if ($ratinguser=="outside") { $ratinguser = "outside";}
    else { $ratinguser = $anonymous;}

    $results3 = mysql_query("SELECT title FROM links_links WHERE lid='$ratinglid'");
    list($title)=mysql_fetch_row($results3);
    $ttitle = $title;

    //Make sure only 1 anonymous from one IP in a single day rate site.
    $anonwaitdays = 1;
    $ip = getip();

    // 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 links_links where lid='$ratinglid'");
       while (list($ratinguserDB)=mysql_fetch_row($result)) {
          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 links_votedata where ratinglid='$ratinglid'");
       while (list($ratinguserDB)=mysql_fetch_row($result)) {
          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 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 links_votedata WHERE ratinglid='$ratinglid' AND ratinguser='outside' AND ratinghostname = '$ip' AND TO_DAYS(NOW()) - TO_DAYS(ratingtimestamp) < '$outsidewaitdays'");
       $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 links_votedata values (NULL, '$ratinglid', '$ratinguser', '$rating', '$ip', '$ratingcomments', now())");

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

function completevoteheader(){
    mainheader();
    echo "<BR><table border=0 width=450><tr><td>";
}

function completevotefooter($lid, $ttitle, $ratinguser) {
    global $sitename;
    $result=mysql_query("select url FROM links_links WHERE lid='$lid'");
    list($url)=mysql_fetch_row($result);
    echo "</td></tr><tr><td>
          ".translate("Thank you for taking the time to rate a site. Input from users such as yourself will help other visitors better decide which links to click on.")."<BR><BR>
          </td></tr>";
     if ($ratinguser=="outside") {
        echo "<tr><td>
             <center>".translate("We appreciate your visit to")." $sitename<BR><a href=$url>".translate("Return to")." $ttitle</a></center><BR><BR>
             </td></tr>";
        $result=mysql_query("select title FROM links_links where lid='$lid'");
        list($title)=mysql_fetch_row($result);
        $ttitle=$title;
     }
     if (strstr($ttitle,"<img src")) {
        $pos = strpos($ttitle, "<img src");
           $ttitleX=substr($ttitle,0,$pos-1);
           $ttitle = check_html(str_replace (" ", "_", $ttitleX),"nohtml");
     } else {
        $ttitle = str_replace (" ", "_", $ttitle);
     }
     echo "</table>";
     linkinfomenu($lid,$ttitle);
}

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

function ratelink($lid, $user, $ttitle) {
    include("header.php");
    OpenTable();
    mainheader();
    echo "</center>";
    if (strstr($ttitle,"<img src")) {
       $pos = strpos($ttitle, "<img src");
          $ttitle=substr($ttitle,0,$pos);
          $transfertitle = check_html(str_replace (" ", "_", $ttitle),"nohtml");
    } else {
       $transfertitle = str_replace (" ", "_", $ttitle);
    }
    $displaytitle = $transfertitle;
    global $title, $datetime, $anonymous;
    $ip = getip();

    echo "<b>".stripslashes($displaytitle)."</b>
         <UL>
         <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 Top Rated Resources.")."
         <LI>".translate("Do not vote for your own resource.");
    if (isset($user)) {
        echo "<LI>".translate("You are a registered user and are logged in.")."
              <LI>".translate("Feel free to add a comment about this site.")."";
        global $cookie;
        $name = $cookie[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 "</UL>";

    echo"<table border=0 cellpadding=1 cellspacing=0 width=100%>
     <tr><td width=25 nowrap>&nbsp;</td><td>
     <form method=POST action=\"links.php\">
     <input type=hidden name=\"ratinglid\" value=\"$lid\">
     <input type=hidden name=\"ratinguser\" value=\"$name\">
     <input type=hidden name=\"ratinghost_name\" value=\"$ip\">
     ".translate("Rate this Website")." :
     <select name=\"rating\" CLASS=\"TEXTBOX_STANDARD\">
     <option>--
     <option>10
     <option>9
     <option>8
     <option>7
     <option>6
     <option>5
     <option>4
     <option>3
     <option>2
     <option>1
     </select><input type=hidden name=op value=\"addrating\">&nbsp;&nbsp;<input type=submit CLASS=\"BOUTON_STANDARD\" value=\"".translate("Rate this Website")."\">
     <BR><BR>";
     if (isset($user)) {
        echo "<b>".translate("Comments")."</b> : <BR><TEXTAREA  CLASS=\"TEXTBOX\" wrap=virtual cols=50 rows=10 name=\"ratingcomments\"></TEXTAREA>";
     } else {
        echo"<input type=hidden name=\"ratingcomments\" value=\"\">";
     }

     echo "</TD></tr></form></table>";
     CloseTable();
     include("footer.php");
}

switch($op) {

    case "menu":
        $pdst="1";
        menu($mainlink);
        break;

    case "AddLink":
        AddLink();
        break;

    case "NewLinks":
        $pdst="1";
        NewLinks($newlinkshowdays);
        break;

    case "NewLinksDate":
        $pdst="1";
        NewLinksDate($selectdate);
        break;

    case "TopRated":
        $pdst="1";
        TopRated($ratenum, $ratetype);
        break;

    case "MostPopular":
        $pdst="1";
        MostPopular($ratenum, $ratetype);
        break;

    case "RandomLink":
        RandomLink();
        break;

    case "viewlink":
        $pdst="1";
        viewlink($cid, $min, $orderby, $show);
        break;

    case "viewslink":
        $pdst="1";
        viewslink($sid, $min, $orderby, $show);
        break;

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

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

    case "modifylinkrequestS":
        $pdst="1";
        modifylinkrequestS($lid, $cat, $title, $url, $xtext, $modifysubmitter);
        break;

    case "brokenlinkS":
        $pdst="1";
        brokenlinkS($lid, $modifysubmitter);
        break;

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

    case "Add":
        Add($title, $url, $name, $cat, $xtext, $name, $email);
        break;

    case "search":
        $pdst="1";
        search($query, $min, $orderby, $show);
        break;

    case "rateinfo":
        rateinfo($lid, $user, $title);
        break;

    case "ratelink":
        ratelink($lid, $user, $ttitle);
        break;

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

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

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

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

    default:
        $pdst="1";
        index();
        break;
}
?>