MyBB Community Forums

Full Version: SQL Error 1064 in profile comments
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi i install profile comments and i get this error(first say that all thing in local host is good)



MyBB SQL Error

MyBB has experienced an internal SQL error and cannot
continue.
SQL Error:1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 7Query  sELECT * FROM mybb_profilecomments p LEFT JOIN mybb_users u ON u.uid = p.sender LEFT JOIN mybb_usergroups g ON u.usergroup = g.gid WHERE p.user = 1 ORDER BY date DESC LIMIT 0,
Please contact the MyBB Group for technical support. 



<?php

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

/**
 * Return plugin info
 *
 */
function profilecomments_info()
{
	/**
	 * Array of information about the plugin.
	 * name: The name of the plugin
	 * description: Description of what the plugin does
	 * website: The website the plugin is maintained at (Optional)
	 * author: The name of the author of the plugin
	 * authorsite: The URL to the website of the author (Optional)
	 * version: The version number of the plugin
	 * guid: Unique ID issued by the MyBB Mods site for version checking
	 * compatibility: A CSV list of MyBB versions supported. Ex, "121,123", "12*". Wildcards supported.
	 */
	return array(
				"name" => "یادداشت در پروفایل",
				"description" => "این پلاگین، امکان ارسال یادداشت در پروفایل کاربر ها را فراهم می کند، فارسی سازی توسط MyBBIran.com",
				"website" => "http://mods.mybboard.net/view/profile-comments/",
				"author" => "Santiago Dimattia",
				"authorsite" => "http://www.teleportz.com.ar",
				"version" => "0.9.2",
				"guid" => "e6063fe5a0fd9b7b7982f68336bf1d4d",
				"compatibility" => "*"
			);
}

/*************************************************************************************************************************************** HOOKS */

// GLOBAL
$plugins->add_hook('global_start', 'profilecomments_mark_comments_as_read', 5);
$plugins->add_hook('global_start', 'profilecomments_new_comments');

// PROFILE
$plugins->add_hook('member_profile_start', 'profilecomments_page');

// AJAX
$plugins->add_hook('xmlhttp', 'profilecomments_ajax_comment');

// ACP
$plugins->add_hook('admin_formcontainer_end', 'profilecomments_edit_group');
$plugins->add_hook('admin_user_groups_edit_commit', 'profilecomments_edit_group_do');

// UCP
$plugins->add_hook('usercp_do_options_end', 'profilecomments_update_user_settings');
$plugins->add_hook('usercp_options_start', 'profilecomments_user_settings_check');

/*************************************************************************************************************************************** REQUIRE CORE CLASSES */

/**
 * ProfileComments Master Class
 *
 * @author Santiago Dimattía <[email protected]>
 * @version 0.1-dev
 */
class Comments {

	/**
	 * Instance
	 *
	 */
	private static $instance;

	/**
	 * Target user
	 *
	 */
	public $target = array();

	/**
	 * Error message
	 *
	 */
	public $error = '';

	/**
	 * Message in the redirect
	 *
	 */
	public $message = '';

	/**
	 * Library Class
	 *
	 * @access protected
	 */
	public $lib;

	/**
	 * Model Class
	 *
	 * @access protected
	 */
	public $model;

	/**
	 * Return class instance
	 *
	 */
	public static function instance()
	{
		if(!is_object($instance))
		{
			$instance = new self;
		}

		return $instance;
	}

	/**
	 * Construct
	 *
	 */
	public function __construct()
	{
		global $mybb, $lang;

		// Load profilecomments lang file
		$lang->load('profilecomments');

		// Load the model and the library
		$this->model = new Comments_Model();
		$this->lib = new Comments_Library();

		// Set target user
		if(!empty($mybb->input['uid']) && $mybb->input['uid'] != $mybb->user['uid'])
		{
			$this->target = $this->model->user_get((int)$mybb->input['uid']);
		}
		else
		{
			$this->target = $mybb->user;
		}
	}

	/**
	 * Do actions: delete, edit or create a new comment
	 *
	 * @access public
	 * @return mixed
	 */
	public function do_actions()
	{
		global $mybb;

		// If the user is not logged, don't do anything
		if(!$mybb->user['uid'])
		{
			return false;
		}

		switch($mybb->input['op'])
		{
			case 'delete':
				$action = $this->delete_comment();
			break;

			case 'do_edit':
				$action = $this->edit_comment();
			break;

			case 'edit':
				$action = $this->edit_comment_form();
			break;

			case 'new':
				$action = $this->new_comment();
			break;
		}

		if(!isset($action))
		{
			return false;
		}

		if(!$action)
		{
			error($this->error);
			exit;
		}
	}

	/**
	 * Display on profile
	 *
	 * @access public
	 * @return void
	 */
	public function display()
	{
		global $mybb, $db, $templates, $lang, $theme, $comments_index, $pf_statistics, $comments_form_edit;

		if(!$mybb->input['uid'])
		{
			$mybb->input['uid'] = $mybb->user['uid'];
		}

		// Show user statistics
		if($mybb->settings['profilecomments_show_statistics'] && $this->target['uid'])
		{
			$statistics = $this->model->user_statistics($this->target['uid']);
			$received = $statistics['received'];
			$given = $statistics['given'];

			eval("\$pf_statistics .= \"".$templates->get("profile_comments_statistics")."\";");
		}
		else
		{
			$pf_statistics = '';
		}
	
		// Query the number of comments
		$quantity = $this->model->comments_count($this->target['uid']);

		// Get the query offset
		$offset = $this->lib->pagination($quantity);

		// Get the comments
		if($comments_array = $this->model->comments_get_all($this->target['uid'], $mybb->settings['profilecomments_perpage'], $offset))
		{
			$comments = '';
			$style = 'trow1';

			foreach($comments_array AS $comment)
			{
				$comments .= $this->lib->render_comment($comment, $style);
				$style = alt_trow();
			}
		}
		else
		{
			eval("\$comments = \"".$templates->get("profile_comments_nocomments")."\";");
		}

		// Get page number
		$page = 1;
		if($mybb->input['page'])
		{
			$page = (int) $mybb->input['page'];
		}

		// Render pagination
		$pagination = multipage($quantity, (int) $mybb->settings['profilecomments_perpage'], $page, 'member.php?action=profile&uid=' . $this->target['uid']);

		// If the user can send comments, show the comments form
		if($this->lib->can_send_to($this->target['uid'], $mybb->user['uid']))
		{
			// Is the bbcode editor active?
			$editor = '';
			$editor_active = 0;
			if($mybb->settings['profilecomments_show_editor'] == 1)
			{
				$editor = build_mycode_inserter();
				$editor_active = 1;
			}

			// Is AJAX active?
			$ajax = 0;
			if($mybb->settings['profilecomments_ajax'] == 1)
			{
				$ajax = 1;
			}
			
			// Show the comments form
			eval("\$comments_form = \"".$templates->get("profile_comments_form")."\";");
		}
		else
		{
			// Show why the user can't send a message
			$reason = $lang->sprintf($lang->pf_reason_message, $this->lib->error);
			eval("\$comments_form = \"".$templates->get("profile_comments_form_no_access")."\";");
		}

		// Render the page!
		eval("\$comments_index = \"".$templates->get("profile_comments")."\";");
	}

