Wiki source code of Scripting

Version 47.6 by Vincent Massol on 2014/10/03

Hide last authors
OCTAGRAM 24.1 1 {{box cssClass="floatinginfobox" title="**Contents**"}}
2 {{toc/}}
3 {{/box}}
Caleb James DeLisle 23.1 4
Vincent Massol 20.4 5 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 and HTML syntax as the contents of an XWiki page.
Vincent Massol 1.1 6
jvinarek 44.1 7 XWiki integrates [[jsr-223>>http://jcp.org/en/jsr/detail?id=223]] scripting. You can script using several available languages by using one of the following macros:
OCTAGRAM 24.1 8
Vincent Massol 30.3 9 * [[Velocity Macro>>extensions:Extension.Velocity Macro]] (installed by default in XWiki Enterprise)
10 * [[Groovy Macro>>extensions:Extension.Groovy Macro]] (installed by default in XWiki Enterprise)
11 * [[Python Macro>>extensions:Extension.Python Macro]] (installed by default in XWiki Enterprise)
12 * [[Ruby Macro>>extensions:Extension.Ruby Macro]] (not installed by default in XWiki Enterprise)
13 * [[PHP Macro>>extensions:Extension.PHP Macro]] (not installed by default in XWiki Enterprise)
Vincent Massol 20.4 14
Vincent Massol 38.1 15 = Choosing a Scripting language =
16
Sergiu Dumitriu 39.1 17 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.
Vincent Massol 38.1 18
Sergiu Dumitriu 39.1 19 == Velocity ==
20
Vincent Massol 38.1 21 The first thing to know is that Velocity is different from the other scripting languages on 2 aspects:
Manuel Smeria 45.4 22
Sergiu Dumitriu 39.1 23 * 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:(((
Vincent Massol 38.1 24 Velocity:
25
26 {{code}}
27 {{velocity}}
28 Your username is $xcontext.getUser(), welcome to the site.
29 {{/velocity}}
30 {{/code}}
31
32 Groovy:
33
34 {{code}}
35 {{groovy}}
36 println("Your username is " + xcontext.getUser() + " welcome to the site.");
37 {{/groovy}}
38 {{/code}}
39 )))
Sergiu Dumitriu 39.1 40 * It doesn't require special permissions 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>>platform:AdminGuide.Configuration#HSecuringGroovyScripts]] too, but it's still in an early stage.
Vincent Massol 38.1 41
Sergiu Dumitriu 40.1 42 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.
Sergiu Dumitriu 39.1 43
Sergiu Dumitriu 40.1 44 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.
45
Sergiu Dumitriu 39.2 46 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.
Sergiu Dumitriu 39.1 47
48 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.**
49
50 == Groovy ==
51
52 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.
53
Sergiu Dumitriu 39.3 54 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.
Sergiu Dumitriu 39.1 55
56 Other than being available as a scripting language for writing custom code, it is also the language in which scheduler tasks are written.
57
58 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.**
59
Vincent Massol 38.1 60 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!
61
OCTAGRAM 24.1 62 = XWiki Scripting API =
Caleb James DeLisle 20.1 63
Vincent Massol 30.3 64 The API is documented in Javadoc format and can be accessed here: [[XWiki API Javadoc>>DevGuide.API]]. 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>>extensions:Main.WebHome]] area to see how others have figured out how to achieve a variety of results.
Caleb James DeLisle 20.1 65
Vincent Massol 30.3 66 == [[Bindings>>extensions:Extension.Script Macro#HBindings]] ==
Caleb James DeLisle 20.1 67
Thomas Mortagne 46.1 68 These main objects available to you in scripting languages are:
OCTAGRAM 24.1 69
Thomas Mortagne 46.1 70 * The current Document: **##doc##**
71 * The Context of the request: **##xcontext##**
72 * The Request object: **##request##**
73 * The Response object: **##response##**
74 * The XWiki object: **##xwiki##**
75 * The XWiki utils: **##util##** (this is deprecated)
Vincent Massol 41.1 76 * Various [[Script Services>>extensions:Extension.Script Module]]: **##services##**
Caleb James DeLisle 20.1 77
Thomas Mortagne 46.1 78 See [[Scripting Reference Documentation>>http://platform.xwiki.org/xwiki/bin/view/SRD/Navigation?xpage=embed]] for a complete list.
79
Vincent Massol 30.3 80 == [[XWiki Component>>extensions:Extension.Component Module]] Access ==
Caleb James DeLisle 20.1 81
Manuel Smeria 45.4 82 Since XWiki 4.1M2+ there's a Script Service to access the Component Manager (see also: [[Accessing components from Groovy>>DevGuide.WritingComponents#HFromwikipages]]).
Caleb James DeLisle 30.1 83
Vincent Massol 41.1 84 For example using Groovy you'd write:
85
86 {{code language="java"}}
87 {{groovy}}
88 def greeter = services.component.getInstance(org.xwiki.component.HelloWorld.class)
89 println greeter.sayHello()
90 {{/groovy}}
91 {{/code}}
92
93 You can also get the ComponentManager with:
94
95 {{code language="java"}}
96 {{groovy}}
97 def cm = services.component.componentManager
98 {{/groovy}}
99 {{/code}}
100
Eduard Moraru 35.4 101 {{info}}
Vincent Massol 41.1 102 With versions of XWiki older than 4.1M2 you'd use (in Groovy):
Vincent Massol 34.1 103
coffeemug13 31.1 104 {{code language="java"}}
105 {{groovy}}
Vincent Massol 41.1 106 def greeter = com.xpn.xwiki.web.Utils.getComponent(org.xwiki.component.HelloWorld.class)
107 println greeter.sayHello()
coffeemug13 31.1 108 {{/groovy}}
109 {{/code}}
Vincent Massol 41.1 110 {{/info}}
Caleb James DeLisle 20.1 111
Vincent Massol 20.3 112 == XWiki Core Access ==
Caleb James DeLisle 20.1 113
Vincent Massol 34.1 114 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.
Caleb James DeLisle 30.1 115
coffeemug13 31.1 116 {{code language="java"}}
117 {{groovy}}
Caleb James DeLisle 20.1 118 def xc = xcontext.getContext();
119 def wiki = xc.getWiki();
120 def xdoc = doc.getDocument();
coffeemug13 31.1 121 {{/groovy}}
122 {{/code}}
Caleb James DeLisle 30.1 123
Caleb James DeLisle 20.1 124 After using this snippet, you will have 3 new objects:
OCTAGRAM 24.1 125
Caleb James DeLisle 20.1 126 * [[The underlying XWikiContext behind the Context object>>http://maven.xwiki.org/site/xwiki-core-parent/xwiki-core/apidocs/com/xpn/xwiki/XWikiContext.html]]: **##xc##**
127 * [[The underlying XWiki object which backs the **##xwiki##** object>>http://maven.xwiki.org/site/xwiki-core-parent/xwiki-core/apidocs/com/xpn/xwiki/XWiki.html]]: **##wiki##**
128 * [[The underlying XWikiDocument behind the current Document>>http://maven.xwiki.org/site/xwiki-core-parent/xwiki-core/apidocs/com/xpn/xwiki/doc/XWikiDocument.html]]: **##xdoc##**
129
Caleb James DeLisle 22.2 130 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##**.
131
Caleb James DeLisle 22.1 132 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.
Caleb James DeLisle 20.1 133
Vincent Massol 23.2 134 == Querying XWiki's Model ==
135
Manuel Smeria 45.4 136 From your script you can query the full XWiki Model. Check the [[Query Module>>extensions:Extension.Query Module]] for more information.
Vincent Massol 23.2 137
OCTAGRAM 24.1 138 {{id name="velocity"/}}
139
Vincent Massol 20.3 140 = Velocity Specific Information =
Vincent Massol 1.1 141
Vincent Massol 38.1 142 Velocity is currently the only scripting language which can be used without Programming [[AdminGuide.Access Rights]]. This means you can save velocity scripts using a user with less permission and an exploit of your script is less of a security breach.
Vincent Massol 1.1 143
Vincent Massol 34.1 144 You can [[gain access to the XWiki core>>#HXWikiCoreAccess]] 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).
145
Caleb James DeLisle 20.1 146 In Velocity you can't import classes and as such you cannot gain direct access to XWiki components as shown [[above>>#HXWikiComponentAccess]]. This leaves you with the provided [[bindings>>#HBindings]] (NOTE: In Velocity, these bindings all start with **##$##** as with all other Velocity variables)
Vincent Massol 1.1 147
Manuel Smeria 45.4 148 For more information about programming in the Velocity language, you can refer to the [[Velocity User Guide>>http://velocity.apache.org/engine/releases/velocity-1.7/user-guide.html]].
Vincent Massol 1.1 149
Vincent Massol 36.2 150 For more details on using Velocity check the [[Velocity Module Documentation>>extensions:Extension.Velocity Module]] which also contains the full list of Velocity Tools that you can use in your scripts.
OCTAGRAM 24.1 151
152 {{info}}
153 If you wish to add new Velocity tools you'll need to edit your ##xwiki.properties## file and follow the instructions in there.
154 {{/info}}
Vincent Massol 9.2 155
Caleb James DeLisle 16.1 156 To include Velocity scripts in other Velocity scripts, see [[How to include a velocity page into another page>>DevGuide.IncludeInVelocity]].
jeanvivienmaurice 1.20 157
Vincent Massol 20.3 158 == Other Velocity Variables ==
Vincent Massol 13.1 159
Marta Girdea 28.1 160 {{warning}}
OCTAGRAM 24.1 161 These variables can be used but are subject to change in the future.
Marta Girdea 28.1 162 {{/warning}}
Vincent Massol 13.1 163
Vincent Massol 20.3 164 === Controlling Which Sections to Display ===
Vincent Massol 13.1 165
Vincent Massol 47.1 166 You can control whether to display Comments/History/Attachment/Information sections or not by setting some velocity variables to ##false##:
Vincent Massol 13.1 167
Thomas Mortagne 33.1 168 {{code language="velocity"}}
Vincent Massol 47.1 169 #set ($showcomments = false)
170 #set ($showattachments = false)
171 #set ($showhistory = false)
172 #set ($showinformation = false)
Caleb James DeLisle 16.1 173 {{/code}}
Vincent Massol 13.1 174
175 To remove them all you can set:
176
Thomas Mortagne 33.1 177 {{code language="velocity"}}
Vincent Massol 13.1 178 #set($docextras = [])
Caleb James DeLisle 16.1 179 {{/code}}
Vincent Massol 13.1 180
Marta Girdea 28.2 181 === Information about the current user ===
Marta Girdea 28.1 182
Sergiu Dumitriu 35.2 183 The following variables (set in the {{scm path="xwiki-platform-core/xwiki-platform-web/src/main/webapp/templates/xwikivars.vm"}}xwikivars.vm{{/scm}} template) are shortcuts for checking various information **for the current user**:
Marta Girdea 28.1 184
185 * ##$isGuest##: checks if the current user is ##XWiki.XWikiGuest##
186 * ##$isSuperAdmin##: checks if the current user is the special user ##superadmin##
187
188 * ##$hasComment##: checks comment rights on the current document
189 * ##$hasEdit##: checks edit rights on the current document
190 * ##$hasWatch##: checks if the user is authenticated and the watch service is available
191
192 * ##$hasAdmin##: checks admin rights on the current document
193 * ##$hasSpaceAdmin##: checks admin rights on the ##XWikiPreferences## document of the current space
194 * ##$hasGlobalAdmin##: checks admin rights on ##XWiki.XWikiPreferences##
195
196 * ##$hasCreateSpace##: checks edit rights on that page that does not exist, in a space that doesn't exist
197 * ##$hasCreatePage##: checks edit rights on that page that does not exist, in the current space
198
199 * ##$hasProgramming##: checks if the current user has programming rights
200
201 * ##$isAdvancedUser##: advanced users: ##superadmin##, users with the ##usertype## property set to "Advanced", guest users with admin rights
202
Marta Girdea 28.2 203 Example:
Caleb James DeLisle 30.1 204
Thomas Mortagne 33.1 205 {{code language="velocity"}}
coffeemug13 31.1 206 {{velocity}}
Marta Girdea 28.2 207 #if ($hasAdmin)
208 ## This link will only be visible to users that have admin rights on this document
209 [[Do some admin action>>Some.Document]]
210 #end
coffeemug13 31.1 211 {{/velocity}}
212 {{/code}}
Marta Girdea 28.2 213
Marta Girdea 28.1 214 === Information about the current wiki ===
215
Sergiu Dumitriu 35.2 216 The following variables (set in the {{scm path="xwiki-platform-core/xwiki-platform-web/src/main/webapp/templates/xwikivars.vm"}}xwikivars.vm{{/scm}} template) are shortcuts for checking various information **about the current wiki**:
Marta Girdea 28.1 217
218 * ##$isReadOnly##
219 * ##$isInServletMode##
220 * ##$isInPortletMode##
221
Vincent Massol 20.3 222 = Groovy Specific Information =
Vincent Massol 1.1 223
Eduard Moraru 35.4 224 {{info}}
Manuel Smeria 45.4 225 Currently all non Velocity scripting languages are only allowed to be used by users having Programming Rights.
Eduard Moraru 35.4 226 {{/info}}
Vincent Massol 1.1 227
Vincent Massol 35.1 228 * See Groovy snippets in the [[Extensions wiki>>extensions:Main.WebHome]] (click on the "Groovy" tag in the Tag Cloud)
229 * [[Groovy web site>>http://groovy.codehaus.org/]]
Vincent Massol 1.1 230
Vincent Massol 20.3 231 == Groovy Example ==
gfiorentino 1.17 232
Caleb James DeLisle 18.1 233 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##.
Vincent Massol 8.2 234
Vincent Massol 34.1 235 **Using XWiki Syntax 2.0:**
236
Caleb James DeLisle 19.1 237 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.
Caleb James DeLisle 30.1 238
Thomas Mortagne 33.1 239 {{code language="velocity"}}
coffeemug13 31.1 240 {{velocity}}
Caleb James DeLisle 19.1 241 #set($hostname = "www.xwiki.org")
242 Host Name: $hostname
243 $xcontext.put("hostname", $hostname)
244 {{/velocity}}
245 {{groovy}}
246 import java.net.InetAddress;
247 host = xcontext.get("hostname");
248 InetAddress addr = InetAddress.getByName(host);
249 String address = addr.getHostAddress();
250 xcontext.put("address", address);
251 {{/groovy}}
252 {{velocity}}
253 IP Address: $xcontext.get("address")
coffeemug13 31.1 254 {{/velocity}}
255 {{/code}}
Caleb James DeLisle 19.1 256
Vincent Massol 34.1 257 **Using XWiki Syntax 1.0:**
258
Caleb James DeLisle 19.1 259 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.
Caleb James DeLisle 30.1 260
Thomas Mortagne 33.1 261 {{code language="velocity"}}
coffeemug13 31.1 262 #set ($hostname = "www.xwiki.org")
Caleb James DeLisle 18.1 263 Host Name: $hostname
Vincent Massol 8.2 264 <%
265 import java.net.InetAddress;
266 vcontext = context.get("vcontext");
Caleb James DeLisle 18.1 267 host = vcontext.get("hostname");
268 InetAddress addr = InetAddress.getByName(host);
269 String address = addr.getHostAddress();
Vincent Massol 8.2 270 %>
coffeemug13 31.1 271 IP Address: $address
272 {{/code}}
Caleb James DeLisle 20.1 273
Caleb James DeLisle 26.1 274 = Python Specific Information =
Marta Girdea 28.1 275
Vincent Massol 34.1 276 You can run Python code in XWiki just like Velocity or Groovy.
Caleb James DeLisle 30.1 277
coffeemug13 31.1 278 {{code language="python"}}
279 {{python}}
Caleb James DeLisle 20.1 280 print "The full name of this document is " + doc.getFullName()
coffeemug13 31.1 281 {{/python}}
282 {{/code}}
Caleb James DeLisle 20.1 283
Thomas Mortagne 42.1 284 = Share variable between languages =
285
Vincent Massol 47.6 286 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.
Thomas Mortagne 42.1 287
Thomas Mortagne 43.1 288 Since 4.1M2 a bridge has been written for Velocity (which is not based on JSR223) to allow it to access the current ScriptContext variable so you can do things like:
Thomas Mortagne 42.1 289
290 {{code}}
291 {{groovy}}
292 var = "toto"
293 {{/groovy}}
294
295 {{velocity}}
296 $var
297 {{/velocity}}
298 {{/code}}
299
Vincent Massol 47.6 300 Note that you can also share variables by setting them in the XWiki Context (##xcontext## binding).
301
Vincent Massol 20.3 302 = Scripting In XWiki Syntax 1.0 =
Caleb James DeLisle 20.1 303
Manuel Smeria 45.4 304 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.
Caleb James DeLisle 20.1 305
306 * The only scripting languages available to you are Velocity and Groovy.
307 * In Groovy, the context is known as: **##context##** not **##xcontext##**
Vincent Massol 30.3 308 * The beginning and end of Groovy scripts are denoted by <% and %> rather than through the [[extensions:Extension.Groovy Macro]] (using ~{~{groovy}} and ~{~{/groovy}})
309 * Velocity is parsed in a page no matter what (there is no need to invoke the [[extensions:Extension.Velocity Macro]] using ~{~{velocity}} and ~{~{/velocity}})
Caleb James DeLisle 20.1 310
Manuel Smeria 45.4 311 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.

Get Connected