<?php

include('inc.php');

if(isset($_COOKIE['sessionToken'])) {
        $GLOBALS['user_data'] = getUserData($_COOKIE['sessionToken']);
}

// Cookie consent and Ads
$requiresGDPR = requiresGDPR(@$_SERVER['HTTP_CF_IPCOUNTRY']);
$requiresGDPR = false;

$requiresCookieConsent = $requiresGDPR && !(isset($_COOKIE['acceptedCookies']) || isset($_COOKIE['acceptedAllCookies']));
$doPersonalizedAds = false;
$doAnalytics = false;

if($requiresGDPR && isset($_COOKIE['acceptedCookies']) && $_COOKIE['acceptedCookies'] == false) {
        $approvedCookies = explode(',', $_COOKIE['acceptedAllCookies']);
        foreach($approvedCookies as $approvedCookie) {
                if($approvedCookie == 'personalized-ads') {
                        $doPersonalizedAds = true;
                }
                if($approvedCookie == 'analytics') {
                        $doAnalytics = true;
                }
        }
} else {
        $doPersonalizedAds = true;
        $doAnalytics = true;
}

$stats = json_decode(file_get_contents('stats.json'), true);
ob_start();

$page = 'default';
if (isset($_GET['page'])) {
	$page = $_GET['page'];
}

if(!isset($currentSub)) {
        $currentSub = 'all-stocks';
}

$rate = 1;
$currency = 'USD';
$currencyName = 'dollar';
$currencySymbol = '$';
$currencySymbolPosition = 'front';

$type = '';
switch ($page) {
	case 'methodology':
		header("HTTP/1.1 200 OK");
		include('pages/methodology.php');
	break;
	case 'api':
		header("HTTP/1.1 200 OK");
                include('pages/apiDoc.php');
        break;
        case 'details':
                include('pages/details.php');
        break;
        case 'stats':
                include('stats.php');
        break;
        case '404':
		header("HTTP/1.0 404 Not Found");
                include('pages/404.php');
        break;
        case 'sign-up':
                include('pages/sign-up.php');
        break;
        case 'account':
                include('pages/account.php');
        break;
        case 'password-reset':
                include('pages/password-reset.php');
        break;
        case 'forgot-password':
                include('pages/forgot-password.php');
        break;
        case 'privacy':
                include('pages/privacy.php');
        break;
	default:
		$pageNbr = 1;
		if(isset($_GET["page_nbr"])) {
        		$pageNbr = (int)$_GET["page_nbr"];
		} else {
        		$pageNbr = getCurrentPage();
		}

		$perPage = 100;
		$pageCount = ceil(getResCount($currentSub) / $perPage);

		if($page == 'watchlist') {
				if(!isLoggedIn()) {
					?>
					<div class="middle-header">
							<div class="alert error-alert">You must be logged in to see this page!</div>
							<div style="font-size: 65px; text-align:center; padding: 50px;">⛔</div>
					</div>
					<?php
				} else {
                        $topAll = getAssetBatch($pageNbr, @$GLOBALS['user_data']['watchlist']);
                        $resCount = getAssetBatchCount(@$GLOBALS['user_data']['watchlist']);
                        $pageCount = ceil($resCount / $perPage);
						include('pages/top100.php');
				}
		} else {
				$topAll = getTopAll($pageNbr, $currentSub);
				include('pages/top100.php');
		}
}