	/**
	 * Show edit comment form
	 *
	 * @access public
	 * @return bool
	 */
	public function edit_comment_form()
	{
		global $mybb, $lang, $templates, $comments_form_edit, $theme;

		// If the user can edit the comment
		if($this->lib->can_manage_comment((int) $mybb->input['mid'], $mybb->user['uid'], 'edit'))
		{
			$comment = $this->model->comment_get((int) $mybb->input['mid']);
			$user = $this->model->user_get($comment['uid']);

			$edit_form_title = $lang->sprintf($lang->profile_comments_editing, (int) $mybb->input['mid'], $user['username']);
			eval("\$comments_form_edit = \"".$templates->get("profile_comments_form_edit")."\";");
		}
	}

	/**
	 * Adding a new comment page
	 *
	 * @access public
	 * @return bool
	 */
	public function new_comment()
	{
		global $mybb, $lang;

		if(isset($mybb->input['reply_to_profile']) && $mybb->input['reply_to_profile'] != 'default')
		{
			$this->target = $this->model->user_get((int) $mybb->input['reply_to_profile']);
		}

		if(!$this->target)
		{
			$this->error = $lang->profilecomments_invalid_uid;
			return false;
		}

		if($this->lib->comment_add($mybb->user['uid'], $this->target['uid'], $mybb->input['message']))
		{
			$this->lib->redirect($this->target['uid'], $lang->profile_comments_added);
		}

		error($this->lib->error);
	}

	/**
	 * Delete an existing comment
	 *
	 * @access public
	 * @return bool
	 */
	public function delete_comment()
	{
		global $mybb, $lang;

		$comment = $this->model->comment_get((int) $mybb->input['mid']);

		if(!$comment)
		{
			$this->error = $lang->profile_comments_invalid_id;
			return false;
		}

		if($this->lib->comment_delete($comment['mid'], $mybb->user['uid']))
		{
			$this->lib->redirect($mybb->input['uid'], $lang->profile_comments_deleted);
		}

		error($this->lib->error);
	}

	/**
	 * Edit an comment
	 *
	 * @access public
	 * @return bool
	 */
	public function edit_comment()
	{
		global $mybb, $lang;

		$comment = $this->model->comment_get((int) $mybb->input['mid']);

		if(!$comment)
		{
			$this->error = $lang->profile_comments_invalid_id;
			return false;
		}

		$this->lib->comment_edit($comment['mid'], $mybb->user['uid'], $mybb->input['editmessage']);

		$this->lib->redirect($mybb->input['uid'], $lang->profile_comments_edited);
	}

	/**
	 * Update the newcomments value
	 *
	 * @access public
	 * @return bool
	 */
	public function update_newcomments()
	{
		global $mybb;

		// If the user is not logged in or isn't viewing a profile, return
		if(!$mybb->user['uid'] OR (THIS_SCRIPT != 'member.php' && $mybb->input['action'] != 'profile'))
		{
			return false;
		}

		// If the user is not in his own profile, return
		if(($mybb->input['uid'] && $mybb->input['uid'] != $mybb->user['uid']))
		{
			return false;
		}

		// Reset the counter on the DB
		return $this->lib->mark_comments_as_read($mybb->user['uid']);
	}

	/**
	 * Show ProfileComments link on the site header
	 *
	 * @access public
	 * @return bool
	 */
	public function show_header_text()
	{
		global $mybb, $db, $templates, $lang, $comments_alert;
		
		// Set New Comments var
		$new_comments = $mybb->user['newcomments'];

		// If the user is logged in and has new comments
		if($mybb->user['uid'] != 0 && $new_comments > 0)
		{
			// Show the numer "(x)" in the header
			$lang->profile_comments_new_inmenu_count = $lang->sprintf($lang->profile_comments_new_inmenu_count, $new_comments);
			
			// If alert bar is active, show it
			if($mybb->settings['profilecomments_alertbar'] == 1)
			{
				$comments_alert_text = $lang->sprintf($mybb->settings['profilecomments_alertbar_text'], $new_comments);
				eval("\$comments_alert .= \"".$templates->get("profile_comments_alert")."\";");
			}
		}
		else
		{
			$lang->profile_comments_new_inmenu_count = '';
		}
	}

	/**
	 * Called by AJAX
	 *
	 * @access public
	 * @todo change REPLY_TO_PROFILE to REPLY?
	 * @return bool
	 */
	public function call_ajax()
	{
		global $mybb, $db, $lang, $parser;

		if($mybb->input['action'] != 'profile' OR $mybb->input['section'] != 'comments')
		{
			return false;
		}

		// If the user is not logged, don't do anything
		if(!$mybb->user['uid'])
		{
			return false;
		}

		// Set target
		if(isset($mybb->input['reply_to_profile']) && $mybb->input['reply_to_profile'] != 'default')
		{
			$this->target = $this->model->user_get((int) $mybb->input['reply_to_profile']);
		}

		if(!$this->lib->can_send_to($this->target['uid'], $mybb->user['uid']))
		{
			xmlhttp_error($lang->sprintf($lang->pf_reason_message, $this->lib->error));
			exit;
		}

		if(!$this->target)
		{
			xmlhttp_error($lang->profilecomments_invalid_uid);
			exit;
		}

		// Add the comment
		$this->lib->comment_add($mybb->user['uid'], $this->target['uid'], $mybb->input['message']);

		// Get the comment ID
		$mid = $db->insert_id();
		$comment = $this->model->comment_get($mid);

		echo $this->lib->render_comment($comment);
		exit;
	}

	/**
	 * Called normally...
	 *
	 * @access public
	 * @return bool
	 */
	public function call_normal()
	{
		$this->do_actions();
		$this->display();

		// TODO: View conversations between 2 users?
		// $q = $db->query('SELECT * FROM ' . TABLE_PREFIX . 'profilecomments WHERE (user = 1 AND sender = 2) OR (user = 2 AND sender = 1)');
	}
}

/**
 * Library Comments Class
 *
 */
class Comments_Library {

	/**
	 * Error
	 *
	 */
	public $error = '';


