<?php
//////////////////////////// COPYRIGHT NOTICE //////////////////////////////
// This script is part of PhotoPost vBGallery, a software application by  //
// All Enthusiast, Inc.  Use of any kind of part or all of this           //
// script or modification of this script requires a license from All      //
// Enthusiast, Inc.  Use or modification of this script without a license //
// constitutes Software Piracy and will result in legal action from All   //
// Enthusiast, Inc.  All rights reserved.                                 //
// http://www.photopost.com      legal@photopost.com                      //
//                                                                        //
//            PhotoPost Copyright 2008, All Enthusiast, Inc.              //
////////////////////////////////////////////////////////////////////////////

// ####################### SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE);

// #################### DEFINE IMPORTANT CONSTANTS #######################
define('NO_REGISTER_GLOBALS', 1);
define('THIS_SCRIPT', 'gallery_index');
define('PP_SCRIPT', 'vBGallery');

// ################### PRE-CACHE TEMPLATES AND DATA ######################
// get special phrase groups
$phrasegroups = array();

// get special data templates from the datastore
$specialtemplates = array(
	'smiliecache',
	'bbcodecache'
);

// pre-cache templates used by all actions
$globaltemplates = array(
	'ADV_GALLERY',
	'adv_gallery_categorybit_level1',
	'adv_gallery_categorybit_level2',
	'adv_gallery_categorybit_main',
	'adv_gallery_categorybit_subcat',
	'adv_gallery_nodisplay',
    'forumhome_loggedinuser',
    'adv_gallery_newimages',
	'adv_gallery_imagebit',
    'adv_gallery_randomimages',
	'forumhome_moderator'
);

// pre-cache templates used by specific actions
$actiontemplates = array();

// ######################### REQUIRE BACK-END ############################
require_once('./gallery_global.php');


// #######################################################################
// ######################## START MAIN SCRIPT ############################
// #######################################################################

($hook = vBulletinHook::fetch_hook('ppgal_home_start')) ? eval($hook) : false;

$categoryperms = fetch_category_perms();

