[pmwiki-users] Getting a random page name inside a cookbook recipe

Petko Yotov 5ko at 5ko.fr
Wed Oct 21 19:25:22 CDT 2009

On Tuesday 20 October 2009 17:29:49 Maxim wrote:
> Within a cookbook recipe I want to select a page at random from a
> particular group. The solution I came up with is:
> $pagename = trim(strip_tags(MarkupToHTML('', '(:pagelist fmt=#simple
> list=normal group=Sprites order=random count=1:)')));
> This has the advantage of not needing any dedicated pagelist format.
> However, I'm a little worried that it's doing more than is necessary.
> Is there a nicer way?

Hello. First, you probably shouldn't set a variable $pagename = ... outside of 
a function, because this may interfere with what PmWiki considers the 
currently browsed page. (Just use another variable like $randompage = ...)

There is a much faster and easier (for your server) way to do it, but because 
when config.php is included, not all variables are defined yet, the code is 

PmWiki can list pages with the ListPages($patterns) function, where $patterns 
are regular expressions for pages to be included or excluded.

  global $SearchPatterns; # only if inside a function

  # this may not be required, if pagelist.php has been loaded
  SDVA($SearchPatterns['normal'], array(
  'recent' => '!\.(All)?Recent(Changes|Uploads)$!',
  'group' => '!\.Group(Print)?(Header|Footer|Attributes)$!',
  'self' => str_replace('.', '\\.', "!^$pagename$!")));

  # we add a custom pattern like the list=normal...
  $SearchPatterns['MyList'] = $SearchPatterns['normal'];
  # ... but pages only from the Sprites wikigroup
  $SearchPatterns['MyList']['Sprites'] = '/^Sprites\\./';

  # get all pages
  $mypages = ListPages( $SearchPatterns['MyList'] );

  # randomize them and get the first one
  $randompage = $mypages[0];

  # or alternatively, no shuffle:
  $randompage = $mypages[ array_rand($mypages) ];

Now, if this is inside a Markup() function, it could be shorter:

  global $SearchPatterns;
  $mypages = ListPages( array_merge(
    $SearchPatterns['normal'], array('Sprites'=>'/^Sprites\\./')));
  $randompage = $mypages[ array_rand($mypages) ];


More information about the pmwiki-users mailing list