<?php
require_once('include/admin.inc.php');

auth_redirect(); // Require logged in user to access this page.

$rant = new Rant();
$rant->id = (int)$_REQUEST['rant_id'];
$rant = getrant($rant->id);

if( $_POST ) {
	$rant->published = strtotime( $_POST['rant_date'] );
	$rant->status = $_POST['rant_status'] == 'published' ? 'published' : 'draft';
	$rant->side = $_POST['rant_side'] == 'left' ? 'left' : 'right';
	$rant->author = (int)$_POST['rant_author'];
	$rant->title = $_POST['title'];
	$rant->body = preg_replace('/&nbsp;/', '', $_POST['content']);
	$rant->link = $_POST['link'];
	$rant->imagetext = $_POST['rant_imagetext'];

	if( USING_TIDY ) {
		$tidy = new tidy;
		$config = $tidy->getConfig();
		$tidy->parseString( $rant->body, $config, 'UTF8' );
		$tidy->cleanRepair();
		$rant->body = tidy_get_output($tidy);
	}

	$action = isset($_POST['publish']) ? 'post' : 'edit';
	
	if( isset( $_POST['publish'] ) ) $rant->status = 'published';	// If [publish] button is used, ignore radio button

	
	$source_rantimage_filename = $_FILES['ranterImage']['tmp_name'];
	extract( pre_upload_rant_image( $source_rantimage_filename ) );
	if( $upload_error ) $error.=$upload_error;

	$source_rantattachment_filename = Array();
	for($i = 0; $i < count($_FILES['rant_attachment']['error']); $i++) {
		if( !is_valid_upload('rant_attachment', $i) ) {
			$error .= "<p>Attachment $i was not uploaded properly</p>";
			$source_rantattachment_filename[] = '';
		} else {
			$source_rantattachment_filename[] = $_FILES['rant_attachment']['tmp_name'][$i];
		}
	}
	
	switch( $_POST['action'] ) {
		case 'new_rant':
		
			check_nonce('new-rant');
	
			if( ! $doing_upload ) {
				// Use default rant image for this contributor.
				$contributor = get_userdatabyid( $rant->author );
				$image_data = getimagesize(SITE_PATH_ABS .'/'. SITE_RANT .'/'. $contributor->default_image);
				$rant->imagetype = $image_data[2] ? $image_data[2] : 'NULL';
				$source_rantimage_filename = $contributor->default_image;
			} else {
				$rant->imagetype = $upload_imagetype;
			}
	
			$rant->id = insertrant($rant);
			if( $rant->id === false )
			{
				adminlog("Error on rant insertion: ".mysql_error(), MTS_RANT, MTA_INSERT, E_ERROR);
				mtdie('There was an error inserting the rant into the database.', 'SQL Error');
			}

			for($i = 0; $i < count($source_rantattachment_filename); $i++) {
				if('' == $source_rantattachment_filename[$i]) continue;

				$upload_error = $upload_info = '';
				extract( save_upload_rant_attachment($_FILES['rant_attachment']['tmp_name'][$i], $rant->id) );

				if( $upload_error ) $error.=$upload_error;	
				if( $upload_info ) {
					$info .= $upload_info;
					$rant->body = preg_replace('/(href|src)=\"([^\"]*?)\\{'.($i+1).'\\}(.*?)\"/', '\1="'.get_rantattachment_filename($rant_attachment_id).'"', $rant->body);
				}
			}

			if(count($_FILES['rant_attachment']['error']) > 0)
				updaterant($rant);

			if( $doing_upload ) {
				extract( save_upload_rant_image( $source_rantimage_filename, $rant ) );
				if( $upload_info ) $info.=$upload_info;
				if( $upload_error ) $error.=$upload_error;	
			} elseif($rant->imagetype != 'NULL') {
				extract( save_stock_rant_image( $source_rantimage_filename, $rant ) );
				if( $upload_info ) $info.=$upload_info;
				if( $upload_error ) $error.=$upload_error;	
			}
			
			break;
			
		case 'saverant':

			check_nonce('save-rant-' . $rant->id);
			
			if( isset( $_POST['rant_reverttodefaultimage'] ) ) {
				// Use default rant image for this contributor, copy it into place
				$contributor = get_userdatabyid( $rant->author );
				$imagedata = getimagesize(SITE_PATH_ABS .'/'. SITE_RANT .'/'. $contributor->default_image);
				$rant->imagetype = $imagedata[2] ? $imagedata[2] : 'NULL';
				if($rant->imagetype != 'NULL')
					extract( save_stock_rant_image( $contributor->default_image, $rant ) );
				adminlog("Reverting to user's default rant image for rant ".$rant->id.".", MTS_RANT, MTA_UPDATE);
				
			} elseif( $doing_upload ) {
				$rant->imagetype = $upload_imagetype;
				extract( save_upload_rant_image( $source_rantimage_filename, $rant ) );
				adminlog("Uploading new rant image for rant ".$rant->id.".", MTS_RANT, MTA_UPDATE);
				if( $upload_info ) $info.=$upload_info;
				if( $upload_error ) $error.=$upload_error;	
			}

			foreach($_POST['delete_attachment'] as $attachment)
				deleteattachment($attachment);

			$existing_attachments = $mtdb->getAll('SELECT ra.id AS id, extension FROM rant_attachment ra JOIN media_t ON ra.media = media_t.id WHERE ra.rant = '.$rant->id.' ORDER BY id');
			for($i = 0; $i < count($existing_attachments); $i++) {
				$rant->body = preg_replace('/(href|src)=\"([^\"]*?)\\{'.($i+1).'\\}(.*?)\"/', '\1="'.get_rantattachment_filename($existing_attachments[$i]->id).'"', $rant->body);
			}
			
			for($j = $i; $j < count($source_rantattachment_filename) + $i; $j++) {
				if('' == $source_rantattachment_filename[$j - $i]) continue;
				
				$upload_error = $upload_info = '';
				extract( save_upload_rant_attachment($_FILES['rant_attachment']['tmp_name'][$j - $i], $rant->id) );

				if( $upload_error ) $error.=$upload_error;	
				if( $upload_info ) {
					$info .= $upload_info;
					$rant->body = preg_replace('/(href|src)=\"([^\"]*?)\\{'.($i+1).'\\}(.*?)\"/', '\1="'.get_rantattachment_filename($rant_attachment_id).'"', $rant->body);
				}
			}

			updaterant($rant);
			
			if($rant->status != 'draft' && $_POST['broadcast'] &&
					($rant->published <= mktime(0,0,0, date('m'), date('d')-1, date('Y'))))
			{
				rsspost('Rant '.$rant->id.' updated.', SITE_HOST.SITE_PATH.'/rant/'.$rant->id);
				twitterpost('Rant '.$rant->id.' updated: '.SITE_HOST.SITE_PATH.'/rant/'.$rant->id);
			}

			break;
	}
	if( $error ) $action='edit';

	if( 'post' == $action ) _redirect( ADMIN_PATH . '/manage-rants.php?saved=success' );

	$info.= '<p>' . ( $rant->status === 'draft' ? 'Rant draft saved.' : sprintf('Rant published. <a href="%s%s/index.php?rant_id=%d">View on site</a>.', SITE_HOST, SITE_PATH, $rant->id) ) . '</p>';

} elseif( !$rant->id ) {
	mtdie('Attempted to edit rant with no rantid supplied.', 'Bad Request');
}

