<?php
require_once('includes/config.php');

$id = isset($_GET['id']) ? $_GET['id'] : NULL;
//$id = html($_GET['id']);

$stmt = $db->prepare('SELECT postID,postHash,postTitle,postSlug,postAuthor,postLink,postDesc,postCont,postTaille,postDate,postTorrent,postImage FROM blog_posts_seo WHERE postSlug = :postSlug');
$stmt->bindValue(':postSlug', $id, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch();

//Si le torrent est à supprimer ...
if(isset($_GET['deltorr'])) {

	$deltorr = (int) $_GET['deltorr'];

	if(isset($_SESSION['username']) && isset($_SESSION['userid'])) {

        	if(($row['postAuthor'] == $_SESSION['username']) || ($_SESSION['userid'] == 1)) {

        		// 1 - on supprime le fichier .torrent dans le répertoire /torrents
        		$stmt4 = $db->prepare('SELECT postID,postTorrent FROM blog_posts_seo WHERE postID = :postID') ;
			$stmt4->bindValue(':postID', $deltorr, PDO::PARAM_INT);
        		$stmt4->execute();
        		$efface = $stmt4->fetch();

        		$file = $REP_TORRENTS.$efface['postTorrent'];
        		if (file_exists($file)) {
                		unlink($file);
        		}

        		// 2 - on supprime le torrent dans la base blog_posts_seo
        		$stmt = $db->prepare('DELETE FROM blog_posts_seo WHERE postID = :postID') ;
			$stmt->bindValue(':postID', $deltorr, PDO::PARAM_INT);
        		$stmt->execute();

        		// 3 - on supprime sa référence de catégorie
        		$stmt1 = $db->prepare('DELETE FROM blog_post_cats WHERE postID = :postID');
			$stmt1->bindValue(':postID', $deltorr, PDO::PARAM_INT);
        		$stmt1->execute();

        		// 4 - on supprime sa référence de licence
        		$stmt2 = $db->prepare('DELETE FROM blog_post_licences WHERE postID_BPL = :postID_BPL');
			$stmt2->bindValue(':postID_BPL', $deltorr, PDO::PARAM_INT);
        		$stmt2->execute();

			/*
        		// 5 - on supprime ses commentaires s'ils existent
        		$stmt22 = $db->prepare('SELECT cid_torrent FROM blog_posts_comments WHERE cid_torrent = :cid_torrent');
			$stmt22->bindValue(':cid_torrent', $deltorr, PDO::PARAM_INT);
        		$stmt22->execute();
        		$commentaire = $stmt22->fetch();

        		if(!empty($commentaire)) {
                		$stmtsupcomm = $db->prepare('DELETE FROM blog_posts_comments WHERE cid_torrent = :cid_torrent');
				$stmtsupcomm->bindValue(':cid_torrent', $deltorr, PDO::PARAM_INT);
                		$stmtsupcomm->execute();
        		}
			*/

        		// 6 - enfin, on supprime le torrent du tracker en mettant le champ "flag" à "1" dans l'enregistrement correspondant de la table xbt_files
        		$stmt3 = $db->prepare('UPDATE xbt_files SET flags = :flags WHERE fid = :fid') ;
			$stmt3->bindValue(':flags', '1', PDO::PARAM_INT);
			$stmt3->bindValue(':fid', $deltorr, PDO::PARAM_INT);
        		$stmt3->execute();

        		header('Location: torrents.php?action=supprime');
        		//exit;

		}

		else {
			// Alors comme ça vous n'avez pas le droit de supprimer ce torrent ?!!
			header('Location: '. SITEURL);
                        exit();
		}

	}

}//fin de if isset $_GET['deltorr']

/*
$id = html($_GET['id']);

$stmt = $db->prepare('SELECT postID,postHash,postTitle,postSlug,postAuthor,postLink,postDesc,postCont,postTaille,postDate,postTorrent,postImage FROM blog_posts_seo WHERE postSlug = :postSlug');
$stmt->bindValue(':postSlug', $id, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch();
*/

//Si le post n'existe pas on redirige l'utilisateur
if($row['postID'] == ''){
        header('Location: ./');
        exit();
}

$pagetitle = html($row['postTitle']);

//Stats : bbclone
define("_BBC_PAGE_NAME", $pagetitle);
define("_BBCLONE_DIR", "bbclone/");
define("COUNTER", _BBCLONE_DIR."mark_page.php");
if (is_readable(COUNTER)) include_once(COUNTER);

include_once('includes/header.php');
?>

<body>
<div id="container">

        <?php
	   include_once('includes/header-logo.php');
           include_once('includes/nav.php');
        ?>

    	<div id="body">
			<div id="content">

			<?php include_once('includes/ariane.php'); ?>	

			<br />

				<div class="post">

		                        <?php
					echo '<div class="title"';
                                        	echo '<span style="font-size: 22px; font-weight: bold;">'.html($row['postTitle']).'</span>';
						
						/*
						if(isset($_SESSION['username']) && isset($_SESSION['userid'])) {
							if(($row['postAuthor'] == $_SESSION['username']) || ($_SESSION['userid'] == 1)) {
                                        			echo '<a style="text-decoration: none; padding-left: 100px;" href="admin/edit-post.php?id='.html($row['postID']).'"><input type="button" class="button" value="Editer" /></a>';
								?>
								<a style="text-decoration: none;" href="javascript:deltorr('<?php echo html($row['postID']); ?>','<?php echo html($row['postTitle']); ?>')"><input type="button" class="button" value="Supp." /></a>
								<?php
                                        		}
						}
						*/

						echo '<div class="viewpostcadre" style="background-color: #FFFFCC; font-size: 10px; width: 250px;">';
						echo '<span style="font-weight: bold; font-size: 18px;">Télécharger :</span> <a href="admin/download.php?id='.html($row['postID']).'">&nbsp;<img src="images/download-2-icon.png" alt="Download" /></a><br />';
						echo '&rsaquo; <span style="text-decoration: underline;">Posté le</span> : '.date_fr('d-m-Y à H:i:s', strtotime($row['postDate'])).'<br />';
						echo '&rsaquo; <span style="text-decoration: underline;">Par</span> : <a href="'.SITEURL.'/admin/profil.php?membre='.html($row['postAuthor']).'">'.html($row['postAuthor']).'</a><br />';
						echo '&rsaquo; <span style="text-decoration: underline;">Dans</span> : ';
							$stmt2 = $db->prepare('SELECT catTitle, catSlug FROM blog_cats, blog_post_cats WHERE blog_cats.catID = blog_post_cats.catID AND blog_post_cats.postID = :postID ORDER BY catTitle ASC');
							$stmt2->bindValue(':postID', $row['postID'], PDO::PARAM_INT);
							$stmt2->execute();
							$catRow = $stmt2->fetchAll(PDO::FETCH_ASSOC);
							$links = array();
							foreach ($catRow as $cat) {
								$links[] = "<a href='c-".$cat['catSlug']."'>".$cat['catTitle']."</a>";
							}
							echo implode(", ", $links);

						echo '<br />';
	
						echo '&rsaquo; <span style="text-decoration: underline;">Lien web du média</span> : <a style="color: orange;" href="'.html($row['postLink']).'">URL</a><br />';
						echo '&rsaquo; <span style="text-decoration: underline;">Taille</span> : '.makesize($row['postTaille']).'<br />';

						   	$filetorrent = $REP_TORRENTS.html($row['postTorrent']);
						   	
							//On décode le fichier torrent...	
							//$fd = fopen($_FILES["torrent"]["tmp_name"], "rb");
							//$length=filesize($_FILES["torrent"]["tmp_name"]);
							$fd = fopen($filetorrent, "rb");
							$length = filesize($filetorrent);			
	
							if ($length) {
								$alltorrent = fread($fd, $length);
							}
							$array = BDecode($alltorrent);
							$hash = sha1(BEncode($array["info"]));
							fclose($fd);

							if (isset($array["info"]) && $array["info"]) {
								$upfile=$array["info"];
							}
							else {
								$upfile = 0;
							}

							if (isset($upfile["length"])) {
								$size = (float)($upfile["length"]);
							}
							else if (isset($upfile["files"])) {
								//Pour les torrents multifichiers (Lupin - Xbtit - Btiteam - 2005)
								$size=0;
								foreach ($upfile["files"] as $file) {
									$size+=(float)($file["length"]);
                						}
							}
							else {
								$size = "0";
							}

							$ffile=fopen($filetorrent,"rb");
							$content=fread($ffile,filesize($filetorrent));
							fclose($ffile);

							$content=BDecode($content);
							$numfiles=0;

							if (isset($content["info"]) && $content["info"]) {
								$thefile=$content["info"];
								if (isset($thefile["length"])) {
									$dfiles[$numfiles]["filename"]=$thefile["name"];
									$dfiles[$numfiles]["size"]=makesize($thefile["length"]);
									$numfiles++;
								}

								elseif (isset($thefile["files"])) {
									foreach($thefile["files"] as $singlefile) {
										$dfiles[$numfiles]["filename"]=implode("/",$singlefile["path"]);
										$dfiles[$numfiles]["size"]=makesize($singlefile["length"]);
										$numfiles++;
									}
								}

							else {
								// Impossible ... mais bon ...
							}

							}

						   	//echo '&rsaquo; <span style="text-decoration: underline;">Nb de fichiers</span> : '.$numfiles.'<br />';
						
	
						   	$stmt3 = $db->prepare('SELECT * FROM blog_posts_seo,xbt_files WHERE blog_posts_seo.postID = :postID AND xbt_files.fid = blog_posts_seo.postID');
							$stmt3->bindValue(':postID', $row['postID'], PDO::PARAM_INT);
                                                   	$stmt3->execute();
                                                   	$xbt = $stmt3->fetch();
						
							//echo '&rsaquo; <span style="text-decoration: underline;">Hash</span> : <span style="font-size: 7.5px;">'.bin2hex($xbt['info_hash']).'</span><br />';

							echo '&rsaquo; <span style="text-decoration: underline;">Trafic</span> : ';
						   		echo '<span style="font-weight: bold;">S :</span> <a style="text-decoration: none; color:green;" href="peers.php?hash='.html($row['postHash']).'">'.$xbt['seeders'].'</a> | '; 
						   		echo '<span style="font-weight: bold;">L :</span> <a style="text-decoration: none; color:red;" href="peers.php?hash='.html($row['postHash']).'">'.$xbt['leechers'].'</a> | ';

							// on met à jour le nb de vues de l'article
							$stmt33 = $db->query('UPDATE blog_posts_seo SET postViews = postViews+1 WHERE postID = '.$row['postID']);

							// on affiche le nombre de vue de l'article
							$stmt333 = $db->prepare('SELECT postViews FROM blog_posts_seo WHERE postID = :postID');
                                                        $stmt333->execute(array(':postID' => $row['postID']));
                                                        $views = $stmt333->fetch();

						   	echo '<span style="font-weight: bold;">T :</span> '.$xbt['completed'].'<br />';

							echo '&rsaquo; <span style="text-decoration: underline;">Lu</span> : '.$views['postViews'].' fois<br />';
						   	echo '&rsaquo; <span style="text-decoration: underline;">Licence(s)</span> : ';	
	
						   	$stmt3 = $db->prepare('SELECT licenceID,licenceTitle FROM blog_licences, blog_post_licences WHERE blog_licences.licenceID = blog_post_licences.licenceID_BPL AND blog_post_licences.postID_BPL = :postID_BPL ORDER BY licenceTitle ASC');
                                                   	$stmt3->execute(array(':postID_BPL' => $row['postID']));
						   	$licenceRow = $stmt3->fetchALL(PDO::FETCH_ASSOC);
							$liclist = array();
							foreach($licenceRow as $lic) {
								$liclist[] = $lic['licenceTitle'];
							}
							echo implode(", ", $liclist);

							if(isset($_SESSION['username']) && isset($_SESSION['userid'])) {
								if(($row['postAuthor'] == $_SESSION['username']) || ($_SESSION['userid'] == 1)) {
									echo '<br /><br />';
									echo '<span><a style="text-decoration: none; padding-left: 100px;" href="admin/edit-post.php?id='.html($row['postID']).'"><input type="button" class="button" value="Editer" /></a>';
							?>
									<a style="text-decoration: none;" href="javascript:deltorr('<?php echo html($row['postID']); ?>','<?php echo html($row['postTitle']); ?>')"><input type="button" class="button" value="Supp." /></a></span>
							<?php
								}
							}


						echo '</div>';

					echo '</div>';

	
					//echo '<div style="padding: 0 15px 0 15px;">';
                                                echo '<p>';
                                                    if (!empty($row['postImage']) && file_exists($REP_IMAGES_TORRENTS.$row['postImage'])) {
                                                        echo '<img src="images/imgtorrents/'.html($row['postImage']).'" alt="'.html($row['postTitle']).'" style="float: left; margin-right: 10px; margin-top: 20px; margin-bottom: 10px; max-width: 150px; max-height: 150px;" />';
                                                    }
                                                    else {
                                                        echo '<img src="images/noimage.png" alt="Image" style="float: left; margin-right: 10px; margin-top: 20px; max-width: 150px; max-height: 150px;" />';
                                                    }
                                                        echo '<p>'.nl2br(bbcode($row['postDesc'])).'</p>';
                                                        echo '<p>'.nl2br(bbcode($row['postCont'])).'</p>';

                                                        echo '<div style="background-color: #FFFFCC; font-size: 12px;">';

                                                                if (isset($content['info']) && $content['info']) {
                                                                        $thefile=$content['info'];

                                                                        /*
                                                                        if (isset($thefile['length'])) {
                                                                                $nbfilestorr = $thefile['name'];
                                                                        }

                                                                        elseif (isset($thefile['files'])) {
                                                                                foreach($thefile['files'] as $singlefile) {
                                                                                        $nbfilestorr = html(implode('/',$singlefile['path']));
                                                                                }
                                                                        }

                                                                        else {
                                                                                // rien
                                                                        }
                                                                        */

                                                                }


                                                                echo '<table style="text-align: center;">';

                                                                if($numfiles == 1) {
                                                                        echo '<tr><td><span style="font-weight: bold; text-align: center;">Nb de fichier du torrent :</span> '.$numfiles.'</td></tr>';
                                                                }
                                                                else {
                                                                        echo '<tr><td><span style="font-weight: bold; text-align: center;">Nb de fichiers du torrent :</span> '.$numfiles.'</td></tr>';
                                                                }

                                                                if (isset($thefile['files'])) {
                                                                        echo '<tr><td><span style="font-weight: bold;">Fichiers du torrent :</span></td></tr>';
                                                                        foreach($content['info']['files'] as $multiplefiles) {
                                                                                echo '<tr><td>'.implode('/',$multiplefiles['path']).'</td></tr>';
                                                                        }
                                                                }
                                                                else {
                                                                        echo '<tr><td><span style="font-weight: bold;">Fichier du torrent :</span></td></tr>';
                                                                        echo '<tr><td><img src="images/file.png" /> '.html($thefile['name']).'</td></tr>';
                                                                }
                                                                echo '</table>';

                                                        echo '</div>';
                                                echo '</p>';
                                        ?>

                                        <br />

	
				<div style="background-color: #EFF5FB; padding: 5px; text-align:center;">
					<!-- icones partage réseaux sociaux -->
					
					<!-- Mastodon -->
					<div><a href="https://spacejerk.fr"><img src="<?php echo SITEURL; ?>/images/social/mastodon.png" style="width: 30px; height: 30px;" alt="Social Network Mastodon" title="Instance Mastodon spacejerk.fr" /></a>
					<!-- TWITTER -->
                                        <a href="https://twitter.com/share" class="twitter-share-button" data-size="large" data-hashtags="freetorrent,Libre">Tweet</a>
                                        <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
					</div>	

					<!-- FACEBOOK -->
					<div id="fb-root"></div>
					<script>(function(d, s, id) {
  				   		var js, fjs = d.getElementsByTagName(s)[0];
  				   		if (d.getElementById(id)) return;
  				   		js = d.createElement(s); js.id = id;
  				   		js.src = "//connect.facebook.net/fr_FR/sdk.js#xfbml=1&version=v2.0";
  				   		fjs.parentNode.insertBefore(js, fjs);
				   		}(document, 'script', 'facebook-jssdk'));
					</script>

					<div class="fb-like" data-href="<?php echo SITEURL; ?>/<?php echo $xbt['postSlug']; ?>" data-layout="button_count" data-action="recommend" data-show-faces="true" data-share="true"></div>

					<!-- GOOGLE+ -->
					<!-- Placez cette balise où vous souhaitez faire apparaître le gadget Bouton +1. -->
					<div class="g-plusone"></div>

			   		<!-- Placez cette ballise après la dernière balise Bouton +1. -->
					<script type="text/javascript">
  						window.___gcfg = {lang: 'fr'};

  						(function() {
    						var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    						po.src = 'https://apis.google.com/js/platform.js';
    						var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  						})();
					</script>


				</div>
				<br />


			</div>
			
			<br />

			<!-- disqus commentaires -->
			<div id="disqus_thread"></div>
    			<script type="text/javascript">
        			/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
        			var disqus_shortname = '<?php echo SITEDISQUS; ?>'; // required: replace example with your forum shortname

        			/* * * DON'T EDIT BELOW THIS LINE * * */
        			(function() {
            			   var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            			   dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            			   (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        			})();
    			</script>
    			<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>

	</div>
        
	<?php require('sidebar.php'); ?>
        
    	<div class="clear"></div>
	</div>
</div>

<div id="footer">
	<?php require('includes/footer.php'); ?>
</div>

</body>
</html>