<?php
session_start();

// Verifica se o usuÃ¡rio estÃ¡ logado
if (!isset($_SESSION['user_id'])) {
    // Redireciona para a pÃ¡gina de login se nÃ£o estiver logado
    header("Location: login.html");
    exit;
}

// Aqui vai o restante do seu cÃ³digo PHP...
?>


<!DOCTYPE html>
<html lang="pt-BR">
<head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Pr&eacute;-Visualiza&ccedil;&atilde;o e Edi&ccedil;&atilde;o</title>
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
	<style type="text/css">body {
            font-family: Arial, sans-serif;
            font-size: 20px;
            background-color: #ffffff;
            margin: 0;
            padding-top: 50px; /* Adiciona espaÃ§o para a barra de busca fixa */
        }

/* Estilos para o modo escuro */
body.dark-mode {
  background-color: #333;
  color: #fff;
}

.short-text {
    display: none; /* esconde o texto curto por padrÃ£o */
}

@media (max-width: 768px) {
    .full-text {
        display: none; /* esconde o texto completo em telas pequenas */
    }

    .short-text {
        display: inline; /* mostra o texto curto em telas pequenas */
    }
}


        @media (min-width: 4800px) {
            .result-list {
                grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
            }
        }






    /* Estilos para o rodapÃ© */
    footer {
        position: fixed;
        left: 0;
        bottom: 0;
        width: 100%;
        text-align: center;
        font-size: 8px;
        padding: 3px;
        background-color: #f2f2f2;
        border-top: 1px solid #ccc;
    }



.category-buttons-container {
  position: fixed;
  top: 25px;
  left: 0;
  right: 0;
  z-index: 998;
  max-width: 100%;
  width: 90%;
  margin-left: auto;
  margin-right: auto;
  overflow-x: auto;
  white-space: nowrap;
  padding: 5px;
  background-color: transparent; /* Torna o fundo transparente */
  box-shadow: 0 2px 10px rgba(0,0,0,0.1); /* Adicione sombra para profundidade */
  overflow: hidden;
}

.category-buttons {
  display: flex;
  justify-content: space-between; /* Posiciona os botÃµes nas extremidades */
  align-items: center;
}

.left-arrow,
.right-arrow {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  background-color: #F7F7F7;
  border-radius: 50%;
  font-size: 1.2rem;
  color: #333333;
  cursor: pointer;
  transition: background-color 0.3s ease, transform 0.3s ease;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1); /* Adicione sombra para profundidade */
}

.left-arrow:hover,
.right-arrow:hover {
  background-color: #EAEAEA;
  transform: scale(1.1); /* Efeito de zoom ao passar o mouse */
}

.category-button {
    margin: 0 0.5rem;
    background-color: #F7F7F7;
    border: none;
    border-radius: 0.4rem;
    padding: 0.5rem 1rem;
    font-size: 0.8rem;
    cursor: pointer;
    transition: background-color 0.3s ease, transform 0.3s ease;
    font-family: 'Arial', sans-serif; /* Substitua por qualquer fonte de sua escolha */
    box-shadow: 0 2px 5px rgba(0,0,0,0.1); /* Adicione sombra para profundidade */
}

.category-button:hover {
    background-color: #EAEAEA;
    transform: scale(1.05); /* Adicione um efeito de "zoom" ao passar o mouse */
}

        .category-buttons-wrapper {
            display: flex;
            align-items: center;
            overflow-x: auto;
            scrollbar-width: none;
        }

        .category-buttons-wrapper::-webkit-scrollbar {
            display: none;
        }

.category-button.all {
    background-color: #e8e9e8;
    color: #000000;
    font-weight: bold;
    font-size: 20px;
    text-decoration: none;
    border: none;
    padding: 0 5px; /* EspaÃ§amento horizontal de 5px */
    border-radius: 4px;
    line-height: 32px; /* Altura da linha para controlar o espaÃ§amento vertical */
    transition: background-color 0.3s ease; /* TransiÃ§Ã£o suave para a mudanÃ§a de cor de fundo */
}

.category-button.all:hover {
    background-color: #d2d3d2;
}


.category-button.world-news {
    background-color: #e8e9e8;
    color: #000000;
    font-weight: bold;
    font-size: 20px;
    text-decoration: none;
    border: none;
    padding: 0 5px; /* EspaÃ§amento horizontal de 5px */
    border-radius: 4px;
    line-height: 32px; /* Altura da linha para controlar o espaÃ§amento vertical */
    transition: background-color 0.3s ease; /* TransiÃ§Ã£o suave para a mudanÃ§a de cor de fundo */
}}

.category-button.world-news:hover {
    background-color: #d2d3d2;
}

.category-button.entertainment {
    background-color: #e8e9e8;
    color: #000000;
    font-weight: bold;
    font-size: 20px;
    text-decoration: none;
    border: none;
    padding: 0 5px; /* EspaÃ§amento horizontal de 5px */
    border-radius: 4px;
    line-height: 32px; /* Altura da linha para controlar o espaÃ§amento vertical */
    transition: background-color 0.3s ease; /* TransiÃ§Ã£o suave para a mudanÃ§a de cor de fundo */
}

