<?
// *** Manually Define DEBUG ***
define(DEBUG1);
define(OFFSET60*60); // *** Offset for one hour ***
define ('DEFAULT_RSS_FEED','10');

// *** Just in case they werent opened, or were calling this script from something other than main.phps... ***

// *** Include Secrets ***
include_once "secret.php";

// *** Include Persistant Link ***
include_once "pconnect.phps";

// *** Get Config from MySQL DB ***
include_once "get_config.phps";

// *** Functions for detecting the user browser ***
include_once "browser.phps";

class 
template
{
    var 
$tpl;
    var 
$tpl_vars;
    var 
$tpl_content;
    var 
$tpl_header;
    var 
$tpl_template_path;
    var 
$tpl_style_path;
    var 
$headless;

    function 
template(){
        
// *** Constructor ***
        
$this->tpl_template_path=$this->get_layout();
        
$this->tpl_style_path=$this->get_style();
        
$this->tpl_header=read_file($this->tpl_template_path."header.tpl");
        return 
1;
    }

    function 
template_set($variable$data){
        if (
is_array($this->tpl_vars)){
            
reset ($this->tpl_vars);
            while (list(
$name$val) = each ($this->tpl_vars)){
                
$data=str_replace($name$val$data);
            }
        }
        
$this->tpl_vars[$variable]=$data;
        return 
1;
    }

    function 
template_set_array($array){
        while (list(
$name$val) = each ($array)){
            
$this->tpl_vars[$name]=$val;
        }
        return 
1;
    }

    function 
template_set_content($content){
        
$this->tpl_content=$content;
    }

    function 
message($msg)
    {
        
$this->template_set_content($this->get_mini_tpl("content.tpl", array("{CONTENT_FILL}" => $msg)));
    }
    function 
get_mini_tpl($file$array ""$dir "")
    {
        
// *** Can't set the variable in the parameter because of $ ***
        
if (empty($dir)) $dir $this->tpl_template_path;

        if(
$temp_tpl=read_file($dir.$file)){
            if (
is_array($array)){
                while (list(
$name$val) = each ($array)){
                    
$temp_tpl=str_replace($name$val$temp_tpl);
                }
            }
            if (
is_array($this->tpl_vars)){
                
reset ($this->tpl_vars);
                while (list(
$name$val) = each ($this->tpl_vars)){
                    
$temp_tpl=str_replace($name$val$temp_tpl);
                }
            }
            return 
$temp_tpl;
        } else {
            return 
"file not found: ".$dir."$file";
        }
    }

    function 
set_rss_feed($rss_feed)
    {
        
$this->tpl_header=$rss_feed;
        
$this->headless 1;
        return 
1;
    }

    function 
set_media($id)
    {
        global 
$tpl;

        
$media_folder "media/";
        
$tpl_file get_media_tpl($id);

        
$query mysql_query(sprintf("select * from media where id='%s';"$id));
        
$media mysql_fetch_array($query);

        
$content2["{SOURCE}"] = $media_folder $media["type"] . $media["src"];
        
$media_code $tpl->get_mini_tpl($tpl_file$content2);

        
$content1["{TITLE}"] =         $media["title"];
        
$content1["{MEDIA}"] =         $media_code;
        
$content1["{COMMENT}"] =     $media["comment"];
        
$content1["{WIDTH}"] =         "800";
        
$content1["{HEIGHT}"] =     "600";

        
$output $tpl->get_mini_tpl("media.tpl"$content1);

        
$this->tpl_header $output;
        
$this->headless 1;

        return 
1;
    }

    function 
compile_tpl(){
        if (
$this->headless == 1){
            
$this->tpl=$this->tpl_header;
            return 
1;
        }
        
$content=$this->tpl;
        if (
$this->set_globals()){
            if (
is_array($this->tpl_vars)){
                
$temp_tpl $this->tpl_header;

                
// *** Comment out Every line with $temp_cont in it to prevent active content from being replaced ***
                /**/
$temp_cont $this->tpl_content;
                
reset ($this->tpl_vars);
                while (list(
$name$val) = each ($this->tpl_vars)){
                    if (
$name=="{TITLE}"){
                        
$temp_tpl=str_replace($name$val " - " TITLE$temp_tpl);
                        
/**/$temp_cont str_replace($nameTITLE " - " $val$temp_cont);
                    } else {
                        
$temp_tpl=str_replace($name$val$temp_tpl);
                        
/**/$temp_cont=str_replace($name$val$temp_cont);
                    }
                }

                
/**/$this->tpl_content $temp_cont;
                
// *** Time to add the header ***
                
$temp_tpl=str_replace("{CONTENT}"$this->tpl_content$temp_tpl);
                
$this->tpl=$temp_tpl;
                return 
1;
            } else {
                die (
"Global Variables non-existant!");
            }
        } else {
            die (
"Globals Unable to be Set");
        }
    }

    function 
set_globals()
    {
        
//$tpl->template_set("{SITE_NAME}", SITE_NAME);
        //$tpl->template_set("{SITE_URL}", SITE_URL);
        //$tpl->template_set("{SITE_OWNER}", SITE_OWNER);
        //$tpl->template_set("{LOADTIME}", $benchmark->result() AND $benchmark->START);
        
$login=login_menu();
        
$this->template_set("{GUEST_MESSAGE}",            get_guest_message());
        
$this->template_set("{DEBUG}",                get_debug());
        
$this->template_set("{META_DESCRIPTION}",         META_DESCRIPTION);
        
$this->template_set("{META_AUTHOR}",             META_AUTHOR);
        
$this->template_set("{META_GENERATOR}",         META_GENERATOR);
        
$this->template_set("{META_COPYRIGHT}",         META_COPYRIGHT);
        
$this->template_set("{META_REVISIT-AFTER}",        META_REVISIT-AFTER);
        
$this->template_set("{META_KEYWORDS}",            META_KEYWORDS);
        
$this->template_set("{META_ROBOTS}",             META_ROBOTS);
        
$this->template_set("{META_CHARSET}",             META_CHARSET);
        
$this->template_set("{NAV}",                 get_nav());
        
$this->template_set("{STYLE}",                 $this->get_style());
        
$this->template_set("{CURRENT_USER}",            current_member());
        
$this->template_set("{BANNER_FILE}",             BANNER);
        
$this->template_set("{LOGIN_STATUS}",            $login[1]);
        
$this->template_set("{LOGIN_USER_MENU}",        $login[0]);
        
$this->template_set("{STAT_UPTIME}",            nl2br(shell_exec(escapeshellcmd("uptime"))));
        
$this->template_set("{STAT_SERVER_INFO}",        nl2br(shell_exec(escapeshellcmd("cat /proc/cpuinfo"))));
        
$this->template_set("{STAT_MEMORY_INFO}",        nl2br(shell_exec(escapeshellcmd("free"))));
        
$this->template_set("{THEME_BOX}",            get_themes());
        
$this->template_set("{THEME_LINKS}",            get_themes_links());
        
$this->template_set("{CAT_LIST}",            get_cat_list());
        
$this->template_set("{RECENT_ACTIVITY}",        get_activity_list());
        
$this->template_set("{RECENT_CONTENT}",            get_content_list());
        
$this->template_set("{RECENT_DELICIOUS}",        get_delicious());
        
$this->template_set("{SCRATCHPAD}",            get_preview_scratch());
        
$this->template_set("{SCRATCH_MORE}",            get_scratch(20));
        
$this->template_set("{STATS}",                $this->get_mini_tpl("stats.tpl"));
        
$this->template_set("{SIDEBAR}",            $this->get_mini_tpl("sidebar.tpl"));
        
$this->template_set("{STATS_UNIQUE}",            get_stats("hits_unique"));
        
$this->template_set("{STATS_TOTAL}",            get_stats("hits_total"));
        
$this->template_set("{STATS_MAX}",            get_stats("max_online"));


        
$whos=whos_online();
        
$this->template_set("{WHOS_COUNT}",            $whos[0]);
        
$this->template_set("{WHOS_BODY}",            $whos[1]);

        
$this->template_set("{TIME}"date("m.d.y @ g:i a"));
        return 
1;
    }

    function 
get_layout()
    {
        if (
current_member() == "frikk" || current_member() == "tom" || current_member() == "Xyloft")
            return 
TPL_DIR."new/";

        return 
TPL_DIR.CURRENT_TEMPLATE;
    }

    function 
get_style()
    {
        return 
STYLE_DIR.STYLE_DEFAULT."style.css";
    }
}

class 
benchmark
{
    var 
$START;
    function 
benchmark() {
        list(
$usec$sec) = explode(' 'microtime());
        
$this->START = (float)$usec + (float)$sec;
    }

    function 
result() {
        list(
$usec$sec) = explode(' 'microtime());
        
$this->START number_format(((float)$usec + (float)$sec) - $this->START3);
    }
}

function 
get_media_tpl($id)
{
    
$query mysql_query(sprintf("select src from media where id='%s';"$id));
    list(
$src) = mysql_fetch_row($query);
    
$path_info pathinfo($src);
    switch (
$path_info["extension"])
    {
        case 
"swf":
            return 
"flash.tpl";
        case 
"jpg":
            return 
"image.tpl";
        default:
            return 
"media_error.tpl";
    }
}
function 
get_guest_message()
{
    
$ie_message "<b>Warning:</b> It appears that you are using Microsoft Internet Explorer.  " .
    
"There are some things on this website " .
    
"that may not show up correctly for you (drop down scratchpad, some mouseover menus), not to mention that " .
    
"IE is outdated, insecure, and does not correctly follow web standards.  I suggest trying " .
    
"one of the free <a href=\"http://browsehappy.com/\">alternate</a> browsers.  I personally recommend " .
    
"<a href=\"http://spreadfirefox.com/community/?q=affiliates&id=137283\">Mozilla Firefox</a>.";

    
$guest_message sprintf("Hi Guest! Thanks for stopping by! I'd really appreciate it if you took a moment and considered " .
    
"<a href=\"%s?register\">registering</a>! Its free, and you get a few perks (including disabling ads, posting with your " .
    
"username instead of anonymous, and a few other things).  It'd really mean alot to me! -- Blaine"SITE_DOMAIN);

    global 
$browser$tpl;
    if (
current_member() == "Guest")
        
$content .= $guest_message;

    if (
current_member() == "Guest" && strstr(strtolower($browser->Name), "msie"))
        
$content .= "<br/><br/>";

    if (
eregi("msie"strtolower($browser->Name)))
        
$content .= $ie_message;

    if (!empty(
$content))
        
$content .= ""// *** click here to never see this again ***

    
return (empty($content)) ? "" $tpl->get_mini_tpl("guest_message.tpl", array("{MESSAGE}"=>$content));
}

function 
get_preview_scratch()
{
    global 
$tpl;
    
$content = array(
        
"{SCRATCH_SINGLE_MSG}"    =>get_scratch(1)
    );
    return 
$tpl->get_mini_tpl("scratch_single.tpl"$content);
}

function 
post_scratch($author$url$body)
{
    
$author htmlentities(urldecode($author), ENT_QUOTES);
    
$body htmlentities(urldecode($body), ENT_QUOTES);
    
$url htmlentities(urldecode($url), ENT_QUOTES);
    if (!
mysql_query(sprintf("insert into scratchpad (author, date, body, url, ip)
    values ('%s', '%s', '%s', '%s', '%s');"
,
    
$authordate("U"), $body$url$_SERVER["REMOTE_ADDR"])))
    {
        
$mysql_error=mysql_error();
        die(
"Sorry, couldn't scratch: $mysql_error");
    }
    return 
1;
}

