This repository has been archived on 2024-01-22. You can view files and clone it, but cannot push or open issues or pull requests.
speedie-page/blog.php

296 lines
7.6 KiB
PHP
Raw Normal View History

2023-06-30 23:39:01 +02:00
<?php
/*
* speedie-blog
*
* Copyright (C) 2007-2011 Steven Frank <http://stevenf.com/>
* Copyright (C) 2023 speedie <speedie@speedie.site>
*
* See LICENSE file for copyright and license details.
*/
spl_autoload_register(function($class){
require str_replace('\\', DIRECTORY_SEPARATOR, ltrim($class, '\\')).'.php';
});
use md\MarkdownExtra;
define('BLOG_PATH', dirname(__FILE__). '/articles');
define('BLOG_EXT', 'md');
define('BASE_URI', str_replace('/index.php', '', $_SERVER['SCRIPT_NAME']));
define('SELF', $_SERVER['SCRIPT_NAME']);
define('VIEW', ''); // '?action=view&page='
define('ENABLE_TITLE', true);
define('ENABLE_HEAD', true);
define('ENABLE_FOOTER', true);
define('META_DESC', true);
define('META_ENC', true);
define('TITLE_DATE', 'j M Y');
function __( $label, $alt_word = null ) {
return is_null($alt_word) ? $label : $alt_word;
}
function truncate($text, $chars) {
if (strlen($text) <= $chars) {
return $text;
}
$text = $text." ";
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,' '));
$text = $text."...";
return $text;
}
function printHeader($title, $action, $html) {
// TODO: Improve this garbage, I suck at PHP and this is just stuff I found on the internet.
if (META_DESC) {
$nhtml = $html;
$nhtml = preg_replace( '@<p\b[^>]*>(?=.*?<a\b[^>]*>).*?<\@p>@si', '', $nhtml);
$nhtml = preg_replace( '@<(li)[^>]*?>.*?</\\1>@si', '', $nhtml);
$nhtml = preg_replace( '@<(ul)[^>]*?>.*?</\\1>@si', '', $nhtml);
$nhtml = strip_tags($nhtml);
$nhtml = preg_replace('/\s*$^\s*/m', "\n", $nhtml);
$nhtml = truncate($nhtml, 512);
}
print "<!DOCTYPE html>\n";
print "<html lang=\"en\">\n";
if (ENABLE_HEAD) {
print " <head>\n";
if (META_ENC) {
print " <meta charset=\"UTF-8\">\n";
}
if (META_DESC && $action != 'home') {
print " <meta name=\"description\" content=\"$nhtml\">\n";
}
if (ENABLE_TITLE) {
print " <title>$title</title>\n";
}
include("php/header.php");
print " </head>\n";
}
print " <body>\n";
if ($action === 'home') {
include("php/blog-p.php");
}
}
function printFooter() {
if (ENABLE_FOOTER) {
print " </body>\n";
include("php/footer.php");
}
}
function getDateForPage($pageName, $date_format, $pageDate) {
$file = BLOG_PATH . "/$pageName." . BLOG_EXT . ".date";
if (file_exists($file)) {
return file_get_contents($file);
} else {
return date($date_format, $pageDate);
}
}
function descLengthSort($val_1, $val_2) {
$firstVal = strlen($val_1);
$secondVal = strlen($val_2);
return ( $firstVal > $secondVal ) ?
-1 : ( ( $firstVal < $secondVal ) ? 1 : 0);
}
function getAllPageNames($path = "") {
$filenames = array();
$dir = opendir(BLOG_PATH . "/$path" );
while ( $filename = readdir($dir) ) {
if ( $filename[0] == "." ) {
continue;
}
if ( is_dir( BLOG_PATH . "/$path/$filename" ) ) {
array_push($filenames, ...getAllPageNames( "$path/$filename" ) );
continue;
}
if ( preg_match("/".BLOG_EXT."$/", $filename) != 1) {
continue;
}
$filename = substr($filename, 0, -(strlen(BLOG_EXT)+1) );
$filenames[] = substr("$path/$filename", 1);
}
closedir($dir);
return $filenames;
}
function fileNameForPage($page) {
return BLOG_PATH . "/$page." . BLOG_EXT;
}
function dateForPage($page) {
$file = BLOG_PATH . "/$page." . BLOG_EXT . ".date";
if (!file_exists($file)) {
return filectime(BLOG_PATH . "/$page." . BLOG_EXT);
} else {
return file_get_contents($file);
}
}
function numForPage($page) {
$file = BLOG_PATH . "/$page." . BLOG_EXT . ".num";
return file_get_contents($file);
}
function sanitizeFilename($inFileName) {
return str_replace(array('~', '..', '\\', ':', '|', '&'), '-', $inFileName);
}
function pageURL($page) {
return SELF . VIEW . "/".str_replace("%2F", "/", str_replace("%23", "#", urlencode(sanitizeFilename($page))));
}
function pageLink($page, $title, $attributes="") {
return "<a href=\"" . pageURL($page) ."\"$attributes>$title</a>";
}
function redirectWithMessage($page, $msg) {
$_SESSION["msg"] = $msg;
header("HTTP/1.1 303 See Other");
header("Location: " . pageURL($page) );
exit;
}
function checkedExecute(&$msg, $cmd) {
$returnValue = 0;
$output = '';
exec($cmd, $output, $returnValue);
if ($returnValue != 0) {
$msg .= "<br/>Error executing command ".$cmd." (return value: ".$returnValue."): ".implode(" ", $output);
}
return ($returnValue == 0);
}
function toHTMLID($noid) {
return str_replace(" ", "-", $noid);
}
function toHTML($inText) {
$parser = new MarkdownExtra;
$parser->no_markup = true;
$outHTML = $parser->transform($inText);
preg_match_all("/\[\[(.*?)\]\]/", $outHTML, $matches, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($matches[0]); $i++) {
$fullLinkText = $matches[1][$i];
$linkTitleSplit = explode('|', $fullLinkText);
$linkedPage = $linkTitleSplit[0]; // split away an eventual link text
$linkText = (count($linkTitleSplit) > 1) ? $linkTitleSplit[1] : $linkedPage;
$pagePart = explode('#', $linkedPage)[0]; // split away an eventual anchor part
$linkedFilename = fileNameForPage(sanitizeFilename($pagePart));
$exists = file_exists($linkedFilename);
$outHTML = str_replace("[[$fullLinkText]]",
pageLink($linkedPage, $linkText, ($exists? "" : " class=\"noexist\"")), $outHTML);
}
$outHTML = preg_replace("/\{\{(.*?)\}\}/", "<img src=\"" . BASE_URI . "/images/\\1\" alt=\"\\1\" />", $outHTML);
preg_match_all("/<h([1-4])>(.*?)<\/h\\1>/", $outHTML, $matches, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($matches[0]); $i++) {
$prefix = "<h".$matches[1][$i].">";
$caption = $matches[2][$i];
$suffix = substr_replace($prefix, "/", 1, 0);
$outHTML = str_replace("$prefix$caption$suffix",
"$prefix<a id=\"".toHTMLID($caption)."\">$caption</a>$suffix", $outHTML);
}
return $outHTML;
}
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view';
$newPage = "";
$text = "";
$html = "";
if ($action === 'view') {
$page = preg_match('@^/@', @$_SERVER["PATH_INFO"]) ?
urldecode(substr($_SERVER["PATH_INFO"], 1)) : urldecode(@$_REQUEST['page']);
$page = sanitizeFilename($page);
if ($page != '') {
$filename = fileNameForPage($page);
if ( file_exists($filename) ) {
$text = file_get_contents($filename);
} else {
$newPage = NULL;
include('php/404.php');
die();
}
} else {
$action = 'home';
}
}
if ( $action === 'home') {
$pageNames = getAllPageNames();
$filelist = array();
$sortBy = isset($_REQUEST['sortBy']) ? $_REQUEST['sortBy'] : 'name';
foreach($pageNames as $page) {
$filelist[$page] = numForPage($page);
}
arsort($filelist, SORT_NUMERIC);
// Page list
$date_format = __('date_format', TITLE_DATE);
foreach ($filelist as $pageName => $pageDate) {
$html .= "<p>".pageLink($pageName, $pageName).", written ".getDateForPage($pageName, $date_format, $pageDate)."</p>\n";
}
} else { // convert the page and view it
$html .= empty($text) ? '' : toHTML($text);
}
// All blog posts
$datetime = '';
if (($action === 'home')) {
$title = __("Blog posts");
} else if ($filename != '') {
$title = $page;
$date_format = __('date_format', TITLE_DATE);
if ( $date_format ) {
$datetime = "<span class=\"titledate\">" . date($date_format, @filectime($filename)) . "</span>";
}
}
// print text
printHeader($title, $action, $html);
print " <div class=\"content\">\n\n";
print "$html\n";
print " </div>\n";
print " </html>\n";
printFooter();