﻿<?php
/** 
* Polish Language File developed by mybboard.pl for New Points 1.4 
* Tłumaczenie: Gigi 
* Poprawki: Ekipa Polskiego Supportu MyBB (mybboard.pl)
* Wersja 1.0
**/

/***************************************************************************
 *
 *   NewPoints plugin (/inc/plugins/newpoints.php)
 *	 Author: Pirata Nervo
 *   Copyright: © 2009-2010 Pirata Nervo
 *   
 *   Website: http://www.mybb-plugins.com
 *
 *   NewPoints plugin for MyBB - A complex but efficient points system for MyBB.
 *
 ***************************************************************************/
 
/****************************************************************************
	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU 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 General Public License for more details.
	
	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
****************************************************************************/

if(!defined("IN_MYBB"))
	die("This file cannot be accessed directly.");
	
if(my_strpos($_SERVER['PHP_SELF'], 'showthread.php'))
{
    global $templatelist;
    if(isset($templatelist))
    {
        $templatelist .= ',';
    }
    $templatelist .= 'newpoints_postbit,newpoints_donate_inline';
}
elseif(my_strpos($_SERVER['PHP_SELF'], 'member.php'))
{
    global $templatelist;
    if(isset($templatelist))
    {
        $templatelist .= ',';
    }
    $templatelist .= 'newpoints_profile';
}
	
define('NEWPOINTS_VERSION', '1.4');

// load plugins and do other stuff
if (defined('IN_ADMINCP'))
{
	$plugins->add_hook('admin_load', 'newpoints_admin_load_hook');
	$plugins->add_hook('admin_newpoints_menu', 'newpoints_admin_menu_hook');
	$plugins->add_hook('admin_newpoints_action_handler', 'newpoints_admin_action_handler_hook');
	$plugins->add_hook('admin_newpoints_permissions', 'newpoints_admin_permissions_hook');
}
else {
	$plugins->add_hook('global_start', 'newpoints_load_plugins');
	
	// postbit
	$plugins->add_hook('postbit', 'newpoints_postbit', 50); // set priority to 50
	
	// member profile
	$plugins->add_hook("member_profile_end", "newpoints_profile");
	
	// per new post
	$plugins->add_hook('datahandler_post_insert_post', 'newpoints_newpost');
	// edit post
	$plugins->add_hook('datahandler_post_update', 'newpoints_editpost');
	$plugins->add_hook('xmlhttp', 'newpoints_editpost_xmlhttp');
	// delete post
	$plugins->add_hook('class_moderation_delete_post', 'newpoints_deletepost');
	
	// per new thread
	$plugins->add_hook('datahandler_post_insert_thread', 'newpoints_newthread');
	// delete thread
	$plugins->add_hook('class_moderation_delete_thread', 'newpoints_deletethread');
	
	// per new poll
	$plugins->add_hook('polls_do_newpoll_process', 'newpoints_newpoll');
	$plugins->add_hook('class_moderation_delete_poll', 'newpoints_deletepoll');
	
	// per new registration
	$plugins->add_hook("member_do_register_end", "newpoints_newreg");
	
	// per poll vote
	$plugins->add_hook('polls_vote_process', 'newpoints_pervote');
	
	// per pm sent
	$plugins->add_hook('private_do_send_end', 'newpoints_pmsent');
	
	// per thread rate
	$plugins->add_hook('ratethread_process', 'newpoints_perrate');
	
	// per page viewed and visit
	$plugins->add_hook('global_end', 'newpoints_perview');
	
	// minimum points to view
	$plugins->add_hook('forumdisplay_end', 'newpoints_blockview');
	$plugins->add_hook('showthread_start', 'newpoints_blockview');
	$plugins->add_hook('editpost_start', 'newpoints_blockview_edit');
	$plugins->add_hook('sendthread_do_sendtofriend_start', 'newpoints_blockview_send');
	$plugins->add_hook('sendthread_start', 'newpoints_blockview_send');
	$plugins->add_hook('archive_forum_start', 'newpoints_blockview_archive');
	$plugins->add_hook('archive_thread_start', 'newpoints_blockview_archive');
	
	// minimum points to post
	$plugins->add_hook('newreply_start', 'newpoints_blockpost');
	$plugins->add_hook('newreply_do_newreply_start', 'newpoints_blockpost');
	$plugins->add_hook('newthread_start', 'newpoints_blockpost');
	$plugins->add_hook('newthread_do_newthread_start', 'newpoints_blockpost');
	
	// Inline moderation
	$plugins->add_hook('moderation_start', 'newpoints_inline_delete');
}

function newpoints_info()
{
	return array(
		"name"			=> "NewPoints",
		"description"	=> "NewPoints to rozbudowany i wydajny system nagradzania dla MyBB.",
		"website"		=> "http://www.consoleaddicted.com",
		"author"		=> "Pirata Nervo",
		"authorsite"	=> "http://www.mybb-plugins.com",
		"version"		=> "1.4",
		"guid" 			=> "152e7f9f32fadb777d58fda000eb7a9e",
		"compatibility" => "16*"
	);
}

