<?php
/**************************************************************************************************
| Ionicware
| http://www.ionicware.com
| support@ionicware.com
|
|**************************************************************************************************
|
| Copyright (c) 2011 ionicware.com. All rights reserved.
|**************************************************************************************************/

include("include/config.php");
include("include/functions/import.php");
$thebaseurl = $config['baseurl'];

$s = stripslashes((is_array($_REQUEST['s']) ? null : strip_tags($_REQUEST['s']))); // ?x[]=: as on 7.4, not a TypeError (#1925)

/*
 * Make the title change based on category and
 * page
 * 8/16/2012
 */
if ($config['sitetitle']  == 'CodeClerks')
{
	$title = $lang['2060'];
}
else if ($config['sitetitle']  == 'ListingDock')
{
	$title = $lang['2061'];
}
else
{
	$title = $lang['612'];
}
$page = intval($_REQUEST['page']);

/*
 * Forward the user to a proper URL that
 * google will love.
 * 1/9/2013
 */
if (stristr($_SERVER['REQUEST_URI'], '/faq?s=')) {
	///faq?s=r/tag/Clerks
	$newsquery = str_ireplace('/faq?s=', 'faq/s/', $_SERVER['REQUEST_URI']);
	header("location: $config[baseurl]/$newsquery");
	die();
}

/*
 * If it is the category or
 * tag based, add an extra bit
 * added 11/30/2011
 */
if (!empty($_REQUEST['cat'])) {
	$category = escape($_REQUEST['cat']);
	$addsql .= " AND B.seo='$category'";

	//$catname = GetQuestionCatNameFromSeo($category);
	$categoryDetails = GetCategoryInfoFromTypeSeo('faq', $category);


	if ($config['baseurl'] == 'http://www.monsterbacklinks.com' && $categoryDetails['name'] == 'SEOClerks')
	{
		$categoryDetails['name'] = 'Monster Backlinks';
	}
	else if ($config['baseurl'] == 'https://www.seocheckout.com' && $categoryDetails['name'] == 'SEOClerks')
	{
		$categoryDetails['name'] = 'Seocheckout';
	}
	else if ($config['baseurl'] == 'https://www.seolads.com' && $categoryDetails['name'] == 'SEOClerks')
	{
		$categoryDetails['name'] = 'SEOLads';
	}

	$catname 			= $categoryDetails['name'];
	$h2header 			= $categoryDetails['h2header'];
	$metaheader 		= $categoryDetails['metaheader'];
	$metadescription 	= $categoryDetails['metadescription'];
	$categoryId 		= intval($categoryDetails['CATID']);

	/*
	 * Get all of the parents
	 * Category data for the nav
	 * 6/18/2016
	 */
	if ($categoryDetails['parentid'] > 0)
	{
		$parentCatDetails = GetCategorySeoFromType('faq', $categoryDetails['parentid']);

		if ($parentCatDetails['parentid'] > 0)
		{
			$pParentCatDetails 	= GetCategorySeoFromType('faq', $parentCatDetails['parentid']);

			if ($pParentCatDetails['parentid'] > 0)
			{
				$ppParentCatDetails 	= GetCategorySeoFromType('faq', $pParentCatDetails['parentid']);
				$preCategory[] 			= $ppParentCatDetails;
			}

			$preCategory[] 		= $pParentCatDetails;
		}

		$preCategory[] 		= $parentCatDetails;
	}

	if (empty($metaheader) && !empty($metadescription))
	{
		//$metaheader = $metadescription;
	}

	$requestString .= "/cat/{$_REQUEST['cat']}";
	$title = $lang[2744] . ' ' . $catname;
}

/*
 * Tags
 */
if (!empty($_REQUEST['tag']))
{
	$tag = cleanit(escape($_REQUEST['tag']));
	/*
	 * We have to clean it here to prevent
	 * reflected XSS when we display it in the code
	 * 12-22-2014
	 */
	$tag 			= str_ireplace(array('.', '<', '>', '"', "'"), ' ', urldecode(stripslashes(strip_tags($tag))));
	$tag 			= str_replace('-', " ", $tag);
	$requestTag 	= $tag;
	$tag 			= escape($tag);
	$addsql 		.= " AND (A.tags LIKE '% {$tag} %' OR A.tags LIKE '{$tag} %' OR A.tags LIKE '% {$tag}' OR A.tags='{$tag}')";
	$requestString .= "/tag/{$tag}";

	$title = $lang[2744] . ' ' . $tag;

	/*
	 * Set this page to noindex to
	 * avoid duplicate content
	 * 6/16/2016
	 */
	// STemplate::assign('noindex', 1);
}
/*
 * Search
 */
