Scripting
Scripting allows you to create basic to complex web applications at the XWiki page (or view) layer without the need for compiling code or deploying software components. In other words, you can use scripting syntax in addition to wiki markup inside the content of an XWiki page (e.g. see the script syntax for the XWiki 2.1 syntax).
XWiki integrates jsr-223 scripting. You can script using several available languages by using the generic Script Macro or one of following specific macros:
- Velocity Macro (installed by default in XWiki)
- Groovy Macro (installed by default in XWiki)
- Python Macro (installed by default in XWiki)
- Ruby Macro (not installed by default in XWiki)
- PHP Macro (not installed by default in XWiki)
Permissions
Starting with XWiki 7.2M1, a user needs to have the Script Permission in order to be able to write Script.
In addition, all scripting languages other than Velocity also require Programming Rights (see below for more details).
Choosing a Scripting language
Since XWiki supports several scripting languages you might be wondering which one to use. Most of the code written by XWiki developers is in Velocity, with a few more complex extensions written in Groovy; these two are thoroughly tried and tested, so they are both a safe bet. The other languages should work just as well, but there are less developers that could help answering any questions.
Velocity
The first thing to know is that Velocity is different from the other scripting languages on 2 aspects:
- It's a templating language rather than a pure scripting language, which means that its content is actually wiki markup interspersed with Velocity directives, whereas pure scripting languages are written in that language and they need to explicitly output wiki markup. For example:
Velocity:
{{velocity}}
Your username is $xcontext.getUser(), welcome to the site.
{{/velocity}}Groovy:
{{groovy}}
println("Your username is " + xcontext.getUser() + " welcome to the site.");
{{/groovy}} - It doesn't require special permissions (other than Script Permission starting with XWiki 7.2M1) since it runs in a Sandbox, with access to only a few safe objects, and each API call will check the rights configured in the wiki, forbidding access to resources or actions that the current user shouldn't be allowed to retrieve/perform. Other scripting language require the user that wrote the script to have Programming Rights to execute them, but except this initial precondition, access is granted to all the resources on the server. Note that starting with XWiki 4.1 we've introduced a Sandbox for Groovy too, but it's still in an early stage and is currently very restrictive.
Being a templating engine, Velocity doesn't offer many means of structuring code. In fact, there's only one useful directive in this regard, #macro. However, because it is a templating engine, its syntax is much simpler and easier to understand by non-developers, which means that it's accessible to a wider range of users, without a serious background in programming.
Without Programming Rights, it's impossible to instantiate new objects, except literals and those safely offered by the XWiki APIs. Nevertheless, the XWiki API is powerful enough to allow a wide range of applications to be safely developed, if "the XWiki way" is properly followed.
Velocity is also available in some other parts of XWiki: it is the language in which all the templates that generate the HTML UI of XWiki are written, it can be optionally activated in skin extensions, and it is executed when sending CSS and JavaScript skin resources from the filesystem.
In conclusion, Velocity is suited for projects with small to medium complexity, and which don't require access to other resources except the provided XWiki API and registered script services. It allows very quick and easy development, offers good security and decent performance, and can easily be packaged and distributed as a XAR.
Groovy
Groovy is a full-fledged scripting language, which supports almost the entire Java syntax, and provides its own syntax delicacies and custom APIs that enhance the Java language even further. While it is recommended that complex code be written in Java as components accessible via script services, Groovy has the advantage that it is written live in the wiki, without requiring compilation, deployment and server restarts, thus enabling faster development.
The XWiki API is available in the context when executing Groovy scripts, but unlike in Velocity, the code isn't limited to this API, and any other classes or objects can be accessed freely. New classes can be defined in Groovy, compatible with Java classes, and this allows more structured code to be written, unlike in Velocity. A particular case of classes is new component roles and component implementations, which allows, for example, new script services or new event listeners to be defined in the wiki. It is possible to load attached jar files into the classpath of an executing script, which means that a wiki document can contain a complex program AND its required libraries not already provided by the platform.
Other than being available as a scripting language for writing custom code, it is also the language in which scheduler tasks are written.
In conclusion, Groovy is suited for complex projects or for custom wiki enhancement through new components, when speedy live development is required. Being written in wiki documents, it can also be easily packaged and distributed as a XAR.
After taking into account these considerations and if requiring Programming Rights isn't an issue for you, you should pick the script language that you're most familiar with!
XWiki Scripting API
The API is documented in Javadoc format and can be accessed here: XWiki API Javadoc. If you are not familiar with Java or object oriented programming, you will probably be confused by the API documentation. It is not within the scope of our documentation to teach you all the details about Java, or object oriented programming. You can find all of that information already online. You can also explore the page code found throughout the Extensions wiki area to see how others have figured out how to achieve a variety of results.
We're also making available an API Guide with examples about using the XWiki API.
Bindings
The main objects available to you in scripting languages are:
- The current Document: doc
- The Context of the request: xcontext
- The Request object: request
- The Response object: response
- The XWiki object: xwiki
- The XWiki utils: util (this is deprecated)
- Various Script Services: services
See Scripting Reference Documentation for a complete list.
XWiki Component Access
Since XWiki 4.1M2+ there's a Script Service to access the Component Manager (see also: Accessing components from Groovy).
For example using Groovy you'd write:
def greeter = services.component.getInstance(org.xwiki.component.HelloWorld.class)
println greeter.sayHello()
{{/groovy}}
You can also get the ComponentManager with:
def cm = services.component.componentManager
{{/groovy}}
XWiki Core Access
Sometimes the XWiki Api doesn't provide the methods which you need for your application. You can gain raw access the core of XWiki but it presents an increased security risk and requires Programming Rights to be able to save the page containing the script (Programming Rights are not required for viewing a page containing a script requiring Programming Rights, rights are only needed at save time). Using the core should be avoided if at all possible.
def xc = xcontext.getContext();
def wiki = xc.getWiki();
def xdoc = doc.getDocument();
{{/groovy}}
After using this snippet, you will have 3 new objects:
- The underlying XWikiContext behind the Context object: xc
- The underlying XWiki object which backs the xwiki object: wiki
- The underlying XWikiDocument behind the current Document: xdoc
You will find that many of the methods in wiki and xdoc require an instance of the XWikiContext, this is the underlying xcontext xc not the Api context xcontext.
Again, these methods are only for the rare cases when functionality is not provided by the public Api. We put a lot of effort into preserving the behavior of the public Api and much less into preserving the behavior of core methods so you may find that core methods are deprecated, removed, or their behavior is changed in subsequent versions.
Querying XWiki's Model
From your script you can query the full XWiki Model. Check the Query Module for more information.
See also this HQL tutorial in Velocity.
Velocity Specific Information
Velocity is currently the only scripting language which can be used without Programming Access Rights. This means you can save Velocity scripts using a user with less permissions and nobody will be able to exploit your script to perform a security breach.
You can gain access to the XWiki core from Velocity but this will require Programming Rights. Strictly speaking, protected APIs are only available when the page that contains them was last saved by someone who had Programming Rights (see above).
In Velocity you can't import classes and as such you cannot gain direct access to XWiki components as shown above. This leaves you with the provided bindings (NOTE: In Velocity, these bindings all start with $ as with all other Velocity variables)
For more information about programming in the Velocity language, you can refer to the Velocity User Guide. See also this Velocity Training Presentation.
For more details on using Velocity check the Velocity Module Documentation which also contains the full list of Velocity Tools that you can use in your scripts.
To include Velocity scripts in other Velocity scripts, see How to include a Velocity page into another page.
Velocity Macros
See available Velocity macros.
Other Velocity Variables
Controlling Page Tabs
You can control whether to display Comments/Annotations/History/Attachment/Information tabs or not by setting some velocity variables to false:
#set ($showannotations = false)
#set ($showattachments = false)
#set ($showhistory = false)
#set ($showinformation = false)
To remove them all you can set:
You can also control whether shortcuts links are displayed in the page menu:
Control Content Footer
displayContentFooter binding.
The content footer can be controlled through theInformation about the current user
The following variables (set in the xwikivars.vm template) are shortcuts for checking various information for the current user:
- $isGuest: checks if the current user is XWiki.XWikiGuest
- $isSuperAdmin: checks if the current user is the special user superadmin
- $hasComment: checks comment rights on the current document
- $hasEdit: checks edit rights on the current document
- $hasWatch: checks if the user is authenticated and the watch service is available
- $hasAdmin: checks admin rights on the current document
- $hasSpaceAdmin: checks admin rights on the XWikiPreferences document of the current space
- $hasGlobalAdmin: checks admin rights on XWiki.XWikiPreferences
- $hasCreateSpace: checks edit rights on that page that does not exist, in a space that doesn't exist
- $hasCreatePage: checks edit rights on that page that does not exist, in the current space
- $hasProgramming: checks if the current user has programming rights
- $isAdvancedUser: advanced users: superadmin, users with the usertype property set to "Advanced", guest users with admin rights
Example:
#if ($hasAdmin)
## This link will only be visible to users that have admin rights on this document
[[Do some admin action>>Some.Document]]
#end
{{/velocity}}
Information about the current wiki
The following variables (set in the xwikivars.vm template) are shortcuts for checking various information about the current wiki:
- $isReadOnly
- $isInServletMode
- $isInPortletMode
Groovy Specific Information
- See Groovy snippets in the Snippets wiki (click on the "Groovy" tag in the Tag Cloud)
- Groovy web site
Groovy Example
The following example demonstrates how to use a groovy script to interact with velocity code in your page. This example performs a DNS lookup from the velocity variable $hostname and stores the result in the variable $address.
Using XWiki Syntax 2.0:
Objects can be passed back and forth between scripting languages by storing them in commonly available objects. One such commonly available object which only lasts the length of the request is the context object, known as xcontext.
#set($hostname = "www.xwiki.org")
Host Name: $hostname
$xcontext.put("hostname", $hostname)
{{/velocity}}
{{groovy}}
import java.net.InetAddress;
host = xcontext.get("hostname");
InetAddress addr = InetAddress.getByName(host);
String address = addr.getHostAddress();
xcontext.put("address", address);
{{/groovy}}
{{velocity}}
IP Address: $xcontext.get("address")
{{/velocity}}
Using XWiki Syntax 1.0:
Because Groovy and Velocity code are parsed together, variables defined in Groovy can be used directly in velocity without storing in and retrieving from the context.
Host Name: $hostname
<%
import java.net.InetAddress;
vcontext = context.get("vcontext");
host = vcontext.get("hostname");
InetAddress addr = InetAddress.getByName(host);
String address = addr.getHostAddress();
%>
IP Address: $address
Python Specific Information
You can run Python code in XWiki just like Velocity or Groovy.
print "The full name of this document is " + doc.getFullName()
{{/python}}
Share variable between languages
Most JSR223 based scripting languages reinject the created variable in the current ScriptContext which means you can define a variable in a Groovy script and reuse it in a following Python script for example.
Since the Velocity implementation isn't based on JSR223, we have also set up a bridge so that Velocity scripts can access the current ScriptContext variables. This allows for example to define a variable in a Groovy script and then reuse it in a Velocity one:
var = "foo"
{{/groovy}}
{{velocity}}
$var
{{/velocity}}
Starting with XWiki 8.3 the Velocity bridge has been improved and it's now possible to do the opposite, i.e. define a variable in Velocity and access it from another scripting language. For example:
#set($myvar = "foo")
{{/velocity}}
{{groovy}}
print myvar
{{/groovy}}
Note that you can also share variables by setting them in the XWiki Context (xcontext binding).
Scripting In XWiki Syntax 1.0
XWiki Syntax 1.0 is rendered by an old rendering engine which is still supported but for which no further development is planned (it will eventually be removed). Syntax 1.0 has some idiosyncrasies which were solved by syntax 2.0.
- The only scripting languages available to you are Velocity and Groovy.
- In Groovy, the context is known as: context not xcontext
- The beginning and end of Groovy scripts are denoted by <% and %> rather than through the Groovy Macro (using {{groovy}} and {{/groovy}})
- Velocity is parsed in a page no matter what (there is no need to invoke the Velocity Macro using {{velocity}} and {{/velocity}})
The last part is important because it means you need to be careful when using $ and # in your document. This is still true inside of <% and %> so you have to be careful when writing Groovy.