<repo_name>steffmeister/phpircbot<file_sep>/module_klo.php
<?php

/* module_klo, a klo geh vs meetings counter */

function klo_init() {
	irc_bot_echo("init klo_module");
	klo_reset_counter();
	ircbot_register_for_global_listening( 'klo_listener_global' );
}

function klo_command( $string, $target='', $private=0 ) {
	irc_bot_echo("klo_command($string)");
	$user='';
	$input = explode(' ', $string);	
	$string=$input[0];
	switch ( $string ) {
		case 'reset':
			$user = isset($input[1]) ? $input[1] : 'all' ;
			klo_reset_counter($user);
			irc_send_message( "Zähler zurückgesetzt.", $target, $private );
			break;
		case 'show':
			$user = isset($input[1]) ? $input[1] : 'all' ;
			klo_print_stats($user, $target, $private );
			break;
		case 'k++':
		case 'klo+1':
			klo_increase_counter( 'k' , $target);
			klo_print_stats( 'all' , $target, $private );
			break;
		case 'm++':
		case 'mtg+1':
			klo_increase_counter( 'm' , $target);
			klo_print_stats( 'all', $target, $private );
			break;
		case 'help':
		case 'man':
		default:
			klo_print_help( $target, $private );
	}
}

/*
	interpret messages from chat and count klos or meetings
*/
function klo_listener_global( $sender, $msg ) {
	if ( preg_match( '/[kK]lo/', $msg ) ) {
		klo_increase_counter( 'k', $sender );
	}
	if ( preg_match( '/[mM]eeting/', $msg ) ) {
		klo_increase_counter( 'm', $sender );
	}
}

/*
	reset all individual counters
*/
function klo_reset_counter($user='all') {
	irc_bot_echo("reset all counters");
	
	if ($user === 'all') {
		foreach ( $GLOBALS['counter'] as $key => $value ) {
			foreach ( $value as $k => $v ) {
				$GLOBALS['counter'][$key][$k] = 0;
			}
		}
	} else {
		foreach ( $GLOBALS['counter'] as $key => $value ) {
			$GLOBALS['counter'][$key][$user] = 0;
		}
	}		
}

/*
	increase individual counter
*/
function klo_increase_counter( $what , $who ) {
	$GLOBALS['counter'][$what][$who]++;
}

/*
	print stats for all or for specific user
*/
function klo_print_stats( $user='all', $target='', $private=0 ) {
	irc_send_message( "Stats for $user:", $target, $private );
	
	if ( $user==='all' ) {
		$all_counts=array();
		// count all klos and meetings
		foreach ( $GLOBALS['counter'] as $key => $value ) {
			foreach ( $value as $k => $v ) {
				$all_counts[$key]+=$v;
			}
		}
		
		irc_send_message( "Klo ".$all_counts['k']." : ".$all_counts['m']." Meetings", $target, $private );
	}else {
		irc_send_message( "Klo ".$GLOBALS['counter']['k'][$user]." : ".$GLOBALS['counter']['m'][$user]." Meetings", $target, $private );
	}
}

/*
	print available commands
*/

function klo_print_help( $target='', $private=0 ) {
	$usage = array(
		"#wtf is it?",
		"Scans stream for \"klo\" or \"meeting\" and counts how much shit gets produced.",
		"#Commands:",
		"reset 			- reset ALL the counters",
		"show [user]	- show the current stats for [user]; default is 'all'",
		"klo+1,k++ 		- increase your klo count",
		"mtg+1,m++ 		- increase your meeting count",
		"help 			- show this message",
	);

	foreach ( $usage as $key => $value ) {
		irc_send_message( $value, $target, $private );
	}
}

?>
<file_sep>/module_numbergame.php
<?php

/* module_demo, some tests */

$current_game = array();

function numbergame_init() {
	irc_bot_echo("numbergame_init module");
	ircbot_register_command('ng', 'ng_custom');
	ircbot_register_for_global_listening('ng_listener_global');
}

function numbergame_command($string, $target='', $private=0) {
	irc_send_message('default command handler', $target, $private);
}