	/**
	 * Pagination helper
	 *
	 * @access public
	 * @param string $quantity Quantity of comments to paginate
	 * @param string $page Current page number
	 * @param string $perpage Comments to show per page
	 * @return string
	 */
	public function pagination($quantity, $page = NULL, $perpage = NULL)
	{
		global $mybb;

		if(!isset($page))
		{
			$page = (int) $mybb->input['page'];
		}

		if(!isset($perpage))
		{
			$perpage = (int) $mybb->settings['profilecomments_perpage'];
		}

		// Pagination magic
		if($page > 0)
		{
			$start = ($page - 1) * $perpage;
			$pages = $quantity / $perpage;
			$pages = ceil($pages);
			if($page > $pages || $page <= 0)
			{
				$start = 0;
			}
		}
		else
		{
			$start = 0;
		}

		return $start;
	}

	/**
	 * Render comment 
	 *
	 * @access public
	 * @param array $data Comment Data
	 * @param string $style Row style
	 * @return mixed
	 */
	public function render_comment($comment = array(), $style = 'trow1')
	{
		global $mybb, $lang, $db, $templates;

		if(count($comment) <= 0)
		{
			return FALSE;
		}

		$pf = Comments::instance();

		$target =& $pf->target;
		
		// Set uid
		$id = $comment['mid'];
				
		// Format date
		$date = my_date($mybb->settings['dateformat'], $comment['date']);
		$time = my_date($mybb->settings['timeformat'], $comment['date']);

		// Format and link username
		$username = format_name($comment['username'], $comment['usergroup'], $comment['displaygroup']);
		$username = build_profile_link($username, $comment['sender']);

		// Default avatar
		$avatar = (!empty($comment['avatar'])) ? $comment['avatar'] : $mybb->settings['profilecomments_default_avatar'];
		
		// Parse bbcode
		$text = $this->parse_comment($comment['text']);
		// TODO: Consistency. Here I use "text". In the class I use "message". Choose.
		
		// Show edit link if the current user can edit this comment
		$edit = '';
		if(($mybb->usergroup['caneditselfcomments'] && $mybb->user['uid'] == $comment['sender']) OR $mybb->usergroup['canmanagecomments'])
		{
			eval("\$edit = \"".$templates->get("profile_comments_edit")."\";");
		}
		
		// Show delete link if the current user can delete this comment
		$delete = '';
		if(($mybb->usergroup['candeleteselfcomments'] && $mybb->user['uid'] == $comment['sender']) OR $mybb->usergroup['canmanagecomments'])
		{
			eval("\$delete = \"".$templates->get("profile_comments_delete")."\";");
		}
		
		// If user can send comments & is not editing a comment
		$reply = '';
		if($this->can_send_to($pf->target['uid'], $mybb->user['uid']))
		{
			// TODO: PHP fallback for the reply link - dosn't work without js
			eval("\$reply .= \"".$templates->get("profile_comments_reply")."\";");
		}
		
		eval("\$comments .= \"".$templates->get("profile_comments_list")."\";");

		return $comments;
	}

	/**
	 * Returns true or false if a user can manage an comment
	 *
	 * @access public
	 * @param string $mid Comment ID
	 * @param string $uid User ID
	 * @param string $action Action to validate (edit/delete)
	 * @return bool
	 */
	public function can_manage_comment($mid, $uid, $action = 'edit')
	{
		global $mybb, $db, $cache, $pf;

		$pf = Comments::instance();

		// Get the comment data
		$comment = $pf->model->comment_get($mid);

		// If the comment dosn't exists, throw error
		if(!$comment)
		{
			return false;
		}

		// Get the user and the usergroup info
		$user = $pf->model->user_get($uid);
		$usergroups = $cache->read('usergroups');

		// If the user group is an comments-admin, allow to manage the comment
		if($usergroups[$user['usergroup']]['canmanagecomments'])
		{
			return true;
		}

		// If the users has sent this comment
		if($comment['sender'] == $user['uid'])
		{
			// And can edit own comments
			if($action == 'edit' && $usergroups[$user['usergroup']]['caneditselfcomments'])
			{
				return true;
			}

			// And can delete own comments
			if($action == 'delete' && $usergroups[$user['usergroup']]['candeleteselfcomments'])
			{
				return true;
			}
		}

		return false;
	}

	/**
	 * Parse comment
	 *
	 * @access public
	 * @param string $message Comment content
	 * @return string
	 */
	public function parse_comment($message)
	{
		global $mybb, $parser;

		// Check if the parser has been loaded before
		if(!isset($parser))
		{
			require_once MYBB_ROOT . 'inc/class_parser.php';
			$parser = new postParser;
		}

		// Parse bbcode
		$options = array(
			"allow_html" => (int)$mybb->settings['profilecomments_allow_html'],
			"allow_mycode" => (int)$mybb->settings['profilecomments_allow_bbcode'],
			"allow_smilies" => (int)$mybb->settings['profilecomments_allow_smilies'],
			"allow_imgcode" => (int)$mybb->settings['profilecomments_allow_imgcode'],
			"filter_badwords" => (int)$mybb->settings['profilecomments_filter_badwords']
		);

		return $parser->parse_message($message, $options);
	}

	/**
	 * Checks if an user can send a comment to another user
	 *
	 * @access public
	 * @param string $target Target User ID
	 * @param string $user Current User ID
	 * @return bool
	 */
	public function can_send_to($target, $user)
	{
		global $mybb, $cache, $lang;

		if(!is_numeric($target) OR !is_numeric($user))
		{
			return FALSE;
		}

		$pf = Comments::instance();

		$target = $pf->model->user_get($target);
		$user = $pf->model->user_get($user);
		$usergroups = $cache->read('usergroups');

		// If some UID is invalid
		if(!$target OR !$user)
		{
			$this->error = $lang->profilecomments_invalid_uid;
			return false;
		}

		// If the current user group is not allowed to send comments
		if($usergroups[$user['usergroup']]['cansendcomments'] == 0)
		{
			$this->error = $lang->pf_reason_you_cant_comment;
			return false;
		} 

		// If the target user is banned
		if($usergroups[$target['usergroup']]['isbannedgroup'] == 1 && $mybb->settings['profilecomments_close_comments_on_banned'] == 1)
		{
			$this->error = $lang->pf_reason_user_is_banned;
			return false;
		}

		// If the target user has deactivated the comments on his/her profile
		if($target['commentsfilter'] == 2)
		{
			$this->error = $lang->pf_reason_nobody_can_comment;
			return false;
		}

		// If the target is ignoring the user (And the option 'Ignored users can send comments' is active on the ACP)
		if($mybb->settings['profilecomments_ignored_can_send_comments'] == 0)
		{
			if(in_array($user['uid'], explode(',', $target['ignorelist'])))
			{
				$this->error = $lang->pf_reason_you_are_being_ignored;
				return false;
			}
		}

		// If the target user is the same as the current user, it's allowed to send comments.
		if($target['uid'] == $user['uid'])
		{
			return true;
		}

		// If the target user only accepts comments from friends, check if I'm one of them
		if($target['commentsfilter'] == 1)
		{
			if(!in_array($user['uid'], explode(',', $target['buddylist'])))
			{
				$this->error = $lang->pf_reason_only_friends_can_comment;
				return false;
			}
		}

		// If I don't have any check left, the user can send the comment.
		return true;
	}

