<?php
require 'paragonie/autoload.php';
use ParagonIE\Paseto\Builder;
use ParagonIE\Paseto\Purpose;
use ParagonIE\Paseto\Keys\SymmetricKey;
use ParagonIE\Paseto\Protocol\Version2;

include("core/HTMLMinify.smarty.php");
include("core/rs.php");
include("inc_taalkeuze.php");
include("inc_tools.php");


// put full path to Smarty.class.php
require('plugins/Smarty3.1.16/libs/Smarty.class.php');
$smarty = new Smarty();

$smarty->setTemplateDir('/var/www/www.anderlecht-online.be/smarty/templates');
$smarty->setCompileDir('/var/www/www.anderlecht-online.be/smarty/templates_c');
$smarty->setCacheDir('/var/www/www.anderlecht-online.be/smarty/cache');
$smarty->setConfigDir('/var/www/www.anderlecht-online.be/smarty/configs');

include("inc_mobileapp.php");
include("inc_session.php");

$smarty->assign('lang', $_lang);

include("core/rightNavGeneric.php");

/** Recent nieuws **/
$recenteitems = callRS('/nieuws/' . $_lang . '/hometitles?select=newsid,date,titel&limit=0,15&orderBy=date_desc');
//echo "<pre>"; print_r($recenteitems); echo "</pre>"; 
if ($mobileapp==1) { 
	for ($z=0; $z<count($recenteitems); $z++) {
		$artikelrecent = callRS('/nieuws/' . $_lang . '/' . $recenteitems[$z][0] . '?select=inl,foto');
		//echo "<pre>"; print_r($artikelrecent); echo "</pre>";
		$recenteitems[$z][3] = strip_tags(splitKeepWordsReplace($artikelrecent[0][0]));
		$recenteitems[$z][4] = $artikelrecent[0][1];
	}
}
$smarty->assign('recenteitems',$recenteitems);


/** Artikel **/
if (is_numeric($_GET['id']) && $_GET['id']!=NULL && $_GET['id']!='') { $id=$_GET['id']; } else { $id=0; }
$artikel = callRS('/nieuws/' . $_lang . '/' . $id . '?select=newsid,date,titel,inl,tekst,foto,poster,lead,bron1,link1,bron2,link2,bron3,link3,auteur1,auteur2,auteur3,unibettxt,unibetend,id');
//print_r($artikel);

$datetime = new DateTime(date("Y-m-d H:i:s", $artikel[0][1]));
$dateInISO = $datetime->format(DateTime::ISO8601);
$smarty->assign('dateISO',$dateInISO);

$all = trim(fixTags(str_replace(chr( 194 ) . chr( 160 ), ' ', html_entity_decode($artikel[0][3],ENT_COMPAT|ENT_HTML5,"UTF-8")))) . " " . trim(fixTags(str_replace(chr( 194 ) . chr( 160 ), ' ', html_entity_decode($artikel[0][4],ENT_COMPAT|ENT_HTML5,"UTF-8"))));
$smarty->assign('all',$all);


/* broken link fixer */
$inl = $artikel[0][3];
$tekst = $artikel[0][4];

if (stripos ($inl, 'href=') !== false) {
	$inl = str_replace ("&quot;", "\"", $inl);
	$inl = str_replace ("&#39;", "'", $inl);
	$inl = str_replace ("&lt;", "<", $inl);
	$inl = str_replace ("&gt;", ">", $inl);	
	$inl = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http|https)([^\"'>]+)([\"'>]+)#", '$1https://www.anderlecht-online.be/$2$3', $inl);
}
if (stripos ($tekst, 'href=') !== false) {
	$tekst = str_replace ("&quot;", "\"", $tekst);
	$tekst = str_replace ("&#39;", "'", $tekst);
	$tekst = str_replace ("&lt;", "<", $tekst);
	$tekst = str_replace ("&gt;", ">", $tekst);
	$tekst = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http|https)([^\"'>]+)([\"'>]+)#", '$1https://www.anderlecht-online.be/$2$3', $tekst);
}