function ng_custom($string, $target='', $private=0) {
	global $current_game;
	switch($string) {
		case 'new':
			$current_game['running'] = 1;
			$current_game['number'] = rand(1, 10);
			//irc_send_message('nummer:'. $current_game['number'], $target, 0);
			irc_send_message('Los gehts! Erratet die Nummer, 1-10!'.$score, $sender, 0);
			irc_bot_echo("Nummer ist ".$current_game['number']);
			break;
		case 'stop':
			$current_game['running'] = 0;
			break;
		case 'reset':
			$current_game['scores'] = array();
			break;
		case 'scores':
			foreach($current_game['scores'] as $nick=>$score) {
				irc_send_message($nick.': '.$score, $sender, 0);
			}
			break;
	}
	
	//irc_send_message('registered command handler', $target, $private);
}

function ng_listener_global($sender, $msg) {
	global $current_game;
	if ($current_game['running']) {
		if (is_numeric($msg)) {
			if ($msg == $current_game['number']) {
				$current_game['running'] = 0;
				if (!isset($current_game['scores'][$sender])) {
					$current_game['scores'][$sender] = 0;
				}
				$current_game['scores'][$sender]++;
				irc_send_message($sender.' hat die richtige Nummer erraten: '.$current_game['number'].'!', $sender, 0);
				irc_bot_echo("Nummer erraten");
			}
		}
	}
}


?>
<file_sep>/module_pyload.php
<?php

/* module_pyload */

/* name of the python executable */
define('PYTHON', 'python2.5');
/* directory of pyload */
define('PYLOAD_PATH', '/share/MD0_DATA/.qpkg/pyload/');
/* my admin users */
define('MODULE_ADMINS', 'steffmeister');
/* temporary file - no need to change */
define('TEMP_FILE', 'ircpyload.tmp');

$module_admins = array();

$config_status = true;

function pyload_init() {
	global $module_admins, $config_status;
	echo "\npyload_init module\n";
	$config_status = true;
	if (!file_exists(PYLOAD_PATH.'pyLoadCli.py')) {
		echo "pyLoadCli.py not found!!\n";
		$config_status = false;
	}
	$module_admins = explode(',', MODULE_ADMINS);
}

function pyload_command($string, $target='', $private=0) {
	global $module_admins, $config_status;
	$ok = false;
	echo "my admins are\n";
	print_r($module_admins);
	foreach($module_admins as $username) {
		echo "Comparing $username with $target...\n";
		if ($username == $target) $ok = true;
	}
	if (!$ok) {
		irc_send_message('Access denied.', $target, $private);
		return false;
	}
	if (!$config_status) {
		irc_send_message('Configuration error.', $target, $private);
		return false;
	}
	//irc_send_message('default command handler', $target, $private);
	if (strpos($string, ' ') !== false) {
		$param = substr($string, strpos($string, ' ')+1);
		$string = substr($string, 0, strpos($string, ' '));
		echo "param: '$param'\n";
		echo "cmd: '$string'\n";
	}
	switch($string) {
		case 'add':
			if ($param != '') {
				if (preg_match('~^(http|ftp)(s)?\:\/\/((([a-z0-9\-]*)(\.))+[a-z0-9]*)($|/.*$)~i', $param)) {
					exec(PYTHON.' '.PYLOAD_PATH.'pyLoadCli.py add ircbotpyload '.$param.' > '.TEMP_FILE);
					if (send_temp_file($target, $private) == '') {
						irc_send_message('Added.', $target, $private);
					}
				} else {
					irc_send_message('Does not look like a valid URL.', $target, $private);
				}
			} else {
				irc_send_message('Parameter missing.', $target, $private);
			}
			break;
		case 'status':
			exec(PYTHON.' '.PYLOAD_PATH.'pyLoadCli.py status > '.TEMP_FILE);
			send_temp_file($target, $private);
			break;
			
	}
}

function send_temp_file($target, $private) {
	$content = '';
	if (file_exists(TEMP_FILE)) {
		$fh = fopen(TEMP_FILE, 'r');
		if ($fh !== false) {
			while(!feof($fh)) {
				$line = fgets($fh);
				$content .= $line;
				irc_send_message($line, $target, $private);
			}
		}
		fclose($fh);
		unlink(TEMP_FILE);
	}
	return $content;
}

?>
<file_sep>/module_demo.php
<?php

