<?php

/********************************************************************************************************************************
*
*  Note moderator (/inc/plugins/notemoderator.php)
*  Author: Krzysztof "Supryk" Supryczyński
*  Copyright: © 2013 - 2016 @ Krzysztof "Supryk" Supryczyński @ All rights reserved
*  
*  Website: 
*  Description: Allow moderator to add simple note to each post.
*
********************************************************************************************************************************/
/********************************************************************************************************************************
*
* This file is part of "Note moderator" plugin for MyBB.
* Copyright © 2013 - 2016 @ Krzysztof "Supryk" Supryczyński @ All rights reserved
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
********************************************************************************************************************************/

if(!defined("IN_MYBB"))
{
	die("Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined.");
}

$plugins->add_hook("admin_config_settings_manage", "notemoderator_admin_lang_load");
$plugins->add_hook("admin_config_settings_change", "notemoderator_admin_lang_load");
$plugins->add_hook("admin_config_settings_start", "notemoderator_admin_lang_load");
$plugins->add_hook("admin_style_templates_set", "notemoderator_admin_lang_load");
$plugins->add_hook("admin_settings_print_peekers", "notemoderator_admin_settings_print_peekers");
$plugins->add_hook("admin_page_output_footer", "notemoderator_admin_page_output_footer");
$plugins->add_hook("postbit", "notemoderator_postbit");
$plugins->add_hook("postbit_prev", "notemoderator_postbit");
$plugins->add_hook("editpost_end", "notemoderator_editpost_end");
$plugins->add_hook("datahandler_post_validate_post", "notemoderator_datahandler_post_validate_post");
$plugins->add_hook("editpost_do_editpost_end", "notemoderator_editpost_do_editpost_end");
$plugins->add_hook("xmlhttp_update_post", "notemoderator_xmlhttp_update_post");
$plugins->add_hook("class_moderation_delete_post_start", "notemoderator_class_moderation_delete_post_start");
$plugins->add_hook("class_moderation_merge_posts", "notemoderator_class_moderation_merge_posts");
$plugins->add_hook("class_moderation_delete_thread_start", "notemoderator_class_moderation_delete_thread_start");
$plugins->add_hook("xmlhttp", "notemoderator_xmlhttp");
$plugins->add_hook("global_start", "notemoderator_global_start");
$plugins->add_hook("pre_output_page", "notemoderator_pre_output_page");

function notemoderator_info()
{
    global $lang;
    $lang->load("config_notemoderator");
	
	return array(
		"name"				=> $lang->notemoderator,
		"description"		=> $lang->notemoderator_desc,
		"website"			=> "",
		"author"			=> "Krzysztof \"Supryk\" Supryczyński",
		"authorsite"		=> "",
		"version"			=> "2.0",
		"compatibility"	=> "1801,1812,1803,1804,1805,1806,1807,1808,1809,1810",
		"codename"		=> "note_moderator",
	);
}

function notemoderator_is_installed()
{
    global $db;
	
	return $db->num_rows($db->simple_select("settinggroups", "*", "name = \"notemoderator\""));
}

