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

include_once("include/config.php");
include_once("include/functions/import.php");
include_once("include/functions/includes/string.php");
include_once("include/functions/includes/service.php");
include_once('include/bbcode.php');

/**
 * Debug data
 *
 * 2023-06-09 05:31:39 JD
 */
$__debug = isDebug();

/**
 * Get the user's username
 */
$uname 			= cleanit($_REQUEST['uname']);
$profileView 	= true; //This tells the listing views to display certain things only found on the profile

if ($uname == "") redirectAndDie('/');

/*
 * Added on 4/3/2013
 * If the user is linking into a service using an
 * affiliate link, forward them to the correct
 * URL
 *
 * Aff should go to the affiliate
 */
if ($_REQUEST['aff']) header("location: $config[baseurl]/user/{$uname}");

/*
* Custom Title
* 7/1/2013
*/
$pagetitle .= $uname . ' - ' . $lang[2337];


$query = "SELECT *
			FROM seoclerks.members
			WHERE username='".escape($uname)."'
			AND status='1'
			";

$executequery	= $conn->execute($query);
$userData		= $executequery->fields;
$USERID 		= $userData['USERID'];
$uid			= $USERID;
$addtime 		= $userData['addtime'];
$desc 			= $userData['description'];
$profileData 	= $userData['profile_data'];

if ($USERID <= 0)
{
	// Unknown or closed account: a 404, not a redirect to the homepage (a soft 404). 2026-09-23
	include '404.php';
	die();
}

/**
 * Grab what type of user this is. Buyer, Seller, Affiliate
 */

$userStatusArray 	= GetUserTypes($USERID, $profileData);
$userStatusMain 	= $userStatusArray['main'];

/**
 * Logged in users can send custom order requests
 */
if ($__loggedUserDetails['USERID'] > 0)
{
	$query = "SELECT gtitle, PID
						FROM posts
						WHERE USERID = ?
						AND active = 1
						AND type != 99
						";

	$results 	= $conn->CacheExecute(320, $query, array($__loggedUserDetails['USERID']));
	$services 	= $results->getrows();
}

/**
 * Setup additional data needed for the view
 */
($__loggedUserDetails['USERID'] == $uid) ? $userData['profileButtons']	= 0 : $userData['profileButtons']	= 1;

/*
* Data needed for the sidebar user info file.
* 11/30/2018
*/
$userData['profileBackground'] 	= $profileBackground;
$userData['userlevel'] 			= getUserLevelFromLevel($userData['userlevel']);
$userData['online'] 			= $online;
$userData['joinDate'] 			= $addtime;
$userData['moreinfo'] 			= 1;

/**
 * The "supports other sellers" badge. One primary-key lookup against the
 * table crons/cronSellerSupporters.php rebuilds - deliberately not an
 * aggregate over orders, which is what this profile page would otherwise have
 * to run on every view.
 */
$supporterBadgeData = function_exists('sellerSupporterBadge') ? sellerSupporterBadge($userData['USERID']) : null;

if (!empty($profileData))
{
	$profileDataArray 		= json_decode($profileData, true);
	$workTo		 			= $profileDataArray['workTo'];
	$outOffice 				= $profileDataArray['outOffice'];
	$workFrom		 		= $profileDataArray['workFrom'];
	$allow_custom			= $profileDataArray['allow_custom'];

	/**
	 * Assign all additional data to our $p array
	 * 2021-08-15 08:25:35 - SE
	 */
	foreach($profileDataArray as $key => $profile)
	{
		/**
		 * Some users have a "status" field in their profile data
		 * which causes issues in the order.
		 *
		 * 2021-08-25 16:03:05 JD
		 */
		if ($key != 'status') $userData[$key] = $profile;
	}
}

if (stristr($_SERVER["HTTP_HOST"], 'monsterbacklinks.com') || stristr($_SERVER["HTTP_HOST"], 'seolads.com') || stristr($_SERVER["HTTP_HOST"], 'seocheckout.com'))
	$desc = ConditionText($desc);

/*
* Get the average response time
* 8/7/2013
*/
$average_response_time = GetResponseTime($userData['average_response_time'], true);

/*
* Does this post have a short_url?
* If not, grab it.
* 5/25/2013
*/
if (empty($userData['short_url']))
	$userData['short_url'] = GetAndSetShortUrl($uname, 'user');

