<?php
/*
This is the include file for the website and includes functions used by other programs.
*/

require "/home/hpr/php/credentials.php";

$pos = strpos($_SERVER['REQUEST_URI'], '/', 1 );
if ( ! $pos === false) {
  $pos = strpos($_SERVER['REQUEST_URI'], '/cms/', 1 );
  if ( ! $pos === false) {
    http_response_code(404);
    mysqli_close();
    exit;
  }
}

date_default_timezone_set("UTC"); 



if (!($connection = @ mysqli_connect("$databaseHostName", "$databaseUsername", "$databasePassword")))
die("Could not connect to database");

if (!mysqli_select_db($connection, "$databaseName")) {
    error_log($msg, 3, "/home/site/logs/sql_error_log");
    return "Requested page is temporarily unavailable, please try again later.";
}

$connection->set_charset('utf8');

function rrmdir($src) {
  $dir = opendir($src);
  while(false !== ( $file = readdir($dir)) ) {
    if (( $file != '.' ) && ( $file != '..' )) {
      $full = $src . '/' . $file;
      if ( is_dir($full) ) {
        rrmdir($full);
      }
      else {
        unlink($full);
      }
    }
  }
  closedir($dir);
  rmdir($src);
}

function call412($error){
  usleep(rand(10000000,30000000));
	global $HPR_Name, $HPR_Names, $naughtyfile;
	header("Status: 412 Precondition Failed");
	print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>'.$HPR_Name.' Public Radio</title>
</head>
<body>
<h1>412 Precondition Failed</h1>
<h2>ERROR CODE</h2>
<p>
<strong>'.$error.'</strong>
</p>
<p>
If you believe this to be an error, then please copy this error code and send it to admin@hpr.
</p>
<p>
<small>'.date('Y-m-d\TH:i:s') . "\t" . getUserIP() . "\t" . $_SERVER["HTTP_USER_AGENT"] .'</small>
</p>
<!-- 
If however you are checking out how our site works then 
please record a show telling us about what you were 
trying to do.

We are always looking for help from the community and 
over the years many hackers have helped us improve the site.
${baseurl}contribute.html

Thanks.
-->
</body>
</html>';
	file_put_contents($naughtyfile, date('Y-m-d\TH:i:s\Z') . "\t" . getUserIPAdress() ."\t" . $error . "\t" . $_SERVER['REQUEST_URI'] . "\t" . $_SERVER["HTTP_USER_AGENT"] . "\n", FILE_APPEND | LOCK_EX );
	exit;
}


function problem($error){
  global $HPR_Name, $HPR_Names, $naughtyfile;
	file_put_contents($naughtyfile, date('Y-m-d\TH:i:s\Z') . "\t" . getUserIPAdress() ."\tERROR: " . $error . "\t" . $_SERVER['REQUEST_URI'] . "\t" . $_SERVER["HTTP_USER_AGENT"] . "\n", FILE_APPEND | LOCK_EX );
  #usleep(2000000);
  header("Status: 412 Precondition Failed");
  print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>'.$HPR_Name.' Public Radio</title>
</head>
<body>
<h1>412 Precondition Failed</h1>
<h2>ERROR CODE</h2>
<p>
<strong>'.$error.'</strong>
</p>
<p>
If you believe this to be an error, then please copy this error code and send it to admin@hpr.
</p>
<p>
<small>'.date('Y-m-d\TH:i:s') . "\t" . getUserIP() . "\t" . $_SERVER["HTTP_USER_AGENT"] .'</small>
</p>
<!-- 
If however you are checking out how our site works then 
please record a show telling us about what you were 
trying to do.

We are always looking for help from the community and 
over the years many hackers have helped us improve the site.
${baseurl}contribute.html

Thanks.
-->
</body>
</html>';
	exit;
}

function naughty($error){
  global $HPR_Name, $HPR_Names, $naughtyfile;
	file_put_contents($naughtyfile, date('Y-m-d\TH:i:s\Z') . "\t" . getUserIPAdress() ."\t" . $error . "\t" . $_SERVER['REQUEST_URI'] . "\t" . $_SERVER["HTTP_USER_AGENT"] . "\n", FILE_APPEND | LOCK_EX );
  #usleep(rand(10000000,30000000));
  header("Status: 412 Precondition Failed");
  print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>'.$HPR_Name.' Public Radio</title>
</head>
<body>
<h1>412 Precondition Failed</h1>
<h2>ERROR CODE</h2>
<p>
<strong>'.$error.'</strong>
</p>
<p>
If you believe this to be an error, then please copy this error code and send it to admin@hpr.
</p>
<p>
<small>'.date('Y-m-d\TH:i:s') . "\t" . getUserIP() . "\t" . $_SERVER["HTTP_USER_AGENT"] .'</small>
</p>
<!-- 
If however you are checking out how our site works then 
please record a show telling us about what you were 
trying to do.

We are always looking for help from the community and 
over the years many hackers have helped us improve the site.
${baseurl}contribute.html

Thanks.
-->
</body>
</html>';
	exit;
}

function logextra($message){
    global $HPR_Name, $HPR_Names, $naughtyfile;
	file_put_contents($naughtyfile, date('Y-m-d\TH:i:s\Z') . "\t" . getUserIPAdress() ."\t" . $message . "\t" . $_SERVER['REQUEST_URI'] . "\t" . $_SERVER["HTTP_USER_AGENT"] . "\n", FILE_APPEND | LOCK_EX );
}

function convertSecToTime($sec){
	$date1 = new DateTime("@0"); //starting seconds
	$date2 = new DateTime("@$sec"); // ending seconds
	$interval =  date_diff($date1, $date2); //the time difference
	return $interval->format('%y Years, %m months, %d days, %h hours, %i minutes and %s seconds'); // convert into Years, Months, Days, Hours, Minutes and Seconds
}