/* module_demo, some tests */

/* each module needs an *_init() function
   use it to set up variables and such stuff */
function demo_init() {
	echo "\ndemo_init module";
	/* this will register a custom command */
	ircbot_register_command('dm', 'dm_custom');
	/* register a callback which is called when someone writes on the channel */
	ircbot_register_for_global_listening('dm_listener_global');
	/* register a callbick which is called when a private message is received */
	ircbot_register_for_private_listening('dm_listener_private');
}

/* this function is also required by every module */
function demo_command($string, $target='', $private=0) {
	irc_send_message('default command handler', $target, $private);
}

/* our custom command callback, target is the sender, eg the channel or a username */
/* private means if the message was received privately */
function dm_custom($string, $target='', $private=0) {
	irc_send_message('registered command handler', $target, $private);
}

/* our global message callback */
function dm_listener_global($sender, $msg) {
	irc_send_message('global handler', $sender, 0);
}

/* our private message callback */
function dm_listener_private($sender, $msg) {
	irc_send_message('private handler', $sender, 1);
}

?>
<file_sep>/startbot.sh
#!/bin/sh
# this will launch the bot
# if the exit code of the bot is 3, we will pull the code from github
# and restart again

# check if php command exists
command -v php >/dev/null && continue || { echo "php-cli not found! Please install!"; exit 5; }

# main loop
quit=0
while [ $quit -eq 0 ]
do
	php phpircbot.php > bot.log
	returncode=$?
	if [ $returncode = "3" ] 
	then
		git pull
	else
		quit=1
	fi
done

echo "Exiting, code: $returncode"
exit $returncode
<file_sep>/module_magicball.php
<?php

/* module_magicball, magic 8 ball */

$answers = array();

function magicball_init() {
	irc_bot_echo("magicball_init module");
	/* answers were shamelessly copied from wikipedia */
	global $answers;
	$answers[] = 'It is certain';
	$answers[] = 'It is decidedly so';
	$answers[] = 'Without a doubt';
	$answers[] = 'Yes – definitely';
	$answers[] = 'You may rely on it';
	$answers[] = 'As I see it, yes';
	$answers[] = 'Most likely';
	$answers[] = 'Outlook good';
	$answers[] = 'Yes';
	$answers[] = 'Signs point to yes';
	$answers[] = 'Reply hazy, try again';
	$answers[] = 'Ask again later';
	$answers[] = 'Better not tell you now';
	$answers[] = 'Cannot predict now';
	$answers[] = 'Concentrate and ask again';
	$answers[] = 'Don\'t count on it';
	$answers[] = 'My reply is no';
	$answers[] = 'My sources say no';
	$answers[] = 'Outlook not so good';
	$answers[] = 'Very doubtful';
}


function magicball_command($string, $target='', $private) {
	global $answers;
	$send_answer = rand(0, count($answers)-1);
	irc_send_message($answers[$send_answer].'.', $target, $private);
}

?>
<file_sep>/phpircbot.php
<?php

/* check if config file exists */
if (!file_exists('phpircbot.conf.php')){
	echo "No config found, please read the README!\n";
	exit(4);
}

/* remember start time */
$start_time = time();

/* load phpircbot.conf.php */
require('phpircbot.conf.php');

/* internal constants */
define('IRCBOT_VERSION', '0.1');
define('USER_SHUTDOWN', '1');
define('CONNECTION_LOST', '2');
define('USER_RESTART', '3');
define('CONFIG_NOT_FOUND', '4');

/* quiet mode, disable output */
$quiet_mode = false;

/* convert admin users to array */
$admin_users = explode(',', IRC_ADMIN_USERS);

/* registered commands */
$commands = array();

/* listener */
$msg_listener_global = array();
$msg_listener_private = array();

/* global modules array, contains loaded modules */
$modules = array();

/* auto load modules */
$autoload_modules = explode(',', AUTOLOAD_MODULES);
if (count($autoload_modules) > 0) {
	foreach($autoload_modules as $module_to_load) {
		load_module($module_to_load, '', 1);
	}
}

/* irc channel users */
$users = array();

/* irc resource handle */
$irc_res = false;

/* counter for connection failures */
$connection_failure = 0;