	/**
	 * Alert the user that he received a new comment (alertbart, email) 
	 *
	 * @access protected
	 * @param string $target Target User ID
	 * @param string $user Current User ID
	 * @return bool
	 */
	public function alert_user($target, $user)
	{
		global $mybb, $lang, $pf;

		// If some uid is invalid
		if(!is_numeric($target) OR !is_numeric($user))
		{
			return false;
		}

		// Don't show me the alert if i'm posting a comment on my profile...
		if($target == $user)
		{
			return false;
		}

		$pf = Comments::instance();

		// Get users data
		$target = $pf->model->user_get($target);
		$user = $pf->model->user_get($user);

		// If some user is invalid
		if(!$target OR !$user)
		{
			return false;
		}

		// Update the newcomments value
		$update = array(
			'newcomments' => $target['newcomments'] + 1
		);
		$pf->model->user_update($target['uid'], $update);

		// Send a comment notification, but only if the user has activated the option and we didn't send an email after his last visit
		if(!$target['newcomments'] && $target['commentnotify'])
		{
			// Everything is okay, send the email
			$subject = $lang->sprintf($lang->comment_notify_subject, $mybb->settings['bbname']);
			$message = $lang->sprintf($lang->comment_notify_message, $target['username'], $user['username'], $mybb->settings['bbname'], $mybb->settings['bburl'], $target['uid']);
		
			my_mail($target['email'], $subject, $message);
		}

		return TRUE;
	}

	/**
	 * Mark comments as read
	 *
	 * @access public
	 * @param string $uid User ID
	 * @return bool
	 */
	public function mark_comments_as_read($uid = NULL)
	{
		global $mybb;

		if(!isset($uid))
		{
			return false;
		}

		$pf = Comments::instance();

		$user = $pf->model->user_get($uid);

		// Only update if the user has new comments!
		if(isset($user['newcomments']) && $user['newcomments'] > 0)
		{
			return $pf->model->user_update($uid, array('newcomments' => 0));
		}

		return false;
	}

	/**
	 * Redirect to a user profile
	 *
	 * @access public
	 * @param string $uid User ID
	 * @param string $message Message to show
	 * @return bool
	 */
	public function redirect($uid = null, $message = null)
	{
		if(!isset($uid))
		{
			return false;
		}

		redirect('member.php?action=profile&uid=' . (int) $uid, $message);
		exit;
	}

	/**
	 * Add a comment
	 *
	 * @access public
	 * @param string $user User ID
	 * @param string $target Target UID
	 * @param string $message Comment
	 * @return bool
	 */
	public function comment_add($user, $target, $message)
	{
		global $mybb, $lang;

		if(!$this->can_send_to($target, $user))
		{
			$this->error = $lang->profilecomments_no_permission;
			return false;
		}

		if(empty($message))
		{
			$this->error = $lang->profile_comments_insert_comment;
			return false;
		}

		// Alert the user
		$this->alert_user($target, $user);

		// Insert the comment
		return Comments::instance()->model->comment_new($target, $user, $message);
	}

	/**
	 * Edit a comment
	 *
	 * @access public
	 * @param string $mid Comment ID
	 * @param string $uid User ID
	 * @param string $message Comment message
	 * @return bool
	 */
	public function comment_edit($mid, $uid, $message)
	{
		global $mybb, $lang;

		if(!$this->can_manage_comment($mid, $uid, 'edit'))
		{
			$this->error = $lang->profilecomments_no_permission;
			return false;
		}

		// If the message is empty, delete the comment
		if(empty($message))
		{
			$this->error = $lang->profile_comments_insert_comment;
			return false;
		}

		return Comments::instance()->model->comment_edit($mid, array('text' => $mybb->input['editmessage']));
	}

	/**
	 * Delete a comment
	 *
	 * @access public
	 * @param string $mid Comment ID
	 * @param string $uid User ID - If null, don't check for user validation
	 * @return bool
	 */
	public function comment_delete($mid, $uid = NULL)
	{
		global $mybb, $lang;

		if(isset($uid))
		{
			if(!$this->can_manage_comment($mid, $uid, 'delete'))
			{
				$this->error = $lang->profilecomments_no_permission;
				return false;
			}
		}

		return Comments::instance()->model->comment_delete($mid);
	}
}

/**
 * Model Comments Class
 *
 */
class Comments_Model {
	
	/**
	 * User cache
	 *
	 * @access protected
	 */
	protected $users = array();

	/**
	 * Comments cache
	 *
	 * @access protected
	 */
	protected $comments = array();

	/**
	 * User statistics
	 *
	 * @access protected
	 */
	protected $statistics = array();

	/**
	 * Count comments
	 *
	 * @access public
	 * @param string $uid User ID
	 * @return mixed
	 */
	public function comments_count($uid = NULL)
	{
		global $db;

		if(isset($uid))
		{
			$where = 'user = ' . $uid;
		}
		else
		{
			$where = FALSE;
		}

		$q = $db->simple_select('profilecomments', 'COUNT(mid) AS quantity', $where, array('limit' => 1));

		return $db->fetch_field($q, 'quantity');
	}

