<?php // vim: ts=4 sw=4 sts=4 fdm=marker ai noet:
// $Id: index.php,v 1.14 2004/12/01 19:24:06 ishii Exp $

define('_AM_WIKI_CONFIG_FILE', '../cache/config.php');
define('_AM_WIKI_READ_AUTH',   '../cache/readauth.php');
define('_AM_WIKI_EDIT_AUTH',   '../cache/editauth.php');
define('_AM_WIKI_ADMIN_PASS',  '../cache/adminpass.php');
define('_AM_WIKI_CSS_FILE',    '../cache/css.css');
define('_WIKI_AM_TEXT_SIZE',   '50');
define('BWIKI_ADMIN',          TRUE);
define('DATA_HOME', '../');

include_once('admin_header.php');
include_once(XOOPS_ROOT_PATH.'/class/module.errorhandler.php');

$bwikidir = XOOPS_ROOT_PATH."/modules/".$xoopsModule->dirname();

define('S_VERSION', ''); // dummy
require_once('../pukiwiki.ini.php');

$cache_files = array(
	_AM_WIKI_CONFIG_FILE,
	_AM_WIKI_READ_AUTH,
	_AM_WIKI_EDIT_AUTH,
);

foreach($cache_files as $c)
{
	if(file_exists($c) && is_readable($c))
	{
		require_once($c);
	}
}

// {{{ changePermit()

// パーミッションの変更。
function changePermit()
{
	global $HTTP_POST_VARS;
	global $bwikidir;

	$_target_dir = array(
		"attach",
		"backup",
		"cache",
		"counter",
		"diff",
		"wiki",
		"wiki.en",
		"trackback"
	);

	// PHPの仕様で``.''(ピリオド)をポストすると``_''に変換されてしまうようだ。
	if( isset($HTTP_POST_VARS['wiki_en']) )
	{
		$HTTP_POST_VARS['wiki.en'] = 1;
	}

	foreach($_target_dir as $_td)
	{
		if(isset($HTTP_POST_VARS[$_td]) && $HTTP_POST_VARS[$_td] == 1)
		{
			if ($dir = @opendir("$bwikidir/$_td"))
			{
				while($file = readdir($dir))
				{
					if($file == ".." || $file == ".") continue;
					@chmod(trim("$bwikidir/$_td/$file"), 0666);
				}
				closedir($dir);
			}
		}
	}

	redirect_header("index.php",1,_AM_DBUPDATED);
	exit();
}

// }}}
// {{{ writeConfig()

// 設定の書き込み。
function writeConfig()
{
	global $HTTP_POST_VARS;

	extract($HTTP_POST_VARS);

	// 基本設定書き込み。
	$filename = _AM_WIKI_CONFIG_FILE;
	$file = fopen($filename, "w");

	$content = "";
	$content .= "<?php";
	$content .= "
	\$defaultpage = '$wiki_defaultpage';
	\$modifier = '$wiki_modifier';
	\$modifierlink = '$wiki_modifierlink';
	\$function_freeze = $wiki_function_freeze;
	\$read_auth = $wiki_read_auth;
	\$edit_auth = $wiki_edit_auth;
	\$auth_method_type = '$wiki_auth_method_type';
	\$trackback = $wiki_trackback;
	\$referer = $wiki_referer;
	\$nowikiname = $wiki_nowikiname;
	\$notify = $wiki_notify;
	\$notify_to = '$wiki_notify_to';
	\$notify_from = '$wiki_notify_from';
	\$notify_header = \"From: $wiki_notify_from\\r\\nX-Mailer: B-Wiki/\".S_VERSION.\" PHP/\".phpversion();\n\n";

	if( ! empty( $permit_group ) )
	{
		foreach($permit_group as $p)
		{
			$content .= "\$editable_group_id[] = $p;\n";
		}
	}

	$content .= "\n?>";

	fwrite($file, $content);
	fclose($file);

	// adminパス書き込み。
	if($wiki_adminpass != "")
	{
		$wiki_adminpass = md5($wiki_adminpass);
		$filename = _AM_WIKI_ADMIN_PASS;
		$file = fopen($filename, "w");
		$content = "<?php\n\$adminpass = '$wiki_adminpass';\n?>";
		fwrite($file, $content);
		fclose($file);
	}

	// css書き込み。
	$filename = _AM_WIKI_CSS_FILE;
	$file = fopen($filename, "w");
	fwrite($file, $wiki_css);
	fclose($file);

	redirect_header("index.php",1,_AM_DBUPDATED);
	exit();
}

// }}}
// {{{ checkPermit()

// パーミッションのチェック。
function checkPermit()
{
	global $bwikidir;
	global $defaultpage;

	$wiki_error = array();

	$target_list = array();

	$_check_list = array(
		"/attach/",
		"/backup/",
		"/cache/",
		"/counter/",
		"/diff/",
		"/wiki/",
		"/wiki.en/",
		"/trackback/"
	);

	foreach($_check_list as $dir)
	{
		$target_list[] = "{$bwikidir}{$dir}";
		if( $d = opendir("{$bwikidir}{$dir}") )
		{
			while( $file = readdir($d) )
			{
				if( $file == '..' ||
					$file == '.' ||
					$file == '.htaccess' ||
					$file == 'index.html' ||
					$file == '.cvsignore' ||
					$file == 'CVS' ) continue;
				$target_list[] = "{$bwikidir}{$dir}{$file}";
			}
			closedir($d);
		}
	}

	$_alert_icon = "<img src='../image/alert.gif'>&nbsp;";
	foreach($target_list as $target)
	{
		if( ! is_writable($target) )
		{
			$wiki_error[] = preg_replace("/^.*modules\/bwiki\/(.*)$/", "\\1", $target);
		}
	}

	if( count($wiki_error) > 0 ){
		printf("<b>%s %s</b><br />", $_alert_icon, _AM_WIKI_ERROR01);
		foreach($wiki_error as $target)
		{
			printf("%s<br />", $target);
		}
		echo "<br />";
	}

	// defaultpageが空かチェック。
	if( empty($defaultpage) )
	{
		echo "<h3><font color='red'>undefined default page.</font></h3><br />";
	}
}

