Cookbook /
Functions
Summary: Brief description of some of PmWiki's internal functions available to cookbook recipe authors and custom markup developers
Categories: MarkupWriting PmWiki Developer
Discussion: Functions-Talk
This page briefly describes some of PmWiki's internal functions available to cookbook recipe authors and custom markup developers.
FmtPageName($fmt, $pagename)- Returns
$fmt, with$variableand$[internationalisation]substitutions performed, under the assumption that the current page is$pagename. See PmWiki.Variables for an (incomplete) list of available variables, PmWiki.Internationalizations for internationalisation. IsEnabled($var, $flag)- Returns the value of
$varif it is set; otherwise it returns$flag(i.e., a default value). Thus,IsEnabled($var, 0)returns false if$varis false or is not set, andIsEnabled($var, 1)returns true if$varis true or not set. - The purpose of the function is to provide an easy way to specify a default action without actually setting the configuration variable (because we may later need to know that the configuration variable was unset, as opposed to being programmatically set to a default).
- For example:
if (IsEnabled($cond, 0 )) { blah blah }, "blah blah" is executed if$condis explicitly set to a non-zero (true) value. This is in contrast to something like:if (IsEnabled($cond, 1)) { blah blah }, where "blah blah" is executed unless$condhas been explicitly set to a zero (false) value. Keep($value, $pool='')- Stores
$valuein a "Keep pool", and returns a "keep token" that's intended to be inserted into the wiki text (the keep token uniquely identifies$valuein the pool).
The string that is "kept" is stored in a global variable. The keep token replaces the string in the text, thus avoiding any other substitutions on that string. Later on the keep token must be replaced by the value in the global variable again. Search for
$KeepToken for examples of how this feature is used in pmwiki scripts.
The
$pool parameter, if set, specifies in which pool the kept data should be placed. Currently, these pools are defined:
'L' - the pool of kept link URLs. Data from this pool is restored back into the text before CSS styles are applied.
'P' - the pool of kept strings (quoted) within MarkupExpressions (scripts/markupexpr.php).
'' - the default pool. Anything in this pool will be restored back into the text after all other markup rules have been processed.
(A
Module writers can use
'B' ("block") pool for nestable markup is currently under consideration.)Module writers can use
Keep() to set up their own pools. Just make sure you use pool names that begin with the name of your recipe.
$LinkFunctions['...']($pagename, $imap, $path, $title, $txt, $fmt)- $LinkFunctions is an array of functions, indexed by URL "protocol strings" such as '
http:', 'mailto:', or 'ftp:'. These functions get called after all markup processing and()elimination in links like[[(Wiki)Sandbox]]; they are supposed to construct the final HTML from their parameters:- The name of the current page.$pagename$imap- The protocol string ('http:', 'mailto:', ...)$path- The rest of the URL after the protocol string (i.e. the full URL is$imap . $path).$title- Text for a title='...' attribute (usually for images).$txt- Text that should go between<a href=...>and</a>.$fmt- A format string to be applied to$txtviaFmtPageName($fmt, $txt).
Insert or replace entries in
$LinkFunctions to modify the way that links are displayed in HTML.
LinkPage($pagename, $imap, $path, $title, $txt, $fmt)- Creates a link to the page given by
$path,using the link text given by$txt. If$fmtisn't supplied, uses,$LinkPageExistsFmt, etc. as appropriate.$LinkPageCreateFmt ListPages($pat=NULL)- Provides an array of pages whose filenames match
$pati.e. to get a list of all pages on a site, use$allpages = ListPages();.$patis a pattern that will be matched byMatchPageNames(), for example'Group1.*,Group2.*,-*.RecentChanges,-*.GroupAttributes'.- found in
pmwiki.php- makes use of the
ls($pats=NULL)function, also inpmwiki.php - To get a list of pages within a specific group:
$pagesingroup = ListPages('/^Group\\./');or$pagesingroup = ListPages('Group.*'); - for a list of groups:
$listofgroups = array(); foreach(ListPages() as $pn) { $group = preg_replace('/\\..*/', '', $pn); $listofgroups[$group]++; } $listofgroups = array_keys($listofgroups); - See this message from 2007 (examples are now listed here)
- makes use of the
- compare to
MakePageList()
- found in
MakePageName($basepage, $string)- Converts string into a valid pagename (relative to $basepage).
MakePageList($pagename, $opt, $retpages = 1)- generates a list of pages using the specifications given by
$opt.- found in
/scripts/pagelist.php - compare to
ListPages()
- found in
MakeLink($pagename, $tgt, $txt, $suffix, $fmt)- Creates a link to
$tgt(url, intermap link, or page name) using$txtas the link text according to the string given by$fmt. If$txtisn't given then it uses$tgtas the link text after stripping anything in parentheses. If$fmtisn't given then it uses the default formatting for whatever kind of link$tgtis. For page links this means theand$LinkPageExistsFmtvariables, for intermap-style links it comes from either the$LinkPageCreateFmtarray or from$IMapLinkFmt. Inside of the formatting strings,$UrlLinkFmt$LinkUrlis replaced by the resolved url for the link,$LinkTextis replaced with the appropriate text, and$LinkAltis replaced by any "title" (alternate text) information associated with the link. Markup($name, $when, $pattern, $replacement)- Adds a new markup to the conversion table. Described in greater detail at PmWiki.CustomMarkup.
MarkupToHTML($pagename, $str)- Converts the string
$strwith PmWiki markup into the corresponding HTML code, assuming the current page is$pagename. MarkupToHTML()replaces\n\nsequences by<:vspace>first thing when text is passed to it. Subsequently<:vspace>is processed by the markup rules:
'
!vspace' removes <:vspace> after headings.
'
<vspace><p>' replaces <:vspace><p> with <p class='vspace'>
'
<vspace>' replaces <:vspace> with <div class='vspace'>
and finally
'
^<:' removes any remaining <:vspace>, mostly from restored [=escaped text=].
MatchPageNames($list, $patterns)- Returns a matched new list of page names.
$listis a pagename or array of pagenames, and$patternsis an array of patterns to be matched. If a pattern starts with a slash, the pagename must match the pattern, else if the pattern starts with an exclamation point, the pagename must not match the pattern, else the pagename must match the wildcard pattern. Mixed use of regex pattern and wildcards possible.
Note that individual elements of the
$patterns array can consist of comma-separated wildcard patterns. This (or regex with |) is the way to accomplish inclusive "or" conditions. Each element of the $patterns array is combined with the others by boolean "and". For inclusion this can be confusing since 2 elements of the array holding "GroupA.*" and then "GroupB.*" respectively will mean that no page is ever matched. GroupA.Page1 will match and so be included by the 1st element but will not match the 2nd element of the array and so will not be included. If you want all pages in both GroupA and GroupB then your array must include a SINGLE array element containing the string 'GroupA.*,GroupB.*'.
Note that
MatchPageNames() is case-INsensitive for all but regex (slash- or bang-surrounded).
PageTextVar($pagename, $ptv)- Returns the value of PageTextVariable
$ptvof page. Make sure$pagenamepoints to the page with the PTV.$pagename PageVar($pagename, $var, $pn)- Returns the contents of the page variable
$var, assuming that the current page is namedMakePageName($pagename, $pn). (The current page name influences some page variables.) - Here is another example using
PageVar()(I don't understand the code above at all!):
# Get the group and page name $pagename = ResolvePageName($pagename); $group = PageVar($pagename, '$Group'); $name = PageVar($pagename, '$Name');
ParseArgs($str)- Parses arguments.
$stris expected to be theargumentspart of a markup like(:blah arguments:); theParseArgsfunction findsname=valueandname:valuepairs (wherevaluemay be a quote-delimited string), as well as+value,-valueandvalueoptions.
The found items are returned as an array, indexed byname,'+','-', and'', respectively. Array values will be a string forname, arrays of strings otherwise.
See ParseArgs for a description, usage examples, and a demo. PQA($x)- "Prepare Quoted Arguments" This function parses html argument parameters and makes sure they're properly quoted and protected against cross-site scripting attacks. Given a string like
"border=1 cellspacing=0 onclick='destroy()'",PQA()converts it to"border='1' cellspacing='0'". For an example of use, one might define a form(:option...:)command that produces an html<option...>tag like this: Markup('option', 'inline', '/\\(:option (.*?):\\)/e', "Keep('<option '.PQA(PSS('$1')).' />')");PRR()- "PmWiki Redo Rules": This shortcut function simply increments the global
$RedoMarkupLinevariable, which tells the markup engine to begin reprocessing the current string (line) from the beginning of the markup translation table. This is commonly used when the replacement string might contain newlines, directives, or other sequences that would normally have been processed by markups earlier in the table.PRR($text)returns$text.
- Note: some processing happens outside of markup rules, particularly regarding HTML entities and vertical space. For example, if you insert
[[<<]]into a page as markup and callPRR()it may not be processed correctly.- You should process the newly inserted plain text with
PVSE()to convert special characters to entities and vertical space. - Reading a raw page (
ReadPage($somepagename))and inserting text can run into this problem.
- You should process the newly inserted plain text with
PSS($x)- "PmWiki Strip Slashes": When PHP's
preg_replacefunction is called with the/e(execute) modifier, it automatically adds backslash escapes in front of any double-quotes (") in the matched string. ThePSS()function removing the backslashes added by PHP in the match. Note that you don't need to callPSS()if the/emodifier isn't used on the pattern, or you know the matched component won't contain any double-quotes. PUE($x)- "PmWiki URL Encode": The specifications for uris/urls indicate that non-ASCII characters and spaces should be encoded (via '%' and two hex digits) when used in uris/urls. The
PUE()function performs this encoding on any string passed to it. (Yes, PHP provides aurl_encode()function that does this; buturl_encode()also encodes '%', '/', and other ASCII characters, which often isn't what we want.) PZZ($x)- "PmWiki Zero Zero": Sometimes a markup replacement will need to assign a value to a variable but not return anything to be displayed in the output. The
PZZ()function simply returns an empty string, to make it easier to perform variable assignments. For example, if a markup needs to set$XYZ=1but not produce any output, it can do
Markup('xyz', 'directives',
'/\\(:xyz:\\)/e',
"PZZ(\$GLOBALS['XYZ']=1)");
- and the
PZZ()function suppresses the '1' that would normally be returned from the assignment. SDV($var, $x)- "Set Default Value": Assign a value
$xto$varonly if$varhasn't already been set. This is normally used in cookbook recipes and extension scripts to set the values for variables that weren't set by a previous configuration file. SDVA($var, $x)- "Set Default Values in Array": This is the same as
SDV(), except$varand$xare arrays (hashes). The key/value pairs in$xare copied into$varonly for those keys which do not already exist in$var.SDVA($RecipeVarName, [ #$RecipeName usually works well 'RecipeFlag1'=>'defaultValue1', 'RecipeVar2'=>'defaultValue2', #etc ]);
XL($key)- "Translate": This function looks up the
$keyvalue in the translation dictionary stored in$XL, trying each language from the$XLLangsarray in turn until it finds a match or runs out of languages. If it finds a match, it returns the corresponding translation. If it fails to find a match, it returns the$keyvalue unchanged. Note that this function will skip over languages that have dictionaries in$XLbut no current entry in. This can be used to toggle dictionaries on and off for special purposes.$XLLangs
- NOTE: If you need to translate a phrase that has internationalization, you may be better off with
FmtPageName()- For example:
XL('<input value="$[Translated Phrase]">');will NOT work; -
XL('Translated Phrase');will work.
- For example:
XLPage($lang,$page)- "Translate Page": This function reads the page named in
$page, looking for lines of the form:If the page exists and contains at least one key/translation pair, then'some key' => 'translation text'$langis entered into the list of languages inand a dictionary for that language is stored in the$XLLangs$XLarray using the XLSDV function. If the page doesn't exist, or is empty, then this function has no effect. This function is also used to process user preferences from a Site.Preferences page, and can be used to implement a custom preference page (in this case for a fictitious recipe called 'zort') using a block of code like this:# load settings from our prefs page. XLPage('zort', 'Site.ZortPreferences'); # set our defaults, in case they weren't set on the page. XLSDV('zort', array ( 'power' => '8' , 'volume' => '11' )); # look up and save our prefs. global $ZortPower, $ZortVolume; $ZortPower = XL('power'); $ZortVolume = XL('volume'); # erase 'zort' from the language array # so we don't pollute any translations. array_shift($XLLangs); XLSDV($lang,$vals)- "Translation Set Default Values": This acts much as
SDVAdoes, but the key/value pairs in the$valsarray are inserted into$XLunder$langas a set of translations for that language. As with all of the Set Default functions, it doesn't change any entries that are already set.
See Also
PmWiki.Functions - PmWiki.Variables
Category: PmWiki Internals