RU/Resource Web Access
The Multi Theft Auto Server provides a web interface that resources can use in a variety of ways. This document's purpose is to explain what these ways are and how to go about using them.
Краткий обзор
Есть две ключевые роли, которые составляют эту систему. Первой является стандартный веб-сервер, открывающий веб-браузерам возможность просматривать страницы и файлы, отмеченные в ресурсе. Второй является система позволяющая веб-браузерам вызывать функции, которые вы экспортировали из ресурса.
Pages
Добавление файла в meta
Вы можете обозначить в meta файле своего ресурса, определенные данные доступные через веб-сервер. Чтобы сделать это, добавьте строку:
<html src="filename" />
Вы можете получить доступ к этому файлу через веб-браузер, перейдя по следующей ссылке: http://host:port/resourcename/filename
Бинарные файлы
Несмотря на вводящее в заблуждение название, было определено, что при использовании узла html файл может иметь любой тип. Если это - бинарные файлы (изображения, сжатые файлы) тогда, вы должны обозначить их в meta файле, добавляя raw = "true" в конце строки html. Это означает, что файлы не будут предварительно обработаны прежде, чем они передадутся веб-браузеру.
Пример:
<html src="image.gif" raw="true" />
Parsed files
If a file is not specified in the meta file as "raw", then it is passed through a pre-processor before it is returned to the client. This pre-processor works much like PHP or ASP, but uses LUA. You can embed standard MTA scripts within HTML pages, controlling the output. Almost all standard MTA functions work, plus a number of special HTTP Functions, such as httpWrite, a function that outputs text to the buffer.
Пример:
[html] <html> <body> This resource is called <* httpWrite( getResourceName(getThisResource()) ) *> </body> <html>
There is a shorthand (in common with PHP and ASP) for this code, meaning that you can also write the above code as:
[html] <html> <body> This resource is called <* = getResourceName(getThisResource()) *> </body> <html>
Aside from HTTP functions, embedded Lua has access to the following environment variables that contain information about how the page was requested:
- table requestHeaders: This is a table containing all the headers that were requested with the page. You can set returned headers using httpSetResponseHeader.
- table form: This is a table containing all the form data submitted to the page using HTTP POST combined with any variables passed in the querystring with HTTP GET.
- table cookies: This is a table of all the cookies. You can modify cookies using httpSetResponseCookie.
- string hostname: This is a string containing the IP address or hostname that requested the page.
- string url: This is the URL of the page.
- account user: This is the account of the current user.
It's important to note that parsed files are run in a separate virtual machine from the rest of your resource's code. As such, if you want to call a function in your resource's main code, you need to export the function and use the call function from your parsed file.
Calls
You can specify that certain exported functions in your resource are able to be called from the HTTP interface. All the SDKs (listed below) allow you to call these functions from a remote location.
To specify an exported http-accessible function, add the following to your meta.xml file:
<export function='functionName' http='true' />
You can code your function just as you would any normal function, returning as many values as you want, including tables and resources and most importantly elements. You cannot however return other 'userdata' values such as xmlnodes or functions.
Calls from the HTTP web interface
Using calls is probably easiest from the web interface and can be done almost seamlessly.
First, add this to your meta.xml file:
<include resource="ajax" />
Secondly, add the following to the <head> section of the page you want to call from:
<* = call ( getResourceFromName("ajax"), "start", getResourceName(getThisResource()) ) *>
Finally, you can create a javascript block in your page and call your functions almost as if they were local. The only difference is that the calls are aysnchronous - you should specify a callback function as the last argument for your call. This is called when the function returns.
Here's a simple example.
meta.xml
<meta> <include resource="ajax" /> <script src='code.lua' /> <html src='page.htm' default='true' /> <export function='showChatMessage' http='true' /> </meta>
code.lua
function showChatMessage ( message ) outputChatBox ( message ) return 5; end
page.htm
[html] <html> <head> <* = call ( getResourceFromName("ajax"), "start", getResourceName(getThisResource()) ) *> <script type='text/javascript'> function say() { var message = document.getElementById('message') showChatMessage ( message.value, function ( number ) { // the function has been called and returned something message.value = "The function returned " + number; } ); } </script> </head> <body> <input type='text' id='message' /><input type='button' value='say' onclick='say();' /> </body> </html>
You can see (fairly complex) examples of how this can be done in the resources resourcebrowser, resourcemanager and webadmin.
SDK
There are a number of so-called 'SDKs' available that allow you to interface with the server from other programming languages. With these you could (in theory) write whole gamemodes. In practice this is probably a bad idea, but it is useful for statistics and administration. The PHP SDK is the most developed version. Feel free to modify or create your own SDKs - if you do please send us a copy.
See Also
callRemote - Allows game servers to call functions on PHP pages (with the PHP SDK) and on other game servers.