	/**
	 * Get comments
	 *
	 * @access public
	 */
	public function comments_get_all($uid = NULL, $perpage = 10, $offset = 0)
	{
		global $db;

		if(isset($uid))
		{
			$where_user = 'WHERE p.user = ' . $uid;
		}
		else
		{
			$where_user = '';
		}

		// Select the comments from the DB
		$q = $db->query('
		SELECT * FROM ' . TABLE_PREFIX . 'profilecomments p
		LEFT JOIN ' . TABLE_PREFIX . 'users u ON u.uid = p.sender
		LEFT JOIN ' . TABLE_PREFIX . 'usergroups g ON u.usergroup = g.gid
		' . $where_user . '
		ORDER BY date
		DESC
		LIMIT ' . $offset . ', ' . $perpage);

		if($db->num_rows($q) > 0)
		{
			$comments = array();
			while($row = $db->fetch_array($q))
			{
				$comments[] = $row;
			}

			return $comments;
		}

		return FALSE;
	}

	/**
	 * Gets an user
	 *
	 * @access public
	 * @param string $uid User ID
	 * @return mixed
	 */
	public function user_get($uid)
	{
		global $mybb, $db;

		if(isset($this->users[$uid]))
		{
			return $this->users[$uid];
		}

		if($uid == $mybb->user['uid'])
		{
			$this->users[$uid] =& $mybb->user;
			return $this->users[$uid];
		}

		$q = $db->simple_select('users', '*', 'uid = ' . $uid, array('limit' => 1));

		if($db->num_rows($q) > 0)
		{
			$this->users[$uid] = $db->fetch_array($q);
			$this->users[$uid]['profile_url'] = 'member.php?action=profile&uid=' . $this->users[$uid]['uid'];

			return $this->users[$uid];
		}

		return FALSE;
	}

	/**
	 * Updates an user
	 *
	 * @access public
	 * @param string $uid User ID
	 * @param array $data Data to update
	 * @return bool
	 */
	public function user_update($uid = null, $data = null)
	{
		global $db;

		if(!isset($uid) OR !isset($data))
		{
			return false;
		}

		foreach($data as $key => $val)
		{
			$values[$key] = $db->escape_string($val);
		}

		return $db->update_query('users', $values, 'uid = ' . $uid, 1);
	}


	/**
	 * Get user statistics
	 *
	 * @access public
	 * @param string $uid User ID
	 * @return bool
	 */
	public function user_statistics($uid)
	{
		global $db;

		if(isset($this->statistics[$uid]))
		{
			return $this->statistics[$uid];
		}

		$q = $db->simple_select('profilecomments', 'COUNT(mid) AS quantity', 'sender = ' . $uid, array('limit' => 1));
		$q2 = $db->simple_select('profilecomments', 'COUNT(mid) AS quantity', 'user = ' . $uid, array('limit' => 1));

		if($db->num_rows($q) > 0)
		{
			$this->statistics[$uid] = array(
				'given' => $db->fetch_field($q, 'quantity'),
				'received' => $db->fetch_field($q2, 'quantity')
			);

			return $this->statistics[$uid];
		}

		return FALSE;
	}

	/**
	 * Get comment
	 *
	 * @access public
	 * @param string $mid Comment ID
	 * @return mixed
	 */
	public function comment_get($mid)
	{
		global $db;

		if(isset($this->comments[$mid]))
		{
			return $this->comments[$mid];
		}


		$q = $db->query('
		SELECT * FROM ' . TABLE_PREFIX . 'profilecomments p
		LEFT JOIN ' . TABLE_PREFIX . 'users u ON u.uid = p.sender
		LEFT JOIN ' . TABLE_PREFIX . 'usergroups g ON u.usergroup = g.gid
		WHERE mid = ' . $mid . '
		LIMIT 1');

		if($db->num_rows($q) > 0)
		{
			$this->user[$uid] = $db->fetch_array($q);
			return $this->user[$uid];
		}

		return FALSE;
	}

	/**
	 * Create a new comment
	 *
	 * @access public
	 * @param string $uid User ID
	 * @param string $who The one who sent the comment
	 * @param string $text Comment content
	 * @return bool
	 */
	public function comment_new($uid, $who, $text)
	{
		global $mybb, $db;

		$data = array(
			'user' => $uid,
			'sender' => $who,
			'text' => $db->escape_string($text),
			'date' => time()
		);

		$db->insert_query('profilecomments', $data);

		return TRUE;
	}

	/**
	 * Delete comment
	 *
	 * @access public
	 * @param string $mid Comment ID
	 * @return bool
	 */
	public function comment_delete($mid)
	{
		global $db;

		if($db->delete_query('profilecomments', 'mid = ' . $mid))
		{
			return TRUE;
		}

		return FALSE;
	}

	/**
	 * Comment edit
	 *
	 * @access public
	 * @param string $mid Comment ID
	 * @param arrya $data New comment data
	 * @return bool
	 */
	public function comment_edit($mid, $data)
	{
		global $db;

		if(!is_numeric($mid))
		{
			return FALSE;
		}

		// Don't update the ID
		if(isset($data['mid']))
		{
			unset($data['mid']);
		}

		foreach($data as $key => $val)
		{
			$values[$key] = $db->escape_string($val);
		}

		if($db->update_query('profilecomments', $values, 'mid = ' . $mid, 1))
		{
			return TRUE;
		}

		return FALSE;
	}
}

/*************************************************************************************************************************************** WORKAROUNDS */

/**
 * Add a comment via AJAX
 *
 */
function profilecomments_ajax_comment()
{
	return Comments::instance()->call_ajax();
}

/**
 * Runs the Comments page
 *
 */
function profilecomments_page()
{
	return Comments::instance()->call_normal();
}

/**
 * Show the link to the profile in the header and cache all the plugin templates
 *
 */
function profilecomments_new_comments()
{
	global $templatelist;

	// Cache the templates - saves 1 query for every template in use
	if(THIS_SCRIPT == 'member.php')
	{
		$templatelist .= ',profile_comments_statistics,profile_comments_edit,profile_comments_delete,profile_comments_reply,profile_comments_list,multipage_page_current,multipage_page,multipage_nextpage,multipage,codebuttons,profile_comments_form,profile_comments';
	}
	
	return Comments::instance()->show_header_text();
}

/**
 * Mark comments as read
 *
 */
function profilecomments_mark_comments_as_read()
{
	return Comments::instance()->update_newcomments();
}

/*************************************************************************************************************************************** ACP FUNCTIONS */

/**
 * Add usergroup permissions to the ACP
 *
 */
function profilecomments_edit_group()
{
	global $run_module, $form_container, $lang, $form, $mybb;

	// If the current tab is "Users & Permissions", add plugin options
	if($run_module == 'user' && !empty($form_container->_title) & !empty($lang->users_permissions) & $form_container->_title == $lang->users_permissions)
	{
		// Load the language
		$lang->load('profilecomments');

		// And generate the checkbox
		$profilecomments_options = array();
		$profilecomments_options[] = $form->generate_check_box('canmanagecomments', 1, $lang->profile_comments_can_manage, array('checked' => $mybb->input['canmanagecomments']));
		$profilecomments_options[] = $form->generate_check_box('cansendcomments', 1, $lang->profile_comments_can_send, array('checked' => $mybb->input['cansendcomments']));
		$profilecomments_options[] = $form->generate_check_box('caneditselfcomments', 1, $lang->profile_comments_can_selfedit, array('checked' => $mybb->input['caneditselfcomments']));
		$profilecomments_options[] = $form->generate_check_box('candeleteselfcomments', 1, $lang->profile_comments_can_selfdelete, array('checked' => $mybb->input['candeleteselfcomments']));
		
		$form_container->output_row($lang->profile_comments, '', '<div class="group_settings_bit">'.implode('</div><div class="group_settings_bit">', $profilecomments_options).'</div>');
	}
}

/**
 * Update the usergroup permissions on the ACP
 *
 */
function profilecomments_edit_group_do()
{
	global $updated_group, $mybb;

	$updated_group['canmanagecomments'] = $mybb->input['canmanagecomments'];
	$updated_group['cansendcomments'] = $mybb->input['cansendcomments'];
	$updated_group['caneditselfcomments'] = $mybb->input['caneditselfcomments'];
	$updated_group['candeleteselfcomments'] = $mybb->input['candeleteselfcomments'];
}

/*************************************************************************************************************************************** UCP FUNCTIONS */

/**
 * Add settings on the UCP
 *
 */
function profilecomments_user_settings_check()
{
	global $mybb, $templates, $lang, $pf_notification_options;

	if($mybb->user['commentnotify'])
	{
		$commentnotifycheck = 'checked="checked"';
	}
	else
	{
		$commentnotifycheck = '';
	}

	if($mybb->user['commentsfilter'] == 0)
	{
		$anyone_can_leave_comments = 'selected="selected"';
		$only_friends_can_leave_comments = '';
		$nobody_can_leave_comments = '';
	}
	elseif($mybb->user['commentsfilter'] == 1)
	{
		$anyone_can_leave_comments = '';
		$only_friends_can_leave_comments = 'selected="selected"';
		$nobody_can_leave_comments = '';
	}
	else
	{
		$anyone_can_leave_comments = '';
		$only_friends_can_leave_comments = '';
		$nobody_can_leave_comments = 'selected="selected"';
	}

	eval("\$pf_notification_options = \"".$templates->get("profile_comments_ucp_notification")."\";");
}


/**
 * Update the user settings on the UCP
 *
 */
function profilecomments_update_user_settings()
{
	global $mybb, $db;

	// Don't change the setting if it has the same value
	if($mybb->input['commentnotify'] == $mybb->user['commentnotify'] && $mybb->input['commentsfilter'] == $mybb->user['commentsfilter'])
	{
		return TRUE;
	}

	$update = array('commentnotify' => (int) $mybb->input['commentnotify'], 'commentsfilter' => (int) $mybb->input['commentsfilter']);
	$db->update_query('users', $update, 'uid = ' . $mybb->user['uid'], 1);

	return TRUE;
}

/*************************************************************************************************************************************** INFO/NSTALL FUNCTIONS */

/**
 * Install function
 *
 */
function profilecomments_install()
{
	global $lang, $db, $cache;
	
	// Load the language
	$lang->load('profilecomments');

	// Creates the table where comments are saved
	$tables = "CREATE TABLE `".TABLE_PREFIX."profilecomments` (
  `mid` int(10) NOT NULL auto_increment,
  `user` int(10) NOT NULL,
  `sender` int(10) NOT NULL,
  `text` text NOT NULL,
  `date` int(10) NOT NULL,
  PRIMARY KEY  (`mid`)
)   DEFAULT CHARSET=utf8 AUTO_INCREMENT=18 ;";
	$db->write_query($tables);

	// Creates fields for groups-based permissions
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."usergroups` ADD `canmanagecomments` INT(1) NOT NULL DEFAULT '0';");
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."usergroups` ADD `cansendcomments` INT(1) NOT NULL DEFAULT '0';");
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."usergroups` ADD `caneditselfcomments` INT(1) NOT NULL DEFAULT '0';");
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."usergroups` ADD `candeleteselfcomments` INT(1) NOT NULL DEFAULT '0';");
	
	// Give access to send and edit own comments to ALL USERGROUPS
	$db->write_query('UPDATE '.TABLE_PREFIX.'usergroups SET canmanagecomments = "0", cansendcomments = "1", caneditselfcomments = "1"');
	// Give access to EDIT & DELETE (all comments) to Administrators
	$db->write_query('UPDATE '.TABLE_PREFIX.'usergroups SET canmanagecomments = "1", candeleteselfcomments = "1" WHERE gid = "4"');
	// Delete all access for guests
	$db->write_query('UPDATE '.TABLE_PREFIX.'usergroups SET cansendcomments = "0", caneditselfcomments = "0" WHERE gid = "1"');
	// Delete all access for banned users
	$db->write_query('UPDATE '.TABLE_PREFIX.'usergroups SET cansendcomments = "0", caneditselfcomments = "0" WHERE gid = "7"');
	// Delete all access for 'awaiting activation' users
	$db->write_query('UPDATE '.TABLE_PREFIX.'usergroups SET cansendcomments = "0", caneditselfcomments = "0" WHERE gid = "5"');
	
	// Update usergroups cache
	$cache->update_usergroups();

	// Creates a field in users table (For new comments alert)
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."users` ADD `newcomments` INT(10) NOT NULL DEFAULT '0';");
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."users` ADD `commentnotify` INT(10) NOT NULL DEFAULT '0';");
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."users` ADD `commentsfilter` INT(10) NOT NULL DEFAULT '0';");

	// Create the config group for MyBB Settings
	$query = $db->simple_select("settinggroups", "COUNT(*) as rows");
	$rows = $db->fetch_field($query, "rows");

	$new_groupconfig = array(
		'name' => 'profilecomments', 
		'title' => $db->escape_string($lang->profile_comments),
		'description' => $db->escape_string($lang->profile_comments_info),
		'disporder' => $rows+1,
		'isdefault' => 0
	);
	
	$group['gid'] = $db->insert_query("settinggroups", $new_groupconfig);

	// Insert ProfileComments options
	$new_config = array();
	
	$new_config[] = array(
		'name' => 'profilecomments_perpage',
		'title' => $db->escape_string($lang->profile_comments_perpage),
		'description' => $db->escape_string($lang->profile_comments_perpage_info),
		'optionscode' => 'text',
		'value' => '4',
		'disporder' => 1,
		'gid' => $group['gid']
	);
	
	$new_config[] = array(
		'name' => 'profilecomments_alertbar',
		'title' => $db->escape_string($lang->profile_comments_alertbar),
		'description' => $db->escape_string($lang->profile_comments_alertbar_info),
		'optionscode' => 'yesno',
		'value' => '0',
		'disporder' => 2,
		'gid' => $group['gid']
	);
	
	$new_config[] = array(
		'name' => 'profilecomments_alertbar_text',
		'title' => $db->escape_string($lang->profile_comments_alertbar_text),
		'description' => $db->escape_string($lang->profile_comments_alertbar_text_info),
		'optionscode' => 'text',
		'value' => $db->escape_string($lang->profile_comments_alertbar_text_content),
		'disporder' => 3,
		'gid' => $group['gid']
	);
	
	$new_config[] = array(
		'name' => 'profilecomments_default_avatar',
		'title' => $db->escape_string($lang->profile_comments_default_avatar),
		'description' => $db->escape_string($lang->profile_comments_default_avatar_info),
		'optionscode' => 'text',
		'value' => $db->escape_string('images/avatars/invalid_url.gif'),
		'disporder' => 5,
		'gid' => $group['gid']
	);

	$new_config[] = array(
		'name' => 'profilecomments_allow_html',
		'title' => $db->escape_string($lang->profile_comments_allow_html),
		'description' => $db->escape_string($lang->profile_comments_allow_html_info),
		'optionscode' => 'yesno',
		'value' => '0',
		'disporder' => 6,
		'gid' => $group['gid']
	);

	$new_config[] = array(
		'name' => 'profilecomments_allow_smilies',
		'title' => $db->escape_string($lang->profile_comments_allow_smilies),
		'description' => $db->escape_string($lang->profile_comments_allow_smilies_info),
		'optionscode' => 'yesno',
		'value' => '1',
		'disporder' => 7,
		'gid' => $group['gid']
	);

	$new_config[] = array(
		'name' => 'profilecomments_allow_bbcode',
		'title' => $db->escape_string($lang->profile_comments_allow_bbcode),
		'description' => $db->escape_string($lang->profile_comments_allow_bbcode_info),
		'optionscode' => 'yesno',
		'value' => '1',
		'disporder' => 8,
		'gid' => $group['gid']
	);
	
		$new_config[] = array(
		'name' => 'profilecomments_allow_imgcode',
		'title' => $db->escape_string($lang->profile_comments_allow_imgcode),
		'description' => $db->escape_string($lang->profile_comments_allow_imgcode_info),
		'optionscode' => 'yesno',
		'value' => '1',
		'disporder' => 9,
		'gid' => $group['gid']
	);
	
	$new_config[] = array(
		'name' => 'profilecomments_filter_badwords',
		'title' => $db->escape_string($lang->profile_comments_filter_badwords),
		'description' => $db->escape_string($lang->profile_comments_filter_badwords_info),
		'optionscode' => 'yesno',
		'value' => '1',
		'disporder' => 10,
		'gid' => $group['gid']
	);

	$new_config[] = array(
		'name' => 'profilecomments_show_editor',
		'title' => $db->escape_string($lang->profile_comments_show_editor),
		'description' => $db->escape_string($lang->profile_comments_show_editor_info),
		'optionscode' => 'yesno',
		'value' => '0',
		'disporder' => 11,
		'gid' => $group['gid']
	);

	$new_config[] = array(
		'name' => 'profilecomments_close_comments_on_banned',
		'title' => $db->escape_string($lang->profile_comments_close_on_banned),
		'description' => $db->escape_string($lang->profile_comments_close_on_banned_info),
		'optionscode' => 'yesno',
		'value' => '1',
		'disporder' => 12,
		'gid' => $group['gid']
	);

	$new_config[] = array(
		'name' => 'profilecomments_show_statistics',
		'title' => $db->escape_string($lang->profilecomments_show_statistics),
		'description' => $db->escape_string($lang->profilecomments_show_statistics_info),
		'optionscode' => 'yesno',
		'value' => '0',
		'disporder' => 13,
		'gid' => $group['gid']
	);

	$new_config[] = array(
		'name' => 'profilecomments_ajax',
		'title' => $db->escape_string($lang->profilecomments_ajax),
		'description' => $db->escape_string($lang->profilecomments_ajax_info),
		'optionscode' => 'yesno',
		'value' => '0',
		'disporder' => 14,
		'gid' => $group['gid']
	);

	$new_config[] = array(
		'name' => 'profilecomments_ignored_can_send_comments',
		'title' => $db->escape_string($lang->profile_comments_ignored_can_send_comments),
		'description' => $db->escape_string($lang->profile_comments_ignored_can_send_comments_info),
		'optionscode' => 'yesno',
		'value' => '1',
		'disporder' => 15,
		'gid' => $group['gid']
	);

	foreach($new_config as $array => $content)
	{
		$db->insert_query("settings", $content);
	}
	
	rebuild_settings();
}