/////////////////////// Display Edit Form ///////////////////////


adminhead('Edit Rant');
adminmenu('manage-rants.php');

?>

<script language="javascript" type="text/javascript" src="include/tiny_mce/tiny_mce.js"></script>
<script language="javascript" type="text/javascript">
tinyMCE.init({
	mode : "textareas",
	theme : "advanced",
	theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontsizeselect,|,cut,copy,paste,pastetext,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,|,cleanup,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
	theme_advanced_buttons2 : "hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,fullscreen,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
	theme_advanced_buttons3 : "",
	plugin_preview_width : "350",
	plugin_preview_height : "700",
	language:"en",
	theme_advanced_toolbar_location:"top",
	theme_advanced_toolbar_align:"left",
	theme_advanced_statusbar_location:"bottom",
	theme_advanced_resizing:"1",
	theme_advanced_resize_horizontal:"",
	paste_convert_middot_lists:"1",
	paste_remove_spans:"1",
	paste_remove_styles:"1",
	gecko_spellcheck:"1",
	extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style],iframe[src|width|height|scrolling|frameborder|style]",
	theme_advanced_blockformats : "p,h3,h4,h5,h6",
	plugins:"safari,inlinepopups,autosave,paste,media,fullscreen,contextmenu,advimage,advlink,visualchars,preview"
});
</script>

