<?php
/*
*
* @package ppkBB3cker
* @version $Id: ppkBB3cker.php,v 1.000 2009-04-02 10:48:00 PPK Exp $
* @copyright (c) PPK 2008, 2009
* http://ppkbb3cker.rx22.ru, http://protoneutron.narod.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

if (!defined('IN_PHPBB'))
{
	exit;
}

/**
*/

if(!function_exists('get_img_size_format'))
{
	/**
	* Calculate the needed size for Thumbnail
	*/
	function get_img_size_format($width, $height)
	{
		global $config;

		// Maximum Width the Image can take
		$config['img_max_thumb_width']=$config['ppkbb_tmax_thumbwidth'];
		$max_width = ($config['img_max_thumb_width']) ? $config['img_max_thumb_width'] : 400;

		if ($width > $height)
		{
			return array(
				round($width * ($max_width / $width)),
				round($height * ($max_width / $width))
			);
		}
		else
		{
			return array(
				round($width * ($max_width / $height)),
				round($height * ($max_width / $height))
			);
		}
	}
}

//
// Fetch Posts for announcements from portal/includes/functions.php if we want to see the announcements
//

$sql = 'SELECT forum_id, forum_name
FROM ' . FORUMS_TABLE . '
	WHERE forum_type = ' . FORUM_POST . " AND forumas='1'";

if(!($result = $db->sql_query($sql)))
{
	die('Could not query forum information');
}
$forum_sql=array();
while($row = $db->sql_fetchrow($result))
{
	$forum_sql[$row['forum_id']]=$row['forum_name'];
}
$db->sql_freeresult($result);
$forum_sql2=implode("', '", array_keys($forum_sql));

$start = intval(request_var('start', 0));
$start < 0 ? $start=0 : '';

$fetch_announcements = ppkbb_fetch_posts($forum_sql2, $start, $config['ppkbb_portal_torrents_perpage'], $config['ppkbb_portal_torrents_textlength'], $config['ppkbb_portal_torrents_posttime'], 'sticky');

$result=$db->sql_query("SELECT FOUND_ROWS() t_count");
$torr_count=$db->sql_fetchrow($result);
$db->sql_freeresult($result);
$topics_count=intval($torr_count['t_count']);
$s_display_active=0;

if(@$fetch_announcements[0])
{
	$query=$db->sql_query("SELECT attach_id, i_width, i_height, post_msg_id, extension, real_filename, is_orphan, thumbnail, filesize FROM ".ATTACHMENTS_TABLE." WHERE post_msg_id IN('".implode("', '", $fetch_announcements[0])."') AND !in_message");
	$image_ext=array('gif', 'jpeg', 'jpg', 'png', 'tga', 'tif', 'tiff');
	$attachments=array();
	while($row=$db->sql_fetchrow($query))
	{
		if($row['extension']=='torrent')
		{
			$attachments[$row['post_msg_id']]['torrents'][]=$row;
		}
		else if(in_array($row['extension'], $image_ext))
		{
			if(preg_match('/poster/i', $row['real_filename']))
			{
				$attachments[$row['post_msg_id']]['posters'][]=$row;
			}
			else
			{
				$attachments[$row['post_msg_id']]['screenshots'][]=$row;
			}
		}
	}
	$db->sql_freeresult($query);
	unset($fetch_announcements[0]);
	$tracker_substr=35;
	$ic=0;
}

