Recent Changes - Search:

Cookbook

PmWiki

pmwiki.org

ConditionalMarkupSamples

Summary: List of default and custom conditional markup definitions
Version: 2006-03-02
Status: Stable
Prerequisites: pmwiki-2.0
Maintainer:
Votes: 5

(:if key arguments:) samples and definitions

PmWiki comes with a number of default conditions already defined. See Conditional Markup and also below. Other conditions can be added by defining them in local/config.php or another local customisation file.

Conditionals not defined in PmWiki

To use any of the following conditionals you need to add the definition to your config.php or another local configuration file.

if action Not defined in PmWiki

Displays following text only if a given action is in progress.

  • Markup: (:if action ACTION:) (to check if ?action=ACTION is happening)
  • Definition: $Conditions['action'] = '\$GLOBALS["action"]==\$condparm';
  • Example: Add a 'View' item to Site.PageActions that only displays when we aren't currently performing that action.
(:if ( ! action browse ) :)
* %item class=browse accesskey='$[ak_view]'%[[{$FullName} | $[View] ]]
(:ifend:)

Note, even if there is no "if action" conditional, you can use "if equal {$Action} browse":

(:if equal "{$Action}" "browse":)
Current action is "browse".
(:else:)
Current action is not "browse", it is
"{$Action}".
(:if:)

Current action is "browse".

if attachexists Not defined in PmWiki

Displays following text only if the given file exists as an attachment. The single argument can be in the form "filename.ext", "directory/filename.ext" or "directory/pagename/filename.ext".

  • Markup: (:if attachexists filename.jpg:)
  • upload files in Group/ subfolders:
    (:if attachexists Group/myfile.doc:)
  • upload files in Group/PageName subfolders:
    (:if attachexists Group/PageName/myfile.doc:)
Definition:

$Conditions['attachexists'] = 'UploadFileExist($pagename, $condparm)';
function UploadFileExist($pagename, $attachname) {
global $UploadDir, $UploadPrefixFmt;

        $fname = explode("/", $attachname);
        $filename = end($fname);
        if(count($fname)==2) 
                $pagename = MakePageName($pagename, $fname[0]);
        if(count($fname)==3) 
                $pagename = MakePageName($pagename, $fname[0].".".$fname[1]);
        $uploaddir = FmtPageName("$UploadDir$UploadPrefixFmt", $pagename);
        $dirp = @opendir($uploaddir);
        if (!$dirp) return '';
        $filelist = array();
        while (($file=readdir($dirp)) !== false) {
                if ($file{0} == '.') continue;
                        $filelist[$file] = $file;
        }
        closedir($dirp);
        return in_array($filename, $filelist);

}

Alternative implementation

Displays following text only if the given file exists as an attachment. The single argument can be in the form "filename.ext", "Group/filename.ext" or "Group.Page/filename.ext".

The difference between this and the above is that it's independent of your uploads folder structure, as the part of the argument before the "/" is taken as a page name; if the attachment you're looking for would be found if you wrote Attach:filename.ext on that page, it'll exist with this function as well. The default is to use the current page.

Markup: (:if attachexists filename.jpg:) or (:if attachexists Page/filename.jpg:).
Definition:
$Conditions['attachexists'] = "AttachFileExists(\$pagename,\$condparm)";
function AttachFileExists( $pagename, $path ) {
	global $UploadFileFmt;
	if (preg_match('!^(.*)/([^/]+)$!', $path, $match)) {
		$pagename = MakePageName($pagename, $match[1]);
		$path = $match[2];
	}
	$upname = MakeUploadName($pagename,$path);
	$filepath = FmtPageName("$UploadFileFmt/$upname", $pagename);
	return file_exists($filepath);
}

Alternative Wildcard implementation

See Wildcard attach exists. --Petko March 21, 2011, at 11:11 AM

if author Not defined in PmWiki

a) Displays following text only if author = specified authorname.

  • Markup: (:if author AUTHORNAME:)
  • Definition: $Conditions['author'] = "\$GLOBALS['Author']==\$condparm";

b) Displays following text only, if author within specified list of authors.

  • Markup: (:if author AUTHORNAME:) (for a single author)
  • Markup: (:if author AUTHORNAME,AUTHORNAME,...:) (for an autorlist)
  • Definition: $Conditions['author'] = 'preg_match("/".$GLOBALS["Author"]."/",$condparm)';

This will only work if Author is "logged on" or has already put his name into the author-field while editing a page, i.e. the global variable $Author must be set. You can use only one of this author-condition-definition

if authgroup Not defined in PmWiki

