<?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_search');
define('PP_SCRIPT', 'vBGallery');

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

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

// pre-cache templates used by all actions
$globaltemplates = array(
		'ADV_GALLERY_SEARCH',
		'adv_gallery_search_custombits',
		'ADV_GALLERY_RESULTS',
		'adv_gallery_imagebit'
);

// 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_search_start')) ? eval($hook) : false;

if (!isset($_REQUEST['do']) OR !$_REQUEST['do'])
{
	$_REQUEST['do'] = 'search';
}

if (!$galleryperms['cansearchimages'])
{
	print_no_permission();
}

// ############################### Search results ###############################
if ($_REQUEST['do'] == 'searchresults')
{
	require_once(DIR . '/includes/functions_search.php');
	require_once(DIR . '/includes/functions_misc.php');

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




	$catids = $vbulletin->input->clean_gpc('r', 'catids', TYPE_ARRAY_STR);
    $cfields = $vbulletin->input->clean_gpc('r', 'cfields', TYPE_ARRAY_STR);
    $fields = $vbulletin->input->clean_gpc('r', 'fields', TYPE_ARRAY_STR);
    $dateline = $vbulletin->input->clean_gpc('r', 'dateline', TYPE_INT);
	$string = $vbulletin->input->clean_gpc('r', 'string', TYPE_NOHTML);
	$orderby = $vbulletin->input->clean_gpc('r', 'orderby', TYPE_NOHTML);
	$direction = $vbulletin->input->clean_gpc('r', 'direction', TYPE_NOHTML);
	$subcats = $vbulletin->input->clean_gpc('r', 'subcats', TYPE_INT);
	$username = $vbulletin->input->clean_gpc('r', 'username', TYPE_NOHTML);
	$exactusername = $vbulletin->input->clean_gpc('r', 'exactusername', TYPE_INT);
	$quicksearch = $vbulletin->input->clean_gpc('r', 'quicksearch', TYPE_INT);

    $pagenumber = $vbulletin->input->clean_gpc('r', 'pagenumber', TYPE_INT);
	$searchid = $vbulletin->input->clean_gpc('r', 'searchid', TYPE_INT);
// #############################################################################
	// start search timer
	$starttimecounter = microtime();

    // check for flood search
    if ($vbulletin->options['searchfloodtime'])
	{
		if ($checksearch = $db->query_first("SELECT dateline FROM " . TABLE_PREFIX . "ppgal_search WHERE userid = '" . $vbulletin->userinfo['userid'] . "' AND dateline > " . (TIMENOW - $vbulletin->options['searchfloodtime']) . ""))
		{
			eval(standard_error(fetch_error('searchfloodcheck', $vbulletin->options['searchfloodtime'], ($vbulletin->options['searchfloodtime'] - (TIMENOW - $checksearch['dateline'])))));
		}
	}

    // Quick search from navbar and within a category
    if ($quicksearch){
	$fields = array('title', 'keywords', 'description');

    // check if in a category
    if($catid == '0'){$catids = 0;}

    $subcats = 1;
    }

    // Check for missing data
    if (!$string AND !$username)
    {
		eval(standard_error(fetch_error('searchspecifyterms')));
	}

	if (empty($fields) AND empty($cfields))
	{
		eval(standard_error(fetch_error('adv_gallery_error_no_search_fields')));
	}

	if (!empty($fields))
	{
		$sfields = $fields;
	}

	if (!empty($cfields))
	{
		$sfields = array_merge((array)$sfields, (array)$cfields);
		$cfjoin = 'LEFT JOIN ' . TABLE_PREFIX . 'ppgal_customfields_entries AS customfields ON (images.imageid = customfields.imgid)';
	}

	$fields = implode(',', $sfields);

	if ($string)
	{
		$searchstring = explode(' ', $string);
		$condition = '(';
		$strcount = 0;
		foreach ($searchstring AS $sstring)
		{
			$concount = 0;
			$strcount++;
			if ($strcount > 1)
			{
				$condition .= '(';
			}
			foreach ($sfields AS $value)
			{
				$concount++;
				if ($concount > 1)
				{
					$condition .= ' OR ';
				}

				if ($value == 'title')
				{
					$value = 'images.title';
				}

				if ($_REQUEST['matchwholeword'])
				{
					$condition .= "$value LIKE '% " . sanitize_word_for_sql($sstring) . " %'";
				}
				else
				{
					$condition .= "$value LIKE '%" . sanitize_word_for_sql($sstring) . "%'";
				}
			}
			$condition .= ') AND ';
		}
	}

	if (in_array('pagetext', $sfields))
	{
		$postjoin = 'LEFT JOIN ' . TABLE_PREFIX . 'ppgal_posts AS posts ON (posts.imageid = images.imageid)';
	}

	if ($username)
	{
		if (!$exactusername AND strlen($username) < 3)
		{
			eval(standard_error(fetch_error('searchnametooshort')));
		}

		$username = sanitize_word_for_sql($username);

		$getuserids = $db->query_read("SELECT userid, username FROM " . TABLE_PREFIX . "user WHERE username " . iif($exactusername, '= \'' . $username . '\'', 'LIKE \'%' . $username . '%\''));
		if ($db->num_rows($getuserids))
		{
			$users = array();
			while ($userinfo = $vbulletin->db->fetch_array($getuserids))
			{
				$users["$userinfo[userid]"] = $userinfo['username'];
			}
		}
		else
		{
			eval(standard_error(fetch_error('invalidid', $vbulletin->options['bburl'] . '/' . $vbulletin->options['contactuslink']  .  $vbulletin->session->vars['sessionurl_q'], $vbphrase['user'])));
		}
		$userids = implode(',', array_keys($users));
		if (implode(',', $sfields) == 'pagetext')
        {
            $condition .= ' posts.userid IN(' . $userids . ') AND ';
        }
        else
        {
            $condition .= ' (images.userid IN(' . $userids . ')' . iif (in_array('pagetext', $sfields), ' OR posts.userid IN(' . $userids . ')') . ') AND ';
        } 
		}

	if ($dateline)
	{
		if ($_POST['new_old'] == 'older')
		{
			$arr = '<=';
		}
		else
		{
			$arr = '>=';
		}

		if ($dateline == 'lastvisit')
		{
			$condition .= ' images.dateline ' . $arr . ' ' . $vbulletin->userinfo['lastvisit'] . ' AND ';
		}
		else
		{
			$cutoffdate = time() - ($dateline * 86400);
			$condition .= ' images.dateline ' . $arr . ' ' . $cutoffdate . ' AND ';
		}
		unset($arr);
	}
	if ($_POST['replycount'] OR $_POST['leastmost'] == 'most')
	{
		if ($_POST['leastmost'] == 'least')
		{
			$arr = '>=';
		}
		else
		{
			$arr = '<=';
		}
		$condition .= ' posts ' . $arr . ' ' . intval($_POST['replycount']) . ' AND ';
	}

	if (empty($catids) AND $catids != 0)
	{
		eval(standard_error(fetch_error('adv_gallery_search_nocat')));
	}

	$categoryperms = fetch_category_perms();
	if ($privatecatids = fetch_private_categories())
	{
		$condition .= ' images.catid NOT IN(' . $privatecatids . ') AND ';
	}

	if (!empty($catids) AND in_array('favorites', $catids))
	{
		$searchquery = "
				SELECT images.imageid
				FROM " . TABLE_PREFIX . "ppgal_favorites AS favorites
				LEFT JOIN " . TABLE_PREFIX . "ppgal_images AS images USING (imageid)
				$postjoin
				$cfjoin
				WHERE $condition valid = 1
		";
	}
	else
	{
		if (!empty($catids) AND $catids != array(0))
		{
			if ($subcats)
			{
				$newcatinfo = array();
				foreach ($catids AS $scats)
				{
					$newcatinfo[] = implode(',', fetch_category_children($scats));
				}
				$cids = implode(',', $newcatinfo);
			}
			else
			{
				$cids = implode(',', $catids);
			}

			$condition .= " images.catid IN($cids) AND ";
		}

		$searchquery = "
				SELECT images.imageid
				FROM " . TABLE_PREFIX . "ppgal_images AS images
				$postjoin
				$cfjoin
				WHERE $condition valid = 1
		";
	}

	// Get Images
	$getimages = $db->query_read($searchquery);

	if ($debug)
	{
		$gallerynav .= '<table width="100%"><tr><td>' . $searchquery . '</td></tr></table><br />';
	}

	if ($db->num_rows($getimages))
	{
		$imagecount = 0;
		while ($images = $vbulletin->db->fetch_array($getimages))
		{
			$imagecount++;
			$imageidarray[] = $images['imageid'];
		}
	}
	else
	{
		eval(standard_error(fetch_error('searchnoresults', '')));
	}

	$countimages['count'] = $imagecount;

	$db->free_result($getimages);
	unset($images);

	if (!empty($imageidarray))
	{
		$imagearray = implode(',', $imageidarray);

		if (!empty($users))
		{
			$usernames = serialize($users);
		}

		$db->query_write("INSERT INTO " . TABLE_PREFIX . "ppgal_search (string, username, sfields, catids, dateline, userid, imageids, orderby, direction, wholeword, numresults, searchtime) VALUES ('" . addslashes(htmlspecialchars($string)) . "', '" . addslashes($usernames) . "', '$fields', '$cids', '" . time() . "', '" . $vbulletin->userinfo['userid'] . "', '$imagearray', '" . addslashes(htmlspecialchars($orderby)) . "', '" . addslashes(htmlspecialchars($direction)) . "', '$_REQUEST[matchwholeword]', '$imagecount', '" .  vb_number_format(fetch_microtime_difference($starttimecounter), 3) . "')");

		$searchid = $db->insert_id();

		$vbulletin->url = 'browseimages.php?' . $vbulletin->session->vars['sessionurl'] . 'do=searchresults&amp;searchid=' . $searchid;
		eval(print_standard_redirect('search'));
	}
}

// ############################### Main search page ###############################
if ($_REQUEST['do'] == 'search')
{
	if ($ppg_options['gallery_allowreplies'])
	{
		$counter = 1;
	}
	else
	{
		$counter = 0;
	}

	$customfields = $db->query_read("
			SELECT fieldid, title
			FROM " . TABLE_PREFIX . "ppgal_customfields
			WHERE searchable = 1
			ORDER BY displayorder
	");
	while ($field = $vbulletin->db->fetch_array($customfields))
	{
		$counter++;
		if ($counter == 2)
		{
			$customfieldboxes .= '</tr><tr>';
			$counter = 0;
		}
		eval('$customfieldboxes .= "' . fetch_template('adv_gallery_search_custombits') . '";');
	}

	if (!$catid)
	{
		$selected[0] = 'selected="selected"';
	}

	$categorylist = print_cat_select($catid, 'search');

	$navbits[''] = $vbphrase['search'];
	$navbits = construct_navbits($navbits);

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

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

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

}

?>