TWiki Reference Manual (Sun, 06 Nov 2005 build 7330)
This page contains all documentation topics as one long, complete reference sheet.
Doubleclick anywhere to return to the top of the page.
Note - if you are reading this at twiki.org, then you are reading about the code running on that site.
If you want to read about the features on your local TWiki, then you should read the documentation there!
- TWiki System Requirements
- Basic Installation
- Next Steps (optional)
- Troubleshooting
- TWiki Upgrade Guide
- TWiki Access Control
- TWiki Text Formatting
- TWiki Variables
- File Attachments
- TWiki Forms
- TWiki Templates
- TWiki Skins
- TWiki Formatted Search Results
- TWiki Meta Data
- TWiki Plugins
- Package TWiki::Func
- Functions: CGI Environment
- getSessionValue( $key ) -> $value
- setSessionValue( $key, $value ) -> $result
- clearSessionValue( $key ) -> $result
- getSkin( ) -> $skin
- getUrlHost( ) -> $host
- getScriptUrl( $web, $topic, $script, ... ) -> $url
- getScriptUrlPath( ) -> $path
- getViewUrl( $web, $topic ) -> $url
- getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $url
- getPubUrlPath( ) -> $path
- getCgiQuery( ) -> $query
- writeHeader( $query, $contentLength )
- redirectCgiQuery( $query, $url )
- getContext() -> \%hash
- Functions: Preferences
- Functions: User Handling and Access Control
- Functions: Content Handling
- getListOfWebs( $filter ) -> @webs
- webExists( $web ) -> $flag
- createWeb( $newWeb, $baseWeb, $opts )
- moveWeb( $oldName, $newName )
- topicExists( $web, $topic ) -> $boolean
- getRevisionInfo($theWebName, $theTopic, $theRev, $attachment ) -> ( $date, $user, $rev, $comment )
- getRevisionAtTime( $web, $topic, $time ) -> $rev
- checkTopicEditLock( $web, $topic ) -> ( $oopsUrl, $loginName, $unlockTime )
- setTopicEditLock( $web, $topic, $lock )
- readTopic( $web, $topic, $rev ) -> ( $meta, $text )
- readTopicText( $web, $topic, $rev, $ignorePermissions ) -> $text
- saveTopic( $web, $topic, $meta, $text, $options ) -> $error
- saveTopicText( $web, $topic, $text, $ignorePermissions, $dontNotify ) -> $oopsUrl
- moveTopic( $web, $topic, $newWeb, $newTopic )
- attachmentExists( $web, $topic, $attachment ) -> $boolean
- readAttachment( $web, $topic, $name, $rev ) -> $data
- saveAttachment( $web, $topic, $attachment, $opts )
- moveAttachment( $web, $topic, $attachment, $newWeb, $newTopic, $newAttachment )
- getTopicList( $web ) -> @topics
- Functions: Rendering
- registerTagHandler( $tag, \&fn, $syntax )
- addToHEAD( $id, $header )
- expandCommonVariables( $text, $topic, $web ) -> $text
- renderText( $text, $web ) -> $text
- internalLink( $pre, $web, $topic, $label, $anchor, $createLink ) -> $text
- getWorkArea( $pluginName ) -> $directorypath
- formatTime( $time, $format, $timezone ) -> $text
- Functions: File I/O
- Functions: System and I18N related
- Functions: Template handling and topic creation
- Functions: Email
- sendEmail ( $text, $retries ) -> $error
- Deprecated functions
- TWiki CGI Scripts
- TWiki Site Tools
- Web Changes Notification Service
- Sysadmins
- Managing Topics
- Managing Webs
- Manage Users
- TWiki CSS
Note: Read the most up to date version of this document at
http://TWiki.org/cgi-bin/view/TWiki/TWikiDocumentation
Related Topics: TWikiSite,
TWikiHistory,
TWikiPlannedFeatures,
TWikiEnhancementRequests,
UserDocumentationCategory,
AdminDocumentationCategory
TWiki System Requirements
Server and client requirements
Low client and server requirements are core features that keep TWiki widely deployable, particularly across a range of browser platforms and versions.
Server Requirements
TWiki is written in Perl 5, uses a number of shell commands, and requires
RCS (Revision Control System), a GNU Free Software package. TWiki is developed in a basic Linux/Apache environment. It also works with Microsoft Windows, and should have no problem on any other platform that meets the requirements.
| Resource | Required Server Environment * |
| Perl | 5.005_03 or higher (5.8.4 or higher is recommended) |
| RCS | 5.7 or higher (including GNU diff) Optional, TWiki includes a pure perl implementation of RCS that can be used instead (though it's slower) |
GNU diff | GNU diff 2.7 or higher is required when not using the all-Perl RcsLite. Install on PATH if not included with RCS (check version with diff -v) Must be the version used by RCS, to avoid problems with binary attachments - RCS may have hard-coded path to diff |
| Other external programs | fgrep, egrep |
| Cron/scheduler | • Unix: cron • Windows: cron equivalents |
| Web server | Apache is well supported; for other servers, see the TWiki:Codev.CategoryCookbook lists |
Required CPAN Modules
The following Perl modules are used by TWiki:
| Module | Preferred version |
| Algorithm::Diff | |
| CGI::Carp | >=1.26 |
| Config | >=0 |
| Cwd | >=3.05 |
| Data::Dumper | >=2.121 |
| Error | |
| File::Copy | >=2.06 |
| File::Find | >=1.05 |
| File::Spec | >=3.05 |
| FileHandle | >=2.01 |
| IO::File | >=1.10 |
| Text::Diff | |
| Time::Local | >=1.11 |
Optional CPAN Modules
The following Perl modules may be used by TWiki:
| Module | Preferred version | Description |
| CGI::Cookie | >=1.24 | Used for session support |
| CGI::Session | >=3.95 | Used for session support |
| Digest::base | | |
| Digest::SHA1 | | |
| Jcode | | Used for I18N support with perl 5.6 |
| Locale::Maketext::Lexicon | >=0 | Used for I18N support |
| Net::SMTP | >=2.29 | Used for sending mail |
| Unicode::Map | | Used for I18N support with perl 5.6 |
| Unicode::Map8 | | Used for I18N support with perl 5.6 |
| Unicode::MapUTF8 | | Used for I18N support with perl 5.6 |
| Unicode::String | | Used for I18N support with perl 5.6 |
| URI | | Used for configure |
Most of them will probably already be available in your installation.
You can check if they are available from the command-line like this
perl -e 'use FileHandle; print $FileHandle::VERSION."\n"'
Client Requirements
The TWiki
standard installation has extremely low browser requirements:
- HTML 3.2 compliant
- Cookies, if persistent sessions are required
CSS and Javascript are used in most skins, though there is a low-fat skin (Classic skin) available that minimises these requirements. Some skins will require more recent releases of browsers. The default skin (Pattern) is tested on IE 6, and Mozilla 5.0 based browsers (such as Firefox).
You can easily select a balance of browser capability versus look and feel.
- The TWikiPlugins feature currently does not have compatibility guidelines for developers. Plugins can require just about anything - browser-specific functions, stylesheets (CSS), Java applets, cookies, specific Perl modules,... - check the individual Plugin specs.
-
Plugins included in the TWiki distribution do not add requirements.
Related Topics: AdminDocumentationCategory
TWiki Installation Guide
Installation instructions for the TWiki Dakar production release
Please review the
AdminSkillsAssumptions before you install TWiki.
TWiki should be fine with any web server and OS that meet the
system requirements. See the cookbooks list at
TWiki:Codev.CategoryCookbook for guidance for your particular platform.
If you need help, ask a question in the
TWiki:Support web or on
TWiki:Codev.TWikiIRC (irc.freenode.net, channel #twiki)
Basic Installation
- Download the TWiki distribution from http://TWiki.org/download.html.
- Make a directory for the installation and unpack the distribution in it.
- Make sure the user that runs CGI scripts on your system can read and write all files in the distribution.
Detailed instructions on file permissions are beyond the scope of this guide, but in general:- During installation and configuration, the CGI user needs to be able to read and write everything in the distribution,
- Once installation and configuration is complete, the CGI user needs write access to everything under the
data and pub directories and to lib/LocalSite.cfg. Everything else should be read-only. - Everybody else should be denied access to everything, always.
- Make sure Perl 5 and the Perl CGI library are installed on your system.
The default location of Perl is /usr/bin/perl. If it's somewhere else, change the path to Perl in the first line of each script in the twiki/bin directory.
Some systems require a special extension on perl scripts (e.g. .cgi or .pl). If necessary, rename all files in twiki/bin (i.e. rename view to view.pl etc). If you do this, make sure you set the ScriptSuffix option in configure (Step 6). - Create the file
/twiki/bin/LocalLib.cfg.
There is a template for this file in /twiki/bin/LocalLib.cfg.txt.
The file must contain a setting for $twikiLibPath, which must point to the absolute file path of your twiki/lib e.g. /home/httpd/twiki/lib.
If you need to install additional CPAN modules, but can't update the main Perl installation files on the server, you can set $CPANBASE to point to your personal CPAN install. Don't forget that the webserver user has to be able to read those files as well. - Configure the webserver so you can execute the
bin/configure script from your browser.- Explicit instructions for doing this are beyond the scope of this document, though there is a lot of advice on TWiki.org covering different configurations of webserver. To help you out, there's an example Apache
httpd.conf file in twiki_httpd_conf.txt at the root of the package. This file also contains advice on securing your installation. There's also a script called tools/rewriteshebang.pl to help you in fixing up the shebang lines in your CGI scripts.
- Run the
configure script from your browser, and resolve any errors or warnings it tells you about.
You now have a basic, unauthenticated installation running. At this point you can just point your Web browser at
http://yourdomain.com/twiki/bin/view and start TWiki-ing away!
Next Steps (optional)
Once you have your TWiki running, you can move on to customise it for your users.
- Edit the TWikiPreferences topic in the TWiki web. Read through it and set any additional settings you think you might need (you can click the 'Edit' button near the top to edit the settings in place)
- Enable authentication, if required. Read TWikiUserAuthentication..
- Enable email notification (WebChangesAlerts). Read TWikiSiteTools.
- Install Plugins. TWiki:Plugins is an extensive library of Plugins for TWiki, that enhance functionality in a huge number of ways. A few plugins are pre-installed in the TWiki distribution. Installation instructions for the other plugins can be found in the plugin topics on TWiki.org.
Troubleshooting
The first step is to re-run the
configure script and make sure you have resolved all errors, and are happy that you understand any warnings.
Failing that, please check the topics listed below, they include some important tips for HP-UX, Solaris, OS/390, and many other platforms.
If you need help, ask a question in the
TWiki:Support web or on IRC (irc.freenode.net, channel #twiki)
TWiki Upgrade Guide
Upgrade from the previous TWiki Sep-2004 "Cairo" production release to TWiki "Dakar"
Overview
Dakar is a major new release. You can chose between an automated upgrade using a script or a manual update.
Upgrade Requirements
- Please review the AdminSkillsAssumptions before you upgrade TWiki
- To upgrade from a Cairo standard installation to the latest Dakar Production Release, follow the instructions below
- NOTE: To upgrade from a pre-Cairo TWiki, start with TWikiUpgradeToCairo
- To upgrade from a Beta of the new release, or if you made custom modifications, read through all new reference documentation, then use the procedure below as a guideline
- Once the upgrade has been applied, an existing earlier installation will still be able to read all the topics, but will not be able to write. Make sure you take a backup!
- Not all Cairo plugins are supported with Dakar. Make sure the plugins you use can be upgraded as well!
Major Changes Compared to TWiki Cairo
SEE
TWiki:Codev.DakarReleaseNotes FOR NOW
Automated Upgrade Procedure
If you would prefer to do things manually, skip to the
manual upgrade procedure below.
The upgrade script is called
"UpgradeTwiki", and is found in the root of the distribution. It can be run by any user, though you will need to make sure you correct permissions so the webserver user can write all files in the new installation when you have finished. The upgrade script does
not write to your existing installation.
The upgrade script will upgrade the
TWiki core only. Plugins will need to be upgraded separately.
It will:
- Create a new TWiki installation, placing the files from the distribution there as appropriate
- Where possible, merge the changes you've made in your existing topics and attachments into the new twiki
- Where not possible, it will tell you, and you can inspect those differences manually
- Create new configuration files for the new TWiki based on your existing configuation information
- Set the permissions in the new TWiki so that it should work straight away
- Attempt to setup authentication for your new TWiki, if you are using .htaccess in the old one
- Tell you what else you need to do
To perform the upgrade, you need to:
- Check first if there is a newer
UpgradeTwiki script available, see TWiki:Codev.UpgradeTWiki - Create a new directory for your new installation: Let's call this
distro/ - Put the distribution zip file in
distro/ - Unzip it
- Choose a directory for the new installation. I will call this
new_twiki. This directory must not already exist. - Change directory to
distro/ and run:
./UpgradeTwiki <full path to existing_twiki's setlib.cfg> <full path to new_twiki> - confirm your system settings by pointing your browser to
cgi-bin/configure
Assuming all goes well,
UpgradeTwiki will give you the final instructions.
There are a few points worth noting:
-
UpgradeTwiki may not be able to merge all the changes you made in your existing TWiki into the new installation, but it will tell you which ones it couldn't deal with -
UpgradeTwiki creates the new installation in a new directory tree. It makes a complete copy of all your existing data, so:- Clearly you need to point it to a location where there is enough space
- If you have symlinks under your
data/ directory in your existing installation, these are reproduced as actual directories in the new structure. It is up to you to pull these sub-directories out again and re-symlink as needed
-
UpgradeTwiki doesn't deal with custom templates or Plugins, you will have to reinstall these in the new installation.
If you use it, and would be kind enough to add your experiences to
TWiki:Codev.UpgradeTWiki, it would be much appreciated. The report of your experience will help to make
UpgradeTwiki more robust.
Manual Upgrade Procedure
The following steps are a rough guide to upgrading only. It is impossible to give detailed instructions, as what you have to do may depend on whether you can configure the webserver or not, and how much you have changed distributed files in your current TWiki release.
- Follow the installation instructions, and install the new release in a new directory.
- Copy your local webs over to the data and pub directories of the new install
- You could also use softlinks to link the web directories in data and pub to the old installation area
- Examine your old TWiki.cfg, and for each local setting, set the corresponding value in the
configure interface for the new install.
- If you can't use
configure, then copy the new TWiki.cfg to LocalSite.cfg, and edit LocalSite?.cfg. Remove all the settings that you didn't change in your previous install, and change the remaining settings to the values from your old TWiki.cfg.
- Transfer any local settings from TWikiPreferences to the topic pointed at by {LocalSitePreferences} (usually TWikiPreferences). This avoids having to write over files in the distribution.
- If you changed any of the topics in the original TWiki distribution, you will have to transfer your changes to the new install manually. There is no simple way to do this, though the following procedure may help:
- Install a copy of the original TWiki release you were using in a temporary directory
- Use 'diff' to find changed files, and transfer the changes into the new Dakar install.
- Install updated plugins into your new area.
- Point your webserver at the new install.
You are
highly recommended
not to change any distributed files if you can avoid it, to simplify future upgrades!
TWiki User Authentication
TWiki site access control and user activity tracking options
Authentication, or "login", is the process by which a user lets TWiki know who they are.
Authentication isn't just to do with access control. TWiki uses authentication to identify users, so it can keep track of who made changes, and manage a wide range of personal settings. With authentication enabled, users can personalise TWiki and contribute as recognised individuals, instead of shadows.
TWiki authentication is very flexible, and can either stand alone or integrate with existing authentication schemes. You can set up TWiki to require authentication for every access, or only for changes. Authentication is also essential for access control.
Quick Authentication Test - Use the %WIKIUSERNAME% variable to return your current identity:
TWiki user authentication is split into three sections; password management, user registration, and login management. Password management deals with how users are recognised (authenticated). Registration deals with how new users are added to the wiki. Login management deals with how users log in.
Once a user is logged on, they are remembered using a "session id" stored in a cookie in the browser (or by other less elegant means if the user has disabled cookies). This avoids them having to log on again and again.
Please note
FileAttachments are not protected by TWiki User Authentication.
Password Management
As shipped, TWiki supports the Apache 'htpasswd' password manager. This manager supports the use of
.htpasswd files on the server. These files can be unique to TWiki, or can be shared with other applications (such as an Apache webserver). A variety of password encodings are supported for flexibility when re-using existing files. See the descriptive comments in the Security Settings section of the
configure interface for more details.
New User Registration
New user registration uses the password manager to set and change passwords. It is also responsible for the new user verification process. the registration process supports
single user registration via the
TWikiRegistration page, and
bulk user registration via the
BulkRegistration page (for admins only).
The registration process is responsible for creating user topics.
Login Management
Login management controls the way users have to log in. There are three basic options; no login, login via a TWiki login page, and login using the webserver authentication support.
You can select your chosen login through the Security Settings pane in the
configure interface.
No Login
Does exactly what it says on the tin. Forget about authentication to make your site completely public - anyone can browse and edit freely, in classic Wiki style. All visitors are given the
TWikiGuest default identity, so you can't track individual user activity.
Template Login
Template Login asks for a username and password in a web page, and processes them using whatever Password Manager you choose. Users can log in and log out.
Enabling Template Login
- Use the
configure interface to- enable the
TemplateLogin login manager (on the Security Settings pane). - select the appropriate password manager for your system, or provide your own.
- Register yourself in the TWikiRegistration topic.
Check that the password manager recongises the new user. If you are using .htpasswd files, check that a new line with the username and encrypted password is added to the .htpasswd file. If not, you probably got a path wrong, or the permissions may not allow the webserver user to write to that file. - Create a new topic to check if authentication works.
- Edit the TWikiAdminGroup topic in the TWiki:Main web to include users with system administrator status.
This is a very important step, as users in this group can access all topics, independent of TWiki access controls.
TWikiAccessControl has more information on setting up access controls.

At this time
TWikiAccessControls cannot control access to files in the
pub area, unless they are only accessed through the
viewfile script. If your
pub directory is set up in the webserver to allow open access you may want to add
.htaccess files in there to restrict access.

You can create a custom version of the
TWikiRegistration form by deleting or adding input tags. The
name="" parameter of the input tags must start with:
"Twk0..." (if this is an optional entry), or
"Twk1..." (if this is a required entry). This ensures that the fields are carried over into the user home page correctly.

You can customize the default user home page in
NewUserTemplate. The same variables get expanded as in the
template topics
Apache Login
Using this method TWiki does not authenticate users internally. Instead it depends on the
REMOTE_USER environment variable, which is set when you enable authentication in the webserver.
The advantage of this scheme is that if you have an existing website authentication scheme using Apache modules such as
mod_auth_ldap or
mod_auth_mysql you can just plug in directly to them.
The disadvantage is that because the user identity is cached in the browser, you can log in, but you can't log out again.
TWiki maps the
REMOTE_USER that was used to log in to the webserver to a
WikiName using the table in
TWikiUsers. This table is updated whenever a user registers, so users can choose not to register (in which case their webserver login name is used for their signature) or register (in which case that login name is mapped to their
WikiName).
The same private
.htpasswd file used in TWiki Template Login can be used to authenticate Apache users, using the Apache Basic Authentication support. This allows the TWiki registration support to maintain usernames and passwords.
Enabling Apache Login using mod_auth
You can use any other Apache authentication module that sets REMOTE_USER.
- Use configure to select the
ApacheLogin login manager. - Use configure to set up TWiki to create the right kind of
.htpasswd entries. - Create a
.htaccess file in the twiki/bin directory.
There is an template for this file in twiki/bin/.htaccess.txt that you can copy and change. The comments in the file explain what need to be done.
If you got it right, the browser should now ask for login name and password when you click on the Edit. If .htaccess does not have the desired effect, you may need to "AllowOverride All" for the directory in httpd.conf (if you have root access; otherwise, email web server support)
At this time TWikiAccessControls do not control access to files in the pub area, unless they are only accessed through the viewfile script. If your pub directory is set up to allow open access you may want to add .htaccess files in there as well to restrict access - You can create a custom version of TWikiRegistration by deleting or adding input tags. The
name="" parameter of the input tags must start with: "Twk0..." (if this is an optional entry), or "Twk1..." (if this is a required entry). This ensures that the fields are carried over into the user home page correctly.
You can customize the default user home page in NewUserTemplate. The same variables get expanded as in the template topics - Register yourself in the TWikiRegistration topic.
Check that a new line with the username and encrypted password is added to the .htpasswd file. If not, you may have got a path wrong, or the permissions may not allow the webserver user to write to that file. - Create a new topic to check if authentication works.
- Edit the TWikiAdminGroup topic in the TWiki:Main web to include users with system administrator status.
This is a very important step, as users in this group can access all topics, independent of TWiki access controls.
TWikiAccessControl has more information on setting up access controls.
Logons via bin/logon
Any time a user enters a page that needs authentication, they will be forced to log on. It may be convenient to have a "logon" as well, to give the system a chance to identify the user and retrieve their personal settings. It may be convenient to force them to log on.
The
bin/logon script accomplishes this. The
bin/logon script must be setup in the
bin/.htaccess file to be a script which requires a
valid user. However, once authenticated, it will simply redirect the user to the view URL for the page from which the
logon script was linked.
Sessions
TWiki uses the
CPAN:CGI::Session and
CPAN:CGI::Cookie modules to track sessions using cookies. These modules are de facto standards for session management among Perl programmers. If you can't use Cookies for any reason,
CPAN:CGI::Session also supports session tracking using the client IP address. See
How to choose an authentication method for a discussion of the pros and cons of the various authentication methods.
There are a number of
TWikiVariables available that you can use to interrogate your current session. You can even add your own session variables to the TWiki cookie. Session variables are referred to as "sticky" variables.
Getting, Setting, and Clearing Session Variables
You can get, set, and clear session variables from within TWiki web pages or by using script parameters. This allows you to use the session as a personal "persistent memory space" that is not lost until the web browser is closed. Also note that if a session variable has the same name as a TWiki preference, the session variables value takes precedence over the TWiki preference.
This allows for per-session preferences.
To make use of these features, use the tags:
%SESSION_VARIABLE{ "varName" }%
%SESSION_VARIABLE{ "varName" set="varValue" }%
%SESSION_VARIABLE{ "varName" clear="" }%
Cookies and Transparent Session IDs
TWiki normally uses cookies to store session information on a client computer. Cookies are a common way to pass session information from client to server. TWiki cookies simply hold a unique session identifier that is used to look up a database of session information on the TWiki server.
For a number of reasons, it may not be possible to use cookies. In this case, TWiki has a fallback mechanism; it will automatically rewrite every internal URL it sees on pages being generated to one that also passes session information.
TWiki Username vs. Login Username
This section applies only if you are using authentication with existing login names (i.e. mapping from login names to
WikiNames).
APS Sahaja Yoga internally manages two usernames: Login Username and TWiki Username.
- Login Username: When you login to the intranet, you use your existing login username, ex:
pthoeny. This name is normally passed to TWiki by the REMOTE_USER environment variable, and used internally. Login Usernames are maintained by your system administrator.
- TWiki Username: Your name in WikiNotation, ex:
PeterThoeny, is recorded when you register using TWikiRegistration; doing so also generates a personal home page in the Main web.
TWiki can automatically map an Intranet (Login) Username to a TWiki Username if the {AllowLoginName} is enabled in
configure. The default is to use your
WikiName as a login name.
NOTE: To correctly enter a WikiName - your own or someone else's - be sure to include the Main web name in front of the Wiki username, followed by a period, and no spaces. Ex:
Main.WikiUsername or %MAINWEB%.WikiUsername
This points WikiUser to the Main web, where user registration pages are stored, no matter which web it's entered in. Without the web prefix, the name appears as a NewTopic? everywhere but in the Main web.
Changing Passwords
If your {PasswordManager} supports password changing, you can change and reset passwords using forms on regular pages.
Controlling access to individual scripts
You may want to add or remove scripts from the list of scripts that require authentication. The method for doing this is different for each of Template Login and Apache Login.
- For Template Login, update the {AuthScripts} list using
configure - For Apache Login, add/remove the script from =
.htaccess=
How to choose an authentication method
One of the key features of TWiki is that it is possible to add HTML to topics. No authentication method is 100% secure on a website where end users can add HTML, as there is always a risk that a malicious user can add code to a topic that gathers user information, such as session IDs. The TWiki developers have been forced to make certain tradeoffs, in the pursuit of efficiency, that may be exploited by a hacker.
This section discusses some of the known risks. You can be sure that any potential hackers have read this section as well!
Firstly, the
most secure method is without doubt to use the webserver authentication support, with Sessions turned
off.
The
second most secure method is to use TWiki's internal authentication with Sessions turned
off. This method is less secure than using the webserver because passwords are sent in
plain text and can therefore be intercepted in transit.
As soon as you allow the server to maintain information about a logged-in user, you open a door to potential attacks. There are a variety of ways a malicious user can pervert TWiki to obtain another users session ID, the most common of which is known as a
cross-site scripting attack. Once a hacker has an SID they can pretend to be that user.
To help prevent these sorts of attacks, TWiki supports
IP matching, which ensures that the IP address of the user requesting a specific session is the same as the IP address of the user who created the session. This works well as long as IP addresses are unique to each client, and as long as the IP address of the client can't be faked.
The
third most secure method is to use sessions with IP matching ({UseIPMatching} switched on). Shorter session expiry times are more secure ({Sessions}{ExpireAfter}). The default session lifetime is 6 hours, which is quite a long lifetime for a session.
Session IDs are usually stored by TWiki in cookies, which are stored in the client browser. Cookies work well, but not all environments or users permit cookies to be stored in browsers. So TWiki also supports two other methods of determining the session ID. The first method uses the client IP address to determine the session ID. The second uses a rewriting method that rewrites local URLs in TWiki pages to include the session ID in the URL.
The first method works well as long as IP addresses are
unique to each individual client, and client IP addresses can't be faked by a hacker. If IP addresses are unique and can't be faked, it is almost as secure as cookies + IP matching, so it ranks as the
fourth most secure method.
If you have to turn IP matching off, and cookies can't be relied on, then you may have to rely on the second method, URL rewriting. This method exposes the session IDs very publicly, so should be regarded as the
least secure method.
See
TWiki:Codev.SecuringYourTWiki for more information
TWiki Access Control
Restricting read and write access to topics and webs, by Users and groups
TWikiAccessControl allows you restrict access to single topics and entire webs, by individual user and by user Groups. Access control, combined with
TWikiUserAuthentication, lets you easily create and manage an extremely flexible, fine-grained privilege system.
An Important Control Consideration
Open, freeform editing is the essence of
WikiCulture - what makes TWiki different and often more effective than other collaboration tools. For that reason, it is strongly recommended that decisions to restrict read or write access to a web or a topic are made with great care - the more restrictions, the less Wiki in the mix. Experience shows that
unrestricted write access works very well because:
- Peer influence is enough to ensure that only relevant content is posted.
- Peer editing - the ability for anyone to rearrange all content on a page - keeps topics focussed.
- In TWiki, content is transparently preserved under revision control:
- Edits can be undone by the TWikiAdminGroup (the default administrators group; see #ManagingGroups).
- Users are encouraged to edit and refactor (condense a long topic), since there's a safety net.
As a
collaboration guideline:
- Create broad-based Groups (for more and varied input), and...
- Avoid creating view-only Users (if you can read it, you should be able to contribute to it).
Authentication vs. Access Control
Authentication: Identifies who a user is based on a login procedure. See
TWikiUserAuthentication.
Access control: Restrict access to content based on users and groups once a user is identified.
Users and Groups
Access control is based on the familiar concept of Users and Groups. Users are defined by their
WikiNames. They can then be organized in unlimited combinations by inclusion in one or more user Groups. For convenience, Groups can also be included in other Groups.
Managing Users
A user can create an account in
TWikiRegistration. The following actions are performed:
- WikiName and encrypted password are recorded using the password manager if authentication is enabled.
- A confirmation e-mail is sent to the user.
- A user home page with the WikiName of the user is created in the Main web.
- The user is added to the TWikiUsers topic.
The default visitor name is
TWikiGuest. This is the non-authenticated user.
Managing Groups
Groups are defined by group topics created in the
Main web, like the
TWikiAdminGroup. To create a new group:
-
Edit TWikiGroups by entering a new topic with a name that ends in Group. Example: - Define two TWikiVariables in the new group topic:
-
Set GROUP = < list of Users and/or Groups > -
Set ALLOWTOPICCHANGE = < list of Users and/or Groups > - The GROUP variable is a comma-separated list of Users and/or other Groups. Example:
-
Set GROUP = Main.SomeUser, Main.OtherUser, Main.SomeGroup
- ALLOWTOPICCHANGE defines who is allowed to change the group topic; it is a comma delimited list of Users and Groups. You typically want to restrict that to the members of the group itself, so it should contain the name of the topic. This prevents Users not in the Group from editing the topic to give themselves or others access. For example, for the TWikiAdminGroup topic write:
-
Set ALLOWTOPICCHANGE = Main.TWikiAdminGroup
- These are summarised on SitePermissions

TWiki has strict formatting rules. Make sure you have three spaces, an asterisk, and an extra space in front of any access control rule.
The SuperAdminGroup
By mistyping a user or group name in the settings, it's possible to lock a topic so that no-one can edit it from a browser. To avoid this, you can create
superusers:
- Edit the
SuperAdminGroup as described above and add the wikinames of a group of Users who are always allowed to edit/view topics e.g.-
Set GROUP= ElizabethWindsor?,Main.TonyBlair
Restricting Access
You can define who is allowed to read or write to a web or a topic. Note that some plugins may not respect access permissions.
- Restricting VIEW blocks viewing and searching of content.
- Restricting CHANGE blocks creating new topics, changing topics or attaching files.
- Restricting RENAME controls who is allowed to rename, move or delete a topic.
- To rename, move or delete a topic, the user also also needs VIEW and CHANGE permission. They also need CHANGE access to change references in any referring topics (though the rename can proceed without this access), and CHANGE access to the target topic.
Controlling access to a Web
You can define restrictions of who is allowed to view a APS Sahaja Yoga web. You can restrict access to certain webs to selected Users and Groups, by:
- authenticating all webs and restricting selected webs: Topic access in all webs is authenticated, and selected webs have restricted access.
- authenticating and restricting selected webs only: Provide unrestricted viewing access to open webs, with authentication and restriction only on selected webs.
- You can define these settings in the WebPreferences topic, preferable towards the end of the topic:
-
Set DENYWEBVIEW = < comma-delimited list of Users and Groups > -
Set ALLOWWEBVIEW = < comma-delimited list of Users and Groups > -
Set DENYWEBCHANGE = < comma-delimited list of Users and Groups > -
Set ALLOWWEBCHANGE = < comma-delimited list of Users and Groups > -
Set DENYWEBRENAME = < comma-delimited list of Users and Groups > -
Set ALLOWWEBRENAME = < comma-delimited list of Users and Groups >
Be careful with empty values for any of these. In older versions of TWiki,
meant the same as not setting it at all. However since TWiki Dakar release, it means
allow no-one access i.e. prevent anyone from viewing the web. Similarly
now means
do not deny anyone the right to view this web. See "How TWiki evaluates ALLOW/DENY settings" below for more on this.
Controlling access to a Topic
- You can define these settings in the WebPreferences topic, preferable towards the end of the topic:
-
Set DENYTOPICVIEW = < comma-delimited list of Users and Groups > -
Set ALLOWTOPICVIEW = < comma-delimited list of Users and Groups > -
Set DENYTOPICCHANGE = < comma-delimited list of Users and Groups > -
Set ALLOWTOPICCHANGE = < comma-delimited list of Users and Groups > -
Set DENYTOPICRENAME = < comma-delimited list of Users and Groups > -
Set ALLOWTOPICRENAME = < comma-delimited list of Users and Groups >
Remember when opening up access to specific topics within a restricted web that other topics in the web - for example, the
WebLeftBar - may also be accessed when viewing the topics. The message you get when you are denied access should tell you what topic you were not permitted to access.
Be careful with empty values for any of these. In older versions of TWiki,
meant the same as not setting it at all. However since TWiki Dakar release, it means
allow no-one access i.e. prevent anyone from viewing the topic. Similarly
now means
do not deny anyone the right to view this topic. See "How TWiki evaluates ALLOW/DENY settings" below for more on this.
Controlling access to Attachments
Attachments are referred to directly, and are not normally indirected via TWiki scripts. This means that the above instructions for access control will
not apply to attachments. It is possible that someone may inadvertently publicise a URL that they expected to be access-controlled.
The easiest way to apply the same access control rules for attachments as apply to topics is to use the Apache
mod_rewrite module, and configure your webserver to redirect accesses to attachments to the TWiki
viewfile script. For example,
ScriptAlias /twiki/bin/ /filesystem/path/to/twiki/bin/
Alias /twiki/pub/ /filesystem/path/to/twiki/pub/
RewriteEngine on
RewriteRule ^/twiki/pub/TWiki/(.*)$ /twiki/pub/TWiki/$1 [L,PT]
RewriteRule ^/twiki/pub/([^\/]+)/([^\/]+)/([^\/]+)$ /twiki/bin/viewfile/$1/$2?filename=$3 [L,PT]
That way all the controls that apply to the topic also apply to attachments to the topic. Other types of webserver have similar support.
How TWiki evaluates ALLOW/DENY settings
When deciding whether to grant access, TWiki evaluates the following rules in order (read from the top of the list; if the logic arrives at
PERMITTED or
DENIED that applies immediately and no more rules are applied). You need to read the rules bearing in mind that VIEW, CHANGE and RENAME access may be granted/denied separately.
- If the user is a super-user
- If DENYTOPIC is set to a list of wikinames
- people in the list will be DENIED.
- If DENYTOPIC is set to empty ( i.e. Set DENYTOPIC = )
- access is PERMITTED i.e _ no-one is denied access to this topic
- If ALLOWTOPIC is set
- people in the list are PERMITTED
- everyone else is DENIED
- Note that this means that setting ALLOWTOPIC to empty _denies access to everyone except admins (unless DENYTOPIC is also set to empty, as described above)
- If DENYWEB is set to a list of wikiname
- people in the list are DENIED access
- If ALLOWWEB is set to a list of wikinames
- people in the list will be PERMITTED
- everyone else will be DENIED
- Note that setting ALLOWWEB to empty denies access to everyone except admins
- If you got this far, access is PERMITTED
Access Control quick recipes
Obfusticating Webs
Another way of hiding webs is to keep them hidden by not publishing the URL and by preventing the
all webs search option from accessing obfuscated webs. Do so by enabling the
NOSEARCHALL variable in
WebPreferences:
This setup can be useful to hide a new web until content its ready for deployment.
Obfuscating webs is very insecure, as anyone who knows the URL can access the web.
Authenticate all Webs and Restrict Selected Webs
Use the following setup to authenticate users for topic viewing in all webs and to restrict access to selected webs. Requires
TWikiUserAuthentication to be enabled.
- Restrict view access to selected Users and Groups. Set one or both of these variables in its WebPreferences topic:
-
Set DENYWEBVIEW = < list of Users and Groups > -
Set ALLOWWEBVIEW = < list of Users and Groups > - Note:
DENYWEBVIEW is evaluated before ALLOWWEBVIEW. Access is denied if the authenticated person is in the DENYWEBVIEW list, or not in the ALLOWWEBVIEW list. Access is granted in case DENYWEBVIEW and ALLOWWEBVIEW is not defined.
- Hide the web from an "all webs" search. Enable this restriction with the
NOSEARCHALL variable in its WebPreferences topic:
Authenticate and Restrict Selected Webs Only
Use the following setup to provide unrestricted viewing access to open webs, with authentication only on selected webs. Requires
TWikiUserAuthentication to be enabled.
- Restrict view access to selected Users and Groups. Set one or both of these variables in its WebPreferences topic:
-
Set DENYWEBVIEW = < list of Users and Groups > -
Set ALLOWWEBVIEW = < list of Users and Groups > - Note:
DENYWEBVIEW is evaluated before ALLOWWEBVIEW. Access is denied if the authenticated person is in the DENYWEBVIEW list, or not in the ALLOWWEBVIEW list. Access is granted in case DENYWEBVIEW and ALLOWWEBVIEW is not defined.
- Hide the web from an "all webs" search. Enable this restriction with the
NOSEARCHALL variable in its WebPreferences topic:
Hide Control Settings

To hide access control settings from normal browser viewing, place them in HTML comment markers.
TWiki Text Formatting
Working in TWiki is as easy as typing in text. You don't need to know HTML, though you can use it if you prefer. Links to topics are created automatically when you enter
WikiWords. And TWiki shorthand gives you all the power of HTML with a simple coding system that takes no time to learn. It's all laid out below.
TWiki Editing Shorthand
|
Formatting Command:
|
You write:
|
You get:
|
Paragraphs:
Blank lines will create new paragraphs.
|
1st paragraph
2nd paragraph
|
1st paragraph
2nd paragraph
|
Headings:
Three or more dashes at the beginning of a line, followed by plus signs and the heading text. One plus creates a top level heading, two pluses a second level heading, etc. The maximum heading depth is 6.
You can create a table of contents with the %TOC% variable. If you want to exclude a heading from the TOC, put !! after the ---+.
Empty headings are allowed, but won't appear in the table of contents.
|
---++ Sushi
---+++ Maguro
---++++++!! Exclude from TOC
|
Sushi
Maguro
Exclude from TOC
|
Bold Text:
Words get shown in bold by enclosing them in * asterisks.
|
*Bold*
|
Bold
|
Italic Text:
Words get shown in italic by enclosing them in _ underscores.
|
_Italic_
|
Italic
|
Bold Italic:
Words get shown in bold italic by enclosing them in __ double-underscores.
|
__Bold italic__
|
Bold italic
|
Fixed Font:
Words get shown in fixed font by enclosing them in = equal signs.
|
=Fixed font=
|
Fixed font
|
Bold Fixed Font:
Words get shown in bold fixed font by enclosing them in double equal signs.
|
==Bold fixed==
|
Bold fixed
|
You can follow the closing bold, italic, or other (* _ __ = ==) indicator
with normal punctuation, such as commas and full stops.
Make sure there is no space between the text and the indicators.
|
_This works_,
_this does not _
|
This works,
_this does not _
|
Separator (horizontal rule):
Three or more three dashes at the beginning of a line..
|
-------
|
|
Bulleted list:
Multiple of three spaces, an asterisk, and another space.
|
* bullet item level 1
* bullet item level 2
* bulleted item level 3
* back to level 1
| - bullet item level 1
- back to level 1
|
Numbered List:
Multiple of three spaces, a type character, a dot, and another space. Several types are available besides a number:
| Type | Generated Style | Sample Sequence |
| 1. | Arabic numerals | 1, 2, 3, 4... |
| A. | Uppercase letters | A, B, C, D... |
| a. | Lowercase letters | a, b, c, d... |
| I. | Uppercase Roman Numerals | I, II, III, IV... |
| i. | Lowercase Roman Numerals | i, ii, iii, iv... |
If you don't want to cram long text onto one line, wrap it and align continuation lines with leading spaces.
|
1. Mammals
1. Rodents
A. Rats
A. Mice
A. Capybaras
i. Bats
1. Pipistrelle
1. Horseshoe
(lesser)
| - Mammals
- Rodents
- Rats
- Mice
- Capybaras
- Bats
- Pipistrelle
- Horseshoe
(lesser)
|
Definition List:
Three spaces, a dollar sign, the term, a colon, a space, followed by the definition.
|
$ Sushi: Japan
$ Dim Sum: S.F.
| - Sushi
- Japan
- Dim Sum
- S.F.
|
Table:
Each row of the table is a line containing of one or more cells. Each cell starts and ends with a vertical bar '|'. Any spaces at the beginning of a line are ignored.- to make a cell a header, put the text in asterisks
| *bold* | - to center the contents of a cell, put an equal number of spaces on either side of the text (you need more than one space on each side)
- to right-align, put more spaces on the left | right-spaced |=
- to span multiple columns, put the
|='s right next to each other =| 2 colspan || - You can split rows over multiple lines by putting a backslash
'\' at the end of each line - Contents of table cells wrap automatically as determined by the browser.
The TablePlugin increases the number of things you can do with tables - for example, you can control formatting, and create multi-row spans.
|
| *L* | *C* | *R* |
| A2 | 2 | 2 |
| A3 | 3 | 3 |
| multi span |||
| A4-6 | \
four \
| four |
|
| L | C | R |
| A2 | 2 | 2 |
| A3 | 3 | 3 |
| multi span |
| A4-6 | four | four |
|
WikiWord Links:
CapitalizedWordsStuckTogether (or WikiWords) will produce a link automatically.
If you want to link to a topic in a different APS Sahaja Yoga web write Otherweb.TopicName. (The link label is the the name of the web if it is WebHome, otherwise it is the topic name)
|
WebNotify
%MAINWEB%.TWikiUsers
|
WebNotify
TWikiUsers
|
Verbatim (Literal) text:
Surround code excerpts and other formatted text with <verbatim> and </verbatim> tags.
verbatim tags disable HTML code. Use <pre> and </pre> tags instead if you want the HTML code within the tags to be interpreted.
NOTE: VARIABLES are still Set within verbatim tags (this is a historical peculiarity)
|
<verbatim>
class CatAnimal {
void purr() {
<code here>
}
}
</verbatim>
|
class CatAnimal {
void purr() {
<code here>
}
}
|
Anchors:
You can define a reference inside a APS Sahaja Yoga topic (called an anchor name) and link to that. To define an anchor write #AnchorName at the beginning of a line. The anchor name must be a WikiWord. To link to an anchor name use the [[MyTopic#MyAnchor]] syntax. You can omit the topic name if you want to link within the same topic.
|
[[WikiWord#NotThere]]
[[#MyAnchor][Jump]]
#MyAnchor To here
|
WikiWord#NotThere
Jump
To here
|
Forced Links:
You can create a forced internal link by enclosing words in double square brackets.
Text within the brackets may contain optional spaces; the topic name is formed by capitalizing the initial letter and by removing the spaces; for example, [[text formatting FAQ]] links to topic TextFormattingFAQ. You can also refer to a different web and use anchors.
To "escape" double square brackets that would otherwise make a link, prefix the leading left square bracket with an exclamation mark !
|
[[wiki syntax]]
[[%MAINWEB%.TWiki users]]
escaped:
![[wiki syntax]]
|
wiki syntax
Main.TWiki users
escaped:
[[wiki syntax]]
|
Specific Links:
You can create a link where you specify the link text and the URL separately using nested square brackets [[reference][text]]. Internal link references (e.g. WikiSyntax) and URLs (e.g. http://TWiki.org/) are both supported.
The rules described under Forced Links apply for internal link references.
Anchor names can be added as well, to create a link to a specific place in a topic.
|
[[WikiSyntax][wiki syntax]]
[[http://gnu.org][GNU]]
[[mailto:barretts@wimpole.street][write to the Barretts]]
[[TextFormattingRules#SquareBrackets][here]]
|
wiki syntax
GNU
write to the Barretts
here
|
Prevent a Link:
Prevent a WikiWord from being linked by prepending it with an exclamation mark.
|
!SunOS
|
SunOS
|
Disable Links:
You can disable automatic linking of WikiWords by surrounding text with <noautolink> and </noautolink> tags. Each tag must be on a line by itself.
|
<noautolink>
RedHat &
SuSE
</noautolink>
|
RedHat &
SuSE
|
Using HTML
You can use just about any HTML tag without a problem - however, there are a few usability and technical considerations to keep in mind.
- On collaboration pages, it's better not to use HTML, but to use TWiki shorthand instead - this keeps the text uncluttered and easy to edit.
- Use XHTML 1.0 Transitional syntax
- Remove all empty lines. TWiki inserts
<p /> paragraph tags on empty lines, which causes problems if done between HTML tags that do not allow paragraph tags, like for example between table tags. - Remove leading spaces. TWiki might interpret some text as lists.
- Do not span a tag over more than one line
-
Script tags may be filtered out, at the discretion of your sysadmin
-
If you're pasting in preformatted HTML text and notice problems, check the file in a text processor with no text wrap. Also, save without hard line breaks on text wrap, in your HTML editing program.

TWiki converts shorthand notation to HTML for display. To copy a fully marked-up page, simply view source in your browser and save the contents. If you need to save HTML frequently, you may want to check out
TWiki:Plugins/PublishAddOn.
NOTE: TWiki requires that the opening and closing angle brackets -
<...> - of an HTML tag
must be on the same line, or the tag will be broken.
Script tags
You can use HTML
<script> tags in for your TWiki applications. However note that your TWiki administrator can disable
<script> in topics, and may have chosen to do so for security considerations. TWiki markup and
TWikiVariables are
not expanded inside script tags.
Hyperlinks
Being able to create links without any special formatting is a core TWiki feature, made possible with
WikiWords and inline URLs.
Internal Links
- GoodStyle is a WikiWord that links to the GoodStyle topic located in the current APS Sahaja Yoga web.
- NotExistingYet? is a topic waiting to be written. Create the topic by clicking on the ?. (Try clicking, but then, Cancel - creating the topic would wreck this example!)
External Links
-
http://..., https://..., ftp://..., gopher://..., news://..., file://..., telnet://... and mailto:...@... are linked automatically.
- Email addresses like
name@domain.com are linked automatically.
-
[[Square bracket rules]] let you easily create non-WikiWord links.- You can also write
[[http://yahoo.com Yahoo home page]] as an easier way of doing external links with descriptive text for the link, such as Yahoo home page.
TWiki Variables
TWiki Variables are names that are enclosed in percent signs
% that are expanded on the fly.
-
%TOC% : Automatically generates a table of contents based on headings in a topic - see the top of this page for an example.
-
%WEB% : The current web, is TWiki.
-
%TOPIC% : The current topic name, is TextFormattingRules.
-
%ATTACHURL% : The attachment URL of the current topic. Example usage: If you attach a file to a topic you can refer to it as %ATTACHURL%/image.gif to show the URL of the file or the image in your text.
-
%INCLUDE{"SomeTopic"}% : Server side include, includes another topic. The current APS Sahaja Yoga web is the default web. Example: %INCLUDE{"TWiki.SiteMap"}%
-
%SEARCH{"sushi"}% : Inline search showing the search result embedded in a topic. FormattedSearch gives you control over formatting, useful for creating web-based applications.
- TWikiPreferences defines some site-wide variables. Among others:
- Line break: Write
%BR% to start a new line. - Colored text: Write:
%RED% Red %ENDCOLOR% and %BLUE% blue %ENDCOLOR% colors to get: Red and blue colors. - Documentation Graphics: Write:
%H% Help, %T% Tip, %X% Alert to get:
Help,
Tip,
Alert. For more info see TWikiDocGraphics.
- To "escape" a variable, prefix it with an exclamation mark. Write:
!%SOMEVARIABLE% to get: %SOMEVARIABLE%.
TWikiPlugin Formatting Extensions
Plugins can extend the functionality of TWiki into many other areas. There are a huge number of TWiki plugins available from the
Plugins web on TWiki.org.
Currently enabled plugins on this TWiki installation, as listed by
%PLUGINDESCRIPTIONS%:
- CalendarPlugin: (disabled)
- CommentPlugin (Dakar, 6827): Allows users to quickly post comments to a page without an edit/preview/save cycle.
- EditTablePlugin (Dakar, 6827): Edit TWiki tables using edit fields, date pickers and drop down boxes
- HeadlinesPlugin (Dakar, 6827): Build news portals that show headline news based on RSS news feeds from news sites.
- ImageGalleryPlugin (3.1): Displays image gallery with auto-generated thumbnails from attachments.
- InterwikiPlugin (Dakar, $Rev: 7338$): Link
ExternalSite:Page text to external sites based on aliases defined in the %RULESTOPIC% topic - PreferencesPlugin (Dakar, 6827): Allows editing of preferences using fields predefined in a form
- RenderListPlugin (Dakar, $Rev: 7338$): Render bullet lists in a variety of formats
- SlideShowPlugin (Dakar, $Rev: 7338$): Create web based presentations based on topics with headings.
- SmiliesPlugin (Dakar, 6827): Render smilies as icons, like
:-) for
or :cool: for :cool: - SpreadSheetPlugin (Dakar, 6827): Add spreadsheet calculation like
"$SUM( $ABOVE() )" to tables located in APS Sahaja Yoga topics. - TablePlugin (Dakar, 6850): Control attributes of tables and sorting of table columns
Check on current Plugin status and settings for this site in
TWikiPreferences.
Common Editing Errors
TWiki formatting rules are fairly simple to use and quick to type. However, there are some things to watch out for, taken from the
TextFormattingFAQ:
- Q: Text enclosed in angle brackets like
<filename> is not displayed. How can I show it as it is?- A: The
'<' and '>' characters have a special meaning in HTML, they define HTML tags. You need to escape them, so write '<' instead of '<', and '>' instead of '>'.
Example: Type 'prog <filename>' to get 'prog <filename>'.
- Q: Why is the
'&' character sometimes not displayed?- A: The
'&' character has a special meaning in HTML, it starts a so called character entity, i.e. '©' is the © copyright character. You need to escape '&' to see it as it is, so write '&' instead of '&'.
Example: Type 'This & that' to get 'This & that'.
TWiki Variables
Special text strings expand on the fly to display user data or system info
TWikiVariables are text strings -
%VARIABLE% - that expand into content whenever a page is rendered for viewing. Some variables can even take parameters -
%VARIABLE{parameter="value"}%.
- To leave a variable unexpanded, precede it with an exclamation point, e.g. type
!%TOPIC% to get %TOPIC%. - Variables are expanded relative to the topic they are used in, not the topic they are defined in.
- Optional plugins may extend the set of predefined variables
Setting Variables
You can set variables in all the following places:
- local site level in TWikiPreferences
- web level in WebPreferences of each web
- user level in individual user topics in Main web
- session variables (if sessions are enabled)
- topic level in topics in webs
Settings at higher-numbered levels override settings of the same variable at lower numbered levels, unless the variable was included in the setting of FINALPREFERENCES at a lower-numbered level, in which case it is locked at the value it has at that level.
There are many
predefined variables defined by default, and many more may already have been defined for your site. You can put %ALL_VARIABLES% into a topic anywhere in your TWiki to get a full listing of the variables defined there.
The syntax for setting Variables is the same anywhere in TWiki (on its own TWiki bullet line, including nested bullets):
[multiple of 3 spaces] * [space] Set [space] VARIABLENAME [space] = [value]
Examples:
Spaces between the = sign and the value will be ignored. You can split a value over several lines by starting following lines with [multiple of 3 spaces] - as long as you don't try to use * as the first character on the following line.
Example:
* Set VARIABLENAME = value starts here
and continues here
Whatever you include in your Variable will be expanded on display, exactly as if it had been entered directly.
Example: Create a custom logo variable
- To place a logo anywhere in a web by typing
%MYLOGO%, define the Variable on the web's WebPreferences page, and upload a logo file, ex: mylogo.gif. You can upload by attaching the file to WebPreferences, or, to avoid clutter, to any other topic in the same web, ex: LogoTopic - Sample variable setting in WebPreferences:-
Set MYLOGO = %PUBURL%/TWiki/LogoTopic/mylogo.gif
You can also set preference variables on a topic by clicking the link
Edit topic preference settings under
More topic actions. Preferences set in this manner are not visible in the topic text, but take effect nevertheless.
Access Control Variables
You should review
TWikiAccessControl for details about security settings, which are managed using
TWikiVariables.
Local values for variables
Certain topics (a users home topic, web site and default preferences topics) have a problem; variables defined in those topics can have two meanings. For example, consider a user topic. A user may want to use a double-height edit box when they are editing their home topic - but
only when editing their home topic. The rest of the time, they want to have a normal edit box. This separation is achieved using
Local in place of
Set in the variable definition. For example, if the user sets the following in their home topic:
* Set EDITBOXHEIGHT = 10
* Local EDITBOXHEIGHT = 20
Then when they are editing any other topic, they will get a 10 high edit box. However when they are editing their home topic, they will get a 20 high edit box.
Local can be used wherever a preference needs to take a different value depending on where the current operation is being performed.
Use this powerful feature with great care! %ALL_VARIABLES% can be used to get a listing of the values of all variables in their evaluation order, so you can see variable scope if you get confused.
Predefined Variables
Most predefined variables return values that were either set in the configuration when TWiki was installed, or taken from server info (like current username, or date and time). Some, like =%SEARCH%, are powerful and general tools.
-
Predefined variables can be overridden by Preferences variables -
Plugins may extend the set of predefined variables see individual Plugins topics for details -
Take the time to thoroughly read through ALL preference variables. If you actively configure your site, review variables periodically. They cover a wide range of functions, and it can be easy to miss the one perfect variable for something you have in mind. For example, see %INCLUDINGTOPIC%, %INCLUDE%, and the mighty %SEARCH%.
This version of TWiki - Sun, 06 Nov 2005 build 7330 - predefines the following variables
ACTIVATEDPLUGINS -- list of currently activated plugins
- Syntax:
%ACTIVATEDPLUGINS% - Expands to: CommentPlugin, EditTablePlugin, HeadlinesPlugin, ImageGalleryPlugin, InterwikiPlugin, PreferencesPlugin, RenderListPlugin, SlideShowPlugin, SmiliesPlugin, SpreadSheetPlugin, TablePlugin
- Related: PLUGINDESCRIPTIONS, FAILEDPLUGINS, PLUGINVERSION
ATTACHURL -- full URL for attachments in the current topic
ATTACHURLPATH -- path of the attachment URL of the current topic
AUTHREALM -- authentication realm
- String defined as {AuthRealm} in
configure. This is used in certain password encodings, and in login templates as part of the login prompt. - Syntax:
%AUTHREALM% - Expands to: Enter your LoginName. (Typically First name and last name, no space, no dots, capitalized, e.g. JohnSmith, unless you chose otherwise). Visit TWikiRegistration if you do not have one.
- Related: TWikiUserAuthentication, SESSIONID, SESSIONVAR, LOGIN, LOGOUT, SESSION_VARIABLE
BASETOPIC -- base topic where an INCLUDE started
- The name of the topic where a single or nested INCLUDE started - same as
%TOPIC% if there is no INCLUDE - Syntax:
%BASETOPIC% - Related: BASEWEB, INCLUDINGTOPIC, INCLUDE, TOPIC
BASEWEB -- base web where an INCLUDE started
- The web name where the includes started, e.g. the web of the first topic of nested includes. Same as
%WEB% in case there is no include. - Syntax:
%BASEWEB% - Related: BASETOPIC, INCLUDINGWEB, INCLUDE, WEB
DATE -- signature format date
DISPLAYTIME -- display time
DISPLAYTIME{"format"} -- formatted display time
- Formatted time - either GMT or Local server time, depending on setting in configure. Same format qualifiers as
%GMTIME% - Syntax:
%DISPLAYTIME{"format"}% - Example:
%DISPLAYTIME{"$hou:$min"}% expands to 21:22 - Related: DISPLAYTIME, GMTIME, SERVERTIME
ENCODE{"string"} -- encodes a string
- Syntax:
%ENCODE{"string"}% - Supported parameters:
| Parameter: | Description: | Default: |
"string" | String to encode | required (can be empty) |
type="entity" | Encode special characters into HTML entities, like a double quote into " | URL encoding |
type="url" | Encode special characters for URL parameter use, like a double quote into %22 | (this is the default) |
- Example:
%ENCODE{"spaced name"}% expands to spaced%20name - Related: URLPARAM
ENDSECTION{"name"} -- Marks the end of a named section
- Syntax:
%ENDSECTION{"name"}% - Supported parameters:
| Parameter: | Description: | Default: |
"name" | Name of the section. Must be unique inside a topic, and must match with a previous %SEcTION% tag. | Mandatory parameter without a default |
- Related: INCLUDE, SECTION
FAILEDPLUGINS -- debugging for plugins that failed to load, and handler list
FORMFIELD{"format"} -- renders a field in the form attached to some topic
- Syntax:
%FORMFIELD{"fieldname"}% - Supported parameters:
| Parameter: | Description: | Default: |
"fieldname" | The name of a TWiki form field | required |
topic="..." | Topic where form data is located. May be of the form Web.TopicName | Current topic |
format="..." | Format string. $value expands to the field value, and $title expands to the field title | "$value" |
default="..." | Text shown when no value is defined for the field | "" |
alttext="..." | Text shown when field is not found in the form | "" |
- Example:
%FORMFIELD{"ProjectName" topic="Projects.SushiProject" default="(not set)" alttext="ProjectName field found"}% - Related: SEARCH
GMTIME -- GM time
GMTIME{"format"} -- formatted GM time
- Syntax:
%GMTIME{"format"}% - Supported variables:
| Variable: | Unit: | Example |
$seconds | seconds | 59 |
$minutes | minutes | 59 |
$hours | hours | 23 |
$day | day of month | 31 |
$wday | day of the Week (Sun, Mon, Tue, Wed, Thu, Fri, Sat) | Thu |
$dow | day of the week (Sun = 0) | 2 |
$week | number of week in year (ISO 8601) | 34 |
$month | month in ISO format | Dec |
$mo | 2 digit month | 12 |
$year | 4 digit year | 1999 |
$ye | 2 digit year | 99 |
$tz | either "GMT" (if set to gmtime), or "Local" (if set to servertime) | GMT |
$iso | ISO format timestamp | 2010-07-31T21:22Z |
$rcs | RCS format timestamp | 2010/07/31 21:22:48 |
$http | E-mail & http format timestamp | Sat, 31 Jul 2010 21:22:48 GMT |
$epoch | Number of seconds since 00:00 on 1st January, 1970 | 1280611368 |
- Variables can be shortened to 3 characters
- Example:
%GMTIME{"$day $month, $year - $hour:$min:$sec"}% expands to 31 Jul, 2010 - 21:22:48 -
Note: When used in a template topic, this variable will be expanded when the template is used to create a new topic. See TWikiTemplates for details. - Related: DISPLAYTIME, GMTIME, SERVERTIME
HOMETOPIC -- home topic in each web
HTTP -- get HTTP headers
- Called with the name of an HTTP header field, returns its value. Capitalization and the use of hyphens versus underscores are not significant.
- Syntax:
%HTTP% - Syntax:
%HTTP{'Header-name'}% - Examples:
%HTTP% | |
%HTTP{"Accept-language"}% | en-us,en;q=0.5 |
%HTTP{"User-Agent"}% | CCBot/1.0 (+http://www.commoncrawl.org/bot.html) |
- Note: You can see the HTTP headers your browser sends to the server on a number of sites e.g. http://www.ericgiguere.com/tools/http-header-viewer.html
- Related: HTTPS, REMOTE_ADDR, REMOTE_PORT, REMOTE_USER
HTTPS -- get HTTPS headers
- The same as %HTTP but operates on the HTTPS environment variables present when the SSL protocol is in effect. Can be used to determine whether SSL is turned on.
- Syntax:
%HTTPS% - Syntax:
%HTTPS{'Header-name'}% - Related: HTTP, REMOTE_ADDR, REMOTE_PORT, REMOTE_USER
HTTP_HOST -- environment variable
ICON{"name"} -- small documentation graphic or icon of common attachment types
- Small graphic (commonly 16x16 pixels) used to enhance topics. Specify the name of the graphic.
- A set of 16x16 pixel icons of common attachment types is provided. Specify file type only, file name, or full path name.
- Syntax:
%ICON{"name"}% or %ICON{"type"}% - Graphic samples:
arrowbright,
bubble,
choice-yes,
hand - Filetype samples:
bmp,
doc,
gif,
hlp,
html,
mp3,
pdf,
ppt,
txt,
xls,
xml,
zip - Example:
%ICON{"info"}% expands to 
- Related: TWikiPreferences, FileAttachments, TWikiDocGraphics
ICONPATH{"name"} -- url path of small documentation graphic or icon of common attachment types
IF{"condition" ...} -- simple conditionals
- Syntax:
%IF{"CONDITION" then="THEN" else="ELSE"}% - In the example above, if
CONDITION evaluates to TRUE, then THEN will be shown; otherwise ELSE will be shown. - Related: IfStatements has more information on how to write
%IF{}% statements - Related: $IF() of SpreadSheetPlugin
INCLUDE{"page"} -- include other topics or web pages
- Syntax:
%INCLUDE{"page" ...}% - Supported parameters:
| Parameter: | Description: | Default: |
"SomeTopic" | The name of a topic located in the current web, i.e. %INCLUDE{"WebNotify"}% | |
"Web.Topic" | A topic in another web, i.e. %INCLUDE{"TWiki.SiteMap"}% | |
"http://..." | A full qualified URL, i.e. %INCLUDE{"http://twiki.org/"}% if the URL resolves to an attachment file on the server this will automatically translate to a server-side include. | |
pattern="..." | A RegularExpression pattern to include a subset of a topic or page | none |
rev="1.2" | Include a previous topic revision; N/A for URLs | top revision |
warn="off" | Warn if topic include fails: Fail silently (if off); output default warning (if set to on); else, output specific text (use $topic for topic name) | on preferences setting |
section="name" | Includes only the specified section, as defined in the included topic by the SECTION and ENDSECTION tags | |
Any other parameters will be defined as variables within the scope of the included topic. For example, %INCLUDE{"AnotherTopic" PONE="val 1" PTWO="val 2"}% will result in %PONE% and %PTWO% being defined within the included topic. - Example: To include a part of a webpage, use this pattern:
%INCLUDE{"http://some.page.com/index.html" pattern="^.*?BEFORE(.*)AFTER.*" }%, where BEFORE is the part of the page just before the inclusion, and AFTER is the part just after the inclusion. - Related: BASETOPIC, BASEWEB, INCLUDINGTOPIC, INCLUDINGWEB, IncludeTopicsAndWebPages, STARTINCLUDE, STOPINCLUDE, SECTION, ENDSECTION
INCLUDINGTOPIC -- name of topic that includes current topic
- The name of the topic that includes the current topic - same as
%TOPIC% in case there is no include - Syntax:
%INCLUDINGTOPIC% - Related: BASETOPIC, INCLUDINGWEB, INCLUDE, TOPIC
INCLUDINGWEB -- web that includes current topic
- The web name of the topic that includes the current topic - same as
%WEB% if there is no INCLUDE. - Syntax:
%INCLUDINGWEB% - Related: BASEWEB, INCLUDINGTOPIC, INCLUDE, WEB
LANGUAGES -- TWiki available languages
- list the languages available (as PO files) to TWiki. Those are the languages in which TWiki's user interface is available.
- Syntax:
%LANGUAGES{...}% - Supported parameters:
| Parameter: | Description: | Default: |
format | format for each item. See below for variables available in the format string. | " * $langname" |
sep | separator between items. | "\n" (newline) |
-
format variables: | Variable | Meaning |
$langname | language's name, as informed by the translators |
$langtag | language's tag. Ex: en, pt-br, etc. |
LOCALSITEPREFS -- web.topicname of site preferences topic
- The full name of the local site preferences topic. This topic is read for preferences before TWiki.%TWIKIPREFSTOPIC% is read.
- Syntax:
%LOCALSITEPREFS% - Expands to: Main.TWikiPreferences
LOGIN -- present a full login link
LOGOUT -- present a full logout link
MAKETEXT -- creates text using TWiki's I18N infrastructure
- Syntax =
%MAKETEXT{"string" args="..."} - Supported parameters:
| Parameter | Description | Default |
"text" or string="text" | The text to be displayed. | none |
args="param1, param2" | a comma-separated list of arguments to be interpolated in the string, replacing the [_N] placeholders in it. | none |
- Examples:
-
%MAKETEXT{string="Notes:"}%
expands to
Notes: -
%MAKETEXT{"Contact [_1] if you have any questions." args="%WIKIWEBMASTER%"}%
expands to
Contact webmaster if you have any questions. -
%MAKETEXT{"Did you want to [[[_1]][reset [_2]'s password]]?" args="TWiki.ResetPassword,%WIKIUSERNAME%"}%
expands to
Did you want to reset Main.TWikiGuest's password?
- Note that TWiki will translate the
string to the current user's language only if it has such string in its translation table for that language.
MAINWEB -- name of Main web
META -- displays meta-data
- Provided mainly for use in templates, this variable generates the parts of the topic view that relate to meta-data (attachments, forms etc.) The
formfield item is the most likely to be useful to casual users. - Syntax:
%META{ "item" ...}% - Parameters:
| Item | Options | Description |
"formfield" | name="..." - name of the field. The field value can be shortened as described in FormattedSearch for $formfield | Show a single form field |
"form" | none | Generates the table showing the form fields. See Form Templates |
"attachments" | all="on" to show hidden attachments | Generates the table showing the attachments |
"moved" | none | Details of any topic moves |
"parent" | dontrecurse="on": By default recurses up tree, this has some cost. nowebhome="on": Suppress WebHome. prefix="...": Prefix that goes before parents, but only if there are parents, default "". suffix="...": Suffix, only appears if there are parents, default "". separator="...": Separator between parents, default is " > ". | Generates the parent link |
- Related: METASEARCH
METASEARCH -- special search of meta data
- Syntax:
%METASEARCH{...}% - Supported parameters:
| Parameter: | Description: | Default: |
type="topicmoved" | What sort of search is required? "topicmoved" if search for a topic that may have been moved "parent" if searching for topics that have a specific parent i.e. its children "field" if searching for topics that have a particular form field value (use the name and value parameters to specify which field to search) | required |
web="%WEB%" | Wiki web to search: A web, a list of webs separated by whitespace, or all webs. | current web |
topic="%TOPIC%" | The topic the search relates to, for topicmoved and parent searches | current topic |
name | form field to search, for field type searches. May be a regular expression (see SEARCH). | |
value | form field value, for field type searches. May be a regular expression (see SEARCH). | |
title="Title" | Text that is prefixed to any search results | empty |
default="none" | Default text shown if no search hit | empty |
- Example:
%METASEARCH{type="topicmoved" web="%WEB%" topic="%TOPIC%" title="This topic used to exist and was moved to: "}% - Example: You may want to use this in WebTopicViewTemplate and WebTopicNonWikiTemplate:
%METASEARCH{type="parent" web="%WEB%" topic="%TOPIC%" title="Children: "}% - Example:
%METASEARCH{type="field" name="Country" value="China"}% - Related: SEARCH, META
NOP -- template text not to be expanded in instantiated topics
- Syntax:
%NOP% - Syntax:
%NOP{...}% - Available in template topics only. See TWikiTemplates for details. In normal topic text, simply expands to whatever is in the curly braces (if anything).
NOTIFYTOPIC -- name of the notify topic
PLUGINDESCRIPTIONS -- list of plugin descriptions
- Syntax:
%PLUGINDESCRIPTIONS% - Expands to:
- CalendarPlugin: (disabled)
- CommentPlugin (Dakar, 6827): Allows users to quickly post comments to a page without an edit/preview/save cycle.
- EditTablePlugin (Dakar, 6827): Edit TWiki tables using edit fields, date pickers and drop down boxes
- HeadlinesPlugin (Dakar, 6827): Build news portals that show headline news based on RSS news feeds from news sites.
- ImageGalleryPlugin (3.1): Displays image gallery with auto-generated thumbnails from attachments.
- InterwikiPlugin (Dakar, $Rev: 7338$): Link
ExternalSite:Page text to external sites based on aliases defined in the %RULESTOPIC% topic - PreferencesPlugin (Dakar, 6827): Allows editing of preferences using fields predefined in a form
- RenderListPlugin (Dakar, $Rev: 7338$): Render bullet lists in a variety of formats
- SlideShowPlugin (Dakar, $Rev: 7338$): Create web based presentations based on topics with headings.
- SmiliesPlugin (Dakar, 6827): Render smilies as icons, like
:-) for
or :cool: for :cool: - SpreadSheetPlugin (Dakar, 6827): Add spreadsheet calculation like
"$SUM( $ABOVE() )" to tables located in APS Sahaja Yoga topics. - TablePlugin (Dakar, 6850): Control attributes of tables and sorting of table columns
- Related: ACTIVATEDPLUGINS, FAILEDPLUGINS, PLUGINVERSION
PLUGINVERSION -- the version of the TWiki Plugin API
- This is the
$TWiki::Plugins::VERSION number, also indicating the version of the Func module - Syntax:
%PLUGINVERSION% - Expands to:
1.1 - Related: PLUGINVERSION{"name"}, WIKIVERSION
PLUGINVERSION{"name"} -- the version of an installed Plugin
PUBURL -- the base URL of attachments
- Syntax:
%PUBURL% - Expands to:
http://www.sahajayogaverona.it/wiki/pub - Example: You can refer to a file attached to another topic with
%PUBURL%/%WEB%/OtherTopic/image.gif - Related: ATTACHURL, PUBURLPATH, SCRIPTURL, FileAttachments
PUBURLPATH -- the base URL path of attachments
QUERYSTRING -- full, unprocessed string of parameters to this URL
- Syntax: %QUERYSTRING%
- Expands to:
- String of all the URL parameters that were on the URL used to get to the current page. For example, if you add ?name=Samantha;age=24;eyes=blue to this URL you can see this in action. This string can be appended to a URL to pass parameter values on to another page.
-
Note: URLs built this way are typically restricted in length, typically to 2048 characters. If you need more space than this, you will need to use an HTML form and %URLPARAM{}%. - Related: URLPARAM
REMOTE_ADDR -- environment variable
REMOTE_PORT -- environment variable
REMOTE_USER -- environment variable
REVINFO -- revision information of current topic
REVINFO{"format"} -- formatted revision information of topic
- Syntax:
%REVINFO{"format"}% - Supported parameters:
| Parameter: | Description: | Default: |
"format" | Format of revision information, see supported variables below | "r1.$rev - $date - $wikiusername" |
web="..." | Name of web | Current web |
topic="..." | Topic name | Current topic |
rev="1.5" | Specific revison number | Latest revision |
- Supported variables in format:
| Variable: | Unit: | Example |
$web | Name of web | Current web |
$topic | Topic name | Current topic |
$rev | Revison number. Prefix r1. to get the usual r1.5 format | 5 |
$date | Revision date | 11 Jul 2004 |
$username | Login username of revision | jsmith |
$wikiname | WikiName of revision | JohnSmith |
$wikiusername | WikiName with Main web prefix | Main.JohnSmith |
- Example:
%REVINFO{"$date - $wikiusername" rev="1.1"}% returns revision info of first revision - Related: REVINFO
SCRIPTNAME -- name of current script
- The name of the current script is shown, including script suffix, if any (for example
viewauth.cgi) - Syntax:
%SCRIPTNAME% - Expands to:
view - Related: SCRIPTSUFFIX, SCRIPTURL, SCRIPTURLPATH
SCRIPTSUFFIX -- script suffix
- Some APS Sahaja Yoga installations require a file extension for CGI scripts, such as
.pl or .cgi - Syntax:
%SCRIPTSUFFIX% - Expands to:
- Related: SCRIPTNAME, SCRIPTURL, SCRIPTURLPATH
SCRIPTURL -- script URL of APS Sahaja Yoga
- Syntax:
%SCRIPTURL% - Expands to:
http://www.sahajayogaverona.it/wiki/bin - Example: To get the authenticated version of current topic write
%SCRIPTURL%/viewauth%SCRIPTSUFFIX%/%WEB%/%TOPIC% which expands to http://www.sahajayogaverona.it/wiki/bin/viewauth/TWiki/TWikiVariablesNtoZ - Related: PUBURL, SCRIPTNAME, SCRIPTSUFFIX, SCRIPTURLPATH
SCRIPTURLPATH -- script URL path of APS Sahaja Yoga
SEARCH{"text"} -- search content
- Inline search, shows a search result embedded in a topic
- Syntax:
%SEARCH{"text" ...}% - Supported parameters:
| Parameter: | Description: | Default: |
"text" | Search term. Is a keyword search, literal search or regular expression search, depending on the type parameter. SearchHelp has more | required |
search="text" | (Alternative to above) | N/A |
web="Name" web="Main, Know" web="all" | Comma-separated list of webs to search. The special word all means all webs that doe not have the NOSEARCHALL variable set to on in their WebPreferences. You can specifically exclude webs from an all search using a minus sign - for example, web="all,-Secretweb". | Current web |
topic="WebPreferences" topic="*Bug" | Limit search to topics: A topic, a topic with asterisk wildcards, or a list of topics separated by comma. | All topics in a web |
excludetopic="Web*" excludetopic="WebHome, WebChanges" | Exclude topics from search: A topic, a topic with asterisk wildcards, or a list of topics separated by comma. | None |
type="keyword" type="literal" type="regex" | Do a keyword search like soap "web service" -shampoo; a literal search like web service; or RegularExpression search like soap;web service;!shampoo | %SEARCHVAR- DEFAULTTYPE% preferences setting (literal) |
scope="topic" scope="text" scope="all" | Search topic name (title); the text (body) of topic; or all (both) | "text" |
order="topic" order="created" order="modified" order="editby" order "formfield(name)"= | Sort the results of search by the topic names, topic creation time, last modified time, last editor, or named field of TWikiForms. The sorting is done web by web; in case you want to sort across webs, create a formatted table and sort it with TablePlugin's initsort | Sort by topic name |
limit="all" limit="16" | Limit the number of results returned. This is done after sorting if order is specified | All results |
date="..." | limits the results to those pages with latest edit time in the given TimeInterval. | All results |
reverse="on" | Reverse the direction of the search | Ascending search |
casesensitive="on" | Case sensitive search | Ignore case |
bookview="on" | BookView search, e.g. show complete topic text | Show topic summary |
nonoise="on" | Shorthand for nosummary="on" nosearch="on" nototal="on" zeroresults="off" noheader="on" noempty="on" | Off |
| =nosummary="on" | Show topic title only | Show topic summary |
nosearch="on" | Suppress search string | Show search string |
noheader="on" | Suppress search header Topics: Changed: By: | Show search header, unless seach is inline and a format is specified (Cairo compatibility) |
nototal="on" | Do not show number of topics found | Show number |
zeroresults="off" | Suppress all output if there are no hits | zeroresults="on", displays: "Number of topics: 0" |
noempty="on" | Suppress results for webs that have no hits. | Show webs with no hits |
header="..." format="..." | Custom format results: see FormattedSearch for usage, variables & examples | Results in table |
expandvariables="on" | Expand variables before applying a FormattedSearch on a search hit. Useful to show the expanded text, e.g. to show the result of a SpreadSheetPlugin %CALC{}% instead of the formula | Raw text |
multiple="on" | Multiple hits per topic. Each hit can be formatted. The last token is used in case of a regular expression ";" and search | Only one hit per topic |
nofinalnewline="on" | If on, the search variable does not end in a line by itself. Any text continuing immediately after the search tag on the same line will be rendered as part of the table generated by the search, if appropriate. | off |
separator=", " | Line separator between hits | Newline "$n" |
- Example:
%SEARCH{"wiki" web="Main" scope="topic"}% - Example with format:
%SEARCH{"FAQ" scope="topic" nosearch="on" nototal="on" header="| *Topic: * | *Summary: * |" format="| $topic | $summary |"% (displays results in a table with header - details) -
Hint: If the TWiki:Plugins.TablePlugin is installed, you may set a %TABLE{}% variable just before the %SEARCH{}% to alter the output of a search. Example: %TABLE{ tablewidth="90%" }% - Related: METASEARCH, TOPICLIST, WEBLIST, FormattedSearch
SECTION{"name"} -- Marks the start of a named section
SERVERTIME -- server time
SERVERTIME{"format"} -- formatted server time
- Same format qualifiers as
%GMTIME% - Syntax:
%SERVERTIME{"format"}% - Example:
%SERVERTIME{"$hou:$min"}% expands to 23:22 -
Note: When used in a template topic, this variable will be expanded when the template is used to create a new topic. See TWikiTemplates for details. - Related: DISPLAYTIME, GMTIME, SERVERTIME
SESSION_VARIABLE -- get, set or clear a session variable
SESSIONID -- unique ID for this session
SESSIONVAR -- name of CGI and session variable that stores the session ID
SPACEDTOPIC -- topic name, spaced and URL-encoded
- The current topic name with added spaces, for regular expression search of backlinks
- Syntax:
%SPACEDTOPIC% - Expands to:
T%20*Wiki%20*Variables%20*Nto%20*Z -
Hint: This variable is provided almost exclusively for generating URLs for searching for backlinks to topics - Related: TOPIC
STARTINCLUDE -- start position of topic text if included
- If present in included topic, start to include text from this location up to the end, or up to the location of the
%STOPINCLUDE% variable. A normal view of the topic shows everything exept the %STARTINCLUDE% variable itself. An optional parameter can be used to control whether the content is expanded. - Syntax:
%STARTINCLUDE% - Syntax:
%STARTINCLUDE{param}%- If param does not expand to a non-zero integer, then nothing will be included.
- Related: INCLUDE, STOPINCLUDE
STATISTICSTOPIC -- name of statistics topic
STOPINCLUDE -- end position of topic text if included
- If present in included topic, stop to include text at this location and ignore the remaining text. A normal view of the topic shows everyting exept the
%STOPINCLUDE% variable itself. - Syntax:
%STOPINCLUDE% - Related: INCLUDE, STARTINCLUDE
TOC -- table of contents of current topic
TOC{"Topic"} -- table of contents
- Syntax:
%TOC{"SomeTopic" ...}% - Table of Contents. Shows a TOC that is generated automatically based on headings of a topic. Headings in WikiSyntax (
"---++ text") and HTML ("<h2>text</h2>") are taken into account. Any heading text after "!!" is excluded from the TOC; for example, write "---+!! text" if you do not want to list a header in the TOC - Supported parameters:
| Parameter: | Description: | Default: |
"TopicName" | topic name | Current topic |
web="Name" | Name of web | Current web |
depth="2" | Limit depth of headings shown in TOC | 6 |
title="Some text" | Title to appear at top of TOC | none |
- Example:
%TOC{depth="2"}% - Example:
%TOC{"TWikiDocumentation" web="TWiki" title="Contents:"}% - Example: see TWiki:Sandbox.TestTopicInclude
-
Hint: TOC will generate links to the headings, so when a reader clicks on a heading it will jump straight where that heading is anchored in the text. If you have two headings with exactly the same text, then their anchors will also be identical and they won't be able to jump to them. To make the anchors unique, you can add an invisible HTML comment to the text of the heading. This will be hidden in normal view, but will force the anchors to be different. For example, ---+ Heading <!--5-->. - Related: TOC
TOPIC -- name of current topic
TOPICLIST{"format"} -- topic index of a web
- The "format" defines the format of one topic item. It may include variables: The
$name variable gets expanded to the topic name; the $web variable gets expanded to the name of the web. - Syntax:
%TOPICLIST{"format" ...}% - Supported parameters:
| Parameter: | Description: | Default: |
"format" | Format of one line, may include $name and $web variables | "$name" |
format="format" | (Alternative to above) | "$name" |
separator=", " | line separator | "\n" (new line) |
web="Name" | Name of web | Current web |
- Example:
%TOPICLIST{" * $web.$name"}% creates a bullet list of all topics - Example:
%TOPICLIST{separator=", "}% creates a comma separated list of all topics - Example:
%TOPICLIST{" <option>$name</option>"}% creates an option list (for drop down menus) - Related: SEARCH, WEBLIST
TWIKIWEB -- name of TWiki documentation web
- The web containing all documentation and site-wide preference settings for APS Sahaja Yoga
- Syntax:
%TWIKIWEB% - Expands to:
TWiki - Related: MAINWEB
URLPARAM{"name"} -- get value of a URL parameter
- Returns the value of a URL parameter.
- Syntax:
%URLPARAM{"name"}% - Supported parameters:
| Parameter: | Description: | Default: |
"name" | The name of a URL parameter | required |
default="..." | Default value in case parameter is empty or missing | empty string |
newline="<br />" | Convert newlines in textarea to other delimiters | no conversion |
encode="entity" | Encode special characters into HTML entities, like a double quote into ". This is needed if text is put into an HTML form field | no encoding |
encode="url" | Encode special characters for URL parameter use, like a double quote into %22 | no encoding |
multiple="on" multiple="[[$item]]" | If set, gets all selected elements of a <select multiple="multiple"> tag. A format can be specified, with $item indicating the element, e.g. multiple="Option: $item" | first element |
separator=", " | Separator between multiple selections. Only relevant if multiple is specified | "\n" (new line) |
- Example:
%URLPARAM{"skin"}% returns print for a .../view/TWiki/TWikiVariablesNtoZ?skin=print URL. -
Note: When used in a template topic, this variable will be expanded when the template is used to create a new topic. See TWikiTemplates for details. -
Note: There is a risk that this variable could be misused for cross-site scripting. - Related: SEARCH, FormattedSearch, QUERYSTRING
USERNAME -- your login username
- TWiki makes names available in three formats: USERNAME like
jsmith, WIKINAME like JohnSmith and WIKIUSERNAME like Main.JohnSmith. Un-authenticated users are all TWikiGuest. - Syntax:
%USERNAME% - Expands to:
Ospite -
Note: When used in a template topic, this variable will be expanded when the template is used to create a new topic. See TWikiTemplates for details. - Related: REMOTE_USER, WIKINAME, WIKIUSERNAME, TWikiUserAuthentication
USERLANGUAGE -- current user's language
- Returns the language code for the language used as the current user. This is the language actually used by TWiki Internationalization (e.g. in user interface).
- The language is detected from the user's browser, unless some site/web/user/session-defined setting overrides it:
- Is the
LANGUAGE preference is set, it's used as user's language instead of any language detected from the browser. - Avoid to define it
LANGUAGE at a non per-user way, so each user can choose his/her preferred language.
- Related: LANGUAGES
VAR{"NAME" web="Web"} -- get a preference value from another web
- Syntax:
%VAR{"NAME" web="Web"}% - Example: To get
%WEBBGCOLOR% of the Main web write %VAR{"WEBBGCOLOR" web="Main"}%, which expands to =#FFCCFF = - Related: WEBPREFSTOPIC
WEB -- name of current web
WEBLIST{"format"} -- index of all webs
- List of all webs. Hidden webs are excluded, e.g. webs with a
NOSEARCHALL=on preference variable. The "format" defines the format of one web item. The $name variable gets expanded to the name of the web, $qname gets expanded to double quoted name, $marker to marker where web matches selection. - Syntax:
%WEBLIST{"format" ...}% - Supported parameters:
| Parameter: | Description: | Default: |
"format" | Format of one line, may include $name variable. (to support HierarchicalWebs?, there are 2 added variables $webindent and $indentedname) | "$name" |
format="format" | (Alternative to above) | "$name" |
separator=", " | line separator | "\n" (new line) |
webs="public" | comma sep list of Web, public expands to all non-hidden | "public" |
marker="selected" | Text for $marker where item matches selection, otherwise equals "" | "selected" |
selection="%WEB%" | Current value to be selected in list | section="%WEB%" |
- Example:
%WEBLIST{" * [[$name.WebHome]]"}% creates a bullet list of all webs. - Example:
%WEBLIST{"<option $marker value=$qname>$name</option>" webs="Trash,public" selection="TWiki" separator=" "}% Dropdown of all public Webs + Trash Web, current Web highlighted. - Related: TOPICLIST, SEARCH
WEBPREFSTOPIC -- name of web preferences topic
WIKIHOMEURL -- site home URL
-
Note: DEPRECATED, use %WIKILOGOURL% defined in WebPreferences instead. This variables value is defined in lib/TWiki.cfg::$wikiHomeUrl which is marked deprecated. Will be removed in future versions.
WIKINAME -- your Wiki username
WIKIPREFSTOPIC -- name of site-wide preferences topic
WIKITOOLNAME -- name of your TWiki site
WIKIUSERNAME -- your Wiki username with web prefix
- Your %WIKINAME% with Main web prefix, useful to point to your APS Sahaja Yoga home page
- Syntax:
%WIKIUSERNAME% - Expands to:
Main.TWikiGuest, renders as TWikiGuest -
Note: When used in a template topic, this variable will be expanded when the template is used to create a new topic. See TWikiTemplates for details - Related: REMOTE_USER, USERNAME, WIKINAME
WIKIUSERSTOPIC -- name of topic listing all registers users
WIKIVERSION -- the version of the installed TWiki engine
File Attachments
Each topic can have one or more files of any type attached to it by using the Attach screen to upload (or download) files from your local PC. Attachments are stored under revision control: uploads are automatically backed up; all previous versions of a modified file can be retrieved.
What Are Attachments Good For?
File Attachments can be used to archive data, or to create powerful customized groupware solutions, like file sharing and document management systems, and quick Web page authoring.
Document Management System
- You can use Attachments to store and retrieve documents (in any format, with associated graphics, and other media files); attach documents to specific TWiki topics; collaborate on documents with full revision control; distribute documents on a need-to-know basis using web and topic-level access control; create a central reference library that's easy to share with an user group spread around the world.
File Sharing
- For file sharing, FileAttachments on a series of topics can be used to quickly create a well-documented, categorized digital download center for all types of files: documents; graphics and other media; drivers and patches; applications; anything you can safely upload!
Web Authoring
- Through your Web browser, you can easily upload graphics (or sound files, or anything else you want to link to on a page) and place them on a single page, or use them across a web, or site-wide.
- NOTE: You can also add graphics - any files - directly, typically by FTP upload. This requires FTP access, and may be more convenient if you have a large number of files to load. FTP-ed files can't be managed using browser-based Attachment controls. You can use your browser to create TWikiVariables shortcuts, like this %H% =
.
Uploading Files
- Click on the
Attach link at the bottom of the page. The Attach screen lets you browse for a file, add a comment, and upload it. The uploaded file will show up in the File Attachment table.- NOTE: The topic must already exist. It is a two step process if you want to attach a file to a non-existing topic; first create the topic, then add the file attachment.
- Any type of file can be uploaded. Some files that might pose a security risk are renamed, ex:
*.php files are renamed to *.php.txt so that no one can place code that would be read in a .php file. - The previous upload path is retained for convenience. In case you make some changes to the local file and want to upload it, again you can copy the previous upload path into the Local file field.
- TWiki can limit the file size. This is defined by the
%ATTACHFILESIZELIMIT% variable of the TWikiPreferences, currently set at 10000 KB.-
It's not recommended to upload files greater than a few hundred K through a browser. Large files can be extremely slow-loading, and often time out. Use an FTP site for large file uploads.
- From TWiki:Codev.DakarRelease, a new {AutoAttachPubDir} configuration option is provided:
- When enabled, all files in a topic's attachment directory are shown as attachments to the topic - even if they were directly copied to the directory and never attached by using an 'Attach' link.
- For details see TWiki:Codev.AutomaticAttachments
Downloading Files
-
NOTE: There is no access control on individual attachments. If you need control over single files, create a separate topic per file and set topic-level access restrictions for each.
Moving Attachment Files
An attachment can be moved between topics.
- Click
Manage on the Attachment to be moved. - On the control screen, select the new web and/or topic.
- Click
Move. The attachment and its version history are moved. The original location is stored as topic Meta Data.
Deleting Attachments
Move unwanted Attachments to web
Trash, topic
TrashAttachment.
Linking to Attached Files
- To reference an attachment located in another topic, enter:
-
%PUBURL%/%WEB%/OtherTopic/Sample.txt (if it's within the same web) -
%PUBURL%/Otherweb/OtherTopic/Sample.txt (if it's in a different web)
- Attached HTML files and text files can be inlined in a topic. Example:
-
Attach file: Sample.txt -
Edit topic and write text: %INCLUDE{"%ATTACHURL%/Sample.txt"}%
- GIF, JPG and PNG images can be attached and shown embedded in a topic. Example:
-
Attach file: Smile.gif -
Edit topic and write text: %ATTACHURL%/Smile.gif -
Preview: text appears as
, an image.
File Attachment Contents Table
Files attached to a topic are displayed in a directory table, displayed at the bottom of the page, or optionally, hidden and accessed when you click
Attach.
File Attachment Controls
Clicking on a
Manage link takes you to a new page that looks a bit like this (depending on what
skin is selected):
- The first table is a list of all attachments, including their attributes. An
h means the attachment is hidden, it isn't listed when viewing a topic.
- The second table is all the versions of the attachment. Click on View to see that version. If it's the most recent version, you'll be taken to an URL that always displays the latest version, which is usually what you want.
- To change the comment on an attachment, enter a new comment and then click Change properties. Note that the comment listed against the specific version will not change, however the comment displayed when viewing the topic does change.
- To hide/unhide an attachment, enable the
Hide file checkbox, then click Change properties.
Known Issues
- Unlike topics, attachments are not locked during editing. As a workaround, you can change the comment to indicate an attachment file is being worked on - the comment on the specific version isn't lost, it's there when you list all versions of the attachment.
- Attachments are not secured. Anyone can read them if they know the name of the web, topic and attachment.
TWiki Forms
Structured data (key-value pairs) attached to topics, according to a specification given in another topic
Overview
When forms are enabled for a web, and a form is selected in a topic, the form data is shown when the topic is viewed, and the form can be edited in edit mode. You can define an as many different form types as you want, though you can only have one form per topic.
Defining a Form Template
A Form Template specifies the fields in a form. A Form Template is simply a page containing a TWiki table, where each row of the table is one form field.
Form Template Elements
- form template - a set of fields defining a form
- A web can use one or more form templates
- form - additional meta data (besides the freeform TEXTAREA) attached to a topic
- Within a form-enabled web, individual topics can have a form or no form
- form field - a named item in a form (also known as a key)
- field type - selects the field type:
| Input type | Type field | Size field | Value field |
| One or more checkboxes | checkbox | number of items per line | comma list of item labels |
| One or more checkboxes, plus Set and Clear buttons | checkbox+buttons | (same) | (same) |
| One or more radio buttons (radio buttons are mutually exclusive; only one can be selected) | radio | (same) | (same) |
| Read-only label text | label | ignored | text |
| Drop-down menu or scrollable box | select | 1 for drop down, 2 and up for scrollable box | comma-separated list of options |
| A one-line text field | text | text box width in number of characters | initial text, if a new topic is created with a form template |
| A text box | textarea | columns x rows, e.g. 80x6; default size is 40x5 | initial text, if a new topic is created with a form template |
- field value - one or more values from a fixed set (select, checkbox, radio type) or free-form (label, text, text area).
Defining a Form
- Create a new topic with your form name:
YourForm, ExpenseReport, InfoCategory, RecordReview, whatever you need. - Create a TWiki table, with each column head representing one element of an entry field:
Name, Type, Size, Values, Tooltip message, and Attributes (see sample below). - For each field, fill in a new line; for the type of field, select from the list.
- Save the topic (you can later choose to enable/disable individual forms).
Example: WebForm
| *Name* | *Type* | *Size* | *Values* | *Tooltip message* | *Attributes* |
| TopicClassification | select | 1 | NoDisclosure, PublicSupported, PublicFAQ | blah blah... | |
| OperatingSystem | checkbox | 3 | OsHPUX, OsLinux, OsSolaris, OsWin | blah blah... | |
| OsVersion | text | 16 | | blah blah... | |
You can also retrieve possible values for select, checkbox or radio types from other topics:
Example: WebForm
- In the WebForm topic, define the form:
Leave the Values field blank.
- Then in the TopicClassification topic, define the possible values:
| Name | Type | Tooltip message |
| NoDisclosure | option | blah blah... |
| Public Supported | option | blah blah... |
| Public FAQ | option | blah blah... |
Field values can also be obtained as the result of a
FormattedSearch. For example,
%SEARCH{"Office$" scope="topic" web="%MAINWEB%" nototal="on" nosummary="on" nosearch="on" regex="on" format="Main.$topic" separator=", " }%
when used in the value field of the form definition, will take the set of field values to be all topic names in the Main web which end in "Office".
Notes:- A very few field names are reserved. if you try to use one of these names, TWiki will automatically append an underscore to the name when the form is used.
- The field value will be used to initialize a field when a form is created, unless specific values are given by the topic template or query parameters. The first item in the list for a select or radio type is the default item. For label, text, and text area fields that value may also contain commas. Checkbox fields cannot be initialized through the form template.
- The topic definition is not read when a topic is viewed.
- Field names can include any text, but you should stick to alphanumeric characters. If you want to use a non-wikiname for a select, checkbox or radio field, and want to get the values from another topic, you can use
[[...]] links. This notation can also be used when referencing another topic to obtain field values, but one wants to use a name other than the topic name as the name of the field. - Field names have to be unique. If the same name is necessary (as when the field values for several fields are obtained from the same topic), an alternative name must be assigned using the
[[...]] notation. - The topic defining field values can also be generated through a FormattedSearch, which must yield a suitable table as the result.
- Form definition topics can be protected in the usual manner, using TWikiAccessControl, to limit who can change the form template and/or individual value lists. Note that view access is required to be able to edit topics that use the form definition, though view access to the form definition is not required to view a topic where the form has been used.
- The
Tooltip message column is used as a tooltip for the field name (only if field name is a WikiName) - you only see the tooltip in edit view. - The
Attributes column is used to define special behavior for that form field (multiple attributes can be entered, with or without separators):- An attribute
H indicates that this field should not be shown in view mode. However, the field is available for editing and storing information. - An attribute
M indicates that this field is mandatory. The topic cannot be saved unless a value is provided for this field. If the field is found empty during topic save, an error is raised and the user is redirected to an oops page. Mandatory fields are indicated by an asteriks next to the field name.
Enabling Forms by Web
Forms have to be enabled for each individual web. The
WEBFORMS variable in
WebPreferences is optional and defines a list of possible form templates.
Example:- Set WEBFORMS = BugForm, FeatureForm, Books.BookLoanForm
- With
WEBFORMS enabled, an extra button is added to the edit view. If the topic doesn't have a Form, an Add Form button appears at the end of the topic. If a Form is present, a Change button appears in the top row of the Form. The buttons open a screen that enables selection of a form specified in WEBFORMS, or the No form option.
Creating a new topic with a Form (and default values)
- A default Form Template (new topics get this default form) can be provided by creating the
WebTopicEditTemplate topic in a web and adding a form to it. Initial Form values can be set there.
- Additionally a new topic can be given a Form using the
formtemplate parameter in the (edit or save) URL. Initial values can then be provided in the URLs or as form values: - If you want to make a TWikiApplication? where you need an automatically generated unique topicname, you can use 10 X's in the edit / save URL, and they will be replaced on topic save with a count value
- the Codev:DevelopBranch bugs tracking system uses something like
http://develop.twiki.org/~develop/cgi-bin/edit/Bugs/ItemXXXXXXXXXX?formtemplate=Bugs.ItemTemplate&_T=0501092906

Initial values will not be submitted to the form of a new topic if you only use the formtemplate parameter.
Setting Up Multiple Form Options
- The
WEBFORMS variable in WebPreferences lists the different forms that can be selected from the topic editor.
- New topics with a form are created by simple HTML forms asking for a topic name. For example, you can have a
SubmitExpenseReport topic where you can create new expense reports, a SubmitVacationRequest topic, and so on. These can specify the required template topic with its associated form.
Changing a form
- You can change a form definition, and TWiki will try to make sure you don't lose any data from the topics that use that form.
- If you change the form definition, the changes will not take affect in a topic that uses that form until you edit and save it.
- If you add a new field to the form, then it will appear next time you edit a topic that uses the form.
- If you delete a field from the form, or change a field name, then the data will not be visible when you edit the topic (the changed form definition will be used). If you save the topic, the old data will be lost (though thanks to revision control, you can always see it in older versions of the topic)
Searching for Form Data
TWikiForms accept user-input data, stored as
TWikiMetaData. Meta data also contains program-generated info about changes, attachments, etc. To find, format and display form and other meta data, see
TWikiMetaData,
FORMFIELD,
SEARCH and
METASEARCH variables in
TWikiVariables, and
TWiki Formatted Search for various options.
Example
TWiki users often want to have an overview of topics they contributed to. With the $formfield parameter it is easy to display the value of a classification field next to the topic link:
| *Topic* | *Classification* |
%SEARCH{"Main.UserName" scope="text" regex="off" nosearch="on" nototal="on" order="modified" reverse="on"
format="|<b>[[$web.$topic][$topic]]</b> |<nop>$formfield(TopicClassification) |" web="Sandbox"}%
Extending the range of form data types
Several plugins allow you to extend the range of data types accepted by forms. For example, the
TWiki:Plugins.DateFieldPlugin lets you add a 'date' type to the available data types. All data types are single-valued (can only have one value) with the following exceptions:
- any type name starting with
checkbox - any type name with
+multi anywhere in the name
Types with names like this can both take multiple values.
Gotcha!
- Some browsers may strip linefeeds from
text fields when a topic is saved. If you need linefeeds in a field, make sure it is a textarea.
Importing Category Table Data
Very, very old TWiki releases used a system called the "TWikiCategoryTable". Later releases support automatic import of this data.
On upgrading from the previous TWiki, a Form Template topic has to be built for each web that used a Category Table, recreating the fields and values from the old
twikicatitems.tmpl. The replacement Form Template must be set as the first item in the
WebPreferences variable
WEBFORMS. If missing, pages will display, but attempting to edit results in an error message.
The new Form Template system should work with old Category Table data with no special conversion. Data is assigned to Meta variables the first time an imported topic is edited and saved in the new system.

If things aren't working correctly, there may be useful entries in
data/warning.txt.
TWiki Templates
Definition of the templates used to render all HTML pages displayed in TWiki
Overview
There are three types of template:
- Master Templates: Define blocks of text for use in other templates
- HTML Page Templates: Define the layout of APS Sahaja Yoga pages
- Template Topics: Define default text when you create a new topic
All three types of template use the TWiki template system.
The TWiki Template System
Templates are plain text with embedded
template directives that tell TWiki how to compose blocks of text together to create something new.
How Template Directives Work
- Template directives are embedded in templates.
- Directives are of the form
%TMPL:<key>% and %TMPL:<key>{"attr"}%. - Directives:
-
%TMPL:INCLUDE{"file"}%: Includes a template file. The file is found as described below. -
%TMPL:DEF{"block"}%: Define a block. Text between this and the %TMPL:END% directive is not used in-place, but is saved for later use with %TMPL:P. Leading and trailing whitespace is ignored. -
%TMPL:END%: Ends a block definition. -
%TMPL:P{"var"}%: Includes a previously defined block. -
%{...}%: is a comment.
- Two-pass processing lets you use a variable before or after declaring it.
- Templates and TWikiSkins work transparently and interchangeably. For example, you can create a skin that overloads only the
twiki.tmpl master template, like twiki.print.tmpl, that redefines the header and footer. -
Use of template directives is optional: templates work without them. -
NOTE: Template directives work only for templates: they do not get processed in normal topic text.
TMPL:P also supports simple parameters. For example, given the definition
%TMPL:DEF{"x"}% x%P%z%TMPL:END% then
%TMPL:P{"x" P="y"}% will expand to
xyz.
Note that parameters can simply be ignored; for example=%TMPL:P{"x"}%= will expand to x%P%z.
Any alphanumeric characters can be used in parameter names. You are highly recommended to use parameter names that cannot be confused with
TWikiVariables.
Note that three parameter names,
context,
then and
else are
reserved. They are used to support a limited form of "if" condition that you can use to select which of two templates to use, based on a
context identifier:
%TMPL:DEF{"link_inactive"}%<input type="button" disabled value="Link>%TMPL:END%
%TMPL:DEF{"link_active"}%<input type="button" onclick="link()" value="Link" />%TMPL:END%
%TMPL:P{context="inactive" then="inactive_link" else="active_link"}% for %CONTEXT%
When the "inactive" context is set, then this will expand the "link_inactive" template; otherwise it will expand the "link_active" template.
See
IfStatements for details of supported context identifiers.
Finding Templates
Templates are stored either in the
twiki/templates directory, or can also be read from user topics. As an example,
twiki/templates/view.tmpl is the default template file for the
twiki/bin/view script.
Templates that are included using
%TMPL:INCLUDE% are also found using the same search algorithm, unless you explicitly put
'.tmpl' at the end of the template name. In this case, the string is assumed to be the full name of a template in the
templates directory, and the algorithm isn't used.
TWiki uses the following search order to determine which template file or topic to use for a particular script. The
skin path is set as described in
TWikiSkins.
- templates/web/script.skin.tmpl for each skin on the skin path
- templates/script.skin.tmpl for each skin on the skin path
- templates/web/script.tmpl
- templates/script.tmpl
- web.topic if the template name can be parsed into web.topic (e.g. "Myweb.MyTemplate")
- web.SkinSkinScriptTemplate for each skin on the skin path
- web.ScriptTemplate
- TWiki.SkinSkinScriptTemplate for each skin on the skin path
- TWiki.ScriptTemplate
Legend:- script refers to the script name, e.g
view, edit - Script refers to the same, but with the first character capitalized, e.g
View - skin refers to a skin name, e.g
dragon, pattern. All skins are checked at each stage, in the order they appear in the skin path. - Skin refers to the same, but with the first character capitalized, e.g
Dragon - web refers to the current web
The template name may also be a full
Web.Topic name, in which case the search is:
Master Templates
Master templates use the block definition directives (
%TMPL:DEF and
%TMPL:END%) to define common sections that appear in two or more other templates.
twiki.tmpl is the default master template.
| Template variable: | Defines: |
| %TMPL:DEF{"sep"}% | "|" separator |
| %TMPL:DEF{"htmldoctype"}% | Start of all HTML pages |
| %TMPL:DEF{"standardheader"}% | Standard header (ex: view, index, search) |
| %TMPL:DEF{"simpleheader"}% | Simple header with reduced links (ex: edit, attach, oops) |
| %TMPL:DEF{"standardfooter"}% | Footer, excluding revision and copyright parts |
| %TMPL:DEF{"oops"}% | Skeleton of oops dialog |
HTML Page Templates
HTML page templates are files of HTML mixed with template directives that tell TWiki how to build up an HTML page. As described above, the template system supports the use of 'include' directives that let you re-use the same sections of HTML - such as headers and footers - in several different places.
TWiki uses HTML page templates when composing the output from all actions, like topic view, edit, and preview. This allows you to change the look and feel of all pages by editing just a few template files.
HTML page templates are also used in the definition of
TWikiSkins.
Template Topics
Template topics define the default text for new topics. There are three types of template topic:
When you create a new topic, TWiki locates a topic to use as a content template according to the following search order:
- A topic name specified by the
templatetopic CGI parameter- if no web is specified, the current web is searched first and then the TWiki web
- WebTopicEditTemplate in the current web
- WebTopicEditTemplate in the TWiki web
Edit Template Topics and Variable Expansion
The following variables get expanded when a user creates a new topic based on a template topic:
| Variable: | Description: |
%DATE% | Signature format date. See TWikiVariables |
%GMTIME% | Date/time. See TWikiVariables |
%GMTIME{...}% | Formatted date/time. See TWikiVariables |
%NOP% | A no-operation variable that gets removed. Useful to prevent a SEARCH from hitting an edit template topic; also useful to escape a variable like %URLPARAM%NOP%{...}% |
%NOP{ ... }% | Text that gets removed when a new topic based on the template is created. See notes below. |
%SERVERTIME% | Date/time. See TWikiVariables |
%SERVERTIME{...}% | Formatted date/time. See TWikiVariables |
%USERNAME% | Login name of user who is instantiating the new topic, e.g. Ospite |
%URLPARAM{"name"}% | Value of a named URL parameter |
%WIKINAME% | WikiName of user who is instantiating the new topic, e.g. TWikiGuest |
%WIKIUSERNAME% | User name of user who is instantiating the new tpoic, e.g. Main.TWikiGuest |
The
NOP tag is used to embed text that you
do not want expanded when a new topic based on the template is created. For example, you might want to write in the template:
This template can only be changed by:
* Set ALLOWTOPICCHANGE = WikiMastersGroup
This will restrict who can edit the template, but will get removed when a topic based on the template is created.
%NOP% (or %NOP{}% can be used to prevent expansion of TWiki variables that would otherwise be expanded during topic creation e.g.
%SERVERTIME%.
Notes:-
%NOP{ ... }% can span multiple lines. - The scan for the closing
}% pattern is "non-greedy", that is, it stops at the first occurence. That means you have to protect variables with parameters located inside %NOP{ ... }%. To do this, insert a %NOP% between } and %. Example: %NOP{ %GMTIME{"$year"}%NOP%% }%.
All other variables are unchanged, e.g. are carried over "as is" into the new topic.
Template Topics in Action
Here is an example for creating new topics based on a specific template topic:
The above form asks for a topic name. A hidden input tag named
templatetopic specifies
ExampleTopicTemplate as the template topic to use. Here is the HTML source of the form:
<form name="new" action="%SCRIPTURLPATH%/edit%SCRIPTSUFFIX%/%INTURLENCODE{"%WEB%"}%/">
* New example topic:
<input type="text" name="topic" value="ExampleTopic%SERVERTIME{$yearx$mox$day}%" size="23" />
<input type="hidden" name="templatetopic" value="ExampleTopicTemplate" />
<input type="hidden" name="topicparent" value="%TOPIC%" />
<input type="hidden" name="onlywikiname" value="on" />
<input type="hidden" name="onlynewtopic" value="on" />
<input type="submit" class="twikiSubmit" value="Create" />
(date format is <nop>YYYYxMMxDD)
</form>
See
TWikiScripts for details of the parameters that the
edit script understands.
TIP: You can use the
%WIKIUSERNAME% and
%DATE% variables in your topic templates to include the signature of the person creating a new topic. The variables are expanded into fixed text when a new topic is created. The standard signature is:
-- %WIKIUSERNAME% - %DATE%
Master Templates by Example
Attached is an example of an oops based template
oopsbase.tmpl and an example oops dialog
oopstest.tmpl based on the base template. %A%
NOTE: This isn't the release version, just a quick, simple demo.
Base template oopsbase.tmpl
The first line declares a delimiter variable called "sep", used to separate multiple link items. The variable can be called anywhere by writing
%TMPL:P{"sep"}%
%TMPL:DEF{"sep"}% | %TMPL:END%
<html>
<head>
<title> %WIKITOOLNAME% . %WEB% . %TOPIC% %.TMPL:P{"titleaction"}%</title>
<base href="%SCRIPTURL%/view%SCRIPTSUFFIX%/%WEB%/%TOPIC%">
<meta name="robots" content="noindex">
</head>
<body bgcolor="#FFFFFF">
<table width="100%" border="0" cellpadding="3" cellspacing="0">
<tr>
<td bgcolor="%WEBBGCOLOR%" rowspan="2" valign="top" width="1%">
<a href="%WIKIHOMEURL%">
<img src="%PUBURLPATH%/wikiHome.gif" border="0"></a>
</td>
<td>
<b>%WIKITOOLNAME% . %WEB% . </b><font size="+2">
<B>%TOPIC%</b> %TMPL:P{"titleaction"}%</font>
</td>
</tr>
<tr bgcolor="%WEBBGCOLOR%">
<td colspan="2">
%TMPL:P{"webaction"}%
</td>
</tr>
</table>
--- ++ %TMPL:P{"heading"}%
%TMPL:P{"message"}%
<table width="100%" border="0" cellpadding="3" cellspacing="0">
<tr bgcolor="%WEBBGCOLOR%">
<td valign="top">
Topic <b>%TOPIC%</b> . {
%TMPL:P{"topicaction"}%
}
</td>
</tr>
</table>
</body>
|
Test template oopstest.tmpl
Each oops template basically just defines some variables and includes the base template that does the layout work.
%TMPL:DEF{"titleaction"}% (test =titleaction=) %TMPL:END%
%TMPL:DEF{"webaction"}% test =webaction= %TMPL:END%
%TMPL:DEF{"heading"}%
Test heading %TMPL:END%
%TMPL:DEF{"message"}%
Test =message=. Blah blah blah blah blah blah blah blah blah blah blah...
* Some more blah blah blah blah blah blah blah blah blah blah...
* Param1: %PARAM1%
* Param2: %PARAM2%
* Param3: %PARAM3%
* Param4: %PARAM4%
%TMPL:END%
%TMPL:DEF{"topicaction"}%
Test =topicaction=:
[[%WEB%.%TOPIC%][OK]] %TMPL:P{"sep"}%
[[%TWIKIWEB%.TWikiRegistration][Register]] %TMPL:END%
%TMPL:INCLUDE{"oopsbase"}%
|
Sample screen shot of oopstest.tmpl
With URL:
.../bin/oops/Sandbox/TestTopic2?template=oopstest¶m1=WebHome¶m2=WebNotify
Related Topics: TWikiSkins,
DeveloperDocumentationCategory,
AdminDocumentationCategory
TWiki Skins
Skins overlay regular templates with alternate header/footer layouts; topic text is not affected
Overview
Skins are customized
TWikiTemplates files. You can use skins to change the look of a APS Sahaja Yoga topic, for example, the layout of the header and footer. Rendered text between header and footer does
not change. You can also use skins to define an alternate view, like a view optimized for printing.
Defining Skins
Skin files are located in the
twiki/templates directory and are named with the syntax:
<scriptname>.<skin>.tmpl. For example, the
Printable skin for the
view template is
view.print.tmpl. Skin files may also be defined in TWiki topics - see
TWikiTemplates for details.
Use the existing
TWikiTemplates (like
view.tmpl) or skin files as a base for your own skin, name it for example
view.myskin.tmpl.

Two skin names have
reserved meanings;
text skin, and skin names starting with
rss have _hard-coded meanings.
See below?.
Variables in Skins
You can use
template variables,
TWikiVariables, and other predefined variables to compose your skins. Some commonly used variables in skins:
| Variable: | Expanded to: |
%WEBLOGONAME% | Filename of web logo |
%WEBLOGOIMG% | Image URL of web logo |
%WEBLOGOURL% | Link of web logo |
%WEBLOGOALT% | Alt text of web logo |
%WIKILOGOURL% | Link of page logo |
%WIKILOGOIMG% | Image URL of page logo |
%WIKILOGOALT% | Alt text of page logo |
%WEBBGCOLOR% | Web-specific background color, defined in the WebPreferences |
%WIKITOOLNAME% | The name of your TWiki site |
%SCRIPTURL% | The script URL of TWiki |
%SCRIPTSUFFIX% | The script suffix, ex: .pl, .cgi |
%WEB% | The name of the current web. Note: It is recommended to URL-encode the variable in form actions with %INTURLENCODE{"%WEB%"}% for proper handling in an internationalized environment |
%TOPIC% | The name of the current topic. Note: It is recommended to URL-encode the variable in form actions with %INTURLENCODE{"%TOPIC%"}% for proper handling in an internationalized environment |
%WEBTOPICLIST% | Common links of current web, defined in the WebPreferences. It includes a #GoBox |
%TEXT% | The topic text, e.g. the content that can be edited |
%META{"form"}% | TWikiForm, if any |
%META{"attachments"}% | FileAttachment table |
%META{"parent"}% | The topic parent |
%EDITTOPIC% | Edit link |
%REVTITLE% | The revision title, if any, ex: (r1.6) |
%REVINFO% | Revision info, ex: r1.6 - 24 Dec 2002 - 08:12 GMT - TWikiGuest |
%WEBCOPYRIGHT% | Copyright notice, defined in the WebPreferences |
%BROADCASTMESSAGE% | Broadcast message at the beginning of your view template, can be used to alert users of scheduled downtimes; is set in TWikiPreferences |
The "Go" Box and Navigation Box
The
%WEBTOPICLIST% includes a "Jump" box to jump to a topic. The box also understands URLs, e.g. you can type
http://www.google.com/ to jump to an external web site. The feature is handy if you build a skin that has a select box of frequently used links, like Intranet home, employee database, sales database and such. A little JavaScript gets into action on the onSelect method of the select tag to fill the selected URL into the "Go" box field, then submits the form.
Here is an example form that has a select box and the "Go" box for illustration purposes. You need to have JavaScript enabled for this to work:
Using Cascading Style Sheets
Although work is underway at
TWiki:Codev.CssClassNames, the regular templates files currently do not use style sheets. Many skin developers, however, choose to use them; it helps in separating style from content.
Example: To use a style sheet for the broadcast message, add this to
view.myskin.tmpl:
<style type="text/css">
.broadcastmessage {
background: yellow; display:block;
border-style:solid;border-width: 2px;border-color:red;
}
.broadcastmessage strong {color: red}
</style>
Then add a div tag to the
%BROADCASTMESSAGE% variable located after the
#PageTop anchor or after the opening form tag:
<div class="broadcastmessage"> %BROADCASTMESSAGE% </div>
Attachment Tables
Controlling the look and feel of attachment tables is a little bit more complex than for the rest of a skin. By default the attachment table is a standard TWiki table, and the look is controlled in the same way as other tables. In a very few cases you may want to change the
content of the table as well.
The format of standard attachment tables is defined through the use of special
TWiki template macros which by default are defined in the
templates/twiki.tmpl template using the
%TMPL:DEF macro syntax described in
TWikiTemplates. These macros are:
| Macro | Description |
ATTACH:files:header | Standard title bar |
ATTACH:files:row | Standard row |
ATTACH:files:footer | Footer for all screens |
ATTACH:files:header:A | Title bar for upload screens, with attributes column |
ATTACH:files:row:A | Row for upload screen |
ATTACH:files:footer:A | Footer for all screens |
The format of tables of file versions in the Upload screen are also formattable, using the macros:
| Macro | Description |
ATTACH:versions:header | Header for versions table on upload screen |
ATTACH:versions:row | Row format for versions table on upload screen |
ATTACH:versions:footer | Footer for versions table on upload screen |
The
ATTACH:row macros are expanded for each file in the attachment table, using the following special tags:
| Tag | Description |
%A_URL% | URL that will recover the file |
%A_REV% | Revision of this file e.g. "1.1" |
%A_ICON% | A file icon suitable for representing the attachment content |
%A_FILE% | The name of the file |
%A_SIZE% | The size of the file |
%A_DATE% | The date the file was uploaded |
%A_USER% | The user who uploaded it |
%A_COMMENT% | The comment they put in when uploading it |
%A_ATTRS% | The attributes of the file as seen on the upload screen e.g "h" for a hidden file |
Note: it is easy to change the look and feel for an entire site by editing the
twiki.tmpl template file. However, to simplify upgrading, you should avoid doing this. Instead, write a skin-specific template file e.g.
attach.myskin.tmpl and use
%TMPL:INCLUDE{attach.myskin.tmpl}% to include it in each of your skin files. As long as it it included
after twiki.tmpl, your macro definitions will override the defaults defined there.
Packaging and Publishing Skins
See
TWiki:Plugins/SkinPackagingHowTo and
TWiki:Plugins/SkinDeveloperFAQ
Browsing Installed Skins
You can try all installed skins in
TWikiSkinBrowser.
Activating Skins
TWiki uses a
skin search path, which lets you combine skins additively. The skin path is defined using a combination of
TWikiVariables and URL parameters.
TWiki works by asking for a template for a particular function - for example, 'view'. The detail of how templates are searched for is described in
TWikiTemplates, but in summary, the templates directory is searched for a file called
view.skin.tmpl, where
skin is the name of the skin e.g.
pattern. If no template is found, then the fallback is to use
view.tmpl. Each skin on the path is searched for in turn. For example, if you have set the skin path to
local,pattern then
view.local.tmpl will be searched for first, then
view.pattern.tmpl and finally
view.tmpl.
The basic skin is defined by setting the %SKIN%
TWikiVariable?:
-
Set SKIN = catskin,bearskin
You can also add a parameter to the URL: ?skin=catskin,bearskin
Setting %SKIN% (or the
?skin parameter in the URL) replaces the existing skin path setting. You can also
extend the existing skin path as well, using
covers.
This pushes a different skin to the front of the skin search path (so for our example above, that final skin path will be
ruskin,catskin,bearskin). There is also an equivalent
cover URL parameter.
The full skin path is built up as follows:
%SKIN% (or
?skin if it is set), then
%COVER% is added, then
?cover.
Hard Coded Skins
The
text skin is reserved for TWiki internal use.
Skin names starting with
rss also have a special meaning; if one or more of the skins in the skin path starts with 'rss' then 8-bit characters will be encoded as XML entities in the output, and the
content-type header will be forced to
text/xml.
Related Topics: AdminDocumentationCategory,
DeveloperDocumentationCategory
TWiki Formatted Search Results
Inline search feature allows flexible formatting of search result
The
%SEARCH{...}% variable documented in
TWikiVariables has a fixed format for the search result, that is, a table consisting of topic names and topic summaries. Use the
format="..." parameter to specify a customized format of the search result. The string of the format parameter is typically a bullet list or table row containing variables (such as
%SEARCH{ "food" format="| $topic | $summary |" }%).
Syntax
Two parameters can be used to specify a customized search result:
1.
header="..." parameter
Use the header parameter to specify the header of a search result. It should correspond to the format of the format parameter. This parameter is optional.
Example:
header="| *Topic:* | *Summary:* |"
2.
format="..." parameter
Use the format parameter to specify the format of one search hit.
Example:
format="| $topic | $summary |"
Variables that can be used in the format string:
| Name: | Expands To: |
$web | Name of the web |
$topic | Topic name |
$topic(20) | Topic name, "- " hyphenated each 20 characters |
$topic(30, -<br />) | Topic name, hyphenated each 30 characters with separator "-<br />" |
$topic(40, ...) | Topic name, shortended to 40 characters with "..." indication |
$parent | Name of parent topic; empty if not set |
$parent(20) | Name of parent topic, same hyphenation/shortening like $topic() |
$text | Formatted topic text. In case of a multiple="on" search, it is the line found for each search hit. |
$locked | LOCKED flag (if any) |
$date | Time stamp of last topic update, e.g. 31 Jul 2010 - 21:22 |
$isodate | Time stamp of last topic update, e.g. 2010-07-31T21:22Z |
$rev | Number of last topic revision, e.g. 1.4 |
$username | Login name of last topic update, e.g. jsmith |
$wikiname | Wiki user name of last topic update, e.g. JohnSmith |
$wikiusername | Wiki user name of last topic update, like Main.JohnSmith |
$createdate | Time stamp of topic revision 1.1 |
$createusername | Login name of topic revision 1.1, e.g. jsmith |
$createwikiname | Wiki user name of topic revision 1.1, e.g. JohnSmith |
$createwikiusername | Wiki user name of topic revision 1.1, e.g. Main.JohnSmith |
$summary(options) | Topic summary, just the plain text, all formatting and line breaks discarded. options may contain any of the following: a number (characters shown in the summary), showvarnames (shows variables as VARIABLE and VARIABLE{...}; otherwise removed), noheader (suppresses the headings at the beginning). |
$formname | The name of the form attached to the topic; empty if none |
$formfield(name) | The field value of a form field; for example, $formfield(TopicClassification) would get expanded to PublicFAQ. This applies only to topics that have a TWikiForm |
$formfield(name, 10) | Form field value, "- " hyphenated each 10 characters |
$formfield(name, 20, -<br />) | Form field value, hyphenated each 20 characters with separator "-<br />" |
$formfield(name, 30, ...) | Form field value, shortended to 30 characters with "..." indication |
$pattern(reg-exp) | A regular expression pattern to extract some text from a topic (does not search meta data; use $formfield instead). In case of a multiple="on" search, the pattern is applied to the line found in each search hit. • Specify a RegularExpression that covers the whole text (topic or line), which typically starts with .*, and must end in .* • Put text you want to keep in parenthesis, like $pattern(.*?(from here.*?to here).*) • Example: $pattern(.*?\*.*?Email\:\s*([^\n\r]+).*) extracts the email address from a bullet of format * Email: ... • This example has non-greedy .*? patterns to scan for the first occurance of the Email bullet; use greedy .* patterns to scan for the last occurance • Limitation: Do not use .*) inside the pattern, e.g. $pattern(.*foo(.*)bar.*) does not work, but $pattern(.*foo(.*?)bar.*) does • Note: Make sure that the integrity of a web page is not compromised; for example, if you include an HTML table make sure to include everything including the table end tag |
$count(reg-exp) | Count of number of times a regular expression pattern appears in the text of a topic (does not search meta data). Follows guidelines for use and limitations outlined above under $pattern(reg-exp). Example: $count(.*?(---[+][+][+][+]) .*) counts the number of <H4> headers in a page. |
$n or $n() | New line |
$nop or $nop() | Is a "no operation". This variable gets removed; useful for nested search |
$quot | Double quote ("). Alternatively write \" to escape it |
$percnt | Percent sign (%) |
$dollar | Dollar sign ($) |
Examples
Bullet list showing topic name and summary
Write this:
%SEARCH{ "FAQ" scope="topic" nosearch="on" nototal="on" header=" * *Topic: Summary:*" format=" * [[$topic]]: $summary" }%
To get this:
- Topic: Summary:
- TWikiFAQ: Frequently Asked Questions About APS Sahaja Yoga This is a real FAQ, and also a demo of one easily implemented knowledge base solution. See how it's done, click ...
- TWikiFaqTemplate: FAQ: Answer: Back to: TWikiFAQ
- TextFormattingFAQ: Text Formatting FAQ The most frequently asked questions about text formatting are answered. Also, TextFormattingRules contains the complete TWiki shorthand system ...
Table showing form field values of topics with a form
In a web where there is a form that contains a
TopicClassification field, an
OperatingSystem field and an
OsVersion field we could write:
| *Topic:* | *OperatingSystem:* | *OsVersion:* |
%SEARCH{ "[T]opicClassification.*?value=\"[P]ublicFAQ\"" scope="text" regex="on" nosearch="on" nototal="on" format="| [[$topic]] | $formfield(OperatingSystem) | $formfield(OsVersion) |" }%
To get this:
Extract some text from a topic using regular expression
Write this:
%SEARCH{ "__Back to\:__ TWikiFAQ" scope="text" regex="on" nosearch="on" nototal="on" header="TWiki FAQs:" format=" * $pattern(.*?FAQ\:[\n\r]*([^\n\r]+).*) [[$topic][Answer...]]" }%
To get this:
TWiki FAQs:
- How can I create a simple TWiki Form based application? Answer...
- How do I delete or rename a topic? Answer...
- How do I delete or rename a file attachment? Answer...
- Why does the topic revision not increase when I edit a topic? Answer...
- TWiki has a GPL (GNU General Public License). What is GPL? Answer...
- I've problems with the WebSearch. There is no Search Result on any inquiry. By clicking the Index topic it's the same problem. Answer...
- What happens if two of us try to edit the same topic simultaneously? Answer...
- I would like to install TWiki on my server. Can I get the source? Answer...
- So what is this WikiWiki thing exactly? Answer...
- Everybody can edit any page, this is scary. Doesn't that lead to chaos? Answer...
Nested Search
Search can be nested. For example, search for some topics, then form a new search for each topic found in the first search. The idea is to build the nested search string using a formatted search in the first search.
Here is an example. Let's search for all topics that contain the word "culture" (first search), and let's find out where each topic found is linked from (second search).
- First search:
-
%SEARCH{ "culture" format=" * $topic is referenced by: (list all references)" nosearch="on" nototal="on" }%
- Second search. For each hit we want this search:
-
%SEARCH{ "(topic found in first search)" format="$topic" nosearch="on" nototal="on" separator=", " }%
- Now let's nest the two. We need to escape the second search, e.g. the first search will build a valid second search string. Note that we escape the second search so that it does not get evaluated prematurely by the first search:
- Use
$percnt to escape the leading percent of the second search - Use
\" to escape the double quotes - Use
$dollar to escape the $ of $topic - Use
$nop to escape the }% sequence
Write this:
%SEARCH{ "culture" format=" * $topic is referenced by:$n * $percntSEARCH{ \"$topic\" format=\"$dollartopic\" nosearch=\"on\" nototal=\"on\" separator=\", \" }$nop%" nosearch="on" nototal="on" }%
To get this:
- ATasteOfTWiki is referenced by:
- FormattedSearch is referenced by:
- CalendarPlugin, DakarReleaseNotes, EditTablePlugin, EmptyPlugin, ManagingWebs, PreferencesPlugin, RenderListPlugin, SearchHelp, SearchPatternCookbook, SlideShowPlugin, SpreadSheetPlugin, TWikiDocumentation, TWikiForms, TWikiHistory, TWikiMetaData, TWikiReferenceManual, TWikiScripts, TWikiSearchDotPm, TWikiUISearchDotPm, TWikiUpgradeTo01Dec2001, TWikiUpgradeTo01Feb2003, TWikiVariablesAtoM, TWikiVariablesNtoZ, TextFormattingRules, WelcomeGuest
- TWikiAccessControl is referenced by:
- EditTablePlugin, FileAttachment, MainFeatures, ManagingTopics, ManagingUsers, SitePermissions, SourceCode, TWikiAccessControl, TWikiDocumentation, TWikiForms, TWikiFuncDotPm, TWikiHistory, TWikiPreferences, TWikiReferenceManual, TWikiScripts, TWikiTopics, TWikiTutorial, TWikiUpgradeTo01Dec2000, TWikiUpgradeTo01Dec2001, TWikiUserAuthentication, TWikiVariables, WebPreferences, WelcomeGuest, WikiCulture, WikiWord
- TWikiSite is referenced by:
- AdminToolsCategory, InstantEnhancements, InterwikiPlugin, ManagingWebs, StartingPoints, TWikiDocumentation, TWikiGlossary, TWikiI18NDotPm, TWikiInstallationGuide, TWikiPreferences, TWikiReferenceManual, TWikiRegistration, TWikiSite, TWikiSiteTools, TWikiTopics, TWikiTutorial, TWikiUpgradeTo01Dec2000, TWikiUsersGuide, WabiSabi, WebLeftBar, WebSiteTools, WelcomeGuest, WhatIsWikiWiki, WikiCulture, WikiReferences
- WabiSabi is referenced by:
- WelcomeGuest is referenced by:
- WikiCulture is referenced by:
Note: Nested search can be slow, especially if you nest more then 3 times. Nesting is limited to 16 levels. For each new nesting level you need to "escape the escapes", e.g. write
$dollarpercntSEARCH{ for level three,
$dollardollarpercntSEARCH{ for level four, etc.
Most recently changed pages
Write this:
%SEARCH{ "\.*" scope="topic" regex="on" nosearch="on" nototal="on" order="modified" reverse="on" format="| [[$topic]] | $wikiusername | $date |" limit="7" }%
To get this:
Search with conditional output
A regular expression search is flexible, but there are limitations. For example, you cannot show all topics that are up to exactly one week old, or create a report that shows all records with invalid form fields or fields within a certain range, etc. You need some additional logic to format output based on a condition:
- Specify a search which returns more hits then you need
- For each search hit apply a spreadsheet formula to determine if the hit is needed
- If needed, format and output the result
- Else supress the search hit
This requires the
TWiki:Plugins.SpreadSheetPlugin. The following example shows all topics that are up to exactly one week old.
Write this:
%CALC{$SET(weekold, $TIMEADD($TIME(), -7, day))}%
%SEARCH{ "." scope="topic" regex="on" nosearch="on" nototal="on" order="modified" reverse="on" format="$percntCALC{$IF($TIME($date) < $GET(weekold), <nop>, | [[$topic]] | $wikiusername | $date | $rev |)}$percnt" limit="100" }%
- The first line sets the
weekold variable to the serialized date of exactly one week ago - The SEARCH has a deferred CALC. The
$percnt makes sure that the CALC gets executed once for each search hit - The CALC compares the date of the topic with the
weekold date - If topic is older, a
<nop> is returned, which gets removed at the end of the TWiki rendering process - Otherwise, the search hit is formatted and returned
To get this:
Embedding search forms to return a formatted result
Use an HTML form and an embedded formatted search on the same topic. You can link them together with an
%URLPARAM{"..."}% variable. Example:
Write this:
<form action="%SCRIPTURLPATH%/view%SCRIPTSUFFIX%/%WEB%/%TOPIC%">
Find Topics:
<input type="text" name="q" size="32" value="%URLPARAM{"q"}%" /> <input type="submit" class="twikiSubmit" value="Search" />
</form>
Result:
%SEARCH{ search="%URLPARAM{"q"}%" format=" * $web.$topic: %BR% $summary" nosearch="on" }%
To get this:
Result:
Number of topics: 0
Related Topics: UserDocumentationCategory
TWiki Meta Data
Additional topic data, program-generated or from TWikiForms, is stored in META variable name/value pairs
Overview
TWikiMetaData uses
META variables to store topic data that's separate from the main free-form content. This includes program-generated info like
FileAttachment and topic movement data, and user-defined
TWikiForms info. Use
META variables to format and display Meta Data.
Meta Data Syntax
- Format is the same as in TWikiVariables, except all fields have a key.
-
%META:<type>{key1="value1" key2="value2" ...}%
- Order of fields within the meta variables is not defined, except that if there is a field with key
name, this appears first for easier searching (note the order of the variables themselves is defined).
- Each meta variable is on one line.
-
\n (new line) is represented in values by %_N_ and " (double-quotes) by %_Q_%.
Example of Format
%META:TOPICINFO{version="1.6" date="976762663" author="LastEditorWikiName" format="1.0"}%
text of the topic
%META:TOPICMOVED{from="Codev.OldName" to="Codev.NewName"
by="TopicMoverWikiName" date="976762680"}%
%META:TOPICPARENT{name="NavigationByTopicContext"}%
%META:FILEATTACHMENT{name="Sample.txt" version="1.3" ... }%
%META:FILEATTACHMENT{name="Smile.gif" version="1.1" ... }%
%META:FORM{name="WebFormTemplate"}%
%META:FIELD{name="OperatingSystem" value="OsWin"}%
%META:FIELD{name="TopicClassification" value="PublicFAQ"}%
Meta Data Specifications
The current version of Meta Data is 1.0, with support for the following variables.
META:TOPICINFO
| Key | Comment |
| version | Same as RCS version |
| date | integer, unix time, seconds since start 1970 |
| author | last to change topic, is the REMOTE_USER |
| format | Format of this topic, will be used for automatic format conversion |
META:TOPICMOVED
This is optional, exists if topic has ever been moved. If a topic is moved more than once, only the most recent META:TOPICMOVED meta variable exists in the topic, older ones are to be found in the rcs history.
%META:TOPICMOVED{from="Codev.OldName" to="Codev.NewName" by="talintj" date="976762680"}%
| Key | Comment |
| from | Full name, i.e., web.topic |
| to | Full name, i.e., web.topic |
| by | Who did it, is the REMOTE_USER, not WikiName |
| date | integer, unix time, seconds since start 1970 |
Notes:
- at present version number is not supported directly, it can be inferred from the RCS history.
- there is only one META:TOPICMOVED in a topic, older move information can be found in the RCS history.
META:TOPICPARENT
| Key | Comment |
| name | The topic from which this was created, WebHome if done from Go, othewise topic where ? or form used. Normally just topic, but is full web.topic format if parent is in a different Web. Renaming a Web will then only break a few of these references or they can be scanned and fixed. |
META:FILEATTACHMENT
| Key | Comment |
| name | Name of file, no path. Must be unique within topic |
| version | Same as RCS revision |
| path | Full path file was loaded from |
| size | In bytes |
| date | integer, unix time, seconds since start 1970 |
| user | the REMOTE_USER, not WikiName |
| comment | As supplied when file uploaded |
| attr | h if hidden, optional |
Extra fields that are added if an attachment is moved:
| Key | Comment |
| movedfrom | full topic name - web.topic |
| movedby | the REMOTE_USER, not WikiName |
| movedto | full topic name - web.topic |
| moveddate | integer, unix time, seconds since start 1970 |
META:FORM
| Key | Comment |
| name | A topic name - the topic represents one of the TWikiForms. Can optionally include the web name (i.e., web.topic), but doesn't normally |
META:FIELD
Should only be present if there is a META:FORM entry. Note that this data is used when viewing a topic, the form template definition is not read.
| Key | Name |
| name | Ties to entry in TWikiForms template, is title with all bar alphanumerics and . removed |
| title | Full text from TWikiForms template |
| value | Value user has supplied via form |
Recommended Sequence
There is no absolute need for Meta Data variables to be listed in a specific order within a topic, but it makes sense to do so a couple of good reasons:
- form fields remain in the order they are defined
- the
diff function output appears in a logical order
The recommended sequence is:
-
META:TOPICINFO -
META:TOPICPARENT (optional) - text of topic
-
META:TOPICMOVED (optional) -
META:FILEATTACHMENT (0 or more entries) -
META:FORM (optional) -
META:FIELD (0 or more entries; FORM required)
Viewing Meta Data in Page Source
When viewing a topic the
Raw Text link can be clicked to show the text of a topic (i.e., as seen when editing). This is done by adding
raw=on to URL.
raw=debug shows the meta data as well as the topic data, ex:
debug view for this topic
Rendering Meta Data
Meta Data is rendered with the %META% variable. This is mostly used in the
view,
preview and
edit scripts.
Note: Rendering meta data is currently not supported in topic text. As a workaround, use
FormattedSearch on the current topic only to render form fields.
Current support covers:
| Variable usage: | Comment: |
%META{"form"}% | Show form data, see TWikiForms. |
%META{"formfield"}% | Show form field value. Parameter: name="field_name". Example: %META{ "formfield" name="TopicClassification" }% |
%META{"attachments"}% | Show attachments, except for hidden ones. Options: all="on": Show all attachments, including hidden ones. |
%META{"moved"}% | Details of any topic moves. |
%META{"parent"}% | Show topic parent. Options: dontrecurse="on": By default recurses up tree, at some cost. nowebhome="on": Suppress WebHome. prefix="...": Prefix for parents, only if there are parents, default "". suffix="...": Suffix, only appears if there are parents, default "". separator="...": Separator between parents, default is " > ". |
Known Issues
At present, there is no Meta Data support for Plugins. However, the format is readily extendable and the
Meta.pm code that supports the format needs only minor alteration.
Related Topics: DeveloperDocumentationCategory,
UserDocumentationCategory
TWiki Plugins
Plug-in enhanced feature add-ons, with a Plugin API for developers
Overview
You can add Plugins to extend TWiki functionality, without altering the core code. A plug-in approach lets you:
- add virtually unlimited features while keeping the main TWiki code compact and efficient;
- heavily customize an installation and still do clean updates to new versions of TWiki;
- rapidly develop new TWiki functions in Perl using the Plugin API.
Everything to do with TWiki Plugins - demos, new releases, downloads, development, general discussion - is available at TWiki.org, in the
TWiki:Plugins web.
TWiki plugins are developed and contributed by interested members of the community. Plugins are provided on an 'as is' basis; they are not a part of TWiki, but are independently developed and maintained.
Installing Plugins
Each TWikiPlugin comes with its own documentation: step-by-step installation instructions, a detailed description of any special requirements, version details, and a working example for testing. Many plugins have an install script that automates these steps for you.
Special Requests: Some Plugins need certain Perl modules to be preinstalled on the host system. Plugins may also use other resources, like graphics, other modules, applications, templates. You should be able to find detailed instructions are in the Plugin documentation.
Each Plugin has a standard release page, located in the
TWiki:Plugins web at TWiki.org. There's usually a number of other related pages, such as a developers page, and an appraisal page.
On-Site Pretesting
The recommended approach to testing new Plugins before making them public is to create a second local twiki installation, and test the plugin there. You can allow selected users access to the test area. Once you are satisifed that it won't compromise your main installation, you can install it there as well.
InstalledPlugins shows which Plugins are: 1) installed, 2) loading properly and 3) what
TWiki:Codev.PluginHandlers they invoke. Any failures are shown in the Errors section. The %FAILEDPLUGINS%
TWikiVariable? can be used to debug failures. You may also want to check your webserver error log and the various TWiki log files.
Some Notes on Plugin Performance
The performance of the system depends to some extent on the number of Plugins installed and on the Plugin implementation. Some Plugins impose no measurable performance decrease, some do. You can only really tell by installing the plugin and running experiments yourself. The Apache
ab utility is very useful for doing this.

If you need to install an "expensive" Plugin, and you need its functionality only in one web, you can place the Plugin topic into that web. TWiki will initialize the Plugin only if the Plugin topic is found (which won't be the case for other webs.)
Listing Active Plugins
Plugin status variables let you list all active Plugins wherever needed.
%ACTIVATEDPLUGINS%
On this TWiki site, the enabled Plugins are:
CommentPlugin,
EditTablePlugin,
HeadlinesPlugin,
ImageGalleryPlugin,
InterwikiPlugin,
PreferencesPlugin,
RenderListPlugin,
SlideShowPlugin,
SmiliesPlugin,
SpreadSheetPlugin,
TablePlugin.
%PLUGINDESCRIPTIONS%
- CalendarPlugin: (disabled)
- CommentPlugin (Dakar, 6827): Allows users to quickly post comments to a page without an edit/preview/save cycle.
- EditTablePlugin (Dakar, 6827): Edit TWiki tables using edit fields, date pickers and drop down boxes
- HeadlinesPlugin (Dakar, 6827): Build news portals that show headline news based on RSS news feeds from news sites.
- ImageGalleryPlugin (3.1): Displays image gallery with auto-generated thumbnails from attachments.
- InterwikiPlugin (Dakar, $Rev: 7338$): Link
ExternalSite:Page text to external sites based on aliases defined in the %RULESTOPIC% topic - PreferencesPlugin (Dakar, 6827): Allows editing of preferences using fields predefined in a form
- RenderListPlugin (Dakar, $Rev: 7338$): Render bullet lists in a variety of formats
- SlideShowPlugin (Dakar, $Rev: 7338$): Create web based presentations based on topics with headings.
- SmiliesPlugin (Dakar, 6827): Render smilies as icons, like
:-) for
or :cool: for :cool: - SpreadSheetPlugin (Dakar, 6827): Add spreadsheet calculation like
"$SUM( $ABOVE() )" to tables located in APS Sahaja Yoga topics. - TablePlugin (Dakar, 6850): Control attributes of tables and sorting of table columns
%FAILEDPLUGINS%
| Plugin | Errors |
|---|
| CalendarPlugin |
TWiki::Plugins::CalendarPlugin could not be loaded. Errors were:
Can't locate Date/Calc.pm in @INC (@INC contains: /var/www/sahajayogaverona.it/public/wiki/lib/CPAN/lib//arch/ /var/www/sahajayogaverona.it/public/wiki/lib/CPAN/lib//5.10.1/i486-linux-gnu-thread-multi/ /var/www/sahajayogaverona.it/public/wiki/lib/CPAN/lib//5.10.1/ /var/www/sahajayogaverona.it/public/wiki/lib/CPAN/lib// /var/www/sahajayogaverona.it/public/wiki/lib . /etc/perl /usr/local/lib/perl/5.10.1 /usr/local/share/perl/5.10.1 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.10 /usr/share/perl/5.10 /usr/local/lib/site_perl) at /var/www/sahajayogaverona.it/public/wiki/lib/TWiki/Plugins/CalendarPlugin.pm line 203.
BEGIN failed--compilation aborted at /var/www/sahajayogaverona.it/public/wiki/lib/TWiki/Plugins/CalendarPlugin.pm line 203.
Compilation failed in require at (eval 40) line 1.
BEGIN failed--compilation aborted at (eval 40) line 1.
----
|
| CommentPlugin | none |
| EditTablePlugin | none |
| HeadlinesPlugin | none |
| ImageGalleryPlugin | none |
| InterwikiPlugin | none |
| PreferencesPlugin | none |
| RenderListPlugin | none |
| SlideShowPlugin | none |
| SmiliesPlugin | none |
| SpreadSheetPlugin | none |
| TablePlugin | none |
| Handler | Plugins |
|---|
| afterAttachmentSaveHandler | |
| afterCommonTagsHandler | |
| afterEditHandler | |
| afterSaveHandler | |
| beforeAttachmentSaveHandler | |
| beforeCommonTagsHandler | |
| beforeEditHandler | |
| beforeSaveHandler | CommentPlugin |
| commonTagsHandler | CommentPlugin EditTablePlugin HeadlinesPlugin ImageGalleryPlugin SlideShowPlugin SmiliesPlugin SpreadSheetPlugin |
| earlyInitPlugin | |
| endRenderingHandler | |
| initPlugin | CommentPlugin EditTablePlugin HeadlinesPlugin ImageGalleryPlugin InterwikiPlugin PreferencesPlugin RenderListPlugin SlideShowPlugin SmiliesPlugin SpreadSheetPlugin TablePlugin |
| initializeUserHandler | |
| insidePREHandler | |
| modifyHeaderHandler | |
| mergeHandler | |
| outsidePREHandler | |
| postRenderingHandler | EditTablePlugin PreferencesPlugin |
| preRenderingHandler | InterwikiPlugin PreferencesPlugin RenderListPlugin SmiliesPlugin TablePlugin |
| redirectCgiQueryHandler | |
| registrationHandler | |
| renderFormFieldForEditHandler | |
| renderWikiWordHandler | |
| startRenderingHandler | |
| writeHeaderHandler | |
12 plugins
The TWiki Plugin API
The Application Programming Interface (API) for TWikiPlugins provides the specifications for hooking into the core TWiki code from your external Perl Plugin module.
Available Core Functions
The
TWikiFuncDotPm module (
lib/TWiki/Func.pm) describes ALL the interfaces available to Plugins. Plugins should ONLY use the interfaces described in this module.

If you use other core functions not described in
Func.pm, you run the risk of creating security holes. Also, your Plugin will likely break and require updating when you upgrade to a new version of TWiki.
Predefined Hooks
In addition to TWiki core functions, Plugins can use
predefined hooks, or
call backs, as described in the
lib/TWiki/Plugins/EmptyPlugin.pm module.
- All but the initPlugin are disabled. To enable a call back, remove
DISABLE_ from the function name.
TWiki:Codev/StepByStepRenderingOrder helps you decide which rendering handler to use.
Hints on Writing Fast Plugins
- Delay initialization as late as possible. For example, if your plugin is a simple syntax processor, you might delay loading extra Perl modules until yu actually see the syntax in the text.
- For example, use an
eval block like this:
eval { require IPC::Run }
return "<font color=\"red\">SamplePlugin: Can't load required modules ($@)</font>" if $@; - You can use a flag to avoid running the initialization twice
Security
- Badly written plugins can open huge security holes in TWiki. This is especially true if care isn't taken to prevent execution of arbitrary commands on the server.
- Don't allow sensitive configuration data to be edited by users. it is better to add sensitive configuration options to the TWiki::cfg hash than adding it as preferences in the plugin topic
- Always use the TWiki::Sandbox to execute commands.
- Always audit the plugins you install, and make sure you are happy with the level of security provided. While every effort is made to monitor plugin authors activities, at the end of the day they are uncontrolled user contributions.
Creating Plugins
With a reasonable knowledge of the Perl scripting language, you can create new Plugins or modify and extend existing ones. Basic plug-in architecture uses an Application Programming Interface (API), a set of software instructions that allow external code to interact with the main program. The
TWiki Plugin API Plugins by providing a programming interface for TWiki.
Anatomy of a Plugin
A basic TWiki Plugin consists of two elements:
- a Perl module, ex:
MyFirstPlugin.pm - a documentation topic, ex:
MyFirstPlugin.txt
The Perl module can be a block of code that connects with TWiki alone, or it can include other elements, like other Perl modules (including other Plugins), graphics, TWiki templates, external applications (ex: a Java applet), or just about anything else it can call.
In particular, files that should be web-accessible (graphics, Java applets ...) are best placed as attachments of the
MyFirstPlugin topic. Other needed Perl code is best placed in a
lib/TWiki/Plugins/MyFirstPlugin/ directory.
The Plugin API handles the details of connecting your Perl module with main TWiki code. When you're familiar with the
Plugin API, you're ready to develop Plugins.
Creating the Perl Module
Copy file
lib/TWiki/Plugins/EmptyPlugin.pm to
<name>Plugin.pm. The
EmptyPlugin.pm module contains mostly empty functions, so it does nothing, but it's ready to be used. Customize it. Refer to the
Plugin API specs for more information.
Writing the Documentation Topic
The Plugin documentation topic contains usage instructions and version details. It serves the Plugin files as
FileAttachments for downloading. (The doc topic is also included
in the
distribution package.) To create a documentation topic:
- Copy the Plugin topic template from TWiki.org. To copy the text, go to TWiki:Plugins/PluginPackage and:
- enter the Plugin name in the "How to Create a Plugin" section
- click Create
- select all in the Edit box & copy
- Cancel the edit
- go back to your site to the TWiki web
- In the GoBox enter your Plugin name, for example
MyFirstPlugin, press enter and create the new topic - paste & save new Plugin topic on your site
- Customize your Plugin topic.
- In case you plan to publish your Plugin at TWiki.org, use Interwiki names for author names, like TWiki:Main/TWikiGuest.
- Save your topic, for use in packaging and publishing your Plugin.
OUTLINE: Doc Topic Contents
Check the Plugins web on TWiki.org for the latest Plugin doc topic template. Here's a quick overview of what's covered:
Syntax Rules: <Describe any special text formatting that will be rendered.>"
Example: <Include an example of the Plugin in action. Possibly include a static HTML version of the example to compare if the installation was a success!>"
Plugin Settings: <Description and settings for custom Plugin %VARIABLES%, and those required by TWiki.>"
- Plugins Preferences <If user settings are needed, explain... Entering values works exactly like TWikiPreferences and WebPreferences: six (6) spaces and then:>"
- Set <EXAMPLE = value added>
Plugin Installation Instructions: <Step-by-step set-up guide, user help, whatever it takes to install and run, goes here.>"
Plugin Info: <Version, credits, history, requirements - entered in a form, displayed as a table. Both are automatically generated when you create or edit a page in the TWiki:Plugins web.>"
Packaging for Distribution
The
TWiki:Plugins.BuildContrib is a powerful build environment that is used by the TWiki project to build TWiki itself, as well as many of the plugins. You don't
have to use it, but it is highly recommended!
If you don't want (or can't) use the BuildContrib, then a minimum Plugin release consists of a Perl module with a
WikiName that ends in
Plugin, ex:
MyFirstPlugin.pm, and a documentation page with the same name(
MyFirstPlugin.txt).
- Distribute the Plugin files in a directory structure that mirrors TWiki. If your Plugin uses additional files, include them ALL:
-
lib/TWiki/Plugins/MyFirstPlugin.pm -
data/TWiki/MyFirstPlugin.txt -
pub/TWiki/MyFirstPlugin/uparrow.gif [a required graphic]
- Create a zip archive with the Plugin name (
MyFirstPlugin.zip) and add the entire directory structure from Step 1. The archive should look like this:-
lib/TWiki/Plugins/MyFirstPlugin.pm -
data/TWiki/MyFirstPlugin.txt -
pub/TWiki/MyFirstPlugin/uparrow.gif
Publishing for Public Use
You can release your tested, packaged Plugin to the TWiki community through the
TWiki:Plugins web. All Plugins submitted to TWiki.org are available for download and further development in
TWiki:Plugins/PluginPackage.
Publish your plugin by following these steps:
- Post the Plugin documentation topic in the TWiki:Plugins/PluginPack
age:
- enter the Plugin name in the "How to Create a Plugin" section, for example
MyFirstPlugin - paste in the topic text from Creating Pl
ugin Documentation and save
- Attach the distribution zip file to the topic, ex: =MyFirstPlugin.z
ip=
- Link from the doc page to a new, blank page named after the Plugin, and ending in
Dev, ex: MyFirstPluginDev. This is the discussion page for fu
ture development. (User support for Plugins is handled in
TWiki:Support.)
- Put the Plugin into the CVS repository, see TWiki:Plugins/ReadmeFir
st (optional)

Once you have done the above steps once, you can use the BuildContrib to upload updates to your plugin.
Where to store Plugin Internal Data
Plugins that need to store data should use the functions in the
FuncDotPm? interface. These functions support saving and loading of:
You can also create a plugin "work area" using the
getWorkArea function, which gives you a persistant directory where you can store data files.
Related Topics: DeveloperDocumentationCategory,
AdminDocumentationCategory
Package TWiki::Func
This module defines official functions that
Plugins
can use to interact with the TWiki engine and content.
Refer to lib/TWiki/Plugins/EmptyPlugin.pm for a template plugin and
documentation on how to write a plugin.
Plugins should
only use functions published in this module. If you use
functions in other TWiki libraries you might create a security hole and
you will likely need to change your Plugin when you upgrade TWiki.
Deprecated functions will still work in older code, though they should
not be called in new plugins and should be replaced in older plugins
as soon as possible.
The version of the TWiki::Func module is defined by the VERSION number of the
TWiki::Plugins module, currently 1.1. This can be shown
by the
%PLUGINVERSION{}% variable. The 'Since' field in the function
documentation refers to the VERSION number and the date that the function
was addded.
Note Contrib authors beware! These methods should only ever be called
from the context of a TWiki plugin. They require a session context to be
established before they are called, and will not work if simply called from
another TWiki module unless the session object is defined first.
- TWiki System Requirements
- Basic Installation
- Next Steps (optional)
- Troubleshooting
- TWiki Upgrade Guide
- TWiki Access Control
- TWiki Text Formatting
- TWiki Variables
- File Attachments
- TWiki Forms
- TWiki Templates
- TWiki Skins
- TWiki Formatted Search Results
- TWiki Meta Data
- TWiki Plugins
- Package TWiki::Func
- Functions: CGI Environment
- getSessionValue( $key ) -> $value
- setSessionValue( $key, $value ) -> $result
- clearSessionValue( $key ) -> $result
- getSkin( ) -> $skin
- getUrlHost( ) -> $host
- getScriptUrl( $web, $topic, $script, ... ) -> $url
- getScriptUrlPath( ) -> $path
- getViewUrl( $web, $topic ) -> $url
- getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $url
- getPubUrlPath( ) -> $path
- getCgiQuery( ) -> $query
- writeHeader( $query, $contentLength )
- redirectCgiQuery( $query, $url )
- getContext() -> \%hash
- Functions: Preferences
- Functions: User Handling and Access Control
- Functions: Content Handling
- getListOfWebs( $filter ) -> @webs
- webExists( $web ) -> $flag
- createWeb( $newWeb, $baseWeb, $opts )
- moveWeb( $oldName, $newName )
- topicExists( $web, $topic ) -> $boolean
- getRevisionInfo($theWebName, $theTopic, $theRev, $attachment ) -> ( $date, $user, $rev, $comment )
- getRevisionAtTime( $web, $topic, $time ) -> $rev
- checkTopicEditLock( $web, $topic ) -> ( $oopsUrl, $loginName, $unlockTime )
- setTopicEditLock( $web, $topic, $lock )
- readTopic( $web, $topic, $rev ) -> ( $meta, $text )
- readTopicText( $web, $topic, $rev, $ignorePermissions ) -> $text
- saveTopic( $web, $topic, $meta, $text, $options ) -> $error
- saveTopicText( $web, $topic, $text, $ignorePermissions, $dontNotify ) -> $oopsUrl
- moveTopic( $web, $topic, $newWeb, $newTopic )
- attachmentExists( $web, $topic, $attachment ) -> $boolean
- readAttachment( $web, $topic, $name, $rev ) -> $data
- saveAttachment( $web, $topic, $attachment, $opts )
- moveAttachment( $web, $topic, $attachment, $newWeb, $newTopic, $newAttachment )
- getTopicList( $web ) -> @topics
- Functions: Rendering
- registerTagHandler( $tag, \&fn, $syntax )
- addToHEAD( $id, $header )
- expandCommonVariables( $text, $topic, $web ) -> $text
- renderText( $text, $web ) -> $text
- internalLink( $pre, $web, $topic, $label, $anchor, $createLink ) -> $text
- getWorkArea( $pluginName ) -> $directorypath
- formatTime( $time, $format, $timezone ) -> $text
- Functions: File I/O
- Functions: System and I18N related
- Functions: Template handling and topic creation
- Functions: Email
- sendEmail ( $text, $retries ) -> $error
- Deprecated functions
- TWiki CGI Scripts
- TWiki Site Tools
- Web Changes Notification Service
- Sysadmins
- Managing Topics
- Managing Webs
- Manage Users
- TWiki CSS
Functions: CGI Environment
getSessionValue( $key ) -> $value
Get a session value from the client session module
Return:
$value Value associated with key; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 200)
setSessionValue( $key, $value ) -> $result
Set a session value via the client session module
-
$key - Session key -
$value - Value associated with key
Return:
$result "1" if success; undef if session plugin is not installed
Since: TWiki::Plugins::VERSION 1.000 (17 Aug 2001)
clearSessionValue( $key ) -> $result
Clear a session value via the client session module
Return:
$result "1" if success; undef if session plugin is not installed
Since: TWiki::Plugins::VERSION 1.1
getSkin( ) -> $skin
Get the skin path, set by the
SKIN preferences variable or the
skin CGI parameter
Return:
$skin Comma-separated list of skins, e.g.
'gnu,tartan'. Empty string if none
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getUrlHost( ) -> $host
Get protocol, domain and optional port of script URL
Return:
$host URL host, e.g.
"http://example.com:80"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrl( $web, $topic, $script, ... ) -> $url
Compose fully qualified URL
-
$web - Web name, e.g. 'Main' -
$topic - Topic name, e.g. 'WebNotify' -
$script - Script name, e.g. 'view'
Return:
$url URL, e.g.
"http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getScriptUrlPath( ) -> $path
Get script URL path
Return:
$path URL path of TWiki scripts, e.g.
"/cgi-bin"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getViewUrl( $web, $topic ) -> $url
Compose fully qualified view URL
-
$web - Web name, e.g. 'Main'. The current web is taken if empty -
$topic - Topic name, e.g. 'WebNotify'
Return:
$url URL, e.g.
"http://example.com:80/cgi-bin/view.pl/Main/WebNotify"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getOopsUrl( $web, $topic, $template, $param1, $param2, $param3, $param4 ) -> $url
Compose fully qualified 'oops' dialog URL
-
$web - Web name, e.g. 'Main'. The current web is taken if empty -
$topic - Topic name, e.g. 'WebNotify' -
$template - Oops template name, e.g. 'oopsmistake'. The 'oops' is optional; 'mistake' will translate to 'oopsmistake'. -
$param1 ... $param4 - Parameter values for %PARAM1% ... %PARAMn% variables in template, optional
Return:
$url URL, e.g.
"http://example.com:80/cgi-bin/oops.pl/ Main/WebNotify?template=oopslocked¶m1=joe"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getPubUrlPath( ) -> $path
Get pub URL path
Return:
$path URL path of pub directory, e.g.
"/pub"
Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
getCgiQuery( ) -> $query
Get CGI query object. Important: Plugins cannot assume that scripts run under CGI, Plugins must always test if the CGI query object is set
Return:
$query CGI query object; or 0 if script is called as a shell script
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
writeHeader( $query, $contentLength )
Prints a basic content-type HTML header for text/html to standard out
-
$query - CGI query object. If not given, the default CGI query will be used. In most cases you should not pass this parameter. -
$contentLength - Length of content
Return: none
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
redirectCgiQuery( $query, $url )
Redirect to URL
-
$query - CGI query object. Ignored, only there for compatibility. The session CGI query object is used instead. -
$url - URL to redirect to
Return: none, never returns
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getContext() -> \%hash
Get a hash of context identifiers representing the currently active
context. The hash
must not be changed.
The context is a set of identifiers that are set
during specific phases of TWiki processing. For example, each of
the standard scripts in the 'bin' directory each has a context
identifier - the view script has 'view', the edit script has 'edit'
etc. So you can easily tell what 'type' of script your plugin is
being called within. The core context identifiers are listed
in the
TWikiTemplates topic. Please be careful not to
overwrite any of these identifiers!
Context identifiers can be used to communicate between plugins, and between
plugins and templates. For example, in
FirstPlugin?.pm, you might write:
sub initPlugin {
TWiki::Func::getContext()->{'FirstPlugin'} = 1;
...
and in
SecondPlugin?.pm:
sub initPlugin {
if( TWiki::Func::getContext()->{'FirstPlugin'}) {
...
}
...
or in a template:
%TMPL:P{context="FirstPlugin", then="first plugin"}%
Since: TWiki::Plugins::VERSION 1.1
Functions: Preferences
Extract all parameters from a variable string and returns a hash of parameters
- Parameter:
$attr | Attribute string
Return:
%params Hash containing all parameters. The nameless parameter is stored in key
_DEFAULT
Since: TWiki::Plugins::VERSION 1.025 (26 Aug 2004)
- Example:
- Variable:
%TEST{ 'nameless' name1="val1" name2="val2" }% - First extract text between
{...} to get: 'nameless' name1="val1" name2="val2" - Then call this on the text:
- params = TWiki::Func::extractParameters( $text );=
- The
%params hash contains now:
_DEFAULT => 'nameless'
name1 => "val1"
name2 => "val2"
extractNameValuePair( $attr, $name ) -> $value
Extract a named or unnamed value from a variable parameter string
- Note: | Function TWiki::Func::extractParameters is more efficient for extracting several parameters
-
$attr - Attribute string -
$name - Name, optional
Return:
$value Extracted value
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
- Example:
- Variable:
%TEST{ 'nameless' name1="val1" name2="val2" }% - First extract text between
{...} to get: 'nameless' name1="val1" name2="val2" - Then call this on the text:
my $noname = TWiki::Func::extractNameValuePair( $text );
my $val1 = TWiki::Func::extractNameValuePair( $text, "name1" );
my $val2 = TWiki::Func::extractNameValuePair( $text, "name2" );
getPreferencesValue( $key, $web ) -> $value
Get a preferences value from TWiki or from a Plugin
-
$key - Preferences key -
$web - Name of web, optional. Current web if not specified; does not apply to settings of Plugin topics
Return:
$value Preferences value; empty string if not set
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
- Example for Plugin setting:
- MyPlugin? topic has:
* Set COLOR = red - Use
"MYPLUGIN_COLOR" for $key -
my $color = TWiki::Func::getPreferencesValue( "MYPLUGIN_COLOR" );
- Example for preferences setting:
- WebPreferences topic has:
* Set WEBBGCOLOR = #FFFFC0 -
my $webColor = TWiki::Func::getPreferencesValue( 'WEBBGCOLOR', 'Sandbox' );
getPluginPreferencesValue( $key ) -> $value
Get a preferences value from your Plugin
-
$key - Plugin Preferences key w/o PLUGINNAME_ prefix.
Return:
$value Preferences value; empty string if not set
NOTE: This sub will retrieve nothing if called from a module in a subpackage of TWiki::Plugins (ie, TWiki::Plugins::MyPlugin::MyModule)
Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
getPreferencesFlag( $key, $web ) -> $value
Get a preferences flag from TWiki or from a Plugin
-
$key - Preferences key -
$web - Name of web, optional. Current web if not specified; does not apply to settings of Plugin topics
Return:
$value Preferences flag
'1' (if set), or
"0" (for preferences values
"off",
"no" and
"0")
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
- Example for Plugin setting:
- MyPlugin? topic has:
* Set SHOWHELP = off - Use
"MYPLUGIN_SHOWHELP" for $key -
my $showHelp = TWiki::Func::getPreferencesFlag( "MYPLUGIN_SHOWHELP" );
getPluginPreferencesFlag( $key ) -> $flag
Get a preferences flag from your Plugin
-
$key - Plugin Preferences key w/o PLUGINNAME_ prefix.
Return:
$flag Preferences flag
'1' (if set), or
"0" (for preferences values
"off",
"no" and
"0", or values not set at all)
NOTE: This sub will retrieve nothing if called from a module in a subpackage of TWiki::Plugins (ie, TWiki::Plugins::MyPlugin::MyModule)
Since: TWiki::Plugins::VERSION 1.021 (27 Mar 2004)
getWikiToolName( ) -> $name
Get toolname as defined in TWiki.cfg
Return:
$name Name of tool, e.g.
'TWiki'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getMainWebname( ) -> $name
Get name of Main web as defined in TWiki.cfg
Return:
$name Name, e.g.
'Main'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
getTwikiWebname( ) -> $name
Get name of TWiki documentation web as defined in TWiki.cfg
Return:
$name Name, e.g.
'TWiki'
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
Functions: User Handling and Access Control
getDefaultUserName( ) -> $loginName
Get default user name as defined in the configuration as
DefaultUserLogin
Return:
$loginName Default user name, e.g.
'guest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiName( ) -> $wikiName
Get Wiki name of logged in user
Return:
$wikiName Wiki Name, e.g.
'JohnDoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWikiUserName( $text ) -> $wikiName
Get Wiki name of logged in user with web prefix
Return:
$wikiName Wiki Name, e.g.
"Main.JohnDoe"
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
wikiToUserName( $wikiName ) -> $loginName
Translate a Wiki name to a login name based on
Main.TWikiUsers topic
-
$wikiName - Wiki name, e.g. 'Main.JohnDoe' or 'JohnDoe'
Return:
$loginName Login name of user, e.g.
'jdoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
userToWikiName( $loginName, $dontAddWeb ) -> $wikiName
Translate a login name to a Wiki name based on
Main.TWikiUsers topic
-
$loginName - Login name, e.g. 'jdoe' -
$dontAddWeb - Do not add web prefix if "1"
Return:
$wikiName Wiki name of user, e.g.
'Main.JohnDoe' or
'JohnDoe'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
isGuest( ) -> $flag
Test if logged in user is a guest
Return:
$flag "1" if yes,
"0" if not
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
isValidWikiWord ( $name ) -> $boolean
Check for a valid
WikiWord or
WikiName
permissionsSet( $web ) -> $flag
Test if any access restrictions are set for this web, ignoring settings on individual pages
-
$web - Web name, required, e.g. 'Sandbox'
Return:
$flag "1" if yes,
"0" if no
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
checkAccessPermission( $type, $wikiName, $text, $topic, $web ) -> $flag
Check access permission for a topic based on the
TWiki.TWikiAccessControl rules
-
$type - Access type, e.g. 'VIEW', 'CHANGE', 'CREATE' -
$wikiName - WikiName of remote user, i.e. "Main.PeterThoeny" -
$text - Topic text, optional. If empty, topic $web.$topic is consulted -
$topic - Topic name, required, e.g. 'PrivateStuff' -
$web - Web name, required, e.g. 'Sandbox'
Return:
$flag "1" if access may be granted,
"0" if not
Since: TWiki::Plugins::VERSION 1.000 (27 Feb 2001)
Functions: Content Handling
getListOfWebs( $filter ) -> @webs
-
$filter - spec of web types to recover
Gets a list of webs, filtered according to the spec in the $filter,
which may include one of:
- 'user' (for only user webs)
- 'template' (for only template webs i.e. those starting with "_")
$filter may also contain the word 'public' which will further filter
out webs that have NOSEARCHALL set on them.
For example, the deprecated getPublicWebList function can be duplicated
as follows:
my @webs = TWiki::Func::getListOfWebs( "user,public" );
Since: TWiki::Plugins::VERSION 1.1
webExists( $web ) -> $flag
Test if web exists
-
$web - Web name, required, e.g. 'Sandbox'
Return:
$flag "1" if web exists,
"0" if not
Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
createWeb( $newWeb, $baseWeb, $opts )
$newWeb is the name of the new web.
$baseWeb is the name of an existing web (a template web). If the
base web is a system web, all topics in it
will be copied into the new web. If it is a normal web, only topics starting
with 'Web' will be copied. If no base web is specified, an empty web
(with no topics) will be created. If it is specified but does not exist,
an error will be thrown.
$opts is a ref to a hash that contains settings to be modified in
the web preferences topic in the new web.
use Error qw( :try );
try {
TWiki::Func::createWeb( "Newweb" );
} catch Error::Simple with {
my $e = shift;
# see documentation on Error::Simple
} catch TWiki::AccessControlException with {
my $e = shift;
# see documentation on TWiki::AccessControlException
} otherwise {
...
};
Since: TWiki::Plugins::VERSION 1.1
moveWeb( $oldName, $newName )
Move (rename) a web.
use Error qw( :try );
try {
TWiki::Func::moveWeb( "Oldweb", "Newweb" );
} catch Error::Simple with {
my $e = shift;
# see documentation on Error::Simple
} catch TWiki::AccessControlException with {
my $e = shift;
# see documentation on TWiki::AccessControlException
} otherwise {
...
};
To delete a web, move it to a subweb of
Trash
TWiki::Func::moveWeb( "Deadweb", "Trash.Deadweb" );
Since: TWiki::Plugins::VERSION 1.1
topicExists( $web, $topic ) -> $boolean
Test if topic exists
-
$web - Web name, optional, e.g. 'Main'. -
$topic - Topic name, required, e.g. 'TokyoOffice', or "Main.TokyoOffice"
$web and $topic are parsed as described in the documentation for
normalizeWebTopicName.
Since: TWiki::Plugins::VERSION 1.000 (14 Jul 2001)
getRevisionInfo($theWebName, $theTopic, $theRev, $attachment ) -> ( $date, $user, $rev, $comment )
Get revision info of a topic
-
$theWebName - Web name, optional, e.g. 'Main' -
$theTopic - Topic name, required, e.g. 'TokyoOffice' -
$theRev - revsion number, or tag name (can be in the format 1.2, or just the minor number) -
$attachment -attachment filename
Return:
( $date, $user, $rev, $comment ) List with: ( last update date, login name of last user, minor part of top revision number ), e.g.
( 1234561, 'phoeny', "5" )
| $date | in epochSec |
| $user | Wiki name of the author (not login name) |
| $rev | actual rev number |
| $comment | WHAT COMMENT? |
NOTE: if you are trying to get revision info for a topic, use
$meta->getRevisionInfo instead if you can - it is significantly
more efficient, and returns a user object that contains other user
information.
NOTE: prior versions of TWiki may under some circumstances have returned
the login name of the user rather than the wiki name; the code documentation
was totally unclear, and we have been unable to establish the intent.
However the wikiname is obviously more useful, so that is what is returned.
Since: TWiki::Plugins::VERSION 1.000 (29 Jul 2001)
getRevisionAtTime( $web, $topic, $time ) -> $rev
-
$web - web for topic -
$topic - topic -
$time - time (in epoch secs) for the rev
Get the revision number of a topic at a specific time.
Returns a single-digit rev number or undef if it couldn't be determined
(either because the topic isn't that old, or there was a problem)
checkTopicEditLock( $web, $topic ) -> ( $oopsUrl, $loginName, $unlockTime )
Check if a lease has been taken by some other user.
-
$web Web name, e.g. "Main", or empty -
$topic Topic name, e.g. "MyTopic", or "Main.MyTopic"
Return
( $oopsUrl, $loginName, $unlockTime ) | The
$oopsUrl for calling redirectCgiQuery(), user's
$loginName, and estimated
$unlockTime in minutes, or ( '', '', 0 ) if no lease exists.
setTopicEditLock( $web, $topic, $lock )
-
$web Web name, e.g. "Main", or empty -
$topic Topic name, e.g. "MyTopic", or "Main.MyTopic" -
$lock 1 to lease the topic, 0 to clear the lease=
Takes out a "lease" on the topic. The lease doesn't prevent
anyone from editing and changing the topic, but it does redirect them
to a warning screen, so this provides some protection. The
edit script
always takes out a lease.
It is
impossible to fully lock a topic. Concurrent changes will be
merged.
readTopic( $web, $topic, $rev ) -> ( $meta, $text )
Read topic text and meta data, regardless of access permissions.
-
$web - Web name, required, e.g. 'Main' -
$topic - Topic name, required, e.g. 'TokyoOffice' -
$rev - revision to read (default latest)
Return:
( $meta, $text ) Meta data object and topic text
$meta is a perl 'object' of class
TWiki::Meta. This class is
fully documented in the source code documentation shipped with the
release, or can be inspected in the
lib/TWiki/Meta.pm file.
This method
ignores topic access permissions. You should be careful to use
checkAccessPermissions to ensure the current user has read access to the topic.
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
readTopicText( $web, $topic, $rev, $ignorePermissions ) -> $text
Read topic text, including meta data
-
$web - Web name, e.g. 'Main', or empty -
$topic - Topic name, e.g. 'MyTopic', or "Main.MyTopic" -
$rev - Topic revision to read, optional. Specify the minor part of the revision, e.g. "5", not "1.5"; the top revision is returned if omitted or empty. -
$ignorePermissions - Set to "1" if checkAccessPermission() is already performed and OK; an oops URL is returned if user has no permission
Return:
$text Topic text with embedded meta data; an oops URL for calling redirectCgiQuery() is returned in case of an error
This method is more efficient than
readTopic, but returns meta-data embedded in the text. Plugins authors must be very careful to avoid damaging meta-data. You are recommended to use readTopic instead, which is a lot safer..
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
saveTopic( $web, $topic, $meta, $text, $options ) -> $error
-
$web - web for the topic -
$topic - topic name -
$meta - reference to TWiki::Meta object -
$text - text of the topic (without embedded meta-data!!! -
\%options - ref to hash of save options
\%options may include:
dontlog | don't log this change in twiki log |
comment | comment for save |
minor | True if this is a minor change, and is not to be notified |
Return: error message or undef.
For example,
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic )
$text =~ s/APPLE/ORANGE/g;
TWiki::Func::saveTopic( $web, $topic, $meta, $text, { comment => 'refruited' } );
Note plugins handlers ( e.g.
beforeSaveHandler ) will be called as
appropriate.
saveTopicText( $web, $topic, $text, $ignorePermissions, $dontNotify ) -> $oopsUrl
Save topic text, typically obtained by readTopicText(). Topic data usually includes meta data; the file attachment meta data is replaced by the meta data from the topic file if it exists.
-
$web - Web name, e.g. 'Main', or empty -
$topic - Topic name, e.g. 'MyTopic', or "Main.MyTopic" -
$text - Topic text to save, assumed to include meta data -
$ignorePermissions - Set to "1" if checkAccessPermission() is already performed and OK -
$dontNotify - Set to "1" if not to notify users of the change
Return:
$oopsUrl Empty string if OK; the
$oopsUrl for calling redirectCgiQuery() in case of error
This method is a lot less efficient and much more dangerous than
saveTopic.
Since: TWiki::Plugins::VERSION 1.010 (31 Dec 2002)
my $text = TWiki::Func::readTopicText( $web, $topic );
# check for oops URL in case of error:
if( $text =~ /^http.*?\/oops/ ) {
TWiki::Func::redirectCgiQuery( $query, $text );
return;
}
# do topic text manipulation like:
$text =~ s/old/new/g;
# do meta data manipulation like:
$text =~ s/(META\:FIELD.*?name\=\"TopicClassification\".*?value\=\")[^\"]*/$1BugResolved/;
$oopsUrl = TWiki::Func::saveTopicText( $web, $topic, $text ); # save topic text
moveTopic( $web, $topic, $newWeb, $newTopic )
-
$web source web - required -
$topic source topic - required -
$newWeb dest web -
$newTopic dest topic
Renames the topic. Throws an exception if something went wrong.
If $newWeb is undef, it defaults to $web. If $newTopic is undef, it defaults
to $topic.
The destination topic must not already exist.
Rename a topic to the $TWiki::cfg{TrashWebName} to delete it.
use Error qw( :try );
try {
moveTopic( "Work", "TokyoOffice", "Trash", "ClosedOffice" );
} catch Error::Simple with {
my $e = shift;
# see documentation on Error::Simple
} catch TWiki::AccessControlException with {
my $e = shift;
# see documentation on TWiki::AccessControlException
} otherwise {
...
};
Since: TWiki::Plugins::VERSION 1.1
attachmentExists( $web, $topic, $attachment ) -> $boolean
Test if attachment exists
-
$web - Web name, optional, e.g. Main. -
$topic - Topic name, required, e.g. TokyoOffice, or Main.TokyoOffice -
$attachment - attachment name, e.g.=logo.gif=
$web and $topic are parsed as described in the documentation for
normalizeWebTopicName.
Since: TWiki::Plugins::VERSION 1.1
readAttachment( $web, $topic, $name, $rev ) -> $data
-
$web - web for topic -
$topic - topic -
$name - attachment name -
$rev - revision to read (default latest)
Read an attachment from the store for a topic, and return it as a string. The names of attachments on a topic can be recovered from the meta-data returned by
readTopic. If the attachment does not exist, or cannot be read, undef will be returned.
View permission on the topic is required for the
read to be successful. Access control violations are flagged by a
TWiki::AccessControlException. Permissions are checked for the user
passed in.
my( $meta, $text ) = TWiki::Func::readTopic( $web, $topic );
my @attachments = $meta->find( 'FILEATTACHMENT' );
foreach my $a ( @attachments ) {
try {
my $data = TWiki::Func::readAttachment( $meta, $a->{name} );
...
} catch TWiki::AccessControlException with {
};
}
Since: TWiki::Plugins::VERSION 1.1
saveAttachment( $web, $topic, $attachment, $opts )
-
$web - web for topic -
$topic - topic to atach to -
$attachment - name of the attachment -
$opts - Ref to hash of options
$opts may include:
dontlog | don't log this change in twiki log |
comment | comment for save |
hide | if the attachment is to be hidden in normal topic view |
stream | Stream of file to upload |
file | Name of a file to use for the attachment data. ignored if stream is set. Local file on the server. |
filepath | Client path to file |
filesize | Size of uploaded data |
filedate | Date |
Save an attachment to the store for a topic. On success, returns undef. If there is an error, an exception will be thrown.
try {
TWiki::Func::saveAttachment( $web, $topic, 'image.gif',
{ file => 'image.gif',
comment => 'Picture of Health',
hide => 1 } );
} catch Error::Simple with {
# see documentation on Error
} otherwise {
...
};
Since: TWiki::Plugins::VERSION 1.1
moveAttachment( $web, $topic, $attachment, $newWeb, $newTopic, $newAttachment )
-
$web source web - required -
$topic source topic - required -
$attachment source attachment - required -
$newWeb dest web -
$newTopic dest topic -
$newAttachment dest attachment
Renames the topic. Throws an exception on error or access violation.
If $newWeb is undef, it defaults to $web. If $newTopic is undef, it defaults
to $topic. If $newAttachment is undef, it defaults to $attachment. If all of $newWeb, $newTopic and $newAttachment are undef, it is an error.
The destination topic must already exist, but the destination attachment must
not exist.
Rename an attachment to $TWiki::cfg{TrashWebName}.TrashAttament to delete it.
use Error qw( :try );
try {
# move attachment between topics
moveAttachment( "Countries", "Germany", "AlsaceLorraine.dat",
"Countries", "France" );
# Note destination attachment name is defaulted to the same as source
} catch TWiki::AccessControlException with {
my $e = shift;
# see documentation on TWiki::AccessControlException
} catch Error::Simple with {
my $e = shift;
# see documentation on Error::Simple
};
Since: TWiki::Plugins::VERSION 1.1
getTopicList( $web ) -> @topics
Get list of all topics in a web
-
$web - Web name, required, e.g. 'Sandbox'
Return:
@topics Topic list, e.g.
( 'WebChanges', 'WebHome', 'WebIndex', 'WebNotify' )
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
Functions: Rendering
registerTagHandler( $tag, \&fn, $syntax )
Should only be called from initPlugin.
Register a function to handle a simple tag. Handles both %TAG% and %TAG{...}%. Registered tags are treated the same as TWiki internal tags, and are expanded at the same time. This is a
lot more efficient than using the
commonTagsHandler.
-
$tag - The name of the tag i.e. the 'MYTAG' part of %MYTAG%. The tag name must match /^[A-Z][A-Z0-9_]*$/ or it won't work. -
\&fn - Reference to the handler function. -
$syntax can be 'classic' (the default) or 'context-free'. 'classic' syntax is appropriate where you want the tag to support classic TWiki syntax i.e. to accept an unquoted default parameter. For example, %MYTAG{unquoted parameter}%. If your tag will only use named parameters, you can use 'context-free' syntax, which supports a more natural and friendly syntax. For example, %MYTAG{param1=value1, value 2, param3="value 3", param4='value 5"}%
Since: TWiki::Plugins::VERSION 1.1
The tag handler function must be of the form:
sub handler(\%session, \%params, $theTopic, $theWeb)
where:
-
\%session - a reference to the TWiki session object (may be ignored) -
\%params - a reference to a TWiki::Attrs object containing parameters. This can be used as a simple hash that maps parameter names to values, with _DEFAULT being the name for the default parameter. -
$theTopic - name of the topic in the query -
$theWeb - name of the web in the query
for example, to execute an arbitrary command on the server, you might do this:
sub initPlugin{
TWiki::Func::registerTagHandler('EXEC', \&boo);
}
sub boo {
my( $session, $params, $topic, $web ) = @_;
my $cmd = $params->{_DEFAULT};
return "NO COMMAND SPECIFIED" unless $cmd;
my $result = `$cmd 2>&1`;
return $params->{silent} ? '' : $result;
}
}
would let you do this:
%EXEC{"ps -Af" silent="on"}%
addToHEAD( $id, $header )
Adds
$header to the HTML header (the tag).
This is useful for plugins that want to include some javascript custom css.
-
$id - Unique ID to prevent the same HTML from being duplicated. Plugins should use a prefix to prevent name clashes (e.g EDITTABLEPLUGIN_JSCALENDAR) -
$header - the HTML to be added to the section. The HTML must be valid in a HEAD tag - no checks are performed.
All TWiki variables present in
$header will be expanded before being inserted into the
section.
Note that this is
not the same as the HTTP header, which is modified through the plugins
modifyHeaderHandler.
Since: TWiki::Plugins::VERSION 1.1
example:
TWiki::Func::addToHEAD('PATTERN_STYLE','<link id="twikiLayoutCss" rel="stylesheet" type="text/css" href="%PUBURL%/TWiki/PatternSkin/layout.css" media="all" />')
expandCommonVariables( $text, $topic, $web ) -> $text
Expand all common
%VARIABLES%-
$text - Text with variables to expand, e.g. 'Current user is %WIKIUSER%' -
$topic - Current topic name, e.g. 'WebNotify' -
$web - Web name, optional, e.g. 'Main'. The current web is taken if missing
Return:
$text Expanded text, e.g.
'Current user is TWikiGuest'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
See also: expandVariablesOnTopicCreation
renderText( $text, $web ) -> $text
Render text from TWiki markup into XHTML as defined in
TWiki.TextFormattingRules-
$text - Text to render, e.g. '*bold* text and =fixed font=' -
$web - Web name, optional, e.g. 'Main'. The current web is taken if missing
Return:
$text XHTML text, e.g.
'<b>bold</b> and <code>fixed font</code>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
internalLink( $pre, $web, $topic, $label, $anchor, $createLink ) -> $text
Render topic name and link label into an XHTML link. Normally you do not need to call this funtion, it is called internally by
renderText()-
$pre - Text occuring before the TWiki link syntax, optional -
$web - Web name, required, e.g. 'Main' -
$topic - Topic name to link to, required, e.g. 'WebNotify' -
$label - Link label, required. Usually the same as $topic, e.g. 'notify' -
$anchor - Anchor, optional, e.g. '#Jump' -
$createLink - Set to '1' to add question linked mark after topic name if topic does not exist;
set to '0' to suppress link for non-existing topics
Return:
$text XHTML anchor, e.g.
'<a href='/cgi-bin/view/Main/WebNotify#Jump'>notify</a>'
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
getWorkArea( $pluginName ) -> $directorypath
Gets a private directory for the plugin. The plugin is entirely responsible
for managing this directory; TWiki will not read from it, or write to it.
The directory is guaranteed to exist, and to be writable by the webserver
user. By default it will
not be web accessible.
The directory and it's contents are permanent, so plugins must be careful
to keep their areas tidy.
formatTime( $time, $format, $timezone ) -> $text
Format the time in seconds into the desired time string
-
$time - Time in epoc seconds -
$format - Format type, optional. Default e.g. '31 Dec 2002 - 19:30'. Can be '$iso' (e.g. '2002-12-31T19:30Z'), '$rcs' (e.g. '2001/12/31 23:59:59', '$http' for HTTP header format (e.g. 'Thu, 23 Jul 1998 07:21:56 GMT'), or any string with tokens '$seconds, $minutes, $hours, $day, $wday, $month, $mo, $year, $ye, $tz' for seconds, minutes, hours, day of month, day of week, 3 letter month, 2 digit month, 4 digit year, 2 digit year, timezone string, respectively -
$timezone - either not defined (uses the displaytime setting), 'gmtime', or 'servertime'
Return:
$text Formatted time string
| Note: | if you used the removed formatGmTime, add a third parameter 'gmtime' |
Since: TWiki::Plugins::VERSION 1.020 (26 Feb 2004)
Functions: File I/O
readTemplate( $name, $skin ) -> $text
Read a template or skin. Embedded
template directives get expanded
-
$name - Template name, e.g. 'view' -
$skin - Comma-separated list of skin names, optional, e.g. 'print'
Return:
$text Template text
Since: TWiki::Plugins::VERSION 1.000 (7 Dec 2002)
writeWarning( $text )
Log Warning that may require admin intervention to data/warning.txt
-
$text - Text to write; timestamp gets added
Return: none
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
writeDebug( $text )
Log debug message to data/debug.txt
-
$text - Text to write; timestamp gets added
Return: none
Since: TWiki::Plugins::VERSION 1.020 (16 Feb 2004)
Functions: System and I18N related
getRegularExpression( $name ) -> $expr
Retrieves a TWiki predefined regular expression or character class.
-
$name - Name of the expression to retrieve. See notes below
Return: String or precompiled regular expression matching as described below.
Since: TWiki::Plugins::VERSION 1.020 (9 Feb 2004)
Note: TWiki internally precompiles several regular expressions to
represent various string entities in an I18N-compatible manner. Plugins
authors are encouraged to use these in matching where appropriate. The
following are guaranteed to be present. Others may exist, but their use
is unsupported and they may be removed in future TWiki versions.
In the table below, the expression marked type 'String' are intended for
use within character classes (i.e. for use within square brackets inside
a regular expression), for example:
my $upper = TWiki::Func::getRegularExpression('upperAlpha');
my $alpha = TWiki::Func::getRegularExpression('mixedAlpha');
my $capitalized = qr/[$upper][$alpha]+/;
Those expressions marked type 'RE' are precompiled regular expressions that can be used outside square brackets. For example:
my $webRE = TWiki::Func::getRegularExpression('webNameRegex');
my $isWebName = ( $s =~ m/$webRE/ );
| Name | Matches | Type |
| upperAlpha | Upper case characters | String |
| upperAlphaNum | Upper case characters and digits | String |
| lowerAlpha | Lower case characters | String |
| lowerAlphaNum | Lower case characters and digits | String |
| numeric | Digits | String |
| mixedAlpha | Alphabetic characters | String |
| mixedAlphaNum | Alphanumeric characters | String |
| wikiWordRegex | WikiWords | RE |
| webNameRegex | User web names | RE |
| anchorRegex | #AnchorNames | RE |
| abbrevRegex | Abbreviations e.g. GOV, IRS | RE |
| emailAddrRegex | email@addressPROTEZIONESPAMDACANCELLARE.com | RE |
| tagNameRegex | Standard tag names e.g. %THIS_BIT% (THIS_BIT only) | RE |
Functions: Template handling and topic creation
loadTemplate ( $theName, $theSkin, $theWeb ) -> $text
-
$theName - template file name -
$theSkin - comma-separated list of skins to use (default: current skin) -
$theWeb - the web to look in for topics that contain templates (default: current web)
Return: expanded template text (what's left after removal of all %TMPL:DEF% statements)
Since: TWiki::Plugins::VERSION 1.1
Reads a template and extracts template definitions, adding them to the
list of loaded templates, overwriting any previous definition.
How TWiki searches for templates is described in
TWikiTemplates.
If template text is found, extracts include statements and fully expands them.
sub expandTemplate( $theDef ) -> $string
Do a , only expanding the template (not expanding any tags other than %TMPL tags)
Return: the text of the expanded template
Since: TWiki::Plugins::VERSION 1.1
A template is defined using a %TMPL:DEF% statement in a template
file. See the documentation on TWiki templates for more information.
expandVariablesOnTopicCreation ( $text ) -> $text
Expand the limited set of variables that are always expanded during topic creation
-
$text - the text to process
Return: text with variables expanded
Since: TWiki::Plugins::VERSION 1.1
Expands only the variables expected in templates that must be statically
expanded in new content.
The expanded variables are:
-
%DATE% Signature-format date -
%SERVERTIME% See TWikiVariables -
%GMTIME% See TWikiVariables -
%USERNAME% Base login name -
%WIKINAME% Wiki name -
%WIKIUSERNAME% Wiki name with prepended web -
%URLPARAM{...}% - Parameters to the current CGI query -
%NOP% No-op
See also: expandVariables
normalizeWebTopicName($web, $topic) -> ($web, $topic)
Parse a web and topic name, supplying defaults as appropriate.
-
$web - Web name, identifying variable, or empty string -
$topic - Topic name, may be a web.topic string, required.
Return: the parsed Web/Topic pai
Since: TWiki::Plugins::VERSION 1.1
| Input | Return |
| ( 'Web', 'Topic' ) | ( 'Web', 'Topic' ) |
| ( '', 'Topic' ) | ( 'Main', 'Topic' ) |
| ( '', '' ) | ( 'Main', 'WebHome' ) |
| ( '', 'Web/Topic' ) | ( 'Web', 'Topic' ) |