/**
* Decode our custom profile data so it
* can be displayed on the site
* 8/27/2016
*
* Code replaced with the background function.
*
* 2023-05-02 09:39:12 JD
*/
$profileBackground	= getUserBackground($USERID, '', false, $userData);

/*
* Update the viewed content so workers
* only see it once. :)
* 11/9/2011
*/
if ($__loggedUserDetails['USERID'] == $USERID && $userData['author_bookmarktip'] == 0)
{
	$query = "UPDATE members
				SET author_bookmarktip = 1
				WHERE USERID = '".escape($USERID)."'";
	$conn->execute($query);
}

/*
* Get the user skills and explode them.
* 1/12/2013
*/
if (!empty($userData['skills'])) $skills = formatUsersSkills($userData['skills']);

/*
* Is the User online?
* 2/1/2019
*/
(IsUserOnline($userData['USERID'], $userData['lastlogin'])) ? $userData['online'] = 1 : $userData['online'] = 0;

/*
* Added 12/1/2011
* to support the FAQ section
*/
$questions = $userData['total_questions'];
$answers   = $userData['total_answers'];

/*
* Get the last login date in days for the gig
* 8/5/2012
*/
$lastLoginDays = GetUserLastLoginDays($USERID, $userData['lastlogin']);

/*
* Get the totals for the user
* 8/5/2012
*/
$ratingData = GetBuyerRatingsTotal($USERID);

/*
* Get the country code
* 6/28/2012
*/
$countryReg	= GetCountryCode($userData['ip']);

/*
* Is the user browsing already following this
* user?
* 10/24/2012
*/
$isFollowing = isUserFollowingUser($USERID);

/*
* Get the latest folowers
* 10/23/2018
*/
$followers = getUniUserFollower($USERID, 4, 1);

/*
* Get the latest folowing
* 10/23/2018
*/
$following = getUniUserFollower($USERID, 4, 1, true);

/**
 * Get the users total follower count
 */
$countFollowers = getUserTotalFollower($USERID);
$countFollowing = getUserTotalFollower($USERID, true);

/**
 * Removed:
 *
 * 			ORDER BY A.PID DESC
 *			LIMIT $config[maximum_results]
 *
 * 2021-10-01 06:14:34 JD
 */
$query = "SELECT
				count(A.PID) AS total
			FROM
				posts A,
				seoclerks.members C
			WHERE A.active = '1'
				AND A.USERID = C.USERID
				AND A.USERID = ?
				AND A.type != 99
";

/**
 * Setup our prepared statments.
 */
$preparedVars[]	= escape($USERID);

/**
 * Execute
 */
$executequery 	= $conn->CacheExecute(500, $query, $preparedVars);
$totalResults 	= $executequery->fields['total'];

/**
 * Fetch page data for wants
 */
$pageData = fetchCurrentPageData($totalResults);

/**
 * In the order by clause, I removed:
 * 	packet_group ASC,
 *
 * This was causing services to not be sorted by lastgigedit.
 *
 * 2021-10-01 06:21:47 JD
 */
$query2 = "SELECT
				A.*,
				C.userlevel,
				C.username,
				C.ip,
				C.lip,
				C.profilepicture,
				/** view_index-bit.php reads these for the thumbnail seal and the pill - always seoclerks.members, so no per-storefront column check is needed here. */
				C.vetted,
				C.vetted_human
			FROM
				posts A,
				seoclerks.members C
			WHERE A.active = 1
				AND A.type != 99
				AND A.USERID = C.USERID
				AND A.USERID = ?
			ORDER BY lastgigedit DESC
			LIMIT {$pageData['start']}, {$config['items_per_page']}
		";

/**
 * Setup our prepared statments.
 */
$preparedVars[]	= escape($USERID);

$results	= $conn->CacheExecute(30, $query2, $preparedVars);
$posts 		= $results->getrows();

/*
* Returns an array of values.
*/
$linkUrl 	= $config['baseurl'] . "/user/{$uname}?page=";

// Create the pagination
$paginationArray = createPagination($pageData['start'] + 1, $pageData['total'], $pageData['page'], $pageData['lastPage'], $linkUrl, $adds, 10);

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