function newpoints_install()
{
	global $db, $mybb;
	
	// create tables
	$db->write_query("CREATE TABLE `".TABLE_PREFIX."newpoints_settings` (
	  `sid` int(10) UNSIGNED NOT NULL auto_increment,
	  `plugin` varchar(100) NOT NULL default '',
	  `name` varchar(100) NOT NULL default '',
	  `title` varchar(100) NOT NULL default '',
	  `description` text NOT NULL,
	  `type` text NOT NULL default '',
	  `value` text NOT NULL default '',
	  `disporder` smallint(5) UNSIGNED NOT NULL default '0',
	  PRIMARY KEY  (`sid`)
		) TYPE=MyISAM");
	
	$db->write_query("CREATE TABLE `".TABLE_PREFIX."newpoints_log` (
	  `lid` bigint(30) UNSIGNED NOT NULL auto_increment,
	  `action` varchar(100) NOT NULL default '',
	  `data` text NOT NULL default '',
	  `date` bigint(30) UNSIGNED NOT NULL default '0',
	  `uid` bigint(30) UNSIGNED NOT NULL default '0',
	  `username` varchar(100) NOT NULL default '',
	  PRIMARY KEY  (`lid`)
		) TYPE=MyISAM");
	
	$db->write_query("CREATE TABLE `".TABLE_PREFIX."newpoints_forumrules` (
	  `rid` bigint(30) UNSIGNED NOT NULL auto_increment,
	  `fid` int(10) UNSIGNED NOT NULL default '0',
	  `name` varchar(100) NOT NULL default '',
	  `description` text NOT NULL,
	  `rate` float NOT NULL default '1',
	  `pointsview` DECIMAL(16,2) UNSIGNED NOT NULL default '0',
	  `pointspost` DECIMAL(16,2) UNSIGNED NOT NULL default '0',
	  PRIMARY KEY  (`rid`)
		) TYPE=MyISAM");
	
	$db->write_query("CREATE TABLE `".TABLE_PREFIX."newpoints_grouprules` (
	  `rid` bigint(30) UNSIGNED NOT NULL auto_increment,
	  `gid` int(10) UNSIGNED NOT NULL default '0',
	  `name` varchar(100) NOT NULL default '',
	  `description` text NOT NULL,
	  `rate` float NOT NULL default '1',
	  `pointsearn` DECIMAL(16,2) UNSIGNED NOT NULL default '0',
	  `period` bigint(30) UNSIGNED NOT NULL default '0',
	  `lastpay` bigint(30) UNSIGNED NOT NULL default '0',
	  PRIMARY KEY  (`rid`)
		) TYPE=MyISAM");
	
	// add settings
	newpoints_add_setting('newpoints_main_enabled', 'main', 'NewPoints aktywny?', 'Jeśli chcesz wyłączyć NewPoints, ustaw Nie.', 'yesno', 1, 1);
	newpoints_add_setting('newpoints_main_curname', 'main', 'Waluta', 'Wpisz nazwę dla waluty.', 'text', 'Punkty', 2);
	newpoints_add_setting('newpoints_main_curprefix', 'main', 'Przedrostek kwoty', 'Wpisz ciąg znaków wyświetlany przed kwotą.', 'text', '', 3);
	newpoints_add_setting('newpoints_main_cursuffix', 'main', 'Przyrostek kwoty', 'Wpisz ciąg znaków wyświetlany za kwotą.', 'text', '€', 4);
	newpoints_add_setting('newpoints_main_decimal', 'main', 'Miejsca po przecinku', 'Liczba możliwych do użycia miejsc po przecinku.', 'text', '2', 5);
	newpoints_add_setting('newpoints_main_statsvisible', 'main', 'Statystyki widoczne dla użytkowników?', 'Jeśli nie chcesz, aby użytkownicy mieli możliwość przeglądać statystyki ustaw Nie.', 'yesno', 1, 6);
	newpoints_add_setting('newpoints_main_donationsenabled', 'main', 'Włączyć darowizny?', 'Jeśli nie chcesz udostępnić możliwości przekazywania kwot, ustaw Nie.', 'yesno', 1, 7);
	newpoints_add_setting('newpoints_main_donationspm', 'main', 'Wysłać Prywatną Wiadomość?', 'Czy wysyłać każdorazowo automatycznie Prywatną Wiadomość do odbiorcy darowizny?', 'yesno', 1, 8);
	newpoints_add_setting('newpoints_main_stats_lastdonations', 'main', 'Ostatnie darowizny', 'Liczba ostatnich darowizn, które mają być wyświetlane.', 'text', 10, 9);
	newpoints_add_setting('newpoints_main_stats_richestusers', 'main', 'Najbogatsi użytkownicy', 'Liczba najbogatszych użytkowników, którzy mają być wyświetlani.', 'text', 10, 9);
	
	// income settings
	newpoints_add_setting('newpoints_income_newpost', 'income', 'Nowy post', 'Liczba punktów otrzymywanych za napisanie posta.', 'text', '10', 1);
	newpoints_add_setting('newpoints_income_newthread', 'income', 'Nowy wątek', 'Liczba punktów otrzymywana za napisanie wątku.', 'text', '20', 2);
	newpoints_add_setting('newpoints_income_newpoll', 'income', 'Nowa ankieta', 'Liczba punktów otrzymywana za utworzenie ankiety.', 'text', '15', 3);
	newpoints_add_setting('newpoints_income_perchar', 'income', 'Za znak', 'Liczba punktów otrzymywanych za każdy napisany znak (w nowych postach i wątkach).', 'text', '0.01', 4);
	newpoints_add_setting('newpoints_income_minchar', 'income', 'Minimalna liczba znaków', 'Minimalna liczba, potrzebna aby otrzymać punkty liczone za znaki.', 'text', '15', 5);
	newpoints_add_setting('newpoints_income_newreg', 'income', 'Rejestracja', 'Liczba punktów otrzymywanych za rejestrację na forum.', 'text', '50', 6);
	newpoints_add_setting('newpoints_income_pervote', 'income', 'Głos w ankiecie', 'Liczba punktów otrzymywanych za oddanie głosu w ankiecie.', 'text', '5', 7);
	newpoints_add_setting('newpoints_income_perreply', 'income', 'Nowa odpowiedź', 'Liczba punktów, którą otrzyma autor wątku, jeśli ktoś odpowie.', 'text', '2', 8);
	newpoints_add_setting('newpoints_income_pmsent', 'income', 'Nowa PW', 'Liczba punktów otrzymywanych za wysłanie prywatnej wiadomości.', 'text', '1', 9);
	newpoints_add_setting('newpoints_income_perrate', 'income', 'Ocena', 'Liczba punktów otrzymywanych za ocenę wątku.', 'text', '0.05', 9);
	newpoints_add_setting('newpoints_income_pageview', 'income', 'Przeglądanie strony', 'Liczba punktów otrzymywanych za każde przeglądanie strony.', 'text', '0', 10);
	newpoints_add_setting('newpoints_income_visit', 'income', 'Wizyta na stronie', 'Liczba punktów otrzymywanych za każdą wizytę na stronie ("wizyta" = nowa sesja MyBB (wygasa po 15 minutach))', 'text', '0.1', 11);
	newpoints_add_setting('newpoints_income_referral', 'income', 'Polecenie forum znajomym', 'Liczba punktów otrzymywanych za polecenie forum nowemu użytkownikowi. (punkty otrzymuje użytkownik polecający)', 'text', '5', 12);
	
	rebuild_settings();
	
	// add points field
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."users` ADD `newpoints` DECIMAL(16,2) NOT NULL DEFAULT '0';");
	
	// create task
	$new_task = array(
		"title" => "Kopia zapasowa NewPoints",
		"description" => "Tworzy kopię zapasową tabeli i punktów użytkowników NewPoints.",
		"file" => "backupnewpoints",
		"minute" => '0',
		"hour" => '0',
		"day" => '*',
		"month" => '*',
		"weekday" => '0',
		"enabled" => '0',
		"logging" => '1'
	);
	
	$new_task['nextrun'] = 0; // once the task is enabled, it will generate a nextrun date
	$tid = $db->insert_query("tasks", $new_task);
}

function newpoints_is_installed()
{
	global $db;
	
	if($db->table_exists('newpoints_settings'))
		return true;
	else
		return false;
}

function newpoints_uninstall()
{
	global $db, $mybb, $cache, $plugins, $theme, $templates, $lang;
	
	// uninstall plugins
	$plugins_cache = $cache->read("newpoints_plugins");
	$active_plugins = $plugins_cache['active'];
	
	if (!empty($active_plugins))
	{
		foreach($active_plugins as $plugin)
		{
			// Ignore potentially missing plugins.
			if(!file_exists(MYBB_ROOT."inc/plugins/newpoints/".$plugin.".php"))
				return true;
		
			require_once MYBB_ROOT."inc/plugins/newpoints/".$plugin.".php";
		
			if(function_exists("{$plugin}_deactivate"))
			{
				call_user_func("{$plugin}_deactivate");
			}
	
			if(function_exists("{$plugin}_uninstall"))
			{
				call_user_func("{$plugin}_uninstall");
			}
		}
	}
	
	// delete plugins cache
	$db->delete_query('datacache', 'title=\'newpoints_plugins\''); 
		
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."users` DROP `newpoints`;");
	
	// delete default main settings
	newpoints_remove_settings("'newpoints_main_enabled','newpoints_main_curname','newpoints_main_curprefix','newpoints_main_cursuffix','newpoints_main_decimal','newpoints_main_statsvisible','newpoints_main_donationsenabled','newpoints_main_donationspm','newpoints_main_stats_lastdonations','newpoints_main_stats_richestusers'");
	
	// delete default income settings
	newpoints_remove_settings("'newpoints_income_newpost','newpoints_income_newthread','newpoints_income_newpoll','newpoints_income_perchar','newpoints_income_minchar','newpoints_income_newreg','newpoints_income_pervote','newpoints_income_perreply','newpoints_income_pmsent','newpoints_income_perrate','newpoints_income_pageview','newpoints_income_visit','newpoints_income_referral'");
	
	// drop tables
	if($db->table_exists('newpoints_settings'))
		$db->drop_table('newpoints_settings');
		
	if($db->table_exists('newpoints_log'))
		$db->drop_table('newpoints_log');
		
	if($db->table_exists('newpoints_forumrules'))
		$db->drop_table('newpoints_forumrules');
		
	if($db->table_exists('newpoints_grouprules'))
		$db->drop_table('newpoints_grouprules');
	
	rebuild_settings();
	
	$db->delete_query('tasks', 'file=\'backupnewpoints\''); 
}

function newpoints_do_template_edits()
{
	// do edits
	require_once MYBB_ROOT."inc/adminfunctions_templates.php";
	find_replace_templatesets("postbit_classic", '#'.preg_quote('{$post[\'user_details\']}').'#', '{$post[\'user_details\']}'.'{$post[\'newpoints_postbit\']}');
	find_replace_templatesets("postbit", '#'.preg_quote('{$post[\'user_details\']}').'#', '{$post[\'user_details\']}'.'{$post[\'newpoints_postbit\']}');
	find_replace_templatesets("member_profile", '#'.preg_quote('{$warning_level}').'#', '{$warning_level}'.'{$newpoints_profile}');
}

