<?php
/**
* This plugin depends on XThreads.
* This plugin uses Control Object Function.
* The XThreads and Control Object Function is coded by:
*
* 		Yumi/ZiNgA BuRgA at http://mybbhacks.zingaburga.com
*
* XThreads official release thread:
*
*		http://mybbhacks.zingaburga.com/showthread.php?tid=288
*
* This plugin is based on Yumi/ZiNgA BuRgA's tutorial.
* The original tutorial can be found here:
*
* 		http://mybbhacks.zingaburga.com/showthread.php?tid=54
*/

if(!defined('IN_MYBB')){
	die('Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined.');
}

function portal_pagination_info(){
	return array(
		'name'			=> 'Portal Pagination',
		'description'	=> 'Add pagination for portal announcements (Based on Yumi/ZiNgA BuRgA\'s Tutorial)',
		'website'		=> 'http://mybbhacks.zingaburga.com',
		'author'		=> 'MyBB Hacks Community',
		'authorsite'	=> 'http://mybbhacks.zingaburga.com',
		'version'		=> '1.0',
		'compatibility' => '1*',
		'guid'        	=> ''
	);
}

function portal_pagination_activate(){
	require_once MYBB_ROOT.'/inc/adminfunctions_templates.php';
	find_replace_templatesets('portal', '#'.preg_quote('{$announcements}').'#', '{\$announcements}{\$multipage}');
}

function portal_pagination_deactivate(){
	require_once MYBB_ROOT.'/inc/adminfunctions_templates.php';
	find_replace_templatesets('portal', '#'.preg_quote('{$multipage}').'#', '',0);
}

$plugins->add_hook('global_start', 'portal_pagination_tcache');
function portal_pagination_tcache(){
	if(THIS_SCRIPT == 'portal.php'){
		if(isset($GLOBALS['templatelist'])){
			$GLOBALS['templatelist'] .= ',multipage_page_current,multipage_page,multipage_nextpage,multipage_prevpage,multipage_start,multipage_end,multipage';
		}
	}
}

$plugins->add_hook('portal_start', 'portal_pagination_run');
function portal_pagination_run(){
	global $multipage;
	$page = intval($GLOBALS['mybb']->input['page']);
	if($page < 1) $page = 1;
	$numann = $GLOBALS['db']->fetch_field($GLOBALS['db']->simple_select('threads', 'COUNT(*) AS numann', 'fid IN ('.$GLOBALS['mybb']->settings['portal_announcementsfid'].') AND visible=1 AND closed NOT LIKE "moved|%"'), 'numann');
	$perpage = intval($GLOBALS['mybb']->settings['portal_numannouncements']);
	$multipage = multipage($numann, $perpage, $page, $_SERVER['PHP_SELF'].'?paged=1');
	control_object($GLOBALS['db'], '
		function query($string, $hide_errors=0, $write_query=0) {
			static $done=false;
			if(!$done && !$write_query && strpos($string, \'SELECT p.pid, p.message, p.tid, p.smilieoff\')) {
				$done = true;
				$string = strtr($string, array(
					\'LIMIT 0,\' => \'LIMIT '.(($page-1)*$perpage).',\'
				));
			}
			return parent::query($string, $hide_errors, $write_query);
		}
	');
}
?>