<?php
///////////////////////////////////////////////
// Neopets GTK Auto Buyer
///////////////////////////////////////////////

$wnd = new GtkWindow();
$wnd->set_title('Neopets Auto Buyer');
$wnd->connect_simple('destroy', array('gtk''main_quit'));

$lblCredit = new GtkLabel('');
$lblCredit->set_markup("<span color=\"blue\">Gary's Hood</span>");
$lblUsername = new GtkLabel('Username:');
$lblPassword = new GtkLabel('Password:');
$lblItem = new GtkLabel('Item:');
$lblPrice = new GtkLabel('Price (NP):');
$txtUsername = new GtkEntry();
$txtPassword = new GtkEntry();
$txtPassword->set_visibility(false);
$txtItem = new GtkEntry();
$txtPrice = new GtkEntry();
$btnHelp = new GtkButton('Help');
$btnStart = new GtkButton('Start');
$btnCancel = new GtkButton('Cancel');

$aUsername = new GtkAlignment(10.500);
$aUsername->add($lblUsername);
$aPassword = new GtkAlignment(10.500);
$aPassword->add($lblPassword);
$aItem = new GtkAlignment(10.500);
$aItem->add($lblItem);
$aPrice = new GtkAlignment(10.500);
$aPrice->add($lblPrice);

$btnStart->connect_simple('clicked''process_data'$wnd$txtUsername$txtPassword$txtItem$txtPrice);
$btnCancel->connect_simple('clicked', array($wnd'destroy'));
$btnHelp->connect_simple('clicked''help_dialog'$wnd);

$tbl = new GtkTable(72);
$tbl->attach($lblCredit0101);
$tbl->attach($btnHelp1201);
$tbl->attach($aUsername0112);
$tbl->attach($txtUsername1212);
$tbl->attach($aPassword0123);
$tbl->attach($txtPassword1223);
$tbl->attach($aItem0134);
$tbl->attach($txtItem1234);
$tbl->attach($aPrice0145);
$tbl->attach($txtPrice1245);
$tbl->attach($btnStart0167);
$tbl->attach($btnCancel1267);

$vbox = new GtkVBox();
$vbox->pack_start($tbl);

$wnd->add($vbox);
$wnd->show_all();
Gtk::main();

///////////////////////////////////////////////
// Process Input
///////////////////////////////////////////////