Displays following text only if the viewer is currently authenticated in the given group. (ie. logged in, and a member of the given authorization group) via optional AuthUser authentication scheme.

  • Markup: (:if authgroup @groupname:) or even (if authgroup id:sally)
  • Definition: $Conditions['authgroup'] = '$GLOBALS["AuthList"][$condparm] > 0';

if authuser Not defined in PmWiki

Displays following text only if the viewer is currently logged in with username 'NAME' via the optional AuthUser authentication module. Do not confuse this with PmWiki's (:if authid:), which returns true if user is logged in, but does not check the user name!

  • Markup: (:if authuser NAME:)
  • Definition: $Conditions['authuser'] = '\$GLOBALS["AuthId"]==\$condparm';

if existswc Not defined in PmWiki

Displays following text only if a given wildcard matches at least one existing pagename.

  • Markup: (:if existswc name_with_wildcard:)
  • Definition: $Conditions['existswc'] = "(boolean)ListPages(FixGlob(\$condparm, '$1*.$2'))";

Note, recent PmWiki versions support wildcards in the exists conditional.

if fullname Not defined in PmWiki

Displays following text only if current fullname = specified fullname (GROUP.NAME).

  • Markup: (:if fullname GROUPNAME.PAGENAME:)
  • Definition: $Conditions['fullname'] = "FmtPageName('\$Group.\$Name',\$pagename)==\$condparm";

You can also use (:if equal "{*$FullName}" "GROUPNAME.PAGENAME":)

if handler Not defined in PmWiki

Displays following text only if a given action is defined. This differs from (:if action ACTION:) which only includes the text if the action is currently being executed. Note that this doesn't work for the diag and phpinfo actions, as they don't use the HandleActions dispatcher. Test for them with (:if enable EnableDiag:) instead.

  • Markup: (:if handler ACTION:) (to check if ACTION is a known action)
  • Definition: $Conditions['handler'] = '(boolean)@$GLOBALS["HandleActions"][$condparm]';
  • Example: Add a 'Del' item to Site.PageActions that only displays if the DeleteAction recipe is loaded.
(:if handler delete:)
* %rel=nofollow% [[{$Name}?action=delete| $[Del] ]]
(:ifend:)

if intext Not defined in PmWiki

Displays following text only if a given string exists in the page text. It does not look in markup directives of form (:...:). The optional second argument can be a page name, to check for presence of 'string' in that page, instead of the current page. Enclose any string which contain spaces in quotes: 'string with spaces'.

  • Markup: (:if intext 'string':) or (:if intext 'string' Group.PageName:)
Definition:
# add (:if intext 'string':) conditional
$Conditions['intext'] = 'StringInText( $pagename, $condparm )';
function StringInText( $pn, $arg ) {
	$arg = ParseArgs($arg);
	if($arg[''][1]) $pn = MakePageName($pn, $arg[''][1]);
	$page = RetrieveAuthPage($pn, 'read', true);
	$text = preg_replace('/\\(:(.*?):\\)/' ,"", $page['text']);
	if( strpos($text, $arg[''][0])!==false ) return true;
}

if link (or if category) Not defined in PmWiki

Displays following text only if a given link exists on the current page (i.e. if it is a "target link" on the current page). Useful to test whether the current page is in a specific category or not (use "Category.CategoryName" to test for [[!CategoryName]] markup).

  • Markup: (:if link Group.PageName:)
Definition:
# add (:if link 'Group.Pagename':) conditional
$Conditions['link'] = 'IsTarget( $pagename, $condparm )';
function IsTarget( $pn, $arg ) {
        $arg = ParseArgs($arg);
        $pn2 = MakePageName($pn, $arg[''][0]);
        $page = RetrieveAuthPage($pn, 'read', true);
        if (in_array($pn2, (explode(',',@$page['targets'])))) return true;
}

if matchstring Not defined in PmWiki

Displays following text only if a given string (best: in a pagetextvar) matches the given regular expression. Useful display sections e.g. in a pagelist-template according to some pagetextvar contents) KAL.

  • Markup: (:if matchstring '/regex/[modifier]' '$:pagetextvar':)
Definition:
# add (:if matchstring '/regex/' '$:pagetextvar':) conditional
$Conditions['matchstring'] = 'RegexCompareArgs($condparm) == 1';
function RegexCompareArgs($arg) 
{
  $arg = ParseArgs($arg);
  return preg_match(@$arg[''][0], @$arg[''][1]);
}

In a pagelist-template you can use:

 
(:if matchstring '/(test|cest|rest)/' 'test':)if matchstring '/(test|cest|rest)/' 'test' is TRUE

(:if matchstring '/(test|cest|rest)/' 'cest':)if matchstring '/(test|cest|rest)/' 'cest' is TRUE

(:if matchstring '/(test|cest|rest)/' 'rest':)if matchstring '/(test|cest|rest)/' 'rest' is TRUE