/*
* Global Function instead of the old
* one that was the same for each....
*/
$posts = ChangePostData($posts);

/*
* Want to Buy Listings
* 12/25/2013
*/
$query = "SELECT
				count(A.wantid) AS total
			FROM
				wanttobuy A,
				seoclerks.members C
			WHERE A.active = 1
			AND  A.USERID = C.USERID
			AND A.USERID = ?
			";

$executequery1 = $conn->CacheExecute(30, $query, $preparedVars);
$scriptolution = $executequery1->fields['total'];

/**
 * Fetch page data for wants
 */
$pageDataWTB = fetchCurrentPageData($scriptolution);

$query2 = "SELECT
				A.*,
				C.userlevel,
				C.username,
				C.ip,
				C.lip,
				C.vetted,
				C.vetted_human,
				D.seo
			FROM
				wanttobuy A,
				seoclerks.members C,
				categories_wanttobuy D
			WHERE A.active = 1
			AND A.USERID = C.USERID
			AND D.CATID = A.category
			AND A.USERID = ?
			ORDER BY lastgigedit DESC
			LIMIT $pageDataWTB[start], $config[items_per_page]";

$results	= $conn->CacheExecute(30, $query2, $preparedVars);
$wtbposts	= $results->getrows();

/*
* Returns an array of values.
*/
$linkUrlWTB 	= $config['baseurl'] . "/user/{$uname}?wtbpage=";

// Create the pagination
$paginationArray = createPagination($pageDataWTB['start'] + 1, $pageDataWTB['total'], $pageDataWTB['page'], $pageDataWTB['lastPage'], $linkUrlWTB, $adds, 10);

// Set the array results to local values
$wtbpageShowingUni 	= $paginationArray['pageShowingUni'];
$wtbpagetoplinks	= $paginationArray['pagetoplinks'];
$wtbpagelinks		= $paginationArray['pagelinks'];
$wtbpageNext		= $paginationArray['pageNext'];
$wtbpagelinksUni	= $paginationArray['pagelinksUni'];

/*
* Global Function instead of the old
* one that was the same for each....
*/
$wtbposts = ChangeWTBPostData($wtbposts);

/*
* Want to Trade
* 12/25/2013
*/
$query = "SELECT
				count(A.tradeid) AS total
			FROM
				wanttotrade A,
				seoclerks.members C
			WHERE A.active = 1
			AND  A.USERID = C.USERID
			AND A.USERID = ?
			ORDER BY A.tradeid DESC";

$executequery1 = $conn->CacheExecute(30, $query, $preparedVars);
$scriptolution = $executequery1->fields['total'];

/**
 * Fetch page data for wants
 */
$pageDataWTT = fetchCurrentPageData($scriptolution);

$query2 = "SELECT
				A.*,
				C.userlevel,
				C.username,
				C.ip,
				C.lip,
				C.vetted,
				C.vetted_human,
				D.seo
			FROM
				wanttotrade A,
				seoclerks.members C,
				categories_wanttotrade D
			WHERE A.active = '1'
			AND A.USERID = C.USERID
			AND D.CATID = A.category
			AND A.USERID = ?
			ORDER BY lastgigedit DESC
			LIMIT $pageDataWTT[start], $config[items_per_page]";

$results	= $conn->CacheExecute(30, $query2, $preparedVars);
$wttposts	= $results->getrows();

/*
* Returns an array of values.
*/
$linkUrlWTT 	= $config['baseurl'] . "/user/{$uname}?wtbpage=";

// Create the pagination
$paginationArray = createPagination($pageDataWTT['start'] + 1, $pageDataWTT['total'], $pageDataWTT['page'], $pageDataWTT['lastPage'], $linkUrlWTT, $adds, 10);

// Set the array results to local values
$wtbpageShowingUni 	= $paginationArray['pageShowingUni'];
$wtbpagetoplinks	= $paginationArray['pagetoplinks'];
$wtbpagelinks		= $paginationArray['pagelinks'];
$wtbpageNext		= $paginationArray['pageNext'];
$wtbpagelinksUni	= $paginationArray['pagelinksUni'];

/*
* Global Function instead of the old
* one that was the same for each....
*/
$wttposts = ChangeWTTPostData($wttposts);

