<?php

	class sets {
		public $title;
		public $slideshow;
		public $gallery_sets;
	}
	$settings = new sets();

	function load_feed( $url ) {
		$doc = new DOMDocument();
		$doc->load( $url );
		$arr_feeds = array();
		foreach ( $doc->getElementsByTagName( 'item' ) as $node ) {
			$item_RSS = array ( 
				'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
				'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
				'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
				'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
			);
			array_push( $arr_feeds, $item_RSS );
		}
		return  $arr_feeds;
	}

	function load_leaderboard() {
		// File to download
		$remote_file = 'http://leaderboard.alleg.net/';
		// Local file for saving
		$local_file = dirname(__FILE__)  . '/cache/leaderboard.csv';
		// Time to cache
		$cache_time = 86400;
		// Connection time out
		$conn_timeout = 10;

		// Check if the leaderboard cache needs to be updated
		if ( !file_exists( $local_file ) ) {
			$new_file = true;
			fopen( $local_file, 'w' );
		}
		if ( $new_file || time() > ( $cache_time + filemtime( $local_file ) ) ) {
			// Load leaderboard page
			$url = parse_url( $remote_file );
			$host = $url[ 'host' ];
			$path = isset( $url[ 'path' ] ) ? $url[ 'path' ] : '/';

			if ( isset( $url[ 'query' ] ) ) {
				$path .= '?' . $url[ 'query' ];
			}

		  $fp = @fsockopen( $host, '80', $errno, $errstr, $conn_timeout );

			if( !$fp ) {
				// If connection failed, return the cached file
				if ( is_writable( $local_file ) ) {
					if ( $fp = fopen( $local_file, 'r' ) ) {
						while( $line = fread( $fp, 4096 ) ) {
							$response .= $line;
						}
						fclose( $fp );
					}
				}
			} else {
				// Header Info
				$header = "GET $path HTTP/1.0\r\n";
				$header .= "Host: $host\r\n";
				$header .= "User-Agent: FAO Home page\r\n";
				$header .= "Accept: */*\r\n";
				$header .= "Accept-Language: en-us,en;q=0.5\r\n";
				$header .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
				$header .= "Keep-Alive: 300\r\n";
				$header .= "Connection: keep-alive\r\n";
				$header .= "Referer: http://$host\r\n\r\n";

				$response = '';
				fwrite( $fp, $header );
				// Get the file content. We don't need the whole file.
				for ( $i = 0; $i < 36; $i ++ ) {
					$line = fread( $fp, 4096 );
					$response .= $line;
				}
				fclose( $fp );

				// Remove Header Info
				$pos = strpos( $response, "\r\n\r\n" );
				$response = substr( $response, $pos + 4 );
			}

			// Create the file, if it doesn't exist already
			if ( !file_exists( $local_file ) ) {
				fopen( $local_file, 'w' );
			}
			if ( is_writable( $local_file ) ) {
				if ( $fp = fopen( $local_file, 'w' ) ) {
					// Parse the table rows. Explode is simpler than regexps
					$response = explode( 'LeaderboardRow', $response, 102 );
					$response[ 0 ] = '';  // First and last item just contain crap
					$response[ 101 ] = ''; 
					for ( $i = 1; $i < 101; $i++ ) {
						$response[ $i ] = str_replace( ' align="right"', '', $response[ $i ] );
						$response[ $i ] = str_replace( '</td>', '', $response[ $i ] );
						$response[ $i ] = str_replace( '</tr>', '', $response[ $i ] );

						$response[ $i ] = explode( '<td>', $response[ $i ], 8 );

						fwrite( $fp, $response[ $i ][ 3 ] . ',' . $response[ $i ][ 6 ] . "\n" );
						$top[ 'name' ][ $i - 1 ] = $response[ $i ][ 3 ];
						$top[ 'rank' ][ $i - 1 ] = $response[ $i ][ 6 ];
					}
					// Done writing cache
					fclose( $fp );
				}
			}				
		} else {
			// Load the cache
			if ( $fp = fopen( $local_file, 'r' ) ) {
				while( $line = fread( $fp, 4096 ) ) {
					$response .= $line;
				}
				fclose( $fp );
				$rows = explode( "\n", $response );
				$j = 0; $i = 0;
				foreach ( $rows as $data ) {
					$data = explode( ',', $rows[ $j ] );
					$top[ 'name' ][ $j ] = $data[ 0 ];
					$top[ 'rank' ][ $j ] = $data[ 1 ];
					$j++;
				}
			

			}
		}
		return $top;
	}

	function lb_row( $place, $name, $rank ) {
		echo '<div class="lb-row"><div class="lb-place">', $place + 1, '</div><div class="lb-callsign">', htmlentities( $name ), '</div><div class="lb-rank">', htmlentities( $rank ), '</div></div>';
	}

	define( 'LB_HEADER', '<div id="lb-head"><div class="lb-row"><div class="lb-place">Place</div><div class="lb-callsign">Callsign</div><div class="lb-rank">Rank</div></div></div>' );

	function leaderboard_widget() {
		echo'<h2>top pilots <a class="view-all" href="http://leaderboard.alleg.net/" title="">view all »</a></h2>';
		echo '
				<script type="text/javascript">
					var lbPage = 1;
					var lbTimer = 0;
					function lbState() {
						lbTimer = lbTimer + 1;
						if ( lbTimer == 301) { lbTimer = 1; }
						if ( lbTimer < 51 ) {
							setOpacity( document.getElementById( "lb-page-"+ lbPage.toString() ), lbTimer * 2 );
						}
						if ( lbTimer > 249 && lbTimer < 300 ) {
							setOpacity( document.getElementById( "lb-page-"+ lbPage.toString() ), (301 - lbTimer) * 2 );
						}
						if ( lbTimer == 300 ) {
							lbTicker();
						}				
					}
					function lbTicker() {
						document.getElementById( "lb-page-" + lbPage.toString() ).style.display = "none";
						lbPage = lbPage + 1;
						if ( lbPage == 11 ) { lbPage = 1; }
						document.getElementById( "lb-page-" + lbPage.toString() ).style.display = "";
					}
					timer = setInterval( "lbState()", 20 );
				</script>

			<div id="top-pilots">
			';
		$top = load_leaderboard();
		if( $top ) {
			echo '<div id="lb-table">', "\n", LB_HEADER;
			for ( $i  = 0; $i < 100; $i++ ) {
				if ( floatval( $i / 10 ) == intval( $i / 10) ) {
					if ( $i == 0 ) {
						echo '<div id="lb-page-', intval( $i / 10 ) + 1, '">', "\n";
					} else {
						echo '</div>', "\n";
						echo '<div id="lb-page-', intval( $i / 10 ) + 1, '" style="filter:alpha(opacity=0);opacity:0; display:none;">', "\n";
					}
				}
				lb_row( $i, $top[ 'name' ][ $i ], $top[ 'rank' ][ $i ] );
			}
			echo '</div>', "\n";
			echo '</div>';
		} else {
			echo 'Leaderboard stats are currently unavailable.';
		}
		echo '</div>';
	}

	function fetch_wiki( $remote_file, $link_domain, $cache ) {
		// Local file for saving
		$local_file = dirname(__FILE__)  . '/cache/' . $cache . '.inc';
		// Time to cache
		$cache_time = 172800;
		// Connection time out
		$conn_timeout = 10;

		// Check if the cache needs to be updated
		if ( !file_exists( $local_file ) ) {
			$new_file = true;
			fopen( $local_file, 'w' );
		}
		if ( $new_file || time() > ( $cache_time + filemtime( $local_file ) ) ) {
			$response = "LOADED PAGE\n";
			// Load page
			$url = parse_url( $remote_file );
			$host = $url[ 'host' ];
			$path = isset( $url[ 'path' ] ) ? $url[ 'path' ] : '/';

			if ( isset( $url[ 'query' ] ) ) {
				$path .= '?' . $url[ 'query' ];
			}

		  $fp = @fsockopen( $host, '80', $errno, $errstr, $conn_timeout );

			if( !$fp ) {
				// If connection failed, return the cached file
				if ( is_writable( $local_file ) ) {
					if ( $fp = fopen( $local_file, 'r' ) ) {
						while( $line = fread( $fp, 4096 ) ) {
							$response .= $line;
						}
						fclose( $fp );
					}
				}
			} else {
				// Header Info
				$header = "GET $path HTTP/1.0\r\n";
				$header .= "Host: $host\r\n";
				$header .= "User-Agent: FAO Home page\r\n";
				$header .= "Accept: */*\r\n";
				$header .= "Accept-Language: en-us,en;q=0.5\r\n";
				$header .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
				$header .= "Keep-Alive: 300\r\n";
				$header .= "Connection: keep-alive\r\n";
				$header .= "Referer: http://$host\r\n\r\n";

				$response = '';
				fwrite( $fp, $header );
				// Get the file content.
				while ( $line = fread( $fp, 4096 ) ) {
					$response .= $line;
				}
				fclose( $fp );

				// Remove Header Info
				$pos = strpos( $response, "\r\n\r\n" );
				$response = substr( $response, $pos + 4 );
			}

			// Create the file, if it doesn't exist already
			if ( !file_exists( $local_file ) ) {
				fopen( $local_file, 'w' );
			}
			if ( is_writable( $local_file ) ) {
				if ( $fp = fopen( $local_file, 'w' ) ) {

					// Extract the content
					$c_start = strpos( $response, '<!-- start content -->' );
					$c_end = strpos( $response, '<!-- end content -->' );
					$response = substr( $response, (int)$c_start, (int)$c_end - (int)$c_start );
					fwrite( $fp, $response );
					// Done writing cache
					fclose( $fp );
				}
			}				
		} else {
			// Load the cache
			if ( $fp = fopen( $local_file, 'r' ) ) {
				while( $line = fread( $fp, 4096 ) ) {
					$response .= $line;
				}
				fclose( $fp );
			}
		}

		// Make the links absolute
		if ( $link_domain ) {
			$response = str_replace( 'href="/', 'href="http://' . $link_domain . '/', $response );
			$response = str_replace( 'src="/', 'src="http://' . $link_domain . '/', $response );
		}
		return $response;
	}

	function blogs_widget() {
		echo '<h2>latest logs <a class="view-all" href="http://www.freeallegiance.org/forums/index.php?autocom=blog" title="">view all »</a></h2>', "\n<ul>\n";
		$news = load_feed( 'http://www.freeallegiance.org/forums/index.php?autocom=blog&req=syndicate' );
		$i = 0;
		foreach ( $news as $headline ) {
			echo '<li><small>',  date( 'd M Y', strtotime( $headline[ 'date' ] ) ), '</small> <a href="', htmlentities( $headline[ 'link' ] ), '">', $headline[ 'title' ], '</a></li>', "\n";
			$i++;
			if ( $i == 8 ) { break; }
		}
		echo "</ul>\n";
	}
?>