.category-button.entertainment:hover {
    background-color: #d2d3d2;
}


.category-button.sports {
    background-color: #e8e9e8;
    color: #000000;
    font-weight: bold;
    font-size: 20px;
    text-decoration: none;
    border: none;
    padding: 0 5px; /* EspaÃ§amento horizontal de 5px */
    border-radius: 4px;
    line-height: 32px; /* Altura da linha para controlar o espaÃ§amento vertical */
    transition: background-color 0.3s ease; /* TransiÃ§Ã£o suave para a mudanÃ§a de cor de fundo */
}

.category-button.sports:hover {
    background-color: #d2d3d2;
}

.category-button.videogames {
    background-color: #e8e9e8;
    color: #000000;
    font-weight: bold;
    font-size: 20px;
    text-decoration: none;
    border: none;
    padding: 0 5px; /* EspaÃ§amento horizontal de 5px */
    border-radius: 4px;
    line-height: 32px; /* Altura da linha para controlar o espaÃ§amento vertical */
    transition: background-color 0.3s ease; /* TransiÃ§Ã£o suave para a mudanÃ§a de cor de fundo */
}

.category-button.videogames:hover {
    background-color: #d2d3d2;
}

.category-button.pins {
    background-color: #1f8aef;
    color: #ffffff;
    font-weight: bold;
    font-size: 20px;
    text-decoration: none;
    border: none;
    padding: 0 5px; /* EspaÃ§amento horizontal de 5px */
    border-radius: 4px;
    line-height: 32px; /* Altura da linha para controlar o espaÃ§amento vertical */
    transition: background-color 0.3s ease; /* TransiÃ§Ã£o suave para a mudanÃ§a de cor de fundo */
}

.category-button.pins:hover {
    background-color: #d2d3d2;
}

.category-button.plus {
    background-color: #ff0000;
    color: #ffffff;
    font-weight: bold;
    font-size: 20px;
    text-decoration: none;
    border: none;
    padding: 0 5px; /* EspaÃ§amento horizontal de 5px */
    border-radius: 4px;
    line-height: 32px; /* Altura da linha para controlar o espaÃ§amento vertical */
    transition: background-color 0.3s ease; /* TransiÃ§Ã£o suave para a mudanÃ§a de cor de fundo */
}

.category-button.plus:hover {
    background-color: #d2d3d2;
}

.category-button.pin {
    background-color: #1f8aef;
    color: #ffffff;
    font-weight: bold;
    font-size: 20px;
    text-decoration: none;
    border: none;
    padding: 0 10px; /* EspaÃ§amento horizontal de 10px */
    border-radius: 4px;
    line-height: 32px; /* Altura da linha para controlar o espaÃ§amento vertical */
    transition: background-color 0.3s ease; /* TransiÃ§Ã£o suave para a mudanÃ§a de cor de fundo */
}

.category-button.pin:hover {
    background-color: #f8ae01;
}
#myBtn {
            display: none;
            position: fixed;
            bottom: 40px;
            right: 12px;
            z-index: 99;
            font-size: 18px;
            border: none;
            outline: none;
            background-color: red;
            color: white;
            cursor: pointer;
            padding: 15px;
            border-radius: 4px;
        }

        #myBtn:hover {
            background-color: #d2d3d2;
        }


/* Estilos para o botÃ£o "Modo Escuro" */
#dark-mode-toggle {
            background-color: #333;
            border: none;
            border-radius: .4rem;
            color: #ffffff;
            cursor: pointer;
            font-size: 1.5rem;
            font-weight: bold;
            height: 2rem;
            width: 10%; /* ajuste esta porcentagem conforme necessÃ¡rio */
            outline: none;
            transition: background-color 0.3s ease;
            display: flex;
            justify-content: center;
            align-items: center;
    overflow: visible; /* permite que o conteÃºdo ultrapasse os limites do botÃ£o */
  margin-right: 5px;
}

#dark-mode-toggle:hover {
  background-color: #555;
}
	</style>
</head>
<body>
<div class="category-buttons-container">
<div class="category-buttons">
<div class="left-arrow"></div>

<div class="category-buttons-wrapper"><a class="category-button pins" href="https://digupdog.com/" target="_self">Pins</a><a class="category-button all" href="https://digupdog.net/FEED/home.html" target="_self">All</a><a class="category-button world-news" href="https://digupdog.net/FEED/news.html" target="_self">World News</a><a class="category-button entertainment" href="https://digupdog.net/FEED/entertainment.html" target="_self">Entertainment</a><a class="category-button sports" href="https://digupdog.net/FEED/sports.html" target="_self">Sports</a><a class="category-button videogames" href="https://digupdog.net/FEED/videogames.html" target="_self">Video Games</a><a class="category-button plus" href="https://digupdog.com/plus" target="_self">18+</a><a class="category-button pin" href="https://digupdog.com/aaa1" target="_self">+</a><button id="dark-mode-toggle"><span class="full-text">DARK</span><span class="short-text">D</span></button></div>