// }}}
// {{{ displayForm()

// 基本設定フォームの表示。
function displayForm()
{
	global $xoopsDB;
	global $defaultpage, $modifier, $modifierlink;
	global $adminpass, $function_freeze, $editable_group_id;
	global $auth_method_type, $read_auth, $read_auth_pages;
	global $edit_auth, $edit_auth_pages;
	global $trackback, $referer, $nowikiname;
	global $notify, $notify_to, $notify_from;

	xoops_cp_header();
	checkPermit();

	// DBからグループ一覧を取得。
	$sql = "select * from ".$xoopsDB->prefix('groups');
	$result = $xoopsDB->query($sql);
	while ( $gid_row = $xoopsDB->fetchArray($result) )
	{
		$gids[] = $gid_row;
	}

	// どのグループに権限を付与したかチェック。
	$editable_group_html = "";
	foreach($gids as $_gid)
	{
		$ckd = "";
		if(isset($editable_group_id) && is_array($editable_group_id))
		{
			foreach($editable_group_id as $_egid)
			{
				if($_egid == $_gid['groupid'])
				{
					$ckd = " checked";
				}
			}
		}
		$editable_group_html .= 
			"<input type='checkbox' name='permit_group[]' value='{$_gid['groupid']}'$ckd>{$_gid['name']}<br />\n";
	}

	// radioのチェックされた方にcheckedを付ける。
	$checked_list = array(
		'trackback',
		'referer',
		'nowikiname',
		'notify',
		'function_freeze',
		'read_auth',
		'edit_auth'
	);

	foreach($checked_list as $key){
		$enable  = "_{$key}_enable";
		$disable = "_{$key}_disable";
		$$enable=$$disable='';

		if($$key)
		{
			$$enable = ' checked';
		}
		else
		{
			$$disable = ' checked';
		}
	}

	$_notify_to = htmlspecialchars($notify_to);
	$_notify_from = htmlspecialchars($notify_from);

	// css読み込み。
	$wiki_css = '';
	if(file_exists(_AM_WIKI_CSS_FILE))
	{
		$_wiki_css_file = @file(_AM_WIKI_CSS_FILE);
		$wiki_css = htmlspecialchars(implode('', $_wiki_css_file));
	}

	// 認証方式種別
	$_amt_page=$_amt_contents='';
	if($auth_method_type == 'pagename')
	{
		$_amt_page = ' selected';
	} else
	{
		$_amt_contents = ' selected';
	}

	// 画面表示。
	include_once("admin.skin.php");

	xoops_cp_footer();
}

// }}}
// {{{ writeReadAuth()

function writeReadAuth()
{
	global $HTTP_POST_VARS;

	extract($HTTP_POST_VARS);
	$result = '';

	foreach($ra as $r)
	{
		if($r['page'] == '' || !isset($r['group']) || count($r['group']) == 0)
		{
			continue;
		}
		$r['page'] = stripslashes($r['page']);
		$r['page'] = preg_replace("/\x27/", "\\\x27", $r['page']);

		$result .= "'{$r['page']}' => '".implode(",", $r['group'])."',\n";
	}

	$ret = "<?php\n\$read_auth_pages = array(\n{$result});\n";
	if($result == '')
	{
		$ret .= "\$read_auth = 0;\n";
	}

	$ret .= "?>";

	$filename = _AM_WIKI_READ_AUTH;
	$file = fopen($filename, "w");
	fwrite($file, $ret);
	fclose($file);

	redirect_header("index.php",1,_AM_DBUPDATED);
	exit();
}

// }}}
// {{{ writeEditAuth()

function writeEditAuth()
{
	global $HTTP_POST_VARS;

	extract($HTTP_POST_VARS);
	$result = '';

	foreach($ea as $e)
	{
		if($e['page'] == '' || !isset($e['group']) || count($e['group']) == 0)
		{
			continue;
		}
		$e['page'] = stripslashes($e['page']);
		$e['page'] = preg_replace("/\x27/", "\\\x27", $e['page']);

		$result .= "'{$e['page']}' => '".implode(",", $e['group'])."',\n";
	}

	$ret = "<?php\n\$edit_auth_pages = array(\n{$result});\n";
	if($result == '')
	{
		$ret .= "\$edit_auth = 0;\n";
	}

	$ret .= "?>";

	$filename = _AM_WIKI_EDIT_AUTH;
	$file = fopen($filename, "w");
	fwrite($file, $ret);
	fclose($file);

	redirect_header("index.php",1,_AM_DBUPDATED);
	exit();
}

// }}}
// {{{ main()

if(0){
echo "<pre>";
print_r($HTTP_POST_VARS);
echo "</pre>";
}
clearstatcache();
if($_SERVER["REQUEST_METHOD"] == "GET")
{
	// フォームの表示。
	displayForm();
}
else
{
	switch($HTTP_POST_VARS['wiki_admin_mode']){
		case "change_config":
			writeConfig();
			break;
		case "change_permit":
			changePermit();
			break;
		case "read_auth":
			writeReadAuth();
			break;
		case "edit_auth":
			writeEditAuth();
			break;
		default:
			break;
	}
}

// }}}

?>