/**
 * Uninstall function
 *
 */
function profilecomments_uninstall()
{
	global $db, $cache;

	// Delete table where comments are saved
	$db->write_query('DROP TABLE `'.TABLE_PREFIX.'profilecomments`');

	// Delete fields for groups-based permissions
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."usergroups` DROP `canmanagecomments`;");
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."usergroups` DROP `cansendcomments`;");
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."usergroups` DROP `caneditselfcomments`;");
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."usergroups` DROP `candeleteselfcomments`;");

	// Delete field for new comments alert
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."users` DROP `newcomments`;");
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."users` DROP `commentnotify`;");
	$db->write_query("ALTER TABLE `".TABLE_PREFIX."users` DROP `commentsfilter`;");

	// Update usergroups cache
	$cache->update_usergroups();

	// Delete config groups
	$query = $db->simple_select('settinggroups', 'gid', 'name = "profilecomments"');
	$groupid = $db->fetch_field($query, 'gid');
	$db->delete_query('settings','gid = "'.$groupid.'"');
	$db->delete_query('settinggroups','gid = "'.$groupid.'"');

	rebuild_settings();
}

/**
 * Function to check if the plugin is installed.
 *
 * @return bool
 */
function profilecomments_is_installed()
{
	global $db;

	// If table exist, plugin is installed
	if($db->table_exists('profilecomments'))
	{
		return TRUE;
	}

	return FALSE;
}

