<?php

if ( $apiHandle ) {

$curlRequest = stream_get_line ( $apiHandle , 4096 ) ;

fclose ( $apiHandle ) ;

if ( ! empty ( $curlRequest ) ) {

$jsonApi = json_decode ( $curlRequest ) ;

if ( $jsonApi -> result == true ) {

if ( $jsonApi -> data -> status == 'NOTACKED' ) {

// show ack form

$tac = $_GET [ 'tac' ] ;

$token = $_GET [ 'token' ] ;

$baseUrl = '?appId=' . urlencode ( $appId ) . '&signed=' . urlencode ( $signed ) . '&username=' . urlencode ( $_GET [ 'username' ] ) . '&token=' . urlencode ( $jsonApi -> data -> token ) ;

if ( ! empty ( $tac ) && ! empty ( $token ) ) {

$tokenRes = do_mysql_query ( 'SELECT userid FROM authtokens WHERE token = \'' . mysql_escape_string ( $token ) . '\'' ) ;

if ( mysql_num_rows ( $tokenRes ) > 0 ) {

$tokenRow = mysql_fetch_array ( $tokenRes ) ;

if ( $tokenRow [ 'userid' ] == $CURUSER [ 'id' ] ) {

if ( $tac == 'ACK' ) {

do_mysql_query ( 'UPDATE authtokens SET state = \'VALID\' WHERE token = \'' . mysql_escape_string ( $token ) . '\'' ) ;

if ( ! empty ( $appRedirectUrl ) ) {

$newUrl = $appRedirectUrl . '?state=VALID&token=' . urlencode ( $token ) ;

header ( 'Location: ' . $newUrl ) ;

} else {

echo "<p>Thank you - request now marked as accepted</p>" ;

}

} else if ( $tac == 'REJECT' ) {

do_mysql_query ( "DELETE FROM authtokens WHERE token = '" . mysql_escape_string ( $token ) . '\'' ) ;

if ( ! empty ( $appRedirectUrl ) ) {

$newUrl = $appRedirectUrl . '?state=REJECTED' ;

header ( 'Location: ' . $newUrl ) ;

} else {

echo "<p>Thank you - the request was rejected</p>" ;

}

} else {

echo "<p>Sorry don't understand that TAC</p>" ;

}

} else {

echo "<p>You can't perform actions on other tokens than your own!</p>" ;

}

} else {

echo "<p>Don't fiddle with our URLs buddy!</p>" ;

}

} else {

echo "<p>Please either <a href= \" $baseUrl &tac=ACK \" >Accept</a> or <a href= \" $baseUrl &tac=REJECT \" >reject</a> it.</p>" ;

}

} else if ( $jsonApi -> data -> status == 'VALID' ) {

if ( ! empty ( $appRedirectUrl ) ) {

$newUrl = $appRedirectUrl . '?state=VALID&token=' . urlencode ( $jsonApi -> data -> token ) ;

header ( 'Location: ' . $newUrl ) ;

} else {

echo "<p>You've already approved this once</p>" ;

}

} else {

echo "<p>Problem with token - create helpdesk ticket</p>" ;

}

} else {

echo "<p>Error happened while talking to API - create ticket in helpdesk</p>" ;

}

} else {

echo "<p>Error happened while talking to API - create ticket in helpdesk</p>" ;

}

} else {

echo "<p>Could not reach API - create ticket in Helpdesk!</p>" ;

}