<?php

$base_path = getcwd();
if (strpos($base_path, 'greenstone') === false)
{
  printError('Failed to determine base path...');
}

// The dokuwiki directory is always in the same place, relative to the PHP
// directory.
$dokuwiki_path = fileCat(array($base_path,'..','packages','dokuwiki'));
$dokuwiki_url = "../packages/dokuwiki";

// Similarly, the xml-source directory is also relative to the PHP directory.
$xml_source_path = fileCat(array($base_path, '..', 'manuals', 'xml-source'));

// Keep track of the id's we've seen to ensure when generating new ones they
//  are unique.
$seen_ids = array();

/**
 */
function fileCat($raw_parts)
{
  // 1. Expand out all of the parts first (as some may contain nested
  //    directories)
  $long_path = array();
  foreach ($raw_parts as $raw_part)
  {
    $long_path = array_merge($long_path, preg_split('/[\\\\\/]/', $raw_part));
  }
  // 2. Resolve any '..' in the path
  $path = array();
  foreach ($long_path as $part)
  {
    if ($part == '..')
    {
      array_pop($path);
    }
    else
    {
      $path[] = $part;
    }
  }
  return implode('/', $path);
}
/** fileCat() **/

/** Given a dokuwiki namespace use the wikis metadata to determine the file
 *  path to the most recently approved version of the page (which may not be
 *  the active page in the 'pages' directory, but an older version in the
 *  attic somewhere).
 *  @param $namespace  A namespace in the form part:part:part
 */
function getApprovedVersionPath($namespace)
{
  global $dokuwiki_path;
  $path = '#ERROR#';
  $dokuwiki_data_path = $dokuwiki_path . '/data';
  $namespace_path = str_replace(':','/',$namespace);
  // 1. Build the path to the pages metadata file
  $metadata_path = $dokuwiki_data_path . '/meta/' . $namespace_path . '.meta';
  if (file_exists($metadata_path))
  {
    // 2. Deserialize the file
    $page_metadata = unserialize(file_get_contents($metadata_path));

    // 3. Look up the 'current' versions timestamp
    $current_timestamp = $page_metadata['current']['date']['modified'];

    // 4. Now look up the timestamp of the most recently approved version
    $approved_timestamp = $current_timestamp; // default to the 'live' page
    // - note that if a page have never been approved the 'approval' array
    //   will not exist
    if (isset($page_metadata['current']['approval']) && !empty($page_metadata['current']['approval']))
    {
      $approved_timestamp = max(array_keys($page_metadata['current']['approval']));
    }

    // 5. If they are the same, we can simply return the path to the 'live'
    //    page in the 'pages' directory. Otherwise we construct a path to
    //    the 'approved' version, which lurks in the mirrored location in
    //    the 'attic' directory
    if ($current_timestamp == $approved_timestamp)
    {
      $path = $dokuwiki_data_path . '/pages/' . $namespace_path . '.txt';
    }
    else
    {
      $path = $dokuwiki_data_path . '/attic/' . $namespace_path . '.' . $approved_timestamp . '.txt';
    }
  }
  ///cho "[debug] Approved path: $path\n";
  return $path;
}
/** getApprovedVersionPath() **/

/** Given a text string generate a unique identifier.
 */
function generateID($text)
{
  global $seen_ids;
  $text = preg_replace('/(<!--.*?-->|\(.*?\))/', '', $text);
  $text = preg_replace('/\'s/', '', $text);
  $text = strtolower(trim($text));
  $poss_id = preg_replace('/\s+/', '_', $text);
  $id = $poss_id;
  $counter = 1;
  while (isset($seen_ids[$id]))
  {
    $id = $poss_id . '_' . $counter;
    $counter++;
  }
  $seen_ids[$id] = true;
  return $id;
}
/** generateID($text) **/

function mkAllDir($destination_dir)
{
  ///cho '<p> * Make all directories: ' . $destination_dir . '</p>' . "\n";
  $dirs_to_create = array();
  $dir = $destination_dir;
  while (!empty($dir) && !file_exists($dir))
  {
    ///cho 'Does not exist - create...<br/>';
    array_unshift($dirs_to_create, $dir);
    $dir = substr($dir, 0, strrpos($dir, '/'));
    ///cho 'Testing for the existance of: ' . $dir . '<br/>';
  }
  foreach ($dirs_to_create as $dir)
  {
    if (!file_exists($dir))
    {
      mkdir($dir, 0775);
    }
  }
  if (!file_exists($destination_dir))
  {
    printError('Failed to create directory: ' . $destination_dir);
  }
}

/**
 */
function parseCLIArguments()
{
  if (isset($_SERVER['argc']) && $_SERVER['argc'] > 0)
  {
    for ($i = 1; $i < $_SERVER['argc'] && !$unknown_argument; $i++)
    {
      if (preg_match('/^\-+(l|m)/i', $_SERVER['argv'][$i], $matches))
      {
        $i++;
        $_REQUEST[$matches[1]] = $_SERVER['argv'][$i];
      }
      else if (preg_match('/^\-+l/i', $_SERVER['argv'][$i]))
      {
        $i++;
        $_REQUEST['l'] = $_SERVER['argv'][$i];
      }
      else
      {
        return false;
      }
    }
  }
  return true;
}
/** parseCLIArguments() **/


/**
 */
function printError($message, $is_fatal=true)
{
  if ($is_fatal)
  {
    exit('<p><b>Error!</b> ' . $message . "</p>\n");
  }
  else
  {
    echo '<p><b>Error!</b> ' . $message . "</p>\n";
  }
}
/** printError($message) **/


/**
 */
function recursiveRemove($dir, $base_dir, $remove_this_dir=false)
{
  ///cho "<h2>recursiveRemove(\"$dir\", \"$base_dir\", $remove_this_dir)</h2>";
  // Ensure that base_dir is within_dir - safety first!
  if (strpos($dir, $base_dir) === false)
  {
    printError('Can\'t delete directory as is isn\'t within project');
  }
  if (is_dir($dir))
  {
    if ($dh = opendir($dir))
    {
      while (($file = readdir($dh)) !== false)
      {
	if (preg_match('/^\./', $file))
	{
	  // Skip dot files
	}
	else
	{
	  $path = fileCat(array($dir, $file));
	  if (is_dir($path))
	    {
	      recursiveRemove($path, $base_dir, true);
	    }
	  else
	    {
	      unlink($path);
	      if (file_exists($path))
		{
		  printError('Failed to delete file: ' . $path);
		}
	    }
	}
      }
      closedir($dh);
    }
    else
    {
      printError('Failed to open directory for reading: ' . $dir);
    }
    // Now that the directory is (hopefully) empty, we can delete it if
    // required to
    if ($remove_this_dir)
    {
      rmdir($dir);
      if (file_exists($dir))
      {
        printError('Failed to remove directory: ' . $dir);
      }
    }
  }
  else
  {
    printError('Can\'t recursive delete - not a directory: ' . $dir);
  }
}
/** recursiveRemove() **/

?>