function fixid($id){
    return sprintf('%04d',$id);
}

function navtext($id,$curr_ep_id){
    if ( $id <= 1 ) {
        echo "&lt;&lt; First, &lt; Previous, ";
    }
    else {
        echo "<a href=\"".$_SERVER['PHP_SELF']."?id=0001\" rel=\"first\">&lt;&lt; First, </a>";
        echo "<a href=\"".$_SERVER['PHP_SELF']."?id=" . (fixid($id-1)) . "\" rel=\"previous\">&lt; Previous, </a>";
    }
    if ( $id >= $curr_ep_id ) {
        echo "Next &gt;, ";
        echo "Latest &gt;&gt;";
    }
    else {
        echo "<a href=\"".$_SERVER['PHP_SELF']."?id=".(fixid($id+1))."\" rel=\"next\">Next &gt;, </a> ";
        echo "<a href=\"".$_SERVER['PHP_SELF']."?id=$curr_ep_id\" rel=\"last\">Latest &gt;&gt;</a>";
    }
}

function formatemail($email) {
    // Miminal spam protection 
  if (!stristr($email, '.nospam@nospam.')){
    $part = explode("@", $email);
    $email = $part[0] . ".nospam@nospam." . $part[1];
  }
  return $email;
}

function unformatemail($email) {
  // Miminal spam protection 
  if (stristr($email, '.nospam@nospam.')){
    $part = explode(".nospam@nospam.", $email);
    $email = $part[0] . "@" . $part[1];
  }
  return $email;
}

function makeClickableLinks($string) {
    # Used to display links from test urls 
    $pattern = '/\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))/i';
    $replacement = '<a href="$1" target="_blank">$1</a>';
    return preg_replace($pattern, $replacement, $string);
}

function get_gravatar( $email, $s = 80, $d = '404', $r = 'x', $img = false, $atts = array() ) {
    /**
    * Get either a Gravatar URL or complete image tag for a specified email address.
    *
    * @param string $email The email address
    * @param string $s Size in pixels, defaults to 80px [ 1 - 512 ]
    * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
    * @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
    * @param boole $img True to return a complete IMG tag False for just the URL
    * @param array $atts Optional, additional key/value attributes to include in the IMG tag
    * @return String containing either just a URL or a complete image tag
    * @source http://gravatar.com/site/implement/images/php/
    */
    $url = 'https://secure.gravatar.com/avatar/';
    $url .= md5( strtolower( trim( $email ) ) );
    $url .= "?s=${s}&d=${d}.png";
    if ( $img ) {
        $url = '<img src="' . $url . '"';
        foreach ( $atts as $key => $val )
            $url .= ' ' . $key . '="' . $val . '"';
            $url .= '.png />';
    }
    return $url;
}

function getUserIPAdress() {
	$ip = '';
	if (getenv('HTTP_CLIENT_IP')) {
		$ip = getenv('HTTP_CLIENT_IP');
	}
	else if(getenv('HTTP_X_FORWARDED_FOR')) {
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	}
	else if(getenv('HTTP_X_FORWARDED')) {
		$ip = getenv('HTTP_X_FORWARDED');
	}
	else if(getenv('HTTP_FORWARDED_FOR')) {
		$ip = getenv('HTTP_FORWARDED_FOR');
	}
	else if(getenv('HTTP_FORWARDED')) {
		$ip = getenv('HTTP_FORWARDED');
	}
	else if(getenv('REMOTE_ADDR')) {
		$ip = getenv('REMOTE_ADDR');
	}
	else {
		$ip = 'UNKNOWN';
	}
	return $ip;
}

function getUserIP()
{
    //check ip from share internet
    if (!empty($_SERVER['HTTP_CLIENT_IP']))
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip . "\t" . $_SERVER['REQUEST_URI'] . "\t" . $_SERVER["HTTP_USER_AGENT"] . "\n";
}
$naughtyfile = '/home/hpr/logs/naughty-ip.txt';
# Read more: http://vidiame.com/php/how-to-block-multiple-ip-addresses-using-php

if ( strlen($_SERVER['QUERY_STRING']) > 15 ) {
  file_put_contents($naughtyfile, getUserIP(), FILE_APPEND | LOCK_EX );
}

function GetFirstFreeSlot() {
    // --------------------------------------------
    // Get first free slot
    $query = mysqli_query("SELECT  id + 1 FROM eps mo
    WHERE   NOT EXISTS
            (
            SELECT  NULL
            FROM    eps mi 
            WHERE   mi.id = mo.id + 1
            )
    ORDER BY
            id
    LIMIT 1");
    $next_show_num_array = mysqli_fetch_row($query);
    return $next_show_num_array[0];
}

function GetLatestPublishedShow($connection){
  // --------------------------------------------
  // Get latest published show
  $query = mysqli_query($connection, "SELECT max(date), max(id) from eps WHERE eps.date <= UTC_DATE()");
  $current_episode_array = mysqli_fetch_row($query);
  return array($current_episode_array[0], $current_episode_array[1]);
}

$PROTOCOL = '';
if ((!empty($_SERVER['HTTPS'])) && ($_SERVER['HTTPS'] !== 'off')) {
  $PROTOCOL .= 'https://';
} else {
  $PROTOCOL .= 'http://';
}

$HTTP_HOST = $_SERVER['HTTP_HOST'];
$pos = strpos($HTTP_HOST, "hobbypublicradio");
if ($pos !== false) {
    $HPR_Name = "Hobby";
    $HPR_Names = "hobbyists";
} else {
    $HPR_Name = "Hacker";
    $HPR_Names = "Hackers";
}

?>