$pageContent = ob_get_contents();
ob_end_clean();
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title><?php echo $title ?></title>
<meta charset="utf-8"/>
<meta name="robots" content="INDEX,FOLLOW" />
<meta name="description" content="<?php echo $meta_description; ?>">
<meta http-equiv="content-language" content="en-us">
<meta property="og:title" content="<?php echo $title; ?>">
<meta property="og:type" content="website" />
<meta property="og:description" content="<?php echo $meta_description; ?>">
<meta property="og:image" content="https://apewisdom.io/apewisdom-media.png">
<?php
$urlPath = explode('?',$_SERVER['REQUEST_URI']);
$urlPath = str_replace('//','/',$urlPath[0]);
$urlPath = str_replace('//','/',$urlPath);
if(substr($urlPath, -1) != '/') {
        $urlPath = $urlPath . '/';
}
echo '<link rel="canonical" href="https://apewisdom.io' . $urlPath . '" />' . PHP_EOL;
echo '<meta property="og:url" content="https://apewisdom.io' . $urlPath . '" />';
?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="icon" type="image/png" href="/favicon.png">
<link rel="manifest" href="/site.webmanifest">
<link rel="stylesheet" type="text/css" href="/style.css?v=195">

<script>
function lightOn() {
        document.body.classList.remove('dark');
        document.cookie = 'darkmode=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
        document.getElementById('logo-img').src='/apewisdom-logo.svg?v=1';

        var assetLogos = document.querySelectorAll(".marketcap-table .company-logo");
        for (i = 0; i < assetLogos.length; i++) {
                if(assetLogos[i].hasAttribute("data-img-path")) {
                        assetLogos[i].src = assetLogos[i].getAttribute("data-img-path");
                }
        }
        return false;
}
function lightOff() {
        document.body.classList.add('dark');
        document.cookie = 'darkmode=1;  max-age=91536000000; path=/;';
        document.getElementById('logo-img').src='/apewisdom-logo-white.svg?v=1';

        var assetLogos = document.querySelectorAll(".marketcap-table .company-logo");
        for (i = 0; i < assetLogos.length; i++) {
                if(assetLogos[i].hasAttribute("data-img-dark-path")) {
                        assetLogos[i].src = assetLogos[i].getAttribute("data-img-dark-path");
                }
        }
        return false;
}
</script>

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9546025474036748"
     crossorigin="anonymous"></script>

</head>
<body class="cmkt<?php
if(isset($_COOKIE['darkmode']) && $_COOKIE['darkmode'] == '1') {
	echo ' dark';
}

if(isset($GLOBALS['user_data']) && $GLOBALS['user_data']['success']) {
        echo ' logged-in';
}
?>">

<?php if(1 == 0 && !isset($_COOKIE['sizzBanner'])) { ?>
<div class="header-banner"></div>
<script src="/banners/js/sizzling.js?v=17"></script>
<?php } ?>

	<div class="container pt-10px">
		<div class="header">
			<a href="/">
			<div class="logo">
