<?php
  if (isset($_REQUEST['url']) || strtolower($_SERVER['REQUEST_URI']) != '/tinyurlapi') {
    $reverse_lookup = false;
        
    if (!isset($_REQUEST['url'])) {
      $request_url = preg_replace('/^\/tinyurlapi\//', 'http://', $_SERVER['REQUEST_URI']);
    } else {
      $request_url = $_REQUEST['url'];
    }
        
    // doesn't need encoding anymore!
    $query_url = "http://is.gd/api.php?longurl=" . $request_url;
    
    if (preg_match('/tinyurl.com\/(.*)$/', $request_url, $matches)) {
      $reverse_lookup = true;
      // just in case
      $query_url = 'http://preview.tinyurl.com/' . $matches[1];
    } 
        
    $callback = isset($_REQUEST['callback']) ? $_REQUEST['callback'] : 'tinyurlCallback';
    $url = 'null';
    
    $dom = new DOMDocument();

    if (@$dom->loadHTMLFile($query_url)) {
      if ($reverse_lookup) {
        $xpath = new DOMXPath($dom);
        $query = "//blockquote/b";

        $entries = $xpath->query($query);
        if ($entries->length) {
            $url = '"' . $entries->item(0)->nodeValue . '"';
        }
      } else {
        $xpath = new DOMXPath($dom);
        $query = "//p";

        $entries = $xpath->query($query);
        if ($entries->length) {
            $url = '"' . $entries->item(0)->nodeValue . '"';
        }
      }
    } 
    
    echo "$callback($url);";
    exit();
  }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en">
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>TinyURL API</title>
    <style type="text/css" media="screen">
    <!--
      BODY { margin: 10px; padding: 0; font: 1em "Trebuchet MS", verdana, arial, sans-serif; }
      BODY { font-size: 100%; }
      H1 { margin-bottom: 2px; font-family: Garamond, "Times New Roman", Times, Serif;}
      DIV.container { margin: auto; width: 90%; margin-bottom: 10px;}
      TEXTAREA { width: 80%;}
      FIELDSET { border: 1px solid #ccc; padding: 1em; margin: 0; }
      LEGEND { color: #ccc; font-size: 120%; }
      INPUT, TEXTAREA { font-family: Arial, verdana; font-size: 125%; padding: 7px; border: 1px solid #999; }
      LABEL { display: block; margin-top: 10px; } 
      IMG { margin: 5px; }
      PRE { display: block; padding: 10px!important; background-color: #eee; border: 1px solid #666; font-family: Monica, Courier; Monospace; }
      DIV#submitted { padding: 5px; border: 1px solid #ccc; margin: 10px 0; }
      DIV#submitted P { margin: 5px; }
    -->
    </style>
    <link rel="stylesheet" href="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css" type="text/css" media="screen" charset="utf-8" />
    <script src="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js" type="text/javascript" charset="utf-8"></script>

    <script type="text/javascript" charset="utf-8">
      var urlInput;
      window.onload = function() {
        prettyPrint();
        // hook demo
        document.getElementById('demo').onsubmit = function() {
          var s = document.createElement('script');
          var v = document.getElementById('url').value;
          
          s.setAttribute('src', window.location + '?callback=tinyurlCallback&url=' + v);
          document.body.appendChild(s);

          return false;
        };
        urlInput = document.getElementById('url');
        urlInput.value = window.location;
      };
      
      function tinyurlCallback(url) {
        alert('URL converted to: ' + url);
        var p = document.createElement('p');
        var t = document.createTextNode(urlInput.value + ' converted to ');
        p.appendChild(t);
        var a = document.createElement('a');
        a.href = url;
        a.appendChild(document.createTextNode(url));
        p.appendChild(a);
        
        document.getElementById('submitted').appendChild(p);
      }
    </script>
  </head>
  <body id="page">
    <div id="doc">
        <h1>TinyURL Callback API</h1>
        <h2>Info</h2>
        <p>The <a href="http://tinyurl.com">TinyURL</a> allows the dynamic creation of TinyURLs on the fly using JavaScript.</p>
        <h2>Usage</h2>
        <p>Call the external script from your web application and pass once the URL is converted, it will pass it back via the 'callback' parameter.</p>
        <p>To preform a reverse lookup on a tinyurl, just pass the 'tinyurl' to the API and it will workout and return where it points to.</p>
        <h2>Example</h2>
        <pre class="prettyprint">
&lt;script type="text/javascript" charset="utf-8"&gt;
window.onload = function() {
  var s = document.createElement('script');
  var v = document.getElementById('url').value;
  <?php echo "s.setAttribute('src', 'http://" . $_SERVER['HTTP_HOST'] . "/tinyurlapi?callback=tinyurlCallback&amp;url=' + v);\n" ?>
  document.body.appendChild(s);
}

function tinyurlCallback(url) {
  alert('URL converted to: ' + url);
}
&lt;/script&gt;</pre>
      <h2>Demo</h2>
      <form action="" method="get" id="demo" accept-charset="utf-8">
        <label for="url">URL:</label> <input size="50" type="text" name="url" value="http://" id="url" />
        <input type="submit" value="Convert &rarr;" />
      </form>
      <div id="submitted">
        <p>Submitted URLs:</p>
      </div>
    </div>
  </body>
</html>
