<?php if (isset($_GET['code'])) { die(highlight_file(__FILE__, 1)); } ?>
<?
    /******************************************************
    * Presence's dynamic comic display system gizmo
    *   presence@irev.net
    ******************************************************/

function InitDB() {
    global $conn;
    global $nowsql;
    global $nowurl;
	require_once("db.php"); // $host, $user, $pass, $db name, $dirlocation no trailing slash
	mysqli_report(MYSQLI_REPORT_OFF);
	//mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
	$conn = mysqli_connect($host, $user, $pass, $db, 3306) or die(mysqli_connect_error());
	//printf("Success... %s\n", mysqli_get_host_info($conn));
    mysqli_select_db($conn,$db);
    $nowsql = Date("Y-m-d G:00:00");
    $nowurl = Date("Y-m-d-G");
}

function ParseQS() {
    if (preg_match("/^(\d{4})-(\d{2})-(\d{2})(:)?(-)?(\d{2})?/", $_SERVER['QUERY_STRING'], $datearray)) {
        $desired['validcomicformat'] = 1;
        $desired['year'] = $datearray[1];
        $desired['month'] = $datearray[2];
        $desired['day'] = $datearray[3];
        if ($datearray[6]) {
            $desired['hour'] = $datearray[6];
        } else {
            $desired['hour'] = 0;
        }
        $desired['sql'] = $desired['year'] ."-". $desired['month'] ."-". $desired['day'] ." ". $desired['hour'] .":00:00";
         return($desired);
    } else {
        $desired['validcomicformat'] = 0;
        return($desired);
    }
}

function ParseDYO() {
    if (preg_match("/^dyo-(\d+)/", $_SERVER['QUERY_STRING'], $dyoarray)) {
        return($dyoarray[1]);
    }
}

function GetDefaultComic() {
    global $nowsql;
    global $conn;
    $desired = ParseQS();
    $stmt_now = "SELECT id,comicimage,toppost,title,dateshow FROM comics WHERE comictype = 'd' and to_days(dateshow) <= to_days('$nowsql') ORDER BY dateshow DESC limit 1";
    $res_now = mysqli_query($conn, $stmt_now);
    if (mysqli_num_rows($res_now) ) {
        $row = mysqli_fetch_array($res_now);
        $comic['id'] = $row['id'];
        $comic['title'] = stripslashes($row['title']);
        $comic['comicimage'] = $row['comicimage'];
        $comic['year'] = substr($row['dateshow'],0,4);
        $comic['month'] = substr($row['dateshow'],5,2);
        $comic['day'] = substr($row['dateshow'],8,2);
        $comic['hour'] = substr($row['dateshow'],11,2);
        if ($comic['hour'] == 0) {
            $comic['display'] = $comic['month']."-". $comic['day'] ."-". $comic['year'];
        } else {
            $comic['display'] = $comic['month']."-". $comic['day'] ."-". $comic['year'] ."-". $comic['hour'];
        }
        return($comic);
    }
}

function GetDesiredComic() {
    // To Be called at any time, reads in Query String for what to see
    global $nowsql;
    global $conn;
    $desired = ParseQS();
    if ($desired['validcomicformat']) {
        $stmt_now = "SELECT id,comicimage,toppost,title,dateshow FROM comics WHERE comictype = 'd' AND dateshow = '". $desired['sql'] ."' and to_days(dateshow) <= to_days('$nowsql') ORDER BY dateshow DESC limit 1";
        $res_now = mysqli_query($conn,$stmt_now);
        if (mysqli_num_rows($res_now) ) {
            $row = mysqli_fetch_assoc($res_now);
            $comic['id'] = $row['id'];
            $comic['title'] = stripslashes($row['title']);
            $comic['comicimage'] = $row['comicimage'];
            $comic['year'] = substr($row['dateshow'],0,4);
            $comic['month'] = substr($row['dateshow'],5,2);
            $comic['day'] = substr($row['dateshow'],8,2);
            $comic['hour'] = substr($row['dateshow'],11,2);
            if ($comic['hour'] == 0) {
                $comic['display'] = $comic['month']."-". $comic['day'] ."-". $comic['year'];
            } else {
                $comic['display'] = $comic['month']."-". $comic['day'] ."-". $comic['year'] ."-". $comic['hour'];
            }
            return($comic);
        }
    } else {
        return(GetDefaultComic());
    }
}