//Split article in parts for inArticleAds when necessary (in tpl file > mobile only)
//Also fix linebreaks & spaces at the end -> first remove obstructing line breaks, then replace - repeat in case order was different.
$tekst = trim($tekst);
$tekst = preg_replace("/\r|\n/", "", $tekst);

//start replacing first time
$tekst = preg_replace('/^&amp;nbsp;$/', '', $tekst);
$tekst = preg_replace('/^&nbsp;$/', '', $tekst);
$tekst = preg_replace('/^<br>$/', '', $tekst);
$tekst = preg_replace('/^<br \/>$/', '', $tekst);
$tekst = preg_replace('/^<br\/>$/', '', $tekst);
$tekst = preg_replace('/^&lt;br&gt;$/', '', $tekst);
$tekst = preg_replace('/^&lt;br \/&gt;$/', '', $tekst);
$tekst = preg_replace('/^&lt;br\/&gt;$/', '', $tekst);
$tekst = preg_replace('/^<p>&nbsp;<\/p>$/', '', $tekst);
$tekst = preg_replace('/^&lt;p&gt;&nbsp;&lt;\/p&gt;$/', '', $tekst);
$tekst = preg_replace('/^<p> <\/p>$/', '', $tekst);
$tekst = preg_replace('/^&lt;p&gt; &lt;\/p&gt;$/', '', $tekst);
//repeat, as the order may have been different
$tekst = preg_replace('/^&amp;nbsp;$/', '', $tekst);
$tekst = preg_replace('/^&nbsp;$/', '', $tekst);
$tekst = preg_replace('/^<br>$/', '', $tekst);
$tekst = preg_replace('/^<br \/>$/', '', $tekst);
$tekst = preg_replace('/^<br\/>$/', '', $tekst);
$tekst = preg_replace('/^&lt;br&gt;$/', '', $tekst);
$tekst = preg_replace('/^&lt;br \/&gt;$/', '', $tekst);
$tekst = preg_replace('/^&lt;br\/&gt;$/', '', $tekst);
$tekst = preg_replace('/^<p>&nbsp;<\/p>$/', '', $tekst);
$tekst = preg_replace('/^&lt;p&gt;&nbsp;&lt;\/p&gt;$/', '', $tekst);
$tekst = preg_replace('/^<p> <\/p>$/', '', $tekst);
$tekst = preg_replace('/^&lt;p&gt; &lt;\/p&gt;$/', '', $tekst);

$longart = fixTags(trim(str_replace(chr( 194 ) . chr( 160 ), ' ', html_entity_decode($tekst,ENT_COMPAT|ENT_HTML5,"UTF-8"))));
$longint = fixTags(trim(str_replace(chr( 194 ) . chr( 160 ), ' ', html_entity_decode($tekst,ENT_COMPAT|ENT_HTML5,"UTF-8"))));
$longtext = preg_replace("/\r|\n/", "", $longint) . "<br><br>" . preg_replace("/\r|\n/", "", $longart);
$parts = explode("<br><br>",preg_replace("/\r|\n/", "", $longart));

if ($tekst!=null && $tekst!='' && str_word_count ($tekst) > 10 && str_word_count ($longtext) > 120 && $parts>2) {
	$newlongart1="";
	$newlongart2="";
	for ($w=0; $w<count($parts); $w++){
		if ($w<1) {
			//first part of the article 
			$newlongart1 = $newlongart1. $parts[$w] . '<br><br>';
		} else {
			//second part of the article
			$newlongart2 = $newlongart2 . $parts[$w] . '<br><br>';
		}
	}
	
	$smarty->assign('tekst1', $newlongart1);
	$smarty->assign('tekst2', $newlongart2);
	$smarty->assign('wordcount', str_word_count ($longtext)); 
} else {
	$smarty->assign('tekst1',fixTags(trim(str_replace(chr( 194 ) . chr( 160 ), ' ', html_entity_decode($tekst,ENT_COMPAT|ENT_HTML5,"UTF-8")))));
	$smarty->assign('tekst2', '');
	$smarty->assign('wordcount', '0');
}
//End split

