<?php
// Sample external tokenizer script 

// Config vars 
$key = "123456"; // this key must match the key entered in the WebTV configuration file (config/Config.inc.php) $EXTERNAL_URL_TOKENIZER_KEY = "....";

if (empty($_GET)) { echo json_encode( array("error"=>"no vars???..." )  ); exit; }

// ==================================== The data sent by the WebTV... ====================================
// When an URL requires a token, the WebTV will call this script with the following GET vars:
//  url            -> The URL that requires the token
//  signature      -> A signature for validating the request
$user_id   = (isset($_GET["user_id"]))? $_GET["user_id"] : 0; // If the User ID is -1 then the User is not logged in the WebTV
$user_ip   = (isset($_GET["user_ip"]))? urldecode($_GET["user_ip"]) : ""; 
$file_url  = (isset($_GET["url"]))? urldecode($_GET["url"]) : "";
$signature = (isset($_GET["signature"]))? rawurldecode($_GET["signature"]) : ""; // you should not need to use rawurldecode here, but if you are not gettting the signature correctly then use urldecode()

// Verify that you have received all the data
if ( !is_numeric($user_id) )  { echo json_encode( array("error"=>"invalid User ID..." )  ); exit; }
if ( $user_ip=="")            { echo json_encode( array("error"=>"invalid User IP..." )  ); exit; }
if ( $file_url=="")           { echo json_encode( array("error"=>"invalid URL..." )  ); exit; }
if ( $signature=="")          { echo json_encode( array("error"=>"invalid signature..." )  ); exit; }

// Now, generate a signature to compare against the one in the "signature" variable. 
$data = array(	
                "user_id"  => (int)$user_id,
                "user_ip"  => $user_ip,
                "url"      => $file_url
			);
$computed_signature = base64_encode(hash_hmac('sha256', json_encode($data), $key, true));

// If the generated signature is different than the received one then don't continue! 
if ( $computed_signature!=$signature) { echo json_encode( array("error"=>"hmmm, invalid signature...")); exit; }
// The signature guarantees that the data has not been altered. 
// If the signatures don't match, and you are sure the data has not been altered, 
// then check if the key supplied to the WebTV is the same key you are using in this script


// ==================================== Generate the token ====================================
// After validating the request, then generate the token and append it to the file URL...

// ...
// ...
// ...

$file_url .= "?token=xds56f4sadf86asdf87asdf4asd53"; // NOTE: This is just an example, the appearance of your token as well as the URL variables may be different than this

// ...
// ...
// ...


// ==================================== Returning the result to the WebTV ====================================
// The result must be a JSON encoded array with the resulting URL associated to the "url" index
echo json_encode( array( "url" => $file_url ));

?>