if (!empty($_REQUEST['query'])) {
	$search			= cleanit((is_array($_REQUEST['query']) ? null : urldecode($_REQUEST['query']))); // ?x[]=: as on 7.4, not a TypeError (#1925)
	/*
	 * We have to clean it here to prevent
	 * reflected XSS when we display it in the code
	 * 12-22-2014
	 */
	$search = str_ireplace(array('.', '<', '>', '"', "'"), ' ', urldecode(stripslashes(strip_tags($search))));
	$requestSearch 	= $search;

	/*
	 * Forward the user to a proper URL that
	 * google will love.
	 * 1/9/2013
	 */
	if (stristr($_SERVER['REQUEST_URI'], '/faq?query=')) {
		$newsquery = urlencode($requestSearch);
		header("location: $config[baseurl]/faq/q/{$newsquery}");
		die();
	}

	/*
	 * Expode the string by spaces and then
	 * create the proper like statement
	 * 4/28/2012
	 */
	$queryArray   = explode(' ', $search);
	$likeString = array();
	foreach ($queryArray as $searchST) {
		$searchST = trim($searchST);
		if (!empty($searchST) && $searchST != ' ') {
			$likeString[] = "'%".escape($searchST)."%'";
		}
	}

	$questionSearch   = implode(' and A.question like', $likeString);
	$descSearch   	  = implode(' and A.description like', $likeString);
	$tagSearch        = implode(' and A.tags like', $likeString);

	$search 		= escape($search);
	$addsql .= " AND ((A.question LIKE {$questionSearch})
					OR (A.description LIKE {$descSearch})
					OR (A.tags LIKE $tagSearch))";

	$requestString .= "/q/" . urlencode($requestSearch);
	$title = $lang[2744] . ' ' . $search;

	/*
	 * Set this page to noindex to
	 * avoid duplicate content
	 * 6/16/2016
	 */
	// $config['noindex'] = 1;
	// STemplate::assign('noindex', 1);
}

/*
 * Username based question find
 * 7/27/2013
 */
if (!empty($_REQUEST['uname']) && $_REQUEST['type'] == 'questions') {
	$uname = escape(cleanit($_REQUEST['uname'], true));

	$title = $lang[2743] . ' ' . $uname;

	/*
	 * Get the USERID from the username
	 * 7/27/2013
	 */
	$USERIDQ = intval(escape(GetUseridFromUsername($uname)));

	if ($USERIDQ > 0)
	{
		$addsql .= " AND A.userid={$USERIDQ}";
		$requestString .= "/u/{$_REQUEST['uname']}/type/questions";
	}
	else
	{
		include '404.php'; // unknown member: a 404, not a redirect to /faq (2026-09-23)
		die();
	}

	/*
	 * Set this page to noindex to
	 * avoid duplicate content
	 * 6/16/2016
	 */
	//$config['noindex'] = 1;
	//STemplate::assign('noindex', 1);
}

/*
 * Username based question find
 * 7/27/2013
 */
if (!empty($_REQUEST['uname']) && $_REQUEST['type'] == 'answers') {
	$uname = escape(cleanit($_REQUEST['uname']));

	/*
	 * Get the USERID from the username
	 * 7/27/2013
	 */
	$USERIDA = intval(escape(GetUseridFromUsername($uname)));

	if ($USERIDA > 0)
	{
		$query 		= "SELECT distinct quesid FROM answers WHERE userid=$USERIDA";
		$results 	= $conn->execute($query);
		$h 			= $results->getrows();

		$title = "Answers from user {$uname} ";

		/*
		 * Loop through the results
		 */
		foreach ($h as $answer)
		{
			$returnString .= "{$answer['quesid']},";
		}

		if (!empty($returnString))
		{
			$returnString = '(' . $returnString;

			 if (substr($returnString, -1) == ',')
			 {
				 $returnString	= substr($returnString, 0, -1);
			 }

			 $returnString = $returnString . ')';

			$addsql .= " AND A.quesid IN {$returnString}";

			$requestString .= "/u/{$_REQUEST['uname']}/type/answers";
		}
		else
		{
			$addsql .= " AND A.quesid IN (0)";
		}
	}
	else
	{
		include '404.php'; // unknown member: a 404, not a redirect to /faq (2026-09-23)
		die();
	}

	/*
	 * Set this page to noindex to
	 * avoid duplicate content
	 * 6/16/2016
	 */
	// STemplate::assign('noindex', 1);
	// $config['noindex'] = 1;
}


