<?php
/*
 * like.php
 * by Stewart Souter
 * email: webmaster@carbonize.co.uk
 * 
 * This scrupt is for the handling of the likes
 * Will add the like and the ip to the database and
 * write a cookie for additional remembering.
 */
 
// Lets grab the database info etc
define('LAZ_INCLUDE_PATH', dirname(__FILE__));
require_once LAZ_INCLUDE_PATH.'/admin/version.php';
require_once LAZ_INCLUDE_PATH.'/admin/config.inc.php';
require_once LAZ_INCLUDE_PATH.'/lib/mysql.class.php';
require_once LAZ_INCLUDE_PATH.'/lib/vars.class.php';
require_once LAZ_INCLUDE_PATH.'/lib/template.class.php';

// Set the prefix for the table names
define('LAZ_TABLE_PREFIX', $table_prefix);

// Get the guestbook settings
$db = new guestbook_vars(LAZ_INCLUDE_PATH);
$db->getVars();

$entry   = (!empty($_GET['entry'])) ? intval($_GET['entry']) : '';
$backUrl = (preg_match('/\?/',$this->db->VARS['laz_url'])) ? '&entry=' . $entry : '?entry=' . $entry;
$backUrl = (!empty($entry)) ? $this->db->VARS['laz_url'] . $backUrl : $this->db->VARS['laz_url'];

$likedID = (!empty($_GET['like'])) ? intval($_GET['like']) : 0;

if(!empty($_COOKIE['liked']))
{
  $cookieLikes = explode(',', $_COOKIE['liked']);
}
else
{
  $cookieLikes[] = 0;
}

// Check that we have an id to like, the id is of a real post and that it has not already been liked by them.
if(($likedID == 0) || 
   (mysql_num_rows(mysql_query('SELECT id FROM ' . LAZ_TABLE_PREFIX . '_likes WHERE ip=`$userid` AND likeid=' . $likedID))) || 
   (in_array($likedID, $cookieLikes)) ||
   (!mysql_num_rows(mysql_query('SELECT id FROM ' . LAZ_TABLE_PREFIX . '_data WHERE id=' . $likedID)))
  )
{
  header('Location: ' . $backUrl);  // Return to the guestbook
}
else
{
  if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/',$_SERVER['HTTP_X_FORWARDED_FOR']) && !preg_match('/^(192\.168\.)|(127\.0\.0\.1)|(10\.)|(169\.((1[2-9])|(2[0-9])|(30)|(31))\.)/', $_SERVER['HTTP_X_FORWARDED_FOR']))
  {
    $theirIP = addslashes($_SERVER['HTTP_X_FORWARDED_FOR']);
  }
  else
  {
    $theirIP = addslashes($_SERVER['REMOTE_ADDR']);
  }
  
  if($sqlQuery = 'INSERT INTO ' . LAZ_TABLE_PREFIX . '_likes (ip,likedid,time) VALUES (\''. $theirIP . '\', \'' . $likedID  '\', \'' . time() . '\')')
  {
    $cookieValue = (!empty($_COOKIE['liked'])) ? $_COOKIE['liked'] . ',' . $likedID : $likedID;
    setcookie('liked', $cookieValue, '1609480740');
  }
  header('Location: ' . $backUrl);  // Return to the guestbook
}
?>
