Resource Web Access: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
Line 26: Line 26:
Si un archivo no se ha especificado en el archivo de metadatos como "cruda", entonces se pasa a través de un pre-procesador antes de que se devuelve al cliente. Este procesador pre-funciona como PHP o ASP, pero utiliza LUA. Puede incrustar secuencias de comandos estándar del MTA dentro de las páginas HTML, el control de la salida. Casi todos los estándares de trabajo MTA funciones, además de un número especial de [[Plantilla: Funciones | Funciones HTTP HTTP]], como [[httpWrite]], una función que envía texto al buffer.
Si un archivo no se ha especificado en el archivo de metadatos como "cruda", entonces se pasa a través de un pre-procesador antes de que se devuelve al cliente. Este procesador pre-funciona como PHP o ASP, pero utiliza LUA. Puede incrustar secuencias de comandos estándar del MTA dentro de las páginas HTML, el control de la salida. Casi todos los estándares de trabajo MTA funciones, además de un número especial de [[Plantilla: Funciones | Funciones HTTP HTTP]], como [[httpWrite]], una función que envía texto al buffer.


For example:
Por ejemplo:
<syntaxhighlight lang="lua" lang="html">
<syntaxhighlight lang="lua" lang="html">
<html>
<html>
     <body>
     <body>
         This resource is called <* httpWrite( getResourceName(getThisResource()) ) *>
         Este recurso se llama <* httpWrite( getResourceName(getThisResource()) ) *>
     </body>
     </body>
<html>
<html>
</syntaxhighlight>
</syntaxhighlight>


There is a shorthand (in common with PHP and ASP) for this code, meaning that you can also write the above code as:
Hay un atajo (en común con PHP y ASP) para este código, lo que significa que también se puede escribir el código anterior como:


<syntaxhighlight lang="lua" lang="html">
<syntaxhighlight lang="lua" lang="html">
<html>
<html>
     <body>
     <body>
         This resource is called <* = getResourceName(getThisResource()) *>
         Este recurso se llama <* = getResourceName(getThisResource()) *>
     </body>
     </body>
<html>
<html>
</syntaxhighlight>
</syntaxhighlight>