function notemoderator_install()
{
	global $db, $lang, $cache, $mybb;
    $lang->load("config_notemoderator");
	
	if(!$db->table_exists("notemoderator"))
	{
		$db->write_query("CREATE TABLE ".TABLE_PREFIX."notemoderator (
			`nmid` int unsigned NOT NULL AUTO_INCREMENT,
			`pid` int unsigned NOT NULL DEFAULT '0',
			`uid` int unsigned NOT NULL DEFAULT '0',
			`message` text NOT NULL,
			`type` int unsigned NOT NULL DEFAULT '0',
			`dateline` int unsigned NOT NULL DEFAULT '0',
			KEY `pid` (`pid`),
			PRIMARY KEY (`nmid`)
		) ENGINE=MyISAM ".$db->build_create_table_collation().";");
	}
	
	if(!$db->index_exists("notemoderator", "pid"))
	{
		$db->write_query("ALTER TABLE ".TABLE_PREFIX."notemoderator ADD INDEX `pid` (`pid`)");
	}
	
	$max_disporder = $db->fetch_field($db->simple_select("settinggroups", "MAX(disporder) AS max_disporder"), "max_disporder");
	
	$settinggroup = array(
	//	"gid"					=> "",
		"name" 				=> "notemoderator", 
		"title" 				=> $db->escape_string($lang->setting_group_notemoderator),
		"description"		=> $db->escape_string($lang->setting_group_notemoderator_desc),
		"disporder" 		=> $max_disporder + 1,
		"isdefault"			=> "0",
	);
	
	$gid = $db->insert_query("settinggroups", $settinggroup);
	
	$settings = array();
	
	$settings[] = array(
	//	"sid"					=> "",
		"name"				=> "notemoderator_onoff",
		"title"					=> $db->escape_string($lang->setting_notemoderator_onoff),
		"description"		=> $db->escape_string($lang->setting_notemoderator_onoff_desc),
		"optionscode"	=> "onoff",
		"value"				=> "1",
		"disporder"		=> "1",
		"gid"					=> $gid,
		"isdefault"			=> "0",
	);
	
	$options = "select\n";
	$options .= "note_author=".$db->escape_string($lang->setting_notemoderator_pm_sender_note_author)."\n";
    $options .= "username=".$db->escape_string($lang->setting_notemoderator_pm_sender_username)."\n";
    $options .= "anonymous=".$db->escape_string($lang->setting_notemoderator_pm_sender_anonymous)."\n";
	
	$settings[] = array(
	//	"sid"					=> "",
		"name"				=> "notemoderator_pm_sender",
		"title"					=> $db->escape_string($lang->setting_notemoderator_pm_sender),
		"description"		=> $db->escape_string($lang->setting_notemoderator_pm_sender_desc),
		"optionscode"	=> $options,
		"value"				=> "0",
		"disporder"		=> "2",
		"gid"					=> $gid,
		"isdefault"			=> "0",
	);

	$settings[] = array(
	//	"sid"					=> "",
		"name"				=> "notemoderator_pm_username",
		"title"					=> $db->escape_string($lang->setting_notemoderator_pm_username),
		"description"		=> $db->escape_string($lang->setting_notemoderator_pm_username_desc),
		"optionscode"	=> "text",
		"value"				=> $mybb->user['username'],
		"disporder"		=> "3",
		"gid"					=> $gid,
		"isdefault"			=> "0",
	);
	
	$settings[] = array(
	//	"sid"					=> "",
		"name"				=> "notemoderator_allowhtml",
		"title"					=> $db->escape_string($lang->setting_notemoderator_allowhtml),
		"description"		=> $db->escape_string($lang->setting_notemoderator_allowhtml_desc),
		"optionscode"	=> "onoff",
		"value"				=> "0",
		"disporder"		=> "4",
		"gid"					=> $gid,
		"isdefault"			=> "0",
	);
	
	$settings[] = array(
	//	"sid"					=> "",
		"name"				=> "notemoderator_allowmycode",
		"title"					=> $db->escape_string($lang->setting_notemoderator_allowmycode),
		"description"		=> $db->escape_string($lang->setting_notemoderator_allowmycode_desc),
		"optionscode"	=> "onoff",
		"value"				=> "1",
		"disporder"		=> "5",
		"gid"					=> $gid,
		"isdefault"			=> "0",
	);
	
	$settings[] = array(
	//	"sid"					=> "",
		"name"				=> "notemoderator_allowsmilies",
		"title"					=> $db->escape_string($lang->setting_notemoderator_allowsmilies),
		"description"		=> $db->escape_string($lang->setting_notemoderator_allowsmilies_desc),
		"optionscode"	=> "onoff",
		"value"				=> "1",
		"disporder"		=> "6",
		"gid"					=> $gid,
		"isdefault"			=> "0",
	);
	
	$settings[] = array(
	//	"sid"					=> "",
		"name"				=> "notemoderator_allowimgcode",
		"title"					=> $db->escape_string($lang->setting_notemoderator_allowimgcode),
		"description"		=> $db->escape_string($lang->setting_notemoderator_allowimgcode_desc),
		"optionscode"	=> "onoff",
		"value"				=> "1",
		"disporder"		=> "7",
		"gid"					=> $gid,
		"isdefault"			=> "0",
	);
	
	$settings[] = array(
	//	"sid"					=> "",
		"name"				=> "notemoderator_allowvideocode",
		"title"					=> $db->escape_string($lang->setting_notemoderator_allowvideocode),
		"description"		=> $db->escape_string($lang->setting_notemoderator_allowvideocode_desc),
		"optionscode"	=> "onoff",
		"value"				=> "0",
		"disporder"		=> "8",
		"gid"					=> $gid,
		"isdefault"			=> "0",
	);

	$db->insert_query_multiple("settings", $settings);
	
	rebuild_settings();
	
	$templategroup = array(
	//	"gid"			  		=> "",
        "prefix"       		=> "notemoderator",
        "title"            		=> $db->escape_string("<lang:notemoderator_templates>"),
    );
	
    $db->insert_query("templategroups", $templategroup);
	
	$templates = array();
	
	$templates[] = array(
	//	"tid"			 	  	=> "",
		"title" 				=> "notemoderator",
		"template" 			=> $db->escape_string('<tr>
	<td class="trow2" valign="top"><strong>{$lang->notemoderator_message}:</strong><br />
		<label><input type="radio" name="notemoderatortype" {$notemoderator_normal} value="1" style="vertical-align: middle;" /> {$lang->notemoderator_normal}</label><br />
		<label><input type="radio" name="notemoderatortype" {$notemoderator_information} value="2" style="vertical-align: middle;" /> {$lang->notemoderator_information}</label><br />
		<label><input type="radio" name="notemoderatortype" {$notemoderator_warn} value="3" style="vertical-align: middle;" /> {$lang->notemoderator_warn}</label><br /><br /><br /><br /><br /><br /><br />
		{$notemoderator_pm}
		{$notemoderator_delete}
	</td>
	<td class="trow2">
		<input type="hidden" name="nmid" value="{$nmid}" />
		<input type="hidden" name="modaction" value="notemoderator" />
		<textarea name="notemoderator" id="notemoderator" rows="10" cols="70" tabindex="3">{$notemoderator_message}</textarea>
			{$codebuttonsmod}
	</td>
</tr>'),
		"sid" 				=> "-2",
		"version" 			=> "2.0",
		"status" 			=> "",
		"dateline" 			=> TIME_NOW,
	);
	
	$templates[] = array(
	//	"tid"			 	 	=> "",
		"title" 				=> "notemoderator_new_note_pm",
"template" 		=> $db->escape_string('<label><input type="checkbox" class="checkbox" name="notemoderator_new_note_pm" value="1" style="vertical-align: middle;" {$notemoderator_new_note_pm_check} /> {$lang->notemoderator_pm}</label>'),
		"sid" 				=> "-2",
		"version" 			=> "2.0",
		"status" 			=> "",
		"dateline" 			=> TIME_NOW,
	);
	
	$templates[] = array(
	//	"tid"			 	  	=> "",
		"title" 				=> "notemoderator_update_note_pm",
"template" 		=> $db->escape_string('<label><input type="checkbox" class="checkbox" name="notemoderator_update_note_pm" value="1" style="vertical-align: middle;" {$notemoderator_update_note_pm_check} /> {$lang->notemoderator_pm}</label><br />'),
		"sid" 				=> "-2",
		"version" 			=> "2.0",
		"status" 			=> "",
		"dateline" 			=> TIME_NOW,
	);
	
	$templates[] = array(
	//	"tid"			 	  	=> "",
		"title" 				=> "notemoderator_delete",
"template" 		=> $db->escape_string('<label><input type="checkbox" class="checkbox" name="notemoderatordelete" value="1" style="vertical-align: middle;" {$notemoderator_deletecheck} /> {$lang->notemoderator_delete}</label>'),
		"sid" 				=> "-2",
		"version" 			=> "2.0",
		"status" 			=> "",
		"dateline" 			=> TIME_NOW,
	);
	
	$templates[] = array(
	//	"tid"			 	 	=> "",
		"title" 				=> "notemoderator_post",
		"template" 		=> $db->escape_string('<div id="notemoderator_post_{$post[\'pid\']}" style="width: 100%;">{$notemoderator}</div>'),
		"sid" 				=> "-2",
		"version" 			=> "2.0",
		"status" 			=> "",
		"dateline" 			=> TIME_NOW,
	);
	
	$templates[] = array(
	//	"tid"			 	 	=> "",
		"title" 				=> "notemoderator_normal",
		"template" 		=> $db->escape_string('<span id="notemoderator_{$note[\'nmid\']}" class="notemoderator"><div class="notemoderator_note_normal"><b>{$note[\'information\']}{$notemoderator_buttons}</b><br />{$note[\'message\']}</div></span>'),
		"sid" 				=> "-2",
		"version" 			=> "2.0",
		"status" 			=> "",
		"dateline" 			=> TIME_NOW,
	);
	
	$templates[] = array(
	//	"tid"			 	  	=> "",
		"title" 				=> "notemoderator_information",
		"template" 		=> $db->escape_string('<span id="notemoderator_{$note[\'nmid\']}" class="notemoderator"><div class="notemoderator_note_information"><b>{$note[\'information\']}{$notemoderator_buttons}</b><br />{$note[\'message\']}</div></span>'),
		"sid" 				=> "-2",
		"version" 			=> "2.0",
		"status" 			=> "",
		"dateline" 			=> TIME_NOW,
	);
	
	$templates[] = array(
	//	"tid"			 	 	=> "",
		"title" 				=> "notemoderator_warn",
		"template" 		=> $db->escape_string('<span id="notemoderator_{$note[\'nmid\']}" class="notemoderator"><div class="notemoderator_note_warn"><b>{$note[\'information\']}{$notemoderator_buttons}</b><br />{$note[\'message\']}</div></span>'),
		"sid" 				=> "-2",
		"version" 			=> "2.0",
		"status" 			=> "",
		"dateline" 			=> TIME_NOW,
	);
	
	$templates[] = array(
	//	"tid"			 	  	=> "",
		"title" 				=> "notemoderator_buttons",
		"template" 		=> $db->escape_string('<div class="float_right"><strong><a href="{$mybb->settings[\'bburl\']}/editpost.php?pid={$post[\'pid\']}&modaction=notemoderator&nmid={$note[\'nmid\']}" class="notemoderator_button_edit" title="{$lang->notemoderator_e_title}">{$lang->notemoderator_e}</a><a href="javascript: notemoderator.deletenote({$post[\'pid\']}, {$note[\'nmid\']});" title="{$lang->notemoderator_d_title}">{$lang->notemoderator_d}</a></strong></div>'),
		"sid" 				=> "-2",
		"version" 			=> "2.0",
		"status" 			=> "",
		"dateline" 			=> TIME_NOW,
	);
	
	$templates[] = array(
	//	"tid"			 	 	=> "",
		"title" 				=> "notemoderator_postbit_button",
		"template" 			=> $db->escape_string('<a href="editpost.php?pid={$post[\'pid\']}" id="edit_post_{$post[\'pid\']}" title="{$lang->postbit_edit}" class="postbit_edit"><span>{$lang->postbit_button_edit}</span></a>
<div id="edit_post_{$post[\'pid\']}_popup" class="popup_menu" style="display: none;"><div class="popup_item_container"><a href="javascript:;" class="popup_item quick_edit_button" id="quick_edit_post_{$post[\'pid\']}">{$lang->postbit_quick_edit}</a></div><div class="popup_item_container"><a href="editpost.php?pid={$post[\'pid\']}" class="popup_item">{$lang->postbit_full_edit}</a></div><div class="popup_item_container"><a href="editpost.php?pid={$post[\'pid\']}&modaction=notemoderator" class="popup_item">{$lang->notemoderator_moderate}</a></div></div>
<script type="text/javascript">
// <!--
	if(use_xmlhttprequest == "1")
	{
		$("#edit_post_{$post[\'pid\']}").popupMenu();
	}
// -->
</script>'),
		"sid" 				=> "-2",
		"version" 			=> "2.0",
		"status" 			=> "",
		"dateline" 			=> TIME_NOW,
	);
	
	$db->insert_query_multiple("templates", $templates);

	$style = "form #notemoderator {
    width: 500px;
}

.notemoderator {
	width: 100%;
}

.notemoderator_note_normal {
	background-image: url(images/notemoderator/normal.png);
	background-repeat: no-repeat;
	background-attachment: scroll;
	background-position: 8px 12px;
	background-color: #ffffff;
	border: 1px solid #d4d4d4;
	padding: 10px 10px 10px 30px;
	border-radius: 6px 6px 6px 6px;
	color: #515151;
	line-height: 150%;
	font-size: 13px;
	margin-top: 7px;
	clear: both;
}

.notemoderator_note_information {
	background-image: url(images/notemoderator/information.png);
	background-repeat: no-repeat;
	background-attachment: scroll;
	background-position: 8px 12px;
	background-color: #ebfcdf;
	border: 1px solid #a4cfa4;
	padding: 10px 10px 10px 30px;
	border-radius: 6px 6px 6px 6px;
	color: #0e440e;
	line-height: 150%;
	font-size: 13px;
	margin-top: 7px;
	clear: both;
}

.notemoderator_note_warn {
	background-image: url(images/notemoderator/warn.png);
	background-repeat: no-repeat;
	background-attachment: scroll;
	background-position: 8px 12px;
	background-color: #f3e3e6;
	border: 1px solid #e599aa;
	padding: 10px 10px 10px 30px;
	border-radius: 6px 6px 6px 6px;
	color: #80001c;
	line-height: 150%;
	font-size: 13px;
	margin-top: 7px;
	clear: both;
}

.notemoderator_button_edit {
	margin-right: 10px;
}";
	
	$stylesheet = array(
	//	"sid"         		=> "",
		"name"         		=> "notemoderator.css",
		"cachefile"		=> "notemoderator.css",
		"tid"         			=> "1",
		"attachedto"   	=> "showthread.php|editpost.php",
		"stylesheet"   	=> $db->escape_string($style),
		'lastmodified' 	=> TIME_NOW
	);

	$db->insert_query("themestylesheets", $stylesheet);
	
	require_once MYBB_ADMIN_DIR."inc/functions_themes.php";

	cache_stylesheet(1, "notemoderator.css", $style);
	update_theme_stylesheet_list(1, false, true);
	
	if(function_exists('myalerts_is_activated') && myalerts_is_activated())
	{
		$alertTypeManager = MybbStuff_MyAlerts_AlertTypeManager::createInstance($db, $cache);

		$alertType = new MybbStuff_MyAlerts_Entity_AlertType();
		$alertType->setCanBeUserDisabled(false);
		$alertType->setCode('notemoderator');
		$alertType->setEnabled(true);

		$alertTypeManager->add($alertType);
	}
}

function notemoderator_uninstall()
{
    global $db, $mybb, $cache, $page, $lang;
	$lang->load("config_notemoderator");
	
	if($mybb->request_method != "post")
	{
		$page->output_confirm_action("index.php?module=config-plugins&action=deactivate&uninstall=1&plugin=notemoderator", $lang->notemoderator_uninstall_message, $lang->notemoderator_uninstall);
	}
	
	if($db->table_exists("notemoderator") && !isset($mybb->input['no']))
	{
		$db->drop_table("notemoderator");
	}
	
	$db->delete_query("settinggroups", "name = \"notemoderator\"");
	$db->delete_query("settings", "name LIKE \"notemoderator%\"");
	rebuild_settings();
	$db->delete_query("templategroups", "prefix = \"notemoderator\"");
	$db->delete_query("templates", "title LIKE \"notemoderator%\"");
	$db->delete_query("themestylesheets", "name= \"notemoderator.css\"");
		
	require_once MYBB_ADMIN_DIR."inc/functions_themes.php";
    
    $query = $db->simple_select("themes", "tid");
    while($theme = $db->fetch_array($query))
    {
        @unlink(MYBB_ROOT."cache/themes/theme{$theme['tid']}/notemoderator.css");
        @unlink(MYBB_ROOT."cache/themes/theme{$theme['tid']}/notemoderator.min.css");
        update_theme_stylesheet_list($theme['tid'], false, true); 
    }
	
	if(function_exists('myalerts_is_activated') && myalerts_is_activated())
	{
		$alertTypeManager = MybbStuff_MyAlerts_AlertTypeManager::createInstance($db, $cache);

		$alertTypeManager->deleteByCode('notemoderator');
	}
}

function notemoderator_activate()
{		
	notemoderator_deactivate();
	
	find_replace_templatesets("editpost", '#'.preg_quote('{$editreason}').'#', '{$editreason}{$notemoderator}');
	find_replace_templatesets("editpost", '#'.preg_quote('</head>').'#', '<script type="text/javascript" src="{$mybb->asset_url}/jscripts/notemoderator.js"></script>'."\n".'<script type="text/javascript">'."\n".'<!--'."\n\t".'lang.notemoderator_delete_error = "{$lang->notemoderator_delete_error}";'."\n\t".'lang.notemoderator_delete_confirm = "{$lang->notemoderator_delete_confirm}";'."\n\t".'lang.notemoderator_has_been_deleted = "{$lang->notemoderator_has_been_deleted}";'."\n".'// -->'."\n".'</script>'."\n".'</head>');
	find_replace_templatesets("showthread", '#'.preg_quote('</head>').'#', '<script type="text/javascript" src="{$mybb->asset_url}/jscripts/notemoderator.js"></script>'."\n".'<script type="text/javascript">'."\n".'<!--'."\n\t".'lang.notemoderator_delete_error = "{$lang->notemoderator_delete_error}";'."\n\t".'lang.notemoderator_delete_confirm = "{$lang->notemoderator_delete_confirm}";'."\n\t".'lang.notemoderator_has_been_deleted = "{$lang->notemoderator_has_been_deleted}";'."\n".'// -->'."\n".'</script>'."\n".'</head>');
}

function notemoderator_deactivate()
{
	include MYBB_ROOT."/inc/adminfunctions_templates.php";
	
	find_replace_templatesets('editpost', '#' . preg_quote('{$notemoderator}') . '#', '', 0);
	find_replace_templatesets('editpost', '#' . preg_quote('<script type="text/javascript" src="{$mybb->asset_url}/jscripts/notemoderator.js"></script>'."\n".'<script type="text/javascript">'."\n".'<!--'."\n\t".'lang.notemoderator_delete_error = "{$lang->notemoderator_delete_error}";'."\n\t".'lang.notemoderator_delete_confirm = "{$lang->notemoderator_delete_confirm}";'."\n\t".'lang.notemoderator_has_been_deleted = "{$lang->notemoderator_has_been_deleted}";'."\n".'// -->'."\n".'</script>'."\n") . '#', '', 0);
	find_replace_templatesets('showthread', '#' . preg_quote('<script type="text/javascript" src="{$mybb->asset_url}/jscripts/notemoderator.js"></script>'."\n".'<script type="text/javascript">'."\n".'<!--'."\n\t".'lang.notemoderator_delete_error = "{$lang->notemoderator_delete_error}";'."\n\t".'lang.notemoderator_delete_confirm = "{$lang->notemoderator_delete_confirm}";'."\n\t".'lang.notemoderator_has_been_deleted = "{$lang->notemoderator_has_been_deleted}";'."\n".'// -->'."\n".'</script>'."\n") . '#', '', 0);
}

function notemoderator_admin_lang_load()
{
    global $lang;
    $lang->load("config_notemoderator");
} 

function notemoderator_admin_settings_print_peekers(&$peekers)
{
    $peekers[] = 'new Peeker($("#setting_notemoderator_pm_sender"), $("#row_setting_notemoderator_pm_username"), /username/, false)';
} 

function notemoderator_admin_page_output_footer()
{	
	        echo '<link rel="stylesheet" href="../jscripts/select2/select2.css">
	<script type="text/javascript" src="../jscripts/select2/select2.min.js?ver=1804"></script>
	<style>
	.select2-container .select2-choice > .select2-chosen {
    width: 300px;
}
	</style>
	<script type="text/javascript">
	<!--
	
	$("#setting_notemoderator_pm_username").select2({
		placeholder: "Search user",
		minimumInputLength: 2,
		maximumSelectionSize: 1,
		multiple: false,
		ajax: { // instead of writing the function to execute the request we use Select2\'s convenient helper
			url: "../xmlhttp.php?action=get_users",
			dataType: \'json\',
			data: function (term, page) {
				return {
					query: term, // search term
				};
			},
			results: function (data, page) { // parse the results into the format expected by Select2.
				// since we are using custom formatting functions we do not need to alter remote JSON data
				return {results: data};
			}
		},
		initSelection: function(element, callback) {
			var query = $(element).val();
			if (query !== "") {
				$.ajax("../xmlhttp.php?action=get_users&getone=1", {
					data: {
						query: query
					},
					dataType: "json"
				}).done(function(data) { callback(data); });
			}
		},
	});

  	$(\'[for=setting_notemoderator_pm_username]\').click(function(){
		$("#setting_notemoderator_pm_username").select2(\'open\');
		return false;
	});
	// -->
	</script>';
}

function notemoderator_postbit(&$post)
{
	global $db, $mybb, $lang, $templates, $theme, $parser, $fid, $pids, $pid;
	$lang->load("notemoderator");
		
	if($mybb->settings['notemoderator_onoff'] != "1")
	{
		return;
	}
	
	if(is_moderator($fid, "caneditposts") && THIS_SCRIPT == "showthread.php" || is_moderator($fid, "caneditposts") && THIS_SCRIPT == "newreply.php" && !$mybb->get_input("processed"))
	{
		eval("\$post['button_edit'] = \"".$templates->get("notemoderator_postbit_button")."\";");
	}
		
	static $notes;
	static $notes_check = false;
		
	if(!$notes_check)
	{			
		if(empty($post['pid']))
		{
			$post['pid'] = $pid;
		}
		
		if(isset($pids))
		{
			$pids = $pids;
		}
		else
		{
			$pids = "pid='{$post['pid']}'";
		}
		
		if($mybb->get_input('notemoderator') != "" && $mybb->get_input('notemoderatordelete', 1) != "1")
		{
			$notes[$post['pid']][] = array(
				"pid" => $post['pid'],
				"uid" => $mybb->user['uid'],
				"username" => $mybb->user['username'],
				"usergroup" => $mybb->user['usergroup'],
				"displaygroup" => $mybb->user['displaygroup'],
				"type" => $mybb->get_input('notemoderatortype', 1),
				"message" => $mybb->get_input('notemoderator'),
				"dateline" => TIME_NOW,
				"prev" => "1",
			);
		}
		
		$query = $db->query("
			SELECT nm.*, u.uid, u.username, u.usergroup, u.displaygroup
			FROM ".TABLE_PREFIX."notemoderator nm
			LEFT JOIN ".TABLE_PREFIX."users u ON (nm.uid=u.uid)
			WHERE {$pids} ORDER BY nm.dateline DESC");
		while($note = $db->fetch_array($query))
		{
			$notes[$note['pid']][$note['nmid']] = array(
				"nmid" => $note['nmid'],
				"pid" => $note['pid'],
				"uid" => $note['uid'],
				"username" => $note['username'],
				"usergroup" => $note['usergroup'],
				"displaygroup" => $note['displaygroup'],
				"type" => $note['type'],
				"message" => $note['message'],
				"dateline" => $note['dateline'],
			);
		}
			
		$notes_check = true;
	}
	
	if($mybb->get_input('nmid', 1) != "" && isset($notes[$post['pid']]) && array_key_exists($mybb->get_input('nmid', 1), $notes[$post['pid']]))
	{			
		unset($notes[$post['pid']][$mybb->get_input('nmid', 1)]);
	}
		
	if(isset($notes[$post['pid']]))
	{			
	    foreach($notes[$post['pid']] as $note)
		{
			$note['username'] = format_name($note['username'], $note['usergroup'], $note['displaygroup']);
			$note['profilelink'] = build_profile_link($note['username'], $note['uid']);
			$note['dataline'] = my_date("relative", $note['dateline']);
			$note['information'] = $lang->sprintf($lang->notemoderator_text, $note['profilelink'], $note['dataline']);
			
			$parser_options = array(
				"allow_html" => $mybb->settings['notemoderator_allowhtml'],
				"allow_mycode" => $mybb->settings['notemoderator_allowmycode'],
				"allow_smilies" => $mybb->settings['notemoderator_allowsmilies'],
				"allow_imgcode" => $mybb->settings['notemoderator_allowimgcode'],
				"allow_videocode" => $mybb->settings['notemoderator_allowvideocode'],
				"me_username" => $mybb->user['username'],
				"filter_badwords" => 1,
			);
					
			$note['message'] = $parser->parse_message($note['message'], $parser_options);
			
			if(is_moderator($fid, "caneditposts") && $note['prev'] != "1")
			{
				eval("\$notemoderator_buttons = \"".$templates->get("notemoderator_buttons")."\";");
			}
				
			if($note['type'] == "1")
			{
				eval("\$notemoderator .= \"".$templates->get("notemoderator_normal")."\";");
			}
			elseif($note['type'] == "2")
			{

				eval("\$notemoderator .= \"".$templates->get("notemoderator_information")."\";");
			}
			elseif($note['type'] == "3")
			{
				eval("\$notemoderator .= \"".$templates->get("notemoderator_warn")."\";");
			}
		}
	}
	
	eval("\$post['message'] .= \"".$templates->get("notemoderator_post")."\";");
}

function notemoderator_editpost_end()
{
	global $db, $mybb, $lang, $templates, $fid, $notemoderator, $post, $pid, $post_errors, $pid, $tid, $forum;
	$lang->load("notemoderator");
	
	if($mybb->settings['notemoderator_onoff'] != "1")
	{
		return;
	}
	
	if(!is_moderator($fid, "caneditposts"))
	{
		return;
	}
	
	if($mybb->settings['use_xmlhttprequest'] != "1")
	{
		$mybb->input['modaction'] = "notemoderator";
	}
	
	if($mybb->get_input("modaction") != "notemoderator")
	{
		return;
	}
	
	if(empty($post['pid']))
	{
		$post['pid'] = $pid;
	}
	
	if($mybb->settings['bbcodeinserter'] != "0" && $forum['allowmycode'] != "0" && $mybb->user['showcodebuttons'] != "0")
	{
		$codebuttonsmod = build_mycode_inserter("notemoderator", 1);
	}
	
	$query = $db->simple_select("notemoderator", "*", "pid = {$post['pid']} and nmid = ".$mybb->get_input("nmid", 1)."");
	if($db->num_rows($query))
	{
		$note = $db->fetch_array($query);
		
		if($note['type'] == "1")
		{
			$notemoderator_normal = "checked=\"checked\"";
		}
		elseif($note['type'] == "2")
		{
			$notemoderator_information  = "checked=\"checked\"";
		}
		elseif($note['type'] == "3")
		{
			$notemoderator_warn = "checked=\"checked\"";
		}
				
		$notemoderator_message = $note['message'];
		$nmid = $note['nmid'];
		
		if($post_errors || $mybb->get_input("processed") == "1")
		{
			$notemoderator_message = $mybb->get_input('notemoderator');
			
			if($mybb->get_input('notemoderatortype', 1) == "1")
			{
				$notemoderator_normal = "checked=\"checked\"";
			}
			elseif($mybb->get_input('notemoderatortype', 1) == "2")
			{
				$notemoderator_information  = "checked=\"checked\"";
			}
			elseif($mybb->get_input('notemoderatortype', 1) == "3")
			{
				$notemoderator_warn = "checked=\"checked\"";
			}
			
			if($mybb->get_input("notemoderatordelete", 1) == "1")
			{
				$notemoderator_deletecheck = "checked=\"checked\"";
			}
			
			if($mybb->get_input("notemoderator_pdate_note_pm", 1) == "1")
			{
				$notemoderator_update_note_pm_check = "checked=\"checked\"";
			}
			
		}
		eval("\$notemoderator_pm = \"".$templates->get("notemoderator_update_note_pm")."\";");
		eval("\$notemoderator_delete = \"".$templates->get("notemoderator_delete")."\";");
	}
	else
	{
		if(!$post_errors && $mybb->get_input("processed") != "1")
		{
			$notemoderator_normal = "checked=\"checked\"";
			$notemoderator_new_note_pm_check = "checked=\"checked\"";
		}
		else
		{
			$notemoderator_message = $mybb->get_input('notemoderator');
			
			if($mybb->get_input('notemoderatortype', 1) == "1")
			{
				$notemoderator_normal = "checked=\"checked\"";
			}
			elseif($mybb->get_input('notemoderatortype', 1) == "2")
			{
				$notemoderator_information  = "checked=\"checked\"";
			}
			elseif($mybb->get_input('notemoderatortype', 1) == "3")
			{
				$notemoderator_warn = "checked=\"checked\"";
			}
			
			if($mybb->get_input("notemoderator_new_note_pm", 1) == "1")
			{
				$notemoderator_new_note_pm_check = "checked=\"checked\"";
			}
		}
		
		eval("\$notemoderator_pm = \"".$templates->get("notemoderator_new_note_pm")."\";");
	}
			
	eval("\$notemoderator = \"".$templates->get("notemoderator")."\";");
}

function notemoderator_datahandler_post_validate_post()
{
	global $mybb, $posthandler;
	
	if($mybb->settings['notemoderator_onoff'] != "1")
	{
		return;
	}
	
	if($mybb->get_input('notemoderatordelete', 1) != '1' && $mybb->get_input("nmid", 1) != "0" && trim_blank_chrs($mybb->get_input("notemoderator")) == "")
	{
		$posthandler->set_error("no_notemoderator");
	}
}

function notemoderator_xmlhttp_update_post()
{
	global $mybb, $post, $templates, $db, $lang, $parser;
	$lang->load("notemoderator");
	
	if($mybb->settings['notemoderator_onoff'] != "1")
	{
		return;
	}
	
	$templatelist = "postbit_editedby,notemoderator_buttons,notemoderator_normal,notemoderator_information,notemoderator_warn,notemoderator_post";
	$templates->cache($db->escape_string($templatelist));
	
	$query = $db->query("
		SELECT nm.*, u.uid, u.username, u.usergroup, u.displaygroup
		FROM ".TABLE_PREFIX."notemoderator nm
		LEFT JOIN ".TABLE_PREFIX."users u ON (nm.uid=u.uid)
		WHERE nm.pid = {$post['pid']} ORDER BY nm.dateline DESC");
	if($db->num_rows($query))
	{			
	    while($note = $db->fetch_array($query))
		{
			$note['username'] = format_name($note['username'], $note['usergroup'], $note['displaygroup']);
			$note['profilelink'] = build_profile_link($note['username'], $note['uid']);
			$note['dataline'] = my_date("relative", $note['dateline']);
			$note['information'] = $lang->sprintf($lang->notemoderator_text, $note['profilelink'], $note['dataline']);
			
			$parser_options = array(
				"allow_html" => $mybb->settings['notemoderator_allowhtml'],
				"allow_mycode" => $mybb->settings['notemoderator_allowmycode'],
				"allow_smilies" => $mybb->settings['notemoderator_allowsmilies'],
				"allow_imgcode" => $mybb->settings['notemoderator_allowimgcode'],
				"allow_videocode" => $mybb->settings['notemoderator_allowvideocode'],
				"me_username" => $mybb->user['username'],
				"filter_badwords" => 1,
			);
					
			$note['message'] = $parser->parse_message($note['message'], $parser_options);
			
			if(is_moderator($post['fid'], "caneditposts") && $note['prev'] != "1")
			{
				eval("\$notemoderator_buttons = \"".$templates->get("notemoderator_buttons")."\";");
			}
				
			if($note['type'] == "1")
			{
				eval("\$notemoderator .= \"".$templates->get("notemoderator_normal")."\";");
			}
			elseif($note['type'] == "2")
			{

				eval("\$notemoderator .= \"".$templates->get("notemoderator_information")."\";");
			}
			elseif($note['type'] == "3")
			{
				eval("\$notemoderator .= \"".$templates->get("notemoderator_warn")."\";");
			}
		}
		
		eval("\$post_notes = \"".$templates->get("notemoderator_post")."\";");
		
		if($post_notes)
		{		
			$post['message'] .= str_replace(array("\r", "\n"), "", $post_notes);
		}
	}
}

function notemoderator_editpost_do_editpost_end()
{
	global $db, $mybb, $post, $thread, $session, $lang, $fid, $posthandler;
	$lang->load("notemoderator");
	
	if($mybb->settings['notemoderator_onoff'] != "1")
	{
		return;
	}
	
	if(!is_moderator($fid, "caneditposts"))
	{
		return;
	}
	
	if(trim_blank_chrs($mybb->get_input('notemoderator')) == "" && $mybb->get_input('notemoderatordelete', 1) != '1')
	{
		return;
	}
	
	if($mybb->request_method != "post")
	{
		return;
	}

	
	$query = $db->simple_select("notemoderator", "*", "pid = {$post['pid']}  and nmid = ".$mybb->get_input("nmid", 1)."");
	if($db->num_rows($query))
	{
		if($mybb->get_input('notemoderatordelete', 1) == '1')
		{
			$db->delete_query("notemoderator", "pid = {$post['pid']} and nmid = ".$mybb->get_input("nmid", 1)."");
			log_moderator_action(array("pid" => $post['pid'], "subject" => $post['subject']), $lang->notemoderator_deleted);
			
			if(function_exists('myalerts_is_activated') && myalerts_is_activated())
			{
				$alertTypeManager = MybbStuff_MyAlerts_AlertTypeManager::getInstance();
				
				if($alertTypeManager === false)
				{
					$alertTypeManager = MybbStuff_MyAlerts_AlertTypeManager::createInstance($db, $cache);
				}
				
				$alertType = MybbStuff_MyAlerts_AlertTypeManager::getInstance()->getByCode('notemoderator');
				
				if($alertType != null && $alertType->getEnabled())
				{
					$alertManager = MybbStuff_MyAlerts_AlertManager::getInstance();

					if($alertManager === false)
					{
						$alertManager = MybbStuff_MyAlerts_AlertManager::createInstance($mybb, $db, $cache, $plugins, $alertTypeManager);
					}

				//	$query = $db->simple_select("alerts", "id","extra_details LIKE '%\"nmid\":{$mybb->get_input("nmid", 1)}%'");
				//	$alertId = $db->fetch_field($query, 'id');
				//	$alertManager->deleteAlerts(array($alertId));
				//	$db->delete_query("alerts", "extra_details LIKE '%\"nmid\":{$mybb->get_input("nmid", 1)}%'"); // delete
				}
			}
			
			return;
		}
		
		$note = array(
			"uid"				=> $mybb->user['uid'],
			"type"				=> $mybb->get_input('notemoderatortype', 1),
			"message"				=> $db->escape_string(trim_blank_chrs($mybb->get_input('notemoderator'))),
			"dateline"	=> TIME_NOW,
		);
		
		$db->update_query("notemoderator", $note, "pid = {$post['pid']}  and nmid = ".$mybb->get_input("nmid", 1)."");
		
		log_moderator_action(array("pid" => $post['pid'], "subject" => $post['subject']), $lang->notemoderator_edited);
		
	//	if(check_post_permission($post))
	//	{
			if(function_exists('myalerts_is_activated') && myalerts_is_activated())
			{
				$alertTypeManager = MybbStuff_MyAlerts_AlertTypeManager::getInstance();
				
				if($alertTypeManager === false)
				{
					$alertTypeManager = MybbStuff_MyAlerts_AlertTypeManager::createInstance($db, $cache);
				}
				
				$alertType = MybbStuff_MyAlerts_AlertTypeManager::getInstance()->getByCode('notemoderator');
				
				if($alertType != null && $alertType->getEnabled())
				{
					$alertManager = MybbStuff_MyAlerts_AlertManager::getInstance();

					if($alertManager === false)
					{
						$alertManager = MybbStuff_MyAlerts_AlertManager::createInstance($mybb, $db, $cache, $plugins, $alertTypeManager);
					}
					
					$alert = new MybbStuff_MyAlerts_Entity_Alert($post['uid'], $alertType, $post['pid']);
					$alert->setExtraDetails(array('tid' => $post['tid'], 'pid'	=> $post['pid'], 'subject' => $post['subject'], 'nmid' => $mybb->get_input("nmid", 1), 'action' => 'edit'));
					$alertManager->addAlert($alert);
				}
			}
			
			if($mybb->get_input("notemoderator_update_note_pm", 1) == "1")
			{			
				if($note['type'] == "1")
				{
					$notetype = $lang->notemoderator_normal;
				}
				elseif($note['type'] == "2")
				{
					$notetype = $lang->notemoderator_information;
				}		
				elseif($note['type'] == "3")
				{
					$notetype = $lang->notemoderator_warn;
				}
				
				$link = $mybb->settings['bburl']."/".get_post_link($post['pid'], "-1") . "#pid{$post['pid']}";
				$mess = $lang->sprintf($lang->notemoderator_message_update_text, $post['username'], $notetype, $link, $post['subject'], $note['message']);
				
				$pm = array(
					"subject" => $lang->notemoderator_message,
					"message" => $mess,
					"touid" => $post['uid'],
				);
				
				switch($mybb->settings['notemoderator_pm_sender'])
				{
					case "note_author":
						$sender_uid = $mybb->user['uid'];
					break;
					case "username":
						$suser = get_user_by_username(trim($mybb->settings['notemoderator_pm_username']));
						$sender_uid = $suser['uid'];
					break;
					case "anonymous":
						$sender_uid = -1;
					break;
				}
				
				send_pm($pm, $sender_uid, true);
			}
	//	}
	}
	else
	{		
		$note = array(
		//	"nmid"			=> "",
			"pid"				=> $post['pid'],
			"uid"				=> $mybb->user['uid'],
			"message"		=> $db->escape_string(trim_blank_chrs($mybb->get_input('notemoderator'))),
			"type"			=> $mybb->get_input('notemoderatortype', 1),
			"dateline"	=> TIME_NOW,
		);
		
		$noteid = $db->insert_query("notemoderator", $note);
		
		log_moderator_action(array("pid" => $post['pid'], "subject" => $post['subject']), $lang->notemoderator_added);
		
	//	if(check_post_permission($post))
	//	{		
			if(function_exists('myalerts_is_activated') && myalerts_is_activated())
			{
				$alertTypeManager = MybbStuff_MyAlerts_AlertTypeManager::getInstance();
				
				if($alertTypeManager === false)
				{
					$alertTypeManager = MybbStuff_MyAlerts_AlertTypeManager::createInstance($db, $cache);
				}
				
				$alertType = MybbStuff_MyAlerts_AlertTypeManager::getInstance()->getByCode('notemoderator');
				
				if($alertType != null && $alertType->getEnabled())
				{
					$alertManager = MybbStuff_MyAlerts_AlertManager::getInstance();

					if($alertManager === false)
					{
						$alertManager = MybbStuff_MyAlerts_AlertManager::createInstance($mybb, $db, $cache, $plugins, $alertTypeManager);
					}
					
					$alert = new MybbStuff_MyAlerts_Entity_Alert($post['uid'], $alertType, $post['pid']);
					$alert->setExtraDetails(array('pid'	=> $post['pid'], 'subject' => $post['subject'], 'nmid' => $noteid, 'action' => 'add'));
					$alertManager->addAlert($alert);
				}
			}
			
			if($mybb->get_input("notemoderator_new_note_pm", 1) == "1")
			{			
				if($note['type'] == 1)
				{
					$notetype = $lang->notemoderator_normal;
				}
				elseif($note['type'] == 2)
				{
					$notetype = $lang->notemoderator_information;
				}		
				elseif($note['type'] == 3)
				{
					$notetype = $lang->notemoderator_warn;
				}
				
				$link = $mybb->settings['bburl']."/".get_post_link($post['pid'],  "-1") . "#pid{$post['pid']}";
				$mess = $lang->sprintf($lang->notemoderator_message_new_text, $post['username'], $notetype, $link, $post['subject'], $note['message']);
				
				$pm = array(
					"subject" => $lang->notemoderator_message,
					"message" => $mess,
					"touid" => $post['uid'],
				);
				
				switch($mybb->settings['notemoderator_pm_sender'])
				{
					case "note_author":
						$sender_uid = $mybb->user['uid'];
					break;
					case "username":
						$suser = get_user_by_username(trim($mybb->settings['notemoderator_pm_username']));
						$sender_uid = $suser['uid'];
					break;
					case "anonymous":
						$sender_uid = -1;
					break;
				}
				
				send_pm($pm, $sender_uid, true);
			}
	//	}
	}
}

function notemoderator_class_moderation_delete_post_start(&$pid)
{
	global $db;
	
	$db->delete_query("notemoderator", "pid = \"{$pid}\"");
}

function notemoderator_class_moderation_merge_posts(&$arguments)
{
	global $db;

	$pidin = implode(",", $arguments['pids']);	
	$query = $db->simple_select("posts", "pid", "pid IN($pidin)", array('order_by' => 'dateline', 'order_dir' => 'asc', 'limit' => '1'));
	$post = $db->fetch_array($query);
	
	$update_note = array(
		"pid" => $post['pid'],
	);
	
	$db->update_query("notemoderator", $update_note, "pid IN({$pidin}) AND pid != '{$post['pid']}'");
}

function notemoderator_class_moderation_delete_thread_start()
{
	global $db, $thread;
	
	$query = $db->simple_select("posts", "pid", "tid='{$thread['tid']}'");
	$pids = array();
	
	while($post = $db->fetch_array($query))
	{
		$pids[] = $post['pid'];
	}

	if(!empty($pids))
	{
		$pids = implode(',', $pids);
		$db->delete_query("notemoderator", "pid IN ($pids)");
	}
}

function notemoderator_xmlhttp()
{
	global $db, $mybb, $lang, $fid;
	$lang->load("notemoderator");
	
	if($mybb->settings['notemoderator_onoff'] != "1")
	{
		return;
	}
		
	if($mybb->get_input("action") != "deletenote")
	{
		return;
	}
	
	if(!is_moderator($fid, "caneditposts"))
	{
		xmlhttp_error($lang->notemoderator_donied);
	}
		
	if(!verify_post_check($mybb->get_input('my_post_key'), true))
	{
		xmlhttp_error($lang->notemoderator_invalid_post_key);
	}
	
	$pid = $mybb->get_input("pid", 1);
	$nmid = $mybb->get_input("nmid", 1);
	
	$query = $db->simple_select("notemoderator", "*", "pid = {$pid} and nmid = {$nmid}");
	
	if($db->num_rows($query) == "0")
	{
		xmlhttp_error($lang->notemoderator_donied);
	}
	
	$post = get_post($pid);
	$db->delete_query("notemoderator", "pid = {$post['pid']} and nmid = ".$mybb->get_input("nmid", 1)."");
	log_moderator_action(array("pid" => $post['pid'], "subject" => $post['subject']), $lang->notemoderator_deleted);
	
	/*if(function_exists('myalerts_is_activated') && myalerts_is_activated())
	{
		$alertTypeManager = MybbStuff_MyAlerts_AlertTypeManager::getInstance();
		
		if($alertTypeManager === false)
		{
			$alertTypeManager = MybbStuff_MyAlerts_AlertTypeManager::createInstance($db, $cache);
		}
		
		$alertType = MybbStuff_MyAlerts_AlertTypeManager::getInstance()->getByCode('notemoderator');
		
		if($alertType != null && $alertType->getEnabled())
		{
			$alertManager = MybbStuff_MyAlerts_AlertManager::getInstance();

			if($alertManager === false)
			{
				$alertManager = MybbStuff_MyAlerts_AlertManager::createInstance($mybb, $db, $cache, $plugins, $alertTypeManager);
			}

			$query = $db->simple_select("alerts", "id","extra_details LIKE '%\"nmid\":{$nmid}%'");
			$alertId = $db->fetch_field($query, 'id');
			$alertManager->deleteAlerts(array($alertId));
			$db->delete_query("alerts", "extra_details LIKE '%\"nmid\":{$nmid}%'"); // delete
		}
	}*/
	
	echo json_encode(array('pid' => $pid, 'nmid' => $nmid));
	exit;
}

function notemoderator_global_start()
{
	global $mybb, $lang, $cache, $formatterManager, $templatelist;
	$lang->load("notemoderator");
	
	if($mybb->settings['notemoderator_onoff'] != "1")
	{
		return;
	}
	
	if(function_exists('myalerts_is_activated') && myalerts_is_activated())
	{		
		class NoteModerator_AlertFormatter extends MybbStuff_MyAlerts_Formatter_AbstractFormatter
		{
			private $parser;
			
			public function init()
			{
				if(!isset($this->lang->notemoderator))
				{
					$this->lang->load('notemoderator');
				}
				
				require_once MYBB_ROOT . 'inc/class_parser.php';
				$this->parser = new postParser;

				$this->alertTypeName = 'notemoderator';
			}

			public function formatAlert(MybbStuff_MyAlerts_Entity_Alert $alert, array $outputAlert)
			{
				$alertContent = $alert->getExtraDetails();
				if($alertContent['action'] == "add")
				{
					return $this->lang->sprintf($this->lang->myalerts_alert_add_notemoderator, $outputAlert['from_user'], htmlspecialchars_uni($this->parser->parse_badwords($alertContent['subject'])));
				}
				elseif($alertContent ['action'] == "edit")
				{
					return $this->lang->sprintf($this->lang->myalerts_alert_edit_notemoderator, $outputAlert['from_user'], htmlspecialchars_uni($this->parser->parse_badwords($alertContent['subject'])));
				}
			}

			public function buildShowLink(MybbStuff_MyAlerts_Entity_Alert $alert)
			{
				$alertContent = $alert->getExtraDetails();
				return $this->mybb->settings['bburl'] . "/" . get_post_link($alertContent['pid'], $alertContent['tid'])."#pid".$alertContent['pid'];
			}
		}

		if(class_exists("MybbStuff_MyAlerts_AlertFormatterManager") && class_exists("NoteModerator_AlertFormatter"))
		{
			$formatterManager = MybbStuff_MyAlerts_AlertFormatterManager::createInstance($mybb, $lang);

			$formatterManager->registerFormatter(new NoteModerator_AlertFormatter($mybb, $lang, "notemoderator"));
		}
	}
	
	if(in_array(THIS_SCRIPT, explode(", ", "showthread.php")))
	{	
		if(isset($templatelist))
		{
			$templatelist .= ", ";
		}
		
		$templatelist .= "notemoderator_post, notemoderator_normal, notemoderator_information, notemoderator_warn, notemoderator_buttons, notemoderator_postbit_button";
	}
	
	if(in_array(THIS_SCRIPT, explode(", ", "editpost.php")))
	{	
		if(isset($templatelist))
		{
			$templatelist .= ", ";
		}
		
		$templatelist .= "notemoderator, notemoderator_delete, notemoderator_new_note_pm, notemoderator_update_note_pm, notemoderator_post, notemoderator_normal, notemoderator_information, notemoderator_warn, notemoderator_buttons";
	}
}

/********************************************************************************************************************************
*
* Say thanks to plugin author - paste link to author website.
* Please don't remove this code if you didn't make donate.
* It's the only way to say thanks without donate.
*
********************************************************************************************************************************/
function notemoderator_pre_output_page(&$content)
{
    global $session, $thanksSupryk, $lang;
	$lang->load("notemoderator");
        
    if(!isset($thanksSupryk) && $session->is_spider)
    {
        $thx = '<div style="margin:auto; text-align:center;">'.$lang->notemoderator_thanks.'</div></body>';
        $content = str_replace('</body>', $thx, $content);
        $thanksSupryk = true;
    }
}