All pastes #497396 Raw Edit

Stuff

public text v1 · immutable
·published 2007-05-19 20:42 UTC
rendered paste body
<?php

/*
Plugin Name: Ask Me Blog Experiment
Plugin URI: http://www.theblogexperiment.com/plugins/ask-me.php
Version: 1.5 and 2.0
Author: Sara Smith and Jelena Pavlovic
Author URI: http://www.ilovecode.com and http://www.morningcaffeine.com
Description: Allows user to ask the blog owner questions. Visit <a href="options-general.php?page=askme.php&settings=yes">Options/Ask Me</a> after activation of the plugin. To see the plugin in action you can visit <a href="http://www.ilovecode.com/qanda/">Sara's</a> or <a href="http://www.morningcaffeine.com/about/">Jelena's blog</a>

Inspired by Dean Edwards' about me script
http://dean.edwards.name/about
*/

/**********************
	CONSTANTS
**********************/
define("TABLE_AM_QUESTIONS", $table_prefix."askme_questions");
define("TABLE_AM_QUESTIONS_PHRASE", $table_prefix."askme_questions_phrases");
define("TABLE_AM_COWARDS", $table_prefix."askme_cowards");
define("TABLE_AM_SETTINGS", $table_prefix."askme_settings");


/*
// WordPress 1.5 includes this file again on the options page. Avoid duplicate declaration:
if ( function_exists("is_plugin_page") && is_plugin_page() ) {
	askme_options_page();
	return;
}
*/

add_action('options_page_askme', 'askme_options_page');

/********************
 INSTALLATION FUNC
********************/

function askme_install ()
{
	global $table_prefix, $wpdb;
	global $user_ID;
	require_once(ABSPATH . 'wp-admin/upgrade-functions.php');

	$table_name_questions = $table_prefix . "askme_questions";
	$table_name_questions_phrase = $table_prefix . "askme_questions_phrases";
	$table_name_cowards = $table_prefix . "askme_cowards";
	$table_name_settings = $table_prefix . "askme_settings";

	if($wpdb->get_var("show tables like '$table_name_questions'") != $table_name_questions)
	{
		$sql = "CREATE TABLE ".$table_name_questions." (
			question_ID bigint(20) NOT NULL auto_increment,
			question text NOT NULL,
			answer text,
			user varchar(50) default NULL,
			email varchar(100) default '',
			url varchar(100) default '',
			approved tinyint(1) default '0',
			date_entered datetime default '0000-00-00 00:00:00',
			wants_return_email tinyint(1) default '0',
			PRIMARY KEY  (`question_ID`)
			);";

		dbDelta($sql);
	}

	if($wpdb->get_var("show tables like '$table_name_questions_phrase'") != $table_name_questions_phrase)
	{
		$sql = "CREATE TABLE ".$table_name_questions_phrase." (
			phrase_ID bigint(20) NOT NULL auto_increment,
			phrase varchar(255) NOT NULL default '',
			PRIMARY KEY  (`phrase_ID`)
			)";

		dbDelta($sql);

		$sql = "INSERT INTO ".$table_name_questions_phrase." (phrase_ID, phrase) VALUES
			(1, 'asks');";

		$wpdb->query($sql);
	}

	if($wpdb->get_var("show tables like '$table_name_cowards'") != $table_name_questions)
	{
		$sql = "CREATE TABLE ".$table_name_cowards." (
			coward_ID bigint(20) NOT NULL auto_increment,
			coward varchar(255) NOT NULL default '',
			PRIMARY KEY  (`coward_ID`)
			);";

		dbDelta($sql);

		$sql = "INSERT INTO ".$table_name_cowards." (coward_ID, coward) VALUES
			(1, 'Guest'),
			(2, 'Anonymous');";

		$wpdb->query($sql);
	}

	//create a page called Ask me

	//prepare date:
	$date_now = current_time('mysql');
	$date_now_gm = get_gmt_from_date($date_now);

	$page_url = get_option('siteurl')."/ask-me/";

	$content = "Regular about pages are boring, aren't they? In addition to having a typical \"About Me\" page, I decided to have a page where visitors could ask what they want to know instead of me telling them what I think they should know. So go ahead, <a href=\"".$page_url."#ask\">ask me</a> a question. Of course these questions are moderated, but pretty much anything goes (within reason).

	<?php check_submit(); askme_get_questions(); output_form(); ?>";

	$content = $wpdb->escape($content);

	$sql = "INSERT INTO ".$table_prefix."posts SET";
	$sql .= " post_author = '".$user_ID."'";
	$sql .= ", post_date = '".$date_now."'";
	$sql .= ", post_date_gmt = '".$date_now_gm."'";
	$sql .= ", post_title = 'Ask me'";
	$sql .= ", post_name = 'ask-me'";
	$sql .= ", post_status = 'static'";
	$sql .= ", post_category = 0";
	$sql .= ", post_parent = 0";
	$sql .= ", post_content = '".$content."'";


	$wpdb->query($sql);



	if($wpdb->get_var("show tables like '$table_name_settings'") != $table_name_questions)
	{
		$sql = "CREATE TABLE ".$table_name_settings." (
			SettingsID int(11) NOT NULL auto_increment,
			Email varchar(255) NOT NULL default '',
			PerPage smallint(6) NOT NULL default '0',
			PerPagePublic tinyint(4) NOT NULL default '0',
			FormAction varchar(100) NOT NULL,
			PRIMARY KEY  (`SettingsID`)
			);";

		dbDelta($sql);


		$email = get_option('admin_email');
		$sql = "INSERT INTO ".$table_name_settings." (SettingsID, Email, PerPage, PerPagePublic, FormAction) VALUES
			(1, '" . $email . "', 20, 20, '".$page_url."');";


		$results = $wpdb->query($sql);
	}
	return true;
}


