+ default:
+ print json_encode ( array( 'response' => 'invalid') );
+ }
+}
+else
+{
+ token_auth();
+
+ switch ( $_SERVER['PATH_INFO'] )
+ {
+ case "/ping":
+ // API clients are required to periodically ping the server
+ // The time between pings (interval) is 5 minutes?
+ // A ping call refreshes cookie lifetimes, then
+ // generates and stores a new auth_key
+ // The ping required a valid session...
+ // A successful ping returns a 'response' => 'pong'
+ // along with the new auth_key.
+ $session_name = $_GET['session'];
+ $authid = $_SESSION['authid'];
+ $auth_key = update_authkey( $session_name, $authid );
+ print json_encode( array( 'response' => 'pong', 'auth_key' => $auth_key ));
+ break;
+ case "/new_apikey":
+ // If the current authorization has write access, create
+ // a new API key with requested access (ro/rw).
+ if ( ! can_write() )
+ simple_authfail();
+
+ if ( array_key_exists('host_ip', $_GET )
+ && array_key_exists('access', $_GET ))
+ {
+ $host = $_GET['host_ip'];
+ $access = $_GET['access'];
+
+ if (! preg_match("/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $host) || ! authlevel_value( $access ) )
+ {
+ print json_encode ( array( 'response' => 'invalid', 'cause' => 'parameters' ) );
+ break;
+ }
+ $level = authlevel_value( $access );
+ $key = add_apikey( $host, $level );
+ if ( ! $key )
+ {
+ print json_encode( array( 'response' => 'failed', 'cause' => 'error', 'detail' => 'Database error.'));
+ break;
+ }
+ print json_encode( array( 'response' => 'ok', 'key' => $key, 'host' => $host, 'access' => authlevel_name( $level ) ) );
+ break;
+ }
+ else print json_encode ( array( 'response' => 'invalid') );
+ break;
+ case "/remove_apikey":
+ // If the current authorization has write access,
+ // remove the given API key.
+ if ( ! can_write() )
+ simple_authfail();
+
+ if ( array_key_exists('api_key', $_GET ) )
+ {
+ $key = sql_clean( $_GET['api_key'] );
+ // Perform a key-verification, skipping host/remote-address check.
+ if ( ! verify_apikey( $key, true ) )
+ {
+ print json_encode( array ( 'response' => 'failed', 'cause' => 'nonexistant'));
+ break;
+ }
+ if ( ! remove_apikey( $key ) )
+ {
+ print json_encode( array( 'response' => 'failed', 'cause' => 'error', 'detail' => 'Database error.'));
+ break;
+ }
+ print json_encode( array( 'response' => 'ok', 'key' => $key ) );
+ break;
+ }
+ else print json_encode ( array( 'response' => 'invalid') );
+ break;
+ case "/list_apikeys":
+ // List valid API keys.
+ // Fail is current authorization does not have write access.
+ if ( ! can_write() )
+ simple_authfail();
+ $list = list_apikeys();
+ print json_encode( array( 'response' => 'ok', 'list' => $list ) );
+ break;