<div class="right-arrow"></div>
</div>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script><script>
var container = document.querySelector('.category-buttons-container');
var wrapper = document.querySelector('.category-buttons-wrapper');
var leftArrow = document.querySelector('.left-arrow');
var rightArrow = document.querySelector('.right-arrow');
var scrollAmount = 0;
var scrollStep = 5;
var scrollInterval;

function startScrollLeft() {
    scrollInterval = setInterval(function() {
        wrapper.scrollLeft -= scrollStep;  // Ajuste o valor de scrollLeft diretamente
    }, 10);
}

function startScrollRight() {
    scrollInterval = setInterval(function() {
        wrapper.scrollLeft += scrollStep;  // Ajuste o valor de scrollLeft diretamente
    }, 10);
}

function stopScroll() {
  clearInterval(scrollInterval);
}

leftArrow.addEventListener('mousedown', startScrollLeft);
leftArrow.addEventListener('mouseup', stopScroll);
leftArrow.addEventListener('mouseleave', stopScroll);
rightArrow.addEventListener('mousedown', startScrollRight);
rightArrow.addEventListener('mouseup', stopScroll);
rightArrow.addEventListener('mouseleave', stopScroll);

leftArrow.addEventListener('touchstart', startScrollLeft);
leftArrow.addEventListener('touchend', stopScroll);
rightArrow.addEventListener('touchstart', startScrollRight);
rightArrow.addEventListener('touchend', stopScroll);



// Seletor para o botÃ£o de alternar modo escuro
const darkModeToggle = document.querySelector('#dark-mode-toggle');

// Evento de clique no botÃ£o
darkModeToggle.addEventListener('click', function() {
  // Adiciona ou remove a classe 'dark-mode' no elemento body
  document.body.classList.toggle('dark-mode');
});

</script></body>
</html>




<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PrÃ©-VisualizaÃ§Ã£o e EdiÃ§Ã£o</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet">
    <style>
body {
    background-color: #ffffff;
    font-family: 'Arial', sans-serif;
    color: #333;
}

.container {
    width: 90%;
    max-width: 800px;
    margin: 30px auto;
    padding: 40px;
    background-color: #ffffff;
    border-radius: 12px;
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.05);
    overflow-wrap: break-word;
    word-break: break-all; /* Ensures long words/URLs are broken up */
}

.form-heading {
    color: #1da1f2;
    font-weight: 700;
    margin-bottom: 30px;
    font-size: 24px;
}

.btn-primary {
    background-color: #1da1f2;
    border-color: #1da1f2;
    font-weight: 600;
}

.btn-primary:hover {
    background-color: #f8ae01;
    border-color: #f8ae01;
}

.message-container {
    background-color: #f8ae01;
    border-left: 5px solid #f8ae01;
    padding: 15px;
    border-radius: 8px;
    margin-top: 20px;
}

.message-header {
    color: #5d647b;
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 15px;
}

.link-button {
    background-color: #f6d365;
    padding: 10px 15px;
    border-radius: 5px;
    color: white;
    text-decoration: none;
    font-weight: 600;
    transition: background-color 0.3s;
    display: inline-block;
    margin-top: 10px;
}

.link-button:hover {
    background-color: #f3ca54;
}

@media (max-width: 768px) {
    .container {
        width: 95%;
        padding: 20px;
    }

    .form-heading {
        font-size: 20px;
    }

    .message-container {
        padding: 10px;
    }

    .message-header {
        font-size: 16px;
    }
}

.message-content, .alert {
    word-wrap: break-word;
}

.alert-success {
    color: #155724;
    background-color: #d4edda;
    border-color: #c3e6cb;
    border-radius: 0.25rem;
    padding: 10px;
    margin-top: 20px;
    border: 1px solid transparent;
    display: flex;
    align-items: center;
}

.alert-success i {
    font-size: 20px;
    margin-right: 10px;
}

.btn-primary {
    color: #fff;
    background-color: #007bff;
    border-color: #007bff;
}

.btn-primary:hover {
    color: #fff;
    background-color: #0056b3;
    border-color: #0056b3;
}

.view-edit-button {
    margin-top: 20px;
    font-weight: 600;
    display: block;
    width: 100%;
    padding: 10px;
}

.view-edit-button i {
    margin-right: 5px;
}

.modal {
    display: none; 
    position: fixed; 
    z-index: 1; 
    padding-top: 100px; 
    left: 0;
    top: 0;
    width: 100%; 
    height: 100%; 
    overflow: auto; 
    background-color: rgb(0,0,0); 
    background-color: rgba(0,0,0,0.9); 
}

.modal-content {
    margin: auto;
    display: block;
    max-height: 80vh; /* Limita a altura máxima a 80% da altura da viewport */
    width: auto; /* Ajusta a largura automaticamente */
    max-width: 100%; /* Garante que a imagem não ultrapasse a largura da tela */
}

.close {
    position: absolute;
    top: 60px;
    right: 35px;
    color: #f1f1f1;
    font-size: 50px;
    font-weight: bold;
    cursor: pointer;
}

    </style>