function askme_get_questions()
{
	global $wpdb;

	if(!isset($_GET['start']))
	{
		$start = 0;
	}
	else
	{
		$start = $_GET['start'];
	}


	//get No of records from settings tbl
	$sql = "SELECT PerPagePublic FROM ".TABLE_AM_SETTINGS." LIMIT 1";
	$settings = $wpdb->get_row($sql);

	$limit = $settings->PerPagePublic; // No of records to be shown per page.

	askme_print_list($start, $limit);
	$numrows = askme_get_questions_count("SELECT question, answer, user, email, url, date_entered FROM ".TABLE_AM_QUESTIONS." WHERE approved='1' ");
	echo "<div class='askme_navlinks'>";
	//print paging

	if($start > 0)
	{
		print "<a href='?start=" . ($start - $limit) . "'>PREV</a>";
	}

	$i=0;
	$j=1;
	for($i=0;$i < $numrows;$i=$i+$limit)
	{

		if($i <> $start)
		{
			echo " <a href='?start=" . $i . "'>" . $j . "</a> ";
		}
		else
		{
			echo  $j ;
		} /// Current page is not displayed as link and given font color blue
		$j=$j+1;
	}


	if($start <= ($numrows-$limit))
	{
		print "<a href='?start=" . ($start + $limit) . "'>NEXT</a>";
	}
	echo "</div>";
}


function askme_get_questions_count($sql)
{
	global $wpdb;
	$questions = $wpdb->get_results($sql);
	return count($questions);

}

function askme_print_list($start, $limit)
{
    //global $limit;
    //global $begin;
    global $wpdb;
    $questions = $wpdb->get_results("SELECT question, answer, user, email, url, date_entered FROM ".TABLE_AM_QUESTIONS." WHERE approved='1' ORDER BY date_entered DESC limit " . $start . ", " . $limit);

    $phrases = $wpdb->get_results("SELECT phrase FROM ".TABLE_AM_QUESTIONS_PHRASE." ORDER BY rand()");

	if(is_array($questions) && !empty($questions))
	{
	    foreach ($questions as $question)
	    {
		    $randNumber = rand(1, count($phrases)-1);

	    	$post_question = stripslashes($question->question);
	    	$post_answer = stripslashes($question->answer);
	    	$url = $question->url;
	    	$name = $question->user;
	    	if (trim($name) == "")
		{
	    		$name = askme_get_coward();
	    	}


			//start the question/answer div here
			echo "<!-- start Ask me Item --><div class='askme_item'>";

			//the phrase.. i.e. Sara wants to know:
	    	echo "   <div class='askme_phrase'>";
	       	echo "</div>";
	    	echo "<div class='askme_question'>" . $post_question . "</div>";
	    		if($url)
				    	{
				    		echo "<a href='"  . $url . "' class='askme_link'>" . $name . "</a> ";
				    	}
				    	else
				    	{
				    		echo $name . " ";
	    	}

	      	echo "<div class='askme_answer'>" . $post_answer . "</div>";
	    	echo "</div><!-- end Ask Me item -->";
	    }
	}
	else
	{
		echo "<p>Be the first to ask a Question!</p>";
	}
}

