<?php

if(!defined("IN_MYBB"))
{
    die("Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined.");
}

$plugins->add_hook("forumdisplay_start", "sortowanie_w_dziale");
$plugins->add_hook("showthread_start", "info_author_thread");
$plugins->add_hook("forumdisplay_thread", "forumdisplay_created_thread");
$plugins->add_hook("member_profile_end", "member_profile_addinfo");
$plugins->add_hook("member_profile_end", "last_posts_profile");
$plugins->add_hook("member_profile_end", "last_threads_profile");
$plugins->add_hook("member_profile_end", "buddy_list");

if(my_strpos($_SERVER['PHP_SELF'], 'member.php'))
{
    global $templatelist;
    if(isset($templatelist))
    {
        $templatelist .= ',';
    }
    $templatelist .= 'carbon_lastpost_row,carbon_lastpost_none,carbon_lastpost,carbon_lastthread_row,carbon_lastthread_none,carbon_lastthread,carbon_member_profile_buddylist_content,carbon_member_profile_buddylist_content_none,carbon_member_profile_buddylist_content';
}

function addtemplatefunction_info() 
{
    return array(
        'name'            => 'Dodatki do szablonu',
        'description'    => 'Plugin dodaje niezbędne dodatki do szablonu "Skill Game".',
        'website'        => '',
        'author'        => 'Snake_ & BaszaR. & fastlone & Supryk',
        'authorsite'    => '',
        'version'        => '1.0.0',
        'guid'            => '',
        'compatibility' => '18*'
    );
}

