"Fossies" - the Fresh Open Source Software Archive

Member "mythreads/lib/lib_main.php3" (23 Jan 2018, 28513 Bytes) of package /linux/privat/mythreads-links_1.2.1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) PHP source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "lib_main.php3": 1.2.0_vs_1.2.1.

    1 <?php
    2 #----------------------------------------------------------------->
    3 # $Id: lib_main.php3,v 1.71 2010/05/04 18:29:59 ldrolez Exp $
    4 #
    5 # Website: http://mythreads.sourceforge.net
    6 #
    7 # Desc: lib_main.php3. All the main functions are stored here....
    8 #
    9 #
   10 # License: This code is released under the terms of the GNU GPL
   11 # version 2 or later. Please refer to www.gnu.org for a copy
   12 # of this license.
   13 #
   14 #----------------------------------------------------------------->
   15 
   16 
   17 
   18 #################################################
   19 #
   20 #################################################
   21 #
   22 function showMainPage()
   23 {
   24     global $tpl;
   25     
   26     $categories_links = mainPage();
   27 
   28     $tpl->set_var( array( 
   29         "CATEGORIES" => $categories_links,
   30         "CATEGORY_TITLE" => Message ("main_categories")
   31     ));
   32                 
   33     $tpl->parse("MyOutput", "start");
   34     $tpl->p("MyOutput");
   35 }
   36 
   37 
   38 #################################################
   39 #
   40 #################################################
   41 #
   42 # print Main page with just main category's
   43 function mainPage()
   44 {
   45     global $tpl, $config, $start_script, $start_script_t, $mylink, $language, $mylink;
   46 
   47     $a = 0;
   48     $cache_file = $config["cache_dir"] . "frontpage.cache". $language;
   49 
   50     $time = explode(" ", microtime());
   51     srand((double)microtime()*1000000);
   52     $cache_time_rnd = 60 - rand(0, 60);
   53 
   54     if ( (!(file_exists($cache_file))) || ((filectime($cache_file) + $config["cache_time"] - $time[1]) + $cache_time_rnd < 0) || (!(filesize($cache_file))) ) 
   55     {
   56     if (!$result = mysqli_query($mylink, "SELECT cat,title,ttlinks,info FROM ".$config["pre"]."category WHERE under='0' ORDER BY title")) {
   57         echo "<br/><h2><font color=\"red\">DATABASE ERROR: ".mysqli_error($mylink)."</font></h2><br>";
   58     }
   59     $links = "<table width=\"100%\" cellpadding=\"4\"><tr>";
   60     while ($info = mysqli_fetch_array($result))
   61     {
   62         $a++;
   63         
   64         $links_under = "";
   65     
   66         $sublinks_ref = mysqli_query($mylink, "SELECT cat,title FROM ".$config["pre"]."category WHERE under='$info[cat]' ORDER BY title");
   67         if ($sublinks_ref != 0) {
   68         $max = $config["max_sublinks"];
   69         $num_rows = mysqli_num_rows($sublinks_ref);
   70         if ( $num_rows < $config["max_sublinks"] ) {
   71             $max = $num_rows;
   72         }
   73         for ($i=0; $i < $max; $i++) {
   74                 $sublinks = mysqli_fetch_array($sublinks_ref);
   75                 if ($i == 0) {
   76             $links_under .= "<a href=\"".$start_script_t."category=$sublinks[cat]\">$sublinks[title]</a>";
   77             } else {
   78             $links_under .= ", <a href=\"".$start_script_t."category=$sublinks[cat]\">$sublinks[title]</a>";
   79                     }
   80             }
   81         # print '...' if there are more sub categories than shown
   82         if ( $num_rows > $config["max_sublinks"] ) {
   83             $links_under .= "&nbsp;<a href=\"".$start_script_t."category=$info[cat]\">...</a>";
   84         }
   85         }
   86         
   87         $tpl->set_var( array( 
   88             "ACTION_CAT" => $start_script_t."category=$info[cat]",
   89             "INFO_TITLE" => $info['title'],
   90             "INFO_TT" => $info['ttlinks'],
   91             "INFO_INFO" => $info['info'],
   92             "INFO_UNDER" => $links_under            
   93             ));
   94         
   95         $links .= $tpl->subst("category_main");
   96 
   97         if ($a == $config["across"])
   98         {
   99             $links .= "</tr>\n\n<TR><TD COLSPAN=\"2\">&nbsp;</TD></TR>\n\n<tr>\n";
  100             $a=0;
  101         }
  102     }
  103     
  104     $links .= "</tr></table>";
  105 
  106 
  107         if ($config["max_new_links"] > 0) {
  108         $tpl->set_var( "SUBTITLE", Message("new_links"));
  109             $links .= $tpl->subst("subtitle");
  110             $links .= Newly_Added($config["max_new_links"]);
  111     }
  112         if ($config["max_upd_links"] > 0) {
  113         $tpl->set_var( "SUBTITLE", Message("upd_links"));
  114             $links .= $tpl->subst("subtitle");
  115             $links .= Newly_Updated($config["max_upd_links"]);
  116         }       
  117         if ($config["max_top_links"] > 0) {
  118         $tpl->set_var( "SUBTITLE", Message("top_links"));
  119             $links .= $tpl->subst("subtitle");
  120             $links .= Top_Hits($config["max_top_links"]);
  121         }
  122     
  123     $fpwrite = fopen($cache_file, 'w');
  124     fputs($fpwrite, "$links");
  125     fclose($fpwrite);
  126     }
  127     else
  128     {
  129     # data cached
  130     $fp = fopen($cache_file, 'r');
  131     $links = fread( $fp, filesize( $cache_file ) );
  132     fclose($fp);
  133     }
  134     return $links;
  135 }
  136 
  137 #################################################
  138 #
  139 #################################################
  140 #
  141 # View links page
  142 function viewPage($category)
  143 {
  144     #########
  145     # global variables
  146     global $config, $start_script, $start_script_t, $tpl, $mylink;
  147 
  148     $content ="<table width=\"100%\" border=\"0\" cellpadding=\"3\"><tr>";
  149         
  150     $result_t = mysqli_query($mylink, "SELECT cat,title,ttlinks,info FROM ".$config["pre"]."category where under='$category' ORDER BY 'title'");
  151     
  152     // Vertical Alpha routine start (Ratt 26 Nov 02)
  153     // Counts the number of entries to display
  154     $alpha_count = 0;
  155     while ($alpha_array[$alpha_count++] = mysqli_fetch_array($result_t));
  156 
  157     // Takes last increment off the stack due to the way MySQL and PHP handle queries (there
  158     // is 1 more than the actual number of entries, because of the NULL test.
  159     $alpha_count--;
  160 
  161     if ($alpha_count == 0)  return "";
  162     
  163     // Calculate how many rows are going to be needed. If it's less than one, it's obviously 1 :)
  164     $alpha_row_count = ceil($alpha_count / $config[across]);
  165 
  166     if ($alpha_row_count < 1) $alpha_row_count = 1;
  167 
  168     // Cycle through and build each Table Row for each row in $alpha_row_count
  169     for ($alpha_row = 0; $alpha_row < $alpha_row_count; $alpha_row++)
  170     {               
  171 
  172         // Build each Table Row's columns 
  173         for ($alpha_column = 0; $alpha_column < $config[across]; $alpha_column++) 
  174         {
  175             $a++;
  176             // Figure out the position we should be in in the array
  177             $alpha_array_position = floor($alpha_row + ($alpha_row_count * $alpha_column ));
  178 
  179             // If it's not NULL, add to the content.  If it is NULL, it means we are at the 
  180             // end of the table (or there was a data problem!) and should display nothing instead
  181             // of an empty box (yuck)
  182             if (is_array($alpha_array[$alpha_array_position]))
  183             {
  184                 $tpl->set_var( array( 
  185                 "ARRAY_POS" => $alpha_array_position,
  186                 "ACTION_CAT" => $start_script_t."category=" . $alpha_array[$alpha_array_position][cat],
  187                 "INFO_TITLE" => $alpha_array[$alpha_array_position][title],
  188                 "INFO_TT" => $alpha_array[$alpha_array_position][ttlinks],
  189                 "INFO_INFO" => $alpha_array[$alpha_array_position][info]
  190                 ));
  191             
  192                 $content .= $tpl->subst("category");
  193             }
  194                             
  195             if ($a == $config["across"]) { $content .= "</tr>\n<tr>"; $a=0; }
  196         }
  197     }
  198     // Vertical Alpha routine end
  199 
  200     $content .= "</tr></table>";
  201     
  202     return $content;
  203 }
  204 
  205 #################################################
  206 #
  207 #################################################
  208 #
  209 # This function displays the different categories of links there are.
  210 function display_category($category)
  211 {
  212     global $start_script, $start_script_t;
  213     global $config, $mylink;
  214 
  215     $content = "";  
  216     $result_sub = mysqli_query($mylink, "SELECT pathto FROM ".$config["pre"]."category WHERE pathto LIKE '%:$category:'");
  217     $sub_title = mysqli_fetch_array($result_sub);
  218 
  219     $patharray = explode(":",$sub_title['pathto']);
  220         
  221     $content .= "<a href=\"$start_script\">".Message("top_bt")."</a>";
  222     while (list($key, $val)=each($patharray))
  223     {
  224         if ($val != ""){
  225             $result_sub = mysqli_query($mylink, "SELECT title,cat FROM ".$config["pre"]."category WHERE cat='$val' ORDER BY cat ASC");
  226             $sub_title_new = mysqli_fetch_array($result_sub);
  227             $content.= "/<a href=\"".$start_script_t."category=$sub_title_new[cat]\">$sub_title_new[title]</a>";    
  228         }
  229             
  230     }
  231     return $content;
  232 }
  233 
  234 #################################################
  235 #
  236 #################################################
  237 #
  238 # This function displays the links contained in the database for a particular category.
  239 function display_category_links($category,$view)
  240 {
  241     global $config, $nomore, $view_start, $start_script, $start_script_t, $update_link, $add_link, $tpl, $mylink;
  242     
  243     #########
  244     # $view hold the from for LIMIT. Must not be 0
  245     if (! isset($view)){ $view='0';}
  246     
  247     $view_start = $view;
  248     $view_stop = $view + $config["max_displayed_links"];
  249 
  250     #########
  251     # count how many and not go over the max...
  252     $af = mysqli_query($mylink, "SELECT COUNT(*) FROM ".$config["pre"]."links WHERE cat='$category' and status=0");
  253     $howmany = mysqli_fetch_array($af);
  254     if ($howmany[0] <= $view_stop)
  255     {
  256         $view_stop = $howmany[0];
  257         $nomore=1;
  258     }
  259 
  260 
  261     $link_prev_next = showNext($category,$view_stop,$view_start,$nomore);
  262     
  263     $cat_links .= $link_prev_next;  
  264     $result = mysqli_query($mylink, "SELECT title,idx,message,date,hits FROM ".$config["pre"]."links WHERE cat='$category' and status=0 ORDER BY title LIMIT $view_start,".$config["max_displayed_links"]);
  265 
  266     if (mysqli_num_rows($result))
  267     {
  268         # as we append data, make sure to reset link_rows
  269         $tpl->set_var("link_rows", "");
  270 
  271         while ($list = mysqli_fetch_array($result) )
  272         {
  273 
  274         limitlength_cat($list);
  275         $idx = $list["idx"];
  276         $tpl->set_var( array(
  277             "LINK_TITLE" => $list["title"], 
  278             "LINK_MESSAGE" => $list["message"],
  279             "LINK_ADDED" => $list["date"],
  280             "LINK_HITS" => $list["hits"],
  281             "LINK_GO" => $start_script_t."count=$idx",
  282             "LINK_MORE" => $start_script_t."more=$idx",
  283             "LINK_EDIT" => "$update_link&link=$idx"
  284             ));
  285             
  286         $tpl->parse ("link_rows", "link_row", true);
  287         }
  288 
  289         $cat_links .= $tpl->subst("link");
  290     
  291     } else {
  292         $cat_links .= Message ( "no_links_in_this_category",
  293                 array("ADDLINK" => "$add_link&category=$category")
  294                   );
  295     }
  296 
  297     $cat_links = TextToLink($cat_links);    
  298     $cat_links .= $link_prev_next;
  299     
  300     
  301     return $cat_links;
  302 }
  303 
  304 #################################################
  305 #
  306 #################################################
  307 #
  308 # Show Next Previous Page
  309 function showNext($category,$view_stop,$view_start,$nomore)
  310 {
  311     global $start_script, $start_script_t, $config, $most, $tpl;
  312     
  313     $view_prev = $view_start - $config["max_displayed_links"];
  314 
  315     if ($view_prev <= 0 ){ $view_prev = 0;}
  316 
  317     if ($view_start >= 1) { 
  318         $tpl->set_var("PREV_LINK", $start_script_t."category=$category&view=$view_prev");
  319     } else {
  320         # remove the prev button
  321         $tpl->set_block("prevnext", "previous_page", "deleteme");
  322     }
  323     
  324     if (! $nomore ) {
  325         $tpl->set_var("NEXT_LINK", $start_script_t."category=$category&view=$view_stop");
  326     } else {
  327         # remove the next button
  328         $tpl->set_block("prevnext", "next_page", "deleteme");
  329     }
  330     $tpl->set_var("deleteme" , "");
  331 
  332     return $tpl->subst("prevnext");
  333 }
  334 
  335 #################################################
  336 # Remove the search footer (for admin pages)
  337 #################################################
  338 
  339 function No_Search_Footer()
  340 {
  341     global $tpl;    
  342     
  343     $tpl->set_block ("start", "form_search_footer", "deleteme");
  344     $tpl->set_block ("start", "search_title", "nbsp");
  345     $tpl->set_var ("deleteme" , "");
  346     $tpl->set_var ("nbsp" , "&nbsp;");
  347 }
  348 
  349 #################################################
  350 # Counts the hits a particular link gets
  351 #################################################
  352 
  353 function countIt($idx, $redir = 0) {
  354     global $config, $_SERVER, $mylink;
  355     
  356     $lr = $config["local_redirect"];
  357     # get the remote IP address
  358     $ipadd = trim(getenv("REMOTE_ADDR"));
  359     $result = mysqli_query($mylink, "SELECT link,lastip FROM ".$config["pre"]."links WHERE idx='$idx' and status=0");
  360     $list = mysqli_fetch_array($result);
  361 
  362     if ($lr != "") {
  363         if (preg_match("/^[a-zA-Z]+:\/\//", $list["link"])) {
  364         $lr = "";
  365         }
  366     }
  367 
  368     if ($redir != 0) {
  369         # redirect if redir not null
  370         header("Location: ".$lr.$list["link"]."\n\n");
  371     }
  372     
  373     # Bot check, don't count hits from bots
  374     if (preg_match('/bot|curl|crawler|spider|google|infoseek|slurp|scooter/i', $_SERVER['HTTP_USER_AGENT'], $matches)) {
  375         return;
  376         exit(1);
  377     }
  378 
  379     if ($list["lastip"] != $ipadd) {
  380         # new IP: count it
  381         $result = mysqli_query($mylink, "UPDATE ".$config["pre"]."links SET hits=hits+1 , lastip='$ipadd' WHERE idx='$idx' and status=0");
  382         if (!$result){
  383         $error = mysqli_error($mylink);
  384         print $error;
  385         exit(1);
  386         }
  387     }
  388 }
  389 
  390 ###################################################
  391 # User : Add a link in the queue
  392 # Admin : Direct add / modify
  393 ###################################################
  394 function doaddWaitLink($_unused, $mode = "")
  395 {
  396     global $linkbackurl;
  397     global $config, $custom, $mylink;
  398     global $_GET, $_POST;
  399     
  400     $status = 1;
  401     $new = 0;
  402 
  403     if ($config['security_code'] != "" && getuser() != "admin") {
  404         # check the security code
  405         if ($_POST["security"] == "" || $_POST["securitycode"] == "") {
  406             $error = Message("error_security_code");
  407         } else if ($_POST["security"] != ImageGenSecretRef($_POST["securitycode"])) {
  408             $error = Message("error_security_code");
  409         }
  410     }
  411 
  412     if ($_POST["title"] == ''){
  413         $error .= Message ("forgot_title");
  414     }
  415     $email = htmlentities($_POST["email"]);
  416     
  417     if ((getuser() != "admin") && ((!strstr($email, "@")) || (strlen($email) < 7))) {
  418         $error .= Message ("forgot_email");
  419     }
  420     
  421     if ($_POST["link"] == "http://" or $_POST["link"] == ""){
  422         $error .= Message ("forgot_url");
  423     }
  424     
  425     # reject the submit if some fields contain unwanted data
  426     if ($config['spam_filter'] > 0 && getuser() != "admin") {
  427         if (preg_match("/http:\/\//i", $_POST["title"].$_POST["message"])) {
  428             # do not display a nice error message ;-)
  429             $error .= Message("error_security_code");
  430         }
  431     }
  432     
  433     # is the delete flag set ?
  434     if (isset($_POST["delete"]))
  435     {
  436         # TODO: handle direct admin deletion.
  437         $status = 2;
  438     }
  439     else
  440     {
  441       if ($_POST[idx] != "") {
  442         # old link being edited 
  443         $exists_wait = mysqli_num_rows(mysqli_query($mylink, "SELECT idx FROM ".$config["pre"]."links where idx='".intval($_POST[idx])."' and status<>0"));
  444         if ($exists_wait != 0)
  445           {
  446         $error .= Message ("error_already_in_update_queue");
  447           }
  448       } else {
  449         # Assign an idx
  450         $max = mysqli_fetch_array(mysqli_query($mylink, "select MAX(idx)+1 from ".$config["pre"]."links"));
  451         if ($max[0] == "") $max[0] = 1;
  452         $_POST[idx] = $max[0];
  453         $new = 1;
  454       }
  455       if (getuser() == "admin" ) {
  456         # direct add/mod
  457         # if the admin is adding a new link using the admin panel,
  458         # do not put this new link in the wait queue.
  459         if ($_GET["mode"] == "admin") {
  460         $status = 0;
  461         }
  462       } else if ($config["anonymous_add"] == 1) {
  463         # anonymous users can add links without going to the wait queue
  464         $status = 0;
  465       }
  466     }
  467     
  468     if (! isset($error))
  469       {
  470         # FIXME: Is the following loop needed since we also filter 
  471         # custom fields below ????
  472         while (list($key, $data)=each($_POST)) {
  473         $type = "text";
  474         if ($key == "link") $type = "link";
  475         $_POST[$key] = filterIn($type, $_POST[$key]);
  476         }
  477 
  478         # duplicate the row and modify its status
  479         
  480         # these fields should always be present (category also?)
  481         $mod = array ("status" => $status ,
  482             "cat" => intval($_POST[category]),
  483             "idx" => intval($_POST[idx])
  484         );
  485         # standard but optional fields
  486         $tmpar = array ("title", "message", "link");
  487         while (list(,$v) = each($tmpar)) {
  488         if (isset($_POST[$v])) {
  489             $mod[$v] = "'$_POST[$v]'";
  490         }
  491         }
  492         # custom fields
  493         while (list($k,$v) = each($custom)) {
  494         $kl = strtolower($k);
  495         if (isset($_POST[$k])) {
  496             $dt = $_POST[$k];
  497             $mod[$kl] = "'".filterIn($v, $dt)."'";
  498         }
  499         # for checkboxes
  500         if (!isset($_POST[$k]) && $v == "bool") {
  501             $mod[$kl] = "'0'";
  502         }
  503         }
  504         $idx = intval($_POST[idx]);
  505         $numold = 0;
  506         if ((getuser() == "admin" && $status != 2) || ($config["anonymous_add"] == 1)) {
  507         # find the old link entry
  508         $sql = "select idx from ".$config["pre"]."links where idx='".$idx."'";
  509         $numold = mysqli_num_rows(mysqli_query($mylink, $sql));
  510         # new link ? set the date
  511         if ($numold == 0) {
  512           $mod["date"] = "NOW()";
  513         } else {
  514           # status=3 : direct edit
  515           $mod["status"] = 3;
  516           # mark the link as updated ? 
  517           # Quick hack. I should add a check box !
  518           if ($email == "update") $mod["updated"] = "NOW()";
  519         }
  520         }
  521         
  522         dbDupMod($config["pre"]."links", "WHERE idx='$idx'", $mod);
  523 
  524         if ($numold != 0) {
  525         # admin mode in direct edit, delete the old link
  526         $sql = "delete from ".$config["pre"]."links where idx='$idx' and status=0";
  527         $ref = mysqli_query( $mylink, $sql );
  528         # and alter the temporary entry
  529         $sql = "update ".$config["pre"]."links set status=0 where idx='$idx' and status=3 ";
  530         $ref = mysqli_query( $mylink, $sql );
  531         } else {
  532         # not direct admin edit
  533         if ($status != 0) {
  534             # insert some info about the modification
  535             $ip_addy=getenv("REMOTE_ADDR");
  536             $su = mysqli_query($mylink, "insert into ".$config["pre"]."wait (idx,email,ip,date) values(
  537             '".intval($_POST[idx])."',
  538             '$email' ,
  539             '$ip_addy' ,
  540             NOW() )") or die (mysqli_error($mylink));
  541         } else {
  542             # only call updaterss if the admin does a direct add through the
  543             # admin panel
  544             if ($numold == 0 && getuser() == "admin") updateRSS();
  545         }
  546         }   
  547         
  548         if (getuser() == "admin") {
  549         $content .= Message ("link_added", array("LINK" => htmlentities($_POST['link'])));
  550         } else {    
  551         $content .= Message ("thanks_submit",
  552                  array ("LINK" => htmlentities($linkbackurl)));
  553         if ($config["adminemail"] != "") {
  554                 mymail($config["adminemail"], Message("link_submitted").":".htmlentities($_POST[title]), Message("link_submitted_message"), $config["fromemail"]);
  555         }
  556         }       
  557       } else {
  558         $content = Message ("error_submit",
  559                 array ("ERROR" => "$error"));
  560       }
  561     
  562     return $content;
  563 }
  564 
  565 
  566 #################################################
  567 # Duplicate a row and make (minor) modifications
  568 # $tbl = table's name
  569 # $where = SQL WHERE clause (which should begin by 'WHERE ')
  570 # $mod = array of columns to modify
  571 #################################################
  572 
  573 function dbDupMod($tbl,$where,$mod)
  574 {
  575     global $config, $mylink, $database;
  576     
  577     # get the fields info
  578     #$fields = mysqli_list_fields($mylink, $database, $tbl, $mylink);
  579     #$columns = mysqli_num_fields($fields);
  580 
  581     $sqlq = "SELECT *  FROM $tbl $where";
  582     $ref = mysqli_query( $mylink, $sqlq ) or die (mysqli_error($mylink));
  583     $data = mysqli_fetch_array($ref);
  584     $fds = mysqli_fetch_fields($ref);
  585 
  586     #$sql = "INSERT INTO $tbl SELECT "; does not work with mysql so move 
  587     #the data the dumb way !
  588     $sqli = "INSERT INTO $tbl (";
  589     $sqld = "VALUES ( ";
  590     for ($i = 0; $i < count($fds); $i++) {
  591         $f = $fds[$i]->name;
  592         $sqli .= $f.",";
  593         # modify on the fly the data which needs to be modified
  594         if (isset($mod[$f])) {
  595         $f = $mod[$f];
  596         } else {
  597         if (is_array($data)) {
  598             $f = "'$data[$f]'";
  599         } else {
  600             $f = "''";
  601         }
  602         }
  603         $sqld .= $f.",";
  604     }
  605     $sqld[strlen($sqld)-1] = " ";
  606     $sqli[strlen($sqli)-1] = " ";
  607     $sqli .= ") ".$sqld.")";
  608     
  609     #echo($sqli);
  610     #die(); #return;
  611     
  612     $result = mysqli_query( $mylink, $sqli ) or die (mysqli_error($mylink));
  613 }
  614 
  615 #################################################
  616 # Returns the kind of user logged in 
  617 # (currently "" or "admin")
  618 #################################################
  619 function getuser()
  620 {
  621     global $_POST, $_COOKIE;
  622     global $admin_userpass, $admin_username, $admin_password;
  623 
  624     if ((isset($_POST['name']) && isset($_POST['password'])) or 
  625     (isset($_COOKIE['name']) && isset($_COOKIE['password'])))
  626     {
  627         if (($_POST['name'] == $admin_username && $_POST['password'] == $admin_password) or 
  628         ($_COOKIE['name'] == $admin_username && $_COOKIE['password'] == md5($admin_password)))
  629         {
  630         return ("admin");
  631         } else {
  632         reset($admin_userpass);
  633         while ( list( $name, $pass ) = each( $admin_userpass ) ) {
  634             if (($_POST['name'] == $name && $_POST['password'] == $pass) or 
  635             ($_COOKIE['name'] == $name && $_COOKIE['password'] == md5($pass)))
  636                 return("admin");
  637         }           
  638         return ("badpassord");
  639         }
  640     }
  641     # not logged in
  642     return ("");
  643 }
  644 
  645 #################################################
  646 # Send an email like mail() but take into account
  647 # fascist providers
  648 #################################################
  649 function mymail($to, $sub, $text, $from)
  650 {
  651   $sub = substr(urldecode($sub), 0, 80);
  652   $to = urldecode($to);
  653   $from = urldecode($from);
  654   $text = urldecode($text);
  655 
  656   # forbidden expressions
  657   $re = "/[%\n\r]+/i";
  658 
  659   if (preg_match($re, $sub, $matches)) {
  660     //print_r($matches);
  661     //print_r($sub);
  662     die("No spam here !");
  663   }
  664   
  665   #$sub = preg_replace($re, "", $sub);
  666   $to = preg_replace($re, "", $to);
  667   $from = preg_replace($re, "", $from);
  668 
  669   if (function_exists ("email")) {
  670     # email function found : we are running on online.fr's servers 
  671     preg_match ("/^[^@]+/", $from, $newfrom);
  672     $ret = email($newfrom[0], $to, $sub, $text);    
  673   } else {
  674     $ret = mail($to, $sub, $text, "From: $from \r\n");
  675   }
  676 
  677   return $ret;
  678 }
  679 
  680 #################################################
  681 # This function displays newly added links.
  682 #################################################
  683 
  684 function Newly_Added($max_new_links)
  685 {
  686     global $tpl, $start_script, $start_script_t, $update_link;
  687     global $config, $mylink;
  688     
  689     $cont = "";
  690     
  691     $result = mysqli_query( $mylink, "SELECT title,idx,message,date,hits FROM ".$config["pre"]."links WHERE status=0 ORDER BY date DESC,hits LIMIT 0,$max_new_links");
  692 
  693     if (mysqli_num_rows($result))
  694     {
  695         # as we append data, make sure to reset link_rows
  696         $tpl->set_var("link_rows", "");
  697         while ($list = mysqli_fetch_array($result) )
  698         {
  699             limitlength($list);
  700             $idx = $list["idx"];
  701             $tpl->set_var( array(
  702             "LINK_TITLE" => $list["title"], 
  703             "LINK_MESSAGE" => $list["message"],
  704             "LINK_ADDED" => $list["date"],
  705             "LINK_HITS" => $list["hits"],
  706             "LINK_GO" => $start_script_t."count=$idx",
  707             "LINK_MORE" => $start_script_t."more=$idx",
  708             "LINK_EDIT" => "$update_link&link=$idx"
  709             ));         
  710             $tpl->parse ("link_rows", "link_row", true);
  711         }
  712         $cont .= $tpl->subst("link");
  713     } else {
  714         $cont .= Message( "nothing_to_show" );
  715     }
  716     $cont = TextToLink($cont);
  717     
  718     return $cont;
  719 }
  720 
  721 #################################################
  722 # This function displays newly updated links.
  723 #################################################
  724 
  725 function Newly_Updated($max_upd_links)
  726 {
  727     global $tpl, $start_script, $start_script_t, $update_link;
  728     global $config, $mylink;
  729     
  730     $cont = "";
  731     
  732     $result = mysqli_query( $mylink, "SELECT title,idx,message,updated,hits FROM ".$config["pre"]."links WHERE updated<>'' and status=0 ORDER BY updated DESC,hits LIMIT 0,$max_upd_links");
  733 
  734     if (mysqli_num_rows($result))
  735     {
  736         # as we append data, make sure to reset link_rows
  737         $tpl->set_var("link_rows", "");
  738         while ($list = mysqli_fetch_array($result) )
  739         {
  740             limitlength($list);
  741             $idx = $list["idx"];
  742             $tpl->set_var( array(
  743             "LINK_TITLE" => $list["title"], 
  744             "LINK_MESSAGE" => $list["message"],
  745             "LINK_ADDED" => $list["updated"],
  746             "LINK_HITS" => $list["hits"],
  747             "LINK_GO" => $start_script_t."count=$idx",
  748             "LINK_MORE" => $start_script_t."more=$idx",         
  749             "LINK_EDIT" => "$update_link&link=$idx"
  750             ));         
  751             $tpl->parse ("link_rows", "link_row", true);
  752         }
  753         $cont .= $tpl->subst("link");
  754     } else {
  755         $cont .= Message( "nothing_to_show" );
  756     }
  757     $cont = TextToLink($cont);
  758     
  759     return $cont;
  760 }
  761 
  762 #################################################
  763 # This function displays top hits.
  764 #################################################
  765 
  766 function Top_Hits($max_top_links)
  767 {
  768     global $tpl, $start_script, $start_script_t, $update_link;
  769     global $config, $mylink;
  770     
  771     $cont = "";
  772     
  773     $result = mysqli_query( $mylink, "SELECT title,idx,message,date,hits FROM ".$config["pre"]."links WHERE hits<>0 and status=0 ORDER BY hits DESC LIMIT 0,$max_top_links ");
  774 
  775     if (mysqli_num_rows($result))
  776     {
  777         # as we append data, make sure to reset link_rows
  778         $tpl->set_var("link_rows", "");
  779         while ($list = mysqli_fetch_array($result) )
  780         {
  781             $idx = $list["idx"];
  782             limitlength($list);
  783             $tpl->set_var( array(
  784             "LINK_TITLE" => $list["title"], 
  785             "LINK_MESSAGE" => $list["message"],
  786             "LINK_ADDED" => $list["date"],
  787             "LINK_HITS" => $list["hits"],
  788             "LINK_GO" => $start_script_t."count=$idx",
  789             "LINK_MORE" => $start_script_t."more=$idx",         
  790             "LINK_EDIT" => "$update_link&link=$idx"
  791             ));
  792             $tpl->parse ("link_rows", "link_row", true);
  793         }
  794         $cont .= $tpl->subst("link");
  795     } else {
  796         $cont .= Message( "nothing_to_show" );
  797     }
  798     $cont = TextToLink($cont);
  799     return $cont;
  800 }
  801 
  802 #################################################
  803 # This function truncates fields too long before 
  804 # displaying
  805 #################################################
  806 
  807 function limitlength(&$list)
  808 {
  809     global $config;
  810     
  811     if ($config["limit_message_length"] <= 0) {
  812         return;
  813     }
  814     # limit the "message" field
  815     if (strlen($list["message"]) > $config["limit_message_length"]) {
  816         $list["message"] = substr($list["message"], 0, 
  817                     $config["limit_message_length"]). "...";
  818     }
  819 }
  820 
  821 function limitlength_cat(&$list)
  822 {
  823     global $config;
  824     
  825     if ($config["limit_message_length_cat"] <= 0) {
  826         return;
  827     }
  828     # limit the "message" field
  829     if (strlen($list["message"]) > $config["limit_message_length_cat"]) {
  830         $list["message"] = substr($list["message"], 0, 
  831                     $config["limit_message_length_cat"]). "...";
  832     }
  833 }
  834 
  835 
  836 #################################################
  837 # This function displays more information using 
  838 # details.tpl template
  839 #################################################
  840 
  841 function showMore($idx, &$title, $status = 0)
  842 {
  843     global $tpl, $start_script, $start_script_t, $update_link;
  844     global $config, $custom, $mylink;
  845     
  846     $cont = "";
  847     
  848     $result = mysqli_query( $mylink, "SELECT * FROM ".$config["pre"]."links WHERE idx=\"$idx\" and status=$status");
  849     if (mysqli_num_rows($result))
  850     {
  851         $list = mysqli_fetch_array($result);
  852 
  853         $cat = display_category($list["cat"]);
  854         $idx = $list["idx"];
  855         $tpl->set_var( array(
  856             "LINK_TITLE" => $list["title"], 
  857             "LINK_MESSAGE" => $list["message"],
  858             "LINK_MESSAGE_BR" => preg_replace("/\n/", "<br/>", $list["message"]),
  859             "LINK_ADDED" => $list["date"],
  860             "LINK_UPDATED" => $list["updated"],
  861             "LINK_LINK" => $list["link"],
  862             "LINK_HITS" => $list["hits"],
  863             "LINK_CATEGORY" => $cat,
  864             "LINK_GO" => $start_script_t."count=$idx",
  865             "LINK_MORE" => $start_script_t."more=$idx",         
  866             "LINK_EDIT" => "$update_link&link=$idx",
  867             "LINK_IDX" => $idx
  868             ));
  869         # now process custom rows
  870         reset($custom);
  871         while (list($k,$v) = each($custom)) {
  872             $ku = strtoupper($k);
  873             $dt = $list[$k];
  874             if ($dt != "") {
  875             # set data
  876             $tpl->set_var ($ku, filterOut($v, $dt));
  877             } else {
  878             # delete conditional block
  879             $tpl->set_block ("moredetails", "IFDEF_".$ku, "deleteme");
  880             # FIXME: does it work if there's more than one condition ?
  881             }
  882         }
  883         # parse
  884         $tpl->set_var("deleteme", "");
  885         $tpl->set_var("CATEGORY_TITLE", "");
  886         $tpl->parse("Sheet", "moredetails");
  887         $cont .= $tpl->subst("Sheet");
  888         $title .= " ".$list["title"];
  889     } else {
  890         $cont .= Message( "nothing_to_show" );
  891     }
  892 
  893     $cont = TextToLink($cont);
  894     
  895     # force a reload if there's a next call 
  896     $tpl->set_var ("moredetails", "");
  897     
  898     return $cont;
  899 }
  900 
  901 #################################################
  902 # Substitute strings, using the $text_link array
  903 #################################################
  904 
  905 function TextToLink($content)
  906 {
  907     global $text_link;
  908 
  909     reset($text_link);
  910     while ( list( $text, $link ) = each( $text_link ) ) {
  911     $content = str_replace( $text, $link, $content);
  912     }
  913     return $content;    
  914 }
  915 
  916 #################################################
  917 # this function returns a message and do template 
  918 # substitution using message.tpl
  919 #################################################
  920 
  921 function Message ($message_name, $array_vars = "")
  922 {
  923     global $tpl;
  924 
  925     if (!isset($tpl->varkeys[$message_name])) {
  926         # do not set the same block more than 1 time !
  927             $tpl->set_block("messages", $message_name);
  928     } 
  929     $tpl->set_var($array_vars);
  930     $cont = trim($tpl->subst($message_name));
  931                 
  932         return $cont;
  933 }
  934 
  935 #################################################
  936 # SQL escape function
  937 #################################################
  938 function sqlesc($str)
  939 {
  940     global $mylink;
  941 
  942     return mysqli_escape_string($mylink, $str);
  943 }
  944 
  945 #################################################
  946 # Content filtering functions
  947 #################################################
  948 function filterIn($type, $text)
  949 {
  950     switch ($type) {
  951     case "text":
  952         $text = htmlspecialchars($text);
  953         break;
  954     case "link":
  955         # do not strip & in links
  956         $text = htmlspecialchars($text);
  957         $text = preg_replace("/&amp;/", "&", $text);
  958         break;
  959     case "bool":
  960         if ($text == "on") $text = 1;
  961         if ($text != "1") $text = 0;
  962         break;
  963     }
  964     return $text;
  965 }
  966 
  967 function filterOut($type, $text)
  968 {
  969     switch ($type) {
  970     case "text":
  971         $text = TextToLink($text);
  972         break;
  973     case "link":
  974         break;
  975     case "bool":
  976         if ($text == 1) $text = "CHECKED";
  977         else $text = "";
  978         break;
  979     }
  980     return $text;
  981 }
  982 
  983 ?>