if($page=="")
{
	$page = "1";
}
$currentpage = $page;

if ($page >=2)
{
	$title = $title . ' ' . $lang[788] . ' ' . $page;
	$pagingstart = ($page-1)*$config['items_per_page'];
}
else
{
	$pagingstart = "0";
}

if($s == "r")
{
	$dby = "A.total_answer desc";
}
elseif($s == "rz")
{
	$dby = "A.total_answer asc";
}
elseif($s == "v")
{
	$dby = "A.combined_votes desc";
}
elseif($s == "vz")
{
	$dby = "A.combined_votes asc";
}
elseif($s == "p")
{
	$dby = "A.total_views desc";
}
elseif($s == "pz")
{
	$dby = "A.total_views asc";
}
elseif($s == "h")
{
	$dby 	= "A.total_answer desc";
	$addsql .= " AND date_asked>UNIX_TIMESTAMP(NOW())-2592000 "; // 2592000 = 30 days
}
elseif($s == "hz")
{
	$dby 	= "A.total_answer asc";
	$addsql .= " AND date_asked>UNIX_TIMESTAMP(NOW())-2592000 "; // 2592000 = 30 days
}
elseif($s == "u")
{
	$dby 	= "A.quesid desc";
	$addsql .= " AND total_answer=0 ";
}
elseif($s == "uz")
{
	$dby 	= "A.quesid asc";
	$addsql .= " AND total_answer=0 "; // 2592000 = 30 days
}
elseif($s == "c")
{
	$dby = "A.date_answered desc";
}
elseif($s == "cz")
{
	$dby = "A.date_answered asc";
}
elseif($s == "dz")
{
	$dby = "A.date_asked asc";
}
else
{
	$dby = "A.sticky DESC, A.date_asked DESC";
}

$query1 = "SELECT count(A.quesid) as total FROM questions A, categories_faq B, seoclerks.members C
			where A.status='1' AND A.catid=B.CATID AND A.userid=C.USERID $addsql LIMIT 1";

$query2 = "SELECT A.*, C.username, C.userlevel FROM questions A, categories_faq B, seoclerks.members C
			where A.status='1' AND A.catid=B.CATID AND A.userid=C.USERID $addsql
			ORDER BY $dby LIMIT $pagingstart, $config[items_per_page]";

$executequery1 = $conn->CacheExecute(120, $query1);
$scriptolution = $executequery1->fields['total'];

/*
 * A member's question/answer list is a list of links to discussions that are
 * indexed on their own, and most are empty: Google filed thousands as soft 404s
 * or duplicates. Keep them out of the index (links are still followed), and
 * likewise any tag list that has nothing in it.
 * 2026-09-23
 */
if (!empty($_REQUEST['uname']) || (!empty($_REQUEST['tag']) && intval($scriptolution) == 0)) $config['noindex'] = 1;

