<?php
/*
Plugin Name: TF FAQ
Plugin URI: http://tffaq.twentyfiveautumn.com
Description: An advanced frequently asked questions plugin by twentyfiveautumn.com and released under the MIT license.
Version: 0.0.7
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);
				_tffaq_uninstall();
			}
			switch_to_blog($old_blog);
			return;
		}
	}
	_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 style="cursor: pointer;" data-options=\'{"id":'.$question->id.'}\' >'.$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_enqueue_script('jquery');
wp_enqueue_script('jquery-ui-core');
wp_enqueue_script('jquery-ui-tabs');

wp_register_script( 'faq_frontend', plugins_url( 'js/faq-frontend.js' , __FILE__ ) );
wp_enqueue_script( 'faq_frontend' );

wp_register_script( 'tfa_jquery_cookie', plugins_url( 'js/jquery.cookie.js' , __FILE__ ),array('jquery') );
wp_enqueue_script( 'tfa_jquery_cookie' );

}

add_action('wp_head','add_faq_front_js',0);

function add_faq_front_css() {

if (file_exists(get_stylesheet_directory().'/tffaq.css')) {
	wp_register_style( 'tf_faq_frontend', get_stylesheet_directory_uri().'/tffaq.css' );
	wp_enqueue_style( 'tf_faq_frontend' );
} else {
    wp_register_style( 'faq_frontend', plugins_url( 'css/front.css' , __FILE__ ) );
	wp_enqueue_style( 'faq_frontend' );
	}

wp_register_style( 'faq_jquery_custom', plugins_url( 'css/jquery-ui-1.8.16.custom.css' , __FILE__ ) );
wp_enqueue_style( 'faq_jquery_custom' );

}

add_action('wp_head','add_faq_front_css',0);

/***** add jQuery validation here *****/

function tf_faq_validation() {

wp_register_script('tf_faq_validation', plugins_url('/js/jquery.validate.js', __FILE__), array('jquery'),'1.8.1');
wp_enqueue_script('tf_faq_validation');

wp_register_script('tf_faq_validation_extra', plugins_url('/js/additional-methods.js', __FILE__), array('jquery','tf_faq_validation'),'1.8.1');
wp_enqueue_script('tf_faq_validation_extra');

wp_register_script('tf_faq_valid_question', plugins_url('/js/valid-question.js', __FILE__), array('jquery','tf_faq_validation','tf_faq_validation_extra'),'0.0.1',true);
wp_enqueue_script('tf_faq_valid_question');

}

/***** end jQuery validation *****/

add_action('wp_head','tf_faq_validation',0);

/*****	END FRONT END	*****/

//add the admin panel
function add_faq_adminpanel() {
	global $menu, $submenu;

$minLevelGeneral = 'edit_plugins';

	add_menu_page(__('FAQ','tf-faq'), __('FAQ','tf-faq'), $minLevelGeneral , 'faq-questions', 'faq_questions', plugins_url('images/faq-icon.png' , __FILE__ ));
	add_submenu_page('faq-questions', __('Questions','tf-faq'), __('Questions','tf-faq'), $minLevelGeneral , 'faq-questions', 'faq_questions');

		$questions = faq_get_empty_questions();

		$showMenu = (count($questions) > 0)? '<strong>'.__('Unanswered questions','tf-faq').' ('.count($questions).')</strong>': __('Unanswered questions','tf-faq');

		add_submenu_page('faq-questions', __('Unanswered questions','tf-faq'), $showMenu, $minLevelGeneral , 'faq-askquestions', 'faq_askquestions');

	add_submenu_page('faq-questions', __('Categories','tf-faq'), __('Categories','tf-faq'), $minLevelGeneral , 'faq-categories', 'faq_categories');
	add_submenu_page('faq-questions', __('Options'), __('Options'), $minLevelGeneral, '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."'");
	if(!empty($the_question[0])) {
	return $the_question[0];
	}
	return;
}

/***** new shortcodes	*****/

/***** start faq_search	*****/

function faq_search() {

global $wpdb;
$string = isset($_POST['faq-search'])? esc_attr($_POST['faq-search']):'';

if(!isset($_POST['faq-search'])) {

$new_content ='';
$new_content .= '
<div class="faq-search">
<form method="post" id="tffaq_search" name="tffaq_search" >
<h4 class="faq-header">'.__('Search FAQ','tf-faq').'</h4>
<input type="text" name="faq-search" id="faq-search" value="'.$string.'" />
<select name="faq-cat" id="faq-cat">';
$categories = faq_get_categories();
$new_content .= '<option value="0">'.__('All','tf-faq').'</option>';

$selected = '';
foreach($categories as $category) {

if(isset($_POST['faq-cat'])){ $selected = $_POST['faq-cat'] == absint($category->id)? ' selected="selected"':''; }

$new_content .= '<option '.$selected.'value="'.$category->id.'">'.$category->category.'</option>';
}

$new_content .= '</select>
<input type="submit" name="faq-search-btn" id="faq-search-btn" value="'.__('Search','tf-faq').'" /></form></div>';

} 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	*****/
$new_content = '';

$new_content .= '<div class="faq-category"><h4 class="faq-header">Search results for: '.$string.'</h4>';

if($questions && strlen($string) > 2) {

	$new_content .= faq_show($questions);
	} else {
	$new_content .= __('no search results were found: ','tf-faq');
	}

unset($string);
	$new_content .= '<a href="">Search Again</a></div>';

}	/***** end if(!isset($_POST['faq-search'])) *****/

return $new_content;

}	/***** end faq_search *****/