<h2>Editing Rant "<?php echo htmlentities($rant->title, ENT_COMPAT, 'UTF-8') ; ?>"</h2>

<form enctype="multipart/form-data" action="edit-rant.php" method="post" name="post" id="post">
<?php nonce_field('save-rant-'.$rant->id); ?>
<input type="hidden" name="action" value="saverant" />
<input type="hidden" name="rant_id" value="<?php echo $rant->id; ?>" />

<div id="poststuff">

<div id="moremeta">
<div id="grabit" class="dbx-group">

<fieldset id="slugdiv" class="dbx-box">
<h3 class="dbx-handle">Side</h3>
<div class="dbx-content"><select name="rant_side">
<?php
  $sides = array('left'=>'Left','right'=>'Right');
  foreach( $sides as $k=>$v ) {
  	printf('<option value="%s" %s>%s</option>', htmlentities($k, ENT_COMPAT, 'UTF-8'), ($rant->side == $k ? 'selected="selected"' : '' ), htmlentities($v) );
  }
?>
</select></div>
</fieldset>

<fieldset id="authordiv" class="dbx-box">
<h3 class="dbx-handle">Author</h3> 
<div class="dbx-content"><select name="rant_author"><?php
	$contrib = $mtdb->getAll('select id,name from contributor');
	foreach( $contrib as $k=>$v ) {
		printf('<option value="%s" %s>%s</option>', htmlentities($v->id, ENT_COMPAT, 'UTF-8'), ( $v->id == $rant->author ? 'selected="selected"' : '' ), htmlentities($v->name) );
	} ?>
</select></div>
</fieldset>

<fieldset id="pubdatediv" class="dbx-box">
<h3 class="dbx-handle">Post Date</h3>
<div class="dbx-content"> <input type="text" name="rant_date" value="<?php echo htmlentities( date( 'Y-m-d H:i:s', $rant->published )); ?>" /> </div>
</fieldset>

<fieldset id="statusdiv" class="dbx-box">
<h3 class="dbx-handle">Published Status</h3>
<div class="dbx-content">
	<label><input type="radio" name="rant_status" value="draft" <?php echo $rant->status == 'draft' ? 'checked="checked"' : ''; ?>/>Draft</label>
	<label><input type="radio" name="rant_status" value="published" <?php echo $rant->status == 'published' ? 'checked="checked"' : ''; ?>/>Published</label>
</div>
</fieldset>

<?php if($rant->status != 'draft') { ?>
<fieldset id="broadcastdiv" class="dbx-box">
<h3 class="dbx-handle">Broadcast Update</h3>
<div class="dbx-content">
	<label><input type="radio" name="broadcast" value="0" checked="checked" />No</label>
	<label><input type="radio" name="broadcast" value="1" />Yes</label>
</div>
</fieldset>
<?php } ?>

</div>
</div>

<fieldset id="titlediv">
	<legend>Title</legend>
	<div><input type="text" name="title" size="40" tabindex="1" value="<?php echo htmlentities($rant->title, ENT_COMPAT, 'UTF-8'); ?>" id="title" /></div>
