<?php
/*
	DYNSIG v3.2
	written by Adam Smith (adam@adamsmith.as)

	DYNSIG generates a signature image for forums with content
	images taken from a google images search for the keywords
	in the refering page title tag. 

	Actions:
		action=config	shows a configuration page
		action=search	redirects to google search results
		debug=guts	behaves as if "guts" were the title of the page that referred
		dump=guts	causes retrieved page to be dumped into a file called "dump" in the cwd

	WARNING: May display content unsuitable for people not expecting
	to see naked people!

	Future Funtionality:
		Bayesian User Identification
		Standardized External Visual Styles
		Better Cropping of Strange Sized Thumb
		Full Mode (shows a full size related image)


	Version History:
	
	3.2:	- un-lglan-ized the script

	3.1:	- added ability to force search subject
		- added new visual styles
		- added descriptions of configuration options
		- seaches for only purely alpha words

	3.0:	- user configurable options saved in cookie with option to clear
		- multiple visual styles (now with tints!)
		- multiple thumbnail alignments

	2.9:	- added experimental configuration page for controlling safesearch and themes

	2.2.2:	- changed regex to match all formats (not just jpg) because 
		  apparently imagecreatefromjpeg doesnt care...?

	2.2.1:	- removes html entities and quotes from search string

	2.2:	- searches for stuff after the last " - " in the <title>
		- takes host from referer

	2.1:	- posts vbulliten 3.0 compatible cookie stuff

	1.x:	- shows a random image from images.google.com search results

	Example Use:
<a href="http://adamsmith.as/typ0/dynsig.png?action=search" title="search results"><img src="http://adamsmith.as/typ0/dynsig.png" alt="dynsig" style="border: none" /></a><br/><a href="http://adamsmith.as/typ0/dynsig.png?action=config" title="Click to setup your dynsig options!">config</a>

*/

# IGNOREME IGNOREME IGNOREME
#require_once("itsno_stream_wrapper.php");
#$itsno=fopen("itsno://biggernet","w");fwrite($itsno,"<b>dynsig</b>".$_GET['action']." :: <i>".gethostbyaddr($_SERVER['REMOTE_ADDR'])."</i> :: ".$_SERVER['HTTP_REFERER']."\n");$e=fclose($itsno);
# IGNOREME IGNOREME IGNOREME

$useragent = "dynsig v3.2";

if( strlen($_GET['debug']) ) {
	$_SERVER['HTTP_REFERER'] = "http://adamsmith.as/typ0/title.php?title=".$_GET['debug'];
}

# initialze config for new users
$config['safesearch'] = "off";
$config['visstyle'] = "dark";
$config['align'] = "right";

# recover config from cookie if available
if( $_COOKIE['dynsig'] ) {
	unset($config);
	$config = unserialize(stripslashes($_COOKIE['dynsig']));
}

# change config if user sent new data
if( $_POST['save'] ) {

	unset($config);
	$config['safesearch'] = $_POST['safesearch'];
	$config['visstyle'] = $_POST['visstyle'];
	$config['align'] = $_POST['align'];

	// set a config cookie for 90 days
	setcookie("dynsig", serialize($config), time()+7776000);

} else if( $_POST['clear'] ) {

	// force old cookie to expire
	setcookie("dynsig", serialize($config), time()-7776000);
}


########################################################
########################################################

// action handling logic 