function process_data(GtkWindow $wndGtkEntry $txtUsernameGtkEntry $txtPasswordGtkEntry $txtItemGtkEntry $txtPrice) {
    
$strUsername $txtUsername->get_text();
    
$strPassword $txtPassword->get_text();
    
$strItem $txtItem->get_text();
    
$strPrice $txtPrice->get_text();
    
$errors null;
    if(
strlen($strUsername) == 0) {
        
$errors .= "Username is missing.\n";
    }
    if(
strlen($strPassword) == 0) {
        
$errors .= "Password is missing.\n";
    }
    if(
strlen($strItem) == 0) {
        
$errors .= "No item was set.\n";
    }
    if(
strlen($strPrice) == || !is_numeric($strPrice)) {
        
$errors .= "Invalid price.\n";
    }
    if(
$errors !== null) {
        
$dialog = new GtkMessageDialog($wndGtk::DIALOG_MODALGtk::MESSAGE_ERRORGtk::BUTTONS_OK$errors);
        
$dialog->set_title('General Error');
        
$dialog->set_markup("The following errors occured:\r\n<span color='#8B0000'>$errors</span>");
        
$dialog->run();
        
$dialog->destroy();
    } else {
        
$username str_replace(" ""_"$strUsername);
        
$password stripslashes($strPassword);
        
$item stripslashes(str_replace(" ""+"$strItem));
        
$price str_replace(","""$strPrice);
        
$cookiefile tempnam("""neopets_");
        
$data neopets_login($username$password$cookiefile);
        if(
strpos($data'username/password')) {
            
$dialog = new GtkMessageDialog($wndGtk::DIALOG_MODALGtk::MESSAGE_ERRORGtk::BUTTONS_OK$errors);
            
$dialog->set_title('Login Error');
            
$dialog->set_markup("Login information did not process.");
            
$dialog->run();
            
$dialog->destroy();
        } else {
            for(
$i 0$i 10$i++) {
                
$return .= item_search($item$price$cookiefile);
            }
            
$dialog = new GtkMessageDialog($wndGtk::DIALOG_MODALGtk::MESSAGE_INFOGtk::BUTTONS_OKnull);
            
$dialog->set_title('Results');
            if(empty(
$return)) {
                
$return "No results found.";
            }
            
$dialog->set_markup($return);
            
$dialog->run();
            
$dialog->destroy();
        }
        
unlink($cookiefile);
    }
}

function 
help_dialog(GtkWindow $wnd) {
    
$dialog = new GtkMessageDialog($wndGtk::DIALOG_MODALGtk::MESSAGE_INFOGtk::BUTTONS_OKnull);
    
$dialog->set_title('Help');
    
$dialog->set_markup("This Neopets Auto Buyer will search the Shop Wizard several times to find you the best deal on an item of your choosing.\r\n\r\nSimply enter your username and password to process the login, along with the name of the EXACT item you wish to locate. The price field allows you to set a maximum price to search for. If you wish to purchase the item unlimited times, set the price field to 99,999.\r\n\r\nIf a match is found on the Shop Wizard and you have enough Neopoints, this application will automatically purchase the entire quantity of your searched item that is in stock.\r\n\r\nMore usage and information may be found at:\r\nhttp://www.garyshood.com/neopets/");
    
$dialog->run();
    
$dialog->destroy();
}

///////////////////////////////////////////////
// Neopets Login
///////////////////////////////////////////////

function neopets_login($username$password$cookiefile) {
    
$url "http://www.neopets.com/login.phtml";
    
$curl curl_init();
    
curl_setopt($curlCURLOPT_URL$url);
    
curl_setopt($curlCURLOPT_POST1);
    
curl_setopt($curlCURLOPT_POSTFIELDS"username=$username&password=$password");
    
curl_setopt($curlCURLOPT_FOLLOWLOCATIONtrue);
    
curl_setopt($curlCURLOPT_COOKIEJAR$cookiefile);
    
curl_setopt($curlCURLOPT_RETURNTRANSFER1);
    
$data curl_exec($curl);
    
curl_close($curl);
    return 
$data;
}

///////////////////////////////////////////////
// Curl Get
///////////////////////////////////////////////

function curl_get($url$cookiefile$referer "") {
    
$curl curl_init();
    
curl_setopt($curlCURLOPT_URL$url);
    
curl_setopt($curlCURLOPT_FOLLOWLOCATIONtrue);
    
curl_setopt($curlCURLOPT_RETURNTRANSFER1);
    
curl_setopt($curlCURLOPT_REFERER$referer);
    
curl_setopt($curlCURLOPT_COOKIEFILE$cookiefile);
    
$data curl_exec($curl);
    
curl_close($curl);
    return 
$data;
}

///////////////////////////////////////////////
// Curl Post
///////////////////////////////////////////////

function curl_post($url$cookiefile$post$referer "") {
    
$curl curl_init();
    
curl_setopt($curlCURLOPT_URL$url);
    
curl_setopt($curlCURLOPT_POST1);
    
curl_setopt($curlCURLOPT_POSTFIELDS$post);
    
curl_setopt($curlCURLOPT_FOLLOWLOCATIONtrue);
    
curl_setopt($curlCURLOPT_RETURNTRANSFER1);
    
curl_setopt($curlCURLOPT_REFERER$referer);
    
curl_setopt($curlCURLOPT_COOKIEFILE$cookiefile);
    
$data curl_exec($curl);
    
curl_close($curl);
    return 
$data;
}

///////////////////////////////////////////////
// Search for the item
///////////////////////////////////////////////

function item_search($item$price$cookiefile) {
    
$data curl_post("http://www.neopets.com/market.phtml"$cookiefile"type=process_wizard&feedset=0&shopwizard=$item&table=shop&criteria=exact&min_price=0&max_price=$price""http://www.neopets.com/market.phtml?type=wizard");
    
$purchased 0;
    if(!
strpos($data'I did not find anything') && !strpos($data'Whoa there, too many searches!')) {
        
preg_match_all("/<td align=\"left\" bgcolor=\"#F6F6F6\"><a href=\"\/browseshop\.phtml\?owner=(.*?)&buy_obj_info_id=(.*?)&buy_cost_neopoints=(.*?)\">/"$data$info);
        
$user_array = array();
        
$price_array = array();
        foreach(
$info[1] as $info_var) {
            
array_push($user_array$info_var);
        }
        foreach(
$info[2] as $info_var) {
            
$item_id $info_var;
        }
        foreach(
$info[3] as $info_var) {
            
array_push($price_array$info_var);
        }
        for(
$i 0$i count($user_array); $i++) {
            
$return .= "User: $user_array[$i] | Price: $price_array[$i]\n";
            
purchase_item($price_array[$i], $user_array[$i], $item_id$cookiefile);
            
$purchased++;
        }
    } elseif(
strpos($data'Whoa there, too many searches!')) {
        
$return .= "Too many searches. Please try again later.\n";
    }
    if(
$purchased 0) {
        
$return .= "Purchased: $purchased\n\n";
    }
    return 
$return;
}

///////////////////////////////////////////////
// Purchase the item
///////////////////////////////////////////////

function purchase_item($price$user$item_id$cookiefile) {
    
$data curl_get("http://www.neopets.com/browseshop.phtml?owner=$user"$cookiefile);
    
$continue true;
    while(
strpos($data$item_id) && $continue) {
        
$data curl_get("http://www.neopets.com/browseshop.phtml?owner=$user"$cookiefile);    
        
preg_match("/\"buy_item\.phtml\?lower=0&owner=$user&obj_info_id=$item_id&g=1&xhs=(.*?)&old_price=(.*?)&feat=(.*?)&_ref_ck=(.*?)\"/"$data$info);
        if(
$info[2] <= $price) {
            
$data curl_get("http://www.neopets.com/buy_item.phtml?lower=0&owner=$user&obj_info_id=$item_id&g=1&xhs=$info[1]&old_price=$info[2]&feat=$info[3]&_ref_ck=$info[4]"$cookiefile"http://www.neopets.com/browseshop.phtml?owner=$user");
        } else {
            
$continue false;
        }
    }
}
?>