</head>
<body>
    <div class="container">
        <h2 class="form-heading"><i class="fas fa-link"></i> Enter URL for Display</h2>

        <form action="aaa.php" method="post">
            <div class="form-group">
                <label for="web_url"><i class="fas fa-globe-americas"></i> URL:</label>
                <input class="form-control" id="web_url" name="web_url" required type="url">
            </div>
            <button class="btn btn-primary btn-block" type="submit"><i class="fas fa-search"></i> Extract and View</button>
            
            <?php if (isset($_SESSION['username']) && isset($_SESSION['user_id'])): ?>
                <div class="message-container">
                    <div class="message-header"><i class="fas fa-user-check"></i> Logged-in User Information</div>
                    <div><i class="fas fa-user"></i> Username: <?php echo htmlspecialchars($_SESSION['username']); ?></div>
                    <div><i class="fas fa-id-badge"></i> Session User ID: <?php echo htmlspecialchars($_SESSION['user_id']); ?></div>
                    <?php if (isset($existingLink)): ?>
                        <div><i class="fas fa-exclamation-triangle"></i> The link <a href="<?php echo htmlspecialchars($web_url); ?>"><?php echo htmlspecialchars($web_url); ?></a> already exists.</div>
                        <a href='pindetails.html?id=<?php echo htmlspecialchars($existingLink['id']); ?>' class='link-button'><i class="fas fa-eye"></i> Go to Link Details</a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </form>
<!-- The Modal -->
<div id="myModal" class="modal">
    <span class="close">&times;</span>
    <img class="modal-content" id="img01">
</div>

<script>
function showModal(src) {
    var modal = document.getElementById("myModal");
    var modalImg = document.getElementById("img01");
    modal.style.display = "block";
    modalImg.src = src;

    var span = document.getElementsByClassName("close")[0];
    span.onclick = function() { 
        modal.style.display = "none";
    }
}
</script>

<!-- Include jQuery and Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<?php
session_start();

// Check if the user is logged in
if (isset($_SESSION['username'])) {
    echo "" . $_SESSION[''];
} else {
    echo "";
}

if (isset($_SESSION['user_id'])) {
    echo "" . $_SESSION[''];
} else {
    echo "";
}


// Check if user is not logged in, redirect to login page
if (!isset($_SESSION['user_id'])) {
    header("Location: login.html");
    exit;
}

include_once('author_functions.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Database connection settings
$host = 'localhost';
$db = 'digupdog_FEED';
$user = 'digupdog_FEEDadmin';
$pass = 'Raimundinho1';
$charset = 'utf8mb4';

$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
];

// PDO instance creation
$pdo = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass, $options);

