00864: Made *actual* renamer function to rename wiki pages

Summary: Made *actual* renamer function to rename wiki pages
Created: 2007-01-14 14:55
Status: Open
Category: Cookbook
From: Azbok?
Priority: 3
Version: 2.2.0 beta 16

Description: I got the original code from: http://pmwiki.org/wiki/Cookbook/RenamePage

I commented out the original HandlePostRename() function in rename.php and made my own. Ideally the features from the original one should be combined with this one, but I didn't figure out all the regex stuff in the original one so I didn't include it in here.

Note: I have hardcoded the wiki link syntax and this page rename ONLY works with group links such as "Group/Page". Ideally this should be updated to work with all wiki links. Similar to my other update (http://pmwiki.org/wiki/PITS/00863) of removing deleted file entries in the pageindex file, I don't know if this is the proper way to do it, but it works for me.

If you have the update I just mentioned above, this works nicely and it's as if you created the page with the new name to begin with (as far as I can figure anyway).

I hope you guys can make use of this

function HandlePostRename($pagename) {

  global $WikiDir;

  $newpagename = MakePageName($pagename, stripmagic($_POST['group'].'.'.$_POST['renametext']));

  if (PageExists($newpagename)) {
    Abort("'$newpagename' already exists");

  # Get list backlinks to given page plus page index file
  $backlinks = PageIndexGrep($pagename, false);

  # Make sure backlinks don't include the new name
  $backlinks = array_diff($backlinks, (array)$newpagename);

  # Create search regex for old link
  $linkname_regex = preg_replace('/\./', '\/', $pagename);
  $pagename_regex = preg_replace('/\./', '\.', $pagename);

  # Create replacement text for new link
  $newlinkname = preg_replace('/\./', '/', $newpagename);

  # Search and replace all occurances of the oldlinkname with the newlinkname
  foreach ($backlinks as $backlink) {
    $page = RetrieveAuthPage($backlink, 'edit');
    $page['text'] = preg_replace("/$linkname_regex/", $newlinkname, $page['text']);
    $page['targets'] = preg_replace("/$pagename_regex/", $newpagename, $page['targets']);

  # Do the actual file renaming
  $oldqualifiedfile = $WikiDir->pagefile($pagename);
  $newqualifiedfile = $WikiDir->pagefile($newpagename);
  rename($oldqualifiedfile, $newqualifiedfile);

  # Change the internal name property to the new name by just writing the page
  $page = ReadPage($newpagename);

  # Update the index for all pages that have changed
  # Keep the old page name in the backlinks to remove it from the pageindex file
  $backlinks[] = $newpagename;