<?php

	/*

    libGameFly
    Copyright (C) 2007 Evan Sims

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

    -----

    Version 2007.12.27 - Evan Sims (evansims@gmail.com)
    	First release.

	*/

	class libGamefly {

		var $username, $password, $expire;

		function libGamefly($username, $password) {

			$this->username = urlencode($username);
			$this->password = urlencode($password);
			$this->expire = 3600;

		}

		function Get() {

			if(!file_exists('gamefly_cache.dat')) {
				if(!$this->Update()) return false;
			}
			if(!file_exists('gamefly_cache.dat')) return false;

			include('gamefly_cache.dat');

			if(!isset($gf_time)) return false;

			if((time() - $gf_time) > $this->expire) {
				if(!$this->Update()) return false;
				include('gamefly_cache.dat');
			}

			return unserialize($gf_data);

		}

		function Update() {

			if(file_exists('gamefly_cache.dat') && !is_writable('gamefly_cache.dat')) die('libGamefly Error: gamefly_cache.dat is not writable.');

			$fp = fsockopen('www.gamefly.com', 80, $errno, $errstr, 30);

			if(!$fp) {
				return false;
			} else {

				$postdata = 'tp=&re=&pr=&p=0&gcid=&gctp=0&pue=&fc=&un=' . urlencode($this->username) . '&pw=' . urlencode($this->password) . '&forgotpw=0&submit.x=25&submit.y=12';

				$nl = "\r\n";

				$out  = 'POST /member/queueRedesign.asp HTTP/1.1' . $nl;
				$out .= 'Host: www.gamefly.com'  . $nl;
				$out .= 'User-Agent: libGamefly'  . $nl;
				$out .= 'Connection: close'  . $nl;
				$out .= 'Cookie: strack=2; fcR=http%3A//www.gamefly.com/member/; fcPT=http%3A//www.gamefly.com/member/; GFSubPP=0; GFPaying=1; flyers=5EB624; airmail=' . urlencode($this->username) . '; flyer=5EB624; strbranding=; GFMusic=mem'  . $nl;
				$out .= 'Content-Type: application/x-www-form-urlencoded'  . $nl;
				$out .= 'Content-Length: ' . strlen($postdata) .  $nl . $nl;
				$out .= $postdata;

				$data = '';

				@fwrite($fp, $out);
				while (!feof($fp)) $data .= @fgets($fp, 128);
				@fclose($fp);

				if(strpos($data, '</strong> games in your Q</li>') === false) die('libGamefly Error: Credentials appear to be invalid, or queue is empty.');

				$data = $this->Build($data);
				if(!count($data)) return false;

				$data = '<' . "?php\n\n\t\$gf_time=" . time() . ";\n\t\$gf_data='" . str_replace('\'', '\\\'', serialize($data)) . "';\n\n?" . '>';

				if (!$handle = fopen('gamefly_cache.dat', 'w')) die('libGamefly Error: Cannot write to gamefly_cache.dat.');
				if (fwrite($handle, $data) === FALSE) die('libGamefly Error: Cannot write to gamefly_cache.dat.');
				fclose($handle);

				return true;

			}

		}

		function Build($data) {

			$b_Stage = 0;
			$game = array();
			$queue = array();

			for($d = 0; $d < strlen($data); $d++) {

				if($data[$d] == '<') {

					if (substr($data, $d, 55) == '<h1 class="gamesOut"><span>Games I Have Out</span></h1>') {
						$b_Stage = 1; // Checked Out
						$d = $d + 55;
						continue;
					} elseif (substr($data, $d, 71) == '<h1 class="gameQHeader" id="topOfQ" ><span>Games on My List</span></h1>') {
						$b_Stage = 2; // Queue
						$d = $d + 71;
						continue;

					} elseif (substr($data, $d, 11) == '<tr id="tr_') {

						if($b_Stage == 2) {

							if(strlen($game['name'])) $queue[] = $game;

							$game['name'] = '';
							$game['id'] = 0;
							$game['esrb'] = '';
							$game['system'] = '';
							$game['shipped'] = false;
							$game['availability'] = '';
							$game['avg_rating'] = null;
							$game['my_rating'] = null;

						}

						$raw = substr($data, $d + 11);
						$raw = substr($raw, 0, strpos($raw, '"'));

						if(strlen($raw)) $game['id'] = $raw;

					} elseif($b_Stage > 0) {

						if (substr($data, $d, 19) == '<a class="gameInfo"') { //'

							if($b_Stage == 1) {

								if(strlen($game['name'])) $queue[] = $game;

								$game['name'] = '';
								$game['id'] = 0;
								$game['esrb'] = '';
								$game['system'] = '';
								$game['shipped'] = false;
								$game['availability'] = '';
								$game['avg_rating'] = null;
								$game['my_rating'] = null;

							}

							$raw = substr($data, $d);
							$raw = substr($raw, 0, strpos($raw, '</a>'));

							$game['name'] = trim(substr($raw, strpos($raw, '>') + 1));

							if(strpos($raw, 'id="')) {
								$game['id'] = substr($raw, strpos($raw, 'id='));
								$game['id'] = substr($game['id'], strpos($game['id'], '"')+1);
								$game['id'] = (int)trim(substr($game['id'], 0, strpos($game['id'], '"')));
							}

						} elseif (substr($data, $d, 20) == '<p><a class="rating ') {

							$raw = substr($data, strpos($data, '<span>', $d) + 6);
							$raw = trim(substr($raw, 0, strpos($raw, '</span>')));

							if(strlen($raw)) $game['esrb'] = $raw;

						} elseif (substr($data, $d, 18) == '<td class="system"') {

							$raw = substr($data, strpos($data, '<p class="', $d));
							$raw = substr($raw, strpos($raw, '>') + 1);
							$raw = trim(substr($raw, 0, strpos($raw, '<')));

							if(strlen($raw)) $game['system'] = $raw;

						} elseif (substr($data, $d, 22) == '<span class="shipDate"') {

							$raw = substr($data, strpos($data, '>', $d));
							$raw = trim(substr($raw, 0, strpos($raw, '<')));

							if(strlen($raw)) $game['shipped'] = $raw;

						} elseif (substr($data, $d, 23) == '<td class="availability') {

							$raw = substr($data, strpos($data, '<span>', $d + 24));
							$raw = trim(substr($raw, 6, strpos($raw, '</span>')));
							if(substr($raw, 0, 8) == 'Releases') $raw = substr($raw, strpos($raw, '>') + 1);
							$raw = trim(substr($raw, 0, strpos($raw, '<')));

							if(strlen($raw)) $game['availability'] = $raw;

						} elseif (substr($data, $d, 21) == '<td class="ratingInfo') {

							$raw = substr($data, strpos($data, '>', $d + 21) + 1);
							$raw = trim(substr($raw, 0, strpos($raw, '</td>')));

							if(strpos($raw, '<span class="rating">')) {

								$rating = substr($raw, strpos($raw, '<span class="rating">') + 21);
								$rating = trim(substr($rating, 0, strpos($rating, '</span>')));

								if(strlen($rating) && is_numeric($rating)) { $game['avg_rating'] = $rating; }

							}

							if(strpos($raw, '<div class="theRating"')) {

								$rating = substr($raw, strpos($raw, '<div class="theRating"') + 22);
								$rating = substr($rating, strpos($rating, '<span class="rating"') + 22);
								$rating = trim(substr($rating, 0, strpos($rating, '</span>')));

								if(strlen($rating) && is_numeric($rating)) { $game['my_rating'] = $rating; }

							}

						}

					}

				}

			}

			if(strlen($game['name'])) $queue[] = $game;

			return $queue;

		}

	}

?>