(:if matchstring '/(test|cest|rest)/' 'xest':)if matchstring '/(test|cest|rest)/' 'xest' should not be TRUE !

(:if matchstring '/(test|cest|rest)/i' 'REST':)if matchstring '/(test|cest|rest)/i' 'REST' is TRUE

if nopasswd Not defined in PmWiki

Displays following text only if the specified action for the specified page does not require users to be authorized.

  • Markup: (:if nopasswd ACTION [PAGENAME]:)
  • Examples:
    (:if nopasswd read:) This page is world-visible. (:ifend:)
    (:if nopasswd edit Main.HomePage:) Main.HomePage can be edited by anyone. (:ifend:)
  • Definition:
$Conditions['nopasswd'] = 'NoCache(CondNoPasswd($pagename, $condparm))';
function CondNoPasswd($pagename, $condparm) {
       global $HandleAuth;
        @list($level, $pn) = explode(' ', $condparm, 2);
        $pn = ($pn > '') ? MakePageName($pagename, $pn) : $pagename;
        if (@$HandleAuth[$level]>'') $level = $HandleAuth[$level];
        $page = RetrieveAuthPage($pn, $level, false, READPAGE_CURRENT);
        if (!$page || empty($page['=passwd'])) return FALSE;
        $ra = $page['=passwd']['read'];
        return (empty($ra) || ((count($ra) == 1) && (reset($ra) == '@nopass')));
}

if recipe-loaded Not defined in PmWiki

Displays following text only if a given cookbook recipe is in use. The argument should be the name the recipe uses of itself, not its filename. This is most probably the same as its page name on pmwiki.org, but may also be found in the file itself: look for a row of text near the beginning that looks like $RecipeInfo['RECIPENAME']['Version'] = 'xxxx';

  • Markup: (:if recipe-loaded name:)
  • Definition: $Conditions['recipe-loaded'] = "isset(\$GLOBALS['RecipeInfo'][\$condparm])";

if time 0600..1800 Not defined in PmWiki

This condition enables parts of the page to be displayed if the current time is in the selected range. To install it, add to config.php this code:

$Conditions['time'] = "CondTime(\$pagename, \$condparm)";
function CondTime($pagename, $condparm){
  list($start, $end) = explode('..', $condparm);
  if(!$start) $start = '0000';
  if(!$end)   $end = '2400';
  $now = strftime("%H%M");
  if($now>=$start && $now <= $end) return 1;
  return 0;
}
In a wiki page, you can use:
(:if time 0600..1159:) it is between 6 AM and noon
(:if time 1300..:) it is later than 1 PM
(:if time ..1900:) it is earlier than 7 PM

if numcomp Not defined in PmWiki

This condition allows you to do numeric comparisons. (See ConditionalExtensions for another approach.) (Note that some of these are already possible within pmwiki.)

(:if numcomp $:val > 1:)$:val is greater than 1
(:if numcomp $:val >= 1:)$:val is greater than or equal to 1
(:if numcomp $:val < 1:)$:val is less than 1
(:if numcomp $:val <= 1:)$:val is less than or equal to 1
(:if numcomp $:val = 1:)$:val is equal to 1 (== is a synonym)
(:if numcomp $:val != 1:)$:val is not equal to 1
$Conditions['numcomp'] = 'NumericCompareArgs($condparm) == 0';
function NumericCompareArgs($arg) {
  $arg = ParseArgs($arg);
  switch (@$arg[''][1]) {
     case '&gt;':
     case '>': return !(@$arg[''][0] > @$arg[''][2]);
        break;
     case '&gt;=':
     case '>=': return !(@$arg[''][0] >= @$arg[''][2]);
        break;
     case '&lt;':
     case '<': return !(@$arg[''][0] < @$arg[''][2]);
        break;
     case '&lt;=':
     case '<=': return !(@$arg[''][0] <= @$arg[''][2]);
        break;
     #case '&gt;':
     case '!=': return !(@$arg[''][0] != @$arg[''][2]);
        break;
     #case '&gt;':
     case '==':
     case '=': return !(@$arg[''][0] == @$arg[''][2]);
        break;
     default: 
        echo "NumericCompare: ERROR: Unknown operator ".@$arg[''][1]."<br>\n";
        return !(@$arg[''][0] == @$arg[''][2]);
  }
}

Conditionals already defined in PmWiki

if attachments Defined in PmWiki

Displays following text only if current page/group has any attachments.

  • Markup: (:if attachments:)
  • Definition: $Conditions['attachments'] = "AttachExist(\$pagename)";

if auth Defined in PmWiki