$main_quit = 0;
while(!$main_quit) {
	/* main loop, interpret data sent from irc host */

	$nick = IRC_NICK;
	$channels = explode(',', IRC_CHANNEL);
	
	$irc_res = irc_host_connect();
	
	if ($irc_res == false) {
		irc_bot_echo("Connection failure...");
		$connection_failure++;
		if ($connection_failure > IRC_HOST_RECONNECT) $main_quit = 1;
		sleep(60);
	} else {
		irc_bot_echo("Connection established...");
		$connection_failure = 0;
		$quit = 0;
		$nicked = 0;
		$joined = 0;
		$timeouts = 0;
		while($quit == 0) {
			$line = trim(fgets($irc_res));
			
			$meta_data = stream_get_meta_data($irc_res);

			if ($meta_data['timed_out']) {
				irc_bot_echo("TIMEOUT");
				$timeouts++;
				irc_bot_echo("Timeouts: $timeouts");
			} else {
				$timeouts = 0;
				irc_bot_echo("Timeouts: $timeouts");
			}
			
			if ( $meta_data['eof']){
				irc_bot_echo("EOF");
				$quit = 1;
			}

			irc_bot_echo('IRC: '.$line);
			
			/* after 6 timeouts we reconnect */
			if ($timeouts > 6) $quit = CONNECTION_LOST;
	
			/* send our nick */
			if ((preg_match ( "/(NOTICE AUTH).*(hostname)/i" , $line) == 1) && (!$nicked)) {
				irc_bot_echo('Sending nick...', 0);
				irc_send('USER '.$nick.' 0 * :phpircbot '.IRCBOT_VERSION);
				irc_send('NICK '.$nick);
				
				irc_bot_echo("ok");
				$nicked = 1;
			/* nick already in use */
			} else if (($nicked) && (strpos($line, ' 433 ') !== false)) {
				irc_bot_echo("Nick already in use :(");
				irc_bot_echo("what now?!?!");
				$nick = $nick.'_';
				irc_send('NICK '.$nick);
			/* at the end of motd message, join the channel */
			} else if ((strpos($line, ' 376 ') !== false) && (!$joined)) {
				irc_join_channel(IRC_CHANNEL);				
			/* ping - pong, kind of keepalive stuff */
			} else if (substr($line, 0, 4) == 'PING') {
				irc_send(str_replace('PING', 'PONG', $line));
				foreach($msg_listener_global as $function) {
					call_user_func($function, IRC_CHANNEL, 'PING');
				}
			/* message interpretation */
			} else if (strpos($line, ' PRIVMSG '.$nick.' ') !== false) {
				irc_bot_echo("Received private message...");
				$sender = substr($line, 1, strpos($line, '!')-1);
				irc_bot_echo("From: ".$sender);
				$msg = substr($line, strpos($line, ':', 2)+1);
				irc_bot_echo("Message: ".$msg);
				if (interpret_irc_message($sender, $msg, 1) == false) {
					foreach($msg_listener_private as $function) {
						call_user_func($function, $sender, $msg);
					}
				}
			/* general messages */
			} else if (strpos($line, ' PRIVMSG ') !== false) {
				irc_bot_echo("Received message...");
				$sender = substr($line, 1, strpos($line, '!')-1);
				irc_bot_echo("From: ".$sender);
				$msg = substr($line, strpos($line, ':', 2)+1);
				irc_bot_echo("Message: ".$msg);
				irc_bot_echo("My nick is: ".$nick);
				$result = false;
				if (strpos($msg, $nick) !== false) {
					irc_bot_echo("I was mentioned");
					if (substr($msg, 0, strlen($nick)) == $nick) {
						$msg = substr($msg, strpos($msg, ' ') + 1);
						$result = interpret_irc_message($sender, $msg, 0);
					}
				}
				if ($result == false) {
					foreach($msg_listener_global as $function) {
						call_user_func($function, $sender, $msg);
					}
				}
			/* kick message */
			} else if (strpos($line, ' KICK '.IRC_CHANNEL.' '.$nick) !== false) {
				// we were kicked :(
				irc_bot_echo("were kicked");
				$joined = 0;
				sleep(10);
				irc_bot_echo("rejoining");
				irc_join_channel(IRC_CHANNEL); // rejoin
			/* interprete names list */
			} else if (strpos($line, ' 353 '.$nick) !== false) {
				$names = substr($line, strrpos($line, ':')+1);
				$users_temp = explode(' ', $names);
				$users = array();
				foreach($users_temp as $user) {
					if (substr($user, 0, 1) == '@') $user = substr($user, 1);
					if ($user != $nick) {
						$users[] = $user;
					}
				}
				irc_bot_echo("the users are...");
				print_r($users);
			/* interpret quit message */
			} else if (strpos($line, ' QUIT ') !== false) {
				irc_bot_echo("Received quit...");
				$sender = substr($line, 1, strpos($line, '!')-1);
				irc_bot_echo("From: ".$sender);
				$usercounter = 0;
				foreach($users as $user) {
					if ($user == $sender) unset($users[$usercounter]);
					$usercounter++;
				}
				irc_bot_echo("the users are...");
				print_r($users);
			/* interpret quit message */
			} else if (strpos($line, ' JOIN ') !== false) {
				irc_bot_echo("Received join...");
				$sender = substr($line, 1, strpos($line, '!')-1);
				irc_bot_echo("From: ".$sender);
				$users[] = $sender;
				irc_bot_echo("the users are...");
				print_r($users);
			}
			
			//if (feof($irc_res)) $quit = CONNECTION_LOST;			
		}
		
		/* check what to do now... */
		switch($quit) {
			/* if we were forced to shutdown */
			case USER_SHUTDOWN: $main_quit = 1; break;
			case USER_RESTART: $main_quit = 3; break;
			/* connection lost */
			case CONNECTION_LOST:
			default:
				sleep(60);
				irc_bot_echo("QUIT:$quit");
				irc_bot_echo("what next?");
			break;
		}
		/* quit message */
		if (($quit == USER_SHUTDOWN) || ($quit == USER_RESTART))	irc_send(':'.IRC_NICK.' QUIT :gotta go, fight club');

		/* close connection */
		fclose($irc_res);
	}
	
}