/*
* Get any posts from the other marketplaces
* 5/24/2017
*/
$otherPostData = null;
foreach ($config['sharedbs'] as $db)
{
	if ($db != $config['DBNAME'])
	{
		$query2 = "SELECT
						A.*, C.userlevel,
						C.username,
						C.ip,
						C.lip,
						C.vetted,
						C.vetted_human,
						A.lastgigedit
					FROM
						{$db}.posts A,
						seoclerks.members C
					WHERE A.active='1'
					AND A.type!=99
					AND A.USERID=C.USERID
					AND A.USERID='".escape($USERID)."'
					ORDER BY A.lastgigedit DESC
					LIMIT 10";

		$results		= $conn->CacheExecute(30, $query2);
		$otherPosts 	= $results->getrows();

		foreach ($otherPosts as &$oPost)
		{
			$oPost['siteDB'] = $db;
			$otherPostData[] = $oPost;
		}
	}
}


/**
 * Merge the other services from other sites to the main results
 * 7/23/2019
 */
// $totalResults is the count here, so 7.4's array_merge() returned null
// (and nothing reads it after this); 8 throws. Keep the 7.4 result.
$totalResults = (is_array($totalResults) && is_array($otherPosts)) ? array_merge($totalResults, $otherPosts) : null;

/*
	* We only want to run the query for infractions if they
	* will be displayed, not for every access to the user page
	* 11/10/2016
	*/
if ($USERID == $__loggedUserDetails['USERID'] || isStaff())
{
	/*
	* Get user infraction data
	* 1/12/2013
	*/
	$query 			= "SELECT
							date,
							expiredate,
							log,
							expired
						FROM
							seoclerks.members_infractions
						WHERE USERID='".escape($USERID)."'
						ORDER BY date DESC";

	$results		= $conn->CacheExecute(30, $query);
	$infractions 	= $results->getrows();

	if (count($infractions) > 0)
	{
		foreach ($infractions as &$infraction)
		{
			$infraction['displayDate'] 		 = GetDateBasedOnTimezone($infraction['date']);
			$infraction['expireDisplayDate'] = GetDateBasedOnTimezone($infraction['expiredate']);
		}

	}
}

/**
 * Portfolio info
 * 2022-03-02 13:48:25 - SE
 */
if ($ratingData['thumbup'] > 0)
{
	$portfolios 		= 1;
}

/**
 * Get achievements only if profile is logged in user.
 * 12/10/2018
 */
if ($uid == $__loggedUserDetails['USERID']) $achievements = GetAchivements($countAch=0, $countFollowers);
else
{
	/**
	 * Check and see if this seller has banned any users or vice verses
	 * 2022-01-07 18:14:35 - SE
	 */
	$iBlockedUser 		= userBannedFromOrder($uid, $__loggedUserDetails['USERID']);
}

/**
 * Get the time of the last delivery for the user.
 * 12/6/2018
 */
$lastDelivery = getLastDelivery($userData['USERID']);

if ($lastDelivery != false)
	$userData['lastDelivery'] = GetTimeAgo($lastDelivery);
else
	$userData['lastDelivery'] = false;

if ($uid == $__loggedUserDetails['USERID'])
	$header_sub_cat_active = 'public profile';

/**
 * Get our CSFR token
 */
$CSFR = GenerateCSFRCode();

/*
* Setup the data for the message modal popup
*/
$customModalData['about'] 				= $aboutid; // This is an ID which indicates what the message is about (IE: PID)
$customModalData['from'] 				= ''; // Where the user is coming from (IE: an order, WTT, WTB, etc)
$customModalData['recipient']			= $userData['USERID']; // optional, if there is a username
$customModalData['subject'] 			= ''; // optional
$customModalData['CSFR'] 				= $CSFR;
$customModalData['user'] 				= $userData;  // <- comes from conversations_new.php on redictect, user array/results from the database.
$customModalData['droplet'] 			= ''; // Droplet ID to reload
$customModalData['successMessage']		= $lang[3472];
$customModalData['status']				= 0;
$customModalData['title']				= $lang[2766];
$customModalData['username']			= $userData['username'];
$customModalData['img']					= $config['membersprofilepicurl'] . '/' . getProfileImageFromImage($userData['profilepicture']);
$customModalData['rating']				= $userData['rating'];
$customModalData['userType']			= $userLoggedStatusMain;