//Fix space encoding problem from webservice, in this order!
$inl = fixTags($inl);
$inl = trim(str_replace( chr( 194 ) . chr( 160 ), ' ', $inl ));
$inl = html_entity_decode($inl,ENT_COMPAT|ENT_HTML5,"UTF-8");


if ($mobileapp=='1') {
    $mapnaam = date('Y-m', $artikel[0][1]);
	$bestand = '/var/www/www.anderlecht-online.be/admin/cron/newsvideo/' . $mapnaam . '/' . $artikel[0][0] . '.mp4';
    $newsvideo = file_exists($bestand) && filesize($bestand) > 0;
} 

if ($mobileapp=='1' && $newsvideo==true) {
	$smarty->assign('newsvideo','1');
	$smarty->assign('newsfolder',$mapnaam);
}
else {
	$smarty->assign('newsvideo','0');
}

/***********************************
* Newstags
***********************************/
if ($artikel != null && $artikel != 0) {
	$newstags = callRS('/nieuws/' . $_lang . '/tags/' . $artikel[0][19] . '?select=score,occurrences,tid&orderBy=score_desc&limit=0,3');
	//echo "<pre>"; print_r($newstags); echo "</pre>";

	for ($z=1; $z<=count($newstags); $z++){
		if ($newstags[$z][0]==100 && $newstags[$z][1]==100) {}
		else {
			unset($newstags[$z]);
		}
	}
	
	$metatags = array();
	$x=0;
	for ($z=0; $z<count($newstags); $z++){ 
		if ($_lang==="nl") { $metatags[$x] = $newstags[$z][2]['tagNL']; }
		if ($_lang==="fr") { $metatags[$x] = $newstags[$z][2]['tagFR']; }
		if ($_lang==="en") { $metatags[$x] = $newstags[$z][2]['tagEN']; }
		if ($_lang==="de") { $metatags[$x] = $newstags[$z][2]['tagDE']; }
		if ($_lang==="es") { $metatags[$x] = $newstags[$z][2]['tagES']; }
		$x++;
	}
}

//echo "<pre>"; print_r($newstags); echo "</pre>";
//echo "<pre>"; print_r($metatags); echo "</pre>";


/***********************************
* Assign all variables
***********************************/
$smarty->assign('newsid',$artikel[0][0]);
$smarty->assign('datum',printDateTime($artikel[0][1],$_lang));
$smarty->assign('timestamp',$artikel[0][1]);
$smarty->assign('nu',time()-31556926);
$smarty->assign('titel',$artikel[0][2]);
$smarty->assign('metasubtitle',$artikel[0][2]);
$smarty->assign('metamonth',date("m", $artikel[0][1]));
$smarty->assign('metayear',date("y", $artikel[0][1]));
$smarty->assign('metatags',$metatags);
$smarty->assign('inl',$inl);
//$smarty->assign('tekst',fixTags(trim(html_entity_decode($tekst,ENT_COMPAT|ENT_HTML5,"UTF-8")))); //comment out when InArticle ads activated
$smarty->assign('foto',hasWebpVersion($artikel[0][5]));
$smarty->assign('foto_large',str_replace ('_small', '', hasWebpVersion($artikel[0][5])));
$smarty->assign('poster',$artikel[0][6]['poster']);
$smarty->assign('lead',$artikel[0][7]);
$smarty->assign('bron1',$artikel[0][8]);
$smarty->assign('link1',$artikel[0][9]);
$smarty->assign('bron2',$artikel[0][10]);
$smarty->assign('link2',$artikel[0][11]);
$smarty->assign('bron3',$artikel[0][12]);
$smarty->assign('link3',$artikel[0][13]);
$smarty->assign('auteur1',$artikel[0][14]);
$smarty->assign('auteur2',$artikel[0][15]);
$smarty->assign('auteur3',$artikel[0][16]);
$smarty->assign('unibettxt',html_entity_decode($artikel[0][17],ENT_COMPAT|ENT_HTML5,"UTF-8"));
$smarty->assign('unibetend',html_entity_decode($artikel[0][18],ENT_COMPAT|ENT_HTML5,"UTF-8"));
$smarty->assign('alt', trim(determineAlt($artikel[0][5])));
$smarty->assign('newstags', $newstags);