if (!intval($catid))
{
	// Get category info to print the categories and make the stats
	$getcats = $db->query_read("
			SELECT catid, styleid, title, description, parent, parentlist, catimage, imagecount, postcount, lastimageid, lastimagetitle, lastimageuserid, lastimageusername, lastimagedateline, lastpostid, lastpostuserid, lastpostusername, lastpostimagetitle, lastpostdateline, styleoverride
			FROM " . TABLE_PREFIX ."ppgal_categories
			ORDER BY $ppg_options[gallery_catsorderby] $ppg_options[gallery_catsdirection]
	");
	while ($categories = $vbulletin->db->fetch_array($getcats))
	{
		if ($categories['parent'] AND !$categorycache["$categories[parent]"]['active'])
		{
			$categorycache["$categories[catid]"]['active'] = 0;
			continue;
		}
		if ($categoryperms["$categories[catid]"]['canviewimages'] OR $ppg_options['gallery_showimagecount'])
		{
			$stats['categories']++;
			$stats['images'] += $categories['imagecount'];
			$stats['posts'] += $categories['postcount'];

			$categorycache["$categories[catid]"]['description'] = $categories['description'];
			$categorycache["$categories[catid]"]['catimage'] = $categories['catimage'];

			if ($categories['lastimagedateline'] > $categorycache["$categories[catid]"]['lastimagedateline'])
			{
				$categorycache["$categories[catid]"]['lastimagedateline'] = $categories['lastimagedateline'];
				$categorycache["$categories[catid]"]['lastimagetitle'] = $categories['lastimagetitle'];
				$categorycache["$categories[catid]"]['lastimageid'] = $categories['lastimageid'];
				$categorycache["$categories[catid]"]['lastimageusername'] = $categories['lastimageusername'];
				$categorycache["$categories[catid]"]['lastimageuserid'] = $categories['lastimageuserid'];
			}
			if ($categories['lastpostdateline'] > $categorycache["$categories[catid]"]['lastpostdateline'])
			{
				$categorycache["$categories[catid]"]['lastpostdateline'] = $categories['lastpostdateline'];
				$categorycache["$categories[catid]"]['lastpostimagetitle'] = $categories['lastpostimagetitle'];
				$categorycache["$categories[catid]"]['lastpostid'] = $categories['lastpostid'];
				$categorycache["$categories[catid]"]['lastpostusername'] = $categories['lastpostusername'];
				$categorycache["$categories[catid]"]['lastpostuserid'] = $categories['lastpostuserid'];
			}

			if ($categorycache["$categories[catid]"]['level'] >= $ppg_options['gallery_catdepth'] AND $ppg_options['gallery_showsubcats'])
			{
				$categorycache["$categories[parent]"]['subcats']["$categories[catid]"]['title'] = $categories['title'];
				$categorycache["$categories[parent]"]['subcats']["$categories[catid]"]['lastimagedateline'] = $categories['lastimagedateline'];
				$categorycache["$categories[parent]"]['subcats']["$categories[catid]"]['lastpostdateline'] = $categories['lastpostdateline'];
			}

			if ($categories['parentlist'])
			{
				foreach (explode(',', $categories['parentlist']) AS $parid)
				{
					$categorycache["$parid"]['imagecount'] += $categories['imagecount'];
					$categorycache["$parid"]['postcount'] += $categories['postcount'];

					if ($categories['lastimagedateline'] > $categorycache["$parid"]['lastimagedateline'])
					{
						$categorycache["$parid"]['lastimagedateline'] = $categories['lastimagedateline'];
						$categorycache["$parid"]['lastimagetitle'] = $categories['lastimagetitle'];
						$categorycache["$parid"]['lastimageid'] = $categories['lastimageid'];
						$categorycache["$parid"]['lastimageusername'] = $categories['lastimageusername'];
						$categorycache["$parid"]['lastimageuserid'] = $categories['lastimageuserid'];
					}

					if ($categories['lastpostdateline'] > $categorycache["$parid"]['lastpostdateline'])
					{
						$categorycache["$parid"]['lastpostdateline'] = $categories['lastpostdateline'];
						$categorycache["$parid"]['lastpostimagetitle'] = $categories['lastpostimagetitle'];
						$categorycache["$parid"]['lastpostid'] = $categories['lastpostid'];
						$categorycache["$parid"]['lastpostusername'] = $categories['lastpostusername'];
						$categorycache["$parid"]['lastpostuserid'] = $categories['lastpostuserid'];
					}
				}
			}
		}
	}
	$db->free_result($getcats);
	unset($categories);
}

if ($ppg_options['gallery_allowreplies'])
{
	$show['replycells'] = true;
	$stylevar['imagecount'] = 'alt2';
	$stylevar['moderator'] = 'alt2';
}
else
{
	$stylevar['imagecount'] = 'alt1';
	$stylevar['moderator'] = 'alt2';
}

$ppg_options['gallery_catdepth'] = $ppg_options['gallery_catdepth_index'];

// Print the categories
$categorybits = print_categories(intval($catid), iif(!intval($catid), $categorycache));

require_once(DIR . '/includes/functions_bigthree.php');

$ignusers = fetch_ignored_users();

if ($ignusers)
{
	$ignquery = 'AND images.userid NOT IN(' . $ignusers . ')';
}


if (!$catid)
{
	$show['directoryhead'] = true;

	if ($ppg_options['gallery_showstats'])
	{
            $stats['images'] = vb_number_format($maximages);
       	    $stats['views'] = vb_number_format($maxviews);
            $totalcache['categories'] = vb_number_format($maxcategories);
            $stats['cards'] = vb_number_format($maxcards);
    	    $stats['posts'] = vb_number_format($maxposts);
    	    $stats['diskspace'] = vb_number_format($maxfilesize + $maxorigfilesize, 1, true);

	$show['stats'] = true;
	}

	$show['category'] = iif($showfields['category'], true, false);

	if ($ppg_options['gallery_newhomeimages'] OR $ppg_options['gallery_randomhomeimages'])
	{
		include_once('./includes/class_bbcode.php');

		$bbcode_parser =& new vB_BbCodeParser($vbulletin, fetch_tag_list());

		$query = fetch_image_fields();
		$cellwidth = round(100 / $ppg_options['gallery_columns']) . '%';
		if ($privatecatids = fetch_private_categories())
		{
			$privatecatids = explode(',', $privatecatids);
		}

		if ($ppg_options['gallery_homeexcats'])
        {
            $ppg_options['gallery_homeexcats'] = explode(',', $ppg_options['gallery_homeexcats']);
            if(empty($privatecatids))
            {
                $privatecatids = $ppg_options['gallery_homeexcats'];
            }
            else
            {
                $privatecatids = array_merge((array)$privatecatids, (array)$ppg_options['gallery_homeexcats']);
            }
        }

		if (!empty($privatecatids))
		{
			$privcatids = 'images.catid NOT IN(' . implode(',', $privatecatids) . ') AND ';
		}
	}

// *********************************************************************************
// Get active users browsing
if (($ppg_options['gallery_displayloggedin'] == 1 OR $ppg_options['gallery_displayloggedin'] == 2 OR ($ppg_options['gallery_displayloggedin'] > 2 AND $vbulletin->userinfo['userid'])) AND !$show['search_engine'])
{
	$datecut = TIMENOW - $vbulletin->options['cookietimeout'];
	$browsers = '';
	$comma = '';

	$show['activeusers'] = iif(!$show['search_engine'], true, false);

	// Don't put the ingallery value in the WHERE clause as it might not be the newest location!
	$imageusers = $db->query_read_slave("
		SELECT
			user.username, (user.options & " . $vbulletin->bf_misc_useroptions['invisible'] . ") AS invisible, user.usergroupid,
			session.userid, session.badlocation, session.inforum, session.lastactivity,
			IF(displaygroupid=0, user.usergroupid, displaygroupid) AS displaygroupid, infractiongroupid
		FROM " . TABLE_PREFIX . "session AS session
		LEFT JOIN " . TABLE_PREFIX . "user AS user ON(user.userid = session.userid)
		WHERE session.lastactivity > $datecut " . iif($ppg_options['gallery_displayloggedin_local'] == 1, "AND badlocation ='600'") . "
        " . iif($ppg_options['gallery_displayloggedin'] == 1 OR $ppg_options['gallery_displayloggedin'] == 3, "ORDER BY username ASC") . "
	");

	$numberguest = 0;
	$numberregistered = 0;
	$doneuser = array();

    $vbulletin->templatecache['ADV_GALLERY'] = str_replace( '"online.php', '"' . $vbulletin->options['bburl'] . '/online.php', $vbulletin->templatecache['ADV_GALLERY']);
    $vbulletin->templatecache['forumhome_loggedinuser'] = str_replace( '"member.php', '"' . $vbulletin->options['bburl'] . '/member.php', $vbulletin->templatecache['forumhome_loggedinuser']);


	if ($vbulletin->userinfo['userid'])
	{
		$vbulletin->userinfo['joingroupid'] = iif($vbulletin->userinfo['displaygroupid'], $vbulletin->userinfo['displaygroupid'], $vbulletin->userinfo['usergroupid']);
		$loggedin = array(
			'userid' => $vbulletin->userinfo['userid'],
			'username' => $vbulletin->userinfo['username'],
			'invisible' => $vbulletin->userinfo['invisible'],
			'invisiblemark' => $vbulletin->userinfo['invisiblemark'],
			'inforum' => 0,
			'lastactivity' => TIMENOW,
			'musername' => fetch_musername($vbulletin->userinfo, 'joingroupid')
		);
		$numberregistered = 1;
		$numbervisible = 1;
		fetch_online_status($loggedin);
		eval('$activeusers = "' . fetch_template('forumhome_loggedinuser') . '";');
		$doneuser["{$vbulletin->userinfo['userid']}"] = 1;
		$comma = ', ';
	}

	// this requires the query to have lastactivity ordered by DESC so that the latest location will be the first encountered.
	while ($loggedin = $db->fetch_array($imageusers))
	{
		if (empty($doneuser["$loggedin[userid]"]))
		{
				if ($loggedin['userid'] == 0) // Guest
				{
					$numberguest++;
				}
				else
				{
					$loggedin['musername'] = fetch_musername($loggedin);
					$numberregistered++;

					if (fetch_online_status($loggedin))
					{
						eval('$activeusers .= "' . $comma . fetch_template('forumhome_loggedinuser') . '";');
						$comma = ', ';
					}
				}
			if ($loggedin['userid'])
			{
				$doneuser["$loggedin[userid]"] = 1;
			}
		}
	}

	if (!$vbulletin->userinfo['userid'])
	{
		$numberguest = ($numberguest == 0) ? 1 : $numberguest;
		if ($numberregistered == 0)
		{
			$activeusers = '&nbsp;';
		}
	}
	$totalonline = $numberregistered + $numberguest;

	$db->free_result($imageusers);
	unset($comma, $userinfos, $userid, $userinfo, $loggedin, $imageusers, $datecut);

 }

// Newest images
	if ($ppg_options['gallery_newhomeimages'])
	{
       ($hook = vBulletinHook::fetch_hook('ppgal_home_newimages_query')) ? eval($hook) : false;

        $newhomeimages_datecut = TIMENOW - (86400*$ppg_options['gallery_newhomecutoff']);

		$show['newimages'] = true;
		$counter = 0;
		$adv_sorturl = '&amp;catid=newimages';
		$getnew = $db->query_read("
				SELECT imageid, images.title, filename, thumbname, originalname, extension, images.catid $query[fields]
				FROM " . TABLE_PREFIX . "ppgal_images AS images
				$query[tables]
				WHERE $privcatids valid = 1 $ignquery
" . iif(!empty($ppg_options['gallery_newhomecutoff']), "AND dateline >= $newhomeimages_datecut") . "
                ORDER BY dateline DESC
				LIMIT $ppg_options[gallery_newhomeimages]
		");
		if ($db->num_rows($getnew))
		{
			while ($images = $vbulletin->db->fetch_array($getnew))
			{
				$counter++;
				$newimagebits .= construct_imagebits($images);
			}

			if ($ppg_options['gallery_newhomeimages'] >= $ppg_options['gallery_columns'])
            {
                $newimagebits .= construct_empty_cellbits($ppg_options['gallery_columns']);
            }
		}
		else
		{
			eval('$newimagebits = "' . fetch_template('adv_gallery_nodisplay') . '";');
		}
		$db->free_result($getnew);
		unset($images);

		$search_text = $newhomepos;
		$vbulletin->templatecache['ADV_GALLERY'] = str_replace($search_text,
		$search_text.fetch_template('adv_gallery_newimages'),$vbulletin->templatecache['ADV_GALLERY']);


    }

	// Random images
	if ($ppg_options['gallery_randomhomeimages'])
	{
       ($hook = vBulletinHook::fetch_hook('ppgal_home_randimages_query')) ? eval($hook) : false;

       $randomhomeimages_datecut = TIMENOW - (86400*$ppg_options['gallery_randomhomecutoff']);

        $show['randomimages'] = true;
		$counter = 0;
		$getrand = $db->query_read("
				SELECT imageid, images.title, filename, thumbname, originalname, extension, images.catid $query[fields]
				FROM " . TABLE_PREFIX . "ppgal_images AS images
				$query[tables]
				WHERE $privcatids valid = 1 $ignquery
" . iif(!empty($ppg_options['gallery_randomhomecutoff']), "AND dateline >= $randomhomeimages_datecut") . "
                ORDER BY RAND()
				LIMIT $ppg_options[gallery_randomhomeimages]
		");
		if ($db->num_rows($getrand))
		{
			while ($images = $vbulletin->db->fetch_array($getrand))
			{
				$counter++;
				$adv_sorturl = '&amp;catid=' . $images['catid'];
				$randomimagebits .= construct_imagebits($images);
			}
			if ($ppg_options['gallery_randomhomeimages'] >= $ppg_options['gallery_columns'])
            {
                $randomimagebits .= construct_empty_cellbits($ppg_options['gallery_columns']);
            }
		}
		else
		{
			eval('$randomimagebits = "' . fetch_template('adv_gallery_nodisplay') . '";');
		}
		$db->free_result($getrand);
		unset($images);

   		$search_text = $ranhomepos;
		$vbulletin->templatecache['ADV_GALLERY'] = str_replace($search_text,
		$search_text.fetch_template('adv_gallery_randomimages'),$vbulletin->templatecache['ADV_GALLERY']);
    }



	if ($ppg_options['gallery_navbarhomelink'])
	{
		$navbits[''] = $ppg_options['gallery_title'];
		$navbits = construct_navbits($navbits);
	}

    ($hook = vBulletinHook::fetch_hook('ppgal_home_complete')) ? eval($hook) : false;

	eval('$navbar = "' . fetch_template('navbar') . '";');
	eval('$gallerynav = "' . fetch_template('adv_gallery_navbar') . '";');

}
else
{
	if ($ppg_options['gallery_showstats'])
	{
        $stats['images'] = vb_number_format($maximages);
       	$stats['views'] = vb_number_format($maxviews);
        $stats['categories'] = vb_number_format($maxcategories);
        $stats['cards'] = vb_number_format($maxcards);
    	$stats['posts'] = vb_number_format($maxposts);
    	$stats['diskspace'] = vb_number_format($maxfilesize + $maxorigfilesize, 1, true);

	    $show['stats'] = true;
	}

	$show['subcats'] = true;
	$categoryjump = print_category_jump($catid);

	foreach ($categorycache AS $navcat)
	{
		if ($navcat['catid'] == $catid)
		{
			$navinfo['title'] = stripslashes($navcat['title']);
			$navinfo['parentlist'] = $navcat['parentlist'];
		}
	}

	if ($ppg_options['gallery_navbarhomelink'])
	{
		$navbits["$ppg_options[gallery_url]"] = $ppg_options['gallery_title'];
	}
	$navbits = construct_dir_navbits($navinfo['parentlist']);
	$navbits = construct_navbits($navbits);

    ($hook = vBulletinHook::fetch_hook('ppgal_home_complete')) ? eval($hook) : false;

	eval('$navbar = "' . fetch_template('navbar') . '";');
	eval('$gallerynav = "' . fetch_template('adv_gallery_navbar') . '";');
}

$pagetitle = $ppg_options['gallery_title'];

eval('print_output("' . fetch_template('ADV_GALLERY') . '");');


?>