exit($main_quit);

/* connect to irc host */
function irc_host_connect() {
	//global $res;
	/* connect to irc host */
	irc_bot_echo('Connecting...', 0);
	$res = fsockopen(IRC_HOST, IRC_PORT);
	
	if ($res == false) {
		irc_bot_echo("error");
		//die();
		return false;
	}
	irc_bot_echo("ok");
	return $res;
}

/* join channel */
function irc_join_channel($channel) {
	global $joined;
	global $nick;
	irc_bot_echo('Joining channel...', 0);
	irc_send(':'.$nick.' JOIN '.$channel);
	irc_bot_echo("ok");
	$joined = 1;
}

/* interpret irc messages */
function interpret_irc_message($sender, $msg, $private=0) {
	global $quit;
	global $nick;
	global $commands;
	global $modules, $quiet_mode, $start_time;
	$cmd = $msg;
	$params = '';
	if (strpos($msg, ' ') !== false) {
		$cmd = substr($msg, 0, strpos($msg, ' '));
		$params = substr($msg, strpos($msg, ' ')+1);
	}
	
	irc_bot_echo('cmd: \''.$cmd."'");
	irc_bot_echo('params: \''.$params."'");
	
	switch($cmd) {
		/* show loaded modules */
		case 'modules':
			if (count($modules) > 0) {
				$txt = '';
				foreach($modules as $loaded) {
					if ($txt != '') $txt .= ', ';
					$txt .= $loaded;
				}
				irc_send_message('Geladene Module: '.$txt, $sender, $private);
			} else {
				irc_send_message('Keine Module geladen.', $sender, $private);
			}
			break;
		/* show registered commands */
		case 'commands':
			if (count($commands) > 0) {
				$txt = '';
				foreach($commands as $registered=>$func) {
					if ($txt != '') $txt .= ', ';
					$txt .= $registered;
				}
				irc_send_message('Registrierte Befehle: '.$txt, $sender, $private);
			} else {
				irc_send_message('Keine registrierten Befehle.', $sender, $private);
			}
			break;
		/* shutdown bot */
		case 'shutdown':
			if (is_admin($sender)) $quit = USER_SHUTDOWN;
			break;
		/* restart bot */
		case 'restart':
			if (is_admin($sender)) $quit = USER_RESTART;
			break;
		/* rename bot */
		case 'nick':
			if (is_admin($sender)) {
				irc_bot_echo('new nick: '.$params);
				$nick = $params;
				irc_send('NICK '.$nick);
			}
			break;
		/* load module */
		case 'load':
			if (is_admin($sender)) load_module($params, $sender, '', $private);
			break;
		/* switch quiet mode */
		case 'quietmode':
			if (is_admin($sender)) {
				if ($quiet_mode) {
					$quiet_mode = 0;
				} else {
					$quiet_mode = 1;
				}
				irc_send_message('quiet_mode is now: '.$quiet_mode, $sender, $private);
			}
			break;
		/* show version */
		case 'version':
			irc_send_message('v'.IRCBOT_VERSION, $sender, $private);
			break;
		/* help */
		case 'help':
			irc_send_message('Es gibt keine Hilfe!', $sender, $private);
			break;
		/* uptime */
		case 'uptime':
			irc_send_message(date('H:i:s').' up   '.(time() - $start_time).'s');
			break;
		/* else (module commands) */
		default:
			irc_bot_echo("default");
			if (default_command($cmd, $params, $sender, $private)) {
				return true;
			} else {
				irc_send_message('Me no understandy!', $sender, $private);
			}
			break;
	}
	return true;
}