function GetNews($id) {
    global $conn;
    $desired = ParseQS();
	$stmt = "SELECT who,post FROM posts WHERE id = $id";
	$res = mysqli_query($conn,$stmt);
	if (mysqli_num_rows($res) != 0) {
		$row = mysqli_fetch_array($res);
		$row["who"] = stripslashes(ucwords($row["who"]));
		$row["post"] = stripslashes($row["post"]);
		return($row);
    }
}

function DropDownListComics() {
    global $nowsql;
    global $conn;
    $stmt = "SELECT dateshow,title FROM comics WHERE comictype='d' and to_days(dateshow) <= to_days('$nowsql') ORDER BY dateshow DESC";
    $result = mysqli_query($conn,$stmt);
    echo "<OPTION value=\"\">&nbsp; &nbsp; &nbsp; (Previous Comics) &nbsp; &nbsp;</OPTION>\n";
    while ($row = mysqli_fetch_assoc($result)) {
        $dyr = substr($row['dateshow'],2,2);
        $ryr = substr($row['dateshow'],0,4);
        $mo = substr($row['dateshow'],5,2);
        $da = substr($row['dateshow'],8,2);
        $hr = substr($row['dateshow'],11,2);
        echo "<OPTION value=\"/". $ryr ."-". $mo ."-". $da ."-". $hr ."\">". $mo ."/". $da ."/". $dyr ." - ". stripslashes($row['title']) ."</OPTION>\n";
    }
}

function LastComic() {
    global $nowsql;
    global $conn;
    $stmt = "SELECT dateshow,title FROM comics WHERE comictype='d' and to_days(dateshow) <= to_days('$nowsql') ORDER BY dateshow DESC LIMIT 1";
    $result = mysqli_query($conn,$stmt);
    $row = mysqli_fetch_array($result);
    $year = substr($row['dateshow'],0,4);
    $mo = substr($row['dateshow'],5,2);
    $da = substr($row['dateshow'],8,2);
    $hr = substr($row['dateshow'],11,2);
    $last['url'] = $year ."-". $mo ."-". $da ."-". $hr;
    $last['title'] = stripslashes($row['title']);
    return($last);
}

function NextComic() {
    global $nowsql;
    global $conn;
    $desired = ParseQS();
    if (!$desired['validcomicformat']) {
        // if not specified, assume current comic
        $desired['sql'] = $nowsql;
    }
    $stmt = "SELECT dateshow,title FROM comics WHERE comictype = 'd' AND to_days(dateshow) > to_days('". $desired['sql'] ."') and to_days(dateshow) <= to_days('$nowsql') ORDER BY dateshow ASC limit 1";
    $result = mysqli_query($conn,$stmt);
    if (mysqli_num_rows($result)) {
        $row = mysqli_fetch_array($result);
        $year = substr($row['dateshow'],0,4);
        $mo = substr($row['dateshow'],5,2);
        $da = substr($row['dateshow'],8,2);
        $hr = substr($row['dateshow'],11,2);
        $next['url'] = $year ."-". $mo ."-". $da ."-". $hr;
        $next['title'] = stripslashes($row['title']);
    } else {
        $last = LastComic();
        $next['url'] = $last['url'];
    }
    return($next);
}