if ($scriptolution > 0)
{
	if($executequery1->fields['total']<=$config['maximum_results'])
	{
		$total = $executequery1->fields['total'];
	}
	else
	{
		$total = $config['maximum_results'];
	}
	$toppage = ceil($total/$config['items_per_page']);
	if($toppage==0)
	{
		$xpage=$toppage+1;
	}
	else
	{
		$xpage = $toppage;
	}

	$executequery2 	= $conn->CacheExecute(120, $query2);
	$posts 			= $executequery2->getrows();

	/*
	 * Added on 10/16/2011 to get rid of BBCode
	 */
	foreach ($posts as &$faq)
	{
		$faq['gtitle'] = replaceGig($faq['question']);
		$faq['gdesc']  = RemoveTextBbcode($faq['description']);
		$faq['badges'] = json_decode($faq['badges']);

		/*
		 * If the site is MBL, change all references of SC
		 * / Ionicware to MBL.
		 * 4/8/2014
		 */
		if ($config['baseurl'] == 'http://www.monsterbacklinks.com')
		{
			$faq['gtitle'] = str_ireplace('SEOClerks.com', 'MonsterBacklinks.com', $faq['gtitle']);
			$faq['gtitle'] = str_ireplace('Seoclerks', 'Monster Backlinks', $faq['gtitle']);
			$faq['gtitle'] = str_ireplace('SEOClerk', 'Monster Backlinks', $faq['gtitle']);
			$faq['gtitle'] = str_ireplace('SEO Clerks', 'Monster Backlinks', $faq['gtitle']);
			$faq['gtitle'] = str_ireplace('Ionicware', 'SeoMerTech', $faq['gtitle']);

			$faq['gdesc'] = str_ireplace('SEOClerks.com', 'MonsterBacklinks.com', $faq['gdesc']);
			$faq['gdesc'] = str_ireplace('Seoclerks', 'Monster Backlinks', $faq['gdesc']);
			$faq['gdesc'] = str_ireplace('SEOClerk', 'Monster Backlinks', $faq['gdesc']);
			$faq['gdesc'] = str_ireplace('SEO Clerks', 'Monster Backlinks', $faq['gdesc']);
			$faq['gdesc'] = str_ireplace('Ionicware', 'SeoMerTech', $faq['gdesc']);
		}
		else if ($config['baseurl'] == 'https://www.seocheckout.com')
		{
			$faq['gtitle'] = str_ireplace('SEOClerks.com', 'Seocheckout.com', $faq['gtitle']);
			$faq['gtitle'] = str_ireplace('Seoclerks', 'Seocheckout', $faq['gtitle']);
			$faq['gtitle'] = str_ireplace('SEOClerk', 'Seocheckout', $faq['gtitle']);
			$faq['gtitle'] = str_ireplace('SEO Clerks', 'Seocheckout', $faq['gtitle']);
			$faq['gtitle'] = str_ireplace('Ionicware', 'Seocheckout', $faq['gtitle']);

			$faq['gdesc'] = str_ireplace('SEOClerks.com', 'Seocheckout.com', $faq['gdesc']);
			$faq['gdesc'] = str_ireplace('Seoclerks', 'Seocheckout', $faq['gdesc']);
			$faq['gdesc'] = str_ireplace('SEOClerk', 'Seocheckout', $faq['gdesc']);
			$faq['gdesc'] = str_ireplace('SEO Clerks', 'Seocheckout', $faq['gdesc']);
			$faq['gdesc'] = str_ireplace('Ionicware', 'Seocheckout', $faq['gdesc']);
		}
		else if ($config['baseurl'] == 'https://www.seolads.com')
		{
			$faq['gtitle'] = str_ireplace('SEOClerks.com', 'SEOLads.com', $faq['gtitle']);
			$faq['gtitle'] = str_ireplace('Seoclerks', 'SEOLads', $faq['gtitle']);
			$faq['gtitle'] = str_ireplace('SEOClerk', 'SEOLads', $faq['gtitle']);
			$faq['gtitle'] = str_ireplace('SEO Clerks', 'SEOLads', $faq['gtitle']);
			$faq['gtitle'] = str_ireplace('Ionicware', 'SEOLads', $faq['gtitle']);

			$faq['gdesc'] = str_ireplace('SEOClerks.com', 'SEOLads.com', $faq['gdesc']);
			$faq['gdesc'] = str_ireplace('Seoclerks', 'SEOLads', $faq['gdesc']);
			$faq['gdesc'] = str_ireplace('SEOClerk', 'SEOLads', $faq['gdesc']);
			$faq['gdesc'] = str_ireplace('SEO Clerks', 'SEOLads', $faq['gdesc']);
			$faq['gdesc'] = str_ireplace('Ionicware', 'SEOLads', $faq['gdesc']);
		}

		/*
		* Do some extra work for the UNI theme.
		* 06/27/2018
		*/
		if ($config['themeUni']	== 1 && legacyNumber($_REQUEST['amp']) == 0) // the URL's text compared as 7.4 did: 8 compares 'abc' with a number as text (#1925)
		{
			if ($faq['userlevel'] > 5)
			{
				$newUserLevel 			= $faq['userlevel'] - 3;
				$faq['userlevel'] 		= 'X' . "<sup>{$newUserLevel}</sup>";
			}
		}

		/*
		 * Fetch how the browsing user
		 * has voted.
		 * 4/12/2012
		 */
		$faq['uservote'] 		= GetUserVote($faq['quesid'], 'ratings_faq', $_SESSION['USERID']);
		$faq['display_date']	= GetTimeAgo($faq['date_asked']);

		/*
		 * Get the last response time in the for of
		 * time ago.
		 * 9/16/2013
		 */
		$faq['display_lastanswer_date'] = GetTimeAgo($faq['date_answered']); // removed -3600 (not sure why there)
	}

	if($s != "")
	{
		$adds = "/s/$s";
	}

	$beginning	= $pagingstart+1;
	$ending		= $pagingstart+$executequery2->recordcount();

	/*
	* Pagination, refactored to a function 08/21/2018
	* Note: function still looks like ass.
	*
	* Returns an array of values.
	*/
	$linkUrl 	= $config['baseurl'] . '/faq/page/';

	// Create the pagination
	$paginationArray = createPagination($beginning, $ending, $currentpage, $toppage, $linkUrl, $requestString, 7, "ajaxTableSort", "data-droplet='marketlistings'", true);

	// Set the array results to local values
	$pageShowingUni = $paginationArray['pageShowingUni'];
	$pagetoplinks	= $paginationArray['pagetoplinks'];
	$pagelinks		= $paginationArray['pagelinks'];
	$pageNext		= $paginationArray['pageNext'];
	$pagelinksUni	= $paginationArray['pagelinksUni'];
}

