%META:TOPICINFO{author="ProjectContributor" date="1727164675" format="1.1" version="1"}%
%META:TOPICPARENT{name="DeveloperDocumentationCategory"}%
%STARTINCLUDE%
---+ CGI and Command Line Scripts

_Programs on the server performing actions such as rendering, saving and renaming topics._

These scripts are located in the =bin= and =tools= directories. This topic describes the interfaces to some of those scripts. All scripts in the =bin= directory can be called from the CGI ([[http://en.wikipedia.org/wiki/Common_Gateway_Interface][Common Gateway Interface]]) environment or from the command line. The scripts in the =tools= directory can only be called from the command line.

%TOC%

---++ CGI Scripts
Details on CGI scripts located in the =bin= directory.

Note that a blank in the 'Default' column means that the parameter
is not required, and has no default. _required_ means the
parameter is required, and has no default. text _in italics_ describes
default behaviour if no value is given.

---+++ General Information
---++++ CGI environment
In the CGI environment parameters are passed to the scripts via the URL and URL parameters. Environment variables are also used to determine the user performing the action. If the environment is not set up, the default user is used (usually =guest=).

---++++ Command-line
You *must* be have the =bin= directory on the perl path to run the scripts from the command line.

<div class="foswikiHelp">%T% To avoid issues with file permissions, *run the scripts as the web server user such as =nobody=, =www-data= or =www=.* %BR%
If running scripts under the control of cron, install the crontab under the
web server user.</div>

Parameters are passed on the command line using two possible formats:

   * Traditional command line "switch" style format:  =-name value=,  The "-" prefix for the keyword is required.
<verbatim class="bash">
$ cd /usr/local/foswiki/bin
$ save -topic MyWeb.MyTopic -user admin -action save -text "New text of the topic"
</verbatim>
   * Keyword format: =parameter=value=.   A "-" prefix is optional.
<verbatim class="bash">
$ cd /usr/local/foswiki/bin
$ save topic=MyWeb.MyTopic user=admin action=save text="New text of the topic"
</verbatim>
All parameters require a value, even if that is the empty string. Note that parameters passed on the command-line should *not* be URL-encoded.

*Note:* If any of the arguments will contain utf-8 strings, (ie. when entering a Unicode topic name), you must run the command
using the perlrun argument =-CA=.  For example:
<pre class="bash">
$ cd /usr/local/foswiki/bin
$ perl -CA ./save -topic MyWeb.My&Uuml;tf8T&ouml;pic -user admin -action save -text "Text with &raquo;&Auml;&euml;&iuml;&ouml;&uuml;&laquo; utf8 characters."
</pre>

For more details on the perl command line arguments, see [[http://perldoc.perl.org/perlrun.html]].

---+++++ "Authentication" in the command line environment

Unlike the CGI environment, the default user for command line operations is =AdminUser=.

   * The =-user= parameter is specific to the command line and is not recognized by in the web environment.  It allows a user to be specified without requiring that the password be supplied.  It is *only* active from the command line.
   * The =-username= / =-password= parameters are processed by the authentication system and require the password be authenticated.  Depending upon the authentication implementation, it may or may not be usable in the command line environment.

When calling a =tools= script from the command line, you normally need to be cd'd to the =bin directory e.g.
<verbatim class="bash">
$ cd bin
$ ../tools/mailnotify -q -nonews -nochanges -Main -System
</verbatim>

---++++ Context

Each script sets a Foswiki =context= to signal to plugins and other components the environment that they are running.  In addition to the per-script context, two additional contexts are optionally set:
   * =command_line= is set if there is no CGI query object available.
   * =static= is set by scripts that render static content like PDF or other offline publishing tools

A comprehensive list of core context identifiers used by Foswiki is found in the %SYSTEMWEB%.IfStatements#Context_identifiers.

---+++ Common parameters
All the scripts accept a number of common parameters. The first two components of the URL after the script name are taken as the web and the topic, respectively. Standard URL parameters are:

| *Parameter* | *Description* | *Default* |
| =cover= | Specifies temporary skin path to prepend to the skin path for this script only (see [[Skins]]) | |
| =debugenableplugins= | During debugging it can be useful to selectively disable all but a subset of plugins. This parameter allows the caller to specify a comma-separated list of plugins that should be enabled. It can only be used when =$ENV{FOSWIKI_ASSERTS}= is set to 1 in =bin/LocalLib.cfg=. | |
| =foswikioriginalquery= | The original query that was being made before a redirect for user confirmation was required. | |
| =foswiki_redirect_cache= | Foswiki sometimes caches long lists of parameters that must survive over a sequence of browser redirects. This parameter identifies one of these caches. The parameter value is a "magic number" that uniquely idenitifies a file in the =working/tmp= directory. These files have a very short lifetime, and are destroyed when the cache is read. | |
| =logout= | requests the !LoginManager to log the current user out (this happens at the begining of the request so will terminate any other operation requested) | |
| =refresh= | If the Foswiki page cache is in use, setting this parameter will invalidate the cache. Valid values are =cache=, =on= and =all=. See PageCaching for more information on the page cache. | |
| =response= | Used as part of the request validation process. | |
| =skin= | Overrides the default skin path (see [[Skins]]) | _value of the =SKIN= preference_ |
| =t= | While the =t= parameter is not actively used by any scripts, it is used when building links to scripts such as =edit=, to ensure that each edit link is unique. This stops the browser from trying to use a cached reply from a previous call to the script. | _generally set to current time, in seconds_ |
| =topic= | Overrides the web.topic path given in the URL (specify Web.<nop>TopicName, or <nop>TopicName in combination with =defaultweb= below) | |
| =defaultweb= | a default value for web, which is over-ridden by specifying either a web in the =topic= param above, or in the url location (used for selecting a web in a webform) | |
| =user= | Command-line only; set the name of the user performing the action. Note: this usage is inherently insecure, as it bypasses webserver login constraints. For this reason only authorised users should be allowed to execute scripts from the command line. | |
| =validation_key= | part of cross-site scripting protection. Any request sent from browsers that might change data stored on the server must carry a key that indentifies the source of the request. | |
| =preserve_vk= | part of cross-site scripting protection. Normally a validation key is expired once it has been used once. However non-HTML5 browsers can't handle this, so the validation key has to be preserved for re-use. | |
| _&lt;any name&gt;_ | Any other parameter name passed to the script is passed through for possible use by the script.  This is _typically_ only applicable to the =edit=, =save= and =view= scripts. | |

Where revision parameters are required, individual versions are identified by positive, non-zero integers. Versions start with 1 and are sequencial. For compatibility reasons, Some scripts accept revision numbers with '1.' (or even 'r1.') prepended to the number, but this usage is deprecated and should be corrected when encountered.

<div class="foswikiHelp">
*Note:* Prior releases of Foswiki would accept the undocumented =username= and =password= parameter on any script.
Foswiki 1.1.9 restricts this to the =view= script and only on POST transactions unless overridden in the Foswiki configuration.
</div>

---+++ =attach=
Despite the name, this script doesn't actually attach a file to a topic - for that, use =upload=. This script is part of the transactions sequence executed when a file is uploaded from the browser. it just generates the "new attachment" page for a topic.

| *Parameter* | *Description* | *Default* |
| =filename= | Name of existing attachment (if provided, this is a "manage attachment" action) | _this is a "new attachment" action_ |

---+++ =changes=
Shows all the changes in the given web. 

The =changes= script can receive one parameter:

| *Parameter* | *Description* | *Default* |
| =minor= | If 0, show only major changes. If 1, show all the changes (both minor and major) | _show major changes_ |

The main difference between invoking this script and using WebChanges is that WebChanges is based on a =%<nop>SEARCH%=, while this script reads the =changes= file in each web, making it much faster.

*NOTE*: The result from =changes= script and the topic WebChanges can be different, if the =changes= file is deleted from a web. In particular, in new installations the =changes= script will return no results while the WebChanges topic will.

---+++ =configure=
=configure= is the browser script used for inspection of, and changes to, the site configuration. None of the parameters to this script are useable for any purpose except =configure=. See [[%SCRIPTURLPATH{"configure"}%][configure]].

---+++ =edit=
The =edit= script understands the following parameters, typically supplied by HTML input fields.

A major role of the =edit= script is new topic creation. Parameters that are mainly relevant to new topic creation are marked with %ICON{"wip"}%

| *Parameter name* | *Description* | *Default* |
| =action= | If =action=text=, then hide the form. If =action=form=, then hide the normal text area and only edit the form. | _edit both_ |
| =breaklock= | If set, any lease conflicts will be ignored, and the edit will proceed even if someone is already editing the topic. | |
| =cmd= | Admin only features, see below | |
| =contenttype= | Optional parameter that defines the application type to write into the CGI header. May be used to invoke alternative client applications | =text/html= |
| =formtemplate= | Name of the form to instantiate in the topic. Set to =none= to remove any existing form. | |
| =notemplateexpansion= | %ICON{"wip"}% Do not expand any macros in the template topic.  (see [[#NewTopicCreation][New topic creation]] below) | _expand_ |
| =onlynewtopic= | %ICON{"wip"}% If =on=, error if the topic already exists | _edit existing topic_ |
| =onlywikiname= | %ICON{"wip"}% If =on=, error if the name of a topic being created is not a WikiWord | _allow non-wikiword names_ |
| =redirectto= | If the user continues from edit to save, and if the save (or cancel) process is successful, save will redirect to this topic or URL. The parameter value can be a =TopicName=, a =Web.TopicName=, or a URL.%BR% *Note:* Redirect to a URL only works if it is enabled in =configure= (Miscellaneous ={AllowRedirectUrl}=). | |
| =rev= | Lets you specify a specific revision to use as the basis of the edit. | _latest_ |
| =template= | Allows you to specify a different skin template. Overrides any setting of =[[SkinTemplates#TemplatePreferences][EDIT_TEMPLATE]]=. | |
| =templatetopic= | %ICON{"wip"}% The name of the template topic, copied to get the initial content for a new topic. (see [[#NewTopicCreation][New topic creation]] below) | |
| =text= | %ICON{"wip"}% Set the text to be edited. If this parameter is not given, the text is taken from the existing topic (if it exists) | |
| =topicparent= | Sets the parent topic. Set to =none= to remove parent. Set to topic name to change parent, leave empty to keep existing parent. | _keep existing parent_ |
| _&lt;any name&gt;_ | This can be used in two ways; first, if the topic has a form with a field called _&lt;any name&gt;_, it will set the value of that field. %ICON{"wip"}% Second, it can be expanded in the topic text during topic creation - see [[#NewTopicCreation][New topic creation]] below | |

The following options are *only* available to the site Administrator.  They can "rewrite history" and should be used with caution only when absolutely necessary.

| *Parameter name* | *Description* | *Default* |
| =cmd=delRev= | *Administrators only* delete the most recent revision of the topic - all other parameters are ignored. You have to be an administrator to use this, and not all store implementations will support it.  This option returns you to an editor for the current version, but the edit is ignored, and save will delete the latest revision. | |
| =cmd=repRev= | *Administrators only* replace the text of the most recent revision of the topic with the text in the =text= parameter. =text= may include embedded meta-data tags. As far as possible, the original author and date of the revision being replaced are retained. You have to be an administrator to use this, and not all store implementations will support it. | |

__Skin notes:__

The =[[SkinTemplates#TemplatePreferences][EDIT_TEMPLATE]]= preference (or the =template= parameter) can be used to override the default 'edit' template on a per-web or per-topic basis.

The =action= parameter works by loading the =editform.tmpl= or =edittext.tmpl= templates in place of the standard =edit.tmpl=. If an =EDIT_TEMPLATE= has been defined, then it replaces =edit=, e.g. if =EDIT_TEMPLATE=specialed= and =action=form= then the template used will be =specialedform=

In most skins that are based on the default templates (such as [[Pattern skin]]) you can easily change the =Edit= and =Edit Wiki<nop>Text= buttons to append the =action= parameter, by setting the =EDITACTION= [[PreferenceSettings][preference]] to the value =text= or =form= (You can always get back to editing the whole topic by removing the =action= parameter from the URL browser Location window, and reloading the edit window).

#NewTopicCreation
__New topic creation %ICON{"wip"}%:__

The string AUTOINC followed by one or more digits anywhere in the topic name will be converted to a number such that the resulting topic name is unique in the target web. However this doesn't happen until the topic is saved.

When a new topic is created using edit, the topic isn't actually created until the edit is saved. The content of the new topic is initialised according to the parameters you pass.
   * =templatetopic= - defines the full name (web.topic) of a topic to use as a template for the new topic. The template topic is copied and, unless =notemplateexpansion= is set, the following macros are expanded in the topic text: =URLPARAM=, =DATE=, =SERVERTIME=, =GMTIME=, =USERNAME=, =WIKINAME=, =WIKIUSERNAME=, =USERINFO=. (see %SYSTEMWEB%.TopicTemplates)
   * =text= - use this as the text of the topic. Macros are *not* expanded in this text. Overrides any text set in the =templatetopic=.
   * =formtemplate= - Overrides any form set in the =templatetopic=.
   * =notemplateexpansion= - given by =templatetopic=. Use this when you want a verbatim copy of a topic.
   * =onlynewtopic= and =onlywikiname= are used to control validation of the new topic name.
   * _&lt;any name&gt;_ - besides the form field value setting described above, when creating a new topic, =%<nop>URLPARAM{"= _&lt;any name&gt;_ ="}%= in the =templatetopic= will be expanded to the parameter value.

---+++ =login=
Used for logging in with !TemplateLoginManager, and for interactive validation of operations that require user confirmation.
| *Parameter* | *Description* | *Default* |
| =foswikiloginaction= | If 'validate', the login script is being used for interactive validation of an operation. Otherwise it is being used for login. | |
| =foswiki_origin= | URL that was being accessed when an access violation occurred. the login process will redirect to this URL if it is successful | |
| =remember= | If set, this will cause the user's login to be retained even after their browser is shut down. |
| =sudo= | promote login to _internal admin_ (admins only) | |
| =password= | password of user logging in | |
| =username= | username of user logging in (if set, login will attempt to authenticate) | |
| =usernamestep= | used to initialise the =username= input field in the login form (will not attempt to authenticate) | |

<div class="foswikiHelp"> 
*%T% Note:* The =login= script will only accept the username and password fields when submitted with a POST.
</div>

---+++ =logon=
Used for logging in when Web Server authentication is being used (e.g. !ApacheLoginManager). The script does nothing; it is purely a placeholder for triggering the login process. The webserver must be set up to require a valid user to access this script, thus triggering the webserver login process.
 
---+++ =manage=
Performs a range of management functions.

<div class="foswikiHelp"> 
*%X% Note:* The =manage= script can only be called via the HTTP POST method. Make sure you specify =method="post"= if you call the =manage= script via a form action. It is not possible to call =manage= from an =&lt;a href ...&gt;= link.
</div>

| *Parameter* | *Description* | *Default* |
| =action= | One of =create=, =createweb=, =changePassword=, =resetPassword=, =bulkRegister=, =deleteUserAccount=, =editSettings=, =saveSettings=, =restoreRevision= | _required_ |

---++++ =action=create=
Alternative entry point for creation, via =edit=, of a new topic, used by screens that support several actions using =manage=.
| *Parameter* | *Description* | *Default* |
| =topic= | Name of topic to create (can be web.topic) | _required_ |
Other parameters are the same as for =edit=.

---++++ =action=createweb=
Create a new web
| *Parameter* | *Description* | *Default* |
| =baseweb= | Name of the web to copy to create the new web | _required_ |
| =newtopic= | Value of %<nop>TOPIC% within the web creation message. Optionally used in some skins to signify a non-default home topic. | |
| =newweb= | Name of the new web | _required_ |
| =nosearchall= | Value for NOSEARCHALL | '' |
| =webbgcolor= | value for WEBBGCOLOR | '' |
| =websummary= | Value for WEBSUMMARY | '' |

---++++ =action=editSettings=
No parameters

---++++ =action=saveSettings=
| *Parameter* | *Description* | *Default* |
| =originalrev= | Revision that the edit started on | _latest_ |
| =redirectto= | If the savesettings process is successful, save will redirect to this topic or URL. The parameter value can be a =TopicName=, a =Web.TopicName=, or a URL.%BR% *Note:* Redirect to a URL only works if it is enabled in =configure= (Miscellaneous ={AllowRedirectUrl}=). | _redirect to the web.topic from the URL path_ |
| =text= | Text of the topic | _required_ |
| =action_save= | Must be set to =Save= or settings are not saved | _required_ |
| =action_cancel= | Must be set to =Cancel= to cancel save. | _required_ |
If neither =action_save= or =action_cancel= are provided, an oops error is issued. All other parameters may be interpreted as form fields, depending on the current form definition in the topic.

---++++ =action=bulkRegister=
See BulkRegistration.
| *Parameter* | *Description* | *Default* |
| =logtopic= | Topic to save the log in | _same as topic name, with 'Result' appended_ |
| =overwritehometopics= | Whether to overwrite existing home topics or not | _do not overwrite_ |

---++++ =action=changePassword=
Change password, email address, or both, of a user.
| *Parameter* | *Description* | *Default* |
| =email= | new email address | |
| =oldpassword= | current password | _required, unless current user is an admin_ |
| =password= | new password | |
| =passwordA= | new password confirmation | _required if =password= is given_ |
| =username= | login name of user to change password/email for | _required_ |
=password, =passwordA= and =email= are optional. If neither or =password= and =passwordA= is set, then the user password is left unchanged. If =email= is unset, their email is left unchanged.

---++++ =action=resetPassword=
Reset the password for a single or multiple users
| *Parameter* | *Description* | *Default* |
| =introduction= | message to be sent alongside the reset, most often used to announce to the user that they have been given an account.  | |
| =loginname= | *list* of usernames to reset | _required_ |

This is used by BulkResetPassword and ResetPassword. Only administrators can provide a list of login usernames, non-admins can only provide a single UserName. 

BulkRegistration provides the means to create multiple accounts but it does not announce those accounts to the users who own them. BulkResetPassword is used to assign the passwords, the Introduction is used to explain why they are receiving the mail.

---++++ =action=deleteUserAccount=
For non-admin users, it unregisters (removes) the currently logged-in user.  Administrators can remove any account.
| *Parameter* | *Description* | *Default* |
| =user= | User ID to be removed | _required_. Must be current logged in user if not admin |
| =password= | Users' password | _required if not admin_ |
| =removeTopic= | Should user topic be moved to trash web? | |

---++++ =action=restoreRevision=
Alternative entry point for =edit=, used by screens that support several actions using =manage. Parameters are as for =edit=.

---++++ =action=addUserToGroup=
add a user / list of users to a group
| *Parameter* | *Description* | *Default* |
| =create= | create the group if it doesn't exist | =0= |
| =groupname= |groupname to change | _required_ |
| =redirectto= | If the add process is successful, =manage= will redirect to this topic or URL. The parameter value can be a =TopicName=, a =Web.TopicName=, or a URL.%BR% *Note:* Redirect to a URL only works if it is enabled in =configure= (Miscellaneous ={AllowRedirectUrl}=). | None.  An Oops screen showing the results is returned. |
| =username= | *list* of usernames/wikinames to add to group | _required_ |

---++++ =action=removeUserFromGroup=
remove a user / list of users to a group
| *Parameter* | *Description* | *Default* |
| =groupname= |groupname to change | _required_ |
| =redirectto= | If the remove process is successful, =manage= will redirect to this topic or URL. The parameter value can be a =TopicName=, a =Web.TopicName=, or a URL.%BR% *Note:* Redirect to a URL only works if it is enabled in =configure= (Miscellaneous ={AllowRedirectUrl}=). | None.  An Oops screen showing the results is returned. |
| =username= | *list* of usernames/wikinames to add to group | _required_ |

---+++ =oops=
This script is mainly used for rendering pages containing error messages, though it is also used for some functional actions such as manage pages (move topic etc).

=oops= templates are used with the =oops= script to generate system messages. This is done to make internationalisation or other local customisations simple. 

The =oops= script supports the following parameters:

| *Parameter* | *Description* | *Default* |
| =def= | Can be set to the name of a single definition within =template=. This definition will be instantiated in the =template= wherever =%<nop>INSTANTIATE%= is seen. This lets you use a single template file for many messages. For an example, see =oopsmanagebad.tmpl=. | |
| =paramN= | Where N is an integer from 1 upwards. These values will be substituted into =template= for =%<nop>PARAM1%= etc. | |
| =template= | Name of the template file to display | =oops= |

---+++ =preview=
This script is _deprecated_. Its functions are covered by the =save= script.

---+++ =rdiff=
Renders the differences between version of a topic

| *Parameter* | *Description* | *Default* |
| =context= | number of lines of context | |
| =render= | the rendering style {sequential, sidebyside, raw, debug} | =DIFFRENDERSTYLE=, =sequential= |
| =rev1= | the higher revision | _latest_ |
| =rev2= | the lower revision | _latest_ |
| =type= | =history= gives a history, =diff= rev1 against rev2, =last= latest to previous | =diff= |
The =context= parameter is only respected if the back-end store supports
context diffs.

---+++ =register=

| *Parameter* | *Description* | *Default* |
| =action= | =register= or =verify= or =approve= or =disapprove= | _required_ |

<div class="foswikiHelp">
*%X% Note:* The =register= script can only be called via the HTTP POST method except when the action is =verify=. Make sure you specify =method="post"= if you call the =register= script via a form action. It is not possible to call =register= from an =&lt;a href ...&gt;= link. The =verify= action is an exception as it is used to verify registration by clicking a href link from an email.
</div>

---++++ =action=register=

Starts the registration process for a new user.

User data is passed in 0 or more parameters of the format =FwkNname= where =Fwk= is a standard prefix, =N= is =0= for an optional parameter and =1= for a required parameter, and =name= is the parameter name. The following standard =Fwk= parameters are predefined:

| *Parameter* | *Description* | *Default* |
| =Fwk1Email= | New user's email address | _required_ |
| =Fwk1FirstName= | New user's first name | _required_ |
| =Fwk1LastName= | New user's surname | _required_ |
| =Fwk1WikiName= | Wikiname of user being registered | _required_ |
| =Fwk1LoginName= | New user's login username | _required_ |
| =Fwk1Password= | New user's password | |
| =Fwk0Confirm= | Password confirmation (if enabled) | |
| =Fwk0Name= | User's name. Defaults to =FirstName !LastName= | |
| =Fwk0AddToGroups= | Accepts a comma-separated list of group names to add the new user to. | |

Any additional =Fwk= parameters will be written to the user topic (_except_ 
=Photo= and =Confirm=).

If registration verification (or registration approval) is enabled in
=configure=, a pending registration record will be created and the
registrant (or the approver) will be emailed with the verification code.

If all goes well, then:
   * If verification is required, outputs the registration confirmation screen.
   * If approval is required, outputs the pending approval screen.
   * Otherwise outputs the welcome screen.

When called from CGI, this method requires a POST request.

---++++ =action=verify=

Sent to activate a user's pending registration. Only applicable if
registration verification is enabled.

| *Parameter* | *Description* | *Default* |
| =code= | Activation code, verifies a pending registration  |

If the verification is successful:
   * If approval is required, outputs the pending approval screen.
   * Otherwise outputs the welcome screen.

---++++ =action=approve=
Sent to activate a pending registration. Only applicable if
registration approval is enabled.

| *Parameter* | *Description* | *Default* |
| =code= | Approval code for the pending registration  |

Outputs the welcome screen and mails the successful registrant.

---++++ =action=disapprove=
Sent to deny a pending registration. Only applicable if
registration approval is enabled.

| *Parameter* | *Description* | *Default* |
| =code= | Approval code for the pending registration  |

Presents a screen where the admin can optionally enter an email
message to be sent to the failed registrant. NOTE: the registration
fails even if this mail is _not_ sent.

If the =code= has the value =DENIED= then the request is interpreted as
the second stage of an approval denial. Registration parameters are
passed in the URL parameters =email=, =referee=, =wikiname= and =feedback.
These parameters are used to compose a feedback mail for the failed
registrant.

---+++ =rename=
Used for renaming webs, topics and attachments.

| *Parameter* | *Description* | *Default* |
| =action= | =renameweb= or =renameother= | =renameother= |
| =currentwebonly= | if non-0, searches current web only for links to this web | _search all webs_ |
| =confirm= | if non-0, requires a second level of confirmation | |
| =referring_topics= | (internal use only) list of topics that refer to the web or topic being renamed | |
| =redirectto= | If the rename process is successful, rename will redirect to this topic or URL. The parameter value can be a =TopicName=, a =Web.TopicName=, or a URL.%BR% *Note:* Redirect to a URL only works if it is enabled in =configure= (Miscellaneous ={AllowRedirectUrl}=). | _the renamed topic_ |

---++++ =action="renameweb"=
Rename a web.
| *Parameter* | *Description* | *Default* |
| =newparentweb= | new parent web name | _existing parent_ |
| =newsubweb= | new web name | |

---++++ =action=renameother=
Rename a topic or an attachment.
| *Parameter* | *Description* | *Default* |
| =attachment= | Attachment to move | |
| =currentwebonly= | if non-0, searches current web only for links to this topic | _search all webs_ |
| =newattachment= | New name for attachment | _same as =attachment=, if given_ |
| =newtopic= | new topic name | _required_ |
| =newweb= | new web name | _required_ |
| =onlywikiname= | if =off=, a non-wikiword is acceptable for the new topic name | =on= |
| =template= | template for error when an attachment doesn't exist, =deleteattachment= for when deleting an attachment | |

<div class="foswikiHelp">
*%X% Note:* The =rename= script can only be called via the HTTP POST method. Make sure you specify =method="post"= if you call the =rename= script via a form action. It is not possible to call =rename= from an =&lt;a href ...&gt;= link.
</div>

---+++ =resetpasswd=
This script is _deprecated_. Its functions are covered by the =manage= script.

---+++ =rest=
This REST ([[http://en.wikipedia.org/wiki/REST][Representational State Transfer]]) script can be invoked via http in the same way as the other scripts (see *Invocation Examples*, below) to execute a function that is associated to a "subject" and a "verb" (see below). These functions are usually registered by plugins using the =Foswiki::Func::registerRESTHandler= method. The =rest= script will print the result directly to the browser unless the =endpoint= parameter is specified, in which case it will output a redirect to the given topic or url.

The =rest= script supports the following parameters:
| *Parameter* | *Description* | *Default* |
| =redirectto= | Redirect to this topic or URL after successfully running the rest function. The parameter value can be a =TopicName=, a =Web.TopicName=, or a URL.%BR% *Note:* Redirect to a URL only works if it is enabled in =configure= (Miscellaneous ={AllowRedirectUrl}=). | None. |
| =password= | See =username= | |
| =username= | If =TemplateLogin=, or a similar login manager not embedded in the web server, is used, then you can pass a username and password to the server (though see below for a preferred way to pass authentication information). |

REST scripts that require a topic context must use the standard =topic= parameter to pass the topic name, as the URL path is used to identify the REST function. If not defined, then the topic context in REST handlers will be [[%HOMEWEB%.%HOMETOPIC%]].

The function is free to use any other query parameters for its own purposes.

---++++ =rest= authentication
If a REST operation requires a logged-in user but no user is logged in, then it will return a 401 status. In the case of the =TemplateLogin= login manager, this will include a =WWW-Authenticate= header starting with =FoswikiBasic=. This allows the status to percolate through to Javascript where it can be handled by your code. The =realm= in the =WWW-Authenticate= header is taken from the ={AuthRealm}= setting in =configure=, or the empty string if it is not set.

If you are using =TemplateLogin=, the preferred way to pass user login information back to the server is to use the =X-Authorization= HTTP header. This header is modelled on the HTTP Authorization header, as described in [[http://www.ietf.org/rfc/rfc2617.txt]], except that the scheme name =FoswikiBasic= is used instead of =Basic=. The user-id and password are combined with a : and base64 encoded. For example, if the user agent wishes to send the userid "Aladdin" and password "open sesame", it would use the following header field:
<verbatim>
X-Authorization: FoswikiBasic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
</verbatim>
When used with jQuery:
<verbatim>
$.ajax({
  beforeSend: function(xhrObj){
    xhrObj.setRequestHeader("X-Authorization",
      "FoswikiBasic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
  }
});
</verbatim>

<div class="foswikiHelp">
%X% The =rest= script should *always* be configured to require authentication in any site that is using =ApacheLogin=. Otherwise there is a risk of opening up major security holes. So make sure you add it to the ={AuthScripts}= list in =configure=.
</div>

<div class="foswikiHelp"> 
*%X% Note:* As of 1.1.9, the =rest= script no longer will accept the username and password fields by default. If the prior behavior is required, it can be enabled in =bin/configure=
by setting =$Foswiki::cfg{Session}{AcceptUserPwParam} = /^rest$/;=.   Note that even with this enabled, the =rest= script requires that the username and password be entered using POST.
</div>

---++++ Invocation Examples

The =rest= script assumes that it will be called with URL in the form:

=http://my.host/bin/rest/&lt;subject&gt;/&lt;verb&gt;=

where =&lt;subject&gt;= must be the WikiWord name of one of the installed [[Plugins]], and the =&lt;verb&gt;= is the alias for the function registered using the =Foswiki::Func::registerRESTHandler= method. The =&lt;subject&gt;= and =&lt;verb&gt;= are then used to lookup and call the registered function. If you need to
pass a topic name, then this is passed in the =topic= URL parameter.

As an example, the EmptyPlugin has registered a function to be used with the =rest= script under the subject *EmptyPlugin* and the verb *example*. 

The URL to call this function from a browser would be:
   * =%SCRIPTURL{rest}%/EmptyPlugin/example?topic=My.TopicName=
alternatively, to run it from the commandline:
   * =cd foswiki/bin ; ./rest /EmptyPlugin/example -topic=My.TopicName=

Note that for Plugins to register REST handlers, they must be enabled in =configure=.

---++++ Retrieving passed values
Additional parameters can be recovered via the query object in the =$session=, for example with the url:
<verbatim class="html">
http://my.host/bin/rest/MyPlugin/update?web=foo
</verbatim>

The url parameters can be processed using:
<verbatim class="perl">
my $query = $session->{request};
my $web = $query->{param}->{web}[0];
</verbatim>

---+++ =save=
The =save= script performs a range of save-related functions.

| *Parameter* | *Description* | *Default* |
| =action_addform= | Redirect _to_ the "change form" page. | |
| =action_cancel= | exit without save, return to view | |
| =action_checkpoint= | save and redirect to the edit script, =dontnotify= is =on= | |
| =action_delRev= | *Administrators only* delete the most recent revision of the topic - all other parameters are ignored. You have to be an administrator to use this, and not all store implementations will support it. | |
| =action_preview= | preview edited text | |
| =action_quietsave= | save, and return to view, =dontnotify= is =on= | |
| =action_replaceform= | Redirect _from_ the "change form" page. | |
| =action_repRev= | *Administrators only* replace the text of the most recent revision of the topic with the text in the =text= parameter. =text= must included embedded meta-data tags. All other parameters are ignored. You have to be an administrator to use this, and not all store implementations will support it. | |
| =action_save= | *default behaviour*; save, return to view | |
| =dontnotify= | if non-0, suppress change notification | |
| =edit= | The bin script to use to re-edit the topic when action is =checkpoint= | =edit= |
| =editaction= | When action is =checkpoint=, =add form= or =replace form...=, this is used as the =action= parameter to the =edit= script that is redirected to after the save is complete. | |
| =editparams= | The parameter string to use to edit the topic when action is =checkpoint= | |
| =forcenewrevision= | if set, forces a revision even if Foswiki thinks one isn't needed | |
| =formtemplate= | if defined, use the named template for the form (will remove the form if set to 'none') | |
| =newtopic= | If =templatetopic= is given, and this parameter is set to 1 and the topic does not exist, will clear the initial topic text. | |
| =onlynewtopic= | If set, error if topic already exists | |
| =onlywikiname= | If set, error if topic name is not a WikiWord | |
| =originalrev= | Revision on which the edit started. | |
| =redirectto= | The save process will redirect to this topic or URL if it is successful. (Typically this would be the URL that was being viewed when edit was invoked). The parameter value can be a =TopicName=, a =Web.TopicName=, or a URL.%BR% *Note:* Redirect to a URL only works if it is enabled in =configure= (Miscellaneous ={AllowRedirectUrl}=). | _topic specified in URL path_ |
| =template= | The template to use to re-edit the topic when action is =checkpoint= | |
| =templatetopic= | Name of a topic to use as a template for the text and form (new topic _only_) (see [[#NewTopicCreation][New topic creation]] above) | |
| =text= | New text of the topic | |
| =topicparent= | Sets the parent topic. Set to =none= to remove parent. Set to topic name to change parent, leave empty to keep existing parent. | _keep existing parent_ |
| =Local+name= | create/set a local META:PREFERENCE called =name= | |
| =Set+name= | create/set a normal topic META:PREFERENCE called =name= | |
| =Unset+name= | remove a META:PREFERENCE call =name= | |
| =Default+name= | gives a default for =name=. If =name= is set to this value, then the preference will be removed. %X% Requires a corresponding =Set+name= or =Local+name= to work. | |
| _&lt;any name&gt;_ | If the topic has a form with a field called _&lt;any name&gt;_, it will set the value of that field. | |

Any errors will cause a redirect to another page, either an =oops= page to report the error, or a =login= if the save is not authorized.

The string AUTOINC followed by one or more digits anywhere in the topic name will be converted to a number such that the resulting topic name is unique in the target web.

When the action is =save=, =checkpoint=, =quietsave=, or =preview=:
   1 The new text is taken from the =text= parameter, if it is defined,
      * otherwise it is taken from the =templatetopic=, if it is defined, (new topic _only_)
      * otherwise it is taken from the previous version of the topic, if any,
   1 The name of the new form is taken from the =formtemplate=, if defined
      * otherwise it is taken from the =templatetopic=, if defined, (new topic _only_)
      * otherwise it is taken from the previous version of the topic, if any,
      * otherwise no form is attached.
   1 The value for each field in the form is taken from the query, if it is defined
      * otherwise it is taken from the =templatetopic=, if defined, (new topic _only_)
      * otherwise it is taken from the previous version of the topic, if any,
      * otherwise it defaults to the empty string.

Merging is only enabled if the topic text comes from =text= and =originalrev= is &gt; 0 and is not the same as the revision number of the most recent revision. If merging is enabled both the topic and the meta-data are merged.

Form field values are passed in parameters named 'field' - for example, if I have a field =Status= the parameter name is =Status=.

<div class="foswikiHelp"> 
*%X% Note:* The =save= script can only be called via HTTP POST method. Make sure you specify =method="post"= if you call the =save= script via a form action. Example:

<verbatim class="html">
<form name="new" action="%SCRIPTURLPATH{save}%/Sandbox/" method="post">
    ...
</form>
</verbatim>
It is not possible to call =save= from an =&lt;a href ...&gt;= link.
</div>

---+++ =search=
This cgi script has been deprecated. When called, it will redirect to the WebSearch topic, and the parameters will be passed on.

---+++ =statistics=
<!--
   * Set ISSTATISTICSTOPIC = %IF{"istopic '%STATISTICSTOPIC%'" else="!WebStatistics" then="[[$percntSTATISTICSTOPIC$percnt][WebStatistics]]"}%
-->

<div class="foswikiHelp">
%X% *Note:* This script is no longer callable using a
simple HTTP "GET" operation.  It must be called using the POST method using a
form.
</div>

Refresh the %ISSTATISTICSTOPIC% topics in range of webs.
| *Parameter* | *Description* | *Default* |
| =autocreate= | Flag to request auto-creation of missing !WebStatistics topics. 0=false 1=true | _(See logging and statistics page in =bin/configure=.)_ |
| =logdate= | Generate statistics for the specified year/month, spacified as =YYYYMM= | _current month_ |
| =subwebs= | Flag to request processing of subwebs of the requested webs. 0=false 1=true | 0 _(Subwebs are not processed)_ |
| =webs= | comma-separated list of webs. | _all accessible webs_ |

Command line examples:  (All run by first changing to the =foswiki/bin= directory)
<div class="foswikiAlert">
%X% *Caution:* This script writes to foswiki system files.  It *must* be run as the web server user.  If ownership of critical system files is changed, it may disrupt the web server!
</div>
   1 ==./statistics== updates _all user webs, excluding subwebs_
   1 ==./statistics webs=Userweb,%SANDBOXWEB% subwebs=1== updates _Userweb and %SANDBOXWEB% including subwebs_
   1 ==./statistics -webs %WEB% -autocreate 1== updates %WEB%, creating a missing !WebStatistics topic if permitted by configuration.

see SiteToolStatistics for more details on %ISSTATISTICSTOPIC%, a form you can POST to update statistics, and how to update statistics using cron.

---+++ =upload=
Uploads an attachment to a topic. The HTTP request is expected to be in =multipart/form-data= format.
| *Parameter* | *Description* | *Default* |
| =changeproperties= | if non=0, this is a property change operation *only* - no file will be uploaded. | |
| =createlink= | if non-0, will create a link to file at end of topic | |
| =filecomment= | Comment to associate with file in attachment table | |
| =filepath= | local (client) path name of the file being uploaded. This is used to look up the data for the file in the HTTP query. | |
| =hidefile= | if non-0, will not show file in attachment table | |
| =noredirect= | Normally the script will redirect to 'view' when the upload is \
     complete, but also designed to be useable for REST-style calling using \
     the 'noredirect' parameter. If this parameter is set it will return an \
     appropriate HTTP status code and print a message to STDOUT, starting \
     with 'OK' on success and 'ERROR' on failure. | |
| =redirectto= | URL to redirect to after upload. The parameter value can be a \
     =TopicName=, a =Web.TopicName=, or a URL. Redirect to a URL only works \
     if it is enabled in =configure=, and is ignored if =noredirect= is \
     specified.%BR% (Miscellaneous ={AllowRedirectUrl}=). | _topic specified in URL path_ |

*Tips*
   * You can use a tool like =curl= to upload files from the command line using this script.
   * You can call upload easily from !XmlHttpRequest in Javascript.
   * You can directly invoke upload from the CLI script.__New with Foswiki 2.1__
      * You must use the Perl CLI options  '-CA' if the filename or any other arguments contains utf-8 (non-ASCII) characters.
      * ex. Run from the bin directory: =perl -CA ./upload filepath="/path/and/filename.dat" filename="&Atilde;ttachname.dat" topic=Sandbox.Existing&Uuml;tf8Topic=

<div class="foswikiHelp"> 
*%X% Note:* The =upload= script can only be called via HTTP POST method. Make sure you specify =method="post"= if you call the =upload= script via a form action. It is not possible to call =upload= from an =&lt;a href ...&gt;= link.
</div>

---+++ =view=
Used for viewing topics.

| *Parameter* | *Description* | *Default* |
| =contenttype= | Allows you to specify a different *Content-Type:* (e.g. =contenttype=text/plain=) | =text/html= |
| =raw= | <ul>\
<li> =on= - show the text of the topic in a scrollable textarea. </li> \
<li> =debug= - as =on=, but also shows the metadata (forms etc) associated with the topic. </li> \
<li> =text= - show only the source of the topic, as plain text (Content-type: text/plain). Only shows the body text, *not* the form or other meta-data. </li> \
<li> =all= - show only the source of the topic, as plain text (Content-type: text/plain), *with embedded meta-data*. This may be useful if you want to extract the source of a topic to a local file on disc. </li></ul> | |
| =rev= | Revision to view (e.g. =rev=45=) | _latest_ |
| =SEARCH&lt;hex number&gt;= | Identifies a result set that is being paged through | |
| =section= | Allows to view only a part of the topic delimited by a named section (see %SYSTEMWEB%.VarSTARTSECTION). If the given section is not present, no topic content is displayed. | |
| =template= | Allows you to specify a different skin template, overriding the 'view' template the view script would normally use. The default template is =view=. For example, you could specify [[%SCRIPTURLPATH{"view"}%/%WEB%/%TOPIC%?template=edit][%SCRIPTURLPATH{"view"}%/%WEB%/%TOPIC%?template=edit]]. This is mainly useful when you have specialised templates for a Wiki Application. | |
| _&lt;any name&gt;_ | It can be expanded in the topic text during rendering and referenced in IF statements  - See the %SYSTEMWEB%.VarURLPARAM macro and %SYSTEMWEB%.IfStatements | |

<div class="foswikiHelp"> 
%X% For historical reasons, the view script has a special interpretation of the =text= skin. This skin cannot be redefined.
</div>

---+++ =viewfile=
Used for viewing attachments. Normally, a site will publish the attachments (=pub=) directory using a URL. However if it contains sensitive information, you will want to protect attachments using [[AccessControl][AccessControls]]. In this case, you can use the =viewfile= script to give access to attachments while still checking access controls.

| *Parameter* | *Description* | *Default* |
| =filename= | name of attachment | _required_ |
| =rev= | Revision to view | _latest_ |

Instead of using the =filename= parameter, you can append the attachment name
to the end of the URL path (after the topic) e.g. =%SCRIPTURL{viewfile}%/Webname/TopicName/Attachment.gif=

---++ Tool Scripts
Details on command line scripts located in the =tools= directory.

---+++ =configure=
This is a fully functional command line interface to the Foswiki configuration.  It is able to set and check configuration values, and to run wizards.

=tools/configure [-search] [-getspec] [-getcfg] [-check] [-wizard] [-method] [-save] [-json] [-trace] [-help] [-noprompt] [-expert]=

Note: if you need to pass in international characters, it needs to be run with the =perl -CA= command argument. (=perl -CAS= when running a new configuration bootstrap)

| *Function* | *Usage* |
| Bootstrap a new install without helptext | =tools/configure -save -expert= |
| Bootstrap an installation containing international characters | =perl -CAS tools/configure -save= |
| Set multiple variables | =tools/configure -save -set {Password}='newadminpassword' -set {WebMasterEmail}='newadmin@yourco.com'= |
| Check a setting or section of settings. | =tools/configure -check Internationalisation= |
| Run a wizard | =tools/configure -wizard Email -method send_test_email= |
| Set admin password that contains international characters | =perl -CA tools/configure -save -set {Password}='tajemstv&iacute;'= |
| Display one or more settings | =tools/configure -getcfg {SMTP} -getcfg {PubDir}= |

For full help, run =tools/configure -help=.

---+++ =dependencies=
Generates a report of missing or all dependencies.  This report is also available to administrators at [[%SYSTEMWEB%.PerlDependencyReport]]

   $ =tools/dependencies=: Generates a report on the missing dependencies
   $ =tools/dependencies -all=: Generates a report on all dependencies, installed or missing, along with information on the installation location.

---+++ =geturl.pl=
This is a very simple script to get the content of a web site, either using GET or POST. It is marked as _deprecated_ and might be removed in a future release. Its functions are covered by the standard =wget= and =curl= commands, which have the added advantage of performing authentication..
   * Usage:    =geturl.pl &lt;host&gt; &lt;path&gt; [&lt;port&gt; [&lt;header&gt;]]=
   * Example:  =geturl.pl some.domain /some/dir/file.html 80=
   * Will get: =http://some.domain:80/some/dir/file.html=
   * Example:  =geturl.pl POST some.domain /bin/statistics?webs=%SANDBOXWEB%=
   * Will post: =http://some.domain/bin/statistics?webs=%SANDBOXWEB%= triggering a statistics run

---+++ =rewriteshebang.pl=
Simple script to rewrite the =#!/usr/bin/perl= [[http://en.wikipedia.org/wiki/Shebang_%28Unix%29][shebang]] lines specific to your local Perl installation. It will rewrite the first line of all your cgi scripts so they use a different shebang line. Use it if your perl is in a non-standard location, or you want to use a different interpreter (such as 'speedy').

---+++ =tick_foswiki.pl=
This script executes a number of non-essential regular administration tasks that will help keep your site healthy and happy, such as removing expired sessions and lease files.

It is intended to be run as a cron job or a scheduled task once a week. Example crontab entry:%BR%
=0 0 * * 0 cd /usr/local/foswiki/bin && perl ../tools/tick_foswiki.pl=

*Note:* The script has to be run by a user who can write files created by the webserver user.

Extensions, such as the MailerContrib, also install tool scripts. Check the documentation of the extension for details.

---+++ =extension_installer=
This script will download and install, or remove an extension.

For more details, execute it from the Foswiki root directory with the =usage= parameter:
<verbatim>
./tools/extension_installer usage
</verbatim>
Note that this script is a generic version of the =_installer= script shipped with each extension.  There are 3 ways to install a script using these scripts:
   * Download =SomePlugin_installer= and execute it from the Foswiki root directory
   * run =./tools/extension_installer !SomePlugin= - the extension will be downloaded and installed
   * Use the configure web interface to the Extensions Installer.

---
*%MAKETEXT{"Related topics:"}%* AdminDocumentationCategory, DeveloperDocumentationCategory