<?php if(isset($_COOKIE['darkmode']) && $_COOKIE['darkmode'] == '1') { ?>
                                <img id="logo-img" src="/apewisdom-logo-white.svg" alt="ApeWisdom logo">
<?php } else { ?>
				<img id="logo-img" src="/apewisdom-logo.svg" alt="ApeWisdom logo">
<?php } ?>
				<div class="line1">APE</div>
				<div class="line2">Wisdom</div>
			</div>
			</a>
			<div class="navbar-toggler-container">
				<button id="navbar-toggler-btn" class="navbar-toggler" type="button" aria-label="Toggle navigation">
					<span class="navbar-toggler-icon"></span>
				</button>
			</div>
			<div class="right-options responsive850-hidden">

                                <?php if(isLoggedIn()) { ?>
                                <div class="option-item">
                                        <a class="option-link" href="/watchlist/"><img src="/fav.svg?v=3" style="vertical-align: bottom; padding-bottom: 3px;"> Watchlist</a>
                                </div>
                                <?php } ?>
				<!--<div class="option-item">
					<a class="option-link" href="/api/">Charts</a>
				</div>-->
				<div class="option-item">
					<a class="option-link" href="/api/">API</a>
				</div>
				<!--<div class="option-item">
					<a class="option-link" href="/api/">Data export</a>
				</div>-->
				<div class="option-item">
					<a class="option-link" href="/methodology/">Methodology</a>
				</div>

				<?php if(isLoggedIn()) { ?>
				<div class="option-item">
                                        <a class="option-link sign-in" href="/account/"><img alt="account icon" class="dark-hidden" src="/img/account.svg?v=1"><img alt="account icon" class="dark-shown" src="/img/account-dark.svg?v=1"> <span class="">Account</span></a>
				</div>
				<?php } else { ?>
				<div class="option-item">
                                        <a id="sign-in-button" class="option-link sign-in" href="#">
                                        	<img alt="Sign in icon" class="dark-hidden" src="/img/account.svg?v=1"><img alt="Sign in icon" class="dark-shown" src="/img/account-dark.svg?v=1"> Sign in
                                        </a>
				</div>
				<?php } ?>

				<div class="option-item night-button">
					<a href="#" class="option-link dark-hidden" onclick="lightOff()"  title="change to dark mode">
						<span>Dark mode &nbsp;</span>
						<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 70 1000 1000" width="18" height="18">
						<path fill="#444" stroke="#444" d="M525.3,989.5C241.2,989.5,10,758.3,10,474.1c0-196.8,109.6-373.6,285.9-461.4c7.9-3.9,17.5-2.4,23.7,3.8c6.2,6.2,7.9,15.8,4,23.7c-32.2,65.4-48.5,135.7-48.5,208.9c0,261.4,212.7,474.1,474.1,474.1c74,0,145-16.7,211-49.5c7.9-3.9,17.5-2.4,23.7,3.8c6.3,6.3,7.9,15.8,3.9,23.7C900.5,879,723.3,989.5,525.3,989.5z"></path>
						</svg>
					</a>
					<a href="#" class="option-link dark-shown" onclick="lightOn()" title="change to light mode">
						<span>Light mode &nbsp;</span>
						<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 10 220 220" width="18" height="18">
							<path fill="#fff" d="M120,189.697c-38.492,0-69.696-31.205-69.696-69.697S81.508,50.303,120,50.303c38.494,0,69.699,31.205,69.699,69.697 S158.494,189.697,120,189.697z M203.975,140L240,120l-36.025-20V140z M36.025,100L0,120l36.025,20V100z M120,240l20-36.025h-40 L120,240z M120,0l-20,36.025h40L120,0z M46.481,165.238l-11.333,39.615l39.616-11.33L46.481,165.238z M165.238,46.477l28.283,28.285 l11.332-39.613L165.238,46.477z M35.148,35.148L46.48,74.762l28.283-28.285L35.148,35.148z M165.238,193.523l39.615,11.33 l-11.332-39.615L165.238,193.523z"></path>
						</svg>
					</a>
				</div>

				<div class="search-container-small">
						<form method="POST" action="/search/" style="position:relative;">
						<div class="search-wrapper">
							<input value="" type="text" name="search" id="assetSearchInput" class="search" placeholder="Search" data-placeholder-small="Search" autocomplete="off">
							<button type="submit" id="btn-search" class="btn-search">
								<svg class="magnifying-glass" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 14 14"><g stroke-width="2"><path d="M11.29 11.71l-4-4"></path><circle cx="5" cy="5" r="4"></circle></g></svg>
								<svg class="clear-svg hidden" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 14 14"><g stroke-width="2"><path d="M1,1 L11,11 M1,11 L11,1"></path></g></svg>
							</button>
						<div class="search-results hidden" id="search-results">
						</div>
						</div>
						</form>
				</div>

			</div>

			<div class="asset-menu responsive850-hidden">
				<div class="item item-padding all<?php if($currentSub=='all-stocks') { echo ' active'; } ?>">
					<a href="/">Stocks <span class="badge badge-asset"><img alt="reddit icon" src="/img/reddit-icon-white.png"><?php echo formatCount($stats['sumStocks']); ?></span></a>
				</div>
				<div class="item item-padding cryptos<?php if($currentSub=='all-crypto') { echo ' active'; } ?>">
					<a href="/all-crypto/">Cryptos <span class="badge badge-crypto"><img alt="reddit icon" src="/img/reddit-icon-white.png"><?php echo formatCount($stats['sumCrypto']); ?></span></a>
				</div>
				<div class="item item-padding companies<?php if($currentSub=='all') { echo ' active'; } ?>">
                                        <a href="/all/">All <span class="badge badge-company"><img alt="reddit icon" src="/img/reddit-icon-white.png"><?php echo formatCount($stats['sumAll']); ?></span></a>
                                </div>
				<div class="item item-padding chan<?php if($currentSub=='4chan') { echo ' active'; } ?>">
                                        <a href="/4chan/">4chan <span class="badge badge-4chan"><img alt="4chan icon" src="/img/4chan-icon-white.png"><?php echo formatCount($stats['4chan']); ?></span></a>
                                </div>
			</div>
			<div class="asset-menu responsive850-hidden">
				<?php if($currentSub != 'all' && $currentSub != '4chan' && !empty($currentSub)) { ?>
				<div class="item item-padding" style="margin-right: 10px;">
					<span class="badge badge-filter">Subreddits:</span>
				</div>
				<?php } ?>
				<?php
					if(isCrypto($currentSub)) {
                                                echo makeItem('/CryptoCurrency/', 'r/CryptoCurrency', 'crypto', $stats['CryptoCurrency'], $currentSub);
                                                echo makeItem('/CryptoCurrencies/', 'r/CryptoCurrencies', 'crypto', $stats['CryptoCurrencies'], $currentSub);
                                                echo makeItem('/Bitcoin/', 'r/Bitcoin', 'crypto', $stats['Bitcoin'], $currentSub);
                                                echo makeItem('/SatoshiStreetBets/', 'r/SatoshiStreetBets', 'crypto', $stats['SatoshiStreetBets'], $currentSub);
                                                echo makeItem('/CryptoMoonShots/', 'r/CryptoMoonShots', 'crypto', $stats['CryptoMoonShots'], $currentSub);
                                                echo makeItem('/CryptoMarkets/', 'r/CryptoMarkets', 'crypto', $stats['CryptoMarkets'], $currentSub);
						echo makeItem('/ethtrader/', 'r/ethtrader', 'crypto', $stats['ethtrader'], $currentSub);
						echo makeItem('/ethereum/', 'r/ethereum', 'crypto', $stats['ethereum'], $currentSub);
					} else if($currentSub != 'all' && $currentSub != '4chan' && !empty($currentSub)) {
						echo makeItem('/wallstreetbets/', 'r/WSB', 'stocks', $stats['wallstreetbets'], $currentSub);
	                                        echo makeItem('/Wallstreetbetsnew/', 'r/WSBnew', 'stocks', $stats['Wallstreetbetsnew'], $currentSub);
	                                        echo makeItem('/WallStreetbetsELITE/', 'r/WSBElite', 'stocks', $stats['WallStreetbetsELITE'], $currentSub);
	                                        echo makeItem('/stocks/', 'r/stocks', 'stocks', $stats['stocks'], $currentSub);
						echo makeItem('/StockMarket/', 'r/StockMarket', 'stocks', $stats['StockMarket'], $currentSub);
	                                        echo makeItem('/investing/', 'r/investing', 'stocks', $stats['investing'], $currentSub);
	                                        echo makeItem('/SPACs/', 'r/SPACs', 'stocks', $stats['SPACs'], $currentSub);
	                                        echo makeItem('/options/', 'r/options', 'stocks', $stats['options'], $currentSub);
	                                        echo makeItem('/Daytrading/', 'r/Daytrading', 'stocks', $stats['Daytrading'], $currentSub);
						echo makeItem('/Shortsqueeze/', 'r/Shortsqueeze', 'stocks', $stats['Shortsqueeze'], $currentSub);
						echo makeItem('/SqueezePlays/', 'r/SqueezePlays', 'stocks', $stats['SqueezePlays'], $currentSub);
					}
				?>
			</div>
		</div>
		<?php echo $pageContent; ?>
	<div class="footer">
		<div class="container">
			<div class="row">
				<div class="col-sm2">
					<h4>What is ApeWisdom?</h4>
					<p>Apewisdom is a stock sentiment tracker that tracks the most popular stock and crypto boards on Reddit and 4Chan.</p>
					<p>ApeWisdom is not only a WSB tracker, it tracks many different discussion boards including:</p>
					<ul>
						<li>WallStreetBets (WSB)</li>
						<li>r/stocks</li>
						<li>r/investing</li>
						<li>4chan /biz</li>
						<li>and many more</li>
					</ul>
				</div>
				<div class="col-sm2">
					<h4>Learn more</h4>
					<p>We also run <a href="https://companiesmarketcap.com">Companies Market Cap</a>, a website that ranks companies by Market Cap, Earnings and Revenue.</p>
					<p>For inquiries: hel<span class="hidden">(nospam)</span>lo@8market<span class="hidden">(nospam)</span>cap.com</p>

					<h4>Privacy</h4>
					<p>To learn more read our <a href="/privacy/">Privacy-Policy</a>.</p>
				</div>
			</div>
		</div>
	</div>

	<div class="popup-overlay login-popup-overlay hidden"></div>
	<div class="popup-container hidden">
		<div class="popup login-popup">
		<div style="position:absolute; right: 20px;">
			<a href="#" class="close-popup"><span class="popup-close-icon"></span></a>
		</div>
		<div class="popup-title">Sign In</div>
		<div class="popup-body popup-greatings">
			<div id="login-error" class="login-error alert error-alert hidden"></div>
			<div style="margin-top: 15px; margin-bottom: 20px;">No account? &nbsp; <a href="/sign-up/"><span class="grey-button">Sign Up →</span></a></div>
			<div class="label"><label for="email">E-Mail</label></div>
			<div><input class="form-input" onkeydown="if (event.keyCode == 13) {login();}" placeholder="Your E-Mail Address" type="email" name="email" id="login-email"></div>
			<div class="label"><label for="password">Password</label></div>
			<div><input class="form-input" type="password" onkeydown="if (event.keyCode == 13) {login();}" name="password" id="login-password" placeholder="*********"></div>
			<div><a href="/account/forgot-password/">Forgot your Passwort?</a></div>
			<div class="popup-buttons">
					<button class="button-primary" onclick="login()">Log in</button>
			</div>

			<div class="separator">
				<div class="separator-text">OR</div>
			</div>
			<div class="popup-buttons">
				<a href="/google-login.php">
					<button class="button-secondary"><img src="/google-icon.svg"> Continue with Google</button>
				</a>
			</div>

		</div>
	</div>
	</div>