/*
 * Get the counts
 * 8/3/2013
 */
$sql = "SELECT count(A.quesid) as total from questions as A
				where A.status='1' ";
/*
 * Specific for categories
 * 6/16/2016
 */
if ($categoryId > 0)
{
	$sql .= " AND CATID={$categoryId}";
}
$executequery1 	= $conn->CacheExecute(240, $sql);
$totalQuestions = $executequery1->fields['total'];

$sql = "SELECT count(A.ansid) as total
				FROM answers as A";
/*
 * Specific for categories
 * 6/16/2016
 */
if ($categoryId > 0)
{
	$sql .= ", questions as Q ";
}

$sql .=	" where A.status='1' ";

/*
 * Specific for categories
 * 6/16/2016
 */
if ($categoryId > 0)
{
	$sql .= " AND A.quesid=Q.quesid AND Q.CATID={$categoryId}";
}

$executequery1 	= $conn->CacheExecute(240, $sql);
$totalAnswers = $executequery1->fields['total'];

/*
 *  Popular Tags
 * 07-12-2018
 */
//for($i = 0; $i <= 5; $i++) {
foreach ($posts as $tagList)
{
	if (!empty($tagList['tags']))
	{
		$popTag			= str_ireplace(array('.', '<', '>', '"', "'"), ' ', urldecode(stripslashes(strip_tags($tagList['tags']))));
		$popArray 		= explode(',', $popTag);

		foreach ($popArray as $pop)
		{
			if (strlen($pop) < 20)
			{
				if (!is_array($popularTags) || !in_array($pop, $popularTags))
				{
					$popularTags[] = $pop;
				}
			}
		}
	}
}

/*
 * Splice the array to 10 results
 * 8/13/2018
 */
if (count((array) $popularTags) > 10)
{
	$popularTags = array_splice($popularTags, 0, 10);
}

/*
 * We don't need to execute this query if we are in the uni theme.
 * 8/13/2018
 */
if ($config['themeUni']	== 0 && legacyNumber($_REQUEST['amp']) == 0) // the URL's text compared as 7.4 did: 8 compares 'abc' with a number as text (#1925)
{
	/*
	* Fetch a randomly features service to advertise
	* on the right hand side of the FAQ section
	* 6/27/2016
	*/
	$query = "SELECT p.*, m.USERID, m.profilepicture, m.username, m.userlevel,
					m.lastlogin, m.ip, m.lip
				FROM posts as p,
					seoclerks.members as m
				WHERE m.USERID=p.USERID
					AND p.alwaysfeatured_upgrade>0
					AND p.feat=1
					AND p.active=1
					AND p.type!=99
				ORDER BY RAND()
				LIMIT 3
			";

	$randomAdQuery			= $conn->CacheExecute(60, $query);
	$randomAd	 			= $randomAdQuery->getrows();
	$randomAd				= ChangePostData($randomAd);
}