//get a random anonymous user title
function askme_get_coward()
{
	global $wpdb;
	$cowards = $wpdb->get_row("SELECT coward FROM ".TABLE_AM_COWARDS." ORDER BY RAND() LIMIT 1");

	return $cowards->coward;
}//askme_get_coward()

function output_form()
{
	global $start;
	global $limit;
	global $wpdb;

	//get action from the settings
	$result = $wpdb->get_row("select FormAction from " . TABLE_AM_SETTINGS);
	$action = $result->FormAction;

	$form = '<a name="ask"><h3 id="ask">Ask a Question</h3></a>
	        <div class="commentform">
         	<form action="' . get_permalink() . '" method="post">
        		<div><label for="name">Name:</label><input id="name" name="username" type="text" value="' . $comment_author .'" style="width:250px"></div>
        		<div><label for="email">Email: (required)</label><input id="email" name="email" type="text" value="' . $comment_author_email .'" style="width:250px"></div>
        		<div><label for="url">Url: </label><input id="url" name="url" type="text" value="' . $comment_author_url .'" style="width:250px"></div>
      			<div><label for="comment">Question: (required) </label><br /><textarea id="question" name="question"  rows="7" style="width:250px"></textarea></div>
      			<div><input name="submit"  value="Ask Me" type="submit" style="margin-top: 10px;"></div>
            	<div><input id="wants_return_email" name="wants_return_email" checked="checked" type="checkbox" ><label for="url">Subscribe to answer</label></div>

        	</form>
        </div>

        <div style="clear:both; height:1px;">&nbsp;</div>';
		echo $form;

	/*echo '<p class="askme_input"><label for="name">Name:</label>';
   echo '<input id="name" name="username" type="text" value="' . $comment_author .'"></p>';
	echo '<p class="askme_input"><label for="email">Email: (required)</label>';
   echo '<input id="email" name="email" type="text" value="' . $comment_author_email .'"></p>';
	echo '<p class="askme_input"><label for="url">URL:</label>';
   echo '<input id="url" name="url" value="http://" type="text" value="' . $comment_author_url .'"></p>';
	echo '<p class="askme_input"><label for="comment">Question: (Required)</label>;
   echo '<textarea id="question" type="text" name="question" cols="25" rows="5" style="></textarea></p>';
	echo '<p><input name="submit" class="askme_button" value="Submit" type="submit"></p>';
	echo '<p class="askme_input"><label for="comment">Subscribe to answer</label>';
   echo '<input type="checkbox" id="wants_return_email" name="wants_return_email" checked="checked" /></p>';

echo '</p></fieldset>';
echo '</form>';*/


}//output_form()



function check_submit()
{
	if (isset($_POST['question']))
	{
		$errors = verify_input();

		if (!empty($errors))
		{
			echo "<span style='color: red; font-weight:bold;'>" . $errors . "</span>";
		}
		else
		{
			echo "<span style='font-weight:bold;'>Yay! Your question is on the way to be answered. :)</span>";
			insert_question();
			send_email();
		}
	}
}//check_submit()

function send_email()
{
	global $wpdb;
	$settings = $wpdb->get_row("SELECT Email, PerPage FROM ".TABLE_AM_SETTINGS." LIMIT 1");

	$subject = "Someone asked you a question!";
	$from = "From: " . $settings->Email;
	$body = "A question is waiting for your moderation:\n\n";
	$body .= "User: " .  $_POST['username'] . "\n";
	$body .= "Email: " . $_POST['email'] . "\n";
	$body .= "URL: " . $_POST['url'] . "\n";
	$body .= "Question: " . $_POST['question'] . "\n";
	mail($settings->Email, $subject, $body, $from);

}//send_email()

function insert_question()
{
	global $wpdb;

	if($_POST['wants_return_email'])
	{
		$checked = 1;
	}
	else
	{
		$checked = 0;
	}
	$name = $wpdb->escape($_POST['username']);
	$email = $wpdb->escape($_POST['email']);
	$url = $wpdb->escape($_POST['url']);
	if ($url == "http://")
	{
		$url = "";
	}
	$question = $wpdb->escape($_POST['question']);

	$query = "INSERT INTO ".TABLE_AM_QUESTIONS." SET";
	$query .= " question = '".$question."'";
	$query .= ", user = '".$name."'";
	$query .= ", url = '".$url."'";
	$query .= ", email = '".$email."'";
	$query .= ", approved = 0";
	$query .= ", date_entered = NOW()";
	$query .= ", wants_return_email = " . $checked;

	$wpdb->query($query);

}//insert_question()


