<?php

$domain 
"http://example.com/";            // root URL for your site
$images "http://example.com/comics/";    // root URL for the comic images

$con mysql_connect('host','user','pass') or die('MySQL Connection Error');
mysql_select_db('your_comic_db');

date_default_timezone_set('America/Chicago');
$now date("Y-m-d H:i:s",$_SERVER['REQUEST_TIME']);

class 
comic {     // class that sets most of the variables for the comics

    // prepares a bunch of variables to be set in the class
    
public $title$image$ID$info$type$author$datetime$last$first$next$prev$show_author$views;
    
public $is_index false;
    
public $has_author false;
    
public $has_ID false;
    
    
public function __construct($type=false,$ID=0,$author=false) { // this function runs when the class is called
    
        
global $domain$now;
        
        if(!
$type && !$ID && !$author$this->is_index true;
        
        
$default_type "comics"// if no type is declared this one will be used
        
if(strlen($type) > 0$tables explode(" ",mysql_real_escape_string(strip_tags($type)));
        else 
$tables $default_type;
        
$size count($tables);
        
        if(
$author) { 
            
$auth_query " && `author` = '" mysql_real_escape_string(strip_tags($author)) . "'";
            
$this->has_author true;
        }
        
        if(
intval($ID) > 0) {
            
$ID_query " && `ID` = " $ID;
            
$this->has_ID true;
        }
        
        
$num 1;
        
$sql "SELECT * FROM `$tables[0]` WHERE `Time` <= '$now'" $auth_query $ID_query;
        while(
$size $num) { // if multiple types are set, loop through to query each table
            
$sql .= " UNION SELECT * FROM `$tables[$num]` WHERE `Time` <= '$now'" $auth_query $ID_query;
            ++
$num;
        }
        
$sql .= " ORDER BY `Time` DESC LIMIT 1"
        
        
$query mysql_query($sql);
        
$rows = @mysql_num_rows($query); 
        if(
$rows == && !$this->has_author) {
            
$query mysql_query("SELECT * FROM `{$default_type}` ORDER BY `ID` DESC LIMIT 1");
            
$this->has_author false;
            
$this->has_ID false;
        }
        elseif(
$rows == && $this->has_author) {
            
header("Location: ".$domain.$author."/");
            exit;
        }
        
$row mysql_fetch_assoc($query);
        
        
$this->title    $row['Title'];
        
$this->image    $row['Image'];
        
$this->ID        = (int) $row['ID'];
        
$this->info        $row['alt'];
        
$this->type        $row['type'];
        
$this->author    ucfirst($row['author']);
        
$this->datetime    $row['Time'];
        
$this->views    = (int) $row['views'] + 1;
        
        
// finds the first and last comics in the DB 
        
$IDfirst mysql_fetch_row(mysql_query("SELECT `ID` FROM `{$this->type}` WHERE 1=1" $auth_query " ORDER BY `ID` ASC LIMIT 1;"));
        
$IDlast mysql_fetch_row(mysql_query("SELECT `ID` FROM `{$this->type}` WHERE 1=1" $auth_query " ORDER BY `ID` DESC LIMIT 1;"));
        
$this->first = (int) $IDfirst[0];
        
$this->last = (int) $IDlast[0];
        
        if(
$_GET['random'] == 1$this->random(); // redirects to a random comic
        
        // finds the previous and next comic(s) assuming it's not the first or last in the DB
        
if($this->ID != $this->first$IDprev mysql_fetch_row(mysql_query("SELECT `ID` FROM `{$this->type}` WHERE `ID` < " $this->ID $auth_query " ORDER BY `ID` DESC LIMIT 1"));
        if(
$this->ID != $this->last$IDnext mysql_fetch_row(mysql_query("SELECT `ID` FROM `{$this->type}` WHERE `ID` > " $this->ID $auth_query " ORDER BY `ID` ASC LIMIT 1"));
        
$this->next = (int) $IDnext[0];
        
$this->prev = (int) $IDprev[0];

        
$updateviews "UPDATE `{$this->type}` SET `views` = {$this->views} WHERE `ID` = '{$this->ID}' LIMIT 1";
        if(!
mysql_query($updateviews)) echo 'Failed to update views ... sigh';
    
    }
    
    
public function get_link($args='') { // comic link (eg. http://domain.com/###/ where ### = the ID)
        
global $domain;
        
$link $domain $this->not_default() . $this->ID '/' $args;
        return 
$link;
    }
    
    
public function get_image() { // comic image link (eg. http://domain.com/images/TYPE/IMAGE.jpg)
        
global $images;
        
$image $images $this->type '/' $this->image;
        return 
$image;
    }
    
    
public function link_image($args=false,$width=false,$target=false) { 
        
// creates the image+link html (eg. <a href="http://domain.com/###/$args" title="COMIC TITLE"><img src="http://domain.com/images/TYPE/IMAGE.jpg" alt="COMIC TITLE" width="$width"/></a>) if $target = "blank" the link opens in a new window
        
global $domain$images;
        if(
$width && is_numeric($width)) $width2 ' width="'.$width.'px"';
        if(
$target == 'blank'$target ' target="_blank"';
        
$link '<a href="' $this->get_link($args) . '" title="' $this->info '"' $target '><img src="' $this->get_image() . '" alt="' $this->title '"' $width2 '/></a>';
        return 
$link;
    }
    
    
public function get_date($format) { // returns formatted date from a date/time stamp
        
$datetime explode(" ",$this->datetime);
        
$dateA explode("-",$datetime[0]);
        
$timeA explode(":",$datetime[1]);
        return 
date($format,mktime($timeA[0],$timeA[1],$timeA[2],$dateA[1],$dateA[2],$dateA[0]));
}
    
    
public function author_text() { // displays this text if you're browsing comics by author
        
if($this->has_author === true) {
            
$authtext '<p style="text-align:center;color:#999;font-style:italic;">You&#39;re Browsing All of <strong><u>' $this->author '&#8217;s</u></strong> ' ucfirst($this->type) . '! <small style="vertical-align:top;"><a href="' $this->get_link() . '" title="quit browsing by author">[X]</a></small></p>';
            return 
$authtext;
        }
    }
    
    
public function show_author() { // returns the author if it's been set when the class was called
        
if($this->has_author === true) {
            return 
$this->author '/';
        }
    }
    
    
public function has_ID() { // if an ID was passed to the main function
        
if($this->has_ID === true) return true;
        else return 
false;
    }
        
    
public function not_default($type=false) { // only shows the type in the URL if it's not a 'comic'
        
if($type && $type != 'comics') return $type "/";
        elseif(!
$type && $this->type != 'comics') return $this->type "/";
        else return 
false;
    }
    
    
public function is_index() { // returns TRUE if no values were passed to the main __construct function
        
if($this->is_index === true) return true;
        else return 
false;
    }
    
    
private function random() {
        global 
$domain;
        
$rand rand($this->first,$this->last);
        
$regex "#^".$domain.$this->not_default()."(\d+)/#";
        if(
preg_match($regex,$_SERVER['HTTP_REFERER'],$ref) && $ref[1] == $rand$rand rand($this->first,$this->last);
        
header("Location: " $domain $this->not_default() . $rand "/#comic");
        exit;
    }
    
    
public function author_full() {
        
$fullname "Guy Kopsombut";
        if(
$this->author == 'Josh'$fullname "Josh Clayton";
        return 
$fullname;
    }
    
    
public function views() {
        return 
$this->views " Views";
    }

// end class 'comic'


class comments {

    
private $query;
    
public $num$message$type$ID;

    
public function __construct($type,$ID) {
    
        if(isset(
$_POST['submit'])) $this->post_comment($type);
                    
        
$this->query mysql_query("SELECT * FROM `comm_{$type}` WHERE `comicID` = '$ID' ORDER BY `ID` ASC");

        
$this->num = (int) @mysql_num_rows($this->query);
        
        
$this->type $type;
        
$this->ID = (int) $ID;
    
    }
    
    
private function post_comment($type) { //
        
global $domain$images$now;
        
$table "comm_".$type;
        if(
strlen($_POST['comment']) > 1000) {
            
$message "<br /><font size='+1'>Sorry, your message was WAY too long!<br /><smaller>(1000 character max)</smaller></font><br /><br />";
            
$error 1;
        }
        else {
        if((
$_SESSION['security_code'] == $_POST['security_code']) && !empty($_SESSION['security_code']) && is_numeric($_POST['comicID'])) {
        
// Insert you code for processing the form here
        
unset($_SESSION['security_code']);
        
        
$next_ID mysql_fetch_row(mysql_query("SELECT `ID` FROM `{$table}` WHERE `comicID` = '$_POST[comicID]' ORDER BY `ID` DESC LIMIT 1"));
        
$next_ID $next_ID[0] + 1;
        
        
$cookie_domain "." str_replace(array("http://","https://"),"",$domain);
        
        
$website urltest($_POST['website']);
        if(
$website !== 0setcookie("TSL_website",$_POST['website'],$_SERVER['REQUEST_TIME']+60*60*24*365,"/",$cookie_domain);
        
        
$name safe_text($_POST['name'],'','mysql',30);
        
setcookie("TSL_name",$name,$_SERVER['REQUEST_TIME']+60*60*24*365,"/",$cookie_domain);
        
        
$comment url2awesomesafe_text($_POST['comment'],'','mysql') );
        
        
$sql="INSERT INTO `{$table}` (comicID, name, comment, datetime, ID, website) VALUES ('$_POST[comicID]','$name','$comment','$now','$next_ID','$website')";
        if(!
mysql_query($sql)) die('Error: '.mysql_error());
        
        
$body "<strong><em>" $name "</strong></em> left a comment on the comic ---> <strong><em>" $_POST['title'] . "</strong></em> <br /><br />This is what <strong><em>" $name "</strong></em> had to say:<br /><br /><em><font size='+1'><blockquote>" $comment "</blockquote></font></em><br /><br /><a href='" $domain not_default($type) . $_POST['comicID'] . "/#comment-" $next_ID "'><img src='" $images $type "/thumbs/comm/" $_POST['image'] . "' alt='" $_POST['title'] . "' width='300px'></img></a><br />(Click on the image to go straight to the comment)";
        
mailer($name." has left a comment on a comic!",$body);
        
        
$message "<br /><font size='+1'><em>Thanks for the comment!</em></font><br /><br />";
        
$error 0;
        }
        else { 
// Insert your code for showing an error message here
            
$message "<br /><font size='+3' color='red'>f (_) c |(  u n00b.<br /><br /><br />Sp@m i$ 4 D4 l0s3rs</font><br /><br />";
            
$error 1;
        }
        }
        
$this->message $message;
    }
    
    
public function num_comments($zero=false,$one=false,$more=false) { // returns number of comments in a special format
        
if($zero && $one && $more) { // returns, if format is specified
            
if($this->num === 0$return $zero;
            elseif(
$this->num === 1$return $one;
            else 
$return str_replace('%',$this->num,$more);
        }
        else { 
// otherwise, returns default format
            
if($this->num === 0$return "No Comments Yet";
            elseif(
$this->num === 1$return "1 Comment";
            else 
$return $this->num " Comments";
        }
        return 
$return;
    }
    
    
public function get_comments() {
        if(
$this-num 0) return mysql_fetch_assoc($this->query);
        else return 
false;    
    }
    
    
public function last_ID() { // returns the last comment ID for the given comicID
        
while($row $this->get_comments()) {
            
$last $row['ID'];
        }
        return 
$last;
    }

}

function 
get_date($format,$stamp) { // returns formatted date from a date/time stamp
    
if($format) {
        
$datetime explode(" ",$stamp);
        
$dateA explode("-",$datetime[0]);
        
$timeA explode(":",$datetime[1]);
        return 
date($format,mktime($timeA[0],$timeA[1],$timeA[2],$dateA[1],$dateA[2],$dateA[0]));
    }
    else return 
false;
}

function 
replace_smilies($input,$d=0) { // takes input and replaces smilies with emoticons
    
global $domain;
    
$folder "img/smilies/";
    if(
$d$folder $domain $folder;
    
$trans = array(
        
":arrow:"=>"<img src='{$folder}icon_arrow.gif' title='arrow' alt=':arrow:' />",
        
":D"=>"<img src='{$folder}icon_biggrin.gif' title='Big Grin' alt=':D' />",
        
":-?"=>"<img src='{$folder}icon_confused.gif' title='confused' alt=':?' />",
        
"8-)"=>"<img src='{$folder}icon_cool.gif' title='cool' alt='8-)' />",
        
":'("=>"<img src='{$folder}icon_cry.gif' title='cry' alt=':&#39;(' />",
        
":&#39;("=>"<img src='{$folder}icon_cry.gif' title='cry' alt=':&#39;(' />",
        
"o.O"=>"<img src='{$folder}icon_eek.gif' title='eek' alt='o.O' />",
        
">:["=>"<img src='{$folder}icon_evil.gif' title='evil' alt='>:[' />",
        
":!:"=>"<img src='{$folder}icon_exclaim.gif' title='exclaim' alt=':!:' />",
        
":idea:"=>"<img src='{$folder}icon_idea.gif' title='idea' alt=':idea:' />",
        
"LOL"=>"<img src='{$folder}icon_lol.gif' title='LOL' alt='LOL' />",
        
":x"=>"<img src='{$folder}icon_mad.gif' title='mad' alt=':x' />",
        
":mrgreen:"=>"<img src='{$folder}icon_mrgreen.gif' title='Mr. Green' alt=':mrgreen:' />",
        
":-/"=>"<img src='{$folder}icon_neutral.gif' title='neutral' alt=':-/' />",
        
":?:"=>"<img src='{$folder}icon_question.gif' title='question' alt='???' />",
        
":P"=>"<img src='{$folder}icon_razz.gif' title='razz' alt=':P' />",
        
":oops:"=>"<img src='{$folder}icon_redface.gif' title='redface' alt=':oops:' />",
        
":roll:"=>"<img src='{$folder}icon_rolleyes.gif' title='roll eyes' alt=':roll:' />",
        
":("=>"<img src='{$folder}icon_sad.gif' title='sad' alt=':(' />",
        
":)"=>"<img src='{$folder}icon_smile.gif' title='smile' alt=':)' />",
        
":O"=>"<img src='{$folder}icon_surprised.gif' title='surprised' alt=':O' />",
        
">:]"=>"<img src='{$folder}icon_twisted.gif' title='twisted' alt='>:]' />",
        
";)"=>"<img src='{$folder}icon_wink.gif' title='wink' alt=';)' />"
        
);
    return 
strtr($input,$trans);
}

function 
safe_text($text,$html='',$escape='',$length=0) { // makes user input "safe" for the MySQL DB

    
$return trim($text);
    
$return strip_tags($return,'<strong><em><u>');
    
    if(
$html == 'nohtml'$return htmlentities($return,ENT_QUOTES);
    else {
        
$return str_replace(array(chr(39),chr(34),"<?","?>"),array("&#39;","&quot;","&lt;?","?&gt;"),$return);
        
$return strip_tags($return,"<strong><em><u>");    
    }
    
    if(
$escape == 'mysql'$return mysql_real_escape_string($return);
    elseif(
$escape == 'slashes'$return addslashes($return);
    
    if(
intval($length) > 0$return substr($return,0,intval($length));
    
    
$return nl2br($return);
    
    return 
$return;
    
}

function 
urltest($url) { // tests a URL to see if it's valid
    
$syntax "^(https?|ftp)\:\/\/([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*(\:[0-9]{2,5})?(\/([a-z0-9+\$_-]\.?)+)*\/?(\?[a-z+&\$_.-][a-z0-9;:@/&%=+\$_.-]*)?(#[a-z_.-][a-z0-9+\$_.-]*)?\$";
    if(
eregi($syntax,$url)) return $url
    else return 
0;
}

function 
url2awesome($string,$width=378) {
    
$syntax "(https?|ftp)\:\/\/([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*(\:[0-9]{2,5})?(\/([a-z0-9+\$_-]\.?)+)*\/?(\?[a-z+&\$_.-][a-z0-9;:@/&%=+\$_.-]*)?(#[a-z_.-][a-z0-9+\$_.-]*)?";
    if(
eregi($syntax,$string,$url)) { // if we found a valid URL
        
$url $url[0];
        
$ch=curl_init();
        
curl_setopt($ch,CURLOPT_URL,$url);
        
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2);
        
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        
curl_setopt($ch,CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
        
curl_exec($ch);
        
$info curl_getinfo($ch);
        
curl_close($ch);
        
$mime $info['content_type'];
        if(
$mime == 'image/jpeg' || $mime == 'image/gif' || $mime == 'image/png') {
            
// mime-type is an image, so show the image + link
            
$image '<a href="'.$url.'" target="_blank" rel="nofollow"><img src="'.$url.'" style="max-width:'.$width.'px" /></a>';
            
$string str_replace($url$image$string);
        }
        elseif(
$info['http_code'] != 404) { // if it's not an image just make it a link
            
$link '<a href="'.$url.'" target="_blank" rel="nofollow">'.$url.'</a>';
            
$string str_replace($url$link$string);
        }
    }
    return 
$string;
}

function 
mailer($subject,$message) {
    
$to "gjcomics@gmail.com";
    
$headers "From: TheSpiffyLife.com <josh@thespiffylife.com>\r\n";
    
$headers .= "MIME-Version: 1.0\r\n"
    
$headers .= "Content-type: text/html";
    
mail($to,$subject,$message,$headers);
}

function 
not_default($type) { // only shows the type in the URL if it's not a 'comic'
    
if($type != 'comics') return $type "/";
    else return 
false;
}
?>