Advertisement
Guest User

PHP SQL cURL GW2 API v2 Tradepost

a guest
Oct 9th, 2014
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.60 KB | None | 0 0
  1. <?php
  2. # Get the all the items numbers
  3. $url1 = "http://api.guildwars2.com/v2/commerce/listings";
  4. $response1 = file_get_contents($url1);
  5. $data1 = json_decode($response1, true);
  6. $amount_added_to_db = 0;
  7.  
  8. # Process in chunks to avoid out of memory error
  9. $chunksize = round(sizeof($data1)/10); #round(sizeof($data1)/10); # divided by 10 equals around 2215
  10. $offset = 9*$chunksize;
  11. $length = $chunksize;
  12. $splitsize = 25; # maximum 200
  13.  
  14. $smallchunk = array_slice($data1,$offset, $length);  
  15. $splitted_smallchunk = array_chunk($smallchunk, $splitsize);
  16.  
  17. #Retrieve item names and link with numbers
  18. function request_callback($response,$info) {
  19.     global $associative_array;
  20.     if($info['http_code'] === 200){
  21.         $temporary_array = json_decode($response, true);
  22.             foreach ($temporary_array as $value){
  23.                 $associative_array[] = array('name' => $value['name'],'id' => $value['id']);
  24.             }
  25.         }
  26.     }
  27.  
  28. # Queue up multiple curl request for handling
  29. require("rollingcurl.php"); // from https://github.com/LionsAd/rolling-curl
  30.  
  31. foreach ($splitted_smallchunk as $urlstring){
  32.         $urlstring = implode (',',$urlstring);
  33.         $urls[] = "https://api.guildwars2.com/v2/items?ids={$urlstring}";
  34. }
  35.  
  36. $rc = new RollingCurl("request_callback");
  37. $rc->window_size = 20;
  38. foreach ($urls as $url) {
  39.      $request = new  RollingCurlRequest ( $url ) ;
  40.      $rc -> add ( $request ) ;
  41. }
  42. $rc->execute();
  43.  
  44.  
  45.  
  46. try {
  47.         # Make a connection to the database
  48.         $db = new PDO('sqlite:/var/www/gw2db/gw2.sqlite');
  49.         $db ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  50.      
  51.         # Create the database (if already made, IF NOT EXISTS will prevent error)
  52.         $db->exec("CREATE TABLE IF NOT EXISTS alltheitems (Id INTEGER PRIMARY KEY, itemname TEXT, itemnumber INTEGER)");       
  53.    
  54.         # Prepare the query ONCE
  55.         $stmt = $db->prepare('INSERT INTO alltheitems (itemname, itemnumber) VALUES(:name, :number)');
  56.         $stmt->bindParam(':name', $itemname, SQLITE3_TEXT);
  57.         $stmt->bindParam(':number', $itemnumber, SQLITE3_INTEGER);
  58.        
  59.         # Insert values and execute statements
  60.         for ($x=0;$x<sizeof($associative_array);$x++){
  61.             $itemname = $associative_array[$x]['name'];
  62.             $itemnumber = $associative_array[$x]['id'];
  63.            
  64.                 # Check if the item is already in the database or invalid URL return
  65.                 $duplicatecheck = $db->query("SELECT * FROM alltheitems WHERE itemnumber LIKE '$itemnumber'");
  66.                 $alreadyinDB=0;
  67.                 foreach($duplicatecheck as $row)
  68.                     {
  69.                       $alreadyinDB=1;
  70.                     }
  71.  
  72.             if ($alreadyinDB==0) {
  73.                 $stmt->execute();
  74.                 $amount_added_to_db = $amount_added_to_db + 1;
  75.             }
  76.         }
  77.  
  78.    
  79.         $fetchdb = $db->query("SELECT itemnumber, itemname FROM alltheitems");
  80.        
  81.         # Make array from fetchdb object
  82.         $data_array = $fetchdb->fetchAll();
  83.        
  84.         if ($amount_added_to_db > 0){
  85.        
  86.             $data_array_latest_added = array_slice($data_array,-$amount_added_to_db);
  87.            
  88.        
  89.             function request_callback2($response,$info) {
  90.                 global $joint_array;
  91.                 $db2 = new PDO('sqlite:/var/www/gw2db/gw2.sqlite');
  92.                 $temporary_array = json_decode($response, true);
  93.                
  94.                 if (($info['http_code'] === 200) && (is_array($temporary_array))){ 
  95.                    
  96.                     foreach ($temporary_array as $value){
  97.                             $idnumber = $value['id'];
  98.                             $searchname = $db2 ->query("SELECT itemname FROM alltheitems WHERE itemnumber LIKE '$idnumber'");
  99.                             $searcharray = $searchname->fetchAll();
  100.                             $itemname = $searcharray[0]['itemname'];
  101.                                
  102.                             $joint_array[]= array('name'=>$itemname, 'id'=>$value['id'],'buys'=>$value['buys'],'sells'=>$value['sells']);
  103.                             #echo $itemname; echo " with id# "; echo $idnumber; echo " has been added to joint_array "; echo "\n";
  104.                     }
  105.                    
  106.                 }  
  107.                
  108.                 $db2 = NULL;
  109.             }
  110.  
  111.            
  112.            
  113.             $splitted_dala = array_chunk($data_array_latest_added, $splitsize);
  114.            
  115.            
  116.             foreach ($splitted_dala as $urlnumbers){
  117.                     $temp = $urlnumbers;
  118.                     $ids = array();
  119.                         foreach ($temp as $value){
  120.                             $ids[] = $value['itemnumber'];
  121.                             $idstring = implode (',',$ids);
  122.                         }
  123.                     $TPurls[]="https://api.guildwars2.com/v2/commerce/listings?ids={$idstring}";
  124.                     unset($ids);
  125.  
  126.             }
  127.  
  128.             $rc = new RollingCurl("request_callback2");
  129.             $rc->window_size = 20;
  130.             foreach ($TPurls as $url) {
  131.                  $request = new  RollingCurlRequest ( $url ) ;
  132.                  $rc -> add ( $request ) ;
  133.             }
  134.             $rc->execute();    
  135.            
  136.             #echo '<pre>'; print_r($joint_array); echo '</pre>';
  137.            
  138.             for ($y=0; $y<sizeof($joint_array);$y++) {
  139.            
  140.                 $totalbuys = 0;
  141.                 $totalsells = 0;
  142.                 $totalbuyprice = 0;
  143.                 $totalsellprice = 0;
  144.                
  145.                 for ($x=0;$x<sizeof($joint_array[$y]['buys']);$x++) {
  146.                     $totalbuys = $joint_array[$y]['buys'][$x]['listings'] * $joint_array[$y]['buys'][$x]['quantity'] + $totalbuys;
  147.                     $totalbuyprice = $joint_array[$y]['buys'][$x]['listings'] * $joint_array[$y]['buys'][$x]['quantity'] * $joint_array[$y]['buys'][$x]['unit_price'];
  148.                     $countB = $x;
  149.                     if ($totalbuys >= 1000){
  150.                         break;
  151.                     }
  152.                 }
  153.                
  154.                 for ($x=0;$x<sizeof($joint_array[$y]['sells']);$x++) {
  155.                     $totalsells = $joint_array[$y]['sells'][$x]['listings'] * $joint_array[$y]['sells'][$x]['quantity'] + $totalsells;
  156.                     $totalsellprice = $joint_array[$y]['sells'][$x]['listings'] * $joint_array[$y]['sells'][$x]['quantity'] * $joint_array[$y]['sells'][$x]['unit_price'];
  157.                     $countS = $x;
  158.                     if ($totalsells >= 1000){
  159.                         break;
  160.                     }
  161.                 }
  162.                
  163.                 if (($totalsells >= 1000) && ($totalbuys >= 1000)){
  164.                     $totalbuyprice = $totalbuyprice - ($totalbuys - 1000)* $joint_array[$y]['buys'][$countB]['unit_price'];
  165.                     $totalsellprice = $totalsellprice - ($totalsells - 1000)* $joint_array[$y]['sells'][$countS]['unit_price'];
  166.                                
  167.                     $ratio = $totalbuyprice / ($totalsellprice + $totalbuyprice);
  168.                     $ratio_small = number_format((float)$ratio, 2, '.', '');
  169.                 } else {
  170.                     $ratio_small = 0;
  171.                 }
  172.  
  173.                 $db->exec("CREATE TABLE IF NOT EXISTS rating (Id INTEGER PRIMARY KEY, itemnumber INTEGER, itemname TEXT, itemratio REAL)");  
  174.                    
  175.                     # Prepare the query ONCE
  176.                     $stmt = $db->prepare('INSERT INTO rating (itemnumber, itemname, itemratio) VALUES(:number, :name, :ratio)');
  177.                     $stmt->bindParam(':number', $itemnumber, SQLITE3_INTEGER);
  178.                     $stmt->bindParam(':name', $itemname, SQLITE3_TEXT);
  179.                     $stmt->bindParam(':ratio', $itemratio, SQLITE3_FLOAT);
  180.                
  181.                     # Insert values and execute statements
  182.                     $idnumber = $joint_array[$y]['id'];
  183.                     #echo $joint_array[$y][id];'<br>';
  184.                     $alreadyinDBcheck = $db->query("SELECT * FROM rating WHERE itemnumber LIKE '$idnumber'");
  185.                         $found=0;
  186.                         foreach($alreadyinDBcheck as $row)
  187.                             {
  188.                                 $found=1;
  189.                             }  
  190.                         if ($found==0) {
  191.                             $itemratio = $ratio_small;
  192.                             $itemnumber = $joint_array[$y]['id'];
  193.                             $itemname = $joint_array[$y]['name'];
  194.                             $stmt->execute();
  195.                         } else {
  196.                             $db->exec("UPDATE rating SET itemratio='$ratio_small' WHERE itemnumber LIKE '$joint_array[$y][id]'");
  197.                             #echo ' already in DB <br>';
  198.                             }
  199.                                                    
  200.                
  201.            
  202.             }
  203.         }
  204.  
  205.         # add creation timestamp
  206.         date_default_timezone_set("Europe/Amsterdam");
  207.         $time = "This page has been updated at " . date("d-m-Y h:i:sa"). "<br><br>";
  208.         $db->exec("CREATE TABLE IF NOT EXISTS creationtime (Id INTEGER PRIMARY KEY, timestring TEXT)");
  209.             $stmt = $db->prepare('INSERT INTO creationtime (timestring) VALUES(:time)');
  210.             $stmt->bindParam(':time', $timestring, SQLITE3_TEXT);
  211.             $timestring = $time;
  212.             $stmt->execute();
  213.            
  214.         # Clear the table
  215.         #$db-> exec ('DELETE FROM rating');
  216.         #$db-> exec ('DELETE FROM alltheitems');
  217.        
  218.         # close the database connection
  219.         $db = NULL;
  220.  
  221.     }
  222.    
  223.     catch(PDOException $e) {
  224.     echo 'ERROR: ' . $e->getMessage();
  225. }
  226.  
  227.  
  228.  
  229.  
  230. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement