<?php

	// collect the output in case anyone is watching
	$output = array();

	// get all the content that is ready for publishing
	$query = "
		SELECT
			content.ID,
			path,
			field,
			content,
			user,
			user.name AS user_name,
			user.email AS user_email
		FROM content
		INNER JOIN (SELECT MAX(ID) AS ID FROM content GROUP BY path, field) AS content_latest ON content_latest.ID=content.ID
		LEFT JOIN user ON user.ID=content.user
		WHERE status=3
		AND schedule<='".timestamp("PHP", 1)."'
	";
	$result = db_do_query($query);
	$count = db_num_rows($result);
	if (!$count) {
		// don't output anything here; that would be annoying if email notifications are configured in the crontab
		//$output[] = "There is no new content ready for publishing.";
	} else {
	
		for ($i=0; $i<$count; $i++) {
			$row = db_get_row($result, $i);
			extract($row);
	
			// since we're not submitting anything, we need to add slashes manually
			$content = addslashes($content);
			
			// set a default comment
			$comment = "Scheduled publishing";
	
			// insert a new record into the database
			$query2 = "
				INSERT INTO content (
					path,
					field,
					content,
					user,
					status,
					comment,
					date
				) VALUES (
					'$path',
					'$field',
					'$content',
					 $user,
					 4,
					'$comment',
					".timestamp("SQL", 1)."
				)
			";
			$result2 = db_do_query($query2);
			
			// save the content in the site format
			if ($result2) {
				$content = stripslashes($content);
				$result = save_content($path, $field, $content);
			}
			
			// see if we can remove the Dreamweaver lock file
			if ($result2) {
				clear_dreamweaver_lock($path);
			}
		
			// notify the user and add the result to the output
			if ($result2) {
				$output[] = "Publishing $field in $path.";
				$subject = "Published $field in $path";
				$message = "Your content $field in $path has been published according to the schedule you requested. You can click here to view the content:\n\n".SITE_PROTOCOL."://".SITE_DOMAIN."/".EDITOR_SUBDIRECTORY."/".$wrapper_page."?page=content_view&ID=$ID";
			} else {
				$output[] = "Unable to publish $field in $path.";
				$subject = "Unable to publish $field in $path";
				$message = "There was a problem publishing your content $field in $path according to the schedule you requested. You can click here to publish the content manually:\n\n".SITE_PROTOCOL."://".SITE_DOMAIN."/".EDITOR_SUBDIRECTORY."/".$wrapper_page."?page=content_edit&path=$path&field=$field";
			}
			send_email($user_email, $user_name, WEBMASTER_EMAIL, EDITOR_NAME, WEBMASTER_EMAIL, $subject, $message, 0);
		
		}
		
	}
	
	$output = implode("\n", $output);
	print $output;
	//send_email("arlo@arlomedia.com", "", WEBMASTER_EMAIL, EDITOR_NAME, WEBMASTER_EMAIL, "test", $output, 0);
	
?>