function addtemplatefunction_activate()
 {
	global $db;
	/*****
	$insert_array = array(
		'title' => 'carbon_threadautorinfo',
		'template' => $db->escape_string('<div class="info_o_temacie">
<span class="info_o_temacie-avatar">
{$thread[\'avatar_started\']}
</span>
  <span style="float: right;">
    {$ratethread}</span>
<span class="informacje_o_autorze">
<h1>{$thread[\'threadprefix\']}{$thread[\'subject\']}</h1>
<font style="color: #646464;font-size:11px">Napisany przez {$thread[\'username_started\']}, {$thread[\'datethread\']} </font>
</span>
</div>'),
		'sid' => '-1',
		'version' => '',
		'dateline' => time()
	);
	$db->insert_query('templates', $insert_array);
	*****/
	$insert_array = array(
		'title' => 'carbon_lastpost',
		'template' => $db->escape_string('<div style="margin-top: 100px;border: 1px solid #393939; ">
	<div style="margin-top: -14px;">
	{$lastpost_row}
	</div>
</div>'),
		'sid' => '-1',
		'version' => '',
		'dateline' => time()
	);
	$db->insert_query('templates', $insert_array);

	$insert_array = array(
		'title' => 'carbon_lastpost_none',
		'template' => $db->escape_string('<div class="post_block">
	<div class="post_wrap">		
		<p><center style="margin-top: 25px; margin-bottom: -15px; min-height: 35px;">Brak zawartości do wyświetlenia.</center></p>			
	</div>	
</div>'),
		'sid' => '-1',
		'version' => '',
		'dateline' => time()
	);
	$db->insert_query('templates', $insert_array);

	$insert_array = array(
		'title' => 'carbon_lastpost_row',
		'template' => $db->escape_string('<div class="post_block">
	<div class="post_wrap">		
				<h3 class="row2">W temacie: <a href="{$postlink}#pid{$post[\'pid\']}">{$threadsubject}</a></h3>			
				<span style="float: right;margin-top: -40px;margin-right: 10px;" class="otoczka otoczka_gray">Odpowiedzi: {$replies}</span>
		<div class="post_body_member">
			<p class="posted_info">
				{$postdate}
			</p>
			<div class="post">
{$text}
			</div>
		</div>
	</div>
	<br>
</div>'),
		'sid' => '-1',
		'version' => '',
		'dateline' => time()
	);
	$db->insert_query('templates', $insert_array);

	$insert_array = array(
		'title' => 'carbon_lastthread',
		'template' => $db->escape_string('<div style="margin-top: 100px;border: 1px solid #393939; ">
	<div style="margin-top: -14px;">
	{$lastthread_row}
	</div>
</div>'),
		'sid' => '-1',
		'version' => '',
		'dateline' => time()
	);
	$db->insert_query('templates', $insert_array);

	$insert_array = array(
		'title' => 'carbon_lastthread_none',
		'template' => $db->escape_string('<div class="post_block">
	<div class="post_wrap">		
		<p><center style="margin-top: 25px; margin-bottom: -15px; min-height: 35px;">Brak zawartości do wyświetlenia.</center></p>			
	</div>	
</div>'),
		'sid' => '-1',
		'version' => '',
		'dateline' => time()
	);
	$db->insert_query('templates', $insert_array);

	$insert_array = array(
		'title' => 'carbon_lastthread_row',
		'template' => $db->escape_string('<div class="post_block">
	<div class="post_wrap">		
				<h3 class="row2">Temat: <a href="{$mybb->settings[\'bburl\']}/{$threadlink}">{$threadsubject}</a></h3>			
				<span style="float: right;margin-top: -40px;margin-right: 10px;" class="otoczka otoczka_gray">Odpowiedzi: {$replies}</span>
		<div class="post_body_member">
			<p class="posted_info">
				{$threaddate}
			</p>
			<div class="post">
{$text}
			</div>
		</div>
	</div>
	<br>
</div>'),
		'sid' => '-1',
		'version' => '',
		'dateline' => time()
	);

	$db->insert_query('templates', $insert_array);

	$insert_array = array(
		'title' => 'carbon_member_profile_buddylist_content',
		'template' => $db->escape_string('<a href="member.php?action=profile&uid={$id}">
	<img src="{$avatar[\'image\']}" title="{$nick}" class="tipTip userAvatar" width="34" height="34">
</a>'),
		'sid' => '-1',
		'version' => '',
		'dateline' => time()
	);
	$db->insert_query('templates', $insert_array);

	$insert_array = array(
		'title' => 'carbon_member_profile_buddylist',
		'template' => $db->escape_string('<div class="tabela_podglad">
	<h3>Znajomi</h3>
	<div class="tabela_srd">
	{$buddy_list_row}
	</div>
</div>'),
		'sid' => '-1',
		'version' => '',
		'dateline' => time()
	);
	$db->insert_query('templates', $insert_array);

	$insert_array = array(
		'title' => 'carbon_member_profile_buddylist_content_none',
		'template' => $db->escape_string('Brak'),
		'sid' => '-1',
		'version' => '',
		'dateline' => time()
	);
	$db->insert_query('templates', $insert_array);
}

function addtemplatefunction_deactivate()
{
	global $db;
	
//	$db->delete_query("templates", "title = 'carbon_threadautorinfo'");
	$db->delete_query("templates", "title = 'carbon_lastpost'");
	$db->delete_query("templates", "title = 'carbon_lastpost_none'");
	$db->delete_query("templates", "title = 'carbon_lastpost_row'");
	$db->delete_query("templates", "title = 'carbon_lastthread'");
	$db->delete_query("templates", "title = 'carbon_lastthread_none'");
	$db->delete_query("templates", "title = 'carbon_lastthread_row'");
	$db->delete_query("templates", "title = 'carbon_member_profile_buddylist_content'");
	$db->delete_query("templates", "title = 'carbon_member_profile_buddylist_content_none'");
	$db->delete_query("templates", "title = 'carbon_member_profile_buddylist'");
}

function sortowanie_w_dziale()
{   
    global $mybb, $viewssort, $startsort, $lastpostsort, $odpsort;
	
    switch($mybb->input['sortby'])
    {
        case "subject":
			$sortfield = "subject";
        break;
		case "replies":
			$sortfield = "replies";
			$odpsort = "class='activeSORTBY'";
        break;
        case "views":
			$sortfield = "views";
			$viewssort = "class='activeSORTBY'";
        break;
        case "starter":
			$sortfield = "username";
        break;
        case "rating":
			$t = "";
			$sortfield = "averagerating";
			$sortfield2 = ", t.totalratings DESC";
        break;
        case "started":
			$sortfield = "dateline";
			$startsort = "class='activeSORTBY'";
        break;
        default:
			$sortby = "lastpost";
			$sortfield = "lastpost";
			$lastpostsort = "class='activeSORTBY'";
			$mybb->input['sortby'] = "lastpost";
        break;
    }
}

function info_author_thread()
{
    global $db, $mybb, $thread, $avatar;
	
    $user = get_user($thread['uid']);
	
	$user['username'] = format_name($user['username'], $user['usergroup'], $user['displaygroup']);
	$thread['username_started'] = build_profile_link($user['username'], $user['uid']);

    $avatar = format_avatar($user['avatar']);
    $thread['avatar_started'] = '<a href="member.php?action=profile&uid='.$user['uid'].'"><img src="'.$avatar['image'].'" alt="" /></a>';
	$thread['datethread'] = my_date('relative', $thread['dateline']);
}

function forumdisplay_created_thread() 
{
    global $mybb, $thread;
    
    $thread['datethreadf'] = my_date('relative', $thread['dateline']);

}

function member_profile_addinfo()
{
    global $cache, $db, $groupscache, $mybb, $memprofile, $grupa;
    
    if(!is_array($groupscache))
        $groupscache = $cache->read("usergroups");
        
    $grupa = str_replace('{username}', htmlspecialchars_uni($groupscache[$memprofile['usergroup']]['title']), $groupscache[$memprofile['usergroup']]['namestyle']);
} 

function last_posts_profile()
{
    global $mybb, $db, $templates, $theme, $lastpost, $memprofile, $parser, $forum_cache;
	
    require_once MYBB_ROOT."inc/functions_search.php";
	require_once MYBB_ROOT."inc/class_parser.php";
	
    $altbg = alt_trow();
    $lastpost_row = "";
    $memprofileuid = $memprofile['uid'];
    
    $permsql = "";
    $onlyusfids = array();
    $group_permissions = forum_permissions();
    foreach($group_permissions as $fid => $forum_permissions)
    {
        if(isset($forum_permissions['canonlyviewownthreads']) && $forum_permissions['canonlyviewownthreads'] == 1)
        {
            $onlyusfids[] = $fid;
        }
    }
    if(!empty($onlyusfids))
    {
        $permsql .= "AND ((p.fid IN(".implode(',', $onlyusfids).") AND p.uid='{$mybb->user['uid']}') OR p.fid NOT IN(".implode(',', $onlyusfids)."))";
    }

    $unsearchforums = get_unsearchable_forums();
    if($unsearchforums)
    {
        $permsql .= " AND p.fid NOT IN ($unsearchforums)";
    }
    $inactiveforums = get_inactive_forums();
    if($inactiveforums)
    {
        $permsql .= " AND p.fid NOT IN ($inactiveforums)";
    }
	
	$query = $db->query("
        SELECT p.tid, p.uid, p.fid, p.pid, p.dateline, p.message, t.tid, t.fid, t.uid, t.subject, t.replies
        FROM ".TABLE_PREFIX."posts p
        LEFT JOIN ".TABLE_PREFIX."threads t ON (p.tid=t.tid)
        WHERE 1=1 AND p.uid={$memprofileuid} {$unapproved_where} {$permsql} AND t.visible='1' AND t.closed NOT LIKE 'moved|%'
        ORDER BY p.dateline DESC
        LIMIT 0, 5
    ");
    while($post = $db->fetch_array($query))
    {
		$threadsubject = $post['subject'];
		$postlink = get_post_link($post['pid'], $post['tid']);
		$postdate = $threaddate = my_date('relative', $post['dateline']);
		$replies = my_number_format($post['replies']);
        $parser = new postParser;
        $parser_options = array("allow_html" => 0, "allow_mycode" => 1, "allow_smilies" => 1, "allow_imgcode" => 1, "allow_videocode" => 1, "filter_badwords" => 1);
        if(strlen($post['message']) > "850")
		{
			$postmessage = my_substr($post['message'],0,850)."...";
		}
		else
		{
			$postmessage = $post['message'];
		}
        $text = $parser->parse_message($post['message'], $parser_options); 
		eval("\$lastpost_row .= \"".$templates->get("carbon_lastpost_row")."\";");
	}
	
	if(!$lastpost_row)
    {
        eval("\$lastpost_row .= \"".$templates->get("carbon_lastpost_none")."\";");
    }
    
    eval("\$lastpost = \"".$templates->get("carbon_lastpost")."\";");
    return $lastpost;
}

function last_threads_profile()
{
    global $mybb, $db, $templates, $theme, $lastthread, $memprofile, $parser, $forum_cache;
	
    require_once MYBB_ROOT."inc/functions_search.php";
	require_once MYBB_ROOT."inc/class_parser.php";
	
    $altbg = alt_trow();
    $lastthread_row = "";
    $memprofileuid = $memprofile['uid'];
    
    $permsql = "";
    $onlyusfids = array();
    $group_permissions = forum_permissions();
    foreach($group_permissions as $fid => $forum_permissions)
    {
        if(isset($forum_permissions['canonlyviewownthreads']) && $forum_permissions['canonlyviewownthreads'] == 1)
        {
            $onlyusfids[] = $fid;
        }
    }
    if(!empty($onlyusfids))
    {
        $permsql .= "AND ((t.fid IN(".implode(',', $onlyusfids).") AND t.uid='{$mybb->user['uid']}') OR t.fid NOT IN(".implode(',', $onlyusfids)."))";
    }

    $unsearchforums = get_unsearchable_forums();
    if($unsearchforums)
    {
        $permsql .= " AND t.fid NOT IN ($unsearchforums)";
    }
    $inactiveforums = get_inactive_forums();
    if($inactiveforums)
    {
        $permsql .= " AND t.fid NOT IN ($inactiveforums)";
    }

    $query = $db->query("
        SELECT t.tid, t.fid, t.uid, t.subject, t.replies, t.views, t.dateline, t.firstpost, p.pid, p.message
        FROM ".TABLE_PREFIX."threads t
        LEFT JOIN ".TABLE_PREFIX."posts p ON (t.firstpost=p.pid)
        WHERE 1=1 AND t.uid={$memprofileuid} {$unapproved_where} {$permsql} AND t.visible='1' AND t.closed NOT LIKE 'moved|%'
        ORDER BY t.dateline DESC
        LIMIT 0, 5
    ");
    while($thread = $db->fetch_array($query))
    {
		$threadsubject = htmlspecialchars_uni($parser->parse_badwords($thread['subject']));
        $threadlink = get_thread_link($thread['tid']);
        $threaddate = my_date('relative', $thread['dateline']);
		$replies = my_number_format($thread['replies']);
        $parser = new postParser;
        $parser_options = array("allow_html" => 0, "allow_mycode" => 1, "allow_smilies" => 1, "allow_imgcode" => 1, "allow_videocode" => 1, "filter_badwords" => 1);
		if(strlen($thread['message']) > "350")
		{
			$threadmessage = my_substr($thread['message'],0,350)."...";
		}
		else
		{
			$threadmessage = $thread['message'];
		}
        $text = $parser->parse_message($thread['message'], $parser_options); 
        eval("\$lastthread_row .= \"".$templates->get("carbon_lastthread_row")."\";");
        $altbg = alt_trow();
    }
    if(!$lastthread_row)
    {
        eval("\$lastthread_row .= \"".$templates->get("carbon_lastthread_none")."\";");
    }
    
    eval("\$lastthread = \"".$templates->get("carbon_lastthread")."\";");
    return $lastthread;
} 

function buddy_list()
{
    global $mybb, $memprofile, $db, $templates, $buddy_list, $buddy_list_row;
	
	if(strlen($memprofile['buddylist']) == 0) {
		eval("\$buddy_list_row .= \"".$templates->get("carbon_member_profile_buddylist_content_none")."\";");
	}
	else
    {
        $buddies_query = $db->query("SELECT uid, avatar, username FROM ".TABLE_PREFIX."users WHERE uid IN ({$memprofile['buddylist']})");
        while($buddy_user = $db->fetch_array($buddies_query))
        {   
            $avatar = $buddy_user['avatar'];
				if($avatar == 0) {
					$avatar = format_avatar($buddy_user['avatar']);
				}
            $nick = $buddy_user['username'];
            $id = $buddy_user['uid'];
            eval("\$buddy_list_row .= \"".$templates->get("carbon_member_profile_buddylist_content")."\";");
        }
    }
    
    eval("\$buddy_list = \"".$templates->get("carbon_member_profile_buddylist")."\";");
} 
?>