if ($_lang=='nl') {
	$smarty->assign('metatitle', $artikel[0][2] . ' (' . printDateShort($artikel[0][1],$_lang) . ')');
	$smarty->assign('metatitleOG', str_replace('"', '\'', $artikel[0][2]));
	//$smarty->assign('metadescription', strip_tags(str_replace("'", "\'", $artikel[0][3])));
	$smarty->assign('metadescription', strip_tags(splitKeepWordsReplace($artikel[0][3])));
}
if ($_lang=='en') {
	$smarty->assign('metatitle', $artikel[0][2] . ' (' . printDateShort($artikel[0][1],$_lang) . ')');
	$smarty->assign('metatitleOG', str_replace('"', '\'', $artikel[0][2]));
	//$smarty->assign('metadescription', strip_tags(str_replace("'", "\'", $artikel[0][3])));
	$smarty->assign('metadescription', strip_tags(splitKeepWordsReplace($artikel[0][3])));
}
if ($_lang=='fr') {
	$smarty->assign('metatitle', $artikel[0][2] . ' (' . printDateShort($artikel[0][1],$_lang) . ')');
	$smarty->assign('metatitleOG', str_replace('"', '\'', $artikel[0][2]));
	//$smarty->assign('metadescription', strip_tags(str_replace("'", "\'", $artikel[0][3])));
	$smarty->assign('metadescription', strip_tags(splitKeepWordsReplace($artikel[0][3])));
}
if ($_lang=='de') {
	$smarty->assign('metatitle', $artikel[0][2] . ' (' . printDateShort($artikel[0][1],$_lang) . ')');
	$smarty->assign('metatitleOG', str_replace('"', '\'', $artikel[0][2]));
	//$smarty->assign('metadescription', strip_tags(str_replace("'", "\'", $artikel[0][3])));
	$smarty->assign('metadescription', strip_tags(splitKeepWordsReplace($artikel[0][3])));
}
if ($_lang=='es') {
	$smarty->assign('metatitle',  $artikel[0][2] . ' (' . printDateShort($artikel[0][1],$_lang) . ')');
	$smarty->assign('metatitleOG', str_replace('"', '\'', $artikel[0][2]));
	//$smarty->assign('metadescription', strip_tags(str_replace("'", "\'", $artikel[0][3])));
	$smarty->assign('metadescription', strip_tags(splitKeepWordsReplace($artikel[0][3])));
}


/***********************************
* TalkYard
***********************************/
$talkyardKey = "hex:e6507740d188260c38363f000be987dd1c448dca6c5089456f07ca6aea1cee35";
$pasetoV2LocalSecretNoHexPrefix = preg_replace('/^hex:/', '', $talkyardKey);

$sharedSecretKeyBytes = hex2bin($pasetoV2LocalSecretNoHexPrefix);

// Deel de geheime sleutel
$sharedSecretKey = new SymmetricKey($sharedSecretKeyBytes, new Version2());
// Authenticeringsbericht omgezet naar JSON-stringi
$authnMessage = $_SESSION['authnMessage'];

if($authnMessage != ''){
	//$messageAsString = json_encode($authnMessage);
	$authnMessageArr = json_decode($authnMessage, true);

	// Genereer het PASETO-token
	$token = (new Builder())
    		->setKey($sharedSecretKey)
    		->setVersion(new Version2())
    		->setPurpose(Purpose::local())
    		->setClaims($authnMessageArr);

	$token = 'paseto:' . $token;
} else {
	$token = '';
}

$smarty->assign('TalkyardToken', $token);

/***********************************
* USER IS LOGGED IN (change ads)
***********************************/
$token = $_SESSION['token'];
$ip = getUserIP();

$post_data = array(
	'ip' => $ip,
	'token' => $token		
);

$posted = postRS('/security/isLoggedIn', $post_data);