function verify_input()
{
	$errString = '';

	if ($_POST['email'] == '')
	{
		$errString .= "You must enter your email.<br />";
	}
	else if (!eregi('^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$', $_POST['email']))
	{
		$errString .= "Your email must be properly formatted.<br />";
	}
	if ($_POST['question'] == '')
	{
		$errString .= "You must ask a question.";
	}
	return $errString;
}//verify_input()

function askme_add_options_page()
{
	if (function_exists('add_options_page')) {
		// WordPress 1.5 sometimes doesn't show the options page if called in the first style
		if ( $wp_version > "1.5" ) {
			add_options_page('Ask Me Plugin', 'Ask Me', 8, basename(__FILE__),'askme_options_page');
		} else {
			add_options_page('Ask Me Plugin', 'Ask Me', 8, basename(__FILE__));
		}
	}
}//askme_add_options_page()

function askme_admin_get_questions()
{
	global $wpdb;



	if(!isset($_GET['start']))
	{
		$start = 0;
	}
	else
	{
		$start = $_GET['start'];
	}

	//get No of records from settings tbl
	$sql = "SELECT PerPage FROM ".TABLE_AM_SETTINGS." LIMIT 1";
	$settings = $wpdb->get_row($sql);



	$limit = $settings->PerPage; // No of records to be shown per page.

	 $sql = "SELECT question_id, SUBSTRING(question, 1, 40) as question, SUBSTRING(answer, 1, 40) as answer, user, SUBSTRING(url, 1, 25) as url, DATE_FORMAT(date_entered, '%D %b %Y') as date_entered, approved FROM ".TABLE_AM_QUESTIONS;
	 if ($_GET['filterBy'] != '')
	 {
	 	if ($_GET['filterBy'] != 2)
	 	{
	 		$sql .= " WHERE approved= " . $_GET['filterBy'];
	 	}
	 }




	$numrows = askme_get_questions_count($sql);
	echo "<div class='wrap'><a href='".$SERVER['PHP_SELF']."?page=askme.php&settings=yes'>Update Settings</a><h2>You have " . $numrows . " questions.</h2><br /><br />";
	echo "Filter your results. Show: <form method='get' action='" . $_SERVER['PHP_SELF'] . "?page=askme.php' name='filterform'>";
	?>
			<select id='filterBy' name='filterBy'>
				<option value="2" <?php echo (isset($_GET['filterBy']) && $_GET['filterBy'] == 2) ? "selected":"";?>>Show All</option>
				<option value="0" <?php echo (isset($_GET['filterBy']) && $_GET['filterBy'] == 0 || !isset($_GET['filterBy'])) ? "selected":"";?>>Unapproved</option>
				<option value="1" <?php echo (isset($_GET['filterBy']) && $_GET['filterBy'] == 1) ? "selected":"";?>>Approved</option>
			</select>
			<input type='hidden' name='page' id='page' value='askme.php' />
			<input type='submit' id='filter' name='filter' value='Filter' />
			</form>
			</div>
	<?php

	askme_admin_print_list($sql, $start, $limit);


	//print paging
	echo "<div class='wrap'>";
	echo "<table>";
	if($start > 0)
	{
		print "<tr><td><a href='" . $_SERVER['PHP_SELF'] . "?page=askme.php&filterBy=" . $_GET['filterBy'] . "&start=" . $start . "'><font face='Verdana' size='2'>PREV</font></a>";
	}

	echo "</td><td align=center width='30%'>";
	$i=0;
	$j=1;
	for($i=0;$i < $numrows;$i=$i+$limit)
	{

		if($i <> $start)
		{
			echo " <a href='" . $_SERVER['PHP_SELF'] . "?page=askme.php&filterBy=" . $_GET['filterBy'] . "&start=" . $i . "'><font face='Verdana' size='2'>" . $j . "</font></a> ";
		}
		else
		{
			echo "<span style='color:#14568A;'>" . $j . "</span>";
		} /// Current page is not displayed as link and given font color blue
		$j=$j+1;
	}

	echo "</td><td align='right' width='30%'>";

	if($start <= $numrows - $limit)
	{
		print "<a href='" . $_SERVER['PHP_SELF'] . "?page=askme.php&filterBy=" . $_GET['filterBy'] . "&start=" . ($start + $limit) . "'><font face='Verdana' size='2'>NEXT</font></a>";
	}
		echo "</td></tr></table></div>";
}//askme_admin_get_questions()

