<?php
/*
Plugin Name: TF FAQ
Plugin URI: http://tffaq.twentyfiveautumn.com
Description: An enhanced frequently asked questions plugin. A fork of the FAQ You version 2.0.1. plugin. By twentyfiveautumn.com and released under the MIT license.
Version: 0.0.3
Author: ray peaslee
Author URI: http://twentyfiveautumn.com
License: MIT
License URI: http://opensource.org/licenses/MIT
*/

require_once( ABSPATH.'wp-admin/includes/plugin.php' );

register_uninstall_hook( __FILE__, 'tffaq_uninstall' );

function tffaq_uninstall() {
	global $wpdb;

	if (function_exists('is_multisite') && is_multisite()) {
		// check if it is a network activation - if so, run the activation function for each blog id
		if (isset($_GET['networkwide']) && ($_GET['networkwide'] == 1)) {
			$old_blog = $wpdb->blogid;
			// Get all blog ids
			$blogids = $wpdb->get_col($wpdb->prepare("SELECT blog_id FROM $wpdb->blogs"));
			foreach ($blogids as $blog_id) {
				switch_to_blog($blog_id);
				$this->_tffaq_uninstall();
			}
			switch_to_blog($old_blog);
			return;
		}
	}
	$this->_tffaq_uninstall();
}

function _tffaq_uninstall(){

	global $wpdb;
	$db_table_name = $wpdb->prefix . "faq_questions";
	$sql = 'DROP TABLE IF EXISTS '.$db_table_name;
	$wpdb->query( $sql );
	$db_table_name = $wpdb->prefix . "faq_categories";
	$sql = 'DROP TABLE IF EXISTS '.$db_table_name;
	$wpdb->query( $sql );
	delete_option( "faq_version" );
	delete_option( "faq-email" );

}	/**** end uninstall function	*****/

/*****	FRONT END	*****/

function faq_show($questions) {
	$new_content = '';

		foreach($questions as $question) {
			$new_content .= '<p class="faq-question"><a onclick="faq_showQuestion('.$question->id.');" style="cursor: pointer;">'.$question->question.'</a></p>';
			$new_content .= '<p class="faq-answer" id="faq-question-'.$question->id.'" style="display: none;">" '.$question->answer.' "</p>';
	}
	return $new_content;
}


function add_faq_front_js() {

	wp_register_script( 'faq_frontend', plugins_url( 'js/faq-frontend.js' , __FILE__ ) );
	wp_enqueue_script( 'faq_frontend' );
}

add_action('wp_head','add_faq_front_js',0);

function add_faq_front_css() {

	wp_register_style( 'faq_frontend', plugins_url( 'css/front.css' , __FILE__ ) );
	wp_enqueue_style( 'faq_frontend' );
}

add_action('wp_head','add_faq_front_css',0);

/*****	END FRONT END	*****/

//add the admin panel
function add_faq_adminpanel() {
	global $menu, $submenu;

$minLevelGeneral = 'Editor';

	add_menu_page(__('FAQ','faq-you'), __('FAQ','faq-you'), $minLevelGeneral , 'faq-questions', 'faq_questions', plugins_url('images/faq-icon.png' , __FILE__ ));
	add_submenu_page('faq-questions', __('Questions','faq-you'), __('Questions','faq-you'), $minLevelGeneral , 'faq-questions', 'faq_questions');

		$questions = faq_get_empty_questions();

		if(count($questions) > 0) {
			$showMenu = '<strong>'.__('Unanswered questions','faq-you').' ('.count($questions).')</strong>';
		} else {
			$showMenu = __('Unanswered questions','faq-you');
		}
		add_submenu_page('faq-questions', __('Unanswered questions','faq-you'), $showMenu, $minLevelGeneral , 'faq-askquestions', 'faq_askquestions');

	add_submenu_page('faq-questions', __('Categories','faq-you'), __('Categories','faq-you'), $minLevelGeneral , 'faq-categories', 'faq_categories');
	add_submenu_page('faq-questions', __('Options'), __('Options'), 10, 'faq-options', 'faq_options');
}
add_action('admin_menu', 'add_faq_adminpanel');

/*****	add to the editor	*****/

function init_faq_editor() {

global $current_user;

	if(!current_user_can('editor')) {return;}


	if(get_user_option("rich_editing") == "true") {
		add_filter("mce_external_plugins", "add_faq_editor");
		add_filter("mce_buttons", "register_faq_editor");
	}
}
add_action("init", "init_faq_editor");

function register_faq_editor($buttons) {
	array_push($buttons, "separator", "faq");
	return $buttons;
}