function newpoints_undo_template_edits()
{
	// undo edits
	require_once MYBB_ROOT."inc/adminfunctions_templates.php";
	find_replace_templatesets("postbit_classic", '#'.preg_quote('{$post[\'newpoints_postbit\']}').'#', '', 0);
	find_replace_templatesets("postbit", '#'.preg_quote('{$post[\'newpoints_postbit\']}').'#', '', 0);
	find_replace_templatesets("member_profile", '#'.preg_quote('{$newpoints_profile}').'#', '', 0);
}

function newpoints_activate()
{
	global $db, $lang;
	
	newpoints_add_template('newpoints_postbit', '<br /><span class="smalltext">{$currency}:</span> <a href="{$mybb->settings[\'bburl\']}/newpoints.php">{$points}</a></span>{$donate}');
	newpoints_add_template('newpoints_profile', '<tr>
	<td class="trow2"><strong>{$currency}:</strong></td>
	<td class="trow2"><a href="{$mybb->settings[\'bburl\']}/newpoints.php">{$points}</a>{$donate}</td>
</tr>');
	
	newpoints_add_template('newpoints_donate_inline', ' <span class="smalltext">[<a href="{$mybb->settings[\'bburl\']}/newpoints.php?action=donate&amp;uid={$uid}">{$lang->newpoints_donate}</a>]</span>');
	
	newpoints_add_template('newpoints_donate', '
<html>
<head>
<title>{$lang->newpoints} - {$lang->newpoints_donate}</title>
{$headerinclude}
</head>
<body>
{$header}
<table width="100%" border="0" align="center">
<tr>
<td valign="top" width="180">
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
<tr>
<td class="thead"><strong>{$lang->newpoints_menu}</strong></td>
</tr>
{$options}
</table>
</td>
<td valign="top">
<form action="newpoints.php" method="POST">
<input type="hidden" name="postcode" value="{$mybb->post_code}">
<input type="hidden" name="action" value="do_donate">
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
<tr>
<td class="thead" colspan="2"><strong>{$lang->newpoints_donate}</strong></td>
</tr>
<tr>
<td class="trow1" width="50%"><strong>{$lang->newpoints_user}:</strong><br /><span class="smalltext">{$lang->newpoints_user_desc}</span></td>
<td class="trow1" width="50%"><input type="text" name="username" value="{$user[\'username\']}" class="textbox"></td>
</tr>
<tr>
<td class="trow2" width="50%"><strong>{$lang->newpoints_amount}:</strong><br /><span class="smalltext">{$lang->newpoints_amount_desc}</span></td>
<td class="trow2" width="50%"><input type="text" name="amount" value="" class="textbox"></td>
</tr>
<tr>
<td class="trow1" width="50%"><strong>{$lang->newpoints_reason}:</strong><br /><span class="smalltext">{$lang->newpoints_reason_desc}</span></td>
<td class="trow1" width="50%"><input type="text" name="reason" value="" class="textbox"></td>
</tr>
<tr>
<td class="tfoot" width="100%" colspan="2" align="center"><input type="submit" name="submit" value="{$lang->newpoints_submit}"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
{$footer}
</body>
</html>');

	newpoints_add_template('newpoints_statistics', '
<html>
<head>
<title>{$lang->newpoints} - {$lang->newpoints_statistics}</title>
{$headerinclude}
</head>
<body>
{$header}
<table width="100%" border="0" align="center">
<tr>
<td valign="top" width="180">
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
<tr>
<td class="thead"><strong>{$lang->newpoints_menu}</strong></td>
</tr>
{$options}
</table>
</td>
<td valign="top">
<table width="100%" border="0" align="center">
<tr>
<td valign="top" width="40%">
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
<tr>
<td class="thead" colspan="2"><strong>{$lang->newpoints_richest_users}</strong></td>
</tr>
<tr>
<td class="tcat" width="50%"><strong>{$lang->newpoints_user}</strong></td>
<td class="tcat" width="50%" align="center"><strong>{$lang->newpoints_amount}</strong></td>
</tr>
{$richest_users}
</table>
</td>
<td valign="top" width="60%">
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
<tr>
<td class="thead" colspan="4"><strong>{$lang->newpoints_last_donations}</strong></td>
</tr>
<tr>
<td class="tcat" width="30%"><strong>{$lang->newpoints_from}</strong></td>
<td class="tcat" width="30%"><strong>{$lang->newpoints_to}</strong></td>
<td class="tcat" width="20%" align="center"><strong>{$lang->newpoints_amount}</strong></td>
<td class="tcat" width="20%" align="center"><strong>{$lang->newpoints_date}</strong></td>
</tr>
{$last_donations}
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
{$footer}
</body>
</html>');
	
	newpoints_add_template('newpoints_statistics_richest_user', '
<tr>
<td class="{$bgcolor}" width="50%">{$user[\'username\']}</td>
<td class="{$bgcolor}" width="50%" align="center">{$user[\'newpoints\']}</td>
</tr>');
	
	newpoints_add_template('newpoints_statistics_donation', '
<tr>
<td class="{$bgcolor}" width="30%">{$donation[\'from\']}</td>
<td class="{$bgcolor}" width="30%">{$donation[\'to\']}</td>
<td class="{$bgcolor}" width="20%" align="center">{$donation[\'amount\']}</td>
<td class="{$bgcolor}" width="20%" align="center">{$donation[\'date\']}</td>
</tr>');
	
	newpoints_add_template('newpoints_no_results', '
<tr>
<td class="{$bgcolor}" width="100%" colspan="{$colspan}">{$no_results}</td>
</tr>');
	
	newpoints_add_template('newpoints_option', '
<tr>
<td class="{$bgcolor}" width="100%">{$option}</td>
</tr>');
	
	newpoints_add_template('newpoints_home', '
<html>
<head>
<title>{$lang->newpoints} - {$lang->newpoints}</title>
{$headerinclude}
</head>
<body>
{$header}
<table width="100%" border="0" align="center">
<tr>
<td valign="top" width="180">
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
<tr>
<td class="thead"><strong>{$lang->newpoints_menu}</strong></td>
</tr>
{$options}
</table>
</td>
<td valign="top">
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
<tr>
<td class="thead"><strong>{$lang->newpoints}</strong></td>
</tr>
<tr>
<td class="trow1">{$lang->newpoints_home_desc}</td>
</tr>
</table>
</td>
</tr>
</table>
{$footer}
</body>
</html>');
	
	newpoints_do_template_edits();
	
	//Change admin permissions
	change_admin_permission("newpoints", false, 1);
	change_admin_permission("newpoints", "plugins", 1);
	change_admin_permission("newpoints", "settings", 1);
	change_admin_permission("newpoints", "log", 1);
	change_admin_permission("newpoints", "maintenance", 1);
	change_admin_permission("newpoints", "forumrules", 1);
	change_admin_permission("newpoints", "grouprules", 1);
	change_admin_permission("newpoints", "stats", 1);
	change_admin_permission("newpoints", "upgrades", 1);
}

function newpoints_deactivate()
{
	global $db, $mybb;
	
	newpoints_remove_templates("'newpoints_postbit','newpoints_profile','newpoints_donate','newpoints_donate_inline','newpoints_statistics','newpoints_statistics_richest_user','newpoints_statistics_donation','newpoints_no_results','newpoints_option','newpoints_home'");
	
	newpoints_undo_template_edits();
	
	//Change admin permissions
	change_admin_permission("newpoints", false, -1);
	change_admin_permission("newpoints", "plugins", -1);
	change_admin_permission("newpoints", "settings", -1);
	change_admin_permission("newpoints", "log", -1);
	change_admin_permission("newpoints", "maintenance", -1);
	change_admin_permission("newpoints", "forumrules", -1);
	change_admin_permission("newpoints", "grouprules", -1);
	change_admin_permission("newpoints", "stats", -1);
	change_admin_permission("newpoints", "upgrades", -1);
}

/**************************************************************************************/
/****************** FUNCTIONS THAT CAN/SHOULD BE USED BY PLUGINS **********************/
/**************************************************************************************/

/**
 * Somewhat like htmlspecialchars_uni but for JavaScript strings
 * 
 * @param string: The string to be parsed
 * @return string: Javascript compatible string
 */
function newpoints_jsspecialchars($str)
{
	// Converts & -> &amp; allowing Unicode
	// Parses out HTML comments as the XHTML validator doesn't seem to like them
	$string = preg_replace(array("#\<\!--.*?--\>#", "#&(?!\#[0-9]+;)#"), array('','&amp;'), $str);
	return strtr($string, array("\n" => '\n', "\r" => '\r', '\\' => '\\\\', '"' => '\x22', "'" => '\x27', '<' => '&lt;', '>' => '&gt;'));
}

/*
 * Deletes templates from the database
 * 
 * @param string a list of templates seperated by ',' e.g. 'test','test_again','testing'
 * @param bool false if something went wrong
 *
*/
function newpoints_remove_templates($templates = '')
{
	global $db;
	
	if (!$templates)
		return false;
	
	return $db->delete_query('templates', "title IN (".$templates.")");
}

/*
 * Adds a new template
 * 
 * @param string the title of the template
 * @param string the contents of the template
 * @param integer the sid of the template
 * @param bool false if something went wrong
 *
*/
function newpoints_add_template($name = '', $contents = '', $sid = -1)
{
	global $db;
	
	if (!$name || !$contents)
		return false;
	
	$templatearray = array(
		"title" => $db->escape_string($name),
		"template" => $db->escape_string($contents),
		"sid" => intval($sid)
	);

	return $db->insert_query("templates", $templatearray);
}

/*
 * Deletes settings from the database
 * 
 * @param string a list of settings seperated by ',' e.g. 'test','test_again','testing'
 * @param bool false if something went wrong
 *
*/
function newpoints_remove_settings($settings = '')
{
	global $db;
	
	if (!$settings)
		return false;
	
	return $db->delete_query('newpoints_settings', "name IN (".$settings.")");
	return $db->delete_query('settings', "name IN (".$settings.")");
}

/*
 * Adds a new setting
 * 
 * @param string the name (unique identifier) of the setting
 * @param string the codename of plugin which owns the setting ('main' for main setting)
 * @param string the title of the setting
 * @param string the description of the setting
 * @param string the type of the setting ('text', 'textarea', etc...)
 * @param string the value of the setting
 *
*/
function newpoints_add_setting($name = '', $plugin = '', $title = '', $description = '', $type = '', $value = '', $disporder = 0)
{
	global $db;
	
	if ($name == '' || $plugin == '' || $title == '' || $description == '' || $type == '')
		return false;
	
	$setting = array(
		"name"			=> $db->escape_string($name),
		"plugin"		=> $db->escape_string($plugin),
		"title"			=> $db->escape_string($title),
		"description"	=> $db->escape_string($description),
		"type"			=> $db->escape_string($type),
		"value"			=> $db->escape_string($value),
		"disporder"		=> intval($disporder)
	);
	$db->insert_query("newpoints_settings", $setting);
	
	$setting = array(
		"name"			=> $db->escape_string($name),
		"title"			=> $db->escape_string($title),
		"description"	=> $db->escape_string($description),
		"optionscode"	=> $db->escape_string($type),
		"value"			=> $db->escape_string($value),
		"disporder"		=> intval($disporder),
		"gid"			=> ''
	);
	$db->insert_query("settings", $setting);
}

/*
 * Adds/Subtracts points to a user
 * 
 * @param integer the id of the user
 * @param float the number of points to add or subtract (if a negative value)
 * @param integer the forum income rate
 * @param integer the user group income rate
 * @param bool if the uid is a string in case we don't have the uid we can update the points field by searching for the user name
 * @param bool true if you want to run the query immediatly. Default is false which means the query will be run on shut down. Note that if the previous paremeter is set to true, the query is run immediatly
 *
*/
function newpoints_addpoints($uid, $points, $forumrate = 1, $grouprate = 1, $isstring = false, $immediate = false)
{
	global $db, $mybb, $userpoints;
	
	if ($points == 0 || ($uid <= 0 && !$isstring))
		return;
		
	if ($isstring === true)
		$immediate = true;
	
	// might work only for MySQL and MySQLi
	//$db->update_query("users", array('newpoints' => 'newpoints+('.floatval($points).')'), 'uid=\''.intval($uid).'\'', '', true);
	
	if ($isstring) // where username
		$db->query("UPDATE ".TABLE_PREFIX."users SET newpoints=newpoints+'".floatval(round($points*$forumrate*$grouprate, intval($mybb->settings['newpoints_main_decimal'])))."' WHERE username='".$db->escape_string($uid)."'");
	else // where uid
	{
		// if immediate, run the query now otherwise add it to shutdown to avoid slow down
		if ($immediate)
			$db->query("UPDATE ".TABLE_PREFIX."users SET newpoints=newpoints+'".floatval(round($points*$forumrate*$grouprate, intval($mybb->settings['newpoints_main_decimal'])))."' WHERE uid='".intval($uid)."'");
		else
		{
			$userpoints[intval($uid)] = floatval(round($points*$forumrate*$grouprate, intval($mybb->settings['newpoints_main_decimal'])));
			add_shutdown('newpoints_update_addpoints');
		}
	}
}

function newpoints_update_addpoints()
{
	global $cache, $userpoints, $db;
	if (!empty($userpoints))
	{
		foreach($userpoints as $uid => $amount)
		{
			$db->write_query('UPDATE `'.TABLE_PREFIX.'users` SET `newpoints` = `newpoints`+'.$amount.' WHERE `uid`=\''.$uid.'\'');
		}
		unset($userpoints);
	}
}

/*
 * Get rules of a certain group or forum
 * 
 * @param string the type of rule: 'forum' or 'group'
 * @param integer the id of the group or forum
 * @return bool false if something went wrong
 *
*/
function newpoints_getrules($type = '', $id = 0)
{
	global $db;
	
	if (!$type || !$id)
		return false;
		
	if ($type == 'forum')
		$typeid = 'f';
	elseif ($type == 'group')
		$typeid = 'g';
	else
		return;
		
	$query = $db->simple_select('newpoints_'.$type.'rules', '*', $typeid.'id=\''.intval($id).'\'');
	return $db->fetch_array($query);
}

/*
 * Get all rules
 * 
 * @param string the type of rule: 'forum' or 'group'
 * @return array containing all rules
 *
*/
function newpoints_getallrules($type = '')
{
	global $db;
	
	if (!$type)
		return false;
		
	if ($type == 'forum')
		$typeid = 'f';
	elseif ($type == 'group')
		$typeid = 'g';
	else
		return;
		
	$rules = array();
		
	$query = $db->simple_select('newpoints_'.$type.'rules', '*');
	while ($rule = $db->fetch_array($query))
		$rules[$rule[$typeid.'id']] = $rule;
	
	return $rules;
}

/*
 * Formats points according to the settings
 * 
 * @param float the amount of points
 * @return string formated points
 *
*/
function newpoints_format_points($points)
{
	global $mybb;
	
	return $mybb->settings['newpoints_main_curprefix'].number_format($points, intval($mybb->settings['newpoints_main_decimal'])).$mybb->settings['newpoints_main_cursuffix'];
}

/**
 * Sends a PM to a user
 * 
 * @param array: The PM to be sent; should have 'subject', 'message', 'touid' and 'receivepms'
 * (receivepms is for admin override in case the user has disabled pm's)
 * @param int: from user id (0 if you want to use the uid of the person that sends it. -1 to use MyBB Engine
 * @return bool: true if PM sent
 */
function newpoints_send_pm($pm, $fromid = 0)
{
	global $lang, $mybb, $db;
	if($mybb->settings['enablepms'] == 0)
		return false;
		
	if (!is_array($pm))
		return false;
		
	if (!$pm['subject'] ||!$pm['message'] || !$pm['touid'] || !$pm['receivepms'])
		return false;
	
	$lang->load('messages');
	
	require_once MYBB_ROOT."inc/datahandlers/pm.php";
	
	$pmhandler = new PMDataHandler();
	
	$subject = $pm['subject'];
	$message = $pm['message'];
	$toid = $pm['touid'];
	
	require_once MYBB_ROOT."inc/datahandlers/pm.php";
	
	$pmhandler = new PMDataHandler();
	
	if (is_array($toid))
		$recipients_to = $toid;
	else
		$recipients_to = array($toid);
		
	$recipients_bcc = array();
	
	if (intval($fromid) == 0)
		$fromid = intval($mybb->user['uid']);
	elseif (intval($fromid) < 0)
		$fromid = 0;
	
	$pm = array(
		"subject" => $subject,
		"message" => $message,
		"icon" => -1,
		"fromid" => $fromid,
		"toid" => $recipients_to,
		"bccid" => $recipients_bcc,
		"do" => '',
		"pmid" => ''
	);
	
	$pm['options'] = array(
		"signature" => 0,
		"disablesmilies" => 0,
		"savecopy" => 0,
		"readreceipt" => 0
	);
	
	$pm['saveasdraft'] = 0;
	$pmhandler->admin_override = 1;
	$pmhandler->set_data($pm);
	if($pmhandler->validate_pm())
	{
		$pmhandler->insert_pm();
	}
	else
	{
		return false;
	}
	
	return true;
}

/*
 * Get the user data of a user name
 * 
 * @param string the user name
 * @param string the fields to fetch
 * @return array the user data
 *
*/
function newpoints_getuser_byname($username = '', $fields = '*')
{
	global $db;
	
	if (!$username)
		return;
	
	$query = $db->simple_select('users', $fields, 'username=\''.$db->escape_string($username).'\'');
	return $db->fetch_array($query);
}

/*
 * Get the user group data of the gid
 * 
 * @param string the user name
 * @param string the fields to fetch
 * @return array the user data
 *
*/
function newpoints_get_usergroup($gid = 0)
{
	global $db;
	
	if (!$gid)
		return;
	
	$query = $db->simple_select('usergroups', '*', 'gid=\''.intval($gid).'\'');
	return $db->fetch_array($query);
}


/**
 * Find and replace a string in a particular template in global templates set
 *
 * @param string The name of the template
 * @param string The regular expression to match in the template
 * @param string The replacement string
 * @return bolean true if matched template name, false if not.
 */

function newpoints_find_replace_templatesets($title, $find, $replace)
{
	global $db;

	$query = $db->query("
		SELECT template, tid FROM ".TABLE_PREFIX."templates WHERE title='$title' AND sid=-1
	");
	while($template = $db->fetch_array($query))
	{
		if($template['template']) // Custom template exists for this group
		{
			if(!preg_match($find, $template['template']))
			{
				return false;
			}
			$newtemplate = preg_replace($find, $replace, $template['template']);
			$template['template'] = $newtemplate;
			$update[] = $template;
		}
	}
	
	if(is_array($update))
	{
		foreach($update as $template)
		{
			$updatetemp = array("template" => $db->escape_string($template['template']), "dateline" => TIME_NOW);
			$db->update_query("templates", $updatetemp, "tid='".$template['tid']."'");
		}
	}
	return true;
}

/*
 * Create a new log entry
 * 
 * @param string action taken
 * @param string extra data
 * @param username of who's executed the action
 * @param uid of who's executed the action
 * @return bool false if something went wrong
 *
*/
function newpoints_log($action='', $data = '', $username = '', $uid = 0)
{
	global $db, $mybb;
	
	if (!$action)
		return false;
		
	if ($username == '' || $uid == 0)
	{
		$username = $mybb->user['username'];
		$uid = $mybb->user['uid'];
	}
		
	$db->insert_query('newpoints_log', array('action' => $db->escape_string($action), 'data' => $db->escape_string($data), 'date' => TIME_NOW, 'uid' => intval($uid), 'username' => $db->escape_string($username)));
	
	return true;
}

/*
 * Removes all log entries based on action
 * 
 * @param array action taken
 *
*/
function newpoints_remove_log($action=array())
{
	global $db, $mybb;
	
	if (empty($action) || !is_array($action))
		return false;
		
	foreach ($action as $act)
	{
		$db->delete_query('newpoints_log', 'action=\''.$act.'\'');
	}
}

function newpoints_load_plugins()
{
	global $cache, $plugins, $mybb, $theme, $db, $templates, $newpoints_plugins;
	
	$newpoints_plugins = '';
	
	// guests have 0 points
	if (!$mybb->user['uid'])
		$mybb->user['newpoints'] = 0;
	
	$pluginlist = $cache->read("newpoints_plugins");
	if(is_array($pluginlist['active']))
	{
		foreach($pluginlist['active'] as $plugin)
		{
			if($plugin != "" && file_exists(MYBB_ROOT."inc/plugins/newpoints/".$plugin.".php"))
			{
				require_once MYBB_ROOT."inc/plugins/newpoints/".$plugin.".php";
			}
		}
		
		$newpoints_plugins = $pluginlist;
	}
}
	
function newpoints_admin_load_hook()
{
	global $plugins, $newpoints_plugins;
	
	if (!$newpoints_plugins || !isset($newpoints_plugins))
	{
		newpoints_load_plugins();
	}
	
	// as plugins can't hook to admin_load, we must allow them to hook to newpoints_admin_load
	$plugins->run_hooks("newpoints_admin_load");
}

function newpoints_admin_menu_hook(&$sub_menu)
{
	global $plugins, $newpoints_plugins;
	
	if (!$newpoints_plugins || !isset($newpoints_plugins))
	{
		newpoints_load_plugins();
	}
	
	// as plugins can't hook to admin_newpoints_menu, we must allow them to hook to newpoints_admin_newpoints_menu
	$plugins->run_hooks_by_ref("newpoints_admin_newpoints_menu", $sub_menu);
}

function newpoints_admin_action_handler_hook(&$actions)
{
	global $plugins, $newpoints_plugins;
	
	if (!$newpoints_plugins || !isset($newpoints_plugins))
	{
		newpoints_load_plugins();
	}
	
	// as plugins can't hook to admin_newpoints_action_handler, we must allow them to hook to newpoints_newpoints_action_handler
	$plugins->run_hooks_by_ref("newpoints_admin_newpoints_action_handler", $actions);
}

function newpoints_admin_permissions_hook(&$admin_permissions)
{
	global $plugins, $newpoints_plugins;
	
	if (!$newpoints_plugins || !isset($newpoints_plugins))
	{
		newpoints_load_plugins();
	}
	
	// as plugins can't hook to admin_newpoints_permissions, we must allow them to hook to newpoints_newpoints_permissions
	$plugins->run_hooks_by_ref("newpoints_admin_newpoints_permissions", $admin_permissions);
}

function newpoints_lang_load($plugin = '')
{
	global $lang;
	if ($plugin == '')
		return;
		
	$lang->set_path(MYBB_ROOT."inc/plugins/newpoints/languages");
	$lang->load($plugin);
	$lang->set_path(MYBB_ROOT."inc/languages");
}

/**************************************************************************************/
/******************************** INCOME FUNCTIONS ************************************/
/**************************************************************************************/

// postbit
function newpoints_postbit(&$post)
{
	global $mybb, $db, $currency, $points, $templates, $donate, $lang, $uid;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
	{
		$post['newpoints_postbit'] = '';
		return;
	}
	
	$lang->load("newpoints");
	
	$currency = $mybb->settings['newpoints_main_curname'];
	$points = newpoints_format_points($post['newpoints']);
	$uid = intval($post['uid']);
	
	if ($mybb->settings['newpoints_main_donationsenabled'] && $post['uid'] != $mybb->user['uid'] && $mybb->user['uid'] > 0)
		eval("\$donate = \"".$templates->get('newpoints_donate_inline')."\";");
	else
		$donate = '';
	
	eval("\$post['newpoints_postbit'] = \"".$templates->get('newpoints_postbit')."\";");
}

// member profile
function newpoints_profile()
{
	global $mybb, $db, $currency, $points, $templates, $memprofile, $newpoints_profile, $lang, $uid;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
	{
		$newpoints_profile = '';
		return;
	}
	
	$lang->load("newpoints");
	
	$currency = $mybb->settings['newpoints_main_curname'];
	$points = newpoints_format_points($memprofile['newpoints']);
	$uid = intval($memprofile['uid']);
	
	if ($mybb->settings['newpoints_main_donationsenabled'] && $memprofile['uid'] != $mybb->user['uid'] && $mybb->user['uid'] > 0)
		eval("\$donate = \"".$templates->get('newpoints_donate_inline')."\";");
	else
		$donate = '';
	
	eval("\$newpoints_profile = \"".$templates->get('newpoints_profile')."\";");
}

// new post
function newpoints_newpost()
{
	global $db, $mybb, $fid, $post, $thread;
	
	if ($mybb->input['action'] != "do_newreply" || $post['savedraft'])
		return;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
		
	if ($mybb->settings['newpoints_income_newpost'] == 0)
		return;
	
	// check forum rules
	$forumrules = newpoints_getrules('forum', $fid);
	if (!$forumrules)
		$forumrules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the forum rate is 0, nothing is going to be added so let's just leave the function
	if ($forumrules['rate'] == 0)
		return;
	
	// check group rules - primary group check
	$grouprules = newpoints_getrules('group', $mybb->user['usergroup']);
	if (!$grouprules)
		$grouprules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the group rate is 0, nothing is going to be added so let's just leave the function
	if ($grouprules['rate'] == 0)
		return;

	// calculate points ber character bonus
	// let's see if the number of characters in the post is greater than the minimum characters
	if (($charcount = my_strlen($post['message'])) >= $mybb->settings['newpoints_income_minchar']) 
		$bonus = $charcount * $mybb->settings['newpoints_income_perchar'];
	else
		$bonus = 0;
	
	// give points to the poster
	newpoints_addpoints($mybb->user['uid'], $mybb->settings['newpoints_income_newpost']+$bonus, $forumrules['rate'], $grouprules['rate']);
	
	if ($thread['uid'] != $mybb->user['uid'])
	{
		// we are not the thread started so give points to him/her
		if ($mybb->settings['newpoints_income_perreply'] != 0)
			newpoints_addpoints($thread['uid'], $mybb->settings['newpoints_income_perreply'], $forumrules['rate'], $grouprules['rate']);
	}
}


// edit post
function newpoints_editpost(&$newpost)
{
	global $db, $mybb, $thread;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
		
	if ($mybb->settings['newpoints_income_perchar'] == 0)
		return;
		
	if ($mybb->input['action'] != "do_editpost" || $mybb->input['editdraft'])
		return;
			
	$fid = intval($newpost->data['fid']);
	
	// check forum rules
	$forumrules = newpoints_getrules('forum', $fid);
	if (!$forumrules)
		$forumrules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the forum rate is 0, nothing is going to be added so let's just leave the function
	if ($forumrules['rate'] == 0)
		return;
	
	// check group rules - primary group check
	$grouprules = newpoints_getrules('group', $mybb->user['usergroup']);
	if (!$grouprules)
		$grouprules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the group rate is 0, nothing is going to be added so let's just leave the function
	if ($grouprules['rate'] == 0)
		return;
		
	// get old message
	$post = get_post(intval($newpost->data['pid']));
	$oldcharcount = my_strlen($post['message']);
	$newcharcount = my_strlen($newpost->data['message']);

	// calculate points ber character bonus
	// let's see if the number of characters in the post is greater than the minimum characters
	if ($newcharcount >= $mybb->settings['newpoints_income_minchar']) 
	{
		// if we have more characters now
		if ($newcharcount > $oldcharcount)
		{
			// calculate bonus based on difference of characters
			// bonus will be positive as the new message is longer than the old one
			$bonus = ($newcharcount - $oldcharcount) * $mybb->settings['newpoints_income_perchar'];
		}
		// otherwise if the message is shorter
		elseif ($newcharcount < $oldcharcount)
		{
			// calculate bonus based on difference of characters
			// bonus will be positive as the new message is longer than the old one
			$bonus = ($newcharcount - $oldcharcount) * $mybb->settings['newpoints_income_perchar'];
		}
		// else if the length is the same, the bonus is 0
		elseif ($newcharcount == $oldcharcount)
		{
			$bonus = 0;
		}
	}
	else
	{
		// calculate bonus based on difference of characters
		// bonus will be negative as the new message is shorter than the minimum chars
		$bonus = ($newcharcount - $oldcharcount) * $mybb->settings['newpoints_income_perchar'];
	}
	
	// give points to the poster
	newpoints_addpoints($mybb->user['uid'], $bonus, $forumrules['rate'], $grouprules['rate'], false, true);
}

// edit post - counts less chars on edit because of \n\r being deleted
function newpoints_editpost_xmlhttp()
{
	global $db, $mybb, $thread, $lang, $charset;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
		
	if ($mybb->settings['newpoints_income_perchar'] == 0)
		return;
	
	if ($mybb->input['action'] != "edit_post")
		return;
	elseif ($mybb->input['action'] == "edit_post" && $mybb->input['do'] != 'update_post')
		return;
		
	if ($mybb->input['editdraft'])
		return;
		
	// Verify POST request
	if(!verify_post_check($mybb->input['my_post_key'], true))
	{
		xmlhttp_error($lang->invalid_post_code);
	}
		
	$post = get_post($mybb->input['pid']);
			
	$fid = intval($post['fid']);
	
	// check forum rules
	$forumrules = newpoints_getrules('forum', $fid);
	if (!$forumrules)
		$forumrules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the forum rate is 0, nothing is going to be added so let's just leave the function
	if ($forumrules['rate'] == 0)
		return;
	
	// check group rules - primary group check
	$grouprules = newpoints_getrules('group', $mybb->user['usergroup']);
	if (!$grouprules)
		$grouprules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the group rate is 0, nothing is going to be added so let's just leave the function
	if ($grouprules['rate'] == 0)
		return;
		
	// get old message
	$oldcharcount = my_strlen($post['message']);
	
	$message = strval($_POST['value']);
	if(my_strtolower($charset) != "utf-8")
	{
		if(function_exists("iconv"))
		{
			$message = iconv($charset, "UTF-8//IGNORE", $message);
		}
		else if(function_exists("mb_convert_encoding"))
		{
			$message = @mb_convert_encoding($message, $charset, "UTF-8");
		}
		else if(my_strtolower($charset) == "iso-8859-1")
		{
			$message = utf8_decode($message);
		}
	}
	
	$newcharcount = my_strlen($message);
	
	// calculate points ber character bonus
	// let's see if the number of characters in the post is greater than the minimum characters
	if ($newcharcount >= $mybb->settings['newpoints_income_minchar']) 
	{
		// if we have more characters now
		if ($newcharcount > $oldcharcount)
		{
			// calculate bonus based on difference of characters
			// bonus will be positive as the new message is longer than the old one
			$bonus = ($newcharcount - $oldcharcount) * $mybb->settings['newpoints_income_perchar'];
		}
		// otherwise if the message is shorter
		elseif ($newcharcount < $oldcharcount)
		{
			// calculate bonus based on difference of characters
			// bonus will be positive as the new message is longer than the old one
			$bonus = ($newcharcount - $oldcharcount) * $mybb->settings['newpoints_income_perchar'];
		}
		// else if the length is the same, the bonus is 0
		elseif ($newcharcount == $oldcharcount)
		{
			$bonus = 0;
		}
	}
	else
	{
		// calculate bonus based on difference of characters
		// bonus will be negative as the new message is shorter than the minimum chars
		$bonus = ($newcharcount - $oldcharcount) * $mybb->settings['newpoints_income_perchar'];
	}
	
	// give points to the poster
	newpoints_addpoints($mybb->user['uid'], $bonus, $forumrules['rate'], $grouprules['rate'], false, true);
}


// delete post
function newpoints_deletepost($pid)
{
	global $db, $mybb, $fid, $post, $thread;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
		
	if ($mybb->settings['newpoints_income_newpost'] == 0)
		return;
	
	// check forum rules
	$forumrules = newpoints_getrules('forum', $fid);
	if (!$forumrules)
		$forumrules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the forum rate is 0, nothing is going to be removed so let's just leave the function
	if ($forumrules['rate'] == 0)
		return;
	
	// check group rules - primary group check
	$grouprules = newpoints_getrules('group', $mybb->user['usergroup']);
	if (!$grouprules)
		$grouprules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the group rate is 0, nothing is going to be removed so let's just leave the function
	if ($grouprules['rate'] == 0)
		return;

	// calculate points ber character bonus
	// let's see if the number of characters in the post is greater than the minimum characters
	if (($charcount = my_strlen($post['message'])) >= $mybb->settings['newpoints_income_minchar']) 
		$bonus = $charcount * $mybb->settings['newpoints_income_perchar'];
	else
		$bonus = 0;
	
	if ($thread['uid'] != $mybb->user['uid'])
	{
		// we are not the thread started so remove points from him/her
		if ($mybb->settings['newpoints_income_perreply'] != 0)
			newpoints_addpoints($thread['uid'], -$mybb->settings['newpoints_income_perreply'], $forumrules['rate'], $grouprules['rate']);
	}
	
	// remove points from the poster
	newpoints_addpoints($post['uid'], -$mybb->settings['newpoints_income_newpost']-$bonus, $forumrules['rate'], $grouprules['rate']);
}


// new thread
function newpoints_newthread()
{
	global $db, $mybb, $fid, $thread;
	
	if ($mybb->input['action'] != "do_newthread" || $mybb->input['savedraft'])
		return;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
		
	if ($mybb->settings['newpoints_income_newthread'] == 0)
		return;
	
	// check forum rules
	$forumrules = newpoints_getrules('forum', $fid);
	if (!$forumrules)
		$forumrules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the forum rate is 0, nothing is going to be added so let's just leave the function
	if ($forumrules['rate'] == 0)
		return;
	
	// check group rules - primary group check
	$grouprules = newpoints_getrules('group', $mybb->user['usergroup']);
	if (!$grouprules)
		$grouprules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the group rate is 0, nothing is going to be added so let's just leave the function
	if ($grouprules['rate'] == 0)
		return;
	

	// calculate points ber character bonus
	// let's see if the number of characters in the thread is greater than the minimum characters
	if (($charcount = my_strlen($mybb->input['message'])) >= $mybb->settings['newpoints_income_minchar']) 
		$bonus = $charcount * $mybb->settings['newpoints_income_perchar'];
	else
		$bonus = 0;
	
	// give points to the author of the new thread
	newpoints_addpoints($mybb->user['uid'], $mybb->settings['newpoints_income_newthread']+$bonus, $forumrules['rate'], $grouprules['rate']);
}


// delete thread
function newpoints_deletethread($tid)
{
	global $db, $mybb;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
		
	if ($mybb->settings['newpoints_income_newthread'] == 0)
		return;
		
	$thread = get_thread($tid);
	$fid = $thread['fid'];
	
	// check forum rules
	$forumrules = newpoints_getrules('forum', $fid);
	if (!$forumrules)
		$forumrules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the forum rate is 0, nothing is going to be removed so let's just leave the function
	if ($forumrules['rate'] == 0)
		return;
	
	// check group rules - primary group check
	$grouprules = newpoints_getrules('group', $mybb->user['usergroup']);
	if (!$grouprules)
		$grouprules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the group rate is 0, nothing is going to be removed so let's just leave the function
	if ($grouprules['rate'] == 0)
		return;
	
	// get post of the thread
	$post = get_post($thread['firstpost']);

	// calculate points ber character bonus
	// let's see if the number of characters in the thread is greater than the minimum characters
	if (($charcount = my_strlen($post['message'])) >= $mybb->settings['newpoints_income_minchar']) 
		$bonus = $charcount * $mybb->settings['newpoints_income_perchar'];
	else
		$bonus = 0;
	
	if ($thread['poll'] != 0)
	{
		// if this thread has a poll, remove points from the author of the thread
		newpoints_addpoints($thread['uid'], -$mybb->settings['newpoints_income_newpoll'], $forumrules['rate'], $grouprules['rate']);
	}
	
	// remove money from posts posted in the thread even though we might have posted in our own thread..there's no simpler way to do this
	global $num_approved_posts, $num_unapproved_posts;
	newpoints_addpoints($thread['uid'], -($thread['replies']*$mybb->settings['newpoints_income_perreply']), $forumrules['rate'], $grouprules['rate']);
	
	// take out points from the author of the thread
	newpoints_addpoints($thread['uid'], -$mybb->settings['newpoints_income_newthread']-$bonus, $forumrules['rate'], $grouprules['rate']);
}

// new poll
function newpoints_newpoll()
{
	global $db, $mybb, $fid;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
		
	if ($mybb->settings['newpoints_income_newpoll'] == 0)
		return;
	
	// check forum rules
	$forumrules = newpoints_getrules('forum', $fid);
	if (!$forumrules)
		$forumrules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the forum rate is 0, nothing is going to be added so let's just leave the function
	if ($forumrules['rate'] == 0)
		return;
	
	// check group rules - primary group check
	$grouprules = newpoints_getrules('group', $mybb->user['usergroup']);
	if (!$grouprules)
		$grouprules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the group rate is 0, nothing is going to be added so let's just leave the function
	if ($grouprules['rate'] == 0)
		return;
	
	// give points to the author of the new poll
	newpoints_addpoints($mybb->user['uid'], $mybb->settings['newpoints_income_newpoll'], $forumrules['rate'], $grouprules['rate']);
}


// delete poll
function newpoints_deletepoll($pid)
{
	global $db, $mybb;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
		
	if ($mybb->settings['newpoints_income_newpoll'] == 0)
		return;
		
	$query = $db->simple_select("polls", "*", "pid = '{$pid}'");
	$poll = $db->fetch_array($query);
	
	$fid = $poll['fid'];
	
	// check forum rules
	$forumrules = newpoints_getrules('forum', $fid);
	if (!$forumrules)
		$forumrules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the forum rate is 0, nothing is going to be added so let's just leave the function
	if ($forumrules['rate'] == 0)
		return;
	
	// check group rules - primary group check
	$grouprules = newpoints_getrules('group', $mybb->user['usergroup']);
	if (!$grouprules)
		$grouprules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the group rate is 0, nothing is going to be added so let's just leave the function
	if ($grouprules['rate'] == 0)
		return;
	
	// remove points from the author by deleting the poll
	newpoints_addpoints($poll['uid'], -$mybb->settings['newpoints_income_newpoll'], $forumrules['rate'], $grouprules['rate']);
}

// new registration
function newpoints_newreg()
{
	global $db, $mybb, $user_info;
	
	// give points to our new user
	if ($mybb->settings['newpoints_income_newreg'] != 0)
		newpoints_addpoints(trim($mybb->input['username']), $mybb->settings['newpoints_income_newreg'], 1, 1, true);
		
	if ($mybb->settings['newpoints_income_referral'] != 0)
		newpoints_addpoints(trim($mybb->input['referrername']), $mybb->settings['newpoints_income_referral'], 1, 1, true);
}

// new poll vote
function newpoints_pervote()
{
	global $db, $mybb, $fid;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
		
	if ($mybb->settings['newpoints_income_pervote'] == 0)
		return;
	
	// check forum rules
	$forumrules = newpoints_getrules('forum', $fid);
	if (!$forumrules)
		$forumrules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the forum rate is 0, nothing is going to be added so let's just leave the function
	if ($forumrules['rate'] == 0)
		return;
	
	// check group rules - primary group check
	$grouprules = newpoints_getrules('group', $mybb->user['usergroup']);
	if (!$grouprules)
		$grouprules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the group rate is 0, nothing is going to be added so let's just leave the function
	if ($grouprules['rate'] == 0)
		return;
	
	// give points to us as we're voting in a poll
	newpoints_addpoints($mybb->user['uid'], $mybb->settings['newpoints_income_pervote'], $forumrules['rate'], $grouprules['rate']);
}

// send a pm
function newpoints_pmsent()
{
	global $pmhandler, $pminfo, $db, $mybb;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
		
	if ($mybb->settings['newpoints_income_pmsent'] == 0)
		return;
	
	if(isset($pminfo['draftsaved']))
		return;
		
	if($mybb->user['uid'] == $pmhandler->data['toid'])
		return;
	
	// check group rules - primary group check
	$grouprules = newpoints_getrules('group', $mybb->user['usergroup']);
	if (!$grouprules)
		$grouprules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the group rate is 0, nothing is going to be added so let's just leave the function
	if ($grouprules['rate'] == 0)
		return;
	
	// give points to the author of the PM
	newpoints_addpoints($mybb->user['uid'], $mybb->settings['newpoints_income_pmsent'], 1, $grouprules['rate']);
}

// per rate
function newpoints_perrate()
{
	global $db, $mybb, $fid;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
		
	if ($mybb->settings['newpoints_income_perrate'] == 0)
		return;
	
	// check forum rules
	$forumrules = newpoints_getrules('forum', $fid);
	if (!$forumrules)
		$forumrules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the forum rate is 0, nothing is going to be added so let's just leave the function
	if ($forumrules['rate'] == 0)
		return;
	
	// check group rules - primary group check
	$grouprules = newpoints_getrules('group', $mybb->user['usergroup']);
	if (!$grouprules)
		$grouprules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the group rate is 0, nothing is going to be added so let's just leave the function
	if ($grouprules['rate'] == 0)
		return;
	
	// give points us, as we're rating a thread
	newpoints_addpoints($mybb->user['uid'], $mybb->settings['newpoints_income_perrate'], $forumrules['rate'], $grouprules['rate']);
}

// page view / visit
function newpoints_perview()
{
	global $db, $mybb, $cache, $groupscache, $userupdates;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
		
	if ($mybb->settings['newpoints_income_pageview'] != 0)
	{
		newpoints_addpoints($mybb->user['uid'], $mybb->settings['newpoints_income_pageview'], 1, 1);
	}
	
	if ($mybb->settings['newpoints_income_visit'] != 0)
	{
		if((TIME_NOW - $mybb->user['lastactive']) > 900)
			newpoints_addpoints($mybb->user['uid'], $mybb->settings['newpoints_income_visit'], 1, 1);
	}

	// check group rules - primary group check
	$grouprules = newpoints_getallrules('group');
	if (empty($grouprules))
		return;
	
	foreach($grouprules as $gid => $rule)
	{
		if ($rule['pointsearn'] == 0 || $rule['period'] == 0 || $rule['lastpay']>(TIME_NOW - $rule['period']))
			return;
			
		//die("testing".$rule['pointsearn']." | ".$rule['period']." | ".$rule['lastpay']." | ".TIME_NOW);

		$amount = floatval($rule['pointsearn']);

		$userupdates[$gid] = $amount;
		// update rule with last payment
		$db->update_query('newpoints_grouprules', array('lastpay' => TIME_NOW), 'gid=\''.$gid.'\'');
				
		if($mybb->user['usergroup'] == $gid)
			$mybb->user['newpoints'] += $amount;
		
		if(!empty($userupdates))
		{
			// run updates to users on shut down
			add_shutdown('newpoints_update_users');
		}
	}
}

function newpoints_update_users()
{
	global $cache, $userupdates, $db;
	
	if (!empty($userupdates))
	{
		foreach($userupdates as $gid => $amount)
		{
			$db->write_query('UPDATE `'.TABLE_PREFIX.'users` SET `newpoints` = `newpoints`+'.$amount.' WHERE `usergroup`='.$gid);
		}
		unset($userupdates);
	}
}

function newpoints_blockview()
{
	global $mybb, $lang, $fid;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
	
	if (THIS_SCRIPT == 'forumdisplay_start')
		$fid = intval($mybb->input['fid']);

	$forumrules = newpoints_getrules('forum', $fid);
	if ($forumrules['pointsview'] > $mybb->user['newpoints'])
	{
		$lang->load("newpoints");
		error($lang->sprintf($lang->newpoints_not_enough_points, newpoints_format_points($forumrules['pointsview'])));
	}
}

function newpoints_blockview_edit()
{
	global $mybb, $lang;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
	
	$pid = intval($mybb->input['pid']);
	$post = get_post($pid);
	if (!$post)
		return;

	$fid = $post['fid'];

	$forumrules = newpoints_getrules('forum', $fid);
	if ($forumrules['pointsview'] > $mybb->user['newpoints'])
	{
		$lang->load("newpoints");
		error($lang->sprintf($lang->newpoints_not_enough_points, newpoints_format_points($forumrules['pointsview'])));
	}
}

function newpoints_blockview_send()
{
	global $mybb, $lang, $fid;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;

	$forumrules = newpoints_getrules('forum', $fid);
	if ($forumrules['pointsview'] > $mybb->user['newpoints'])
	{
		$lang->load("newpoints");
		error($lang->sprintf($lang->newpoints_not_enough_points, newpoints_format_points($forumrules['pointsview'])));
	}
}

function newpoints_blockview_archive()
{
	global $mybb, $lang, $forum;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
	
	$fid = intval($forum['fid']);

	$forumrules = newpoints_getrules('forum', $fid);
	if ($forumrules['pointsview'] > $mybb->user['newpoints'])
	{
		$lang->load("newpoints");
		error($lang->sprintf($lang->newpoints_not_enough_points, newpoints_format_points($forumrules['pointsview'])));
	}
}

function newpoints_blockpost()
{
	global $mybb, $lang, $fid;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;

	$forumrules = newpoints_getrules('forum', $fid);
	if ($forumrules['pointspost'] > $mybb->user['newpoints'])
	{
		$lang->load("newpoints");
		error($lang->sprintf($lang->newpoints_not_enough_points, newpoints_format_points($forumrules['pointspost'])));
	}
}

function newpoints_inline_delete()
{
	global $db, $mybb, $pid, $post;
	
	if (!$mybb->user['uid'])
		return;
	
	if ($mybb->settings['newpoints_main_enabled'] != 1)
		return;
		
	$fid = intval($mybb->input['fid']);
		
	// check forum rules
	$forumrules = newpoints_getrules('forum', $fid);
	if (!$forumrules)
		$forumrules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the forum rate is 0, nothing is going to be added so let's just leave the function
	if ($forumrules['rate'] == 0)
		return;
	
	// check group rules - primary group check
	$grouprules = newpoints_getrules('group', $mybb->user['usergroup']);
	if (!$grouprules)
		$grouprules['rate'] = 1; // no rule set so default income rate is 1
	
	// if the group rate is 0, nothing is going to be added so let's just leave the function
	if ($grouprules['rate'] == 0)
		return;
		
	// we're deleting threads inline
	if($mybb->input['action'] == "do_multideleteposts")
  	{
		if ($mybb->settings['newpoints_income_newpost'] == 0)
			return;
		
		$posts = explode('|', $mybb->input['posts']);
		if(is_array($posts))
		{
			foreach($posts as $key => $pid)
			{
				$query = $db->simple_select('posts', 'uid,message', 'pid=\''.$pid.'\'');
				$feched_post = $db->fetch_array($query);
				
				// if we have more chars than the limit, we must remove the bonus
				if (my_strlen($fetched_post['message']) >= $mybb->settings['newpoints_income_minchar'])
					$bonus = my_strlen($fetched_post['message']) * $mybb->settings['newpoints_income_perchar'];
				else
					$bonus = 0;
				
				newpoints_addpoints($fetched_post['uid'], -($mybb->settings['newpoints_income_newpost']+$bonus), $forumrules['rate'], $grouprules['rate']);
			}
		}
	}
	// else if we're deleting posts inline
  	elseif($mybb->input['action'] == "do_multideletethreads")
  	{
		if ($mybb->settings['newpoints_income_newthread'] == 0)
			return;
		
		$threads = explode('|', $mybb->input['threads']);
		if(is_array($threads))
		{
			foreach($threads as $key => $tid)
			{
				$thread = get_thread($tid);
				newpoints_addpoints($thread['uid'], -($mybb->settings['newpoints_income_newthread']+($thread['replies']*$mybb->settings['newpoints_income_perreply'])), $forumrules['rate'], $grouprules['rate']);
			}
		}
	}
}

?>