function askme_admin_print_list($sql, $start, $limit)
{
	global $wpdb;
	if (!$start)
		$start = 0;
	$questions = $wpdb->get_results($sql . " ORDER BY approved, date_entered DESC limit " . $start . ", " . $limit);

	if(is_array($questions) && !empty($questions))
	{
    	?>
		<!-- JS FUNCTIONS FOR CHECKBOXES -->
		<script>
		function checkUncheckAll(theElement)
		/*
			Check/uncheck all checkboxes in the form.
		*/
		{
			var theForm = theElement.form, z = 0;
			while(theForm[z])
			{
				if(theForm[z].type == 'checkbox' && theForm[z].name != 'checkall')
					theForm[z].checked = theElement.checked;
				z++;
			}
		}

		function determineFormAction(el, action, target)
		/*
			Change form action that el is part of and submit that form.
		*/
		{
			if(typeof(target) == "undefined" || target == null)
			{
				target = false;
			}

			var theForm = el.form;

			theForm.action = action;
			if(target)
				theForm.target = target;
			theForm.submit();
		}

		function isAnythingChecked(el)
		/*
			Goes through form where el is and returns true
			if at least one checkbox is checked.
		*/
		{
			var theForm = el.form;
			var z = 0;

			while(theForm[z])
			{
				if(theForm[z].type == 'checkbox' && theForm[z].checked && theForm[z].name != 'checkall')
					 return true;
				z++;
			}

			return false;
		}
		</script>
		<!-- JS FUNCTIONS FOR CHECKALL END -->

    	<?php
	echo '<div class="wrap">';
	echo '<form action="" method="post" name="questions" id="questions">';
	echo "<table>
			<tr style=\"background-color: #6DA6D1;\">
				<th scope=row><input type=\"checkbox\" name=\"checkall\" onclick=\"checkUncheckAll(this);\"></th>
				<th scope=row>Question</th>
				<th scope=row>Answer</th>
				<th scope=row>Name</th>
				<th scope=row>Url</th>
				<th scope=row>Date</th>
				<th scope=row>Approved?</th>
				<th scope=row>Action</th>

			</tr>";



    foreach ($questions as $question)
    {
    	$class = ('alternate' == $class) ? '' : 'alternate';

	echo "<tr class='" . $class . "' valign='top'>";
	?>
	<td><input type="checkbox" name="questionid[]" value="<?php echo $question->question_id; ?>"></td>
	<td><?php echo stripslashes(substr($question->question, 0, 300));?></td>
    	<td><?php echo stripslashes(substr($question->answer, 0, 300))?></td>
	<td><?php echo (!($name = $question->user)) ? "Anonymous" : $name = $question->user;?></td>
    	<td><?php echo $question->url; ?></td>
	<td><?php echo $question->date_entered; ?></td>
	<td><?php echo ($question->approved) == 0 ? "No" : "Yes";?></td>
	<td><a href="<?php echo $_SERVER['PHP_SELF'];?>?page=askme.php&action=edit&id=<?php echo $question->question_id;?>&filterBy=<?php echo $_GET['filterBy']; ?>&start=<?php echo $_GET['start'];?>">Edit</a> | <a href='<?php echo $_SERVER['PHP_SELF'];?>?page=askme.php&filterBy=<?php echo $_GET['filterBy']; ?>&start=<?php echo $_GET['start'];?>&action=delete&id=<?php echo $question->question_id;?>' onclick='return confirm("Are you sure you want to delete this question");'>Delete</a></td></tr>
    	<?php
    }
	?>
	</table>
	<input type="hidden" name="action" value="deleteall" />
	<input type="button" name="Delete" value="Delete Selected" onclick="if(!isAnythingChecked(this)) { alert('You must select at least one checkbox.');} else { document.questions.submit(); }" />
	</form>
	</div>
	<?php
}
else
{
	echo "<div class='wrap'>There are no questions in the database at the moment.</div>";
}
}//askme_admin_print_list($sql)