function add_faq_editor($plug_array) {
	$plug_array['faq'] = plugins_url('/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__)).'js/faq-add-tinymce.js');
	return $plug_array;
}

//the admin panel for question creation
function faq_options() {
	require_once('faq-actions.php');
	require_once('faq-options.php');
}

function faq_askquestions() {
	require_once('faq-askquestions.php');
}

function faq_questions() {
	require_once('faq-actions.php');

	if(empty($_GET['insert'])) {
		if(empty($_GET['edit'])) {
			require_once('faq-manage-questions.php');
		} else {
			require_once('faq-add-question.php');
		}
	} else {
		require_once('faq-insert-category.php');
	}
}

function faq_categories() {
	require_once('faq-actions.php');

	if(empty($_GET['edit'])) {
		require_once('faq-manage-categories.php');
	} else {
		require_once('faq-add-category.php');
	}
}

/*****	add some css to the admin side	*****/

function faq_add_css() {
	wp_register_style( 'faq_admin', plugins_url( 'css/faq-style.css' , __FILE__ ) );
	wp_enqueue_style( 'faq_admin' );
}
add_action('admin_init','faq_add_css');

/*****	faq functions	*****/

function faq_get_first_category() {
	global $wpdb;
	$first_cat = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."faq_categories ORDER BY id ASC LIMIT 0,1");
	return $first_cat[0];
}

function faq_get_questions($category) {
	global $wpdb;
	$questions = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."faq_questions WHERE category='".$category."' AND answer!='' ORDER BY id DESC");
	return $questions;
}

function faq_get_empty_questions() {
	global $wpdb;
	$questions = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."faq_questions WHERE answer='' ORDER BY id DESC");
	return $questions;
}

function faq_get_categories() {
	global $wpdb;
	$categories = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."faq_categories ORDER BY id ASC");
	return $categories;
}

function faq_get_category($id) {
	global $wpdb;
	$the_cat = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."faq_categories WHERE id='".$id."'");
	return $the_cat[0];
}

function faq_category_by_name($category) {
	global $wpdb;
	$the_cat = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."faq_categories WHERE category='".$category."'");
	return $the_cat[0];
}

function faq_get_question($id) {
	global $wpdb;
	$the_question = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."faq_questions WHERE id='".$id."'");
	return $the_question[0];
}

/***** new shortcodes	*****/

/***** start faq_search	*****/

function faq_search() {

		global $wpdb;

		$string = isset($_POST['faq-search'])? esc_attr($_POST['faq-search']):'';

		$new_content = '<div class="faq-search">';
		$new_content .= '<form method="post">';
		$new_content .= '<h4 class="faq-header">'.__('Search FAQ','faq-you').'</h4>';
		$new_content .= '<p><input type="text" name="faq-search" id="faq-search" value="'.$string.'" /> ';

		$new_content .= '<select name="faq-cat">';
					$categories = faq_get_categories();
					$new_content .= '<option value="0">'.__('All','faq-you').'</value>';
					foreach($categories as $category) {

		$selected = isset($_POST['faq-cat']) == absint($category->id)? ' selected="selected"':''	;

						$new_content .= '<option'.$selected.' value="'.$category->id.'">'.$category->category.'</option>';
					}
				$new_content .= '</select>';

				$new_content .= '<input type="submit" name="faq-search-btn" id="faq-search-btn" value="'.__('Search','faq-you').'" /></p>';
			$new_content .= '</form></div>';

		if(!isset($_POST['faq-search'])) {

			return $new_content;

		} else {

		/*****	do the search	*****/

		$questions =(!empty($_POST['faq-cat']))? $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."faq_questions WHERE category='".$_POST['faq-cat']."' AND question LIKE '%".$string."%' OR answer LIKE '%".$string."%'") : $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."faq_questions WHERE question LIKE '%".$string."%' OR answer LIKE '%".$string."%'");

		/***** end do the search	*****/

			if($questions && strlen($string) > 2) {
				$new_content .= faq_show($questions);
			} else {
				$new_content .= __('no search results were found: ','faq-you').'<strong>'.$string.'</strong>.';
			}
			$new_content .= '';

			$content = $new_content;
		}

	return $content;
}

add_shortcode('faq_search', 'faq_search');

/***** end faq_search	*****/

