#!/usr/bin/php4 -q
<?php

/*************************************************************
 
This script will let you create a static copy of a bamboo site
as rendered html. This copy is then completely stand alone and 
does not need bamboo to be viewed or browsed.

USAGE:
   staticcopy --src /var/www/mysite --dest /var/www/mycopy

CAVEATS:
   - the site can't have multiple decorators
   - the decorator must include the stylesheet in each page
     statically if $robot is true (use stylesheet() function).
   - decorator images must be in the decorator folder, not
     in a subfolder. 

NOTES: 
  we only need to include the stylesheet in each page
  because of possible images in the stylesheet and our need
  to use all relative urls. if it doesn't have any images
  in the stylesheet, we might as well  use a common style.css
  for all pages.
  
*************************************************************/

$base = dirname(dirname(__FILE__));

require_once("$base/debug.php");
require_once("$base/Lang.php");
require_once("$base/Page.php");
require_once("$base/PageStore.php");
require_once("$base/UserStore.php");
require_once("$base/Properties.php");
require_once("$base/Auth.php");
require_once("$base/Renderer.php");
require_once("$base/PageNav.php");
require_once("$base/Search.php");
require_once("$base/HttpUtil.php");
require_once("$base/Lang.php");

ini_set('error_log', NULL);

### globals for renderstatic command line arguments
##

$src = '';
$dest = '';
$docroot = '';

process_args();

$_SERVER['DOCUMENT_ROOT']=$src;

if (!is_dir($dest)) 
	die("destination directory $dest does not exist (use --dest)\n");

if (!is_dir($src)) 
	die("source directory $src does not exist (use --src)\n");

if (!is_file("$src/b.site")) 
	die("can't find b.site file in $src\n");
	
##
### end command line arguments

$prop     = new Properties("$src/b.site");
$root 	  = $prop->getGlobal('siteroot');
$docroot  = $prop->getGlobal('sitedocroot');
$robot    = true;
$static   = true;

Lang::init( $prop->getGlobal('default-lang'), split(' ',$prop->getGlobal('languages')) );
Lang::set( isset($GLOBALS['language']) ? $GLOBALS['language'] : 'en' );

$ps       = PageStoreFactory::create($prop->getGlobal('pagebackend'),$prop);
$page     = $ps->getPage('/');
$renderer = new Renderer($prop);
$nav      = new PageNav($prop);
$search   = new Search(IndexFactory::create($prop->getGlobal('indexbackend')));

$action	  = 'view';

### the style page

// copy images from the decorator
$decor = $renderer->getDecorator();
$decordir = dirname($decor->template);
$handle = opendir($decordir);
while ($filename = readdir($handle)) { 
	$suffix = preg_replace("/^.*(\....)$/i",'$1',$filename);
	if ($suffix == '.jpg' || $suffix == '.gif' || $suffix == '.png') {
		if (copy("$decordir/$filename", "$dest/$filename"))
			d::log("copied $dest/$filename");
		else
			d::log("FAILED to copy $dest/$filename");
	}
}
closedir($handle);

/*
// copy the stylesheet
ob_start();
  $renderer->style($page);
  $style = &ob_get_contents();
ob_end_clean();
$fp = fopen("$dest/style.css", 'w');
fputs($fp, $style);
fclose($fp);
d::log("wrote $dest/style.css");
*/

### walk the page tree

render_site($page);

return;

### functions

function render_site($curpage, $depth=0) {
	global $renderer, $dest, $decoratorurl;

	if(isset($GLOBALS['language']))
		$langs = array($GLOBALS['language']);
	else	
		$langs = $curpage->availableContent();
	
	if (count($langs)==0) $langs=array('en');
	
	$path = "{$dest}$curpage->path";
	mkdir("$path");
	foreach($langs as $lang) {
		Lang::set($lang);
		$curpage->content = null; // clear out the content;
		ob_start();
			$renderer->renderPage($curpage);
			$data = &ob_get_contents();
		ob_end_clean();
		
		$data = preg_replace(
			array(
				"'$decoratorurl'm",
				'#(href|src)="(.*?)"#ime',
				'#url\((.*?)\)#ime',
			),
			array(
				'',
				'"$1=\"" . converturl("$2","' . $curpage->path . '") . "\""',
				'"url(" . converturl("$1","' . $curpage->path . '") . ")"'
			),
			$data
		);
	
		if (count($langs) == 1)
			$filename = "$path/index.html";
		else
			$filename = "$path/index.html.$lang";
		$fp = fopen("$filename", 'w');
		fputs($fp, $data);
		fclose($fp);
		d::log("wrote $filename");
	}
			
	$files = $curpage->attachments();
	if (count($files)) {
		foreach($files as $filedata) {
			$ok = copy($filedata['file'],"$path/$filedata[name]");
			if ($ok) d::log("copied $path/$filedata[name]");
			else     d::log("FAILED to copied $path/$filedata[name]");
		}
	}

	
	$children = $curpage->children();
	foreach ($children as $child) {
		render_site($child, $depth+1);
	}
	return;
}

function converturl($url, $path) {
	global $search;

	if (!strlen($url)) {
		return '';
	}
	elseif ($url{0} == '/') {
		// converts an absoluteurl to a relative one.
		$path = preg_replace('/\/$/','',$path);
		$depth = substr_count($path, "/");
		return str_repeat("../",$depth) . substr($url,1);
	}
	elseif ($url{0} == '#' || strpos($url,"://") !== FALSE ) {
		return $url;
	}
	else {
		$match = $search->findClosestPage("$path/$url");
		if ($match) {
			return converturl($match, $path);
		}
		else {
			return $url;
		}
	}
}

function process_args() {
	$argv = &$GLOBALS['argv'];
	$argc = &$GLOBALS['argc'];
      
	for($i=1;$i<=$argc;$i++) {
		switch($argv[$i]) {
			case '--language': $GLOBALS['language'] = $argv[$i+1]; break;
			case '--src': $GLOBALS['src'] = $argv[$i+1]; break;
			case '--dest': $GLOBALS['dest'] = $argv[$i+1]; break;
			case '--docroot': $GLOBALS['docroot'] = $argv[$i+1]; break;
		}
	}
}
                        
  
return;
?>