/**
 * Activate function
 *
 */
function profilecomments_activate()
{
	global $db;

	$new_template = array();

	$new_template['profile_comments'] = '{$comments_form_edit}
<br />
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
	<thead>
		<tr>
			<td colspan="2" class="thead">
				<div>
					<strong>{$lang->profile_comments_list}</strong>
				</div>
			</td>
		</tr>
	</thead>
	<tbody style="{$hidecomments}" id="comments_e">
		{$comments_form}
		{$comments}
	</tbody>
</table>
{$pagination}
<script type="text/javascript" src="{$mybb->settings[\'bburl\']}/jscripts/comments.js"></script>';

	// Create new templates
	$new_template['profile_comments_alert'] = '<div class="pm_alert" id="new_comment_notice">
	<div>
		<a href="{$mybb->settings[\'bburl\']}/member.php?action=profile&amp;uid={$mybb->user[\'uid\']}" title="{$lang->profile_comments}">{$comments_alert_text}</a>
	</div>
</div>
<br />';


	$new_template['profile_comments_delete'] = '- <a href="member.php?action=profile&uid={$target[\'uid\']}&op=delete&mid={$id}" class="delete_link" title="{$lang->profile_comments_delete_comment}">{$lang->profile_comments_delete}</a>';

	$new_template['profile_comments_edit'] = '- <a href="member.php?action=profile&uid={$target[\'uid\']}&op=edit&mid={$id}" title="{$lang->profile_comments_edit_comment}">{$lang->profile_comments_edit}</a>';

	$new_template['profile_comments_form'] = '<tr id="comment_form">
	<td colspan="2" style="text-align: left;" class="trow2">
		<form id="newcomment" name="newcomment" action="member.php?action=profile&amp;uid={$this->target[\'uid\']}&amp;op=new" method="post">
			<div id="replyingto" class="pm_alert" style="display: none;"></div>
			<p>
				<textarea name="message" id="message" rows="10" cols="70" tabindex="5"></textarea>
			</p>
			<p>
				<input type="hidden" name="reply_to_profile" id="reply_to_profile" value="default" />
				<input type="hidden" name="to_uid" id="to_uid" value="{$this->target[\'uid\']}" />
				<input type="submit" id="sendcomment" value="{$lang->profile_comments_add_button}" tabindex="6" />

			</p>
			{$editor}
			<script type="text/javascript">
				var editorloaded = {$editor_active};
				var comments_ajax = {$ajax};
				var current_user = {$mybb->input[\'uid\']};
				var replying_message = \'{$lang->profilecomments_replying}\';
				var confirm_delete_message = \'{$lang->profilecomments_confirm_delete}\';
			</script>
		</form>
	</td>
</tr>';

	$new_template['profile_comments_form_edit'] = '<br />
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
	<thead>
		<tr>
			<td colspan="2" class="thead">
				<div>
					<strong>{$edit_form_title}</strong>
				</div>
			</td>
		</tr>
	</thead>
	<tbody id="comments_e">
		<form id="newcomment" name="newcomment" action="member.php?action=profile&amp;uid={$this->target[\'uid\']}&amp;op=do_edit&amp;mid={$comment[\'mid\']}" method="post">
			<tr>
				<td colspan="2" class="trow2">
					<p>
						<textarea name="editmessage" id="editmessage" rows="10" cols="70" tabindex="3">{$comment[\'text\']}</textarea>
					</p>
					<p>
						<input type="submit" value="{$lang->profile_comments_edit_button}" tabindex="4" />
					</p>
				</td>
			</tr>
		</form>
	</tbody>
</table>';

	$new_template['profile_comments_form_no_access'] = '<tr>
	<td colspan="2" style="text-align: left;" class="trow2">
		<p>{$reason}</p>
	</td>
</tr>';

	$new_template['profile_comments_list'] = '<tr id="comment-{$id}">
	<td class="{$style}" rowspan="2" width="100" style="text-align: center; vertical-align: top;">
		<img style="width: 90px;" src="{$avatar}" alt="{$username_plain} " />
	</td>
	<td class="{$style}" >
		{$username} <small style="font-size: 10px;">({$date} {$lang->at} {$time})</small><br />
		<span style="font-size: 10px;">
			{$reply} {$edit} {$delete}
		</span>
	</td>
</tr>
<tr>
	<td class="{$style}" >
		{$text}
	</td>
</tr>';

	$new_template['profile_comments_nocomments'] = '<tr id="no_comments_found" >
	<td class="trow1" colspan="2">
		{$lang->profile_comments_none_found}
	</td>
</tr>';

	$new_template['profile_comments_reply'] = '<a href="#" username="{$comment[\'username\']}" userid="{$comment[\'sender\']}" class="reply" title="{$lang->profile_comments_reply}">{$lang->profile_comments_reply}</a>';

	$new_template['profile_comments_statistics'] = '<tr>
<td class="trow1"><strong>{$lang->profile_comments_received}</strong></td>
<td class="trow1">{$received}</td>
</tr>
<tr>
<td class="trow1"><strong>{$lang->profile_comments_given}</strong></td>
<td class="trow1">{$given}</td>
</tr>';

	$new_template['profile_comments_ucp_notification'] = '<tr>
<td valign="top" width="1"><input type="checkbox" class="checkbox" name="commentnotify" id="commentnotify" value="1" {$commentnotifycheck} /></td>
<td><span class="smalltext"><label for="commentnotify">{$lang->comment_notify}</label></span></td>
</tr>
<tr>
<td colspan="2"><span class="smalltext"><label for="commentnotify">{$lang->who_can_leave_comments}</label></span></td>
<tr>
<td colspan="2">
	<select name="commentsfilter" id="commentsfilter">
		<option value="0" {$anyone_can_leave_comments}>{$lang->anyone_can_leave_comments}</option>
		<option value="1" {$only_friends_can_leave_comments}>{$lang->only_friends_can_leave_comments}</option>
		<option value="2" {$nobody_can_leave_comments}>{$lang->nobody_can_leave_comments}</option>
	</select>
</td>
</tr>';

	foreach($new_template as $title => $template)
	{
		$new_template = array('title' => $db->escape_string($title), 'template' => $db->escape_string($template), 'sid' => '-1', 'version' => '140', 'dateline' => TIME_NOW);
		$db->insert_query('templates', $new_template);
	}

	// Edit some existing templates
	require_once MYBB_ROOT."/inc/adminfunctions_templates.php";

	find_replace_templatesets('member_profile', '#{\$modoptions}#', '{\$modoptions}<!-- ProfileComments -->{$comments_index}<!-- /ProfileComments -->');

	find_replace_templatesets('member_profile', '#{\$warning_level}#', '{\$warning_level}<!-- ProfileComments -->{$pf_statistics}<!-- /ProfileComments -->');

	find_replace_templatesets('header_welcomeblock_member', '#{\$lang->welcome_pms_usage}#', '{$lang->welcome_pms_usage}<!-- ProfileComments --> | <a href="{$mybb->settings[\'bburl\']}/member.php?action=profile&uid={$mybb->user[\'uid\']}" title="{$lang->profile_comments}">{$lang->profile_comments_new_inmenu}</a> {$lang->profile_comments_new_inmenu_count}<!-- /ProfileComments -->');

	find_replace_templatesets('header', '#{\$unreadreports}#', '{$unreadreports}<!-- ProfileComments -->
			{$comments_alert}<!-- /ProfileComments -->');

	find_replace_templatesets('usercp_options', "#lang->pm_notify}</label></span></td>
</tr>#", 'lang->pm_notify}</label></span></td>
</tr><!-- ProfileComments -->{$pf_notification_options}<!-- /ProfileComments -->');

}

/**
 * Deactivate function
 *
 */
function profilecomments_deactivate()
{
	global $db;

	// Delete created templates
	$delete_templates = array('profile_comments', 'profile_comments_alert', 'profile_comments_delete', 'profile_comments_edit', 'profile_comments_form', 'profile_comments_form_edit', 'profile_comments_form_no_access', 'profile_comments_list', 'profile_comments_nocomments', 'profile_comments_reply', 'profile_comments_statistics', 'profile_comments_ucp_notification');

	foreach($delete_templates as $template)
	{
		$db->delete_query('templates', "title = '{$template}'");
	}

	// And delete ProfileComments content from edited templates
	require_once MYBB_ROOT."/inc/adminfunctions_templates.php";
	
	find_replace_templatesets('member_profile', '#\<!--\sProfileComments\s--\>\{\$([a-zA-Z_]+)?\}<!--\s/ProfileComments\s--\>#is', '', 0);
	find_replace_templatesets('header_welcomeblock_member', '#\<!--\sProfileComments\s--\>(.+)\<!--\s/ProfileComments\s--\>#is', '', 0);
	find_replace_templatesets('header', '#\<!--\sProfileComments\s--\>(.+)\<!--\s/ProfileComments\s--\>#is', '', 0);
	find_replace_templatesets('usercp_options', '#\<!--\sProfileComments\s--\>(.+)\<!--\s/ProfileComments\s--\>#is', '', 0);
}
Moved to Plugin Support.