try {
    // Preparando declaraÃ§Ãµes SQL
    $selectStmt = $pdo->prepare('SELECT id, thumbnail FROM pinfeeds WHERE link = ?');
    $insertStmt = $pdo->prepare('INSERT INTO pinfeeds (title, description, thumbnail, pubDate, link, updated, source_website, favicon, tags, embed_code, author, user_id) VALUES (?, ?, ?, NOW(), ?, NOW(), ?, ?, ?, ?, ?, ?)');

    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['web_url'])) {
        $rawLinks = extractURLs($_POST['web_url']);
        $links = array_unique(array_map('trim', $rawLinks));

        foreach ($links as $web_url) {
            $web_url = normalizeURL($web_url);

            if (!filter_var($web_url, FILTER_VALIDATE_URL)) {
                echo "URL invÃ¡lida: $web_url<br>";
                continue;
            }

            $selectStmt->execute([$web_url]);
            $existingLink = $selectStmt->fetch();

if ($existingLink) {
    // Fetch the thumbnail URL from the existing link.
    // Assuming 'thumbnail' is the column name for the thumbnail URL in your 'pinfeeds' table.
    $thumbnailUrl = $existingLink['thumbnail'];

    echo "<div class='alert alert-warning' role='alert'>";

    // Check if there's a thumbnail URL and display it.
    if (!empty($thumbnailUrl)) {
         echo "<img src='" . htmlspecialchars($thumbnailUrl) . "' alt='Thumbnail' style='width: 100px; height: auto; margin-right: 10px; cursor: pointer;' onclick='showModal(\"" . htmlspecialchars($thumbnailUrl) . "\")'>";
    }

    echo "<span class='d-block d-sm-inline'>The link <strong>$web_url</strong> already exists.</span> ";
    echo "<a href='pindetails.html?id=" . $existingLink['id'] . "' class='btn btn-primary btn-sm mt-2 mt-sm-0 ml-sm-2'>View</a>";
    echo "</div>";
    continue;
}


$selectStmt->execute([$web_url]);
if ($selectStmt->fetch()) {
    echo "<div class='alert alert-info' role='alert'>";
    echo "Link already exists: <strong>$web_url</strong>";
    echo "</div>";
    continue;
}
$existingLink = $selectStmt->fetch();

if ($existingLink) {
    echo "<div class='alert alert-warning' role='alert'>";
    echo "<span class='d-block d-sm-inline'>The link <strong>$web_url</strong> already exists.</span> ";
    echo "<a href='pindetails.html?id=" . $existingLink['id'] . "' class='btn btn-primary btn-sm mt-2 mt-sm-0 ml-sm-2'>Take a Look</a>";
    echo "</div>";
    continue;
}


            $ch = curl_init($web_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            $html = curl_exec($ch);

            if ($html === false) {
                echo "Erro ao obter o conteÃºdo de $web_url: " . curl_error($ch) . "<br>";
                curl_close($ch);
                continue;
            }

            curl_close($ch);

            $dom = new DOMDocument;
            libxml_use_internal_errors(true);
            $dom->loadHTML($html);
            libxml_use_internal_errors(false);
            $xpath = new DOMXPath($dom);
            $web_info = extractWebInfo($xpath, $html, $web_url);
            $web_info['source_website'] = parse_url($web_url, PHP_URL_HOST);

            $tags = extractTagsFromTitle($web_info['title']);
            $tagsAsString = implode(", ", $tags);


    $author = generateRandomAuthor(); // Usando generateRandomAuthor em vez de getRandomAuthor
    $tags = extractTagsFromTitle($web_info['title']);
    $tagsAsString = implode(", ", $tags);

if ($web_info) {
    $author = $_SESSION['username'] ?? generateRandomAuthor(); // Fallback to random author if session username is not set
    $tagsAsString = implode(", ", extractTagsFromTitle($web_info['title']));

    // Prepare your parameters array
    $parameters = [
        $web_info['title'],
        $web_info['description'],
        $web_info['thumbnail'],
        $web_url,
        $web_info['source_website'],
        $web_info['favicon'],
        $tagsAsString,
        extractEmbedCode($web_url),
        $author,
        $_SESSION['user_id'] // Assuming user_id is stored in the session
    ];

                $thumbnailUrl = $web_info['thumbnail']; // Or however you fetch this information

    if ($insertStmt->execute($parameters)) {
        $lastInsertId = $pdo->lastInsertId();

        // Echo success message with thumbnail and View/Edit button for each link
        echo "<div class='alert alert-success' role='alert'>";
        echo "<i class='fas fa-check-circle'></i> Link processado com sucesso: $lastInsertId";
        if ($thumbnailUrl) {
    echo "<img src='" . htmlspecialchars($thumbnailUrl) . "' alt='Thumbnail' style='width: 100px; height: auto; margin-left: 10px; cursor: pointer;' onclick='showModal(\"" . htmlspecialchars($thumbnailUrl) . "\")'>";
}
        echo "</div>";
        echo "<a href='edit.php?id=$lastInsertId' class='btn btn-primary btn-block view-edit-button'><i class='fas fa-edit'></i> View / Edit </a>";
        echo "<a href='delete_extract.php?id=$lastInsertId' class='btn btn-danger btn-block delete-button' onclick='return confirm(\"Are you sure you want to delete this link?\");'><i class='fas fa-trash-alt'></i> Delete</a>";
    } else {

                    echo "Erro ao executar a declaraÃ§Ã£o de inserÃ§Ã£o: ";
                    print_r($insertStmt->errorInfo());
                }
            } else {
                echo "Falha ao extrair informaÃ§Ãµes: $web_url<br>";
            }
        }
    }
} catch (PDOException $e) {
    echo "Erro no banco de dados: " . $e->getMessage() . "<br>";
    exit;
}


function normalizeURL($url) {
    $parsedUrl = parse_url($url);
    $queryParameters = [];

    if (isset($parsedUrl['query'])) {
        parse_str($parsedUrl['query'], $queryParameters);
    }

    // Para URLs longas do YouTube, mantenha apenas o parÃ¢metro "v"
    if (isset($parsedUrl['host']) && ($parsedUrl['host'] === 'youtube.com' || $parsedUrl['host'] === 'www.youtube.com')) {
        if (isset($queryParameters['v'])) {
            $url = 'https://www.youtube.com/watch?v=' . $queryParameters['v'];
        }
    }

    // Para URLs curtas do YouTube, converta para o formato longo
    elseif (isset($parsedUrl['host']) && ($parsedUrl['host'] === 'youtu.be')) {
        if (isset($parsedUrl['path'])) {
            $videoId = ltrim($parsedUrl['path'], '/');
            $url = 'https://www.youtube.com/watch?v=' . $videoId;
        }
    }
    
        // Para "vm.tiktok.com", normalize a URL
    elseif (isset($parsedUrl['host']) && strpos($parsedUrl['host'], 'tiktok.com') !== false) {
        $videoId = getTikTokVideoId($url);
        if ($videoId) {
            $url = 'https://www.tiktok.com/@user/video/' . $videoId;
        }
    }
    
        // Para URLs do Vimeo, extraia o ID do vÃ­deo e normalize a URL
    elseif (isset($parsedUrl['host']) && strpos($parsedUrl['host'], 'vimeo.com') !== false) {
        $pathSegments = explode('/', $parsedUrl['path']);
        if (isset($pathSegments[1]) && is_numeric($pathSegments[1])) {
            $url = 'https://vimeo.com/' . $pathSegments[1];
        }
    }

// Para URLs de pesquisa do VK com vÃ­deo especÃ­fico
if (isset($parsedUrl['host']) && strpos($parsedUrl['host'], 'vk.com') !== false) {
    if (isset($parsedUrl['query'])) {
        parse_str($parsedUrl['query'], $queryParameters);

        if (isset($queryParameters['z'])) {
            if (preg_match('/video(\d+_\d+)/', $queryParameters['z'], $matches)) {
                $videoId = $matches[1]; // Captura <owner_id>_<media_id>
                $url = "https://vk.com/video" . $videoId;
            }
        }
    }
}

// Para VK Clips
if (isset($parsedUrl['host']) && strpos($parsedUrl['host'], 'vk.com') !== false) {
    if (isset($parsedUrl['query'])) {
        parse_str($parsedUrl['query'], $queryParameters);
        if (isset($queryParameters['z'])) {
            if (preg_match('/clip(-\d+_\d+)/', $queryParameters['z'], $matches)) {
                $videoId = $matches[1];
                $url = "https://vk.com/clip" . $videoId;
            }
        }
    } elseif (preg_match('/clip(-\d+_\d+)/', $parsedUrl['path'], $matches)) {
        $videoId = $matches[1];
        $url = "https://vk.com/clip" . $videoId;
    }
}




    // Para "ok.ru", remova os parÃ¢metros de consulta da URL
    elseif (isset($parsedUrl['host']) && $parsedUrl['host'] === 'ok.ru') {
        $url = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . $parsedUrl['path'];
    }

    // Adicione aqui condiÃ§Ãµes adicionais para outros domÃ­nios, se necessÃ¡rio

    return $url;
}

