---+ Package =TWiki=

TWiki operates by creating a singleton object (known as the Session
object) that acts as a point of reference for all the different
modules in the system. This package is the class for this singleton,
and also contains the vast bulk of the basic constants and the per-
site configuration mechanisms.

Global variables are avoided wherever possible to avoid problems
with CGI accelerators such as mod_perl.


%TOC%

---++ StaticMethod *getTWikiLibDir* <tt>() -> $path</tt>

STATIC method.

Returns the full path of the directory containing TWiki.pm



---++ ObjectMethod *UTF82SiteCharSet* <tt>($utf8) -> $ascii</tt>
Auto-detect UTF-8 vs. site charset in string, and convert UTF-8 into site
charset.



---++ ObjectMethod *writeCompletePage* <tt>($text,$pageType,$contentType)</tt>

Write a complete HTML page with basic header to the browser.
$text is the HTML of the page body (&lt;html&gt; to &lt;/html&gt;)

This method removes noautolink and no tags before outputting the page.



---++ ObjectMethod *writePageHeader* <tt>($query,$pageType,$contentType,$contentLength)</tt>

All parameters are optional.

	* =$query= CGI query object | Session CGI query (there is no good reason to set this)
	* =$pageType= - May be "edit", which will cause headers to be generated that force caching for 24 hours, to prevent Codev.BackFromPreviewLosesText bug, which caused data loss with IE5 and IE6.
	* =$contentType= - page content type | text/html
	* =$contentLength= - content-length | no content-length will be set if this is undefined, as required by HTTP1.1

Implements the post-Dec2001 release plugin API, which requires the
writeHeaderHandler in plugin to return a string of HTTP headers, CR/LF
delimited. Filters any illegal headers. Plugin headers will override
core settings.



---++ ObjectMethod *redirect* <tt>($url,...)</tt>

Generate a CGI redirect to $url unless (1) $session->{cgiQuery} is undef or
(2) $query->param('noredirect') is set to a true value. Thus a redirect is
only generated when in a CGI context.

The ... parameters are concatenated to the message written when printing
to STDOUT, and are ignored for a redirect.

Redirects the request to $url, via the CGI module object $query unless
overridden by a plugin declaring a =redirectCgiQueryHandler=.



---++ StaticMethod *isValidWikiWord* <tt>($name) -> $boolean</tt>

Check for a valid WikiWord or WikiName



---++ StaticMethod *isValidTopicName* <tt>($name) -> $boolean</tt>

Check for a valid topic name



---++ StaticMethod *isValidAbbrev* <tt>($name) -> $boolean</tt>

Check for a valid ABBREV (acronym)



---++ StaticMethod *isValidWebName* <tt>($name,$system) -> $boolean</tt>

STATIC Check for a valid web name. If $system is true, then
system web names are considered valid (names starting with _)
otherwise only user web names are valid



---++ ObjectMethod *readOnlyMirrorWeb* <tt>($theWeb) -> ($mirrorSiteName,$mirrorViewURL,$mirrorLink,$mirrorNote)</tt>

If this is a mirrored web, return information about the mirror. The info
is returned in a quadruple:

| site name | URL | link | note |



---++ ObjectMethod *getSkin* <tt>() -> $string</tt>

Get the currently requested skin path



---++ ObjectMethod *getScriptUrl* <tt>($web,$topic,$script,...) -> $absoluteScriptURL</tt>

Returns the absolute URL to a TWiki script, providing the web and topic as
"path info" parameters.  The result looks something like this:
"http://host/twiki/bin/$script/$web/$topic".
	* =...= - an arbitrary number of name,value parameter pairs that will be url-encoded and added to the url. The special parameter name '#' is reserved for specifying an anchor. e.g. <tt>getScriptUrl('x','y','view','#'=>'XXX',a=>1,b=>2)</tt> will give <tt>.../view/x/y#XXX?a=1&b=2</tt>



---++ ObjectMethod *getOopsUrl* <tt>($template,@options) -> $absoluteOopsURL</tt>

Composes a URL for an "oops" error page. The @options consists of a list
of key => value pairs. The following keys are used:
	* =-web= - web name
	* =-topic= - topic name
	* =-def= - optional template def within the main template file
	* =-params= - a single parameter, or a reference to an array of parameters  These are passed in the URL as '&param1=' etc.

Do _not_ include the "oops" part in front of the template name.

Alternatively you can pass a reference to an OopsException in place of the template. All other parameters will be ignored.

The returned URL ends up looking something like this:
"http://host/twiki/bin/oops/$web/$topic?template=$template&param1=$scriptParams[0]..."



---++ ObjectMethod *normalizeWebTopicName* <tt>($theWeb,$theTopic) -> ($theWeb,$theTopic)</tt>