function faq_ask() {

		global $wpdb;

			if(isset($_POST['new-question']) and isset($_POST['question'])) {

				$question = esc_textarea($_POST['question']);
				$category = absint($_POST['category']);
				$table_name = $wpdb->prefix.'faq_questions';

        		$wpdb->insert( $table_name, array( 'category' => $category, 'question' => $question, 'answer' => '' ) );

				$message = __('Your question has been submitted. Thank you.','faq-you');

				$faq_email = get_option('faq-email');

				if($faq_email) {	/*****	send e-mail notification that a question was asked	*****/

					$headers  = 'MIME-Version: 1.0' . "\r\n";
					$headers .= 'Content-type: text/html; charset="UTF-8"' . "\r\n";
					$cat = faq_get_category($category);
					$subject = $cat->category.' '.__('question','faq-you');
					$email = '
					<html>
					<body>
						<h2>&quot;'.$cat->category.'&quot; '.__('question','faq-you').'</h2>
						<p>'.__('Someone asked this question on: ','faq-you').' <a href="'.get_option('siteurl').'">'.get_option('siteurl').'</a></p>
						<p><strong>'.__('Category').'</strong>: '.$cat->category.'</p>
						<p><strong>'.__('Question').'</strong>: '.$question.'</p>
						<p><a href="'.admin_url('admin.php?page=faq-askquestions','admin').'">click here to answer the question</a></p>
					</body>
					</html>
					';

					wp_mail($faq_email,$subject,$email,$headers);
				}

			}
			$new_content = '<div class="ask-question">';
			$new_content .= '<form method="post" id="questionForm" name="questionForm">';
				$new_content .= '<h4 class="faq-header">'.__('Ask a question','faq-you').'</h4>';

				if(isset($message)) {
					$new_content .= '<p class="faq-message">'.$message.'</p>';
				} else {
					$new_content .= '<p class="faq-ask-label"><label for="category">'.__('Select a Category for your question.','faq-you').'</label></p>';
					$new_content .= '<p><select name="category" class="required">';
					$categories = faq_get_categories();
					foreach($categories as $category) {
						$new_content .= '<option value="'.$category->id.'">'.$category->category.'</option>';
					}
					$new_content .= '</select></p>';

					$new_content .= '<p class="faq-ask-label"><label for="question">'.__('What is your question?','faq-you').'</label></p>';
					$new_content .= '<p><textarea name="question" id="question" class="required"></textarea></p>';

					$new_content .= '<input type="submit" name="new-question" value="'.__('Ask','faq-you').'" />';
				}
			$new_content .= '</form></div>';

			return $new_content;
	}	/*****	end [faq_ask]	*****/

add_shortcode('faq_ask', 'faq_ask');

function faq_one_category( $atts, $content = null ) {
   extract( shortcode_atts( array(
      'id' => '1',
      ), $atts ) );

	$new_content = '';
	$category = faq_get_category($id);
	$new_content .= '<div class="faq-category"><h4 class="faq-header">'.$category->category.'</h4>';
	$questions = faq_get_questions($category->id);
	$new_content .= faq_show($questions);
	$new_content .= '</div>';

	return $new_content;
}

add_shortcode('faq', 'faq_one_category');

/***** get category by name	*****/

function faq_category_name( $atts, $content = null ) {
   extract( shortcode_atts( array(
      'name' => 'General',
      ), $atts ) );

	$new_content = '';
	$category = faq_category_by_name($name);
	$new_content .= '<div class="faq-category"><h4 class="faq-header">'.$category->category.'</h4>';
	$questions = faq_get_questions($category->id);
	$new_content .= faq_show($questions);
	$new_content .= '</div>';

	return $new_content;
}

add_shortcode('faq_name', 'faq_category_name');


function faq_all_category(){
	$categories = faq_get_categories();
	$new_content = '';
	foreach($categories as $category) {
	$category = faq_get_category($category->id);
	$new_content .= '<div class="faq-category"><h4 class="faq-header">'.$category->category.'</h4>';
	$questions = faq_get_questions($category->id);
	$new_content .= faq_show($questions);
	$new_content .= '</div>';
	}
return $new_content;
}

add_shortcode('faq_all', 'faq_all_category');

/*****	end new shortcodes	*****/

/*****	end FAQ functions	*****/

/*****	install and create the database tables	*****/

register_activation_hook( __FILE__, 'tffaq_install' );

function tffaq_install() {
   global $wpdb;

	if (function_exists('is_multisite') && is_multisite()) {
		// check if it is a network activation - if so, run the activation function for each blog id
		if (isset($_GET['networkwide']) && ($_GET['networkwide'] == 1)) {
	                $old_blog = $wpdb->blogid;
			// Get all blog ids
			$blogids = $wpdb->get_col($wpdb->prepare("SELECT blog_id FROM $wpdb->blogs"));
			foreach ($blogids as $blog_id) {
				switch_to_blog($blog_id);
				$this->_tffaq_install();
			}
			switch_to_blog($old_blog);
			return;
		}
	}
	$this->_tffaq_install();
}