Aside from HTTP functions, embedded Lua has access to the following environment variables that contain information about how the page was requested:
Aparte de las funciones HTTP, integrado Lua tiene acceso a las siguientes variables de entorno que contienen información acerca de cómo la página se solicita:
* table '''requestHeaders''': This is a table containing all the headers that were requested with the page. You can set returned headers using [[httpSetResponseHeader]].  
* Mesa'' 'requestHeaders''': Esta es una tabla que contiene todas las cabeceras que se solicitaron a la página. Puede configurar las cabeceras devueltas mediante [[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.
* Tabla'' 'form''': Esta es una tabla que contiene todos los datos del formulario presentado a la página utilizando HTTP POST combinar con cualquier variables pasadas en la cadena de consulta con HTTP GET.
* table '''cookies''': This is a table of all the cookies. You can modify cookies using [[httpSetResponseCookie]].
* Tabla'' 'cookies''': Esta es una tabla de todas las cookies. Puede modificar las cookies usando [[httpSetResponseCookie]].
* string '''hostname''': This is a string containing the IP address or hostname that requested the page.
* Cadena'' 'hostname''': Esta es una cadena que contiene la dirección IP o el nombre de host que solicita la página.
* string '''url''': This is the URL of the page.
* Cadena'' 'url''': Esta es la URL de la página.
* account '''user''': This is the account of the current user.
Cuenta *'' 'user''': Esta es la cuenta de usuario actual.


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.
Es importante tener en cuenta que los archivos analizados se ejecutan en una máquina virtual independiente del resto del código de su recurso. Por lo tanto, si desea llamar a una función en el código de su principal recurso, es necesario exportar la función y el uso de la [[llamada]] función de su archivo analizado.


==Calls==
==Calls==

Revision as of 22:20, 21 December 2012

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.

Visión de conjunto

Hay dos partes principales que componen este sistema. El primero es un servidor web estándar que permite a los navegadores de Internet para solicitar páginas y archivos que tienes en un recurso. El segundo es un sistema para permitir que los navegadores de Internet para llamar a las funciones que ha exportado de su recurso.

Paginas

Espesificación de un archivo meta

Tu puedes especificar en su archivo de datos meta de recursos de que ciertos archivos sean accesibles a través del servidor web. Para eso, puedes agregar estas lineas:

<html src="filename.ext" />

Tambien puedes acceder a este archivo de navegador web en: http://host:port/resourcename/filename.ext
Por ejemplo, en un servidor alojado localmente utilizando el puerto HTTP predeterminado con webmap comenzó: http://127.0.0.1:22005/webmap/map.htm


Archivos Binarios

A pesar del nombre engañoso, los archivos especificados mediante el nodo html pueden ser de cualquier tipo. Si son archivos binarios (como imágenes, archivos zip), entonces usted tiene que especificar esto en el archivo meta, mediante la adición de crudo = "true" al nodo html. Esto significa que los archivos no se preprocesa antes de ser enviado al navegador web.

Por ejemplo:

<html src="image.gif" raw="true" />

Analizada archivos

Si un archivo no se ha especificado en el archivo de metadatos como "cruda", entonces se pasa a través de un pre-procesador antes de que se devuelve al cliente. Este procesador pre-funciona como PHP o ASP, pero utiliza LUA. Puede incrustar secuencias de comandos estándar del MTA dentro de las páginas HTML, el control de la salida. Casi todos los estándares de trabajo MTA funciones, además de un número especial de Funciones HTTP HTTP, como httpWrite, una función que envía texto al buffer.

Por ejemplo:

<html>
    <body>
        Este recurso se llama <* httpWrite( getResourceName(getThisResource()) ) *>
    </body>
<html>

Hay un atajo (en común con PHP y ASP) para este código, lo que significa que también se puede escribir el código anterior como:

<html>
    <body>
        Este recurso se llama <* = getResourceName(getThisResource()) *>
    </body>
<html>

Aparte de las funciones HTTP, integrado Lua tiene acceso a las siguientes variables de entorno que contienen información acerca de cómo la página se solicita:

  • Mesa 'requestHeaders': Esta es una tabla que contiene todas las cabeceras que se solicitaron a la página. Puede configurar las cabeceras devueltas mediante httpSetResponseHeader.
  • Tabla 'form': Esta es una tabla que contiene todos los datos del formulario presentado a la página utilizando HTTP POST combinar con cualquier variables pasadas en la cadena de consulta con HTTP GET.
  • Tabla 'cookies': Esta es una tabla de todas las cookies. Puede modificar las cookies usando httpSetResponseCookie.
  • Cadena 'hostname': Esta es una cadena que contiene la dirección IP o el nombre de host que solicita la página.
  • Cadena 'url': Esta es la URL de la página.

Cuenta * 'user': Esta es la cuenta de usuario actual.

Es importante tener en cuenta que los archivos analizados se ejecutan en una máquina virtual independiente del resto del código de su recurso. Por lo tanto, si desea llamar a una función en el código de su principal recurso, es necesario exportar la función y el uso de la llamada función de su archivo analizado.

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.

Protocol

This template is no longer in use as it results in poor readability.

Calls are done by requesting http://<your IP>:<your port>/<resource_name>/call/<exported_function_name> using HTTP POST. The body of the request should be a JSON array of the arguments for the function.

The request will return a JSON array of the value(s) returned from the function as the HTTP response.

The server supports HTTP Basic authentication and you can configure access via the ACL and the built-in accounts system.

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:

<* = exports.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>
    <head>
        <* = exports.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.

Securing the web interface

The ACL has a number of rights that can affect what files can be accessed.

This works as with other ACL rights - You can enable it just for Admin users, or any other group of users you wish.

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.