<?php if($requiresCookieConsent) { ?>
<div id="cookie-consent-container"></div>
<!-- <script src="/cookie-consent.js?v=3"></script> -->
<?php } ?>

	<?php if(isLoggedIn()) { ?>
	<script>window.csrfToken = '<?php echo $GLOBALS['user_data']['csrf_token']; ?>';</script>
	<?php } ?>

	<script src="/script.js?v=157"></script>
<?php if($page == 'default' || $page == 'watchlist' || is_numeric($page)) { ?>
	<script src="/tableScript.js?v=8"></script>
<?php } ?>
</body>
<script src="/clever_ads.js"></script>
<script>
<?php
	if(@$_SERVER['HTTP_CF_IPCOUNTRY'] !== 'IN'
                && @$_SERVER['HTTP_CF_IPCOUNTRY'] !== 'IQ'
                && @$_SERVER['HTTP_CF_IPCOUNTRY'] !== 'IR'
                && @$_SERVER['HTTP_CF_IPCOUNTRY'] !== 'BD'
                && @$_SERVER['HTTP_CF_IPCOUNTRY'] !== 'VN'
                && @$_SERVER['HTTP_CF_IPCOUNTRY'] !== 'EG'
                && @$_SERVER['HTTP_CF_IPCOUNTRY'] !== 'PK'
		&& 1 == 0
                ) {
                        echo 'const countryTier = 1;';
                } else {
                        echo 'const countryTier = 0;';
                }