function _tffaq_install() {

   global $wpdb;

   $table_name = $wpdb->prefix . "faq_questions";
   if($wpdb->get_var("show tables like '$table_name'") != $table_name) {

      $sql = "CREATE TABLE " . $table_name . " (
	  id mediumint(9) NOT NULL AUTO_INCREMENT,
	  category int(9) DEFAULT '0' NOT NULL,
	  question text NOT NULL,
	  answer text NOT NULL,
	  UNIQUE KEY id (id)
	);";

      require_once(ABSPATH.'wp-admin/includes/upgrade.php');
      dbDelta($sql);
    }

   $table_name = $wpdb->prefix . "faq_categories";
   if($wpdb->get_var("show tables like '$table_name'") != $table_name) {

      $sql = "CREATE TABLE " . $table_name . " (
	  id mediumint(9) NOT NULL AUTO_INCREMENT,
	  category VARCHAR(50) NOT NULL,
	  UNIQUE KEY id (id)
	);";

      require_once(ABSPATH.'wp-admin/includes/upgrade.php');
      dbDelta($sql);

      $insert = "INSERT INTO ".$table_name." (category) "."VALUES ('".__('General','faq-you')."')";
      $results = $wpdb->query( $insert );
    }

    /***** update the version	*****/
		$tffaq_version = "0.0.3";
		if(!add_option("tffaq_version",$tffaq_version)) {
		update_option("tffaq_version",$tffaq_version);
	}
}

add_action( 'wpmu_new_blog', 'tf_new_blog', 10, 6);

function tf_new_blog($blog_id, $user_id, $domain, $path, $site_id, $meta ) {
	global $wpdb;

	if ( ! function_exists( 'is_plugin_active_for_network' ) ) {
	   require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
	   }

	if (is_plugin_active_for_network('tf-faq/faq.php')) {
		$old_blog = $wpdb->blogid;
		switch_to_blog($blog_id);
		_tffaq_install();
		switch_to_blog($old_blog);
	}
}

/*****	show category dropdown	*****/

function faq_category_dropdown() {
?>
    <select name="faq_category" id="faq_category" onchange="window.location='?page=faq-questions&amp;cat='+this.value">
    	<?php
			global $cur_category;
			$categories = faq_get_categories();
			foreach($categories as $category) {
				$selected = '';
				if($category->category == $cur_category->category) $selected = ' selected="selected" ';
				echo '<option'.$selected.' value="'.$category->id.'">'.$category->category.'</option>';
			}
		?>
    </select>
<?php
}

/*****	show editors	*****/

function faq_categoryname_meta_box() {
?>
		<?php
			$category_id = 0;

			if(isset($_GET['id'])) {
				$category_id = $_GET['id'];
				}

			global $edit_category;
			if($category_id) $edit_category = faq_get_category($category_id);
		?>
	<input type="hidden" name="faq_category_id" value="<?php echo $category_id?>" />
    <input type="text" name="faq_category_name" value="

    <?php
    if(isset($edit_category)) {
    echo $edit_category->category;
    }
    ?>
    " class="regular-text" />
<?php
}

function faq_category_meta_box() {
?>
    <select name="faq_category" id="faq_category">
    	<?php
			global $cur_category;
			$categories = faq_get_categories();
			foreach($categories as $category) {
				$selected = '';
				if($category->category == $cur_category->category) $selected = ' selected="selected" ';
				echo '<option'.$selected.' value="'.$category->id.'">'.$category->category.'</option>';
			}

			$question_id = 0;
			if($_GET['id']) $question_id = $_GET['id'];

			global $edit_question;
			if($question_id) $edit_question = faq_get_question($question_id);
		?>
    </select>
	<input type="hidden" name="faq_question_id" value="<?php echo $question_id?>" />
<?php
}

function faq_question_meta_box() {
	global $edit_question;
	?>
    <textarea id="excerpt" name="faq_question">
    <?php
    if(isset($edit_question)) {
	    echo $edit_question->question;
    	}
    ?>
    </textarea>
    <?php
}

function faq_answer_meta_box() {
	global $edit_question;
?>
    <textarea id="content" name="faq_answer">
    <?php
    if(isset($edit_question)) {
    echo $edit_question->answer;
    }
    ?>
    </textarea>

<?php
}

/*****	Add translation	*****/

function faq_loadtranslation() {
	load_plugin_textdomain('faq-you', false,'tf-faq/languages');
}

add_action('init', 'faq_loadtranslation');
?>