/* module commands */
function default_command($cmd, $params, $target = '', $private) {
	global $modules, $commands;
	irc_bot_echo("default_command($cmd, $params, $target, $private)");
	foreach($commands as $command=>$func) {
		if ($cmd == $command) {
			irc_bot_echo("cmd == command");
			call_user_func($func, $params, $target, $private);
			return true;
		}
	}
	foreach($modules as $loaded) {
		if ($cmd == $loaded) {	
			irc_bot_echo("cmd == loaded");
			call_user_func($loaded.'_command', $params, $target, $private);
			return true;
		}
	}
	return false;
}

/* register command */
function ircbot_register_command($command, $function) {
	global $commands;
	irc_bot_echo("ircbot_register_command($command, $function)");
	$commands[$command] = $function;
	//print_r($commands);
}

/* listener registration public */
function ircbot_register_for_global_listening($function) {
	global $msg_listener_global;
	$msg_listener_global[] = $function;
}

/* listener registration private */
function ircbot_register_for_private_listening($function) {
	global $msg_listener_private;
	$msg_listener_private[] = $function;
}

/* send message to irc host */
function irc_send($string) {
	global $irc_res;
	fwrite($irc_res, $string."\n");
}

/* get array of channel users */
function ircbot_get_channel_users() {
	global $users;
	return $users;
}

/* send (chat) message to irc */
function irc_send_message($string, $target='', $private=1) {
	global $irc_res;
	global $nick;
	if (($target == '') || (!$private)) $target = IRC_CHANNEL;
	if ($private && ($target == '')) $target = IRC_CHANNEL;
	$send = ':'.$nick.' PRIVMSG '.$target.' :'.$string."\n";
	if ($string != '') {
		fwrite($irc_res, $send);
		return true;
	}
	return false;
}

/* load a module */
function load_module($module, $target='', $quiet=0, $private=0) {
	global $modules;
	$already_loaded = 0;
	foreach($modules as $loaded) {
		if ($loaded == $module) $already_loaded = 1;
	}
	if ($already_loaded == 0) {
		if (file_exists('module_'.$module.'.php')) {
			require('module_'.$module.'.php');
			call_user_func($module.'_init');
			$modules[] = $module;
			if (!$quiet) irc_send_message('Modul geladen.', $target, $private);
		} else {
			if (!$quiet) irc_send_message('Modul nicht gefunden.', $target, $private);
		}
	} else {
		if (!$quiet) irc_send_message('Modul bereits geladen.', $target, $private);
	}
}

/* check if user is admin */
function is_admin($user) {
	global $admin_users;
	foreach($admin_users as $admin) {
		if ($admin == $user) return true;
	}
	irc_bot_echo("user is not admin...");
	return false;
}

/* echo messages */
function irc_bot_echo($message, $newline=1) {
	global $quiet_mode;
	if (!$quiet_mode) {
		echo $message;
		if ($newline) echo "\n";
	}
}