Normalize a Web<nop>.<nop>TopicName
<pre>
Input:							 Return:
  ( 'Web',  'Topic' )			( 'Web',  'Topic' )
  ( '',	  'Topic' )			( 'Main', 'Topic' )
  ( '',	  '' )				  ( 'Main', 'WebHome' )
  ( '',	  'Web/Topic' )	  ( 'Web',  'Topic' )
  ( '',	  'Web.Topic' )	  ( 'Web',  'Topic' )
  ( 'Web1', 'Web2.Topic' )	 ( 'Web2', 'Topic' )
  ( '%MAINWEB%', 'Web2.Topic' ) ( 'Main', 'Topic' )
  ( '%TWIKIWEB%', 'Web2.Topic' ) ( 'TWiki', 'Topic' )
</pre>
Note: Function renamed from getWebTopic

SMELL: WARNING: this function defaults the web and topic names.
Be very careful where you use it!



---++ ClassMethod *new* <tt>($remoteUser,$query)</tt>
Constructs a new TWiki object. Parameters are taken from the query object.

	* =$remoteUser= the logged-in user (login name)
	* =$query= the query



---++ ObjectMethod *finish* <tt></tt>
Complete processing after the client's HTTP request has been responded
to. Right now this only entails one activity: calling TWiki::Client to
flushing the user's
session (if any) to disk.



---++ ObjectMethod *writeLog* <tt>($action,$webTopic,$extra,$user)</tt>
	* =$action= - what happened, e.g. view, save, rename
	* =$wbTopic= - what it happened to
	* =$extra= - extra info, such as minor flag
	* =$user= - user who did the saving (user object or string user name)
Write the log for an event to the logfile



---++ ObjectMethod *writeWarning* <tt>($text)</tt>

Prints date, time, and contents $text to $TWiki::cfg{WarningFileName}, typically
'warnings.txt'. Use for warnings and errors that may require admin
intervention. Use this for defensive programming warnings (e.g. assertions).



---++ ObjectMethod *writeDebug* <tt>($text)</tt>

Prints date, time, and contents of $text to $TWiki::cfg{DebugFileName}, typically
'debug.txt'.  Use for debugging messages.



---++ StaticMethod *applyPatternToIncludedText* <tt>($text,$pattern) -> $text</tt>

Apply a pattern on included text to extract a subset



---++ ObjectMethod *inlineAlert* <tt>($template,$def,...) -> $string</tt>
Format an error for inline inclusion in rendered output. The message string
is obtained from the template 'oops'.$template, and the DEF $def is
selected. The parameters (...) are used to populate %PARAM1%..%PARAMn%



---++ ObjectMethod *expandVariablesOnTopicCreation* <tt>($text,$user) -> $text</tt>
	* =$text= - text to expand
	* =$user= - reference to user object. This is the user expanded in e.g. %USERNAME. Optional, defaults to logged-in user.
Expand limited set of variables during topic creation. These are variables
expected in templates that must be statically expanded in new content.

The expanded variables are:
| =%<nop>DATE%= | Signature-format date |
| =%<nop>SERVERTIME%= | Server time |
| =%<nop>GMTIME%= | GM time |
| =%<nop>USERNAME%= | Base login name |
| =%<nop>WIKINAME%= | Wiki name |
| =%<nop>WIKIUSERNAME%= | Wiki name with prepended web |
| =%<nop>URLPARAM%= | Parameters to the current CGI query |
| =%<nop>NOP%= | No-op |



---++ StaticMethod *entityEncode* <tt>($text) -> $encodedText</tt>

Escape characters to HTML entities. Should handle unicode
characters.

HTML4.0 spec:
"Certain characters in HTML are reserved for use as markup and must be
escaped to appear literally. The "&lt;" character may be represented with
an <em>entity</em>, <strong class=html>&amp;lt;</strong>. Similarly, "&gt;"
is escaped as <strong class=html>&amp;gt;</strong>, and "&amp;" is escaped
as <strong class=html>&amp;amp;</strong>. If an attribute value contains a
double quotation mark and is delimited by double quotation marks, then the
quote should be escaped as <strong class=html>&amp;quot;</strong>.</p>

Other entities exist for special characters that cannot easily be entered
with some keyboards...

This method encodes &lt;, &gt;, &amp;, &quot; and any 8-bit characters
using numeric entities.



---++ StaticMethod *entityDecode* <tt>($encodedText) -> $text</tt>

Revrses the encoding from =entityEncode=. _Does not_ decode
named entities such as &amp;



---++ StaticMethod *urlEncode* <tt>($string) -> encodedstring</tt>

Encode by converting characters that are illegal in URLs to
their %NN equivalents. This method is used for encoding
strings that must be embedded _verbatim_ in URLs; it cannot
be applied to URLs themselves, as it escapes reserved
characters such as = and ?.

RFC 1738, Dec. '94:
<verbatim>>
...Only alphanumerics [0-9a-zA-Z], the special
characters $-_.+!*'(), and reserved characters used for their
reserved purposes may be used unencoded within a URL.
</verbatim>
Reserved characters are $&+,/:;=?@ - these are _also_ encoded by
this method.