function PrevComic() {
    global $nowsql;
    global $conn;
    $desired = ParseQS();
    if (!$desired['validcomicformat']) {
        // if not specified, assume current comic is on display now, 
        //  so get comic previous to the current. (limit 1,1)
        $desired['sql'] = $nowsql;
        //  taken out, was causing a bump back issue ----- 
	//$stmt = "SELECT dateshow,title FROM comics WHERE comictype = 'd' AND to_days(dateshow) < to_days('". $desired['sql'] ."') and to_days(dateshow) <= to_days('$nowsql') ORDER BY dateshow DESC limit 1,1";
        $stmt = "SELECT dateshow,title FROM comics WHERE comictype = 'd' AND to_days(dateshow) < to_days('". $desired['sql'] ."') and to_days(dateshow) <= to_days('$nowsql') ORDER BY dateshow DESC limit 1";
    } else { 
        $stmt = "SELECT dateshow,title FROM comics WHERE comictype = 'd' AND to_days(dateshow) < to_days('". $desired['sql'] ."') and to_days(dateshow) <= to_days('$nowsql') ORDER BY dateshow DESC limit 1";
    }
    //echo "$stmt<br>";
    $result = mysqli_query($conn,$stmt);
    if (mysqli_num_rows($result)) {
        $row = mysqli_fetch_array($result);
        $year = substr($row['dateshow'],0,4);
        $mo = substr($row['dateshow'],5,2);
        $da = substr($row['dateshow'],8,2);
        $hr = substr($row['dateshow'],11,2);
        $prev['url'] = $year ."-". $mo ."-". $da ."-". $hr;
        $prev['title'] = stripslashes($row['title']);
    } else {
        $prev['url'] = "2001-10-29";
    }
    return($prev);
}


function RandomSponsor() {
    global $conn;
    $totalstatement = "SELECT sponsor FROM sponsors";
    $quotestotal = mysqli_query($conn,$totalstatement);
    $rows = mysqli_num_rows($quotestotal) -1;
    // seed the random number generator
    srand((double)microtime()*1000000);
    // get a random entry
    $randval = rand(0,$rows);
    $statement = "SELECT sponsor FROM sponsors LIMIT $randval,1";
    $randquote = mysqli_query($conn,$statement);
    $row = mysqli_fetch_assoc($randquote);
    return($row["sponsor"]);
}

function RandomTopic() {
    global $conn;
    $totalstatement = "SELECT quote FROM randomquotes";
    $quotestotal = mysqli_query($conn,$totalstatement);
    $rows = mysqli_num_rows($quotestotal) -1;
    // seed the random number generator
    srand((double)microtime()*1000000);
    // get a random entry
    $randval = rand(0,$rows);
    $statement = "SELECT quote FROM randomquotes LIMIT $randval,1";
    $randquote = mysqli_query($conn,$statement);
    $row = mysqli_fetch_assoc($randquote);
    return(stripslashes($row["quote"]));
}

function LinkBanners() {
    global $conn;
    $total = "SELECT name FROM links";
    $linktotal = mysqli_query($conn,$total);
    $numrows = mysqli_num_rows($linktotal) -1;
    // seed the random number generator
    srand((double)microtime()*1000000);
    // get a random entry
    $randomarray = array();
    while ($counter != 5) {
	$randomval = rand(0,$numrows); 
	if (!in_array($randomval,$randomarray)) {
		$randomarray[] = $randomval;
		$statement = "SELECT name,image,url FROM links LIMIT $randomval,1"; 
		$randlink = mysqli_query($conn,$statement);
		if (mysqli_num_rows($randlink)) { 
			while ($row = mysqli_fetch_assoc($randlink)) { 
				?><td><a href="<? echo $row["url"]; ?>"><img src="/linkbuttons/<? echo $row["image"]; ?>" border="1" alt="<? echo $row["name"]; ?>" height="31" width="88"></a></td><?
				$counter++;
			}
		}
	}
    }
}

function LinkBannersAll() {
	global $conn;
	$statement = "SELECT name,image,url FROM links"; 
	$randlink = mysqli_query($conn,$statement);
	?><table border=0 cellspacing=2 cellpadding=2><?
	while ($row = mysqli_fetch_assoc($randlink)) { 
		?><tr><td><a href="<? echo $row["url"]; ?>"><img src="/linkbuttons/<? echo $row["image"]; ?>" border="1" alt="<? echo $row["name"]; ?>" height="31" width="88"></a></td><td><? echo $row["name"]; ?></td></tr><?
	}
	?></table><?
}