function 
get_scratch($num 1)
{
    global 
$tpl;
    
$l_break "";
    
$return_html "";
    
$query mysql_query(sprintf("select date, author, url, body from scratchpad order by id desc limit %s"$num));
    while (list(
$date$author$url$body) = mysql_fetch_row($query))
    {
        
$l_break = ($num 1) ? "<br>" "";
        
$content = array(
            
"{URL}"        =>$url,
            
"{AUTHOR}"    =>$author,
            
"{MESSAGE}"    =>$body,
            
"{DATE}"    =>date("m.d.y @ g:i a"$date)
            );
        
$return_html $return_html $tpl->get_mini_tpl("scratch_single_msg.tpl"$content) . $l_break;
    }

    if (!empty(
$return_html))
        return 
$return_html;

    return 
"Sorry, no scratches!";
}

function 
logout()
{
    if (
is_logged_in()){
        
//mysql_query(sprintf("UPDATE members SET session_recent='1' where id='%s';", member_info(current_member(), "id")));
        
unset ($_COOKIE["login"]);
        
setcookie("login"," "0);
        return 
1;
    }
}

function 
get_themes()
{
    
$sql mysql_query(sprintf("select name, id from themes where template='%s';"STYLE_DEFAULT));
    while (list(
$name$id) = mysql_fetch_row($sql))
        
$html .= sprintf("<li><a href='#' onclick=\"setActiveStyleSheet('%s'); return false;\">%s</a></li>"$id$name);

    return 
"<ul>" $html "</ul>";
}

function 
get_themes_links()
{
    
$sql mysql_query(sprintf("select name, id from themes where template='%s';"STYLE_DEFAULT));
    while (list(
$name$id) = mysql_fetch_row($sql))
    {
        if (
$alt)
        {
            
$rel "alternate stylesheet";
        } else {
            
$alt 1;
            
$rel "stylesheet";
        }
        
$html .= sprintf("<link rel=\"%s\" title=\"%s\" type=\"text/css\" href=\"%s\"/>\n"$rel$id"/" TPL_DIR.CURRENT_TEMPLATE "themes/" get_theme_info($id"css_file"));
    }

    return 
$html;
}

function 
get_theme_info($id$info "id")
{
    
// *** Get a member's info ***
    
if (is_theme($id)){
        if (
$info=="id")
            return 
$id;
        
$result=mysql_query(sprintf("SELECT %s FROM themes WHERE id='%s'"$info$id));
        list(
$filler)=mysql_fetch_row($result);
        if (
$filler)
            return 
$filler;
    }
}

function 
is_theme($id)
{
    return list(
$id) = mysql_fetch_row(mysql_query(sprintf("select id from themes where id='%s';"$id)));
}

/*
function get_default_theme()
{
    $theme_id = (($_COOKIE["theme"] <> null) || isset($_COOKIE["theme"])) && is_theme($_COOKIE["theme"])) ? $_COOKIE["theme"] : DEFAULT_THEME;

    // *** No cookie.  Could be first time or cookies disabled... ***
    return "/" . TPL_DIR.CURRENT_TEMPLATE."themes/" . get_theme_info($theme_id, "css_file");
}
function set_default_theme($theme_id)
{
    // *** Set the cookie for the theme ***
    if (is_theme($theme_id))
    {
        return setcookie("theme", $theme_id, time() + 25920000);
    }
}
*/

function get_debug()
{
    global 
$tpl;
    if (
DEBUG)
    {
        return 
$tpl->get_mini_tpl("debug.tpl");
    }

}
function 
get_nav()
{

    global 
$tpl;

    
$sql=mysql_query(sprintf("select id, title from content where parent='1' order by sort, title;"));
    while (list(
$table_id$table_title) = mysql_fetch_row($sql)){
        
$sql2=mysql_query(sprintf("select id, title, type, body from content where parent='%s' order by sort, title;",
         
$table_id));
        
$nav_html "";
        while (list(
$link_id$link_title$link_bool$link_body) = mysql_fetch_row($sql2)){
            switch (
$link_bool)
            {
            case 
"1":
                
$nav_html $nav_html sprintf("<li><a href='%s'>%s</a></li>"$link_body$link_title);
                break;
            case 
"2":
            case 
"3":
                
$nav_html $nav_html.sprintf("<li><a href='%s?content,%s'>%s</a></li>"SITE_DOMAIN$link_id$link_title);
                break;
            default:
                die(
MSG_INVALID_NAV_TYPE $link_id " - " $link_title ", type = " $link_bool);
            }
        }

        
$content = array(
        
"{NAV_TITLE}"=>        $table_title,
        
"{NAV_LINKS}"=>        $nav_html
        
);
        
$finalhtml=$finalhtml.$tpl->get_mini_tpl("nav.tpl"$content);
    }

    return 
$finalhtml;
}

function 
update_login_info()
{
    
// **Update login information from cookie ***
    
global $login$page;
    if (
is_logged_in()){
        
$result=mysql_query(sprintf("SELECT hits, session_start, session_recent, status, logins, id FROM members WHERE
         handle='%s'"
,
         
current_member()));
        list(
$hits$session_start$session_recent$status$logins$id)=mysql_fetch_row($result);
        
$hits++;
        if (
intval((date("U")-$session_start)/60) > LOGIN_TIMEOUT){
            list(
$user,$password)=explode(";",$login);
            
login($userdecode($password));
            return 
2;
        } else {
            
mysql_query(sprintf("UPDATE members set hits='%s', last_page_view='%s',
            session_recent='%s' where id='%s';"
$hits$_SERVER["SCRIPT_NAME"].$otherdate("U"), $id));
            return 
1;
        }
    }
}

function 
update_guest_info()
{
    
// *** Update information for guests by ip ***
    
$result=mysql_query(sprintf("SELECT session_start, session_recent, referer, hits, logins from guests where ip='%s';",
     
$_SERVER["REMOTE_ADDR"]));
    list (
$session_start$session_recent$referer$hits$logins)=mysql_fetch_row($result);
    if (
strlen($session_start)){
        
// *** Already hit before, update stats ***
        
if (intval((date("U")-$session_recent)/60) > LOGIN_TIMEOUT){
            
// *** If they timed out ***
            
$hits++;
            
$logins++;
            
mysql_query(sprintf("UPDATE guests SET logins='%s', hits='%s', last_page_view='%s', session_start='%s', agent='%s',
             session_recent='%s', session_recent2='%s' where ip='%s';"
$logins$hits$_SERVER["REQUEST_URI"], date("U"),
              
$_SERVER["HTTP_USER_AGENT"], date("U"), date("U"), $_SERVER["REMOTE_ADDR"]));
            return 
1;
        } else {
            
// *** update login info ***
            
$hits++;
            if (!
mysql_query(sprintf("UPDATE guests SET hits='%s', last_page_view='%s', session_recent='%s', session_recent2='%s'
             where ip='%s';"
$hits$_SERVER["REQUEST_URI"], date("U"), date("U"),  $_SERVER["REMOTE_ADDR"]))){
                echo (
mysql_errno().": ".mysql_error());
            }
            return 
1;
        }
    } else {
        
// ** create new entry ***
        
if (eregi("frikk.tk"$_SERVER['HTTP_REFERER']) or !strlen($_SERVER['HTTP_REFERER'])){
            
$referer="Direct Request";
        } else {
            
$referer "<a href='".$_SERVER['HTTP_REFERER']."'>".$_SERVER['HTTP_REFERER']."</a>";
        }
        
mysql_query(sprintf("INSERT into guests (last_page_view, session_start, session_recent, ip, referer, logins, hits, agent,
         session_recent2) values ('%s', '%s', '%s', '%s', '%s', '1', '1', '%s', '%s');"
$_SERVER["REQUEST_URI"], date("U"), date("U"),
          
$_SERVER["REMOTE_ADDR"], $referer$_SERVER["HTTP_USER_AGENT"], date("U")));
        return 
1;
    }
}