if ($posted == '1') {
	$smarty->assign('userLoggedIn', '1');
} else {
	$smarty->assign('userLoggedIn', '0');
}

/***************************************
* Display different username in office hrs
***************************************/
//Office hours or not?
$dag = date('D',$artikel[0][1]);
$uur = date('H',$artikel[0][1]);

$status = 'free';
if ($dag != 'Sat' && $dag != 'Sun'){
	if ($uur > 07 && $uur <= 16) {
		$status = 'business';
	}
}
if ($dag == 'Fri' || $dag == 'Sat' || $dag == 'Sun'){
	if ($uur > 18 && $uur <= 23) {
		$status = 'weekendnight';
	}
}

$smarty->assign('whattime', $status);


/*******************************************
* Adblocks, spiders, crawlers, ...
* Honeypot & Recaptcha v3
*******************************************/

//Browser detect, firefox blocks ads
$smarty->assign('browser',$_SERVER['HTTP_USER_AGENT']);

//Honeypot
include("core/rsps.php");

$host = gethostbyaddr($ip);
$query = $_SERVER['QUERY_STRING'];
$referer = $_SERVER['HTTP_REFERER'];
$useragent = $_SERVER['HTTP_USER_AGENT'];

//echo $useragent;
$honeypot = callRSPS('/honeypot');
//echo "<pre>"; print_r($honeypot); echo "</pre>";
$reason='';

for ($hp=0; $hp<count($honeypot); $hp++) {
	if ($ip==$honeypot[$hp]['ip']) { $smarty->assign('robot','YES'); $reason="ip->" . $honeypot[$hp]['id']; break; } //If IP is in honeypot, mark as robot
	if ($host==$honeypot[$hp]['hostByIP']) { $smarty->assign('robot','YES'); $reason="hostbyip->" . $honeypot[$hp]['id']; break; } //If hostname is in honeypot, mark as robot
	if (!is_null($honeypot[$hp]['userAgent']) && stripos ($useragent, $honeypot[$hp]['userAgent']) !== false) { $smarty->assign('robot','YES'); $reason="useragent->" . $honeypot[$hp]['id']; break; } //If suspicious parts are in the user agent, mark as robot
	if (!is_null($honeypot[$hp]['browser']) && stripos ($useragent, $honeypot[$hp]['browser']) !== false) { $smarty->assign('robot','YES'); $reason="browser->" . $honeypot[$hp]['id']; break; } //If suspicious parts are in the user agent, mark as robot
	if (!is_null($honeypot[$hp]['crawler']) && stripos ($useragent, $honeypot[$hp]['crawler']) !== false) { $smarty->assign('robot','YES'); $reason="crawler->" . $honeypot[$hp]['id']; break; } //If suspicious parts are in the user agent, mark as robot
	if (!is_null($honeypot[$hp]['stripper']) && stripos ($useragent, $honeypot[$hp]['stripper']) !== false) { $smarty->assign('robot','YES'); $reason="stripper->" . $honeypot[$hp]['id']; break; } //If suspicious parts are in the user agent, mark as robot
	if (!is_null($honeypot[$hp]['platform']) && stripos ($useragent, $honeypot[$hp]['platform']) !== false) { $smarty->assign('robot','YES'); $reason="platform->" . $honeypot[$hp]['id']; break; } //If suspicious parts are in the user agent, mark as robot
	if (!is_null($honeypot[$hp]['referer']) && stripos ($referer, $honeypot[$hp]['referer']) !== false) { $smarty->assign('robot','YES'); $reason="referer->" . $honeypot[$hp]['id']; break; } //If suspicious parts are in the referer, mark as robot
	if (!is_null($honeypot[$hp]['queryString']) && $honeypot[$hp]['queryString']!=='id=203069&lang=ned' && $honeypot[$hp]['queryString']!=='lang=ned' && $honeypot[$hp]['queryString']!=='lang=fra' && $honeypot[$hp]['queryString']!=='lang=eng' && $honeypot[$hp]['queryString']!=='lang=dui' && $honeypot[$hp]['queryString']!=='lang=esp') {
		if (stripos ($query, $honeypot[$hp]['queryString']) !== false) { $smarty->assign('robot','YES'); $reason="querystring->" . $honeypot[$hp]['id']; break; } //If suspicious parts are in the query string, mark as robot
	}
}
//echo $reason;