// Função para normalizar e validar URLs
function normalizeAndValidateURL($url) {
    $parsedUrl = parse_url($url);
    $normalizedUrl = strtolower($parsedUrl['scheme'] . '://' . $parsedUrl['host'] . $parsedUrl['path']);
    return filter_var($normalizedUrl, FILTER_VALIDATE_URL) ? $normalizedUrl : false;
}

// Função para extrair URLs e armazenar em lote
function extractAndStoreURLs($text) {
    global $pdo; // PDO instance
    $urls = extractURLs($text); // Assuma que esta função retorna um array de URLs
    $pdo->beginTransaction();
    try {
        $insertStmt = $pdo->prepare('INSERT IGNORE INTO links (url) VALUES (?)');
        foreach ($urls as $url) {
            $normalizedUrl = normalizeAndValidateURL($url);
            if ($normalizedUrl) {
                $insertStmt->execute([$normalizedUrl]);
            }
        }
        $pdo->commit();
    } catch (PDOException $e) {
        $pdo->rollBack();
        error_log("Falha na inserção: " . $e->getMessage());
    }
}

// Exemplo de uso
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['text'])) {
    extractAndStoreURLs($_POST['text']);
}

function extractURLsIncludingSpecific($text) {
    $extractedURLs = [];

    // Expressões regulares para identificar URLs específicos
    $specificPatterns = [
        '#https?://www\.xvideos\.com/video[0-9]+/[a-zA-Z0-9_\-]+#',  // Xvideos
        '#https?://www\.youporn\.com/watch/[0-9]+/[a-zA-Z0-9_\-]+#', // YouPorn
        // Adicione outras expressões regulares conforme necessário para outros sites específicos
    ];

    // Padrão geral para capturar qualquer URL
    $generalPattern = "#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#";

    // Primeiro, extrai URLs específicos
    foreach ($specificPatterns as $pattern) {
        preg_match_all($pattern, $text, $matches);
        $extractedURLs = array_merge($extractedURLs, $matches[0]);
    }

    // Depois, extrai URLs gerais
    preg_match_all($generalPattern, $text, $generalMatches);
    $extractedURLs = array_merge($extractedURLs, $generalMatches[0]);

    return array_unique($extractedURLs);
}


function extractEmbedCode($url) {
    $embedCode = '';

    // Identify the website by its domain
    $domain = parse_url($url, PHP_URL_HOST);

    switch ($domain) {
        case 'youtube.com':
        case 'www.youtube.com':
            $videoId = getYouTubeVideoId($url);
            $embedCode = "<iframe src=\"https://www.youtube.com/embed/{$videoId}\" width=\"560\" height=\"315\" frameborder=\"0\" allowfullscreen></iframe>";
            break;
        
        case 'vimeo.com':
        case 'www.vimeo.com':
            $videoId = getVimeoVideoId($url);
            $embedCode = "<iframe src=\"https://player.vimeo.com/video/{$videoId}\" width=\"560\" height=\"315\" frameborder=\"0\" allowfullscreen></iframe>";
            break;

        case 'youtube.googleapis.com':
            $videoId = getYouTubeShortsVideoId($url);
            $embedCode = "<iframe src=\"https://www.youtube.com/embed/{$videoId}\" width=\"560\" height=\"315\" frameborder=\"0\" allowfullscreen></iframe>";
            break;

        case 'vm.tiktok.com':
            $videoId = getTikTokVideoId($url);
            $embedCode = "<iframe src=\"https://www.tiktok.com/embed/{$videoId}\" width=\"560\" height=\"315\" frameborder=\"0\" allowfullscreen></iframe>";
            break;

        default:
            // Create a generic iframe embed code using the URL
            $embedCode = "<iframe src=\"$url\" width=\"560\" height=\"315\" frameborder=\"0\" allowfullscreen></iframe>";
            break;
    }

    return $embedCode;
}