function askme_admin_display_form($id)
{
	global $wpdb;
	$question = $wpdb->get_row("SELECT question, answer, user, email, url, date_entered,wants_return_email, approved FROM ".TABLE_AM_QUESTIONS." WHERE question_id = " . $id);
?>
	<div class="wrap">
	<form name="edit" method="post" action=''>
	<div id="editQuestion">
	    <fieldset id="questiondiv">
	      Question
		  <div><textarea rows="5" cols="10" name="askme_question" tabindex="1" id="content"><?php echo stripslashes($question->question); ?></textarea></div>
	    </fieldset>

	 <br />
	<fieldset id="answerdiv">
		Answer
	<div><textarea rows="5" cols="10" name="askme_answer" tabindex="2" id="content"><?php echo stripslashes($question->answer); ?></textarea></div>
</fieldset>
<fieldset id="userdiv">
      Name
	  <div><input type="text" name="askme_name" size="30" tabindex="3" value="<?php echo stripslashes($question->user); ?>" id="askme_name" /></div>
    </fieldset>
    <fieldset id="emaildiv">
	      Email
		  <div><input type="text" name="askme_email" size="30" tabindex="4" value="<?php echo $question->email; ?>" id="askme_email" /></div>
    </fieldset>
    <fieldset id="urldiv">
	      URL
		  <div><input type="text" name="askme_url" size="30" tabindex="5" value="<?php echo $question->url; ?>" id="askme_url" /></div>
    </fieldset>
    <fieldset id="datediv">
	      Date Entered
		  <div><input type="text" name="askme_date" size="30" tabindex="6" value="<?php echo $question->date_entered; ?>" id="askme_date" /></div>
    </fieldset>
    <fieldset id="approveddiv">
	      Approved:
		  <div><input type="checkbox" name="askme_approved" tabindex="7" <?php if ($question->approved){echo "checked";} ?>" id="askme_approved" /></div>
    </fieldset>
    <input type="hidden" id="askme_id" name="askme_id" value="<?php echo $_GET['id']; ?>" />
    <input type="hidden" id="wants_return_email" name="wants_return_email" value="<?php echo $question->wants_return_email; ?>" />
    <input type="submit" name="submit" id="submit" value="Edit" />
</div>
</form>
</div>
<?php
}//askme_admin_display_form($id)


function askme_admin_settings()
{
	global $wpdb;
	$settings = $wpdb->get_row("SELECT Email, PerPage, PerPagePublic, FormAction FROM ".TABLE_AM_SETTINGS." LIMIT 1");

	?>
	<div class="wrap">
		<div><a href="<?php echo $SERVER['PHP_SELF'];?>?page=askme.php">Back to Question list</a></div>
		<h2>Update Settings</h2>
		<form action="" method="post" name="edit">
		<div id="editSettings">
		<fieldset id="emaildiv">Email Address
			<div><input type="text" name="f_settings[Email]" size="30" tabindex="3" value="<?php echo stripslashes($settings->Email); ?>" id="askme_email" /></div>
		</fieldset>
	    	<fieldset id="perpagediv">Admin Per Page
			<div><input type="text" name="f_settings[PerPage]" size="6" tabindex="4" value="<?php echo $settings->PerPage; ?>" id="askme_perpage" /></div>
		</fieldset>
	    	<fieldset id="perpagediv">Public Per Page
			<div><input type="text" name="f_settings[PerPagePublic]" size="6" tabindex="4" value="<?php echo $settings->PerPagePublic; ?>" id="askme_perpage" /></div>
		</fieldset>
	    	<fieldset id="formactiondiv">Form action
			<div><input type="text" name="f_settings[FormAction]" size="6" tabindex="4" value="<?php echo $settings->FormAction; ?>" id="askme_formaction" /></div>
		</fieldset>
	    	<input type="submit" name="submit" id="submit" value="Edit"/> <input type="button" value="Cancel" onclick='self.location="options-general.php?page=askme.php"' />
		<input type="hidden" name="f_settings[action]" value="yes" />
		</div>
		</form>
	</div>
	<?php
}//askme_admin_settings()

function askme_admin_delete_question($id)
{
	global $wpdb;
	$sql = "DELETE FROM ".TABLE_AM_QUESTIONS." WHERE question_id = '$id'";

	$wpdb->query($sql);
	echo ("<div class='updated fade-ff0000'><p><strong>You have successfully deleted your question.</strong></p></div>");

}//askme_admin_delete_question($id)