/*
* Setup the data for the message modal popup
*/
$newMessageModalData['about'] 				= $aboutid; // This is an ID which indicates what the message is about (IE: PID)
$newMessageModalData['from'] 				= ''; // Where the user is coming from (IE: an order, WTT, WTB, etc)
$newMessageModalData['recipientUserName']	= $userData['username']; // optional, if there is a username
$newMessageModalData['subject'] 			= ''; // optional
$newMessageModalData['CSFR'] 				= $CSFR;
$newMessageModalData['user'] 				= $userData;  // <- comes from conversations_new.php on redictect, user array/results from the database.
$newMessageModalData['droplet'] 			= ''; // Droplet ID to reload
$newMessageModalData['successMessage']		= $lang[2887];

/**
 * Include the language that we will need
 */
$config['include']['footerJs'] 			.= getLanguageForJS(array(3472, 3488, 2766, 3777, 3792, 3793, 3846, 3847, 3848, 3849, 3850));
$config['include']['includeUploadJs'] 	= 1;
$config['include']['tagsinput']			= 1;
$config['include']['photoswipe'] 		= 1;
$config['pagetitle'] 					= $pagetitle;

if (userNeedsCaptcha() && !isCaptchaValid() && intval($__loggedUserDetails['USERID']) > 0)
{
	$config['set_recaptcha'] 			= userNeedsCaptcha();
	$config['include']['doubleCaptcha'] = 1;
}

$config['include']['modals'][0]			= 'views/modal/view_modal-following.php';
$config['include']['modals'][1] 		= 'views/modal/view_modal-followers.php';
$config['include']['modals'][2] 		= 'views/modal/view_modal-start-message.php';
$config['include']['modals'][3] 		= 'views/modal/view_modal-custom-order.php';
$config['include']['modals'][4] 		= 'views/modal/view_modal-status.php';
$config['include']['modals'][5] 		= 'views/modal/view_modal-quick-look.php';

/**
 * Include the language that we will need
 * 2022-01-07 18:08:55 - SE
 */
$config['include']['footerJs'] .= getLanguageForJS(array(3846, 3847, 3848, 3849, 3850, 4293, 4294, 4296, 4295));

/**
 * If we're staff let's include our report modal
 */
if (isStaff())
{
	$reportComponentDroplet['type'] = 'profile';
	$reportComponentDroplet['url'] 	= 'fetch/report/profile';
	$config['include']['modals'][6] = 'views/modal/view_modal-report-droplet.php';
}

/*
* Include templates that we need, called in the footer-loader.php file.
*/
$__includeTemplates[0]['path']	= $config['basedir']  . '/views/js/autocomplete/__view-single.js.html';

/*
* Generate a JWT token for the socket server.
*
* Prefaced with __ so as not to conflict elsewhere.
*
* 10/18/2018
*/
$__socketParams = array(
	"type" => "profile",
	"acc" => array(),
	"ouid" => [intval($userData['USERID'])]
);

/**
 * Add meta description to the page
 *
 * 2023-06-09 05:28:23 JD
 */
$config['metadescription'] 	= $lang[1045] . ' ' . $userData['username'];

// If the user has a description, add it to the meta description
if (!empty($userData['description']))
{
	$config['metadescription'] .= ' - ' . trim(str_ireplace('"', '', substr(strip_tags(RemoveBbCode($userData['description'])), 0, 170)));
	$config['metadescription'] = preg_replace('/\s+/', ' ', $config['metadescription']);
}

$config['metakeywords'] 	= $userData['username'];

/**
 * Set the users footer code if they have any (which could be analytics)
 *
 * 5/17/2019
 */
if (!empty($userData['footer_code'])) $config['include']['footerJs'] .= $userData['footer_code'];

/*
 * A profile with no services, jobs or trades is an empty page to Google; hundreds
 * of thousands of them sit in "Crawled - currently not indexed". Keep those out
 * of the index so crawling goes to profiles that have something on them.
 * 2026-09-23
 */
if (intval($pageData['total']) == 0 && intval($pageDataWTB['total']) == 0 && intval($pageDataWTT['total']) == 0) $config['noindex'] = 1;

include 'views/header/view_header-loader.php';
include 'views/profile/view_profile.php';
include 'views/footer/view_footer-loader.php';

?>