function getYouTubeShortsVideoId($url) {
    $pathSegments = explode('/', parse_url($url, PHP_URL_PATH));
    return isset($pathSegments[2]) ? $pathSegments[2] : null;
}


function getTikTokVideoId($url) {
    // Verifica se a URL Ã© encurtada
    if (strpos($url, 'vm.tiktok.com') !== false || strpos($url, 'tiktok.com/t/') !== false) {
        $url = resolveTikTokShortURL($url);
    }

    $parsedUrl = parse_url($url);
    $pathSegments = explode('/', $parsedUrl['path']);

    // Para URLs completas do TikTok
    if (isset($pathSegments[3]) && is_numeric($pathSegments[3])) {
        return $pathSegments[3];
    }

    return null;
}

function resolveTikTokShortURL($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Siga redirecionamentos
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Retorna a resposta como uma string
    curl_setopt($ch, CURLOPT_HEADER, true); // Inclua o cabeÃ§alho na saÃ­da
    curl_setopt($ch, CURLOPT_NOBODY, true); // NÃ£o precisa do corpo da resposta

    $response = curl_exec($ch);
    $final_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // ObtÃ©m a URL final apÃ³s os redirecionamentos

    curl_close($ch);

    return $final_url;
}




function getYouTubeVideoId($url) {
    // Extract the video ID from a YouTube URL
    parse_str(parse_url($url, PHP_URL_QUERY), $query);
    return isset($query['v']) ? $query['v'] : null;
}

function getVimeoVideoId($url) {
    // Extract the video ID from a Vimeo URL
    $pathSegments = explode('/', parse_url($url, PHP_URL_PATH));
    return isset($pathSegments[1]) ? $pathSegments[1] : null;
}


function extractWebInfo($xpath, $html) {
    return [
        'title' => getTitle($xpath, $html),
        'description' => getDescription($xpath, $html),
        'thumbnail' => getThumbnail($xpath),
        'favicon' => getFavicon($xpath)
    ];
}

function extractURLs($text) {
    preg_match_all("#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#", $text, $matches);
    return $matches[0];
}




function extractTagsFromTitle($title) {
    $title = preg_replace("/[.,\/#!$%\^&\*;:{}=\-_`~()]/", "", $title);
    $title = mb_strtolower($title);
    $words = explode(" ", $title);

    $commonWords = ["a", "an", "the", "and", "or", "but", "in", "at", "on", "with", "to", "â€“", "for", "is", "of", "that", "it", "by", "from", "as", "are", "was", "be", "has", "have", "will", "this", "which", "its", "about", "up", "more", "who", "also", "they", "out", "he", "she", "you", "their", "we", "her", "his", "them", "been", "these", "would", "some", "can", "like", "there", "if", "all", "my", "what", "so", "then", "into", "just", "over", "do", "than", "when", "other", "how", "our", "any", "new", "me", "after", "most", "made", "only", "time", "will", "where", "year", "years", "make", "does", "could", "were", "your", "good", "well", "them"];

    $keywords = array_filter($words, function ($word) use ($commonWords) {
        return !in_array($word, $commonWords) && mb_strlen($word) > 2;
    });

    return $keywords;
}


function getFavicon($xpath) {
    $queries = [
        '//link[@rel="icon"]/@href',
        '//link[@rel="shortcut icon"]/@href'
    ];

    foreach ($queries as $query) {
        $nodes = $xpath->query($query);
        if ($nodes->length > 0 && $nodes->item(0)->nodeValue) {
            return trim($nodes->item(0)->nodeValue);
        }
    }

    return 'default_favicon.ico';
}

function getTitle($xpath, $html) {
    // First extraction pattern
    $title = '';
    if (preg_match('/<span class="tiktok-j2a19r-SpanText.*?">(.*?)<\/span>/is', $html, $matches)) {
        $title = strip_tags($matches[1]);
    }

    // Second extraction pattern if the first one fails
    if (empty($title) && preg_match('/another-regex-pattern-for-different-structure/', $html, $matches)) {
        $title = strip_tags($matches[1]);
    }

    // Add more patterns as needed...

    // Check if a title was extracted
    if (!empty($title) && !containsPlaceholder($title)) {
        return $title;
    }

    // If no proper title is found by now, try XPath queries.
    $queries = [
        '//meta[@property="og:title"]/@content',
        '//title',
        '//h1',
        '//h2',
        '//h3',
        '//h4',
        '//h5',
    ];

    foreach ($queries as $query) {
        $nodes = $xpath->query($query);
        if ($nodes->length > 0) {
            $title = trim($nodes->item(0)->nodeValue);
            if (!empty($title) && !containsPlaceholder($title)) {
                return $title;
            }
        }
    }

    // If all else fails, return a default title.
    return 'No title';
}


function getDescription($xpath) {
    $queries = [
        '//meta[@property="og:description"]/@content',
        '//meta[@name="description"]/@content',
        '//p'
    ];

    foreach ($queries as $query) {
        $nodes = $xpath->query($query);
        if ($nodes->length > 0) {
            $description = trim($nodes->item(0)->nodeValue);
            if (!empty($description)) {
                return $description;
            }
        }
    }

    return 'No description';
}

