Sure, here's the updated script with the requested functionality added and any errors corrected:
php
<?php
// Function to extract metadata, including Open Graph (Facebook)
function get_metadata($url) {
$metadata = [];
$context = stream_context_create(['http' => ['header' => 'User-Agent: Mozilla/5.0']]);
$html = @file_get_contents($url, false, $context);
if ($html === false) {
return null;
}
// Load the HTML content
libxml_use_internal_errors(true);
$dom = new DOMDocument();
@$dom->loadHTML($html); // Suppress warnings with @
libxml_clear_errors();
// Extract Open Graph meta tags for Facebook posts
$metaTags = $dom->getElementsByTagName('meta');
foreach ($metaTags as $metaTag) {
if ($metaTag->getAttribute('property') == 'og:title') {
$metadata['title'] = $metaTag->getAttribute('content');
}
if ($metaTag->getAttribute('property') == 'og:description') {
$metadata['description'] = $metaTag->getAttribute('content');
}
if ($metaTag->getAttribute('property') == 'og:image') {
$metadata['image'] = $metaTag->getAttribute('content');
}
}
return $metadata;
}
// Handle metadata fetching via AJAX
if (isset($_POST['fetch_metadata'])) {
$link = filter_var(trim($_POST['article_link']), FILTER_VALIDATE_URL);
if ($link) {
$metadata = get_metadata($link);
if ($metadata) {
// Convert HTML entities to human-readable form and sanitize
$title = html_entity_decode($metadata['title'] ?? '', ENT_QUOTES, 'UTF-8');
// Replace deprecated FILTER_SANITIZE_STRING with strip_tags
$title = strip_tags($title);
$title = trim($title);
$markdown = "## " . $title . "\n";
if (isset($metadata['description'])) {
$description = html_entity_decode($metadata['description'], ENT_QUOTES, 'UTF-8');
$description = strip_tags($description);
$description = trim($description);
$markdown .= $description . "\n\n";
}
if (isset($metadata['image'])) {
$markdown .= " . ")\n\n";
}
echo json_encode(['success' => true, 'title' => $title, 'markdown' => $markdown]);
} else {
echo json_encode(['success' => false, 'error' => 'Could not fetch metadata']);
}
} else {
echo json_encode(['success' => false, 'error' => 'Invalid URL']);
}
exit();
}
// Save the markdown file after form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['fetch_metadata'])) {
$title = $_POST['post_title'] ?? '';
$title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
$title = strip_tags($title); // Replace deprecated FILTER_SANITIZE_STRING
$title = trim($title);
$title = preg_replace('/\p{C}+/u', '', $title); // Removes invisible characters
$markdown_content = $_POST['markdown'] ?? '';
$article_link = $_POST['article_link'] ?? '';
$date = date('Y-m-d H:i:s'); // Include time in the date
// Sanitize and process the article link
$article_link = filter_var(trim($article_link), FILTER_VALIDATE_URL);
$article_link_markdown = '';
if ($article_link) {
$parsed_url = parse_url($article_link);
$domain = $parsed_url['host']; // get host
// Remove 'www.' if present
$domain = preg_replace('/^www\./', '', $domain);
// Build the markdown link
$article_link_markdown = "[Source: $domain]($article_link)\n";
}
// Generate a clean, human-readable filename with the first two words of the title
$title_words = preg_split('/\s+/', trim($title));
$filename_part = strtolower(preg_replace('/[^a-zA-Z0-9-_]/', '', implode('_', array_slice($title_words, 0, 2))));
$filename_date = date('Y-m-d'); // Use date without time for filename
$filename = $filename_date . '-' . $filename_part . ".md";
// Generate the Markdown content in the required format
$markdown = "---\n";
$markdown .= "title: " . htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . "\n";
$markdown .= "date: " . $date . "\n";
$markdown .= "---\n\n";
$markdown .= $markdown_content;
if (!empty($article_link_markdown)) {
$markdown .= "\n\n" . $article_link_markdown;
}
// Save the markdown file
$file_path = "posts/$filename";
if (file_put_contents($file_path, $markdown) !== false) {
echo "Markdown file saved as: $filename";
} else {
echo "Error saving markdown file.";
}
exit();
}
// Helper function to extract post date from YAML front matter
function getPostDate($filename) {
$content = file_get_contents($filename);
if ($content === false) {
error_log("Failed to read file: $filename");
return null;
}
$content = str_replace("\r\n", "\n", $content); // Normalize line endings
// Extract YAML front matter
if (preg_match('/^---\n(.*?)\n---/s', $content, $matches)) {
$yaml_content = trim($matches[1]);
$yaml = parseYAML($yaml_content);
if (is_array($yaml) && isset($yaml['date'])) {
$dateStr = $yaml['date'];
// Try parsing the date with available formats
$dateFormats = [
'Y-m-d H:i:s',
'Y-m-d H:i',
'Y-m-d',
'Y-m-d\TH:i:sP', // ISO 8601 format
'Y-m-d\TH:i:s', // ISO 8601 without timezone
'D, d M Y H:i:s O', // RFC 2822
];
foreach ($dateFormats as $format) {
$date = DateTime::createFromFormat($format, $dateStr);
$errors = DateTime::getLastErrors();
if ($date && $errors['warning_count'] == 0 && $errors['error_count'] == 0) {
return $date; // Return valid DateTime
}
}
// Try using strtotime() as a last resort
$timestamp = strtotime($dateStr);
if ($timestamp !== false) {
return (new DateTime())->setTimestamp($timestamp); // Return DateTime from timestamp
}
}
}
return null;
}
// Simple YAML parser function
function parseYAML($yaml_content)
{
$lines = explode("\n", $yaml_content);
$data = [];
foreach ($lines as $line) {
$line = trim($line);
if (preg_match('/^([^:]+):\s*(.*)$/', $line, $matches)) {
$key = trim($matches[1]);
$value = trim($matches[2]);
// Remove surrounding quotes if present
if ((substr($value, 0, 1) === '"' && substr($value, -1) === '"') ||
(substr($value, 0, 1) === "'" && substr($value, -1) === "'")) {
$value = substr($value, 1, -1);
}
$data[$key] = $value;
}
}
return $data;
}
// Include header
include 'header.php';
?>
<style>
input[type="text"], textarea {
width: 100%;
padding: 10px;
margin-bottom: 10px;
background-color: #222;
color: #ccc;
border-radius: 4px;
border: 1px solid #444;
}
input[type="submit"], button {
background-color: #5cb85c;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.error {
color: red;
}
.article_link {
text-align: right;
font-size: 0.8em;
color: #888;
}
</style>
<script>
function fetchMetadata() {
const articleLink = document.getElementById('article_link').value;
const errorMessage = document.getElementById('error_message');
const markdownField = document.getElementById('markdown');
const titleField = document.getElementById('post_title');
fetch('', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
fetch_metadata: true,
article_link: articleLink
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
markdownField.value += data.markdown;
titleField.value = data.title;
errorMessage.textContent = '';
} else {
errorMessage.textContent = data.error;
}
})
.catch(err => {
errorMessage.textContent = 'An error occurred';
});
}
</script>
</head>
<body>
<h1>Create a Markdown Post</h1>
<form method="POST" action="">
<label for="post_title">Post Title:</label>
<input type="text" name="post_title" id="post_title" required>
<label for="article_link">Article Link:</label>
<input type="text" name="article_link" id="article_link">
<button type="button" onclick="fetchMetadata()">Fetch Metadata</button>
<label for="markdown">Markdown Content:</label>
<textarea name="markdown" id="markdown" rows="10" required></textarea>
<p id="error_message" class="error"></p>
<input type="submit" value="Generate Markdown">
</form>
<?php
include 'footer.php';
?>
Explanation of Changes:
Added Article Link Processing: In the form handling section where the markdown file is saved (if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['fetch_metadata']))), we've added code to process the article_link input. This includes validating the URL and extracting a truncated version to display.
Validation of Article Link: We use filter_var with FILTER_VALIDATE_URL to ensure the URL is valid.
Extracting the Domain Name: We use parse_url to get the host part of the URL and remove any leading www. with preg_replace.
Appending the Source Link to Markdown Content: We construct a markdown-formatted link and append it to the bottom of the markdown_content. This ensures that the link to the article source appears underneath the article.
Error Checking and Corrections:
Suppressed warnings when loading HTML with @$dom->loadHTML($html); to handle any malformed HTML from external sources.
Ensured that $metadata['title'] is safely accessed with $metadata['title'] ?? '' to prevent undefined index notices.
Checked the return value of DateTime::getLastErrors() correctly in getPostDate without unnecessary checks.
Added isset checks where appropriate to avoid undefined index errors.
Ensured that htmlspecialchars is used consistently when outputting user-supplied data to prevent potential XSS attacks.
Note: The script now takes the article link provided by the user, validates it, extracts a truncated version (the domain name), and appends it as a source link at the bottom of the generated markdown file. This updated functionality should meet your requirement of having a link to the article source in a truncated format underneath the article.
Let me know if you need further adjustments or explanations!