function 
whos_online()
{
// *** I've really gotta re-write this... ***
        
$loggedon="0";
        
$guestsin="0";
        
$now=date("U");
        
$result=mysql_query(sprintf("SELECT orig_login, handle, session_start, session_recent, status, id, email,
        site FROM members"
));
        
$totalhtml="";
        
$result2=mysql_query("SELECT session_start, session_recent, referer from guests");
        while (
$guests=mysql_fetch_array($result2)){
            if (
intval((date("U")-$guests["session_recent"])/60) < LOGIN_TIMEOUT){
                
$guestsin++;
            }
        }
        while (
$member=mysql_fetch_array($result)){
            
$time="";
            
$postdata="";
            
$prefix="";
            
$sign="";
            
$status="";
            
$signpostdata="";
            
$html_site="";
            
$info="";
            
$totaltime="";
            
// *** Make sure theyve logged in before ***
            
if ($member["orig_login"]<>"never"){
                
$idle=intval(($now-$member["session_recent"]));
                
$loggedin=intval(($now-$member["session_start"]));
                
// *** Make sure they're logged in... ***
                
if ((($idle)/60)<=LOGIN_TIMEOUT){
                    
// *** See if theyre idle... ***
                    
if (abs((($idle)/60)>LOGIN_IDLE)){ // *** idle ***
                        
$prefix="&nbsp;&nbsp;&nbsp;- idle: ";
                        
$time=round(($idle)/600);
                        
$postdata=" mins";
                    } else if (
abs((($idle)/60)<=LOGIN_IDLE)){ // *** not idle ***
                        
$prefix="&nbsp;&nbsp;&nbsp;- active: ";
                        if (
$loggedin<60){ // *** only online for seconds, not minutes ***
                            
$time=$loggedin;
                            
$postdata=" secs";
                        } else { 
// *** online for more than a minute ***
                            
$time=round(($loggedin)/600);
                            
$postdata=" mins";
                        } 
// end online active time
                    
// end active or idle

                    
$totaltime=$prefix.$time.$postdata;
                    
// *** Get the status symbols ***
                    
$status=$member["status"];
                    
$sign="";
                    if (
$status=="2"){
                        
$signpostdata="</font>";
                        
$sign="<font color=#0000bb>";
                    } elseif (
$status=="3"){
                        
$signpostdata="+</font>";
                        
$sign="<font color=#0000bb>";
                    } elseif (
$status=="4"){
                        
$signpostdata="++</font>";
                        
$sign="<font color=#0000bb>";
                    } elseif (
$status=="5"){
                        
$signpostdata="</font>";
                        
$sign="<font color=#0000bb>@";
                    }

                    
/*
                    // *** Get the info links ***
                    if (strlen($member["site"]))
                    // *** Check for a url (will be valid due to validation at preference update) ***
                        $html_site=" || <a href=" . $member["site"] . ">url</a> ";
                    $info=sprintf("&nbsp;&nbsp;&nbsp; - <a href='?users&id=%s'>info</a>%s", $member["id"],
                     $html_site);
                    */
                    
$totalhtml=$totalhtml sprintf("%s<a href='?get_member,%s' style='color:
                     #0000bb'>%s</a>%s<br>%s<br>"
,
                     
$sign$member["id"], $member["handle"], $signpostdata$totaltime);
                    
$loggedon++;
                } 
// end whos logged on
            
// end never logged on
        
}// end while
    
if ($loggedon==0)
        
$totalhtml="No members<br>";
    
$total $loggedon+$guestsin;
    
$query5=mysql_query(sprintf("select max_online from stats where date='%s';"date("Yz")));
    list(
$max) = mysql_fetch_row($query5);
    if (
$total $max)
    {
        
mysql_query(sprintf("update stats set max_online='%s' where date='%s';"$totaldate("Yz")));
    }

    
$returnit[]=$total;
    
$returnit[]=$totalhtml."<br><b>Guests:</b> ".$guestsin;
    return 
$returnit;
}

function 
get_members($sortby="handle")
{
    
$template=0;
    
$found="";
    if (!
$result=mysql_query(sprintf("select id, handle, logins, hits, session_start, orig_login, session_recent, last_login, status from
     members order by %s;"
$sortby)))
        return 
"<tr><td colspan=10>No Such Column to Sort By</td></tr>";
    while(
$member=mysql_fetch_array($result)){
        
$found="1";
        if (
$template==0){
            
$template=1;
            
$color="#FFFFFF";
        } else {
            
$template=0;
            
$color="#FFFFFF";
        }
        if (
strlen($member["orig_login"])){
            if (
abs(intval((date("U")-$member["session_recent"])/60) < LOGIN_TIMEOUT)){
                
$loggedin="Still Logged In";
            } else {
                
$loggedin=date("m.d.y @ g:i a"$member["session_start"]);
            }
        } else {
            
$loggedin="never";
        }
                
$html=$html.sprintf("<tr><td style='background: %s'><a href='?get_member,%s'>%s</a></td>
                <td style='background: %s'><a href='?get_member,%s'>%s</a></td><td style='background: %s'>%s</td>
                <td style='background: %s'>%s</td><td style='background: %s'>%s</td><td style='background:
                 %s'>%s</td></tr>"
,
                 
$color$member["id"], $member["id"], $color$member["id"], $member["handle"], $color,
                  
$member["status"],
                  
$color$member["logins"], $color$member["hits"], $color$loggedin);
        }
    if (
$found==0)
        return 
"<tr><td colspan=10>No Members</tr></td>";
    return 
$html;

}
function 
mysqlbackup($output$structure_only)
{
    
// taken from http://codewalkers.com/seecode/46.html
    //this function creates a text file (or output to a HTTP connection), that when parsed through MYSQL's telnet client, will re-create the entire database

    //Parameters:
        //      $host: usually "localhost" but depends on where the MySQL database engine is mounted
    //    $dbname : The MySQL database name
    //    $uid : the database's username (not your account's), leave blank if none is required
    //    $pwd : the database's password
    //    $output : this is the complete filespec for the output text file, or if you want the result SQL to be sent back to the browser, leave blank.
    //    $structure_only : set this to true if you want just the schema of the database (not the actual data) to be output.

    // **************
    // IMPORTANT: If you use this function, for personal or commercial use, AND you feel an overwhelming sense of gratitude that someone actually took the time and wrote it,
    // immediately go to your paypal account and send me $10 with a small comment of how and how much it helped! Set the payment recipient to woodystanford@yahoo.com .
    // **************

    
if (strval($output)!=""$fptr=fopen($output,"w"); else $fptr=false;

    
//open back-up file ( or no file for browser output)

    //set up database
    
out($fptr"create database $dbname;\n\n");

    
//enumerate tables
    
$res=mysql_list_tables($dbname);
    
$nt=mysql_num_rows($res);

    for (
$a=0;$a<$nt;$a++)
    {
        
$row=mysql_fetch_row($res);
        
$tablename=$row[0];

        
//start building the table creation query
        
$sql="create table $tablename\n(\n";

        
$res2=mysql_query("select * from $tablename");
        
$nf=mysql_num_fields($res2);
        
$nr=mysql_num_rows($res2);

        
$fl="";

        
//parse the field info first
        
for ($b=0;$b<$nf;$b++)
        {
            
$fn=mysql_field_name($res2,$b);
            
$ft=mysql_fieldtype($res2,$b);
            
$fs=mysql_field_len($res2,$b);
            
$ff=mysql_field_flags($res2,$b);

            
$sql.="    $fn ";

            
$is_numeric=false;
            switch(
strtolower($ft))
            {
                case 
"int":
                    
$sql.="int";
                    
$is_numeric=true;
                    break;

                case 
"blob":
                    
$sql.="text";
                    
$is_numeric=false;
                    break;

                case 
"real":
                    
$sql.="real";
                    
$is_numeric=true;
                    break;

                case 
"string":
                    
$sql.="char($fs)";
                    
$is_numeric=false;
                    break;

                case 
"unknown":
                    switch(
intval($fs))
                    {
                        case 
4:
            
//little weakness here...there is no way (thru the PHP/MySQL interface) to tell the difference between a
            // tinyint and a year field type
                            
$sql.="tinyint";
                            
$is_numeric=true;
                            break;

                        default:    
//we could get a little more optimzation here! (i.e. check for medium ints, etc.)
                            
$sql.="int";
                            
$is_numeric=true;
                            break;
                    }
                    break;

                case 
"timestamp":
                    
$sql.="timestamp";
                    
$is_numeric=true;
                    break;

                case 
"date":
                    
$sql.="date";
                    
$is_numeric=false;
                    break;

                case 
"datetime":
                    
$sql.="datetime";
                    
$is_numeric=false;
                    break;

                case 
"time":
                    
$sql.="time";
                    
$is_numeric=false;
                    break;

                default:
        
//future support for field types that are not recognized (hopefully this will work without need for future modification)
                    
$sql.=$ft;
                    
$is_numeric=true//I'm assuming new field types will follow SQL numeric syntax..this is where this support will breakdown
                    
break;
            }

            
//VERY, VERY IMPORTANT!!! Don't forget to append the flags onto the end of the field creator

            
if (strpos($ff,"unsigned")!=false)
            {
                
//timestamps are a little screwy so we test for them
                
if ($ft!="timestamp"$sql.=" unsigned";
            }

            if (
strpos($ff,"zerofill")!=false)
            {
                
//timestamps are a little screwy so we test for them
                
if ($ft!="timestamp"$sql.=" zerofill";
            }

            if (
strpos($ff,"auto_increment")!=false$sql.=" auto_increment";
            if (
strpos($ff,"not_null")!=false$sql.=" not null";
            if (
strpos($ff,"primary_key")!=false$sql.=" primary key";

            
//End of field flags

            
if ($b<$nf-1)
            {
                
$sql.=",\n";
                
$fl.=$fn.", ";
            }
            else
            {
                
$sql.="\n);\n\n";
                
$fl.=$fn;
            }

            
//we need some of the info generated in this loop later in the algorythm...save what we need to arrays
            
$fna[$b]=$fn;
            
$ina[$b]=$is_numeric;

        }

        
out($fptr,$sql);

        if (
$structure_only!=true)
        {
            
//parse out the table's data and generate the SQL INSERT statements in order to replicate the data itself...
            
for ($c=0;$c<$nr;$c++)
            {
                
$sql="insert into $tablename ($fl) values (";

                
$row=mysql_fetch_row($res2);

                for (
$d=0;$d<$nf;$d++)
                {
                    
$data=strval($row[$d]);

                    if (
$ina[$d]==true)
                        
$sql.= intval($data);
                    else
                        
$sql.="\"".mysql_escape_string($data)."\"";

                    if (
$d<($nf-1)) $sql.=", ";

                }

                
$sql.=");\n";

                
out($fptr,$sql);

            }

            
out($fptr,"\n\n");

        }

        
mysql_free_result($res2);

    }

    if (
$fptr!=falsefclose($fptr);
    return 
0;

}

function 
out($fptr,$s)
{
    if (
$fptr==false) echo("$s"); else fputs($fptr,$s);
}

function 
add_geoip()
{

    
// *** Functions for interfacing with the GeoIP Server ***
    
include_once "netgeo.phps";
    
    
// *** Set up the local Variables ***
    
$info = array();
    
$id ""$query "";
    
$user_agent = new Browser;
    
$netgeo = new netgeo_class;
    
    
// *** First of all, are they aready in the database? ***
    
$query mysql_query(sprintf("select id from map_ip where ip='%s';"$_SERVER["REMOTE_ADDR"]));
    list(
$id) = mysql_fetch_row($query);
    
    if (
strlen($id))
        return;
        
    
// *** If we can't get the information, theres no point in going on ***
    
if(!($netgeo->GetAddressLocation($_SERVER["REMOTE_ADDR"],$location)))
        return;
        
    
$longitude =    doubleval($location["LONG"]);
    
$latitude =     doubleval($location["LAT"]);
    
    
// *** Sometimes we run into problems, and longitude 
    //    and latitude both are set to 0.  We will ignore this
    
if ($longitude == && latitude==0) return;
        
    
/* *** Lets gather the information.  We want things that we can't
        figure out later (like IP, Browser) and also things that 
        don't require a hit to the GeoIP server later (Coords, 
        City, State, etc). *** */
        
    
$info["IP"] =         $_SERVER["REMOTE_ADDR"];
    
$info["User_Agent"] =     $user_agent->Name;
    
$info["OS"] =         $user_agent->Platform;
    
$info["Long"] =     $longitude;
    
$info["Lat"] =         $latitude;
    
$info["City"] =     htmlentities(ucwords(strtolower($location["CITY"])));
    
$info["State"] =     htmlentities(ucwords(strtolower($location["STATE"])));
    
$info["Country"] =     htmlentities(ucwords(strtolower($location["COUNTRY"])));
    
    
// *** Now that we have everything we need, lets add them to the database ***
    
if (!mysql_query(sprintf("insert into map_ip 
        (ip, user_agent, os, longitude, lat, city, state, country) values
        ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');"
,
        
$info["IP"], $info["User_Agent"], $info["OS"], $info["Long"], 
        
$info["Lat"], $info["City"], $info["State"], $info["Country"])))
    {
        echo 
"error adding your geoip entry to database!<br>";
        echo 
mysql_errno().": ".mysql_error()."<BR>";
        return;
    }
    
    
// *** We're all done now.  Return true to say that we didn't have an error ***
    
return true;
}

function 
generate_gmap()
{
    global 
$tpl;
    
$points_html "";
    
$gpoints = array();
    
    
$query mysql_query(sprintf("select * from map_ip order by id desc limit 500;"));
    while (
$points mysql_fetch_array($query))
    {
        
$gpoint["{POINT_NAME}"] =    sprintf("point%s"$points["id"]);
        
$gpoint["{MARKER_NAME}"] =     sprintf("marker%s"$points["id"]);
        
$gpoint["{USER_AGENT}"] =    $points["user_agent"];
        
$gpoint["{LONG}"] =         $points["longitude"];
        
$gpoint["{LAT}"] =        $points["lat"];
        
$gpoint["{CITY}"] =        $points["city"];
        
$gpoint["{STATE}"] =        $points["state"];
        
$gpoint["{COUNTRY}"] =        $points["country"];
        
$gpoint["{OS}"] =        $points["OS"];
        
$points_html .= $tpl->get_mini_tpl("gpoint.tpl"$gpoint);
    }

    return 
$tpl->get_mini_tpl("map.tpl", array("{MAP_POINTS}" => $points_html));
}

function 
update_stats($type="")
{
    global 
$tpl;    
    
    
// *** I'm only calling this because I know it'll get called every page load ***
    
add_geoip();
    
    
    
    
$result=mysql_query(sprintf("select id from stats where date='%s';"date("Yz")));
    list (
$exists) = mysql_fetch_row($result);
    if (!
strlen($exists)){
        
// *** Create New Entry ***
        
if (!mysql_query(sprintf("insert into stats (date, stat_month, stat_year) 
        values ('%s', '%s', '%s');"

        
date("Yz"), date("F"),
         
date("Y")))){
            die(
"Sorry, couldn't create daily entry");
        }
            if (
file_exists("unique.txt"))
            {
                
$file fopen("unique.txt""w");
                
fwrite($file" ");
                
fclose($file);
            } else {
                die(
"Sorry, unique.txt reading error");
            }
    }
        
$result=mysql_query(sprintf("select hits_total, hits_unique, 
        new_members, new_comments from stats where date='%s';"
date("Yz")));
        list (
$hits_total$hits_unique$new_members$new_comments$new_posts) = mysql_fetch_row($result);
        
$hits_total++;
        
// *** Unique Daily ***
        
if (file_exists("unique.txt")){
            
$fp3 fopen("unique.txt""r");
            
$uniques fread($fp3filesize("unique.txt"));
            
fclose($fp3);
        }
        
        
        if (!
strstr($uniques,($_SERVER["REMOTE_ADDR"]))){
        
/* 
        *** This means they are a unique IP for the day... 
            aka the first visit from this IP *** 
        */
            
$file fopen("unique.txt""w");
            
fwrite($file$_SERVER["REMOTE_ADDR"].";".$uniques);
            
fclose($file);
            
$hits_unique++;
            if (!
strstr(strtolower($_SERVER["HTTP_USER_AGENT"]), "bot") && 
                !
strstr(strtolower($_SERVER["HTTP_USER_AGENT"]), "slurp"))
                
$tpl->template_set("{GVISIT_SCRIPT}"
                
"<script language=\"JavaScript\" 
                src=\"http://www.gvisit.com/record.php?sid=6d5d65c02ecabc23fe38afc166fac21d\" 
                type=\"text/javascript\"></script>"
);
            
        } else {
            
$tpl->template_set("{GVISIT_SCRIPT}""<!-- GVISIT Script HERE -->");
        }
        
        if (
strlen($type)){
            
$query2 mysql_query(sprintf("select %s from stats where date='%s';"$typedate("Yz")));
            list(
$num) = mysql_fetch_row($query2);
            
$num++;
            if (!
mysql_query(sprintf("update stats set %s='%s' where date='%s';"$type$numdate("Yz")))){
                die (
mysql_errno().": ".mysql_error()."<BR>");
            }
            return 
1;
        }
        if (!
mysql_query(sprintf("update stats set hits_total='%s', 
        hits_unique='%s', new_members='%s', new_comments='%s' where date='%s';"
,
        
$hits_total$hits_unique$new_members$new_commentsdate("Yz")))){
            die (
mysql_errno().": ".mysql_error()."<BR>");
        }
            return 
1;
}

function 
do_stats()
{
    if (!
eregi(MY_IP$_SERVER["REMOTE_ADDR"])){
        if (!
update_stats())
            echo 
"couldn't update stats";
    }
    if (
is_logged_in()){
        if (!
update_login_info())
            echo 
"couldn't update login info";
    } else {
        if (!
update_guest_info())
            echo 
"couldn't update guest info";
    }
}

function 
get_stats($info$date="Yz")
{
        
$result=mysql_query(sprintf("select %s from stats where date='%s';"$infodate($date)));
        list (
$stat) = mysql_fetch_row($result);
        return 
$stat;
}

function 
stats()
{
    
// *** Generate Stats Table ***
    /*$result=mysql_query("select hits, logins from members");
    while($num=mysql_fetch_array($result)){
        $members++;
        $hits=$hits+$num["hits"];
        $logins=$logins+$num["logins"];
    }
    $result=mysql_query("select hits, logins from guests");
    while($num=mysql_fetch_array($result)){
        $guests++;
        $g_hits=$g_hits+$num["hits"];
    }
    $result=mysql_query("select id from news");
    while($num=mysql_fetch_array($result)){
        $posts++;
    }
    $result=mysql_query("select id from comments");
    while($num=mysql_fetch_array($result)){
        $comments++;
    }
    $totalhits=$hits+$g_hits;
    $lines=linecount();*/
    
return get_stats($info);
    
//."<br><br><b>Totals:</b><br>PHP lines: $lines<br>User Hits: $hits<br>Unique Hits: $guests<br>Guest Hits: $g_hits<br>Total Hits: $totalhits<br><p align=center>[<a href='?stats'>extended</a>]</p>";
}

function 
member_info_by_id($id$info="id")
{
    
// *** Get a member's info ***
    
if (member_exists_by_id($id)){
        if (
$info=="id")
        return 
$id;
        
$result=mysql_query(sprintf("SELECT %s FROM members WHERE id='%s'"$info$id));
        list(
$filler)=mysql_fetch_row($result);
        if (
$filler)
            return 
$filler;
    }
}

function 
login_menu()
{
    
// *** Make this templatable! ***
    // *** Generate the Login Menu in top right table ***
        
$menu="";
    if (
is_logged_in()){
        
$status=member_info(current_member(),"status");
        
$menu1="[ <b>Logged in:</b> ".current_member()." | <a href='index.php?logout'>log out</a> ]";
        
$menu="[ <b>Menu:</b> ";
        if (
$status >= STATUS_CREATE_CONTENT_GROUP)
            
$menu=$menu."<a href='index.php?add_content'>add content</a> | ";
        
/*
        if ($status >= STATUS_PROMOTE_MEMBERS)
            $menu=$menu."<a href='?controlpanel'>member promotions</a> | ";
        if ($status >= STATUS_TEMPLATE_OPTIONS)
            $menu=$menu."<a href='?template_options'>template</a> | ";
        if ($status >= STATUS_STYLE_OPTIONS)
            $menu=$menu."<a href='?color_scheme_options'>color scheme</a> | ";
        /*
        if ($status >= STATUS_UPLOAD)
            $menu=$menu."<a href='?upload'>upload media</a> | ";
        */
        // *** Put regular user menu together ***
        
$menu=$menu."<a href='?prefs'>settings / misc</a>] ";
        
$returnit[]=$menu;
        
$returnit[]=$menu1;
        return 
$returnit;
    } else {
        
$menu1="[ <b>Not Logged In</b> | <a href='index.php?login'>log in</a> | <a href='index.php?register'>register</a> ]";
        
$returnit[]="[ <b>Menu:</b> Please Login ]";
        
$returnit[]=$menu1;
        return 
$returnit;
    }
}

function 
member_info($handle$info="handle")
{
    
// *** Get a member's info ***
    
if (member_exists($handle)){
        if (
$info=="handle")
        return 
$handle;
        
$result=mysql_query(sprintf("SELECT %s FROM members WHERE handle='%s'"$info$handle));
        list(
$filler)=mysql_fetch_row($result);
        if (
$filler)
            return 
$filler;
    }
}

function 
is_valid_email($email)
{
// *** Gyrate.org email validation function ***
    // *** check length ***
    
if (strlen($email) <= USER_MAXEMAILLEN) {
        
// *** check valid characters ***
        
if (ereg("^[[:alnum:]_]([-_.]?[[:alnum:]])*@[[:alnum:]]([-.]?[[:alnum:]])*\\.[[:alpha:]]{2,3}$"$email)) {
            
$result 1;
        }
    }
    return 
$result;
}

function 
is_valid_password($password1$password2)
{
    if (!
trim($password1)==""){
        if (
$password1==$password2){
            if (!
eregi(" "$password1)){
                return 
1;
            }
        }
    }
}

function 
is_valid_handle($handle)
{
    
// *** Detemine if a specified handle is valid (ie: not taken and not obscene ***
    // *** For those of you viewing the source and make a name that goes around these... I'll probably just disable it anyways. ***
    
$cusswords=array();


    
// *** Check Length ***
    
if (strlen($handle) > USER_MAXLEN)
        return 
0;
    if (
strlen($handle) < USER_MINLEN)
        return 
0;

    
// *** Banned Handle? ***
    
for ($i=0$i<=count($cusswords)-1$i++){
        if (
strstr(strtolower($handle), $cusswords[$i])){
            return 
0;
        }
    }

    if (
member_exists($handle))
        return 
0;

    if (
strstr($handle," "))
        return 
0;

    
// *** Gyrate.org Alpha Verification ***
    
if (ereg('^[[:alpha:]]([ ]*[[:alnum:]])*$'$handle))
        return 
1;

    return 
0;
}

/*
function get_thread_count($id)
{
    if (is_topic($id)){
        $query=mysql_query(sprintf("select count(id) from blue_content where topic_id='%s';", $id));
        list($count) = mysql_fetch_row($query);
        return $count;
    }
    if (is_group($id)){
        $query=mysql_query(sprintf("select count(id) from blue_content where topic_id<>'0' AND group_id='%s';", $id));
        list($count) = mysql_fetch_row($query);
        return $count;
    }
}


function get_thread_comments($thread_id)
{
    if (!is_thread($thread_id))
        return;
    $query=mysql_query(sprintf("select * from blue_content where thread_id='%s';", $thread_id));
    while ($comments=mysql_fetch_array($query)){
        $found="1";
    }
    if ($found<>"1")
        return MSG_NO_COMMENTS;
    return $comment_html;
}

function get_topic_count($id)
{
    if (is_group($id)){
        $query=mysql_query(sprintf("select count(id) from blue_content where group_id='%s';", $id));
        list($count) = mysql_fetch_row($query);
        return $count;
    }
}

function get_thread_info($id, $property)
{
    if (is_thread($id)){
        $query=mysql_query(sprintf("select %s from blue_content where id='%s';", $property, $id));
        list ($thread_property) = mysql_fetch_row($query);
        return $thread_property;
    }
}

function get_topic_info($id, $property)
{
    if (is_topic($id)){
        $query=mysql_query(sprintf("select %s from blue_content where id='%s';", $property, $id));
        list ($topic_property) = mysql_fetch_row($query);*/
        /*
        return $topic_property;
    }
}

function get_group_info($id, $property)
{
    if (is_group($id)){
        $query=mysql_query(sprintf("select %s from blue_content where id='%s';", $property, $id));
        list ($group_property) = mysql_fetch_row($query);
        return $group_property;
    }
}

function post_topic_permission($user, $group_id)
{
    if (!is_group($group_id))
        return;
    $query=mysql_query(sprintf("select id from content_topic_permissions where group_id='%s' and user_id='%s';", $group_id,
     member_info($user, "id")));
    list ($permission) = mysql_fetch_row($query);
    if (is_numeric($permission))
        return 1;

}

function post_thread_permission($user, $topic_id)
{
    if (!is_topic($topic_id))
        return;
    $query=mysql_query(sprintf("select id from content_thread_permissions where topic_id='%s' and user_id='%s';", $topic_id,
     member_info($user, "id")));
    list ($permission) = mysql_fetch_row($query);
    if (is_numeric($permission))
        return 1;

}

function is_thread($id)
{
    $query=mysql_query(sprintf("select topic_id from blue_content where id='%s';", $id));
    list ($topic_id) = mysql_fetch_row($query);
    if (is_topic($topic_id))
        return 1;
}

function is_topic($id)
{
    $query=mysql_query(sprintf("select group_id from blue_content where id='%s';", $id));
    list ($topic_id) = mysql_fetch_row($query);
    if (strlen($topic_id)){
        if ($topic_id<>"0"){
            return 1;
        }
    }
}

function is_group($id)
{
    $query=mysql_query(sprintf("select group_id from blue_content where id='%s';", $id));
    list ($group_id) = mysql_fetch_row($query);
    if (strlen($group_id)){
        if ($group_id=="0"){
            return 1;
        }
    }
}
*/

function current_member()
{
    
// *** If user is logged in, returns handle ***
    
global $login;
    if (
is_logged_in()){
        list(
$user,$password)=explode(";",$login);
        return 
$user;
    } else {
        return 
"Guest";
    }
}


function 
encode($string)
{
    return 
base64_encode($string);
}

function 
decode ($string)
{
    return 
base64_decode($string);
}

function 
create_account($handle$email$password)
{
    
// *** Create an Account with the specified handle and email address ***
    // *** Validate ***
    
if (is_valid_email($email)==&& is_valid_handle($handle)==1){
        
$date=date("U");
        
// *** Create Account ***
        
if (mysql_query(sprintf("insert into members (handle, password, email, orig_date, orig_login) values
        ('%s', '%s', '%s', '%s', '%s');"
$handleencode($password), $email$date"never"))){
            
// *** Creation Success, send email ***
            
$mail_body=sprintf("%s\r\nHey %s!\r\nThanks for signing up with frikk dot tk!  With your new membership, you can" .
             
"interact with many different aspects of the site.  The handle, email address, and password you provided were " .
            
" the bare minimum required to be a part of frikk dot tk. Once you http://frikk.tk/?login , you can change your " .
             
"http://frikk.tk/?preferences . I suggest adding your birthdate (month/day), to recieve a special present on your " .
              
"special day! (wow! I'm excited!). Included below is the username and password you provided as a reminder. " .
             
" Please make note to log in before midnight tonight (EST), or your account will be automatically cleared out by a " .
             
" cleanup script. \r\n To verify your account, all you have to do is http://frikk.tk/?login \r\n\r\nYour Account " .
              
"Information:\r\nHandle: %s\r\nPassword: %s\r\n\r\nRemember to login by midnight tonight (EST)! Thanks!\r\n-- " .
               
"blaine\r\n\r\n"date("m.d.y @ g:i a"), $handle$handle$password);
            
send_mail($email"frikk dot tk""webmaster@frikk.tk""Welcome to frikk dot tk!"$mail_body);
            
//update_stats("new_member");
            
return 1;
        }
    }
}


function 
num_comments($id)
{
    
$comment_sql=mysql_query(sprintf("select count(id) from comments where parent='%s';"$id));
    list(
$comment_num)=mysql_fetch_row($comment_sql);
    return 
$comment_num;
}

function 
single_news($id)
{

    global 
$tpl;
    
// *** Return a single news post ***
    
if (strlen($id)){
        
$result=mysql_query("select author, date_updated, body, title, date, ghtml, cat from content where id='$id' order by id DESC");
        list(
$author$date_updated$body$subject$date$ghtml$cat) = mysql_fetch_row($result);
    
        
// *** We need to take the teaser tags out, if any ***
        
$body preg_replace("/\[teaser\](.+)\[\/teaser\]/Us"""$body);
        
        
$toc get_toc($body);
        
        if (
$ghtml == 1$body ghtmlToHtml($body);
        else 
$body nl2br($body);

        
$last_updated = (empty($date_updated)) ? $date $date_updated;
        
$last_updated date("m.d.y @ g:i a \E\S\T"$last_updated OFFSET);
        
        if (
strlen($author))
        {
            
$content=array(
            
"{TOC}" =>            $toc,
            
"{SUBJECT}"=>            $subject,
            
"{BODY}"=>            $body,
            
"{AUTHOR}"=>            member_info_by_id($author"handle"),
            
"{DATE}"=>            date("l, F jS @ g:i a \E\S\T"$date OFFSET),
            
"{LAST_UPDATED}" =>        $last_updated,
            
"{POST_CATEGORIES}"=>    sprintf("<a href='index.php?category,%s'>%s</a>"$catcat_info($cat"name"))
            );
            
$post_tpl=$tpl->get_mini_tpl("single_news_table.tpl"$content);
            return 
$post_tpl;
        }

    }
}

function 
get_news($parent_id$type "parent"$start_id 0)
{
    global 
$tpl;

    if (
$type <> "cat")
    {
        
$tpl->template_set("{TITLE}"content_info($parent_id"title"));

        if (
content_exists($parent_id) != 1)
            return 
MSG_INVALID_CONTENT;
    }

    
$found="";
    
$news2="";
    
$result=mysql_query(sprintf("select * from content where %s='%s' order by id DESC limit %s;"$type$parent_idNEWS_MAX));
    while (
$news=mysql_fetch_array($result))
    {
        
// *** Edit this so that it uses permissions ***
        //if ((member_info(current_member(), "status") >= STATUS_DELPOSTS)){
        //    $otherhtml2=sprintf("<a href='changenews.php?action=deletepost&id=%s'>Delete</a> - </a>", $news["id"]);
        //}
        
        
$body $news["body"];
        
$teaser_html "";
        
        
// *** See if there is a teaser.  If there is a teaser, then display this instead of the body ***
        
preg_match_all("/\[teaser\](.+)\[\/teaser\]/Us"    $body$matches);
        
        if (!empty(
$matches[1][0]))
        {
            
// *** There is a teaser! ***
            
$body $matches[1][0];
            
$teaser_html $tpl->get_mini_tpl("teaser.tpl"
                array(
"{TEASER_LINK}" => 
                
sprintf("comments-%s-%s.htm"$news["id"], 
                
date("m.d.y"$news["date"]))));
        } else {
            
// *** Build the Table of Contents before we parse the GHTML ***
            
$toc get_toc($news["body"]);
        }

        
$last_updated = (empty($news["date_updated"])) ? $news["date"] : $news["date_updated"];
        
$last_updated date("m.d.y @ g:i a \E\S\T"$last_updated OFFSET);
        
        if (
$news["ghtml"] == 1$body ghtmlToHtml($body);
        else 
$body nl2br($body);

        if ((
$news["author"]==member_info(current_member(), "id")))
            
$otherhtml=sprintf(" | <a href='index.php?add_content,weblog,%s'>Edit this post</a>",  $news["id"]);
            
        
$content=array(
        
"{TEASER}" =>            $teaser_html,
        
"{DATE_UPDATED}" =>        $last_updated,
        
"{TOC}" =>            $toc,
        
"{SUBJECT}"=>            $news["title"],
        
"{BODY}"=>            $body,
        
"{AUTHOR}"=>            member_info_by_id($news["author"], "handle"),
        
"{DATE}"=>            date("l, F jS @ g:i a \E\S\T"$news["date"] - OFFSET),
        
"{EDIT_HTML}"=>            $otherhtml.$otherhtml2,
        
"{POST_CATEGORIES}"=>        sprintf("<a href='index.php?category,%s'>%s</a>"$news["cat"], cat_info($news["cat"], "name")),
        
"{COMMENTS_LINK}"=>        sprintf("<a href='comments-%s-%s.htm'>View Comments [ %s ]</a>"$news["id"], date("m.d.y"$news["date"]), num_comments($news["id"]))
        );
        
$post_tpl=$tpl->get_mini_tpl("news_table.tpl"$content)."<br>";
        
$news2=$news2.$post_tpl;
        
$found="true";
    }
    if (!
strlen($found))
        
$news2="No News in Database";
    return 
$news2;
}

function 
get_rss_feed($id)
{
    if (empty(
$id)) $id DEFAULT_RSS_FEED;
    global 
$tpl;
    
$found="";
    
$news2="";
    
$result=mysql_query(sprintf("select * from content where parent='%s' order by id DESC limit %s;"$id8));
    
$body "";
    while (
$news=mysql_fetch_array($result))
    {
        
// *** First, we'll convert this over to GHTML if necessary ***
        
if ($news["ghtml"] == 1$body ghtmlToHtml($news["body"], 1);
        else 
$body nl2br($news["body"]);
        
//$body = nl2br(htmlentities($news["body"]));
        
        
$content=array(
        
"{RSS_ITEM_TITLE}"=>        htmlentities($news["title"]),
        
"{RSS_ITEM_LINK}"=>        sprintf("%scomments-%s-%s.htm"SITE_DOMAIN$news["id"], date("m.d.y"$news["date"])),
        
"{RSS_ITEM_DESCRIPTION}"=>    $body,
        
"{RSS_ITEM_COMMENTS}"=>        sprintf("%scomments-%s-%s.htm"SITE_DOMAIN$news["id"], date("m.d.y"$news["date"])),
        
"{RSS_ITEM_PUBDATE}"=>        date('r'$news["date"])
        );
        
$rss_1=$rss_1."\n\r".$tpl->get_mini_tpl("rss_item.tpl"$content);
    }
    
$rss_content=array(
    
"{RSS_TITLE}"=>            htmlentities(TITLE),
    
"{RSS_LINK}"=>            SITE_DOMAIN,
    
"{RSS_DESCRIPTION}"=>        htmlentities(SLOGAN),
    
"{RSS_ITEM}"=>            $rss_1,
    
"{RSS_COPYRIGHT}"=>        htmlentities(COPYRIGHT),
    
"{RSS_GENERATOR}"=>        htmlentities(META_GENERATOR),
    
"{RSS_WEBMASTER}"=>        WEBMASTER_EMAIL
    
);
    
$rss_2=$tpl->get_mini_tpl("rss_channel.tpl"$rss_content);

    
// *** Update Stats Database ***

    
return $rss_2;

}

function 
get_comments($id)
{
    global 
$tpl;
    if (
strlen($id)){
        
$result=mysql_query("select author, body, date, id, ip from comments where parent='$id' order by id DESC");
        while (
$comments=mysql_fetch_array($result)){
            
$author=$result["author"];
            if ((
$author==member_info(current_member(), "id") || ((member_info(current_member(), "status") >= STATUS_DELCOMMENT)
             && (
member_info(current_member(), "status") > member_info($author"status"))))){
                
$otherhtml2=sprintf("- <a href='index.php?delete_comment,%s'>delete</a>"$comments["id"]);
            }
            
$otherhtml=sprintf("<a href='index.php?edit_comment,%s'>edit</a> ".$otherhtml2$comments["id"]);

            
// *** Fix this guest thing... ***
            
if ($comments["author"]=="Guest"){
                
$link=sprintf("guest [%s]"$comments["ip"]);
            } else {
                
$link=member_link($comments["author"]);
            }
            
$content=array(
            
"{DATE}"=>        date("m.d.y @ g:i a"$comments["date"]),
            
"{AUTHOR}"=>        $link,
            
"{BODY}"=>        nl2br($comments["body"]),
            
"{EDIT_HTML}"=>        $otherhtml
            
);
            
$commentshtml=$commentshtml.$tpl->get_mini_tpl("comments.tpl"$content)."<br>";
        }
        return 
$commentshtml;
    }
}

function 
comment_post($author$body$id$pass_txt$pass_weblog)
{
    global 
$tpl;
    
$f fopen("comments.txt""a");
    
session_start();
    
$pass_weblog trim($pass_weblog);
    
$pass_txt trim($pass_txt);
    if (!
is_logged_in() && (empty($pass_weblog) || empty($pass_txt) || ($pass_weblog != $pass_txt)))
    {
        die(
"Sorry, the code you entered did not match what was in the picture box." 
        
" Make sure you type only what you see in white, <b>do not type the red letters</b>.  Also, if you " 
        
"are behind a proxy - make sure that the proxy has not cached the captcha image by refreshing.");
        
fwrite($f"Attempt Blocked\n\n\n");
        
fclose($f);
        return 
0;
    }
    
    
// *** Catch those damn spam bots ... are they really reading the captcha??? ***
    
$temp "Info for Comment: " date("m.d.y @ g:i a") . "\nServer Vars:";
    foreach(
$_SERVER as $key=>$val)
        
$temp .= "--$key = $val\n";
    
$temp .= "***\nPost Vars:\n";
    foreach(
$_POST as $key=>$val)
        
$temp .= "--$key = $val\n";
    
$temp .= "weblog_pass: $pass_weblog\n\n\n";
    
fwrite($f$temp);
    
fclose($f);
    
    
$result=mysql_query(sprintf("select body from comments where author='%s' order by date DESC limit 1"$author));
    list(
$lastmsg)=mysql_fetch_row($result);
    if (
$lastmsg != $body)
        if (
mysql_query(sprintf("insert into comments (author, parent, body, date, ip) values ('%s', '%s', '%s', '%s', '%s');",
         
$author$id$bodydate("U"), $_SERVER["REMOTE_ADDR"])))
         {
             
mysql_query(sprintf("update content set recent_comment='%s' where id='%s';"date("U"), $id));
             return 
1;
         }
}

function 
member_link($member)
{
    if (
strlen($member)){
        if (
member_exists($member)){
            
$member_id=member_info($member,"id");
            return 
"<a href='?get_member,$member_id'>$member</a>";
        } elseif (
$member=="guest") {
            return 
"guest";
        }
    }
}

function 
passgen()
{
    
//**************************************
    //
    // Name: Password Generator..,
    // Description:This function return Pass
    //     word consists of 0-9, a-z, A-Z
    // By: Bhushan Paranjpe
    //
    //This code is copyrighted and has // limited warranties.Please see
    //http://www.Planet-Source-Code.com/xq/ASP/txtCodeId.733/lngWId.8/qx/vb/scripts/ShowCode.htm
    //for details.
    //**************************************
    
$chars=array();
    for(
$i=48;$i<=57;$i++) {
        
array_push($charschr($i));
    }
    for(
$i=65;$i<=90;$i++) {
        
array_push($charschr($i));
    }
    for(
$i=97;$i<=122;$i++) {
        
array_push($charschr($i));
    }
    while(list(
$k$v)=each($chars)) {
    }
    for(
$i=0;$i<7;$i++) {
        
mt_srand((double)microtime()*1000000);
        
$passwd.=$chars[mt_rand(0,count($chars))];
    }
    return 
$passwd;
}


function 
first_login($user){
    
// *** What to do when a user first logs in ***
    
if (member_exists($user)){
        
mysql_query(sprintf("update members set orig_date='%s', posts='0', status='1', comments='0', logins='0', hits='0',
         show_prefs='1', orig_login='%s' where handle='$user'"
date("U"), date("U")));
        return 
1;
    }

}

function 
is_logged_in()
{
    
// *** Determines if user is logged in ***
    
global $login;
    if (
$login){
        list(
$user,$password)=explode(";",$login);
        if (
member_exists($user)){
            
$result=mysql_query("SELECT password FROM members WHERE handle='$user'");
            list(
$password1)=mysql_fetch_row($result);
            if (
$password1==$password)
                return 
1;
        }
    }
}

function 
login($user$password)
{
    
// *** Log in specified user with password ***
    
if (member_exists($user)){
        
$result=mysql_query("SELECT orig_login FROM members WHERE handle='$user'");
        list(
$orig_login)=mysql_fetch_row($result);
        if (
$orig_login=="never"){
            if (!
first_login($user))
                die (
"Can't set initial data");

        }
        
$result=mysql_query("SELECT password, logins FROM members WHERE handle='$user';");
        list(
$password1$logins$session_recent) = mysql_fetch_row($result);
        
$result4 mysql_query(sprintf("select session_recent from members where handle='%s';"$user));
        list(
$session4) = mysql_fetch_row($result4);

        if (
decode($password1)==$password){
            
$logins++;
            
mysql_query(sprintf("UPDATE members SET session_start='%s', session_recent='%s', last_login='%s',
            logins='%s' where handle='$user'"
date("U"), date("U"), $session4$logins));

            
// *** Correct Guest Entry ***
            
$result2=mysql_query(sprintf("SELECT id from guests where ip='%s'"$_SERVER["REMOTE_ADDR"]));
            list(
$id)=mysql_fetch_row($result2);
            if (
strlen($id))
                
mysql_query(sprintf("update guests set session_recent='1s' where id='%s';"$id));

            
setcookie("login",sprintf("%s;%s",$userencode($password)), time() + 25920000);
            if (!isset(
$return)){
                return 
1;
            }
        }
    }
}

function 
meta_refresh($location$message$time=0)
{
    return 
sprintf("<html><META HTTP-EQUIV=REFRESH CONTENT=%s;URL=%s>%s"$time$location$message);
}

function 
member_exists($user)
{
    
// *** See if a member already exists in the database ***
    
if (isset($user)){
        
$result=mysql_query("SELECT handle FROM members WHERE handle='$user'");
        list(
$tempuser)=mysql_fetch_row($result);
        if (
$tempuser){
            return 
1;
        }
    }
}

function 
member_exists_by_id($id)
{
    
// *** See if a member already exists in the database ***
    
if (isset($id)){
        
$result=mysql_query("SELECT handle FROM members WHERE id='$id';");
        list(
$tempuser)=mysql_fetch_row($result);
        if (
$tempuser){
            return 
1;
        }
    }
}

function 
send_mail($to$from_name$from_email$subject$body)
{
    
// *** Gyrate.org Mail Function ***
    // *** correct blank items ***
    
if (!strlen($from_name)) {
        
$from_name $from_email;
        }
    if (!
strlen($from_email)) {
        
$from_name "Unknown";
    }
    if (!
strlen($subject)) {
        
$subject 'No Subject';
    }
    
// *** add headers ***
    
$headers sprintf("From: %s <%s>"$from_name$from_email);
    
mail($to$subject$body$headers);
    return 
1;
}

function 
read_file($file)
{
    if (
file_exists($file)){
        if (
$temp_file=fopen($file"r")){
            if (
$read_file=fread($temp_filefilesize ($file))){
                
fclose ($temp_file);
                return 
$read_file;
            }
        }
    }
}




// *** New Content Functions... ***

//define('PARENT_ID',    '1');     //*** This should always be 1, but just in case... ***

/*
function get_content_nav()
{
    $sql=mysql_query(sprintf("select id, title from content where parent='%s';", PARENT_ID));
    while (list($table_id, $table_title) = mysql_fetch_row($sql)){
        $sql2=mysql_query(sprintf("select id, title from content where parent='%s' order by title;", $table_id));
        $nav_html = "";
        while (list($link_id, $link_title) = mysql_fetch_row($sql2)){
            $nav_html=$nav_html.sprintf("- <a href='?content&id=%s' class='nav'>%s</a><br>", $link_id, $link_title);
        }

        $finalhtml=$finalhtml."
        <tr>
            <td class=\"title\">
                " . $table_title . "
            </td>
        </tr>
        <tr>
            <td>
                " . $nav_html . "
            </td>
        </tr>
        ";
    }
    return $finalhtml;
}
*/

function execute($path){
    
//return nl2br(shell_exec(escapeshellcmd("$path")));
}

function 
get_content($id)
{
    global 
$tpl;
    if (
content_exists($id) != 1)
    {
        
$tpl->template_set("{TITLE}""Error");
        return 
MSG_INVALID_CONTENT;
    }

    if (
content_info($id"type") == "3")
    {
        return 
get_news($id"parent");
    }

    
$sql mysql_query(sprintf("select title, body, author from content where id='%s' order by title;"$id));
    list(
$title$body$author) = mysql_fetch_row($sql);


    if (
num_children($id) > 0)
    {
        
$sql2=mysql_query(sprintf("select id, title, type, body, date from content where parent='%s' order by sort, title;"$id));
        while (list(
$link_id$link_title$link_bool$link_body$date) = mysql_fetch_row($sql2)){
            
//$html=$html.sprintf("- <a href='?content&id=%s'>%s</a><br>", $link_id, $link_title);
            
switch ($link_bool)
            {
            case 
"1":
                
$link $link_body;
                break;
            case 
"2":
                
$link sprintf("?content,%s"$link_id);
                break;
            case 
"3":
                
$link sprintf("comments-%s-%s.htm"$link_iddate("m.d.y"$date));
                break;
            default:
                die(
MSG_INVALID_NAV_TYPE $link_id " - " $link_title ", type = " $link_bool);
            }
            
$threads=array(
                
"{SUB_ID}"=>        $link,
                
"{SUB_TITLE}"=>        $link_title
                
);
            
$sub_links $sub_links $tpl->get_mini_tpl("sub_threads_link.tpl"$threads);
        }
        
$sub_temp_html $tpl->get_mini_tpl("sub_threads.tpl", array("{THREAD_HTML}" => $sub_links));
    } else {
        
$sub_temp_html "no children";
    }

    
$content=array(
        
"{TRACE_ROOT}"=>        trace_root($id),
        
"{CONTENT_TITLE}"=>        $title,
        
"{CONTENT_BODY}"=>        nl2br($body),
        
"{CONTENT_AUTHOR}"=>        member_info_by_id($author"handle"),
        
"{CONTENT_DATE}"=>        date("m.d.y @ g:i a"$date),
        
"{CONTENT_THREADS}"=>        $sub_temp_html,
        
"{CONTENT_ID}"=>        $id,
        
"{COMMENTS_COUNT}"=>        num_comments($id)

        );

    
//echo trace_root($id);

    
$post_tpl=$tpl->get_mini_tpl("content_new.tpl"$content);

    
$tpl->template_set("{TITLE}"$title);
    return 
$post_tpl;
}

function 
get_cat_list($id 1$edit_id 1$level 0)
{
    
// *** This is for the "what category" on the content posting ***

    
if ($level == 0)
    {
        
$temp .= "<ul><li>[<a href='index.php' class=\"noblock\">Show All</a>]</li>";
        
$temp2 "";
    }
    else
    {
        
$temp .= "<li>";
        
$temp2 "</li>";
    }

    if (
$id 1)
        
$temp .= "<a href='index.php?category," $id "'>" cat_info($id"name") . "</a></li>" $temp2;

    
// *** Heart of the Recursion ***
    
if ($child get_cats_children($id))
        foreach(
$child as $child_id)
            
$temp $temp get_cat_list($child_id$edit_id$level 1);

    return 
$temp . (($level == 0) ? "</ul>" "");
}

function 
get_cats_tree($edit_id 0$id 1$level 0)
{
    
// *** This is for the "what category" on the content posting ***
    
$char "|_";

    if (
content_info($edit_id"cat") == $id)
        
$html "SELECTED";

    
$temp .= "<option value=" $id " " $html ">";

    if (
$level 0)
        
$temp .= str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;"$level-1) . $char;

    
$temp .=  cat_info($id"name") . "</option>";

    
// *** Heart of the Recursion ***
    
if ($child get_cats_children($id))
        foreach(
$child as $child_id)
            
$temp $temp get_cats_tree($edit_id$child_id$level 1);

    return 
$temp;
}

function 
display_posts_by_cat($cat_id)
{
    
$temp $temp get_news($cat_id"cat");

    
/*if ($child = get_cats_children($cat_id))
        foreach($child as $child_id)
            $temp = $temp . display_posts_by_cat($child);*/

    
return $temp;
}

function 
get_tree($edit_id 0$id 1$level 0)
{
    
// *** This is for the "what parent" on the content posting ***
    
$char "|_";

    if (!((
content_info($id"type") == 3) && (content_info(content_info($id"parent"), "type") == 3)))
    {
        if (
content_info($edit_id"parent") == $id)
            
$html "SELECTED";

        if (
$level 0)
        {
            
$temp .= "<option value=" $id " " $html ">";
            
$temp .= str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;"$level-1) . $char;
            
$temp .=  content_info($id"title") . "</option>";
        }
    }

    
// *** Heart of the Recursion ***
    
if ($child get_children($id))
        foreach(
$child as $child_id)
            
$temp $temp get_tree($edit_id$child_id$level 1);

    return 
$temp;
}

function 
get_tree_map($logged_in$id 1$level 0)
// *** Function for displaying site map... i know its redundant, but this code isnt the best anyways ***
// *** Update this later to only display edit link to those who have access ***
{

    
$temp .= "";
    
$char "|_";

    if (
$level 0)
        
$temp .= str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"$level-1) . $char;

    if (
$logged_in == "1")
    {
        if (
content_info($id"type") == "1"$link_bool "hyperlink"; else $link_bool "thread";
        
$html sprintf("(<a href='?add_content,%s,%s'>edit</a>)"$link_bool$id);
    }

    if (
content_info($id"type") == "1")
        
$nav "<a href=" content_info($id"body") . ">" content_info($id"title") . "</a>";
    else if (
content_info($id"type") == "3" && content_info(content_info($id"parent"), "type") == "3")
        
$nav "<a href=comments-" $id "-" date("m.d.y"content_info($id"date")) . ".htm>" content_info($id"title") . "</a>";
    else
        
$nav "<a href=?content/" content_info($id"id") . ">" content_info($id"title") . "</a>";

    
$temp .=  sprintf("%s %s<br>"$nav$html);

    
// *** Heart of the Recursion ***
    
if ($child get_children($id))
        foreach(
$child as $child_id)
            
$temp $temp get_tree_map($logged_in$child_id$level 1);

    return 
$temp;
}


function 
get_children($id)
{
    
// *** Returns array of children id's ***
    
if (num_children($id) == 0)
        return 
0;
    
$result mysql_query(sprintf("select id from content where parent='%s';"$id));
    while(list(
$child) = mysql_fetch_row($result))
        
$temp[] = $child;
    return 
$temp;
}

function 
get_cats_children($id)
{
    
// *** Returns array of children id's ***
    
if (num_children($id) == 0)
        return 
0;
    
$result mysql_query(sprintf("select id from cat_names where parent='%s' order by sort asc;"$id));
    while(list(
$child) = mysql_fetch_row($result))
        
$temp[] = $child;

    return 
$temp;
}

function 
content_info($id$info "id")
{
    
// *** Get a content item's info ***
    
if ($info == "id")
        return 
$id;
    
$result mysql_query(sprintf("select %s from content where id='%s';"$info$id));
    list(
$filler) = mysql_fetch_row($result);
    if (!empty(
$filler))
        return 
$filler;
}

function 
cat_info($id$info "id")
{
    if (
$info == "id")
        return 
$id;
    
$result mysql_query(sprintf("select %s from cat_names where id='%s';"$info$id));
    list(
$filler) = mysql_fetch_row($result);
    if (!empty(
$filler))
        return 
$filler;
}

/*function cat_record_info($id, $info = "id")
{
    if ($info == "id")
        return $id;
    $result = mysql_query(sprintf("select %s from cat_records where id='%s';", $info, $id));
    list($filler) = mysql_fetch_row($result);
    if (!empty($filler))
        return $filler;
}*/

function content_exists($id)
{
    
// *** See if a content thread already exists in the database ***
    
if (!empty($id)){
        
$result=mysql_query("SELECT title FROM content WHERE id='$id'");
        list(
$tempcontent)=mysql_fetch_row($result);
        if (!empty(
$tempcontent)){
            return 
1;
        }
    }
}

function 
num_children($id)
// *** Returns the number of children ***
{
    
$sql mysql_query(sprintf("select id from content where parent='%s';"$id));
    return 
mysql_num_rows($sql);
}

function 
num_cats_children($id)
// *** Returns the number of children ***
{
    
$sql mysql_query(sprintf("select id from cat_names where parent='%s';"$id));
    return 
mysql_num_rows($sql);
}

function 
update_content($content_id$content_body$content_title$content_parent$content_category$ghtml)
{
    if (!
strlen($content_title))
        return;
    if (!
strlen($content_body))
        return;
    if (!
strlen($content_parent))
        return;
    if (!
mysql_query(sprintf("update content set body='%s', title='%s', parent='%s', cat='%s', ghtml='%s', date_updated='%s' where id='%s';",
        
$content_body$content_title$content_parent$content_category$ghtmldate("U"), $content_id)))
        {
        echo (
mysql_errno().": ".mysql_error());
        return;

        }

    if (
LINK_DUMP == 1)
    {
        
mysql_query(sprintf("DELETE from link_dump WHERE parent='%s';"$content_id));
        
add_links($content_id);
    }

    return 
1;

}
function 
add_content($title$body$parent$author$content_category$ghtml$type)
{
    if (!
strlen($title))
        return;
    if (!
strlen($body))
        return;
    if (!
strlen($author))
        return;
    if (!
is_numeric($parent))
        return;

    if (!
mysql_query(sprintf("INSERT into content
    (title, body, parent, author, type, date, cat, ghtml) values
    ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');"
,
    
$title$body$parent$author$typedate("U"), $content_category$ghtml)))
        return ;

    
$query mysql_query(sprintf("select id from content ORDER BY DATE DESC LIMIT 1;"));
    list(
$new_id) = mysql_fetch_row($query);

    if (
LINK_DUMP == 1)
        
add_links($new_id);

    return 
1;
}

function 
trace_root($id$level=0)
{
    
// *** Trace back to the root ***
    // *** I'm pretty proud of this one ;-) ***
    
$char " -> ";
    
$parent content_info($id"parent");
    
$title content_info($id"title");

    
$arrow = (($level == 0) ? "" " $char ");
    if (
$parent == "NULL" || !content_exists($parent)) return $title " $char ";
    return 
trace_root($parent, ++$level) . " " $title $arrow;
}

function 
trace_root_cat($id$level=0)
{
    
// *** Trace back to the root ***
    // *** I'm pretty proud of this one ;-) ***
    
$char "->";
    
$parent cat_info($id"parent");
    
$title cat_info($id"name");

    
$arrow = (($level == 0) ? "" " $char ");

    if (
$parent == "0" || !cat_info($parent"name")) return $title " $char ";
    return 
trace_root($parent, ++$level) . " " $title $arrow;
}

function 
content_link($id) { return sprintf("<a href='index.php?content,%s'>%s</a>"$idcontent_info($id"title")); }

/*
function _get_nav()
{
    global $tpl;
    $sql=mysql_query("select id, title from content_tables");
    while (list($table_id, $table_title) = mysql_fetch_row($sql)){
        $sql2=mysql_query(sprintf("select id, title from content_links where table_id=%s", $table_id));
            $nav_html="";
        while (list($link_id, $link_title) = mysql_fetch_row($sql2)){
            $nav_html=$nav_html.sprintf("<a href='?manage_links,%s' class='nav'>%s</a><br>", $link_id, $link_title);
        }
        $content=array(
        "{NAV_TITLE}"=>        $table_title,
        "{NAV_LINKS}"=>        $nav_html
        );
        $finalhtml=$finalhtml.$tpl->get_mini_tpl("nav.tpl", $content);
    }
    return $finalhtml;
}
*/

// *** MySQL Search Class, Provided by Stephen Bartholomew,
//    from http://aspn.activestate.com/ASPN/Cookbook/PHP/Recipe/125901 ***
#############################################################
#
# -=[ MySQL Search Class ]=-
#
#      version 1.5
#
# (c) 2002 Stephen Bartholomew
#
# Functionality to search through a MySQL database, across
# all columns, for multiple keywords
#
# Usage:
#
#    Required:
#        $mysearch = new MysqlSearch;
#        $mysearch->setidentifier("MyPrimaryKey");
#        $mysearch->settable("MyTable");
#        $results_array = $mysearch->find($mysearchterms);
#
#    Optional:
#        This will force the columns that are searched
#        $mysearch->setsearchcolumns("Name, Description");
#
#             Set the ORDER BY attribute for SQL query
#            $mysearch->setorderby("Name");
#
##############################################################

class MysqlSearch
{
    function 
find($keywords)
    {
        
# Create a keywords array
        
$keywords_array explode(" ",$keywords);

        
# Select data query
        
if(!$this->searchcolumns)
        {
            
$this->searchcolumns "*";
            
$search_data_sql "SELECT ".$this->searchcolumns." FROM ".$this->table;
        }
        else
        {
            
$search_data_sql "SELECT ".$this->entry_identifier.",".$this->searchcolumns." FROM ".$this->table;
        }

        
# Run query, assigning ref
        
$search_data_ref mysql_query($search_data_sql);

        
# Define $search_results_array, ready for population
        # with refined results
        
$search_results_array = array();

        if(
$search_data_ref)
        {
            while(
$all_data_array mysql_fetch_array($search_data_ref))
            {
                
# Get an entry indentifier
                
$my_ident $all_data_array[$this->entry_identifier];

                
# Cycle each value in the product entry
                
foreach($all_data_array as $entry_key=>$entry_value)
                {
                    
# Cycle each keyword in the keywords_array
                    
foreach($keywords_array as $keyword)
                    {
                        
# If the keyword exists...
                        
if($keyword)
                        {
                            
# Check if the entry_value contains the keyword

                            
if(stristr($entry_value,$keyword))
                            {
                                
# If it does, increment the keywords_found_[keyword] array value
                                # This array can also be used for relevence results
                                
$keywords_found_array[$keyword]++;
                            }
                        }
                        else
                        {
                            
# This is a fix for when a user enters a keyword with a space
                            # after it.  The trailing space will cause a NULL value to
                            # be entered into the array and will not be found.  If there
                            # is a NULL value, we increment the keywords_found value anyway.
                            
$keywords_found_array[$keyword]++;
                        }
                        unset(
$keyword);
                    }

                    
# Now we compare the value of $keywords_found against
                    # the number of elements in the keywords array.
                    # If the values do not match, then the entry does not
                    # contain all keywords so do not show it.
                    
if(sizeof($keywords_found_array) == sizeof($keywords_array))
                    {
                        
# If the entry contains the keywords, push the identifier onto an
                        # results array, then break out of the loop.  We're not searching for relevence,
                        # only the existence of the keywords, therefore we no longer need to continue searching
                        
array_push($search_results_array,"$my_ident");
                        break;
                    }
                }
                unset(
$keywords_found_array);
                unset(
$entry_key);
                unset(
$entry_value);
            }
        }

        
$this->numresults sizeof($search_results_array);
        
# Return the results array
        
return $search_results_array;
    }

    function 
setidentifier($entry_identifier)
    {
        
# Set the db entry identifier
        # This is the column that the user wants returned in
        # their results array.  Generally this should be the
        # primary key of the table.
        
$this->entry_identifier $entry_identifier;
    }

    function 
settable($table)
    {
        
# Set which table we are searching
        
$this->table $table;
    }

    function 
setsearchcolumns($columns)
    {
        
$this->searchcolumns $columns;
    }
}

function 
add_links($id$load_all FALSE)
{
    
// *** This is the link dumper, it adds links to the database
    //    if $load_all = TRUE, it will add all the links that it finds
    //    where $id is the parent ***

    // *** Ternary Operators are the Shit!! ***
    
$query = ($load_all == TRUE)
    ? 
mysql_query(sprintf("SELECT id, parent, body, date from content where type='3' AND parent='%s';"$id))
    : 
mysql_query(sprintf("SELECT id, parent, body, date from content where id='%s';"$id));

    while (list(
$id$parent$body$date) = mysql_fetch_row($query))
    {
        
// *** This pattern came from
        //    http://www.desilva.biz/php/xtracturl.html ***

        
$urlpattern '/((http|https|ftp):\/\/|www)'
        
.'[a-z0-9\-\._]+\/?[a-z0-9_\.\-\?\+\/~=&#;,]*'
        
.'[a-z0-9\/]{1}/si';
        
preg_match_all($urlpattern$body$matches);

        for (
$i 0$i count($matches[0]); $i++)
        {
            
// *** Insert every link into the database ***
            
if (!mysql_query(sprintf("insert into link_dump(date, url, parent) values " .
                
"('%s', '%s', '%s');"$date$matches[0][$i], $id)))
                die(
"Error Adding to link dump");
        }
    }
}


function 
get_activity_list()
{
    global 
$tpl;

    
define(MAX_ACTIVITY,7);
    
define(ACTIVITY_TRUNCATE30);
    
$found "";
    
//$result = mysql_query(sprintf("select id, title, recent_comment from content order by recent_comment
    //    desc limit %s", MAX_ACTIVITY));
    
$result mysql_query(sprintf("select parent from comments order by id desc limit %s;"MAX_ACTIVITY));
    while(list(
$id) = mysql_fetch_row($result)){
        
$found "1";

        
$title content_info($id"title");
        
$date content_info($id"date");

        if (
strlen($title) > ACTIVITY_TRUNCATE)
            
$title substr($title0ACTIVITY_TRUNCATE) . "...";
        
$links=array(
            
"{COMMENT_LINK}"=>        sprintf("<a href='comments-%s-%s.htm'>%s</a>"$iddate("m.d.y"$date), $title),
            
"{COMMENT_DATE}"=>        date("m.d.y @ g:i a"$date)
            );
            
$sub_links $sub_links $tpl->get_mini_tpl("recent_activity_item.tpl"$links);
    }

    if (
$found==0)
        return 
"No Content Found";

    return 
$tpl->get_mini_tpl("recent_activity.tpl",
        array(
"{RECENT_ACTIVITY}" => $sub_links));
}

function 
get_content_list()
{
    global 
$tpl;

    
define(MAX_CONTENT,7);
    
define(CONTENT_TRUNCATE30);
    
$found "";
    
$result mysql_query(sprintf("select id, title, date, type, body from content order by date
        desc limit %s"
MAX_CONTENT));
    while(list(
$id$title$date$type$body) = mysql_fetch_row($result)){
        
$found "1";

        if (
strlen($title) > CONTENT_TRUNCATE)
            
$title substr($title0CONTENT_TRUNCATE) . "...";

        switch (
$type)
        {
        case 
"1":
            
$link sprintf("<a href='%s' class='nav'>%s</a>"$body$title);
            break;
        case 
"2":
            
$link sprintf("<a href='?content,%s' class='nav'>%s</a>"$id$title);
            break;
        case 
"3":
            
$link sprintf("<a href='comments-%s-%s.htm' class='nav'>%s</a>"$iddate("m.d.y"$date), $title);
            break;
        default:
            die(
MSG_INVALID_NAV_TYPE $id " - " $title ", type = " $type);
        }

        
$links=array(
            
"{CONTENT_LINK}"=>        $link,
            
"{CONTENT_DATE}"=>        date("m.d.y @ g:i a"$date)
            );
            
$sub_links $sub_links $tpl->get_mini_tpl("recent_content_item.tpl"$links);
    }

    if (
$found==0)
        return 
"No Content Found";

    return 
$tpl->get_mini_tpl("recent_content.tpl",
        array(
"{RECENT_CONTENT}" => $sub_links));
}

function 
get_link_dump($id)
{
    global 
$tpl;
    
$temp = (strlen($id)) ? " where parent='$id' " "" ;

    
$template 0;
    
$found "";
    
$result mysql_query(sprintf("select url, parent, date from link_dump %s order by date desc"$temp));
    while(list(
$url$parent$date) = mysql_fetch_row($result)){
        
$found "1";
        if (
$template == 0){
            
$template=1;
            
$color="color-alt-1";
        } else {
            
$template=0;
            
$color="color-alt-2";
        }

        
$threads=array(
            
"{LINK_URL}"=>        sprintf("<a href='%s'>%s</a>"$urlsubstr($url050) . "..."),
            
"{LINK_DATE}"=>        date("m.d.y @ g:i a"$date),
            
"{LINK_PARENT}"=>    sprintf("<a href='comments-%s-%s.htm'>%s</a>"$parentdate("m.d.y"$date), content_info($parent"title")),
            
"{LINK_COLOR}"=>    $color
            
);
            
$sub_links $sub_links $tpl->get_mini_tpl("link_dump_body.tpl"$threads);
    }

    if (
$found==0)
        return 
"No Links Found";
    return 
$tpl->get_mini_tpl("link_dump.tpl",
        array(
"{LINK_FILLER}" => $sub_links"{LINK_NAME}" => content_info($id"title")));
}


/* *** Function Listings *** */
function get_delicious()
{
    global 
$tpl;

    
// ######################### START CONFIG #########################
    // *** Max Number of chars to display ***
    
$truncate 14;

    
// *** Time to clear cache; 0 to disable ***
    
$clear_cache_time "30";

    
// ######################### END CONFIG #########################

    
$content "";

    if (!
is_numeric($num)) $num 10;

    
// *** Set the url as the live rss file if not set ***
    
if (empty($url)) $url "http://del.icio.us/rss/frikk/";

    
$data GetXMLTree(get_cache($url$clear_cache_time));

    for (
$i 0$i $num$i++)
    {
        
$title $data["rdf:RDF"]["item"][$i]["title"];
        
$link =  $data["rdf:RDF"]["item"][$i]["link"];

        
// *** Take out double quotes ***
        
$title htmlentities($titleENT_QUOTES);

        
$content .= sprintf("<li><a href='%s'>%s</a></li>"$link$title);

    }

    
$content $tpl->get_mini_tpl("delicious_links.tpl", array("{LINKS}" => $content));

    return 
$content;
}


function 
get_cache($url$clear_cache_time "30"$cache_folder "php/custom/rss_cache/")
{
    
/*
    ######################################################################################
    Simple Web Cacher - Blaine Booher - http://frikk.tk
    Release 0.2 - March 02 2006

    Licensed under the GPL (http://gnu.org/gpl)

    use this file like this:
    include "swc_frikk.tk.php";

    What it is: This can be used to work with internet and website data, without requesting
    the data every time you want to use it.  This sits between you and the remote data,
    downloading an updated version at an interval and caching it.  When you want to use
    the data, just call this function and it will check to see if the local copy is older
    than the specified interval (default: 30 minutes), download a new version if necessary,
    and return return the local cached version.

    Use:
    $data = get_cache("http://frikk.tk/?rss");

    You can then do whatever you need to do with it, such as:
    $xml = GetXMLTree($data);

    or just simply

    echo $data;

    There are two options, one for selecting the cache interval and one for selecting
    the cache folder.  They are used as:

    $data = get_cache("http://frikk.tk/?rss", "45", "my_cache/");

    This will get the data at http://frikk.tk/?rss every 45 minutes and store it in
    the folder my_cache.  Make sure my_cache exists, or if not make sure the script is
    able to create it.
    ######################################################################################
    */

    // *** Clear the php cache for file_exists and filemtime() ***
    
clearstatcache();

    if (!
file_exists($cache_folder))
        if (!
mkdir($cache_folder))
            die(
"Cannot Create Directory $cache_file");

    
$filename $cache_folder base64_encode($url);

    
/*
        *** Basically, the following if statement clear the cache if
        one of the following criteria is met: ***
        1.  The clear_cache variable is set in the URL ($clear_cache=1)
        2.  The cache file does not exist
        3.  $clear_cache_time is set to zero (essentially saying never cache)
        4.  The file modified time is older than specified in $clear_cache_time
    */

    
if ($clear_cache || !file_exists($filename) || ($clear_cache_time != "0" &&
        ((
date("U") - filemtime($filename)) >=
        (
$clear_cache_time 60)) ))
    {
        
// *** Download the new data from file and store it locally ***
        
if (!$pointer fopen($filename"w+"))
            die(
"Cannot open file  " $filename " for writing!");

        if (!
fwrite($pointerfile_get_contents($url)))
            die(
"Cannot write to file " $filename);
    }

    
// *** Cache should be there! Use it! ***
    
return (file_get_contents($filename));
}

function 
GetXMLTree ($xmldata)
{
    
// *** from http://whoooop.co.uk/2005/03/20/xml-to-array/ ***
    // we want to know if an error occurs
    
ini_set ('track_errors''1');

    
$xmlreaderror false;

    
$parser xml_parser_create ('ISO-8859-1');
    
xml_parser_set_option ($parserXML_OPTION_SKIP_WHITE1);
    
xml_parser_set_option ($parserXML_OPTION_CASE_FOLDING0);
    if (!
xml_parse_into_struct ($parser$xmldata$vals$index)) {
        
$xmlreaderror true;
    }
    
xml_parser_free ($parser);

    if (!
$xmlreaderror) {
        
$result = array ();
        
$i 0;
        if (isset (
$vals [$i]['attributes']))
            foreach (
array_keys ($vals [$i]['attributes']) as $attkey)
            
$attributes [$attkey] = $vals [$i]['attributes'][$attkey];

        
$result [$vals [$i]['tag']] = array_merge ($attributesGetChildren ($vals$i'open'));
    }

    
ini_set ('track_errors''0');
    return 
$result;
}

function 
GetChildren ($vals, &$i$type)
{
    
// *** from http://whoooop.co.uk/2005/03/20/xml-to-array/ ***
    
if ($type == 'complete') {
        if (isset (
$vals [$i]['value']))
            return (
$vals [$i]['value']);
        else
            return 
'';
    }

    
$children = array (); // Contains node data

    /* Loop through children */
    
while ($vals [++$i]['type'] != 'close') {
        
$type $vals [$i]['type'];
        
// first check if we already have one and need to create an array
        
if (isset ($children [$vals [$i]['tag']])) {
            if (
is_array ($children [$vals [$i]['tag']])) {
                
$temp array_keys ($children [$vals [$i]['tag']]);
                
// there is one of these things already and it is itself an array
                
if (is_string ($temp [0])) {
                    
$a $children [$vals [$i]['tag']];
                    unset (
$children [$vals [$i]['tag']]);
                    
$children [$vals [$i]['tag']][0] = $a;
                }
            } else {
                
$a $children [$vals [$i]['tag']];
                unset (
$children [$vals [$i]['tag']]);
                
$children [$vals [$i]['tag']][0] = $a;
            }

            
$children [$vals [$i]['tag']][] = GetChildren ($vals$i$type);
        } else
            
$children [$vals [$i]['tag']] = GetChildren ($vals$i$type);
        
// I dont think I need attributes but this is how I would do them:
        
if (isset ($vals [$i]['attributes'])) {
            
$attributes = array ();
            foreach (
array_keys ($vals [$i]['attributes']) as $attkey)
            
$attributes [$attkey] = $vals [$i]['attributes'][$attkey];
            
// now check: do we already have an array or a value?
            
if (isset ($children [$vals [$i]['tag']])) {
                
// case where there is an attribute but no value, a complete with an attribute in other words
                
if ($children [$vals [$i]['tag']] == '') {
                    unset (
$children [$vals [$i]['tag']]);
                    
$children [$vals [$i]['tag']] = $attributes;
                }
                
// case where there is an array of identical items with attributes
                
elseif (is_array ($children [$vals [$i]['tag']])) {
                    
$index count ($children [$vals [$i]['tag']]) - 1;
                    
// probably also have to check here whether the individual item is also an array or not or what... all a bit messy
                    
if ($children [$vals [$i]['tag']][$index] == '') {
                        unset (
$children [$vals [$i]['tag']][$index]);
                        
$children [$vals [$i]['tag']][$index] = $attributes;
                    }