SMELL: For non-ISO-8859-1 $TWiki::cfg{Site}{CharSet}, need to convert to
UTF-8 before URL encoding. This encoding only supports 8-bit
character codes.



---++ StaticMethod *urlDecode* <tt>($string) -> decodedstring</tt>

Reverses the encoding done in urlEncode.



---++ StaticMethod *nativeUrlEncode* <tt>($theStr,$doExtract) -> encodedstring</tt>

Perform URL encoding into native charset ($TWiki::cfg{Site}{CharSet}) - for use when
viewing attachments via browsers that generate UTF-8 URLs, on sites running
with non-UTF-8 (Native) character sets.  Aim is to prevent UTF-8 URL
encoding.  For mainframes, we assume that UTF-8 URLs will be translated
by the web server to an EBCDIC character set.

THIS METHOD SHOULD ONLY BE USED IF YOU ABSOLUTELY UNDERSTAND IT. It is
most likely you were looking for =urlEncode=.



---++ StaticMethod *isTrue* <tt>($value,$default) -> $boolean</tt>

Returns 1 if =$value= is true, and 0 otherwise. "true" means set to
something with a Perl true value, with the special cases that "off",
"false" and "no" (case insensitive) are forced to false. Leading and
trailing spaces in =$value= are ignored.

If the value is undef, then =$default= is returned. If =$default= is
not specified it is taken as 0.



---++ StaticMethod *spaceOutWikiWord* <tt>($word,$sep) -> $string</tt>

Spaces out a wiki word by inserting a string (default: one space) between each word component.
With parameter 'sep' any string may be used as separator between the word components; if 'sep' is undefined it defaults to a space.



---++ ObjectMethod *enterContext* <tt>($id,$val)</tt>

Add the context id $id into the set of active contexts. The $val
can be anything you like, but should always evaluate to boolean
TRUE.

An example of the use of contexts is in the use of tag
expansion. The commonTagsHandler in plugins is called every
time tags need to be expanded, and the context of that expansion
is signalled by the expanding module using a context id. So the
forms module adds the context id "form" before invoking common
tags expansion.

Contexts are not just useful for tag expansion; they are also
relevant when rendering.

Contexts are intended for use mainly by plugins. Core modules can
use $session->inContext( $id ) to determine if a context is active.



---++ ObjectMethod *leaveContext* <tt>($id)</tt>

Remove the context id $id from the set of active contexts.
(see =enterContext= for more information on contexts)



---++ ObjectMethod *inContext* <tt>($id)</tt>

Return the value for the given context id
(see =enterContext= for more information on contexts)



---++ StaticMethod *registerTagHandler* <tt>($tag,$fnref)</tt>

STATIC Add a tag handler to the function tag handlers.
	* =$tag= name of the tag e.g. MYTAG
	* =$fnref= Function to execute. Will be passed ($session, \%params, $web, $topic )



---++ ObjectMethod *handleCommonTags* <tt>($text,$web,$topic) -> $text</tt>
Processes %<nop>VARIABLE%, and %<nop>TOC% syntax; also includes
'commonTagsHandler' plugin hook.

Returns the text of the topic, after file inclusion, variable substitution,
table-of-contents generation, and any plugin changes from commonTagsHandler.



---++ StaticMethod *spamProof* <tt>($text) -> $text</tt>

Find and replace all explicit links (&lt;a etc) in $text and apply anti spam measures
to them. This method is designed to be called on text just about to be printed to the
browser, and needs to be very fast.

Links to URLs that are escaped by $cfg{AntiSpam}{Clean} are left untouched. All
other links have $cfg{AntiSpam}{Options} added.



---++ ObjectMethod *addToHEAD* <tt>($id,$html)</tt>
Add =$html= to the HEAD tag of the page currently being generated.

Note that TWiki variables may be used in the HEAD. They will be expanded
according to normal variable expansion rules.

The 'id' is used to ensure that multiple adds of the same block of HTML don't
result in it being added many times.



---++ StaticMethod *initialize* <tt>($pathInfo,$remoteUser,$topic,$url,$query) -> ($topicName,$webName,$scriptUrlPath,$userName,$dataDir)</tt>

Return value: ( $topicName, $webName, $TWiki::cfg{ScriptUrlPath}, $userName, $TWiki::cfg{DataDir} )

Static method to construct a new singleton session instance.
It creates a new TWiki and sets the Plugins $SESSION variable to
point to it, so that TWiki::Func methods will work.

This method is *DEPRECATED* but is maintained for script compatibility.

Note that $theUrl, if specified, must be identical to $query->url()



---++ StaticMethod *readFile* <tt>($filename) -> $text</tt>

Returns the entire contents of the given file, which can be specified in any
format acceptable to the Perl open() function. Fast, but inherently unsafe.

WARNING: Never, ever use this for accessing topics or attachments! Use the
Store API for that. This is for global control files only, and should be
used *only* if there is *absolutely no alternative*.


<!-- Do _not_ attempt to edit this topic; it is auto-generated. Please add comments/questions/remarks to the Dev topic instead. -->