?>
</script>

<script>
ubRecovered = false;
function recoveUB() {
        if(!ubRecovered) {
                ubRecovered = true;
                document.querySelectorAll('.recoverub-container').forEach(recoverContainer => {
                        recoverContainer.classList.remove("hidden");
                        <?php
                        if(isset($GLOBALS['advertisement_recovery_content_mi'])
                                //&& $GLOBALS['current_language'] == 'EN'
                                //&& isset($_SERVER['HTTP_CF_IPCOUNTRY'])
                                //&& in_array($_SERVER['HTTP_CF_IPCOUNTRY'], ['US', 'CA'])
                        ) {
                                // Use json_encode for safe embedding and return to skip iteration

                                echo '  recoverContainer.innerHTML = ' . json_encode($GLOBALS['advertisement_recovery_content_mi']) . ';' . PHP_EOL;
                                echo '  return;' . PHP_EOL; // Use return to skip the current forEach iteration
                        }
                        ?>
						recoverContainer.innerHTML = '<br/>Ad<span class="responsive-hidden">vertisement</span>: <a rel="sponsored nofollow" class="text-underline" href="https://coinwebsocket.com/"><strong>CoinWebSocket</strong> – Real-time Bitcoin price spread comparison tool</a><br/><br/>';
			});
        }
}