//Good bots list  
$bot_list = array( 
	'Googlebot', 'Mediapartners-Google', 'APIs-Google', 'FeedFetcher-Google','Google-Read', 'DuplexWeb-Google', 'Google Favicon', 'AdsBot-Google', 'googleweblight' , 'Storebot-Google',
	'bingbot', 'MSNbot', 'bingpreview', 'AdIdxBot', 'Applebot',
	'Baiduspider', 'Yandex', 'YaDirectFetcher', 'exabot',
	'Sogou web spider', 'Slurp', 'DuckDuckBot', 'ia_archiver', 'aolbuild', 'teoma', 
	'facebookexternalhit', 'facebook', 'facebot', 'Twitterbot', 'pinterestbot',
	'CriteoBot', 'outbrain'
); 

foreach($bot_list as $bl) { 
	if( stripos( $useragent, $bl ) !== false ) {
		$smarty->assign('searchengine','YES');
	}
} 


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cf-turnstile-response'])) {
    $secret = '0x4AAAAAAA9TwiZlwr2Sh-yGZHagbzkLNyk';
    $response = $_POST['cf-turnstile-response'];
    $remoteip = $_SERVER['REMOTE_ADDR'];

    $url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
    $data = array(
        'secret' => $secret,
        'response' => $response,
        'remoteip' => $remoteip
    );

    $options = array(
        'http' => array(
            'header' => "Content-type: application/x-www-form-urlencoded\r\n",
            'method' => 'POST',
            'content' => http_build_query($data)
        )
    );

    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    $json_result = json_decode($result);

    header('Content-Type: application/json');
    echo json_encode(['success' => $json_result->success]);
	exit;
	//This is de Ajax call processing and should end with exit. You cannot render stuff on screen after this call. It's only executed on the Turnstile validation though.
}



/***********************************
* Related news article
***********************************/
//if (count($newstags)==1) {
	//we have one tag, good for related news; now find a match on player name for example
	preg_match_all('/\b[A-Z][a-zA-Z]{4,}\b/u', $artikel[0][2], $matches);
	$woorden = $matches[0]; 
	//array_shift($woorden);	//first match
	reset($recenteitems);
	
	/*
	for ($z=0; $z<count($recenteitems); $z++) {
		if ((strpos($recenteitems[$z][2],$woorden[0]) !== false) && ($artikel[0][0] !== $recenteitems[$z][0])) {
			$relatedTitle = $recenteitems[$z][2];
			$relatedId = $recenteitems[$z][0];
			$relatedDate = $recenteitems[$z][1];
			
			$smarty->assign('relatedTitle',$relatedTitle);
			$smarty->assign('relatedId',$relatedId);
			$smarty->assign('relatedDate',printDateTime($relatedDate,$_lang));
			break;
		}
	}
	*/
	
	for ($z=0; $z<count($recenteitems); $z++) {
		for ($w=0; $w<count($woorden); $w++) {
			if ((strpos($recenteitems[$z][2],$woorden[$w]) !== false) && ($artikel[0][0] !== $recenteitems[$z][0]) && $woorden[$w]!=='RSCA' && $woorden[$w]!=='Anderlecht') { 
			
				$relatedTitle = $recenteitems[$z][2];
				$relatedId = $recenteitems[$z][0];
				$relatedDate = $recenteitems[$z][1];
				
				$smarty->assign('relatedTitle',$relatedTitle);
				$smarty->assign('relatedId',$relatedId);
				$smarty->assign('relatedDate',printDateTime($relatedDate,$_lang));
				$found = true;
				break;			
			}
			
		}
		if ($found) {
			break; // Verlaat de buitenste lus
		}		
	}	
	
	
//}

$smarty->registerPlugin("function", "hasWebpVersion", "hasWebpVersion");

$smarty->registerFilter("output", "minify_html");
$smarty->display('article.tpl');

?>
