shoyebzz

AWS website information API

Mar 31st, 2020
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.80 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Makes a request to AWIS for site info.
  4.  */
  5. class UrlInfo {
  6.  
  7.     protected static $ActionName        = 'UrlInfo';
  8.     protected static $ResponseGroupName = 'Rank,RankByCountry';
  9.     protected static $ServiceHost      = 'awis.amazonaws.com';
  10.     protected static $ServiceEndpoint  = 'awis.us-west-1.amazonaws.com';
  11.     protected static $NumReturn         = 10;
  12.     protected static $StartNum          = 1;
  13.     protected static $SigVersion        = '2';
  14.     protected static $HashAlgorithm     = 'HmacSHA256';
  15.     protected static $ServiceURI = "/api";
  16.     protected static $ServiceRegion = "us-west-1";
  17.     protected static $ServiceName = "awis";
  18.  
  19.  
  20.     public function UrlInfo($accessKeyId, $secretAccessKey, $site) {
  21.         $this->accessKeyId = $accessKeyId;
  22.         $this->secretAccessKey = $secretAccessKey;
  23.         $this->site = $site;
  24.         $now = time();
  25.         $this->amzDate = gmdate("Ymd\THis\Z", $now);
  26.         $this->dateStamp = gmdate("Ymd", $now);
  27.  
  28.     }
  29.  
  30.     /**
  31.      * Get site info from AWIS.
  32.      */
  33.     public function getUrlInfo() {
  34.         $canonicalQuery = $this->buildQueryParams();
  35.         $canonicalHeaders =  $this->buildHeaders(true);
  36.         $signedHeaders = $this->buildHeaders(false);
  37.         $payloadHash = hash('sha256', "");
  38.         $canonicalRequest = "GET" . "\n" . self::$ServiceURI . "\n" . $canonicalQuery . "\n" . $canonicalHeaders . "\n" . $signedHeaders . "\n" . $payloadHash;
  39.         $algorithm = "AWS4-HMAC-SHA256";
  40.         $credentialScope = $this->dateStamp . "/" . self::$ServiceRegion . "/" . self::$ServiceName . "/" . "aws4_request";
  41.         $stringToSign = $algorithm . "\n" .  $this->amzDate . "\n" .  $credentialScope . "\n" .  hash('sha256', $canonicalRequest);
  42.         $signingKey = $this->getSignatureKey();
  43.         $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  44.         $authorizationHeader = $algorithm . ' ' . 'Credential=' . $this->accessKeyId . '/' . $credentialScope . ', ' .  'SignedHeaders=' . $signedHeaders . ', ' . 'Signature=' . $signature;
  45.  
  46.         $url = 'https://' . self::$ServiceHost . self::$ServiceURI . '?' . $canonicalQuery;
  47.         $ret = self::makeRequest($url, $authorizationHeader);
  48.         //echo "\nResults for " . $this->site .":\n\n";
  49.         //echo $ret;
  50.         return self::parseResponse($ret);
  51.     }
  52.  
  53.     protected function sign($key, $msg) {
  54.         return hash_hmac('sha256', $msg, $key, true);
  55.     }
  56.  
  57.     protected function getSignatureKey() {
  58.         $kSecret = 'AWS4' . $this->secretAccessKey;
  59.         $kDate = $this->sign($kSecret, $this->dateStamp);
  60.         $kRegion = $this->sign($kDate, self::$ServiceRegion);
  61.         $kService = $this->sign($kRegion, self::$ServiceName);
  62.         $kSigning = $this->sign($kService, 'aws4_request');
  63.         return $kSigning;
  64.     }
  65.  
  66.     /**
  67.      * Builds headers for the request to AWIS.
  68.      * @return String headers for the request
  69.      */
  70.     protected function buildHeaders($list) {
  71.         $params = array(
  72.             'host'            => self::$ServiceEndpoint,
  73.             'x-amz-date'      => $this->amzDate
  74.         );
  75.         ksort($params);
  76.         $keyvalue = array();
  77.  
  78.         foreach($params as $k => $v) {
  79.             if ($list)
  80.               $keyvalue[$k] = $k . ':' . $v;
  81.             else {
  82.               $keyvalue[] = $k;
  83.             }
  84.         }
  85.         return ($list) ? implode("\n",$keyvalue) . "\n" : implode(';',$keyvalue) ;
  86.     }
  87.  
  88.     /**
  89.      * Builds query parameters for the request to AWIS.
  90.      * Parameter names will be in alphabetical order and
  91.      * parameter values will be urlencoded per RFC 3986.
  92.      * @return String query parameters for the request
  93.      */
  94.     protected function buildQueryParams() {
  95.         $params = array(
  96.             'Action'            => self::$ActionName,
  97.             'Count'             => self::$NumReturn,
  98.             'ResponseGroup'     => self::$ResponseGroupName,
  99.             'Start'             => self::$StartNum,
  100.             'Url'               => $this->site
  101.         );
  102.         ksort($params);
  103.         $keyvalue = array();
  104.         foreach($params as $k => $v) {
  105.             $keyvalue[] = $k . '=' . rawurlencode($v);
  106.         }
  107.         return implode('&',$keyvalue);
  108.     }
  109.  
  110.     /**
  111.      * Makes request to AWIS
  112.      * @param String $url   URL to make request to
  113.      * @param String authorizationHeader  Authorization string
  114.      * @return String       Result of request
  115.      */
  116.     protected function makeRequest($url, $authorizationHeader) {
  117.         //echo "\nMaking request to:\n$url\n";
  118.         $ch = curl_init($url);
  119.         curl_setopt($ch, CURLOPT_TIMEOUT, 4);
  120.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  121.         curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  122.           'Accept: application/xml',
  123.           'Content-Type: application/xml',
  124.           'X-Amz-Date: ' . $this->amzDate,
  125.           'Authorization: ' . $authorizationHeader
  126.         ));
  127.         $result = curl_exec($ch);
  128.         curl_close($ch);
  129.         return $result;
  130.     }
  131.  
  132.     /**
  133.      * Parses XML response from AWIS and displays selected data
  134.      * @param String $response    xml response from AWIS
  135.      */
  136.     public static function parseResponse($response) {
  137.         $xml = new SimpleXMLElement($response,LIBXML_ERR_ERROR,false,'http://awis.amazonaws.com/doc/2005-07-11');
  138.         //return $response;
  139.         if($xml->count() && $xml->Response->UrlInfoResult->Alexa->count())
  140.         {
  141.             $info = $xml->Response->UrlInfoResult->Alexa;
  142.             $nice_array = array(
  143.                 //'Links In Count' => $info->ContentData->LinksInCount,
  144.                 'Rank'           => $info->TrafficData->Rank,
  145.                 'RankByCountry'  => (object) array()
  146.             );
  147.  
  148.             foreach ($info->TrafficData->RankByCountry->Country as $key => $value)
  149.             {
  150.                 $attr = (array) $value->attributes();
  151.                 $nice_array['RankByCountry']->Country[$attr['@attributes']['Code']] = $value;
  152.             }
  153.         }
  154.  
  155.         //$apiInfo = array();
  156.         //foreach($nice_array as $k => $v) {
  157.             //echo $k . ': ' . $v ."\n <br>";
  158.             //$apiInfo[$k] = $v;
  159.             //array_push($apiInfo, $v);
  160.         //}
  161.  
  162.         //return $apiInfo;
  163.         return $nice_array;
  164.     }
  165.  
  166. }
  167.  
  168.  
  169.  
  170. $urlInfo = new UrlInfo($accessKeyId, $secretAccessKey, $site);
  171.  
  172. $getSiteInfo = $urlInfo->getUrlInfo();
  173.  
  174. //print_r($getSiteInfo);
  175.  
  176.  
  177. function xml2array ( $getSiteInfo, $out = array () )
  178. {
  179.     foreach ( (array) $getSiteInfo as $index => $node )
  180.         $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
  181.  
  182.     return $out;
  183. }
  184.  
  185. $fstLevel = xml2array($getSiteInfo['RankByCountry']);
  186. $countryRank = xml2array($fstLevel['Country']['US']);
  187.  
  188.  
  189. echo "Rank : ". $getSiteInfo['Rank']."<br>";
  190. echo "US Rank : ". $countryRank['Rank'];
  191.  
  192. ?>
Advertisement
Add Comment
Please, Sign In to add comment