?>
<file_sep>/module_linky.php
<?php

/* module_linky */

$link_stats = array();

$link_watcher = array();
$link_watcher[] = 'imgur.com';
$link_watcher[] = 'xkcd.com';

$imgur_history = array();

$ping_counter = 0;

$autoimgurpaste = 1;

function linky_init() {
	global $autoimgurpaste;
	irc_bot_echo("linky_init module");
	$autoimgurpaste = 1;
	ircbot_register_for_global_listening('linky_listener_global');
}

function linky_command($string, $target='', $private=0) {
	//irc_send_message('default command handler', $target, $private);
	global $link_stats, $imgur_history, $autoimgurpaste;
	switch($string) {
		case 'show':
			if (count($link_stats) > 0) {
				foreach($link_stats as $host=>$amount) {
					irc_send_message($host.' : '.$amount, $target, $private);
				}
			} else {
				irc_send_message('Noch keine Links gesammelt.', $target, $private);
			}
			break;
		case 'imgur':
			$link = imgur_get_random_link();
			if ($link != false) {
				irc_send_message($link, $target, $private);
			} else {
				irc_send_message("Sorry, keinen gültigen Link erhalten :(", $target, $private);
			}
			break;
		case 'autoimgurpaste':
			if ($autoimgurpaste) {
				$autoimgurpaste = 0;
			} else {
				$autoimgurpaste = 1;
			}
			irc_send_message('autoimgurpaste is now: '.$autoimgurpaste, $target, $private);
			break;
		case 'help':
			irc_send_message('linky module commands:', $target, $private);
			irc_send_message(' imgur          ... get random imgurl link', $target, $private);
			irc_send_message(' autoimgurpaste ... show random imgurl link pasting mode (currently '.$autoimgurpaste.')', $target, $private);
			irc_send_message(' show           ... show some stats about pasted links', $target, $private);
			break;
	}
}

function imgur_get_random_link() {
	global $imgur_history;
	// erzeuge einen neuen cURL-Handle
	$ch = curl_init();

	// setze die URL und andere Optionen
	curl_setopt($ch, CURLOPT_URL, "http://imgur.com/gallery/random");
	curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	// führe die Aktion aus und gebe die Daten an den Browser weiter
	$result = curl_exec($ch);

	// schließe den cURL-Handle und gebe die Systemresourcen frei
	curl_close($ch);
	irc_bot_echo($result);
	$link_begin = strpos($result, 'Location:')+strlen('Location: ');
	$link_end = strpos($result, "\n", $link_begin);
	$link = trim(substr($result, $link_begin, $link_end-$link_begin));
	irc_bot_echo("$link_begin - $link_end, string: '".$link."'");
	if (substr($link, 0, 4) == 'http') {
		$imgur_history[] = $link;
		return $link;
	}
	return false;
}


function linky_listener_global($sender, $msg) {
	global $link_stats, $ping_counter, $imgur_history;
	if ($msg == 'PING') {
		$ping_counter++;
		irc_bot_echo("Received ping...$ping_counter");
		if ($ping_counter > 10) {
			$link = imgur_get_random_link();
			if ($link != false) irc_send_message('Random IMGUR anyone? '.$link, IRC_CHANNEL, 0);
			$ping_counter = 0;
		}
	} else {
		$pos = strpos($msg, 'http');
		if ($pos !== false) {
			$end = strpos($msg, ' ', $pos);
			if ($end !== false) {
				$full_link = substr($msg, $pos, $end);
			} else {
				$full_link = substr($msg, $pos);
			}
			irc_bot_echo("link detected as: ".$full_link);
			$url = parse_url($full_link);
			irc_bot_echo("host of this is: ".$url['host']);
			if (!isset($link_stats[$url['host']])) {
				$link_stats[$url['host']] = 0;
			}
			if ($url['host'] == 'imgur.com') {				
				foreach($imgur_history as $url) {
					if ($url == $full_link) {
						irc_send_message('Den Link hatten wir schon.', IRC_CHANNEL, 0);
						break;
					}					
				}
				$imgur_history[] = $full_link;
			}
			$link_stats[$url['host']]++;
		}
	}
}


?>