for ($i = 1; $i < sizeof($fetch_announcements)+1; $i++)
{
	$a_fid = (intval($fetch_announcements[$i]['forum_id']));

	if(!$user->data['is_registered'])
	{
		$is_candowntorr = $auth->acl_get('u_candowntorr') && $auth->acl_get('f_candowntorr', $a_fid) ? 1 : 0;
		$is_candownpostscr = $auth->acl_get('u_candownpostscr') && $auth->acl_get('f_candownpostscr', $a_fid) ? 1 : 0;
	}
	else
	{
		$is_candowntorr=1;
		$is_candownpostscr=1;
		if($user->data['user_id']!=$fetch_announcements[$i]['user_id'])
		{
			$is_candowntorr=$auth->acl_get('u_candowntorr') && $auth->acl_get('f_candowntorr', $a_fid) ? 1 : 0;
			$is_candownpostscr=$auth->acl_get('u_candownpostscr') && $auth->acl_get('f_candownpostscr', $a_fid) ? 1 : 0;
		}
	}

	$template->assign_block_vars('torrents_row', array(
		'ATTACH_ICON_IMG'	=> ($fetch_announcements[$i]['attachment']) ? $user->img('icon_attach', $user->lang['TOTAL_ATTACHMENTS']) : '',
		'TITLE'				=> $fetch_announcements[$i]['topic_title'],
		'POSTER'			=> $fetch_announcements[$i]['username'],
		'U_USER_PROFILE'	=> (($fetch_announcements[$i]['user_type'] == USER_NORMAL || $fetch_announcements[$i]['user_type'] == USER_FOUNDER) && $fetch_announcements[$i]['user_id'] != ANONYMOUS) ? append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=viewprofile&amp;u=' . $fetch_announcements[$i]['user_id']) : '',
		'TIME'				=> $fetch_announcements[$i]['topic_time'],
		'TEXT'				=> $fetch_announcements[$i]['post_text'],
		'REPLIES'			=> $fetch_announcements[$i]['topic_replies'],
		'TOPIC_VIEWS'		=> $fetch_announcements[$i]['topic_views'],
		'U_TOPICS_VIEWS'	=> append_sid($phpbb_root_path . 'viewtopic.' . $phpEx . '?p=' . $fetch_announcements[$i]['post_id']),
		'U_VIEW_COMMENTS'	=> append_sid($phpbb_root_path . 'viewtopic.' . $phpEx . '?t=' . $fetch_announcements[$i]['topic_id'] . '&amp;f=' . $a_fid),
		'U_POST_COMMENT'	=> append_sid($phpbb_root_path . 'posting.' . $phpEx . '?mode=reply&amp;t=' . $fetch_announcements[$i]['topic_id'] . '&amp;f=' . $a_fid),
		'S_NOT_LAST'		=> ($i < sizeof($fetch_announcements) - 1) ? true : false,
		'MINI_POST_IMG'		=> $user->img('icon_post_target', 'POST'),
		'S_HAS_TRACKER_TORRENT' => $is_candowntorr && $attachments[$fetch_announcements[$i]['post_id']]['torrents'] ? true : false,
		'S_HAS_TRACKER_POSTER' => $is_candownpostscr && @$attachments[$fetch_announcements[$i]['post_id']]['posters'] ? true : false,
		'S_HAS_TRACKER_SCREENSHOT' => $is_candownpostscr && @$attachments[$fetch_announcements[$i]['post_id']]['screenshots'] ? true : false,
		'TORRENT_FORUM_LINK'	=> sprintf('<a href="%s">%s</a>', append_sid($phpbb_root_path . 'viewforum.' . $phpEx . '?f=' . $a_fid), $forum_sql[$a_fid]),
	));
	if($is_candowntorr && $attachments[$fetch_announcements[$i]['post_id']]['torrents'])
	{
		foreach ($attachments[$fetch_announcements[$i]['post_id']]['torrents'] as $torrent_data)
		{
			$torrent_basename=basename($torrent_data['real_filename']);
			$template->assign_block_vars('torrents_row.torrent_fields', array(
				'TORRENT_LINK' => append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . (int) $torrent_data['attach_id'], true, ($torrent_data['is_orphan']) ? $user->session_id : false),
				'TORRENT_SRC' => $phpbb_root_path . 'images/tracker/filesave_big.png',
				'TORRENT_SRCS' => $phpbb_root_path . 'images/tracker/filesave.png',
				'TORRENT_DOWNLOAD_NAME'		=> utf8_strlen($torrent_basename)>$tracker_substr ? utf8_substr($torrent_basename, 0, $tracker_substr).'...' : $torrent_basename,
				'TORRENT_ALTITLE'			=> $torrent_basename,
				)
			);
		}
	}
	if($is_candownpostscr && @$attachments[$fetch_announcements[$i]['post_id']]['posters'])
	{
		$ic+=1;
		foreach ($attachments[$fetch_announcements[$i]['post_id']]['posters'] as $poster_data)
		{
				$poster_addon='';
				if($poster_data['thumbnail'] && $poster_data['filesize'] > $config['ppkbb_tmin_thumbsize'])
				{
					$poster_addon='&amp;t=1';
				}
				$poster_basename=basename($poster_data['real_filename']);
				$poster_wh=get_img_size_format($poster_data['i_width'], $poster_data['i_height']);
				$template->assign_block_vars('torrents_row.torrent_poster_fields', array(
					'POSTER_LINK'=>append_sid("{$phpbb_root_path}download/file.$phpEx", 'mode=view&amp;id=' . (int) $poster_data['attach_id'], true, ($poster_data['is_orphan']) ? $user->session_id : false),
					'POSTER_SRC' =>append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $poster_data['attach_id'] . $poster_addon),

					'POSTER_WH'=>$poster_data['i_width'] > $poster_wh[0] ? ' width="'.$poster_wh[0].'" height="'.$poster_wh[1].'"' : '',
					'POSTER_COUNT'=>$ic,
					)
				);
		}
	}
	if($is_candownpostscr && @$attachments[$fetch_announcements[$i]['post_id']]['screenshots'])
	{
		$ic+=1;
		foreach ($attachments[$fetch_announcements[$i]['post_id']]['screenshots'] as $screenshot_data)
		{
				$screenshot_addon='';
				if($screenshot_data['thumbnail'] && $screenshot_data['filesize'] > $config['ppkbb_tmin_thumbsize'])
				{
					$screenshot_addon='&amp;t=1';
				}
				$screenshot_basename=basename($screenshot_data['real_filename']);
				$screenshot_wh=get_img_size_format($screenshot_data['i_width'], $screenshot_data['i_height']);
				$template->assign_block_vars('torrents_row.torrent_screenshot_fields', array(
					'SCREENSHOT_LINK'=>append_sid("{$phpbb_root_path}download/file.$phpEx", 'mode=view&amp;id=' . (int) $screenshot_data['attach_id'], true, ($screenshot_data['is_orphan']) ? $user->session_id : false),
					'SCREENSHOT_SRC' =>append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $screenshot_data['attach_id'] . $screenshot_addon),

					'SCREENSHOT_WH'=>$screenshot_data['i_width'] > $screenshot_wh[0] ? ' width="'.$screenshot_wh[0].'" height="'.$screenshot_wh[1].'"' : '',
					'SCREENSHOT_COUNT'=>$ic,
					)
				);
		}
	}
}