Displays following text only if user has authenticated during the current browser session

  • Markup: (:if auth ACTION:)
    • (:if auth read:)
    • (:if auth edit:)
    • (:if auth attr:)
    • (:if auth admin:)
  • Definition: $Conditions['auth'] = '@$GLOBALS["PCache"][$GLOBALS["pagename"]]["=auth"][trim($condparm)]';

if authid Defined in PmWiki

Displays following text only if user is authenticated, i.e. logged in with a valid user name and password via optional AuthUser authentication scheme. It does not check particular user names!

  • Markup: (:if authid:)
  • Definition: $Conditions['authid'] = '@$GLOBALS["AuthId"] > ""';

if date Defined in PmWiki

Displays following text only if current date matches date given or matches range given. Date or range given as 8 number datestring in form of yyyy-mm-dd or yyyymmdd. Range includes first and last date given.

  • Markup: (:if date DATE:) or (:if date DATE1..DATE2:)
  • Definition: $Conditions['date'] = "CondDate(\$condparm)";

defined as special function in scripts/stdmarkup.php.

if enabled Defined in PmWiki from pmwiki 2.1 beta1

Displays following text only, if VARIABLE is defined in config.php, or a skin's php script is set to 1 or some string value. If set to zero (0), or not set, the condition is not true and the following text will not display.

  • Markup: (:if enabled VARIABLE:)
  • Definition: $Conditions['enabled'] = '(boolean)@$GLOBALS[$condparm]';

One use for skins: in order for a skin to display something, which will be hidden in other skins, a variable can be set in the skin.php file to 1, and the 'if enabled' markup checks if the variable is set.

if equal Defined in PmWiki from version 2.1.beta15

Displays following text only if string1 equals string2

  • Markup: (:if equal STRING1 STRING2:)
  • Definition: $Conditions['equal'] = 'CompareArgs($condparm) == 0';
function CompareArgs($arg) {
$arg = ParseArgs($arg); return strcmp(@$arg[''][0], @$arg[''][1]);
}

if exists Defined in PmWiki

Displays following text only if SomeGroup.SomeName exists.

  • Markup: (:if exists SomeGroup.SomeName:)
  • Definition: $Conditions['exists'] = 'PageExists(MakePageName(\$pagename, \$condparm))';
  • You can use wildcards in the name argument, like if exists Main.*

if false Defined in PmWiki

This condition is always false, following text including markup will not be displayed.

  • Markup: (:if false:)
  • Definition: $Conditions['false'] = 'false';

if group Defined in PmWiki

Displays following text only if current group = specified groupname.

  • Markup: (:if group GROUPNAME:)
  • Definition: $Conditions['group'] = "FmtPageName('\$Group',\$pagename)==\$condparm";

if match Defined in PmWiki

Displays following text only if current page matches the regular expression.

  • Markup: (:if match REG_EXPRESSION:)
  • Definition: $Conditions['match'] = 'preg_match("!$condparm!",$pagename)';

if name Defined in PmWiki

Displays following text only if current name = specified pagename.

  • Markup: (:if name PAGENAME:)
  • Definition: $Conditions['name'] = "FmtPageName('\$Name',\$pagename)==\$condparm";

if ontrail Defined in PmWiki

Displays following text only if PAGENAME is on TRAILNAME page specified, see WikiTrails. PAGENAME is optional: if missing, it defaults to the current page.

  • Markup: (:if ontrail TRAILNAME PAGENAME:)
  • Example: (:if ontrail Main.Trips 2010.Italy:)

(defined in scripts/trails.php)

if true Defined in PmWiki

This condition is always true, following text including markup will always be displayed.

  • Markup: (:if true:)
  • Definition: $Conditions['true'] = 'true';

Note

Do not use conditional markup to hide security sensitive content. Although portions of a page can be suppressed, they cannot be protected. You will need to protect the entire page instead.

-- Instead, consider creating the security-sensitive content in a separate page and including it, while security that other page. BenWilson January 20, 2006, at 11:52 AM

If someone has read permission to the page and uses ?action=source, they'll see the entire source including the conditional markups.

  • So, then set the 'source' permissions to the 'edit' level. This will mean that source is only viewable to those who can edit the page, and read-only permissions are insufficient to view source. BenWilson April 12, 2007, at 08:37 AM

Please read http://thread.gmane.org/gmane.comp.web.wiki.pmwiki.user/30109/focus=30122 if you have problems with (:if action...:)
Luigi 13 September 2006

See also

Contributors

Comments

See discussion at ConditionalMarkupSamples-Talk


Category: Markup

User notes? : If you use, used or reviewed this recipe, you can add your name. These statistics appear in the Cookbook listings and will help newcomers browsing through the wiki.

Edit - History - Print - Recent Changes - Search
Page last modified on April 29, 2014, at 01:48 AM