Wiki source code of Scripting

Version 41.1 by Vincent Massol on 2012/05/19

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
Vincent Massol 20.4 7 XWiki integrates [[jsr-223>>http://scripting.dev.java.net/]] 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:
Sergiu Dumitriu 39.1 22 * 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 23 Velocity:
24
25 {{code}}
26 {{velocity}}
27 Your username is $xcontext.getUser(), welcome to the site.
28 {{/velocity}}
29 {{/code}}
30
31 Groovy:
32
33 {{code}}
34 {{groovy}}
35 println("Your username is " + xcontext.getUser() + " welcome to the site.");
36 {{/groovy}}
37 {{/code}}
38 )))
Sergiu Dumitriu 39.1 39 * 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 40
Sergiu Dumitriu 40.1 41 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 42
Sergiu Dumitriu 40.1 43 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.
44
Sergiu Dumitriu 39.2 45 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 46
47 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.**
48
49 == Groovy ==
50
51 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.
52
Sergiu Dumitriu 39.3 53 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 54
55 Other than being available as a scripting language for writing custom code, it is also the language in which scheduler tasks are written.
56
57 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.**
58
Vincent Massol 38.1 59 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!
60
OCTAGRAM 24.1 61 = XWiki Scripting API =
Caleb James DeLisle 20.1 62
Vincent Massol 30.3 63 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 64
Vincent Massol 30.3 65 == [[Bindings>>extensions:Extension.Script Macro#HBindings]] ==
Caleb James DeLisle 20.1 66
67 These objects are available to you in scripting languages.
OCTAGRAM 24.1 68
Caleb James DeLisle 20.1 69 * [[The current Document>>http://maven.xwiki.org/site/xwiki-core-parent/xwiki-core/apidocs/com/xpn/xwiki/api/Document.html]]: **##doc##**
70 * [[The Context of the request>>http://maven.xwiki.org/site/xwiki-core-parent/xwiki-core/apidocs/com/xpn/xwiki/api/Context.html]]: **##xcontext##**
71 * [[The Request object>>http://maven.xwiki.org/site/xwiki-core-parent/xwiki-core/apidocs/com/xpn/xwiki/web/XWikiRequest.html]]: **##request##**
72 * [[The Response object>>http://maven.xwiki.org/site/xwiki-core-parent/xwiki-core/apidocs/com/xpn/xwiki/web/XWikiResponse.html]]: **##response##**
73 * [[The XWiki object>>http://maven.xwiki.org/site/xwiki-core-parent/xwiki-core/apidocs/com/xpn/xwiki/api/XWiki.html]]: **##xwiki##**
Vincent Massol 41.1 74 * [[The XWiki utils>>http://maven.xwiki.org/site/xwiki-core-parent/xwiki-core/apidocs/com/xpn/xwiki/api/Util.html]]: **##util##** (this is deprecated)
75 * Various [[Script Services>>extensions:Extension.Script Module]]: **##services##**
Caleb James DeLisle 20.1 76
Vincent Massol 30.3 77 == [[XWiki Component>>extensions:Extension.Component Module]] Access ==
Caleb James DeLisle 20.1 78
Vincent Massol 41.1 79 Since XWiki 4.1M2+ there's a Script Service to access the Component Manager (see also: [[Accessing components from Groovy>>DevGuide.WritingComponents#HAccessingacomponentfromgroovy]]).
Caleb James DeLisle 30.1 80
Vincent Massol 41.1 81 For example using Groovy you'd write:
82
83 {{code language="java"}}
84 {{groovy}}
85 def greeter = services.component.getInstance(org.xwiki.component.HelloWorld.class)
86 println greeter.sayHello()
87 {{/groovy}}
88 {{/code}}
89
90 You can also get the ComponentManager with:
91
92 {{code language="java"}}
93 {{groovy}}
94 def cm = services.component.componentManager
95 {{/groovy}}
96 {{/code}}
97
Eduard Moraru 35.4 98 {{info}}
Vincent Massol 41.1 99 With versions of XWiki older than 4.1M2 you'd use (in Groovy):
Vincent Massol 34.1 100
coffeemug13 31.1 101 {{code language="java"}}
102 {{groovy}}
Vincent Massol 41.1 103 def greeter = com.xpn.xwiki.web.Utils.getComponent(org.xwiki.component.HelloWorld.class)
104 println greeter.sayHello()
coffeemug13 31.1 105 {{/groovy}}
106 {{/code}}
Vincent Massol 41.1 107 {{/info}}
Caleb James DeLisle 20.1 108
Vincent Massol 20.3 109 == XWiki Core Access ==
Caleb James DeLisle 20.1 110
Vincent Massol 34.1 111 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 112
coffeemug13 31.1 113 {{code language="java"}}
114 {{groovy}}
Caleb James DeLisle 20.1 115 def xc = xcontext.getContext();
116 def wiki = xc.getWiki();
117 def xdoc = doc.getDocument();
coffeemug13 31.1 118 {{/groovy}}
119 {{/code}}
Caleb James DeLisle 30.1 120
Caleb James DeLisle 20.1 121 After using this snippet, you will have 3 new objects:
OCTAGRAM 24.1 122
Caleb James DeLisle 20.1 123 * [[The underlying XWikiContext behind the Context object>>http://maven.xwiki.org/site/xwiki-core-parent/xwiki-core/apidocs/com/xpn/xwiki/XWikiContext.html]]: **##xc##**
124 * [[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##**
125 * [[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##**
126
Caleb James DeLisle 22.2 127 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##**.
128
Caleb James DeLisle 22.1 129 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 130
Vincent Massol 23.2 131 == Querying XWiki's Model ==
132
Jean-Vincent Drean 37.1 133 From your script you can query the full XWiki's Model. Check the [[Query Module>>extensions:Extension.Query Module]] for more information.
Vincent Massol 23.2 134
OCTAGRAM 24.1 135 {{id name="velocity"/}}
136
Vincent Massol 20.3 137 = Velocity Specific Information =
Vincent Massol 1.1 138
Vincent Massol 38.1 139 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 140
Vincent Massol 34.1 141 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).
142
Caleb James DeLisle 20.1 143 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 144
Caleb James DeLisle 20.1 145 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.6.2/user-guide.html]].
Vincent Massol 1.1 146
Vincent Massol 36.2 147 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 148
149 {{info}}
150 If you wish to add new Velocity tools you'll need to edit your ##xwiki.properties## file and follow the instructions in there.
151 {{/info}}
Vincent Massol 9.2 152
Caleb James DeLisle 16.1 153 To include Velocity scripts in other Velocity scripts, see [[How to include a velocity page into another page>>DevGuide.IncludeInVelocity]].
jeanvivienmaurice 1.20 154
Vincent Massol 20.3 155 == Other Velocity Variables ==
Vincent Massol 13.1 156
Marta Girdea 28.1 157 {{warning}}
OCTAGRAM 24.1 158 These variables can be used but are subject to change in the future.
Marta Girdea 28.1 159 {{/warning}}
Vincent Massol 13.1 160
OCTAGRAM 24.1 161 {{id name="HControllingwhethertodisplayCommentsHistoryAttachmentInformationsectionsornot"/}}
162
Vincent Massol 20.3 163 === Controlling Which Sections to Display ===
Vincent Massol 13.1 164
Caleb James DeLisle 20.1 165 You can control whether to display Comments/History/Attachment/Information sections or not by setting some velocity variable to "no":
Vincent Massol 13.1 166
Thomas Mortagne 33.1 167 {{code language="velocity"}}
Vincent Massol 13.1 168 #set ($showcomments = "no")
169 #set ($showattachments = "no")
170 #set ($showhistory = "no")
171 #set ($showinformation = "no")
Caleb James DeLisle 16.1 172 {{/code}}
Vincent Massol 13.1 173
174 To remove them all you can set:
175
Thomas Mortagne 33.1 176 {{code language="velocity"}}
Vincent Massol 13.1 177 #set($docextras = [])
Caleb James DeLisle 16.1 178 {{/code}}
Vincent Massol 13.1 179
Marta Girdea 28.2 180 === Information about the current user ===
Marta Girdea 28.1 181
Sergiu Dumitriu 35.2 182 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 183
184 * ##$isGuest##: checks if the current user is ##XWiki.XWikiGuest##
185 * ##$isSuperAdmin##: checks if the current user is the special user ##superadmin##
186
187 * ##$hasComment##: checks comment rights on the current document
188 * ##$hasEdit##: checks edit rights on the current document
189 * ##$hasWatch##: checks if the user is authenticated and the watch service is available
190
191 * ##$hasAdmin##: checks admin rights on the current document
192 * ##$hasSpaceAdmin##: checks admin rights on the ##XWikiPreferences## document of the current space
193 * ##$hasGlobalAdmin##: checks admin rights on ##XWiki.XWikiPreferences##
194
195 * ##$hasCreateSpace##: checks edit rights on that page that does not exist, in a space that doesn't exist
196 * ##$hasCreatePage##: checks edit rights on that page that does not exist, in the current space
197
198 * ##$hasProgramming##: checks if the current user has programming rights
199
200 * ##$isAdvancedUser##: advanced users: ##superadmin##, users with the ##usertype## property set to "Advanced", guest users with admin rights
201
Marta Girdea 28.2 202 Example:
Caleb James DeLisle 30.1 203
Thomas Mortagne 33.1 204 {{code language="velocity"}}
coffeemug13 31.1 205 {{velocity}}
Marta Girdea 28.2 206 #if ($hasAdmin)
207 ## This link will only be visible to users that have admin rights on this document
208 [[Do some admin action>>Some.Document]]
209 #end
coffeemug13 31.1 210 {{/velocity}}
211 {{/code}}
Marta Girdea 28.2 212
Marta Girdea 28.1 213 === Information about the current wiki ===
214
Sergiu Dumitriu 35.2 215 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 216
217 * ##$isReadOnly##
218 * ##$isInServletMode##
219 * ##$isInPortletMode##
220
Vincent Massol 20.3 221 = Groovy Specific Information =
Vincent Massol 1.1 222
Eduard Moraru 35.4 223 {{info}}
224 Currently all non Velocity scripting languages are only allowed users having Programming Rights.
225 {{/info}}
Vincent Massol 1.1 226
Vincent Massol 35.1 227 * See Groovy snippets in the [[Extensions wiki>>extensions:Main.WebHome]] (click on the "Groovy" tag in the Tag Cloud)
228 * [[Groovy web site>>http://groovy.codehaus.org/]]
Vincent Massol 1.1 229
Vincent Massol 20.3 230 == Groovy Example ==
gfiorentino 1.17 231
Caleb James DeLisle 18.1 232 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 233
Vincent Massol 34.1 234 **Using XWiki Syntax 2.0:**
235
Caleb James DeLisle 19.1 236 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 237
Thomas Mortagne 33.1 238 {{code language="velocity"}}
coffeemug13 31.1 239 {{velocity}}
Caleb James DeLisle 19.1 240 #set($hostname = "www.xwiki.org")
241 Host Name: $hostname
242 $xcontext.put("hostname", $hostname)
243 {{/velocity}}
244 {{groovy}}
245 import java.net.InetAddress;
246 host = xcontext.get("hostname");
247 InetAddress addr = InetAddress.getByName(host);
248 String address = addr.getHostAddress();
249 xcontext.put("address", address);
250 {{/groovy}}
251 {{velocity}}
252 IP Address: $xcontext.get("address")
coffeemug13 31.1 253 {{/velocity}}
254 {{/code}}
Caleb James DeLisle 19.1 255
Vincent Massol 34.1 256 **Using XWiki Syntax 1.0:**
257
Caleb James DeLisle 19.1 258 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 259
Thomas Mortagne 33.1 260 {{code language="velocity"}}
coffeemug13 31.1 261 #set ($hostname = "www.xwiki.org")
Caleb James DeLisle 18.1 262 Host Name: $hostname
Vincent Massol 8.2 263 <%
264 import java.net.InetAddress;
265 vcontext = context.get("vcontext");
Caleb James DeLisle 18.1 266 host = vcontext.get("hostname");
267 InetAddress addr = InetAddress.getByName(host);
268 String address = addr.getHostAddress();
Vincent Massol 8.2 269 %>
coffeemug13 31.1 270 IP Address: $address
271 {{/code}}
Caleb James DeLisle 20.1 272
Caleb James DeLisle 26.1 273 = Python Specific Information =
Marta Girdea 28.1 274
Vincent Massol 34.1 275 You can run Python code in XWiki just like Velocity or Groovy.
Caleb James DeLisle 30.1 276
coffeemug13 31.1 277 {{code language="python"}}
278 {{python}}
Caleb James DeLisle 20.1 279 print "The full name of this document is " + doc.getFullName()
coffeemug13 31.1 280 {{/python}}
281 {{/code}}
Caleb James DeLisle 20.1 282
Caleb James DeLisle 26.1 283 {{warning}}
Vincent Massol 30.3 284 Versions prior to [[XWiki Enterprise 2.4>>xwiki:ReleaseNotes.ReleaseNotesXWikiEnterprise24]] have a bug which prevents you from having access to the default objects (doc, xcontext, request, etc.) a [[workaround is available in the Extensions wiki>>extensions:Extension.Access To Bindings In Python]]
Caleb James DeLisle 26.1 285 {{/warning}}
286
Vincent Massol 20.3 287 = Scripting In XWiki Syntax 1.0 =
Caleb James DeLisle 20.1 288
Vincent Massol 20.5 289 XWiki Syntax 1.0 is rendered by an old rendering engine which 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 290
291 * The only scripting languages available to you are Velocity and Groovy.
292 * In Groovy, the context is known as: **##context##** not **##xcontext##**
Vincent Massol 30.3 293 * The beginning and end of Groovy scripts are denoted by <% and %> rather than through the [[extensions:Extension.Groovy Macro]] (using ~{~{groovy}} and ~{~{/groovy}})
294 * 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 295
296 The last part is important because it means you need to be careful of using $ and # in your document. This is still true inside of <% and %> so you have to be careful writing Groovy.

Get Connected