$template->assign_vars(array(
	'TORR_TABLE_WIDTH' => $config['ppkbb_tmax_thumbwidth']+10,
	'PAGINATION'	=> generate_pagination(append_sid("{$phpbb_root_path}portal.$phpEx", "mode=portal"), $topics_count, $config['ppkbb_portal_torrents_perpage'], $start, true),
	'PAGE_NUMBER'	=> on_page($topics_count, $config['ppkbb_portal_torrents_perpage'], $start),
	'LATEST_TORR_COUNT' => sizeof($fetch_announcements) ? 1 : 0,
	)
);

// fetch post for news & announce
function ppkbb_fetch_posts($forum_sql, $start, $number_of_posts, $text_length, $time, $type)
{
	global $db, $phpbb_root_path, $auth, $bbcode_bitfield, $user, $forum_id;

	$from_forum = ($forum_sql) ? "t.forum_id IN ('" . $forum_sql . "') AND" : '';
	$post_time = ($time == 0) ? '' : 't.topic_time > ' . (time() - $time * 86400) . ' AND';

	if ($type == 'announcements')
	{
		// only global announcements for announcements block
		$topic_type = '( t.topic_type = ' . POST_ANNOUNCE . ') AND';
	}
	else if ($type == 'sticky')
	{
		// only sticky topics/posts for torrents block
		$topic_type = '( t.topic_type = ' . POST_STICKY . ' ) AND';
	}
	else if ($type == 'news_all')
	{
		// not show global announcements
		$topic_type = '( t.topic_type != ' . POST_ANNOUNCE . ' ) AND';
	}
	else
	{
		// only normal topic
		$topic_type = 't.topic_type = ' . POST_NORMAL . ' AND';
	}

	$sql = 'SELECT SQL_CALC_FOUND_ROWS
			t.forum_id,
			t.topic_id,
			t.topic_last_post_id,
			t.topic_time,
			t.topic_title,
			t.topic_attachment,
			t.topic_views,
			t.topic_replies,
			t.forum_id,
			t.topic_poster,
			u.username,
			u.user_id,
			u.user_type,
			u.user_colour,
			p.post_id,
			p.post_text,
			p.post_attachment,
			p.enable_smilies,
			p.enable_bbcode,
			p.enable_magic_url,
			p.bbcode_bitfield,
			p.bbcode_uid
		FROM
			' . TOPICS_TABLE . ' AS t,
			' . USERS_TABLE . ' AS u,
			' . TRACKER_TORRENTS_TABLE . ' AS tr,
			' . POSTS_TABLE . ' AS p
		WHERE
			' . $topic_type . '
			' . $from_forum . '
			' . $post_time . "
			t.topic_poster = u.user_id AND
			t.topic_first_post_id = p.post_id AND
			t.topic_status <> 2 AND
			tr.post_msg_id = p.post_id AND
			t.topic_approved = 1
		ORDER BY
			t.topic_time DESC LIMIT $start, $number_of_posts";

	// query the database
	if(!($result = $db->sql_query($sql)))
	{
		die('Could not query topic information for phpBB3 Portal news section');
	}

	//
	// fetch all postings
	//

	// Instantiate BBCode if need be
	if ($bbcode_bitfield !== '')
	{
		$phpEx = substr(strrchr(__FILE__, '.'), 1);
		include_once($phpbb_root_path . 'includes/bbcode.' . $phpEx);
		$bbcode = new bbcode(base64_encode($bbcode_bitfield));
	}
	$posts = array();
	$i = 1;
	while ( ($row = $db->sql_fetchrow($result)) && ( ($i-1 < $number_of_posts) || ($number_of_posts == '0') ) )
	{
		if ( ($auth->acl_get('f_read', $row['forum_id'])) || ($row['forum_id'] == '0') )
		{
			if ($row['user_id'] != ANONYMOUS && $row['user_colour'])
			{
				$row['username'] = '<b style="color:#' . $row['user_colour'] . '">' . $row['username'] . '</b>';
			}

			$row['topic_attachment'] ? $posts[0][]=$row['post_id'] : '';
			$posts[$i]['post_text'] = censor_text($row['post_text']);
			$posts[$i]['topic_id'] = $row['topic_id'];
			$posts[$i]['topic_last_post_id'] = $row['topic_last_post_id'];
			$posts[$i]['forum_id'] = $row['forum_id'];
			$posts[$i]['topic_replies'] = $row['topic_replies'];
			$posts[$i]['topic_time'] = $user->format_date($row['topic_time']);
			$posts[$i]['topic_title'] = $row['topic_title'];
			$posts[$i]['post_id'] = $row['post_id'];
			$posts[$i]['username'] = $row['username'];
			$posts[$i]['user_id'] = $row['user_id'];
			$posts[$i]['user_type'] = $row['user_type'];
			$posts[$i]['user_user_colour'] = $row['user_colour'];
			$posts[$i]['attachment'] = ($row['topic_attachment']) ? true : false;
			$posts[$i]['topic_views'] = ($row['topic_views']);

			$message = $posts[$i]['post_text'];
			$message = smiley_text($message); // Always process smilies after parsing bbcodes

			if ($auth->acl_get('f_html', $forum_id))
			{
				$message = preg_replace('#<!\-\-(.*?)\-\->#is', '', $message); // Remove Comments from post content
			}

			// Parse the message and subject
			$message = censor_text($row['post_text']);
			$message = str_replace("\n", '<br />', $message);

			// Second parse bbcode here
			if ($row['bbcode_bitfield'])
			{
				$bbcode->bbcode_second_pass($message, $row['bbcode_uid'], $row['bbcode_bitfield']);
			}
			$posts[$i]['post_text']= $message;

			$len_check = $posts[$i]['post_text'];

			if (($text_length != 0) && (strlen($len_check) > $text_length))
			{
				$posts[$i]['post_text'] = substr($len_check, 0, $text_length);
				$posts[$i]['post_text'] .= '...';
			}

			$bbcode->bbcode_second_pass($posts[$i]['post_text'], $row['bbcode_uid'], $row['bbcode_bitfield']);
			$posts[$i]['post_text'] = smiley_text($posts[$i]['post_text']);
			$i++;
		}
	}
	// return the result
	return $posts;
}

?>