add_shortcode('faq_search', 'faq_search');

/***** end faq_search	*****/

function faq_ask() {

		global $wpdb;

			if(isset($_POST['new-question']) and isset($_POST['question'])) {

				$question = wp_kses($_POST['question'],'None');
				$q_email = sanitize_email($_POST['email']);
				$category = absint($_POST['category']);
				$table_name = $wpdb->prefix.'faq_questions';

        		$wpdb->insert( $table_name, array( 'category' => $category, 'question' => $question, 'answer' => '', 'email' => $q_email ) );

				$message = __('Your question has been submitted. Thank you.','tf-faq');

				$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','tf-faq');
					$email = '
					<html>
					<body>
						<h2>&quot;'.$cat->category.'&quot; '.__('question','tf-faq').'</h2>
						<p>'.__('Someone asked this question on: ','tf-faq').' <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 = '';

if(isset($message)) { $new_content .=	'<p class="faq-message">'.$message.'</p>'; }

$new_content .= '

<div class="ask-question">
	<form name="questionForm" id="questionForm" method="post">
		<h4 class="faq-header">'.__('Ask a question','tf-faq').'</h4>
		<p class="faq-ask-label"><label for="category">'.__('Select a Category for your question.','tf-faq').'</label></p>
		<p><select class="required" name="category">';

		$categories = faq_get_categories();
		foreach($categories as $category) {

		$new_content .= '<option value="'.$category->id.'">'.$category->category.'</option>';

		}

		$new_content .= '</select></p>
		<p class="faq-ask-label"><label for="question">'.__('What is your question?','tf-faq').'</label></p>
		<p><textarea class="required" id="question" name="question"></textarea></p>
		<p class="faq-ask-label"><label for="email">'.__('Email address to send the answer to:','tf-faq').'</label></p>
		<p><input type="text" class="required" id="email" name="email"></p>
		<input type="submit" value="'.__('Ask Question','tf-faq').'" id="new-question" name="new-question">
	</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(){
	$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');

function tfa_tabs(){

$new_content = '';

	$new_content .= '<div id="tabs">
		<ul>
			<li><a href="#tabs-1">Frequently Asked Questions</a></li>
			<li><a href="#tabs-2">Search</a></li>
			<li><a href="#tabs-3">Ask A Question</a></li>
		</ul>

		<div id="tabs-1">';

		$new_content .= do_shortcode('[faq_all]');

		$new_content .= '</div>

		<div id="tabs-2" >';

		$new_content .= do_shortcode('[faq_search]');

		$new_content .= '</div>

		<div id="tabs-3">';

		$new_content .= do_shortcode('[faq_ask]');

		$new_content .= '</div>
	</div>';

return $new_content;
}

add_shortcode('tfa_tabs', 'tfa_tabs');

/*****	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);
				_tffaq_install();
			}
			switch_to_blog($old_blog);
			return;
		}
	}
	_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','tf-faq')."')";
      $results = $wpdb->query( $insert );
    }

    /***** update the version	*****/
		$tffaq_version = "0.0.7";
		if(!add_option("tffaq_version",$tffaq_version)) {
		update_option("tffaq_version",$tffaq_version);
	}

	/***** add email column if $tffaq_version is less than 0.0.8 *****/

	if($tffaq_version < "0.0.8"){

	/***** add it if it's not already there *****/

	if(!$wpdb->get_col_info($wpdb->prefix.'faq_questions',4)) {

	$sql = 'ALTER TABLE '.$wpdb->prefix.'faq_questions ADD email VARCHAR(56) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;';

	$wpdb->query($sql);

	}	/***** end if(!$wpdb->get_col_info *****/


	}	/***** end add email column *****/

}

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('tf-faq', false,'tf-faq/languages');
}

add_action('init', 'faq_loadtranslation');
?>