function createTitleFromDescription($description) {
    $words = explode(' ', $description);
    $titleWords = array_slice($words, 0, 8);
    return implode(' ', $titleWords) . '...';
}

function containsPlaceholder($string) {
    $placeholders = [
        "%% video.title %%",
        "%% post.title %%",
        "%% n.title %%"
    ];

    foreach ($placeholders as $placeholder) {
        if (strpos($string, $placeholder) !== false) {
            return true;
        }
    }
    return false;
}


function getThumbnail($xpath) {
    $queries = [
        // Consulta especÃ­fica para o TikTok
        '//div[contains(@class, "tiktok-")]/div/div/a/picture/img/@src',

        // Consultas gerais para imagens e vÃ­deos
        '//meta[@property="og:image"]/@content',
        '//img[@class="post-thumbnail"]/@src',
        '//figure/img/@src',
        '//img[contains(@src, "tiktokcdn.com")]/@src',
        '//div[@class="post-thumbnail"]/img/@src',
        '//img[contains(@class, "wp-post-image")]/@src',
        '//video/@poster',

        // Novas consultas adicionadas
        '//img[@data-src]/@data-src',
        '//div[@id="container-imagem"]/img/@src',
        '//section[contains(@class, "galeria-imagem")]/img/@src',
        '//div[contains(@style, "background-image")]/@style',
        '//iframe/ancestor-or-self::body//img/@src',
        '//a[contains(@href, "image")]/@href',
        '//img[contains(@src, "1024x768")]/@src',
        '//img[contains(@src, ".jpg") or contains(@src, ".png")]/@src',

        // Captura genÃ©rica de imagens
        '//img/@src',
        // Novas consultas para suporte a lazy loading
        '//img[@data-lazy-src]/@data-lazy-src',
        '//img[@data-original]/@data-original',
        '//img[@data-srcset]/@data-srcset',

        // Consulta para estilos inline
        "//div[contains(@style, 'background-image')]/@style",

        // Targeting specific attributes
        '//div[@role="banner"]',
        '//input[@type="checkbox"]',

        // Text content-based queries
        '//a[contains(text(), "Download")]',
        
        // Positional queries
        '//li[position()=1]',

        // Attribute-specific queries
        '//img[@alt]',
        '//a[@rel="nofollow"]',

        // Handling dynamic content
        '//div[contains(@class, "dynamic-content")]',

        // File type specific queries
        '//a[contains(@href, ".pdf")]', 

        // Forms and inputs
        '//input[@type="email"]',
        '//textarea',

        // Combining conditions
        '//div[@class="container" and @id="main"]',

        // Using axes
        '//h1/following-sibling::p',

        // Handling classes and IDs
        '//*[@class="button"]',
        '//*[@id="header"]',

        // Negation queries
        '//a[not(contains(@class, "external"))]',

        // Attribute wildcards
        '//input[@*]',

        // Section-specific queries
        '//nav',
        '//footer',

        // Nested element queries
        '//div[@id="content"]//p',

        // Language-based queries
        '//p[lang("en")]',

        // Using functions
        '//ul[count(li)>3]',

        // Conditional queries
        '//div[@data-count>10]',

        // Add more queries as needed
        // ...
    ];

    foreach ($queries as $query) {
        $nodes = $xpath->query($query);
        foreach ($nodes as $node) {
            $url = trim($node->nodeValue);

            // Processamento de estilos inline para extrair URLs
            if (strpos($url, 'background-image') !== false) {
                $url = extractUrlFromStyle($url);
            }

            // Validar a URL da imagem
            if (!empty($url) && filter_var($url, FILTER_VALIDATE_URL)) {
                // Verificar se a imagem Ã© vÃ¡lida (por exemplo, verificando o cabeÃ§alho HTTP)
                if (isValidImage($url)) {
                    return $url;
                }
            }
        }
    }

    // LÃ³gica de fallback
    // ...

    return 'fallback_image.jpg';
}

function extractUrlFromStyle($style) {
    // ExtraÃ§Ã£o de URL de estilos CSS inline
    // Exemplo: extrair URL de "background-image: url('...')"
    preg_match("/url\(['\"]?(.*?)['\"]?\)/", $style, $matches);
    return $matches[1] ?? null;
}

function isValidImage($url) {
    // Verificar se a URL da imagem Ã© vÃ¡lida e acessÃ­vel
    // Implementar lÃ³gica para enviar uma solicitaÃ§Ã£o HTTP HEAD e verificar o cabeÃ§alho de resposta
    // ...

    // Exemplo bÃ¡sico (pode precisar de mais validaÃ§Ãµes conforme o cenÃ¡rio)
    $headers = get_headers($url, 1);
    if (strpos($headers[0], '200 OK') !== false) {
        return true;
    }
    return false;
}





        ?>
        

        <?php
        


function limitText($text, $maxLength) {
    if (strlen($text) > $maxLength) {
        return substr($text, 0, $maxLength) . '...';
    }
    return $text;
}
?>

    </div>
</body>
</html>