function askme_admin_delete_question_all($id)
{
	global $wpdb;

	$sql = "DELETE FROM ".TABLE_AM_QUESTIONS;
	$sql .= " WHERE 1>2";
	for($i=0; $i <count($id); $i++)
	{
		$sql .= " OR question_id = ".$id[$i];
	}

	$wpdb->query($sql);
	echo ("<div class='updated fade-ff0000'><p><strong>You have successfully deleted selected questions.</strong></p></div>");

}//askme_admin_delete_question_all($id)


function askme_admin_edit_question($id)
{
	global $wpdb;
	$sql = "UPDATE ".TABLE_AM_QUESTIONS." SET " .
			"question = '" . addslashes($_POST['askme_question']) . "', " .
			"answer = '" . addslashes($_POST['askme_answer']) . "', " .
			"user = '" . addslashes($_POST['askme_name']) . "', " .
			"email = '" . $_POST['askme_email'] .  "', " .
			"url = '" . $_POST['askme_url'] .  "', " .
			"date_entered = '" . $_POST['askme_date'] . "', ";
	$approved = 0;
	if ($_POST['askme_approved'])
	{
		$approved = 1;
	}
	$sql .= "approved = " . $approved . " WHERE question_id = " . $id;
//	echo $sql;
	$wpdb->query($sql);
	echo ("<div class='updated fade-ff0000'><p><strong>You have successfully updated your question.</strong></p></div>");

	//if the person wants to be notified of a response, send email
	if($_POST['wants_return_email']==1 && $approved)
	{
		$sql = "SELECT Email, FormAction FROM ".TABLE_AM_SETTINGS." LIMIT 1";
		$settings = $wpdb->get_row($sql);

		$email = $settings->Email; // Your email address
		$action = $settings->FormAction; // form action

		$sql = "select option_value from wp_options where option_name = 'blogname'";
		$result = $wpdb->get_row($sql);
		$blogname = $result->option_value; //this will be the blog name

		$sql = "select option_value from wp_options where option_name = 'siteurl'";
		$result = $wpdb->get_row($sql);
		$siteurl = $result->option_value; //this will be the site url

		$headers = "From: " . $email . "\r\n";
		$subject = "Your question has been answered at: " . $blogname;
		$to = $_POST['askme_email'];
		$message = "Thank you for asking a question, I have answered it now. Please visit my site to see the answer:\n\n ";
		$message .= $siteurl . $action;


		mail($to,$subject,$message,$headers);

	}//end email

}//askme_admin_edit_question($id)

function askme_admin_edit_settings($data)
{
	global $wpdb;
	$sql = "UPDATE ".TABLE_AM_SETTINGS." SET";
	$sql .= " Email = '".$data["Email"]."'";
	if(empty($data["PerPage"]))
		$sql .= ", PerPage = 10";
	else
		$sql .= ", PerPage = '".$data["PerPage"]."'";
	if(empty($data["PerPagePublic"]))
		$sql .= ", PerPagePublic = 10";
	else
		$sql .= ", PerPagePublic = '".$data["PerPagePublic"]."'";


	$wpdb->query($sql);
	echo ("<div class='updated fade-ff0000'><p><strong>You have successfully updated your 'Ask me' settings.</strong></p></div>");
}//askme_admin_edit_settings($data)

function askme_options_page ()
{
	if($_POST['submit'])
	{
		if($_POST["f_settings"]["action"] == "yes")
		{
			//call function to update settings
			askme_admin_edit_settings($_POST["f_settings"]);
			askme_admin_settings();
		}
		else
		{
			askme_admin_edit_question($_POST['askme_id']);
			askme_admin_get_questions();
		}
	}
	else if ($_POST['action'] == "deleteall")
	{
		//we need to delete bunch of G&A
		askme_admin_delete_question_all($_POST["questionid"]);
		askme_admin_get_questions();
	}
	else if ($_GET['action'] == 'edit')
	{
		askme_admin_display_form($_GET['id']);
	}
	else if ($_GET['action'] == 'delete')
	{
		askme_admin_delete_question($_GET['id']);
		askme_admin_get_questions();
	}
	else if ($_GET['settings'] == 'yes')
	{
		askme_admin_settings();
	}
	else
	{
		askme_admin_get_questions();
	}
}//askme_options_page ()

add_action('admin_menu', 'askme_add_options_page');

add_action('activate_askme.php','askme_install');

?>