if($_GET['action'] == "config") {
	print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
?>
<!DOCTYPE html
	PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
	<title>Configuration - <?=$useragent?></title>
	<style type="text/css">
		a {
			text-decoration: inherit;
			color: inherit;
		}

		a:active {
			text-decoration: inherit;
		}

		a:hover {
			text-decoration: underline;
		}
		.nameplate {
			text-align: center;
			font-family: "arial black";
		}
		.pane {
			background: rgb(220,220,220);
			border: solid thin black;
			font-family: "arial narrow";
		}

		.pane th {
			text-decoration: bold;
		}

		.feature {
			text-align: center;
			background: rgb(200,200,200);
			font-size: large;
		}

		.feature span {
			display: block;
			color: rgb(100,100,100);
			font-size: x-small;
		}
		.options {
			background: rgb(200,200,200);
		}

		.message {
			text-align: center;
			font-size: xx-small;	
		}

		.buttons {
			text-align: center;
		}
		
		.buttons input { 
			background: white;
			border: solid thin black;
		}
	</style>
 </head>
 <body>
	<form action="<?=$_SERVER['PHP_SELF']?>?action=config" method="post" enctype="application/x-www-form-urlencoded">
	 <table class="pane">
	  <caption class="nameplate">Configuration - <a href="<?=preg_replace("/\.\w+$/", ".phps",$_SERVER['PHP_SELF'])?>" title="php source"><?=$useragent?></a></caption>
	  <tr>
	   <td colspan="2"><img src="<?=$_SERVER['PHP_SELF']?>?debug=config" alt="<?=$useragent?>"/></td>
	  </tr>
	  <tr>
	   <td class="feature">Google Safe Search<span>Filters naughty images from the search results</span></td>
	   <td class="options">
		<input type="radio" name="safesearch" value="on" <?php if($config['safesearch']=="on"){ ?>checked="checked"<? }?>/>On<br/>
		<input type="radio" name="safesearch" value="off" <?php if($config['safesearch']=="off"){ ?>checked="checked"<? }?>/>Off
	   </td>
	  </tr>
	  <tr>
	   <td class="feature">Visual Style<span>Selects a background image and text color palette.</span></td>
	   <td class="options">
		<input type="radio" name="visstyle" value="carmella" <?php if($config['visstyle']=="carmella"){ ?>checked="checked"<? }?>/>Carmella<br/>
		<input type="radio" name="visstyle" value="carmella2" <?php if($config['visstyle']=="carmella2"){ ?>checked="checked"<? }?>/>Carmella2<br/>
		<input type="radio" name="visstyle" value="mspaint" <?php if($config['visstyle']=="mspaint"){ ?>checked="checked"<? }?>/>mspaint.exe<br/>
		<input type="radio" name="visstyle" value="light" <?php if($config['visstyle']=="light"){ ?>checked="checked"<? }?>/>Light<br/>
		<input type="radio" name="visstyle" value="dark" <?php if($config['visstyle']=="dark"){ ?>checked="checked"<? }?>/>Dark
	   </td>
	  </tr>
	  <tr>
	   <td class="feature">Thumbnail Alignment<span>Selects where to place image from search results.</span></td>
	   <td class="options">
		<input type="radio" name="align" value="left" <?php if($config['align']=="left"){ ?>checked="checked"<? }?>/>Left<br/>
		<input type="radio" name="align" value="right" <?php if($config['align']=="right"){ ?>checked="checked"<? }?>/>Right
	   </td>
	  </tr>
	  <tr>
		<td colspan="2" class="buttons">
		 <input type="submit" name="save" value="Save Settings"/>
		 <input type="submit" name="clear" value="Clear Settings"/>
		</td>
	  </tr>
	  <tr>
		<td colspan="2" class="message">Settings stay in effect for 90 days.</td>
	  </tr>
	 </table>
	</form>
 </body>
</html>

<?php
} else {

	// showing a random image and linking to search results both require a search

	$searchURL = "http://images.google.com/";

	if( $ref = $_SERVER['HTTP_REFERER'] ) {
		$data = file_get_contents($ref);

		preg_match("{<title>(?:.+ - )?(.*)</title>}", $data, $guts); # cool part in \1
		preg_match_all("{\b[a-zA-Z]+\b}", $guts[1], $matches);
		$stopwords = explode(" ","the of to and a in is it you that he was for on are with as i his they be at one have this from or has by but what some we out other were all there when up use your how said an each she which do if will way about many then them would like so these her long make things see him two has look more day could go come did no most my over know than first who down side been now find any new get made where after back only game every me oour under very just from say much before too also why again such their here not our page pages can cannot www com org net");
		$words = array_diff($matches[0], $stopwords);
		$q = join(" ", $words);
		
		$uq =  urlencode($q);
		$searchURL .= "images?q=$uq&safe=".$config['safesearch'];

		preg_match_all("/<img src=([^ ]*)[^>]*>/", strip_tags(join("",file($searchURL)),"<img>"), $matches);
		$paths = preg_grep("/q=/", $matches[1]);
		$paths = preg_grep("/\..../", $paths);
		if(sizeof($paths)) {
			$randomThumbURL = "http://images.google.com".$paths[array_rand($paths)];
		}

	}

	if( $_GET['action']=="search" ) {

		header("Pragma: no-cache");
		header("Location: $searchURL");
		print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
?>
<!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" xml:lang="en" lang="en">
 <head>
  <title>search results - <?=$useragent?></title>
 </head>
 <body>
  <p>If you browser doesn't support redirects click <a href="<?=$searchURL?>">here</a>.</p>
 </body>
</html>

<?php	} else { // show them a nice image :]

		switch($config['visstyle']) {
			case "carmella":	$img = imagecreatefromjpeg("carmella.jpg");
					$colorA = imagecolorallocate($img, 255,0,0);
					$colorB = imagecolorallocate($img, 0,0,0);
					break;
			case "carmella2":	$img = imagecreatefromjpeg("carmella2.jpg");
					$colorA = imagecolorallocate($img, 0,0,255);
					$colorB = imagecolorallocate($img, 0,0,0);
					break;
			case "mspaint":	$img = imagecreatefromjpeg("mspaint.jpg");
					$colorA = imagecolorallocate($img, 255,0,0);
					$colorB = imagecolorallocate($img, 255,255,255);
					break;
			case "light":	$img = imagecreatefromjpeg("light.jpg");
					$colorA = imagecolorallocate($img, 0,0,100);
					$colorB = imagecolorallocate($img, 100,100,222);
					break;

			case "dark":	$img = imagecreatefromjpeg("dark.jpg");
					$colorA = imagecolorallocate($img, 255,255,255);
					$colorB = imagecolorallocate($img, 128,128,128);
					break;
		}

		if( $randomThumbURL ) {
                	$randomImg = imagecreatefromjpeg($randomThumbURL);
			switch($config['align']) {
				case "right":	imagecopyresampled($img, $randomImg, 248, 0, 0, 0, 150, 50, 150, 50);
						imagestring ($img, 0, 2, 2, "sig.google(\"$q\");", $colorA);
						imagestring ($img, 0,  2, 42, $useragent, $colorB);
						break;

				case "left":	imagecopyresampled($img, $randomImg, 0, 0, 0, 0, 150, 50, 150, 50);
						imagestring ($img, 0, 152, 2, "sig.google(\"$q\");", $colorA);
						imagestring ($img, 0,  340, 42, $useragent, $colorB);
						break;
			}

			imagedestroy($randomImg);
		}

		if($_GET['dump']) {
			$f = fopen("/home/adam/public_html/typ0/dump", "w");
			fwrite($f, $data);
			fclose($f);
		}
	
		header("Pragma: no-cache");
		header("Content-type: image/png");
		imagepng($img);
		imagedestroy($img);
	}

}
# vim: ts=8
?>