/*
 * Get all of the users who are currently in the
 * FAQ section
 * 6/25/2016
 */
$query = "SELECT USERID, username FROM members_ledger
			WHERE (script='".escape($config['faqScript'])."'
					OR script='".escape($config['viewFaqScript'])."')
				AND added>=UNIX_TIMESTAMP(NOW())-1200
			GROUP BY USERID
";
$executeUsersOnline 	= $conn->CacheExecute(15, $query);
$onlineUsers 			= $executeUsersOnline->getrows();


foreach ($onlineUsers as &$user)
{
	$query     			= "SELECT USERGROUP FROM members WHERE USERID='{$user['USERID']}'";
	$result    			= $conn->CacheExecute(240, $query);
	$user['USERGROUP']  = $result->fields['USERGROUP'];

	if ($user['USERGROUP'] == 'admin')
	{
		$user['class']		= 'justred';
	}
	else if ($user['USERGROUP'] == 'mod' || $user['USERGROUP'] == 'faqmod' || $user['USERGROUP'] == 'unpaidfaq')
	{
		$user['class'] 		= 'justblue';
	}
	else
	{
		$user['class'] 		= '';
	}
}

if ($config['themeUni']	== 1)
{
	/*
	* Set the header category
	* 10/10/2018
	*/
	$header_sub_cat_active = 'faq';
	$header_cat_active = 'community';

	$firstLoad 				= 1;
	$ajax 					= intval($_REQUEST['ajax']);
	$ajaxAdds 				= str_ireplace('?', '&', $adds);
	$ajaxAdds 				.= str_ireplace('?', '&', $latentAdds);
	$ajaxDefaults			= '';
	$config['pagetitle']	= $title;

	if (!empty($categoryId))
	{
		$ajaxAdds 		.= '&cat=' . $category;
		$ajaxDefaults	.= '&cat=' . $category;
	}
	if (!empty($tag))
	{
		$ajaxAdds 		.= '&tag=' . $tag;
		$ajaxDefaults	.= '&tag=' . $tag;
	}
	if (!empty($squery))
	{
		$ajaxAdds 		.= '&query=' . escape($squery);
	}
	if (!empty($uname))
	{
		$ajaxAdds 		.= '&uname=' . escape($squery);
		$ajaxDefaults	.= '&uname=' . $uname;
	}
	if (!empty($_REQUEST['type']))
	{
		$ajaxAdds 		.= '&type=' . escape(cleanit((is_array($_REQUEST['type']) ? null : htmlspecialchars($_REQUEST['type'], ENT_QUOTES)))); // ?x[]=: as on 7.4, not a TypeError (#1925)
		$ajaxDefaults 	.= '&type=' . escape(cleanit((is_array($_REQUEST['type']) ? null : htmlspecialchars($_REQUEST['type'], ENT_QUOTES)))); // ?x[]=: as on 7.4, not a TypeError (#1925)
	}

	if ($ajax == 1)
	{
		$firstLoad = 0;

		/**
		 * HACK, needs to be fixed. The last value for pagination changed to be PAGEDATA
		 * but this does not actually use it.
		 *
		 * @TODO: fix
		 *
		 */
		/**
		 * Fetch our page data
		 */
		$pageData = fetchCurrentPageData(count($posts), 'page');

		/**
		 * Replaced the code below with this as the code below was
		 * redundant in multiple files.
		 * 12/4/2018
		 */
		$ajaxJs = paginationFooterAjax($pagelinksUni, $pageShowingUni, $pageNext, $pageData);
		include 'views/faq/view_faq-bit.php';
		die();
	}
	else
	{
		include 'views/header/view_header-loader.php';
		include 'views/faq/view_faq.php';
		include 'views/footer/view_footer-loader.php';
	}
}
else
{
	$templateselect = "faq.tpl";
	//TEMPLATES BEGIN
	//TEMPLATES END
}