<?php if (MING != "merciless") require ('index.php'); else {




/********************************************************************/
/* This is the Page Editor magic file, for online administration of */
/* Planet Mongo.                                                    */
/********************************************************************/
$file = new FileWrapper();
$file->title = 'Page Editor';
$file->directory = $content_directory;
$file->dont_list = TRUE;
$file->is_capable = TRUE;
$file->file_name = 'page_editor';
$file->type = POWER_HTML;

main_add_magic_file ($file );

function magicfile_page_editor () {
	global $editor_enabled;
	$return_value =
	'
<h1>Page Editor</h1>
<!--[[ user : protect : security_level <= 0 ]]-->';

	if ($editor_enabled == FALSE) return $return_value . '
	<h2>Although you have logged on correctly, the Page Editor is disabled by default.</h2>
<p><strong>Note:</strong> The page editor is disabled by default, for security reasons. To enable it, edit "$editor_enabled" to equal TRUE, in the config/config.php file. But first, change the administrator\'s password to something other than the default. You can change the administrator\'s password by editing the config/user.php file.</p>
<p>You see, if this were not disabled by default, an attacker could take advantage of any new Planet Mongo installation, as long as the attacker gets to that installation before the Planet Mongo administrator changes the password of the admin account in the config/users.php file.</p>
<p>Once $editor_enabled has been set to equal TRUE, then this message will go away and be replaced with Planet Mongo\'s web-based page editor.</p>';
	else return $return_value.'
<!--[[ editor : directory_list ]]-->
<hr style="border: 6px solid #aaa; margin: 10px;" />
<!--[[ editor : page_list ]]-->
<hr style="border: 6px solid #aaa; margin: 10px;" />
<!--[[ editor : page_commit ]]-->
';
}

/************************************************************/






$editor_directory_list = Array(new FileWrapper('content'), new FileWrapper('news'));

$editor_html_filetype_drop_down = '';
$editor_html_link_to_content_file = '
<?php
	if(\'%directory%\' == \''.$content_directory.'\'){
		$url = \'index.php?'.$content_request_get_variable.'=%file_name_url%\';
		outblurt("URL to Page: <a href=\"$url\">$url</a>", POWER_HTML);
	} else outblurt(\'This file does not appear to be a content file.\', POWER_HTML);
?>
';
$editor_html_action_rename = '<h2>Currently renaming / dating %title%...</h2>
<form action="#" class="form-page-editor" method="post"  style="display: inline;">
<input type="hidden" name="action" value="rename2" />
<input type="hidden" name="target" value="%file_name%" />
<input type="hidden" name="path" value="%path%" />
<ol>
	<li>Original Title: <strong>%title%</strong></li>
	<li>Original Time and Date: <strong>%date_formatted%</strong> </li>
	<li>Original File Type: <strong>%type_extension%</strong> </li>
	<li>Original Raw File Name: <code>%file_name%</code></li>
	<li>'.$editor_html_link_to_content_file.'</li>
</ol>
<hr style="border: 2px solid #999" />
<ol>
	<li>New Title: <input type="text" name="new_title" value="%title%"/> <br />
		<label for="autoformat-title"><input id="autoformat-title" name="autoformat_title" type="checkbox" checked="true" />Auto format title</label></li>
	<li>New Date:
		<ul>
			<li><label for="date-opt1"><input id="date-opt1" type="radio" name="value-date-type" value="today" 
				 />Today (<em> <?php global $main_date_format; outblurt(date($main_date_format), POWER_BB); ?>)</em></label></li>
			<li><label for="date-opt2"><input id="date-opt2" type="radio" name="value-date-type" value="human" 
			checked="true" />YYYY/MM/DD, HH:MM <em>(24 hour format)</em>:</label> &nbsp;  &nbsp; 
				<input type="text" name="date-year" value="%dY%" size="4"/>&mdash;<input type="text" name="date-month" value="%dm%" size="2"/>&mdash;
				<input type="text" name="date-day" value="%dd%" size="2"/> &nbsp; , &nbsp; 
				<input type="text" name="date-hour" value="%dH%" size="2"/>:<input type="text" name="date-minutes" value="%di%" size="2"/>
			</li>
			<li><label for="date-opt3"><input id="date-opt3" type="radio" name="value-date-type" value="unix" />Unix timestamp: </label>
			<input type="text" name="date-unix" value="%date%"/></li>
			<li><label for="date-opt4"><input id="date-opt4" type="radio" name="value-date-type" value="none" />No date</label></li>
		</ul>
	</li>
	<li>New File Type:
	<select id="new-file-type" name="new_type">
		<?php
			global $editor_allowed_filetypes;
			foreach ($editor_allowed_filetypes as $type) {
				$selected = $type == strtolower(\'%type_extension%\') ? \' selected="true"\' : \' \';
				outblurt("<option value=\"$type\" $selected>$type</option>", POWER_HTML);
			}
		?>
	</select></li><!--TODO: make these work! 
	<li>Other settings...
		<ul>
			<li><label for="fl1"><input id="fl1" name="is_index" type="checkbox" 
				checked="true" />Serve this page first</label></li>
			<li><label for="fl2"><input id="fl2" name="is_capable" type="checkbox" 
				checked="false" />Capable of using "Planet Mongo commands"</label></li>
		</ul>
	</li>-->		
</ol>
<input type="submit" style="display: inline; margin-right: 10px; padding: 3px" value="Save New Name" />
</form>

<form action="#" class="form-page-editor" method="post" style="display: inline;">
<input type="hidden" name="path" value="%path%" />
<input style="display: inline; margin-right: 10px; padding: 3px" type="submit" value="Cancel" />
</form>
';


$editor_html_action_delete = '<h2>Are you sure you want to delete %path%/%file_name%?</h2>
<p>Page Title: <strong>%title%</strong></p>
<p>Time and date for file: <strong>%date_formatted%</strong> </p>

<form action="#" class="form-page-editor" method="post"  style="display: inline;">
<input type="hidden" name="action" value="delete2" />
<input type="hidden" name="target" value="%file_name%" />
<input type="hidden" name="path" value="%path%" />
<input type="submit" style="display: inline; margin-right: 10px; padding: 3px" value="Delete" />
</form>

<!-- CANCEL BUTTON -->
<form action="#" class="form-page-editor" method="post" style="display: inline;">
<input type="hidden" name="path" value="%path%" />
<input style="display: inline; margin-right: 10px; padding: 3px" type="submit" value="Cancel" />
</form>';

$editor_html_action_edit = '
<h2>Currently editing %title%...</h2><br />
<form action="#" class="form-page-editor" method="post"  style="display: inline;">
<input type="hidden" name="action" value="edit2" />
<input type="hidden" name="target" value="%file_name%" />
<input type="hidden" name="path" value="%path%" />
<p>Page Title: <strong>%title%</strong></p>
<p>Time and date for file: <strong>%date_formatted%</strong> </p>
<p>You can use %type_extension% when editing this file.</p>
<?php
	if(%is_capable%) outblurt("<p>You can use \"Planet Mongo\" commands when editing this file.</p>");
?>
<p>'.$editor_html_link_to_content_file.'</p>
<textarea name="value" rows="40" style="width: 100%;">
%raw_contents_encoded%
</textarea><br /><br /><br />
<input type="submit" style="display: inline; margin-right: 10px; padding: 3px" value="Save" />
</form>
<!-- CANCEL BUTTON -->
<form action="#" class="form-page-editor" method="post" style="display: inline;">
<input type="hidden" name="path" value="%path%" />
<input style="display: inline; margin-right: 10px; padding: 3px" type="submit" value="Cancel" />
</form>';
$editor_html_action_edit2 = '
<hr />
<br />
<br />
<br />
' . $editor_html_action_edit;

$editor_html_file_item = '
	<tr>
	<td><span title="%file_name%">%title%</span></td> <td>%date_formatted%</td> <td>%type_extension%</td>
	<?php
	if(%is_locked%) {	?>
		<td colspan="3"><em>File is not available for editing.</em></td>
	<?php } else { ?>
	<td><form action="#" class="form-page-editor" method="post">
		<input type="hidden" name="action" value="edit" />
		<input type="hidden" name="target" value="%file_name%" />
		<input type="hidden" name="path" value="%path%" />
		<input type="submit" value="Edit" />
	</form></td>
	<td><form action="#" class="form-page-editor" method="post">
		<input type="hidden" name="action" value="rename" />
		<input type="hidden" name="target" value="%file_name%" />
		<input type="hidden" name="path" value="%path%" />
		<input type="submit" value="Rename" />
	</form></td>
	<td><form action="#" class="form-page-editor" method="post">
		<input type="hidden" name="action" value="delete" />
		<input type="hidden" name="target" value="%file_name%" />
		<input type="hidden" name="path" value="%path%" />
		<input type="submit" value="Delete" />
	</form></td> <?php }	?>
	</tr>
	' . "\n\n";
$editor_html_file_list = '<h2>Contents of "%path%"...</h2>
<table width="100%"><tr><th>Title</th> <th>Date</th> <th>Type</th> <th colspan="3">Actions</th> </tr> %list% </table>

<!-- CREATE NEW BUTTON -->
<form action="#" class="form-page-editor" method="post" style="display: inline;">
		<input type="hidden" name="action" value="create" />
		<input type="hidden" name="target" value="untitled.html" />
		<input type="hidden" name="value" value=" " />
		<input type="hidden" name="path" value="%path%" />
<input style="display: inline; margin-right: 10px; padding: 3px" type="submit" value="Create New File" />
</form>

';
$editor_html_directory_list = '<table><tr>%list%</tr></table>';
/*$editor_html_directory_list  = '<form action="#" class="form-page-editor" method="post">
	<label for="directory-selecter">Directory: </label><select id="directory-selecter" name="path">%list%</select>
	<input type="submit" value="Show" />
</form>
';*/
$editor_html_directory_item  = '<td style="padding-right: 10px"><form action="#" class="form-page-editor" method="post">
		<input type="hidden" name="path" value="%file_name%" />
		<input type="submit" value="%title%" style="padding:3px" />
</form></td>';


$editor_html_404 = '<h2>Error! The file you selected could not be found.</h2>
<h3>The attempt to %action% %path%/%target% was unsuccessful.</h3>';
/*
function editor_save_to_page ($file_name, $contents) {
	file_put_contents ($file_number, $contents);
    $fd = @opendir($dir);
    if($fd) {
    	while (($part = @readdir($fd)) == true) {
    	if ($part != "." && $part != "..") $file_array[]=$part;
      }
    }
}*/
function editor_directory_list_doaction ( $path ='' ) {
	global $editor_html_directory_list, $editor_html_directory_item, $editor_directory_list;
	$split = split("%list%", $editor_html_directory_list);
	$ra = Array (
		'%path%' => $path // TODO: Possibility of EVIL ATTACK here -- $path needs to be checked
		);
	outblurt(main_replace($split[0],$ra), POWER_DEFAULT);
	if(strlen($path)<1) $filelist = $editor_directory_list;
	if ($filelist !== FALSE) {// checks to make sure there is a directory
		foreach ( $filelist as $file ) {
			$text = $file->applyTemplate($editor_html_directory_item);
			outblurt(main_replace($text,$ra), POWER_PHP);
		}
	} else echo "<small>Error [editor_03]. Directory could not be found.</small>";
	outblurt(main_replace($split[1],$ra), POWER_DEFAULT);
}
function editor_page_list_doaction ($path = '') {
	if (strlen($path)<1) $path = $_POST['path'];
	if (strlen($path)>0) {
		global $editor_html_file_list, $editor_html_file_item;
		$split = split("%list%", $editor_html_file_list);
		$ra = Array (
			'%path%' => $path // TODO: Possibility of EVIL ATTACK here -- $path needs to be checked
			);
		outblurt(main_replace($split[0],$ra), POWER_DEFAULT);
		$filelist = main_dir_contents ($path, FALSE); // List contents, WITHOUT magic files
		if ($filelist !== FALSE) {// checks to make sure there is a directory
			foreach ( $filelist as $file ) {
				$text = $file->applyTemplate($editor_html_file_item);
				outblurt(main_replace($text,$ra), POWER_PHP);
			}
		} else echo "<small>Error [editor_03]. Directory could not be found.</small>";
		outblurt(main_replace($split[1],$ra), POWER_DEFAULT);
	}
}
function editor_try_to_make_writable ($path, $dir) {
	if(is_writable($path)) return TRUE;
	@chmod($path, 0666);
	if(is_writable($path)) return TRUE;
	@chmod($dir, 0777);
	if(is_writable($path)) return TRUE;
	@chmod($path, 0666);
	if(is_writable($path)) return TRUE;
	outblurt("<h1>Error! File write permissions error. 
				To remedy this, change the permissions of the file '$path' to allow writing by others.
				(and likely the '$dir' directory too)</h1>
				<code> [editor_00] </code>");
	return FALSE;
}
function editor_page_commit_doaction ($limitations = '') {
	$action = trim($_POST['action']);
	$possible_actions = Array('edit', 'edit2', 'rename', 'rename2', 'delete', 'delete2', 'create');
	if(strlen($action)>'' && in_array($action, $possible_actions, TRUE)) {
		$target = $_POST['target'];
		$path = $_POST['path'];
		$ra = Array (
			'%target%' => $target,
			'%path%' => $path,
			'%action%' => $action
		);
		$template = $editor_html_file_editor; // <-- This might be useless, I should get rid if it is redundant or useless
		
		
		//////////////////////////////////
		// This section checks to see if it is an "edit2" action, which means the user has clicked 
		// on the "Save" button when editing a page.
		// This section also creates the file for a "newfile" action
		if($action=='edit2' || $action=='create') { // ** edit2 **
			if(editor_try_to_make_writable($path, $target)){	
				$value = $_POST['value'];
				$full_path = "$path/$target";				
				if(file_put_contents($full_path, $value) == FALSE)
					outblurt("<h1>Error! Could not save! Probably a file write permissions error.</h1>
					<code> [editor_02] </code>");
				else outblurt("<h2>File saved succesfully!</h2>", POWER_HTML);
			}
		}
		//////////////////////////////////
		
		//////////////////////////////////
		// This section checks to see if it is an "create" action, which creates a file, and then 
		// changes $action so that the action becomes a "rename" action.
		if ($action == 'create') { // ** newfile **
			outblurt('<br /><h1>New file created. Now you must rename your file...</h1>');
			$action = 'rename';
		}
		//////////////////////////////////
		
		//////////////////////////////////
		// This section attempts to read the file by using the usual means. It then stores it in 
		// the $file variable for use with the remaining actions.
		// Finally, it outblurts the template (found as a global variable) that corresponds with this action.
		$file = main_get_file($target, $path);		
		if($file !== FALSE) {
			if($file->is_locked == TRUE) {
				// This is only displayed in (what can be assumed to be) an attempted JavaScript hack, so it doesn't 
				// need to be friendly.
				outblurt("<h1>The file you selected is disabled for edit.</h1>", POWER_HTML);
				return FALSE;
			} else $template = $file->applyTemplate($GLOBALS['editor_html_action_' . $action]);
		} else $template = $GLOBALS['editor_html_404'];
		outblurt(main_replace($template, $ra), POWER_PHP);
		//////////////////////////////////
		
		if ($action=='rename2') { // ** rename2 **
			////////////////////////////
			// This block computes the file name to rename it to
			////////////////////////////		
			// First, figure out the date
			$date_type_array = Array(
				'today' => time(),
				'human' => mktime( $_POST['date-hour'], $_POST['date-minute'], 0,
					$_POST['date-month'], $_POST['date-day'], $_POST['date-year']),
				'unix' => intval($_POST['unix_time']),
				'none' => FALSE
				);
			$new_unix_date = $date_type_array[$_POST['value-date-type']];
			$new_title = $_POST['new_title'];
			// TODO: secure this from changing type to bad type (ie PHP)
			$new_type = $_POST['new_type'];
			if($_POST['autoformat_title']=='on') $new_title = strtolower($new_title);
			$new_title = str_replace(' ', '_', $new_title); // TODO Convert to more robust filename cleanser
			$new_filename = $new_title.($new_unix_date!==FALSE&&$new_unix_date>0?(".$new_unix_date"):'').".$new_type";
			// TODO JUST CHANGE TO A TEMPLATE MAYBE??? ;)
			$old_path = "$path/$target";
			$new_path = "$path/$new_filename";
			// TODO make this MUCH more robust... change it to a FileWrapper method
			outblurt("<h2>Renaming...</h2>
			<strong>Date type</strong>: ". $_POST['value-date-type']."<br />	
			<strong>New date:</strong> $new_unix_date<br />
			<strong>New title:</strong> $new_title<br />
			<strong>New filename:</strong> $new_filename <br />
			<code>Rename operation... '$old_path' to '$new_path'</code>
			");
			if(editor_try_to_make_writable($old_path, $path) != FALSE) {
				if(@rename($old_path, $new_path)===FALSE)
					outblurt("<h1>Error! Could not re-name! File write permissions error.</h1>
					<code> [editor_01] </code>");
				else outblurt("<em>Renaming process a success! (You may need to refresh to see effect.)</em>", POWER_HTML);
			}
		}
		elseif ($action=='delete2') { // ** delete2 **
			if(editor_try_to_make_writable($path, $target)){
				$full_path = "$path/$target";			
				if(unlink($full_path) == FALSE)
					outblurt("<h1>Error! Could not delete! Probably a file write permissions error.</h1>
					<code> [editor_03] </code>");
				else outblurt("<h2>File deleted succesfully! (You may need to refresh to see effect.)</h2>", POWER_HTML);
			}
		}
	}
}

} ?>