</fieldset>

<fieldset id="linkdiv">
	<legend>Link</legend>
	<div><input type="text" name="link" size="40" tabindex="2" value="<?php echo htmlentities($rant->link, ENT_COMPAT, 'UTF-8'); ?>" id="link" /></div>
</fieldset>

<fieldset id="postdivrich">
	<legend>Post</legend>
	<style type="text/css">
		#postdivrich table, #postdivrich #quicktags {border-top: none;}
		#quicktags {border-bottom: none; padding-bottom: 2px; margin-bottom: -1px;}
		#edButtons {border-bottom: 1px solid #ccc;}
	</style>
	<div><textarea class="mceEditor" rows="13" cols="40" name="content" tabindex="3" id="content"><?php echo htmlentities($rant->body, ENT_COMPAT, 'UTF-8'); ?></textarea></div>
</fieldset>



<p class="submit">
 <input name="save" type="submit" id="save" tabindex="3" value="Save and Continue Editing" style="font-weight: bold;" />
 <input name="publish" type="submit" id="publish" tabindex="5" accesskey="p" value="Publish" />
</p>



<div class="dbx-b-ox-wrapper">

<fieldset id="rant-image" class="dbx-box">
	<h3 class="dbx-handle">Image</h3>
	<div>
	<table border="0">
	<tr><td valign="top">
	<?php

		$contributor = get_userdatabyid( $rant->author );
		$rantimage_filename = get_rantimage_filename($rant);
		if( ! file_exists( SITE_PATH_ABS.'/' . $rantimage_filename )) {
			// no image in place yet
			$rantimage_filename = SITE_RANT.'/' . $contributor->default_image;
			if( file_exists( SITE_PATH_ABS.'/' . $rantimage_filename )) {
				echo 'Currently using default rant image for this contributor. <a href="user-edit.php?edit='.$currentuser->id.'">Change default</a>.';
			} else {
				$rantimage_filename = false;
				echo 'There is currently no image associated with this rant, <br/>and no default rant image associated with this contributor.
				<br/><a href="user-edit.php?edit=' . $currentuser->id . '">Add a default rant image to your profile.</a>';
			}
		} else {
			echo 'Custom rant image is specified.';
		}
	?>
	
	<p>Upload new rant image:<br/>
		<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
		<input name="ranterImage" type="file"/>
	</p>
	<p><input type="checkbox" name="rant_reverttodefaultimage" /> Revert to default rant image.</p>		
	</td><td>
	<?php if ( false !== $rantimage_filename ): ?>
		<p><img src="<?php echo SITE_HOST . '/' . SITE_PATH . '/' . $rantimage_filename; ?>" width="150" /></p>
	<?php endif; ?>
	</td></tr>
	<tr><td>
		<p>Rant image alt text:</p>
		<input type="text" name="rant_imagetext" size="40" tabindex="2" value="<?php echo $rant->imagetext; ?>" id="rant_imagetext" />
	</td></tr>
	<tr id="rant_attachments"><td>
		<p>Attach files:</p>
		<ol id="rant_attachment_list">
		<?php
			$attachments = $mtdb->getAll('SELECT ra.id AS id, extension FROM rant_attachment ra JOIN media_t ON ra.media = media_t.id WHERE ra.rant = '.$rant->id.' ORDER BY id');
			foreach($attachments as $k=>$v)
				printf('<li><input type="checkbox" name="delete_attachment[]" value="%d" /> <a href="%s/%s/%s">%s</a></li>', $v->id, SITE_HOST, SITE_PATH, get_rantattachment_filename($v->id), get_rantattachment_filename($v->id));
		?>
		</ol>
		<p>(Checked attachments will be deleted on submit.)</p>
		<script src="include/rants.js" type="text/javascript"></script>
		<a href="#rant_attachments" onclick="new_rant_attachment()">(add attachment)</a>
	</td></tr>
	</table>
	</div>
</fieldset>

</div>


</div>
</form>

<?php adminfooter() ?>