<?php
if(isset($GLOBALS['advertisement_recovery_content_mi'])
        //&& $GLOBALS['current_language'] == 'EN'
        //&& isset($_SERVER['HTTP_CF_IPCOUNTRY'])
        //&& in_array($_SERVER['HTTP_CF_IPCOUNTRY'], ['US', 'CA'])
) {
        echo $GLOBALS['advertisement_recovery_content_mi_script']. PHP_EOL;
}
?>

var ub0802dwds = 1;
if(document.getElementById('Sssa9sanbOsnbq723')){
        ub0802dwds = 0;
} else {
        recoveUB();
}

(function detectUB(callback) {
  var flaggedURL = 'https://static.getclicky.com/js';

        var request = new Request(flaggedURL, {
        method: 'GET',
        mode: 'no-cors',
        });
        fetch(request)
        .then(function(response) {
        if (response.status === 200 ) {
                callback(false);
        }
        })
        .catch(function(error) {
                callback(true);
        });
        })(function(usingAdblock) {
                if(usingAdblock) {
                        ub0802dwds = 2;
                        recoveUB();
                        console.log('using adblock');
                }
        })

	function ae6dd7anadbac(siteID) {
		var uuid = '';
		try {
			if(localStorage.getItem("UUID-ae6dd7anadbac") == undefined) {
				localStorage.setItem("UUID-ae6dd7anadbac", window.crypto.randomUUID());
			}

			uuid = localStorage.getItem("UUID-ae6dd7anadbac");
		} catch(error) {}

		var timeOffset = '';
		try {
			timeOffset = new Date().getTimezoneOffset()
		} catch(error) {}

		var userLang = ''; 
		try {
			userLang = navigator.language || navigator.userLanguage; 
		} catch(error) {}

		var payload = {
			"siteID" : siteID,
			"uuid" : uuid,
			"referrer" : document.referrer,
			"url" : window.location.href,
			"screen_height": window.screen.height,
			"screen_width": window.screen.width,
			"timeOffset": timeOffset,
			"userLang": userLang,
			"blocker" : ub0802dwds
		};

		fetch("https://apewisdom.io/c/", {
			method: "POST",
			body: JSON.stringify(payload),
			headers: {
				"Content-type": "application/json; charset=UTF-8"
			}
		});
	}

	setTimeout("ae6dd7anadbac('APE')", 625);
</script>
</html>
