summaryrefslogtreecommitdiffstats
path: root/core
diff options
context:
space:
mode:
Diffstat (limited to 'core')
-rw-r--r--core/application.php136
-rw-r--r--core/configuration-example.php103
-rw-r--r--core/functions.php322
-rw-r--r--core/language/de.php194
-rw-r--r--core/language/en.php194
-rw-r--r--core/namespace/Application.php148
-rw-r--r--core/namespace/Attribute.php74
-rw-r--r--core/namespace/AttributeInterface.php7
-rw-r--r--core/namespace/Database.php7
-rw-r--r--core/namespace/ExceptionHandler.php8
-rw-r--r--core/namespace/Factory.php19
-rw-r--r--core/namespace/FactoryInterface.php5
-rw-r--r--core/namespace/HTTP.php234
-rw-r--r--core/namespace/Item.php150
-rw-r--r--core/namespace/ItemFactory.php12
-rw-r--r--core/namespace/ItemInterface.php5
-rw-r--r--core/namespace/Language.php48
-rw-r--r--core/namespace/Page/Attribute.php22
-rw-r--r--core/namespace/Page/Exception.php5
-rw-r--r--core/namespace/Page/Factory.php9
-rw-r--r--core/namespace/Page/Item.php29
-rw-r--r--core/namespace/Parsedown.php1548
-rw-r--r--core/namespace/Post/Attribute.php22
-rw-r--r--core/namespace/Post/Exception.php5
-rw-r--r--core/namespace/Post/Factory.php9
-rw-r--r--core/namespace/Post/Item.php50
-rw-r--r--core/namespace/Template/Exception.php5
-rw-r--r--core/namespace/Template/Factory.php18
-rw-r--r--core/namespace/Template/Template.php72
-rw-r--r--core/namespace/User/Attribute.php24
-rw-r--r--core/namespace/User/Exception.php5
-rw-r--r--core/namespace/User/Factory.php13
-rw-r--r--core/namespace/User/Item.php36
33 files changed, 3538 insertions, 0 deletions
diff --git a/core/application.php b/core/application.php
new file mode 100644
index 0000000..58dd728
--- /dev/null
+++ b/core/application.php
@@ -0,0 +1,136 @@
+<?php
+#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
+# Application initialization [Thomas Lange <code@nerdmind.de>] #
+#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
+# #
+# This file is included by each file from the system or admin directory. #
+# #
+#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
+
+#===============================================================================
+# Document root
+#===============================================================================
+define('ROOT', dirname(__DIR__).'/');
+
+#===============================================================================
+# Autoload register for classes
+#===============================================================================
+spl_autoload_register(function($classname) {
+ $classname = str_replace('\\', '/', $classname);
+ require_once "namespace/{$classname}.php";
+});
+
+#===============================================================================
+# Exception handler for non-caught exceptions
+#===============================================================================
+set_exception_handler(function($Exception) {
+ http_response_code(503);
+ exit($Exception->getMessage());
+});
+
+#===============================================================================
+# Initialize HTTP class and remove all arrays from $_GET and $_POST
+#===============================================================================
+HTTP::init($_GET, $_POST, $_FILES, TRUE);
+
+#===============================================================================
+# Include configuration
+#===============================================================================
+require_once 'configuration.php';
+
+#===============================================================================
+# Overwrite configuration if admin
+#===============================================================================
+if(defined('ADMINISTRATION') AND ADMINISTRATION === TRUE) {
+
+ #===========================================================================
+ # Enable sessions
+ #===========================================================================
+ session_start();
+
+ #===========================================================================
+ # Authentication check
+ #===========================================================================
+ if(defined('AUTHENTICATION') AND !Application::isAuthenticated()) {
+ HTTP::redirect(Application::getAdminURL('auth.php'));
+ }
+
+ #===========================================================================
+ # Overwrite configuration
+ #===========================================================================
+ Application::set('CORE.LANGUAGE', Application::get('ADMIN.LANGUAGE'));
+ Application::set('TEMPLATE.NAME', Application::get('ADMIN.TEMPLATE'));
+ Application::set('TEMPLATE.LANG', Application::get('ADMIN.LANGUAGE'));
+}
+
+#===============================================================================
+# Include functions
+#===============================================================================
+require_once 'functions.php';
+
+#===============================================================================
+# TRY: PDOException
+#===============================================================================
+try {
+ $Language = Application::getLanguage();
+ $Database = Application::getDatabase();
+
+ $Database->setAttribute($Database::ATTR_DEFAULT_FETCH_MODE, $Database::FETCH_OBJ);
+ $Database->setAttribute($Database::ATTR_ERRMODE, $Database::ERRMODE_EXCEPTION);
+}
+
+#===============================================================================
+# CATCH: PDOException
+#===============================================================================
+catch(PDOException $Exception) {
+ http_response_code(503);
+ exit("PDO database connection error: {$Exception->getMessage()}");
+}
+
+#===============================================================================
+# Check if "304 Not Modified" and ETag header should be send
+#===============================================================================
+if(Application::get('CORE.SEND_304') === TRUE AND !defined('ADMINISTRATION')) {
+ #===========================================================================
+ # Select edit time from last edited items (page, post, user)
+ #===========================================================================
+ $execute = 'SELECT time_update FROM %s ORDER BY time_update DESC LIMIT 1';
+
+ $PageStatement = $Database->query(sprintf($execute, Page\Attribute::TABLE));
+ $PostStatement = $Database->query(sprintf($execute, Post\Attribute::TABLE));
+ $UserStatement = $Database->query(sprintf($execute, User\Attribute::TABLE));
+
+ #===========================================================================
+ # Define HTTP ETag header identifier
+ #===========================================================================
+ $HTTP_ETAG_IDENTIFIER = sha1(implode(NULL, [
+ serialize(Application::getConfiguration()),
+ $PageStatement->fetchColumn(),
+ $PostStatement->fetchColumn(),
+ $UserStatement->fetchColumn(),
+ 'CUSTOM-STRING-0123456789'
+ ]));
+
+ #===========================================================================
+ # Send ETag header within the HTTP response
+ #===========================================================================
+ HTTP::responseHeader(HTTP::HEADER_ETAG, "\"{$HTTP_ETAG_IDENTIFIER}\"");
+
+ #===========================================================================
+ # Validate ETag header from the HTTP request
+ #===========================================================================
+ if(isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
+ $HTTP_IF_NONE_MATCH = $_SERVER['HTTP_IF_NONE_MATCH'];
+ $HTTP_IF_NONE_MATCH = trim($HTTP_IF_NONE_MATCH, '"');
+
+ # If the server adds the extensions to the response header
+ $HTTP_IF_NONE_MATCH = rtrim($HTTP_IF_NONE_MATCH, '-br');
+ $HTTP_IF_NONE_MATCH = rtrim($HTTP_IF_NONE_MATCH, '-gzip');
+
+ if($HTTP_IF_NONE_MATCH === $HTTP_ETAG_IDENTIFIER) {
+ http_response_code(304);
+ exit();
+ }
+ }
+}
+?> \ No newline at end of file
diff --git a/core/configuration-example.php b/core/configuration-example.php
new file mode 100644
index 0000000..80192cf
--- /dev/null
+++ b/core/configuration-example.php
@@ -0,0 +1,103 @@
+<?php
+#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
+# Application configuration [Thomas Lange <code@nerdmind.de>] #
+#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
+# #
+# [see documentation] #
+# #
+#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
+
+#===============================================================================
+# Core configuration
+#===============================================================================
+Application::set('CORE.LANGUAGE', 'en');
+Application::set('CORE.SEND_304', FALSE);
+
+#===============================================================================
+# Blog configuration
+#===============================================================================
+Application::set('BLOGMETA.NAME', 'My Techblog');
+Application::set('BLOGMETA.DESC', '[a creative description]');
+Application::set('BLOGMETA.HOME', 'Home');
+Application::set('BLOGMETA.MAIL', 'mail@example.org');
+Application::set('BLOGMETA.LANG', 'en');
+
+#===============================================================================
+# Settings for database connection
+#===============================================================================
+Application::set('DATABASE.HOSTNAME', 'localhost');
+Application::set('DATABASE.BASENAME', 'blog');
+Application::set('DATABASE.USERNAME', '');
+Application::set('DATABASE.PASSWORD', '');
+
+#===============================================================================
+# Backend configuration
+#===============================================================================
+Application::set('ADMIN.TEMPLATE', 'admin');
+Application::set('ADMIN.LANGUAGE', Application::get('CORE.LANGUAGE'));
+
+#===============================================================================
+# Settings for template configuration
+#===============================================================================
+Application::set('TEMPLATE.NAME', 'standard');
+Application::set('TEMPLATE.LANG', Application::get('CORE.LANGUAGE'));
+
+#===============================================================================
+# Protocol, hostname and path for this installation
+#===============================================================================
+Application::set('PATHINFO.PROT', isset($_SERVER['HTTPS']) ? 'https' : 'http');
+Application::set('PATHINFO.HOST', $_SERVER['HTTP_HOST']);
+Application::set('PATHINFO.BASE', '');
+
+#===============================================================================
+# Enable or disable the use of slug URLs for item permalinks
+#===============================================================================
+Application::set('PAGE.SLUG_URLS', TRUE);
+Application::set('POST.SLUG_URLS', TRUE);
+Application::set('USER.SLUG_URLS', TRUE);
+
+#===============================================================================
+# Number of items to display on feed and overview sites
+#===============================================================================
+Application::set('PAGE.LIST_SIZE', 10);
+Application::set('POST.LIST_SIZE', 10);
+Application::set('USER.LIST_SIZE', 10);
+Application::set('PAGE.FEED_SIZE', 25);
+Application::set('POST.FEED_SIZE', 25);
+
+#===============================================================================
+# Settings for item URL generation (you have to change the .htaccess as well!)
+#===============================================================================
+Application::set('PAGE.DIRECTORY', 'page');
+Application::set('POST.DIRECTORY', 'post');
+Application::set('USER.DIRECTORY', 'user');
+
+#===============================================================================
+# Enable or disable the use of emoticons for item content
+#===============================================================================
+Application::set('PAGE.EMOTICONS', TRUE);
+Application::set('POST.EMOTICONS', TRUE);
+Application::set('USER.EMOTICONS', TRUE);
+
+#===============================================================================
+# Number of characters to display in the items <meta> description
+#===============================================================================
+Application::set('PAGE.DESCRIPTION_SIZE', 200);
+Application::set('POST.DESCRIPTION_SIZE', 200);
+Application::set('USER.DESCRIPTION_SIZE', 200);
+
+#===============================================================================
+# "ORDER BY" clause for item sorting on feed and overview sites
+#===============================================================================
+Application::set('PAGE.LIST_SORT', 'time_insert DESC');
+Application::set('POST.LIST_SORT', 'time_insert DESC');
+Application::set('USER.LIST_SORT', 'time_insert DESC');
+Application::set('PAGE.FEED_SORT', 'time_insert DESC');
+Application::set('POST.FEED_SORT', 'time_insert DESC');
+
+#===============================================================================
+# Item attributes used to generate the <guid> hash for feed items
+#===============================================================================
+Application::set('PAGE.FEED_GUID', ['id', 'time_insert']);
+Application::set('POST.FEED_GUID', ['id', 'time_insert']);
+?> \ No newline at end of file
diff --git a/core/functions.php b/core/functions.php
new file mode 100644
index 0000000..726e96f
--- /dev/null
+++ b/core/functions.php
@@ -0,0 +1,322 @@
+<?php
+#===============================================================================
+# Helper function to reduce duplicate code
+#===============================================================================
+function generatePageNaviTemplate($currentSite): Template\Template {
+ $Database = Application::getDatabase();
+ $Statement = $Database->query(sprintf('SELECT COUNT(id) FROM %s', Page\Attribute::TABLE));
+
+ $lastSite = ceil($Statement->fetchColumn() / Application::get('PAGE.LIST_SIZE'));
+
+ $PaginationTemplate = Template\Factory::build('pagination');
+ $PaginationTemplate->set('THIS', $currentSite);
+ $PaginationTemplate->set('LAST', $lastSite);
+ $PaginationTemplate->set('HREF', Application::getPageURL('?site=%d'));
+
+ return $PaginationTemplate;
+}
+
+#===============================================================================
+# Helper function to reduce duplicate code
+#===============================================================================
+function generatePostNaviTemplate($currentSite): Template\Template {
+ $Database = Application::getDatabase();
+ $Statement = $Database->query(sprintf('SELECT COUNT(id) FROM %s', Post\Attribute::TABLE));
+
+ $lastSite = ceil($Statement->fetchColumn() / Application::get('POST.LIST_SIZE'));
+
+ $PaginationTemplate = Template\Factory::build('pagination');
+ $PaginationTemplate->set('THIS', $currentSite);
+ $PaginationTemplate->set('LAST', $lastSite);
+ $PaginationTemplate->set('HREF', Application::getPostURL('?site=%d'));
+
+ return $PaginationTemplate;
+}
+
+#===============================================================================
+# Helper function to reduce duplicate code
+#===============================================================================
+function generateUserNaviTemplate($currentSite): Template\Template {
+ $Database = Application::getDatabase();
+ $Statement = $Database->query(sprintf('SELECT COUNT(id) FROM %s', User\Attribute::TABLE));
+
+ $lastSite = ceil($Statement->fetchColumn() / Application::get('USER.LIST_SIZE'));
+
+ $PaginationTemplate = Template\Factory::build('pagination');
+ $PaginationTemplate->set('THIS', $currentSite);
+ $PaginationTemplate->set('LAST', $lastSite);
+ $PaginationTemplate->set('HREF', Application::getUserURL('?site=%d'));
+
+ return $PaginationTemplate;
+}
+
+#===============================================================================
+# Helper function to reduce duplicate code
+#===============================================================================
+function generatePageItemTemplate(Page\Item $Page, User\Item $User): Template\Template {
+ $Template = Template\Factory::build('page/item');
+ $Template->set('PAGE', generatePageItemData($Page));
+ $Template->set('USER', generateUserItemData($User));
+
+ return $Template;
+}
+
+#===============================================================================
+# Helper function to reduce duplicate code
+#===============================================================================
+function generatePostItemTemplate(Post\Item $Post, User\Item $User): Template\Template {
+ $Template = Template\Factory::build('post/item');
+ $Template->set('POST', generatePostItemData($Post));
+ $Template->set('USER', generateUserItemData($User));
+
+ return $Template;
+}
+
+#===============================================================================
+# Helper function to reduce duplicate code
+#===============================================================================
+function generateUserItemTemplate(User\Item $User): Template\Template {
+ $Template = Template\Factory::build('user/item');
+ $Template->set('USER', generateUserItemData($User));
+
+ return $Template;
+}
+
+#===============================================================================
+# Helper function to reduce duplicate code
+#===============================================================================
+function generateItemData(Item $Item): array {
+ return [
+ 'ID' => $Item->getID(),
+ 'URL' => $Item->getURL(),
+ 'GUID' => $Item->getGUID(),
+
+ 'PREV' => FALSE,
+ 'NEXT' => FALSE,
+
+ 'FILE' => [
+ 'LIST' => $Item->getFiles()
+ ],
+
+ 'BODY' => [
+ 'TEXT' => $Item->getBody(),
+ 'HTML' => $Item->getHTML()
+ ],
+
+ 'ATTR' => [
+ 'USER' => $Item->attr('user'),
+ 'SLUG' => $Item->attr('slug'),
+ 'NAME' => $Item->attr('name'),
+ 'BODY' => $Item->attr('body'),
+ 'TIME_INSERT' => $Item->attr('time_insert'),
+ 'TIME_UPDATE' => $Item->attr('time_update')
+ ]
+ ];
+}
+
+#===============================================================================
+# Helper function to reduce duplicate code
+#===============================================================================
+function generatePageItemData(Page\Item $Page): array {
+ return generateItemData($Page);
+}
+
+#===============================================================================
+# Helper function to reduce duplicate code
+#===============================================================================
+function generatePostItemData(Post\Item $Post): array {
+ return generateItemData($Post);
+}
+
+#===============================================================================
+# Helper function to reduce duplicate code
+#===============================================================================
+function generateUserItemData(User\Item $User): array {
+ return [
+ 'ID' => $User->getID(),
+ 'URL' => $User->getURL(),
+ 'GUID' => $User->getGUID(),
+
+ 'PREV' => FALSE,
+ 'NEXT' => FALSE,
+
+ 'FILE' => [
+ 'LIST' => $User->getFiles()
+ ],
+
+ 'BODY' => [
+ 'TEXT' => $User->getBody(),
+ 'HTML' => $User->getHTML()
+ ],
+
+ 'ATTR' => [
+ 'SLUG' => $User->attr('slug'),
+ 'BODY' => $User->attr('body'),
+ 'USERNAME' => $User->attr('username'),
+ 'FULLNAME' => $User->attr('fullname'),
+ 'MAILADDR' => $User->attr('mailaddr'),
+ 'TIME_INSERT' => $User->attr('time_insert'),
+ 'TIME_UPDATE' => $User->attr('time_update')
+ ]
+ ];
+}
+
+#===============================================================================
+# Parser for datetime formatted strings [YYYY-MM-DD HH:II:SS]
+#===============================================================================
+function parseDatetime($datetime, $format): string {
+ $Language = Application::getLanguage();
+
+ list($date, $time) = explode(' ', $datetime);
+
+ list($DATE['Y'], $DATE['M'], $DATE['D']) = explode('-', $date);
+ list($TIME['H'], $TIME['M'], $TIME['S']) = explode(':', $time);
+
+ $M_LIST = [
+ '01' => $Language->text('month_01'),
+ '02' => $Language->text('month_02'),
+ '03' => $Language->text('month_03'),
+ '04' => $Language->text('month_04'),
+ '05' => $Language->text('month_05'),
+ '06' => $Language->text('month_06'),
+ '07' => $Language->text('month_07'),
+ '08' => $Language->text('month_08'),
+ '09' => $Language->text('month_09'),
+ '10' => $Language->text('month_10'),
+ '11' => $Language->text('month_11'),
+ '12' => $Language->text('month_12'),
+ ];
+
+ $D_LIST = [
+ 0 => $Language->text('day_6'),
+ 1 => $Language->text('day_0'),
+ 2 => $Language->text('day_1'),
+ 3 => $Language->text('day_2'),
+ 4 => $Language->text('day_3'),
+ 5 => $Language->text('day_4'),
+ 6 => $Language->text('day_5'),
+ ];
+
+ return strtr($format, [
+ '[Y]' => $DATE['Y'],
+ '[M]' => $DATE['M'],
+ '[D]' => $DATE['D'],
+ '[H]' => $TIME['H'],
+ '[I]' => $TIME['M'],
+ '[S]' => $TIME['S'],
+ '[W]' => $D_LIST[date('w', strtotime($datetime))],
+ '[F]' => $M_LIST[date('m', strtotime($datetime))],
+ '[DATE]' => $date,
+ '[TIME]' => $time,
+ '[RFC2822]' => date('r', strtotime($datetime))
+ ]);
+}
+
+#===============================================================================
+# Get emoticons with unicode characters and description
+#===============================================================================
+function getEmoticons(): array {
+ $Language = Application::getLanguage();
+
+ return [
+ ':)' => ['&#x1F60A;', $Language->text('emoticon_1F60A')],
+ ':(' => ['&#x1F61E;', $Language->text('emoticon_1F61E')],
+ ':D' => ['&#x1F603;', $Language->text('emoticon_1F603')],
+ ':P' => ['&#x1F61B;', $Language->text('emoticon_1F61B')],
+ ':O' => ['&#x1F632;', $Language->text('emoticon_1F632')],
+ ';)' => ['&#x1F609;', $Language->text('emoticon_1F609')],
+ ';(' => ['&#x1F622;', $Language->text('emoticon_1F622')],
+ ':|' => ['&#x1F610;', $Language->text('emoticon_1F610')],
+ ':X' => ['&#x1F635;', $Language->text('emoticon_1F635')],
+ ':/' => ['&#x1F612;', $Language->text('emoticon_1F612')],
+ '8)' => ['&#x1F60E;', $Language->text('emoticon_1F60E')],
+ ':S' => ['&#x1F61F;', $Language->text('emoticon_1F61F')],
+ 'xD' => ['&#x1F602;', $Language->text('emoticon_1F602')],
+ '^^' => ['&#x1F604;', $Language->text('emoticon_1F604')],
+ ];
+}
+
+#===============================================================================
+# Parse emoticons to HTML encoded unicode characters
+#===============================================================================
+function parseEmoticons($string): string {
+ foreach(getEmoticons() as $emoticon => $data) {
+ $pattern = '#(^|\s)'.preg_quote($emoticon).'#';
+ $replace = " <span title=\"{$data[1]}\">{$data[0]}</span>";
+
+ $string = preg_replace($pattern, $replace, $string);
+ }
+
+ return $string;
+}
+
+#===============================================================================
+# Wrapper function for htmlspecialchars()
+#===============================================================================
+function escapeHTML($string): string {
+ return htmlspecialchars($string);
+}
+
+#===============================================================================
+# Wrapper function for strip_tags()
+#===============================================================================
+function removeHTML($string): string {
+ return strip_tags($string);
+}
+
+#===============================================================================
+# Remove all double line breaks from string
+#===============================================================================
+function removeDoubleLineBreaks($string): string {
+ return preg_replace('#(\r?\n){2,}#', "\n\n", $string);
+}
+
+#===============================================================================
+# Remove line breaks and tabs from a string
+#===============================================================================
+function removeLineBreaksAndTabs($string, $replace = ''): string {
+ return str_replace(["\r\n", "\r", "\n", "\t"], $replace, $string);
+}
+
+#===============================================================================
+# Return pseudo-random (hex converted) string
+#===============================================================================
+function getRandomValue($length = 40): string {
+ return strtoupper(bin2hex(random_bytes(ceil($length / 2))));
+}
+
+#===============================================================================
+# Return cutted string
+#===============================================================================
+function cut($string, $length, $replace = ' […]') {
+ if(mb_strlen($string) > $length) {
+ return preg_replace("/^(.{1,{$length}}\\b).*/su", "\\1{$replace}", $string);
+ }
+
+ return $string;
+}
+
+#===============================================================================
+# Return excerpt content
+#===============================================================================
+function excerpt($string, $length = 500, $replace = ' […]') {
+ $string = removeHTML($string);
+ $string = removeDoubleLineBreaks($string);
+ $string = cut($string, $length, $replace);
+ $string = nl2br($string);
+
+ return $string;
+}
+
+#====================================================================================================
+# Generate a valid slug URL part from a string
+#====================================================================================================
+function makeSlugURL($string) {
+ $string = strtolower($string);
+ $string = str_replace(['ä', 'ö', 'ü', 'ß'], ['ae', 'oe', 'ue', 'ss'], $string);
+ $string = preg_replace('/[^a-zA-Z0-9\-]/', '-', $string);
+ $string = preg_replace('/-+/', '-', $string);
+
+ return trim($string, '-');
+}
+?>
diff --git a/core/language/de.php b/core/language/de.php
new file mode 100644
index 0000000..dc6e924
--- /dev/null
+++ b/core/language/de.php
@@ -0,0 +1,194 @@
+<?php
+#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
+# Internationalization [DE] [Thomas Lange <code@nerdmind.de>] #
+#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
+# #
+# This file contains core internationalization strings for the DE language. If #
+# you are a translator, please only use the original EN language file for your #
+# translation and open a pull request on GitHub or send your language file via #
+# email back to <code@nerdmind.de>. #
+# #
+#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
+
+#===============================================================================
+# Date element names
+#===============================================================================
+$LANGUAGE['date_d'] = 'Tag';
+$LANGUAGE['date_m'] = 'Monat';
+$LANGUAGE['date_y'] = 'Jahr';
+
+#===============================================================================
+# Time element names
+#===============================================================================
+$LANGUAGE['time_h'] = 'Stunde';
+$LANGUAGE['time_m'] = 'Minute';
+$LANGUAGE['time_s'] = 'Sekunde';
+
+#===============================================================================
+# Day names
+#===============================================================================
+$LANGUAGE['day_0'] = 'Montag';
+$LANGUAGE['day_1'] = 'Dienstag';
+$LANGUAGE['day_2'] = 'Mittwoch';
+$LANGUAGE['day_3'] = 'Donnerstag';
+$LANGUAGE['day_4'] = 'Freitag';
+$LANGUAGE['day_5'] = 'Samstag';
+$LANGUAGE['day_6'] = 'Sonntag';
+
+#===============================================================================
+# Month names
+#===============================================================================
+$LANGUAGE['month_01'] = 'Januar';
+$LANGUAGE['month_02'] = 'Februar';
+$LANGUAGE['month_03'] = 'März';
+$LANGUAGE['month_04'] = 'April';
+$LANGUAGE['month_05'] = 'Mai';
+$LANGUAGE['month_06'] = 'Juni';
+$LANGUAGE['month_07'] = 'Juli';
+$LANGUAGE['month_08'] = 'August';
+$LANGUAGE['month_09'] = 'September';
+$LANGUAGE['month_10'] = 'Oktober';
+$LANGUAGE['month_11'] = 'November';
+$LANGUAGE['month_12'] = 'Dezember';
+
+#===============================================================================
+# Emoticon explanations
+#===============================================================================
+$LANGUAGE['emoticon_1F60A'] = 'Lächelndes Gesicht mit lächelnden Augen';
+$LANGUAGE['emoticon_1F61E'] = 'Enttäuschtes Gesicht';
+$LANGUAGE['emoticon_1F603'] = 'Lächelndes Gesicht mit offenem Mund';
+$LANGUAGE['emoticon_1F61B'] = 'Gesicht mit herausgestreckter Zunge';
+$LANGUAGE['emoticon_1F632'] = 'Erstauntes Gesicht';
+$LANGUAGE['emoticon_1F609'] = 'Zwinkerndes Gesicht';
+$LANGUAGE['emoticon_1F622'] = 'Weinendes Gesicht';
+$LANGUAGE['emoticon_1F610'] = 'Neutrales Gesicht';
+$LANGUAGE['emoticon_1F635'] = 'Schwindeliges Gesicht';
+$LANGUAGE['emoticon_1F612'] = 'Frustriertes Gesicht';
+$LANGUAGE['emoticon_1F60E'] = 'Lächelndes Gesicht mit Sonnenbrille';
+$LANGUAGE['emoticon_1F61F'] = 'Besorgtes Gesicht';
+$LANGUAGE['emoticon_1F602'] = 'Gesicht mit Freudentränen';
+$LANGUAGE['emoticon_1F604'] = 'Lächelndes Gesicht mit offenem Mund und lachenden Augen';
+
+#===============================================================================
+# Error messages
+#===============================================================================
+$LANGUAGE['error_security_csrf'] = 'Der Sicherheitstoken stimmt nicht mit dem Sicherheitstoken des Servers überein.';
+$LANGUAGE['error_database_exec'] = 'Es ist ein unerwarteter Fehler bei der Kommunikation mit der Datenbank aufgetreten.';
+
+#===============================================================================
+# Fulltext search
+#===============================================================================
+$LANGUAGE['search_no_results'] = 'Entschuldigung, es wurden keine Ergebnisse für "%s" gefunden.';
+
+#===============================================================================
+# Authentication
+#===============================================================================
+$LANGUAGE['authentication_failure'] = 'Der Benutzername oder das Passwort ist nicht korrekt.';
+
+#===============================================================================
+# Items [singular]
+#===============================================================================
+$LANGUAGE['page'] = 'Seite';
+$LANGUAGE['post'] = 'Beitrag';
+$LANGUAGE['user'] = 'Benutzer';
+
+#===============================================================================
+# Items [plural]
+#===============================================================================
+$LANGUAGE['pages'] = 'Seiten';
+$LANGUAGE['posts'] = 'Beiträge';
+$LANGUAGE['users'] = 'Benutzer';
+
+#===============================================================================
+# Actions
+#===============================================================================
+$LANGUAGE['select'] = 'Anzeigen';
+$LANGUAGE['insert'] = 'Erstellen';
+$LANGUAGE['update'] = 'Bearbeiten';
+$LANGUAGE['delete'] = 'Löschen';
+$LANGUAGE['search'] = 'Suchen';
+$LANGUAGE['remove'] = 'Entfernen';
+
+#===============================================================================
+# Previous items
+#===============================================================================
+$LANGUAGE['prev_page'] = 'Vorherige Seite';
+$LANGUAGE['prev_post'] = 'Vorheriger Beitrag';
+$LANGUAGE['prev_user'] = 'Vorheriger Benutzer';
+
+#===============================================================================
+# Next items
+#===============================================================================
+$LANGUAGE['next_page'] = 'Nächste Seite';
+$LANGUAGE['next_post'] = 'Nächster Beitrag';
+$LANGUAGE['next_user'] = 'Nächster Benutzer';
+
+#===============================================================================
+# Item overview
+#===============================================================================
+$LANGUAGE['page_overview'] = 'Seitenübersicht';
+$LANGUAGE['post_overview'] = 'Beitragübersicht';
+$LANGUAGE['user_overview'] = 'Benutzerübersicht';
+
+#===============================================================================
+# Items select
+#===============================================================================
+$LANGUAGE['select_page'] = 'Seite anzeigen';
+$LANGUAGE['select_post'] = 'Beitrag anzeigen';
+$LANGUAGE['select_user'] = 'Benutzer anzeigen';
+
+#===============================================================================
+# Items insert
+#===============================================================================
+$LANGUAGE['insert_page'] = 'Seite erstellen';
+$LANGUAGE['insert_post'] = 'Beitrag erstellen';
+$LANGUAGE['insert_user'] = 'Benutzer erstellen';
+
+#===============================================================================
+# Items update
+#===============================================================================
+$LANGUAGE['update_page'] = 'Seite bearbeiten';
+$LANGUAGE['update_post'] = 'Beitrag bearbeiten';
+$LANGUAGE['update_user'] = 'Benutzer bearbeiten';
+
+#===============================================================================
+# Items delete
+#===============================================================================
+$LANGUAGE['delete_page'] = 'Seite löschen';
+$LANGUAGE['delete_post'] = 'Beitrag löschen';
+$LANGUAGE['delete_user'] = 'Benutzer löschen';
+
+#===============================================================================
+# Item insert titles
+#===============================================================================
+$LANGUAGE['title_page_insert'] = $LANGUAGE['insert_page'];
+$LANGUAGE['title_post_insert'] = $LANGUAGE['insert_post'];
+$LANGUAGE['title_user_insert'] = $LANGUAGE['insert_user'];
+
+#===============================================================================
+# Item update titles
+#===============================================================================
+$LANGUAGE['title_page_update'] = $LANGUAGE['update_page'];
+$LANGUAGE['title_post_update'] = $LANGUAGE['update_post'];
+$LANGUAGE['title_user_update'] = $LANGUAGE['update_user'];
+
+#===============================================================================
+# Item delete titles
+#===============================================================================
+$LANGUAGE['title_page_delete'] = $LANGUAGE['delete_page'];
+$LANGUAGE['title_post_delete'] = $LANGUAGE['delete_post'];
+$LANGUAGE['title_user_delete'] = $LANGUAGE['delete_user'];
+
+#===============================================================================
+# Item overview titles
+#===============================================================================
+$LANGUAGE['title_page_overview'] = "{$LANGUAGE['page_overview']} [%d]";
+$LANGUAGE['title_post_overview'] = "{$LANGUAGE['post_overview']} [%d]";
+$LANGUAGE['title_user_overview'] = "{$LANGUAGE['user_overview']} [%d]";
+
+#===============================================================================
+# Search titles
+#===============================================================================
+$LANGUAGE['title_search_request'] = 'Volltextsuche';
+$LANGUAGE['title_search_results'] = 'Ergebnisse für "%s"';
+?> \ No newline at end of file
diff --git a/core/language/en.php b/core/language/en.php
new file mode 100644
index 0000000..3e48191
--- /dev/null
+++ b/core/language/en.php
@@ -0,0 +1,194 @@
+<?php
+#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
+# Internationalization [EN] [Thomas Lange <code@nerdmind.de>] #
+#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
+# #
+# This file contains core internationalization strings for the EN language. If #
+# you are a translator, please only use the original EN language file for your #
+# translation and open a pull request on GitHub or send your language file via #
+# email back to <code@nerdmind.de>. #
+# #
+#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
+
+#===============================================================================
+# Date element names
+#===============================================================================
+$LANGUAGE['date_d'] = 'Day';
+$LANGUAGE['date_m'] = 'Month';
+$LANGUAGE['date_y'] = 'Year';
+
+#===============================================================================
+# Time element names
+#===============================================================================
+$LANGUAGE['time_h'] = 'Hour';
+$LANGUAGE['time_m'] = 'Minute';
+$LANGUAGE['time_s'] = 'Second';
+
+#===============================================================================
+# Day names
+#===============================================================================
+$LANGUAGE['day_0'] = 'Monday';
+$LANGUAGE['day_1'] = 'Tuesday';
+$LANGUAGE['day_2'] = 'Wednesday';
+$LANGUAGE['day_3'] = 'Thursday';
+$LANGUAGE['day_4'] = 'Friday';
+$LANGUAGE['day_5'] = 'Saturday';
+$LANGUAGE['day_6'] = 'Sunday';
+
+#===============================================================================
+# Month names
+#===============================================================================
+$LANGUAGE['month_01'] = 'January';
+$LANGUAGE['month_02'] = 'February';
+$LANGUAGE['month_03'] = 'March';
+$LANGUAGE['month_04'] = 'April';
+$LANGUAGE['month_05'] = 'May';
+$LANGUAGE['month_06'] = 'June';
+$LANGUAGE['month_07'] = 'July';
+$LANGUAGE['month_08'] = 'August';
+$LANGUAGE['month_09'] = 'September';
+$LANGUAGE['month_10'] = 'October';
+$LANGUAGE['month_11'] = 'November';
+$LANGUAGE['month_12'] = 'December';
+
+#===============================================================================
+# Emoticon explanations
+#===============================================================================
+$LANGUAGE['emoticon_1F60A'] = 'Smiling face with smiling eyes';
+$LANGUAGE['emoticon_1F61E'] = 'Disappointed face';
+$LANGUAGE['emoticon_1F603'] = 'Smiling face with open mouth';
+$LANGUAGE['emoticon_1F61B'] = 'Face with stuck-out tongue';
+$LANGUAGE['emoticon_1F632'] = 'Astonished face';
+$LANGUAGE['emoticon_1F609'] = 'Winking face';
+$LANGUAGE['emoticon_1F622'] = 'Crying face';
+$LANGUAGE['emoticon_1F610'] = 'Neutral face';
+$LANGUAGE['emoticon_1F635'] = 'Dizzy face';
+$LANGUAGE['emoticon_1F612'] = 'Unamused face';
+$LANGUAGE['emoticon_1F60E'] = 'Smiling face with sunglasses';
+$LANGUAGE['emoticon_1F61F'] = 'Worried face';
+$LANGUAGE['emoticon_1F602'] = 'Face with tears of joy';
+$LANGUAGE['emoticon_1F604'] = 'Smiling face with open mouth and smiling eyes';
+
+#===============================================================================
+# Error messages
+#===============================================================================
+$LANGUAGE['error_security_csrf'] = 'The security token does not matches the security token at server.';
+$LANGUAGE['error_database_exec'] = 'An unexpected error occurred while communicating with the database.';
+
+#===============================================================================
+# Fulltext search
+#===============================================================================
+$LANGUAGE['search_no_results'] = 'Sorry, there are no search results for "%s".';
+
+#===============================================================================
+# Authentication
+#===============================================================================
+$LANGUAGE['authentication_failure'] = 'The username or password is incorrect.';
+
+#===============================================================================
+# Items [singular]
+#===============================================================================
+$LANGUAGE['page'] = 'Page';
+$LANGUAGE['post'] = 'Post';
+$LANGUAGE['user'] = 'User';
+
+#===============================================================================
+# Items [plural]
+#===============================================================================
+$LANGUAGE['pages'] = 'Pages';
+$LANGUAGE['posts'] = 'Posts';
+$LANGUAGE['users'] = 'Users';
+
+#===============================================================================
+# Actions
+#===============================================================================
+$LANGUAGE['select'] = 'Show';
+$LANGUAGE['insert'] = 'Create';
+$LANGUAGE['update'] = 'Edit';
+$LANGUAGE['delete'] = 'Delete';
+$LANGUAGE['search'] = 'Search';
+$LANGUAGE['remove'] = 'Remove';
+
+#===============================================================================
+# Previous items
+#===============================================================================
+$LANGUAGE['prev_page'] = 'Previous page';
+$LANGUAGE['prev_post'] = 'Previous post';
+$LANGUAGE['prev_user'] = 'Previous user';
+
+#===============================================================================
+# Next items
+#===============================================================================
+$LANGUAGE['next_page'] = 'Next page';
+$LANGUAGE['next_post'] = 'Next post';
+$LANGUAGE['next_user'] = 'Next user';
+
+#===============================================================================
+# Item overview
+#===============================================================================
+$LANGUAGE['page_overview'] = 'Page overview';
+$LANGUAGE['post_overview'] = 'Post overview';
+$LANGUAGE['user_overview'] = 'User overview';
+
+#===============================================================================
+# Items select
+#===============================================================================
+$LANGUAGE['select_page'] = 'Show page';
+$LANGUAGE['select_post'] = 'Show post';
+$LANGUAGE['select_user'] = 'Show user';
+
+#===============================================================================
+# Items insert
+#===============================================================================
+$LANGUAGE['insert_page'] = 'Create page';
+$LANGUAGE['insert_post'] = 'Create post';
+$LANGUAGE['insert_user'] = 'Create user';
+
+#===============================================================================
+# Items update
+#===============================================================================
+$LANGUAGE['update_page'] = 'Edit page';
+$LANGUAGE['update_post'] = 'Edit post';
+$LANGUAGE['update_user'] = 'Edit user';
+
+#===============================================================================
+# Items delete
+#===============================================================================
+$LANGUAGE['delete_page'] = 'Delete page';
+$LANGUAGE['delete_post'] = 'Delete post';
+$LANGUAGE['delete_user'] = 'Delete user';
+
+#===============================================================================
+# Item insert titles
+#===============================================================================
+$LANGUAGE['title_page_insert'] = $LANGUAGE['insert_page'];
+$LANGUAGE['title_post_insert'] = $LANGUAGE['insert_post'];
+$LANGUAGE['title_user_insert'] = $LANGUAGE['insert_user'];
+
+#===============================================================================
+# Item update titles
+#===============================================================================
+$LANGUAGE['title_page_update'] = $LANGUAGE['update_page'];
+$LANGUAGE['title_post_update'] = $LANGUAGE['update_post'];
+$LANGUAGE['title_user_update'] = $LANGUAGE['update_user'];
+
+#===============================================================================
+# Item delete titles
+#===============================================================================
+$LANGUAGE['title_page_delete'] = $LANGUAGE['delete_page'];
+$LANGUAGE['title_post_delete'] = $LANGUAGE['delete_post'];
+$LANGUAGE['title_user_delete'] = $LANGUAGE['delete_user'];
+
+#===============================================================================
+# Item overview titles
+#===============================================================================
+$LANGUAGE['title_page_overview'] = "{$LANGUAGE['page_overview']} [%d]";
+$LANGUAGE['title_post_overview'] = "{$LANGUAGE['post_overview']} [%d]";
+$LANGUAGE['title_user_overview'] = "{$LANGUAGE['user_overview']} [%d]";
+
+#===============================================================================
+# Search titles
+#===============================================================================
+$LANGUAGE['title_search_request'] = 'Fulltext search';
+$LANGUAGE['title_search_results'] = 'Results for "%s"';
+?> \ No newline at end of file
diff --git a/core/namespace/Application.php b/core/namespace/Application.php
new file mode 100644
index 0000000..39cb522
--- /dev/null
+++ b/core/namespace/Application.php
@@ -0,0 +1,148 @@
+<?php
+class Application {
+
+ #===============================================================================
+ # Singleton instances
+ #===============================================================================
+ private static $Database;
+ private static $Language;
+
+ #===============================================================================
+ # Configuration array
+ #===============================================================================
+ private static $configuration = [];
+
+ #===============================================================================
+ # Set configuration value
+ #===============================================================================
+ public static function set($config, $value) {
+ return self::$configuration[$config] = $value;
+ }
+
+ #===============================================================================
+ # Get configuration value
+ #===============================================================================
+ public static function get($config) {
+ return self::$configuration[$config] ?? "{$config}";
+ }
+
+ #===============================================================================
+ # Get configuration
+ #===============================================================================
+ public static function getConfiguration(): array {
+ return self::$configuration;
+ }
+
+ #===============================================================================
+ # Return singleton PDO database instance
+ #===============================================================================
+ public static function getDatabase($force = FALSE): Database {
+ if(!self::$Database instanceof Database OR $force === TRUE) {
+ $hostname = self::get('DATABASE.HOSTNAME');
+ $basename = self::get('DATABASE.BASENAME');
+ $username = self::get('DATABASE.USERNAME');
+ $password = self::get('DATABASE.PASSWORD');
+
+ self::set('DATABASE.PASSWORD', NULL);
+
+ self::$Database = new Database($hostname, $basename, $username, $password);
+ }
+
+ return self::$Database;
+ }
+
+ #===============================================================================
+ # Return singleton Language instance
+ #===============================================================================
+ public static function getLanguage($force = FALSE): Language {
+ if(!self::$Language instanceof Language OR $force === TRUE) {
+ $Language = new Language(self::get('CORE.LANGUAGE'));
+ $Language->loadLanguage(ROOT.'template/'.self::get('TEMPLATE.NAME').'/lang/'.self::get('TEMPLATE.LANG').'.php');
+ self::$Language = $Language;
+ }
+
+ return self::$Language;
+ }
+
+ #===============================================================================
+ # Return unique CSRF token for the current session
+ #===============================================================================
+ public static function getSecurityToken(): string {
+ if(!isset($_SESSION['token'])) {
+ $_SESSION['token'] = getRandomValue();
+ }
+
+ return $_SESSION['token'];
+ }
+
+ #===============================================================================
+ # Return boolean if successfully authenticated
+ #===============================================================================
+ public static function isAuthenticated(): bool {
+ return isset($_SESSION['auth']);
+ }
+
+ #===============================================================================
+ # Return absolute base URL
+ #===============================================================================
+ public static function getURL($more = ''): string {
+ $prot = self::get('PATHINFO.PROT');
+ $host = self::get('PATHINFO.HOST');
+ $base = self::get('PATHINFO.BASE');
+
+ return "{$prot}://{$host}/{$base}{$more}";
+ }
+
+ #===============================================================================
+ # Return absolute root URL
+ #===============================================================================
+ public static function getAdminURL($more = ''): string {
+ return self::getURL("admin/{$more}");
+ }
+
+ #===============================================================================
+ # Return absolute post URL
+ #===============================================================================
+ public static function getPostURL($more = ''): string {
+ return self::getURL(self::get('POST.DIRECTORY')."/{$more}");
+ }
+
+ #===============================================================================
+ # Return absolute page URL
+ #===============================================================================
+ public static function getPageURL($more = ''): string {
+ return self::getURL(self::get('PAGE.DIRECTORY')."/{$more}");
+ }
+
+ #===============================================================================
+ # Return absolute user URL
+ #===============================================================================
+ public static function getUserURL($more = ''): string {
+ return self::getURL(self::get('USER.DIRECTORY')."/{$more}");
+ }
+
+ #===============================================================================
+ # Return absolute file URL
+ #===============================================================================
+ public static function getFileURL($more = ''): string {
+ return self::getURL("rsrc/{$more}");
+ }
+
+ #===============================================================================
+ # Return absolute template URL
+ #===============================================================================
+ public static function getTemplateURL($more = ''): string {
+ $template = self::get('TEMPLATE.NAME');
+ return Application::getURL("template/{$template}/{$more}");
+ }
+
+ #===============================================================================
+ # Exit application with
+ #===============================================================================
+ public static function exit($code = 500) {
+ http_response_code($code);
+ $code === 404 AND require_once(ROOT."system/404.php");
+ exit();
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/Attribute.php b/core/namespace/Attribute.php
new file mode 100644
index 0000000..69998e0
--- /dev/null
+++ b/core/namespace/Attribute.php
@@ -0,0 +1,74 @@
+<?php
+abstract class Attribute implements AttributeInterface {
+
+ #===============================================================================
+ # Set attribute
+ #===============================================================================
+ public function set($attribute, $value) {
+ return $this->{$attribute} = $value;
+ }
+
+ #===============================================================================
+ # Get attribute
+ #===============================================================================
+ public function get($attribute) {
+ return $this->{$attribute} ?? NULL;
+ }
+
+ #===============================================================================
+ # Get array with not FALSE attributes
+ #===============================================================================
+ protected function getFilteredAttributes(): array {
+ return array_filter(get_object_vars($this), function($value) {
+ return $value !== FALSE;
+ });
+ }
+
+ #===============================================================================
+ # Insert database item
+ #===============================================================================
+ public function databaseINSERT(\Database $Database): bool {
+ $part[0] = '';
+ $part[1] = '';
+
+ $attributes = $this->getFilteredAttributes();
+
+ foreach($attributes as $column => $value) {
+ $part[0] .= "{$column},";
+ $part[1] .= '?,';
+ }
+
+ $part[0] = rtrim($part[0], ',');
+ $part[1] = rtrim($part[1], ',');
+
+ $Statement = $Database->prepare('INSERT INTO '.static::TABLE." ({$part[0]}) VALUES ({$part[1]})");
+ return $Statement->execute(array_values($attributes));
+ }
+
+ #===============================================================================
+ # Update database item
+ #===============================================================================
+ public function databaseUPDATE(\Database $Database): bool {
+ $part = '';
+
+ $attributes = $this->getFilteredAttributes();
+
+ foreach($attributes as $column => $value) {
+ $part .= "{$column} = ?,";
+ }
+
+ $part = rtrim($part, ',');
+
+ $Statement = $Database->prepare('UPDATE '.static::TABLE.' SET '.$part.' WHERE id = '.(int) $this->get('id'));
+ return $Statement->execute(array_values($attributes));
+ }
+
+ #===============================================================================
+ # Delete database item
+ #===============================================================================
+ public function databaseDELETE(\Database $Database): bool {
+ $Statement = $Database->prepare('DELETE FROM '.static::TABLE.' WHERE id = ?');
+ return $Statement->execute([$this->get('id')]);
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/AttributeInterface.php b/core/namespace/AttributeInterface.php
new file mode 100644
index 0000000..74cd1f1
--- /dev/null
+++ b/core/namespace/AttributeInterface.php
@@ -0,0 +1,7 @@
+<?php
+interface AttributeInterface {
+ public function databaseINSERT(\Database $Database);
+ public function databaseUPDATE(\Database $Database);
+ public function databaseDELETE(\Database $Database);
+}
+?> \ No newline at end of file
diff --git a/core/namespace/Database.php b/core/namespace/Database.php
new file mode 100644
index 0000000..ae233f4
--- /dev/null
+++ b/core/namespace/Database.php
@@ -0,0 +1,7 @@
+<?php
+class Database extends \PDO {
+ public function __construct($hostname, $basename, $username, $password) {
+ parent::__construct("mysql:host={$hostname};dbname={$basename};charset=utf8mb4;", $username, $password);
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/ExceptionHandler.php b/core/namespace/ExceptionHandler.php
new file mode 100644
index 0000000..d64d74c
--- /dev/null
+++ b/core/namespace/ExceptionHandler.php
@@ -0,0 +1,8 @@
+<?php
+abstract class ExceptionHandler extends Exception {
+ public function defaultHandler($code = 503) {
+ http_response_code(503);
+ exit(parent::getMessage());
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/Factory.php b/core/namespace/Factory.php
new file mode 100644
index 0000000..38be666
--- /dev/null
+++ b/core/namespace/Factory.php
@@ -0,0 +1,19 @@
+<?php
+abstract class Factory implements FactoryInterface {
+ public static $storage = [];
+
+ #===============================================================================
+ # Adds an instance of a class to the runtime instance cache
+ #===============================================================================
+ protected static function storeInstance($identifier, $instance) {
+ return self::$storage[get_called_class()][$identifier] = $instance;
+ }
+
+ #===============================================================================
+ # Gets an instance of a class from the runtime instance cache
+ #===============================================================================
+ protected static function fetchInstance($identifier) {
+ return self::$storage[get_called_class()][$identifier] ?? FALSE;
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/FactoryInterface.php b/core/namespace/FactoryInterface.php
new file mode 100644
index 0000000..54a115b
--- /dev/null
+++ b/core/namespace/FactoryInterface.php
@@ -0,0 +1,5 @@
+<?php
+interface FactoryInterface {
+ public static function build($identifier);
+}
+?> \ No newline at end of file
diff --git a/core/namespace/HTTP.php b/core/namespace/HTTP.php
new file mode 100644
index 0000000..f9fbf01
--- /dev/null
+++ b/core/namespace/HTTP.php
@@ -0,0 +1,234 @@
+<?php
+class HTTP {
+ private static $GET = NULL;
+ private static $POST = NULL;
+ private static $FILE = NULL;
+
+ #===============================================================================
+ # HTTP protocol versions
+ #===============================================================================
+ const VERSION_1_0 = 'HTTP/1.0';
+ const VERSION_1_1 = 'HTTP/1.1';
+ const VERSION_2_0 = 'HTTP/2.0';
+
+ #===============================================================================
+ # HTTP header fields
+ #===============================================================================
+ const HEADER_ETAG = 'ETag';
+ const HEADER_CONTENT_TYPE = 'Content-Type';
+ const HEADER_TRANSFER_ENCODING = 'Transfer-Encoding';
+ const HEADER_ACCESS_CONTROL = 'Access-Control-Allow-Origin';
+
+ #===============================================================================
+ # Values for HTTP header fields
+ #===============================================================================
+ const CONTENT_TYPE_JSCRIPT = 'application/x-javascript; charset=UTF-8';
+ const CONTENT_TYPE_TEXT = 'text/plain; charset=UTF-8';
+ const CONTENT_TYPE_HTML = 'text/html; charset=UTF-8';
+ const CONTENT_TYPE_JSON = 'application/json; charset=UTF-8';
+ const CONTENT_TYPE_XML = 'text/xml; charset=UTF-8';
+
+ #===============================================================================
+ # HTTP status codes
+ #===============================================================================
+ const RESPONSE_CODE = [
+ 100 => 'Continue',
+ 101 => 'Switching Protocols',
+ 200 => 'OK',
+ 201 => 'Created',
+ 202 => 'Accepted',
+ 203 => 'Non-Authoritative Information',
+ 204 => 'No Content',
+ 205 => 'Reset Content',
+ 206 => 'Partial Content',
+ 300 => 'Multiple Choices',
+ 301 => 'Moved Permanently',
+ 302 => 'Found',
+ 303 => 'See Other',
+ 304 => 'Not Modified',
+ 305 => 'Use Proxy',
+ 307 => 'Temporary Redirect',
+ 400 => 'Bad Request',
+ 401 => 'Unauthorized',
+ 402 => 'Payment Required',
+ 403 => 'Forbidden',
+ 404 => 'Not Found',
+ 405 => 'Method Not Allowed',
+ 406 => 'Not Acceptable',
+ 407 => 'Proxy Authentication Required',
+ 408 => 'Request Time-out',
+ 409 => 'Conflict',
+ 410 => 'Gone',
+ 411 => 'Length Required',
+ 412 => 'Precondition Failed',
+ 413 => 'Request Entity Too Large',
+ 414 => 'Request-URI Too Large',
+ 415 => 'Unsupported Media Type',
+ 416 => 'Requested range not satisfiable',
+ 417 => 'Expectation Failed',
+ 500 => 'Internal Server Error',
+ 501 => 'Not Implemented',
+ 502 => 'Bad Gateway',
+ 503 => 'Service Unavailable',
+ 504 => 'Gateway Time-out'
+ ];
+
+ #===============================================================================
+ # Initialize $GET, $POST and $FILE
+ #===============================================================================
+ public static function init($GET, $POST, $FILE, $removeArrays = FALSE, $trimValues = TRUE) {
+ self::$GET = $GET;
+ self::$POST = $POST;
+ self::$FILE = $FILE;
+
+ $removeArrays AND self::removeArrays();
+
+ self::$GET = ($trimValues === TRUE ? self::trim(self::$GET) : self::$GET );
+ self::$POST = ($trimValues === TRUE ? self::trim(self::$POST) : self::$POST);
+ }
+
+ #===============================================================================
+ # Remove all arrays from $_GET and $_POST
+ #===============================================================================
+ private static function removeArrays() {
+ foreach(['GET', 'POST'] as $HTTP) {
+ foreach(self::$$HTTP as $name => $value) {
+ if(is_array(self::$$HTTP[$name])) {
+ unset(self::$$HTTP[$name]);
+ }
+ }
+ }
+ }
+
+ #===============================================================================
+ # Trim all strings in argument
+ #===============================================================================
+ private static function trim($mixed) {
+ if(is_array($mixed)) {
+ return array_map('self::trim', $mixed);
+ }
+
+ return trim($mixed);
+ }
+
+ #===============================================================================
+ # Checks if all elements of $arguments are set as key of $data
+ #===============================================================================
+ private static function issetData($data, $arguments) {
+ foreach($arguments as $key) {
+ if(is_array($key)) {
+ if(!isset($data[key($key)]) OR $data[key($key)] !== $key[key($key)]) {
+ return FALSE;
+ }
+ }
+
+ else if(!isset($data[$key]) OR !is_string($data[$key])) {
+ return FALSE;
+ }
+ }
+
+ return TRUE;
+ }
+
+ #===============================================================================
+ # Return null or the value (if set) from one of the three requests attributes
+ #===============================================================================
+ public static function returnKey($data, array $paths) {
+ $current = &$data;
+
+ foreach($paths as $path) {
+ if(!isset($current[$path])) {
+ return NULL;
+ }
+ $current = &$current[$path];
+ }
+
+ return $current;
+ }
+
+ #===============================================================================
+ # Return GET value
+ #===============================================================================
+ public static function GET() {
+ return self::returnKey(self::$GET, func_get_args());
+ }
+
+ #===============================================================================
+ # Return POST value
+ #===============================================================================
+ public static function POST() {
+ return self::returnKey(self::$POST, func_get_args());
+ }
+
+ #===============================================================================
+ # Return FILE value
+ #===============================================================================
+ public static function FILE() {
+ return self::returnKey(self::$FILE, func_get_args());
+ }
+
+ #===============================================================================
+ # Checks if all elements of func_get_args() are set key of self::$POST
+ #===============================================================================
+ public static function issetPOST() {
+ return self::issetData(self::$POST, func_get_args());
+ }
+
+ #===============================================================================
+ # Checks if all elements of func_get_args() are set key of self::$GET
+ #===============================================================================
+ public static function issetGET() {
+ return self::issetData(self::$GET, func_get_args());
+ }
+
+ #===============================================================================
+ # Checks if all elements of func_get_args() are set key of self::$FILE
+ #===============================================================================
+ public static function issetFILE() {
+ return self::issetData(self::$FILE, func_get_args());
+ }
+
+ #===============================================================================
+ # Return HTTP request method or check if request method equals with $method
+ #===============================================================================
+ public static function requestMethod($method = NULL) {
+ if(!empty($method)) {
+ return ($_SERVER['REQUEST_METHOD'] === $method);
+ }
+
+ return $_SERVER['REQUEST_METHOD'];
+ }
+
+ #===============================================================================
+ # Return REQUEST_URL
+ #===============================================================================
+ public static function requestURI() {
+ return $_SERVER['REQUEST_URL'] ?? FALSE;
+ }
+
+ #===============================================================================
+ # Sends a HTTP header line to the client
+ #===============================================================================
+ public static function responseHeader($field, $value) {
+ self::sendHeader("{$field}: {$value}");
+ }
+
+ #===============================================================================
+ # Sends a HTTP redirect to the client
+ #===============================================================================
+ public static function redirect($location, $code = 303, $exit = TRUE) {
+ http_response_code($code);
+ self::sendHeader("Location: {$location}");
+ $exit AND exit();
+ }
+
+ #===============================================================================
+ # Sends a new HTTP header line to the client if headers are not already sent
+ #===============================================================================
+ private static function sendHeader($header) {
+ if(!headers_sent()) {
+ header($header);
+ }
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/Item.php b/core/namespace/Item.php
new file mode 100644
index 0000000..6d17011
--- /dev/null
+++ b/core/namespace/Item.php
@@ -0,0 +1,150 @@
+<?php
+abstract class Item implements ItemInterface {
+ protected $Database = NULL;
+ protected $Attribute = NULL;
+ protected $Reflection = NULL;
+
+ abstract public function getURL();
+ abstract public function getGUID();
+
+ #===============================================================================
+ # Abstract item constructor
+ #===============================================================================
+ public final function __construct($itemID, \Database $Database) {
+ $this->Database = $Database;
+
+ $this->Reflection = new ReflectionObject($this);
+
+ $attribute = "{$this->Reflection->getNamespaceName()}\\Attribute";
+ $exception = "{$this->Reflection->getNamespaceName()}\\Exception";
+
+ #===============================================================================
+ # Checking if item in database exists
+ #===============================================================================
+ $Statement = $Database->prepare(sprintf('SELECT * FROM %s WHERE id = ?', $attribute::TABLE));
+ $Statement->execute([$itemID]);
+
+ #===============================================================================
+ # Checking if retrieving data failed
+ #===============================================================================
+ if(!$this->Attribute = $Statement->fetchObject($attribute)) {
+ throw new $exception(sprintf('%s\\Item with ID %s does not exists', $this->Reflection->getNamespaceName(), (int) $itemID));
+ }
+ }
+
+ #===============================================================================
+ # Return attribute by name (short hand wrapper)
+ #===============================================================================
+ public function attr($attribute) {
+ return $this->Attribute->get($attribute);
+ }
+
+ #===============================================================================
+ # Return Attribute object
+ #===============================================================================
+ public final function getAttribute(): Attribute {
+ return $this->Attribute;
+ }
+
+ #===============================================================================
+ # Return unique ID
+ #===============================================================================
+ public final function getID(): int {
+ return $this->Attribute->get('id');
+ }
+
+ #===============================================================================
+ # Return pre-parsed content
+ #===============================================================================
+ public function getBody(): string {
+ $content = preg_replace_callback('#\{(POST|PAGE|USER)\[([0-9]+)\]\}#', function($matches) {
+ $namespace = ucfirst(strtolower($matches[1])).'\\Factory';
+
+ try {
+ $Item = $namespace::build($matches[2]);
+ return $Item->getURL();
+ } catch(Exception $Exception) {
+ return '{undefined}';
+ }
+ }, $this->Attribute->get('body'));
+
+ $content = preg_replace('#\{BASE\[\"([^"]+)\"\]\}#', \Application::getURL('$1'), $content);
+ $content = preg_replace('#\{FILE\[\"([^"]+)\"\]\}#', \Application::getFileURL('$1'), $content);
+
+ return $content;
+ }
+
+ #===============================================================================
+ # Return parsed content
+ #===============================================================================
+ public function getHTML(): string {
+ $item = "{$this->Reflection->getNamespaceName()}\\Item";
+
+ $Parsedown = new Parsedown();
+ $content = $this->getBody();
+
+ if(\Application::get($item::CONFIGURATION.'.EMOTICONS') === TRUE) {
+ $content = parseEmoticons($content);
+ }
+
+ return $Parsedown->text($content);
+ }
+
+ #===============================================================================
+ # Return attached files
+ #===============================================================================
+ public function getFiles(): array {
+ if(preg_match_all('#\!\[(.*)\][ ]?(?:\n[ ]*)?\((.*)(\s[\'"](.*)[\'"])?\)#U', $this->getBody(), $matches)) {
+ return array_map('htmlentities', $matches[2]);
+ }
+
+ return [];
+ }
+
+ #===============================================================================
+ # Return previous item ID
+ #===============================================================================
+ public function getPrevID(): int {
+ $execute = 'SELECT id FROM %s WHERE DATE(time_insert) <= DATE(?) AND id < ? ORDER BY time_insert DESC, id DESC LIMIT 1';
+
+ $attribute = "{$this->Reflection->getNamespaceName()}\\Attribute";
+ $Statement = $this->Database->prepare(sprintf($execute, $attribute::TABLE));
+
+ if($Statement->execute([$this->Attribute->get('time_insert'), $this->Attribute->get('id')])) {
+ return $Statement->fetchColumn();
+ }
+
+ return 0;
+ }
+
+ #===============================================================================
+ # Return next item ID
+ #===============================================================================
+ public function getNextID(): int {
+ $execute = 'SELECT id FROM %s WHERE DATE(time_insert) >= DATE(?) AND id > ? ORDER BY time_insert ASC, id DESC LIMIT 1';
+
+ $attribute = "{$this->Reflection->getNamespaceName()}\\Attribute";
+ $Statement = $this->Database->prepare(sprintf($execute, $attribute::TABLE));
+
+ if($Statement->execute([$this->Attribute->get('time_insert'), $this->Attribute->get('id')])) {
+ return $Statement->fetchColumn();
+ }
+
+ return 0;
+ }
+
+ #===============================================================================
+ # Return unique ID based on specific field comparison with value
+ #===============================================================================
+ public static function getIDByField($field, $value, \Database $Database): int {
+ $attribute = (new ReflectionClass(get_called_class()))->getNamespaceName().'\\Attribute';
+ $Statement = $Database->prepare('SELECT id FROM '.$attribute::TABLE." WHERE {$field} = ?");
+
+ if($Statement->execute([$value])) {
+ return $Statement->fetchColumn();
+ }
+
+ return 0;
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/ItemFactory.php b/core/namespace/ItemFactory.php
new file mode 100644
index 0000000..e5793d4
--- /dev/null
+++ b/core/namespace/ItemFactory.php
@@ -0,0 +1,12 @@
+<?php
+abstract class ItemFactory extends Factory implements FactoryInterface {
+ public static function build($itemID): Item {
+ if(!$Instance = parent::fetchInstance($itemID)) {
+ $Item = (new ReflectionClass(get_called_class()))->getNamespaceName().'\\Item';
+ $Instance = parent::storeInstance($itemID, new $Item($itemID, \Application::getDatabase()));
+ }
+
+ return $Instance;
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/ItemInterface.php b/core/namespace/ItemInterface.php
new file mode 100644
index 0000000..e7ccb6a
--- /dev/null
+++ b/core/namespace/ItemInterface.php
@@ -0,0 +1,5 @@
+<?php
+interface ItemInterface {
+ public function __construct($itemID, \Database $Database);
+}
+?> \ No newline at end of file
diff --git a/core/namespace/Language.php b/core/namespace/Language.php
new file mode 100644
index 0000000..c8a018e
--- /dev/null
+++ b/core/namespace/Language.php
@@ -0,0 +1,48 @@
+<?php
+class Language {
+ private $language = [];
+ private $template = [];
+
+ public function __construct($lang) {
+ require ROOT."core/language/{$lang}.php";
+ $this->language = $LANGUAGE;
+ }
+
+ public function loadLanguage($filename) {
+ require $filename;
+ $this->template = $LANGUAGE;
+ }
+
+ public function template($name, $params = FALSE) {
+ if(isset($this->template[$name])) {
+ if($params) {
+ return vsprintf($this->template[$name], $params);
+ }
+
+ return $this->template[$name];
+ }
+
+ return "{{$name}}";
+ }
+
+ private function get($name, $params = FALSE) {
+ if(isset($this->language[$name])) {
+ if($params) {
+ return vsprintf($this->language[$name], $params);
+ }
+
+ return $this->language[$name];
+ }
+
+ return "{{$name}}";
+ }
+
+ public function text($name, $params = FALSE) {
+ return $this->get($name, $params);
+ }
+
+ public function set($name, $value) {
+ return $this->language[$name] = $value;
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/Page/Attribute.php b/core/namespace/Page/Attribute.php
new file mode 100644
index 0000000..c12a2c8
--- /dev/null
+++ b/core/namespace/Page/Attribute.php
@@ -0,0 +1,22 @@
+<?php
+namespace Page;
+
+class Attribute extends \Attribute {
+
+ #===============================================================================
+ # Pre-Define database table columns
+ #===============================================================================
+ protected $id = FALSE;
+ protected $user = FALSE;
+ protected $slug = FALSE;
+ protected $name = FALSE;
+ protected $body = FALSE;
+ protected $time_insert = FALSE;
+ protected $time_update = FALSE;
+
+ #===============================================================================
+ # Define database table name
+ #===============================================================================
+ const TABLE = 'page';
+}
+?> \ No newline at end of file
diff --git a/core/namespace/Page/Exception.php b/core/namespace/Page/Exception.php
new file mode 100644
index 0000000..d4794b7
--- /dev/null
+++ b/core/namespace/Page/Exception.php
@@ -0,0 +1,5 @@
+<?php
+namespace Page;
+
+class Exception extends \Exception {}
+?> \ No newline at end of file
diff --git a/core/namespace/Page/Factory.php b/core/namespace/Page/Factory.php
new file mode 100644
index 0000000..f53b35f
--- /dev/null
+++ b/core/namespace/Page/Factory.php
@@ -0,0 +1,9 @@
+<?php
+namespace Page;
+
+class Factory extends \ItemFactory {
+ public static function buildBySlug($slug): \Item {
+ return self::build(Item::getIDByField('slug', $slug, \Application::getDatabase()));
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/Page/Item.php b/core/namespace/Page/Item.php
new file mode 100644
index 0000000..c6cece7
--- /dev/null
+++ b/core/namespace/Page/Item.php
@@ -0,0 +1,29 @@
+<?php
+namespace Page;
+
+class Item extends \Item {
+ const CONFIGURATION = 'PAGE';
+
+ #===============================================================================
+ # Return absolute page URL
+ #===============================================================================
+ public function getURL(): string {
+ if(\Application::get('PAGE.SLUG_URLS')) {
+ return \Application::getPageURL("{$this->Attribute->get('slug')}/");
+ }
+
+ return \Application::getPageURL("{$this->Attribute->get('id')}/");
+ }
+
+ #===============================================================================
+ # Return unique pseudo GUID
+ #===============================================================================
+ public function getGUID(): string {
+ foreach(\Application::get('PAGE.FEED_GUID') as $attribute) {
+ $attributes[] = $this->Attribute->get($attribute);
+ }
+
+ return sha1(implode(NULL, $attributes));
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/Parsedown.php b/core/namespace/Parsedown.php
new file mode 100644
index 0000000..610658b
--- /dev/null
+++ b/core/namespace/Parsedown.php
@@ -0,0 +1,1548 @@
+<?php
+
+#
+#
+# Parsedown
+# http://parsedown.org
+#
+# (c) Emanuil Rusev
+# http://erusev.com
+#
+# For the full license information, view the LICENSE file that was distributed
+# with this source code.
+#
+#
+
+class Parsedown
+{
+ # ~
+
+ const version = '1.6.0';
+
+ # ~
+
+ function text($text)
+ {
+ # make sure no definitions are set
+ $this->DefinitionData = array();
+
+ # standardize line breaks
+ $text = str_replace(array("\r\n", "\r"), "\n", $text);
+
+ # remove surrounding line breaks
+ $text = trim($text, "\n");
+
+ # split text into lines
+ $lines = explode("\n", $text);
+
+ # iterate through lines to identify blocks
+ $markup = $this->lines($lines);
+
+ # trim line breaks
+ $markup = trim($markup, "\n");
+
+ return $markup;
+ }
+
+ #
+ # Setters
+ #
+
+ function setBreaksEnabled($breaksEnabled)
+ {
+ $this->breaksEnabled = $breaksEnabled;
+
+ return $this;
+ }
+
+ protected $breaksEnabled;
+
+ function setMarkupEscaped($markupEscaped)
+ {
+ $this->markupEscaped = $markupEscaped;
+
+ return $this;
+ }
+
+ protected $markupEscaped;
+
+ function setUrlsLinked($urlsLinked)
+ {
+ $this->urlsLinked = $urlsLinked;
+
+ return $this;
+ }
+
+ protected $urlsLinked = true;
+
+ #
+ # Lines
+ #
+
+ protected $BlockTypes = array(
+ '#' => array('Header'),
+ '*' => array('Rule', 'List'),
+ '+' => array('List'),
+ '-' => array('SetextHeader', 'Table', 'Rule', 'List'),
+ '0' => array('List'),
+ '1' => array('List'),
+ '2' => array('List'),
+ '3' => array('List'),
+ '4' => array('List'),
+ '5' => array('List'),
+ '6' => array('List'),
+ '7' => array('List'),
+ '8' => array('List'),
+ '9' => array('List'),
+ ':' => array('Table'),
+ '<' => array('Comment', 'Markup'),
+ '=' => array('SetextHeader'),
+ '>' => array('Quote'),
+ '[' => array('Reference'),
+ '_' => array('Rule'),
+ '`' => array('FencedCode'),
+ '|' => array('Table'),
+ '~' => array('FencedCode'),
+ );
+
+ # ~
+
+ protected $unmarkedBlockTypes = array(
+ 'Code',
+ );
+
+ #
+ # Blocks
+ #
+
+ protected function lines(array $lines)
+ {
+ $CurrentBlock = null;
+
+ foreach ($lines as $line)
+ {
+ if (chop($line) === '')
+ {
+ if (isset($CurrentBlock))
+ {
+ $CurrentBlock['interrupted'] = true;
+ }
+
+ continue;
+ }
+
+ if (strpos($line, "\t") !== false)
+ {
+ $parts = explode("\t", $line);
+
+ $line = $parts[0];
+
+ unset($parts[0]);
+
+ foreach ($parts as $part)
+ {
+ $shortage = 4 - mb_strlen($line, 'utf-8') % 4;
+
+ $line .= str_repeat(' ', $shortage);
+ $line .= $part;
+ }
+ }
+
+ $indent = 0;
+
+ while (isset($line[$indent]) and $line[$indent] === ' ')
+ {
+ $indent ++;
+ }
+
+ $text = $indent > 0 ? substr($line, $indent) : $line;
+
+ # ~
+
+ $Line = array('body' => $line, 'indent' => $indent, 'text' => $text);
+
+ # ~
+
+ if (isset($CurrentBlock['continuable']))
+ {
+ $Block = $this->{'block'.$CurrentBlock['type'].'Continue'}($Line, $CurrentBlock);
+
+ if (isset($Block))
+ {
+ $CurrentBlock = $Block;
+
+ continue;
+ }
+ else
+ {
+ if ($this->isBlockCompletable($CurrentBlock['type']))
+ {
+ $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
+ }
+ }
+ }
+
+ # ~
+
+ $marker = $text[0];
+
+ # ~
+
+ $blockTypes = $this->unmarkedBlockTypes;
+
+ if (isset($this->BlockTypes[$marker]))
+ {
+ foreach ($this->BlockTypes[$marker] as $blockType)
+ {
+ $blockTypes []= $blockType;
+ }
+ }
+
+ #
+ # ~
+
+ foreach ($blockTypes as $blockType)
+ {
+ $Block = $this->{'block'.$blockType}($Line, $CurrentBlock);
+
+ if (isset($Block))
+ {
+ $Block['type'] = $blockType;
+
+ if ( ! isset($Block['identified']))
+ {
+ $Blocks []= $CurrentBlock;
+
+ $Block['identified'] = true;
+ }
+
+ if ($this->isBlockContinuable($blockType))
+ {
+ $Block['continuable'] = true;
+ }
+
+ $CurrentBlock = $Block;
+
+ continue 2;
+ }
+ }
+
+ # ~
+
+ if (isset($CurrentBlock) and ! isset($CurrentBlock['type']) and ! isset($CurrentBlock['interrupted']))
+ {
+ $CurrentBlock['element']['text'] .= "\n".$text;
+ }
+ else
+ {
+ $Blocks []= $CurrentBlock;
+
+ $CurrentBlock = $this->paragraph($Line);
+
+ $CurrentBlock['identified'] = true;
+ }
+ }
+
+ # ~
+
+ if (isset($CurrentBlock['continuable']) and $this->isBlockCompletable($CurrentBlock['type']))
+ {
+ $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
+ }
+
+ # ~
+
+ $Blocks []= $CurrentBlock;
+
+ unset($Blocks[0]);
+
+ # ~
+
+ $markup = '';
+
+ foreach ($Blocks as $Block)
+ {
+ if (isset($Block['hidden']))
+ {
+ continue;
+ }
+
+ $markup .= "\n";
+ $markup .= isset($Block['markup']) ? $Block['markup'] : $this->element($Block['element']);
+ }
+
+ $markup .= "\n";
+
+ # ~
+
+ return $markup;
+ }
+
+ protected function isBlockContinuable($Type)
+ {
+ return method_exists($this, 'block'.$Type.'Continue');
+ }
+
+ protected function isBlockCompletable($Type)
+ {
+ return method_exists($this, 'block'.$Type.'Complete');
+ }
+
+ #
+ # Code
+
+ protected function blockCode($Line, $Block = null)
+ {
+ if (isset($Block) and ! isset($Block['type']) and ! isset($Block['interrupted']))
+ {
+ return;
+ }
+
+ if ($Line['indent'] >= 4)
+ {
+ $text = substr($Line['body'], 4);
+
+ $Block = array(
+ 'element' => array(
+ 'name' => 'pre',
+ 'handler' => 'element',
+ 'text' => array(
+ 'name' => 'code',
+ 'text' => $text,
+ ),
+ ),
+ );
+
+ return $Block;
+ }
+ }
+
+ protected function blockCodeContinue($Line, $Block)
+ {
+ if ($Line['indent'] >= 4)
+ {
+ if (isset($Block['interrupted']))
+ {
+ $Block['element']['text']['text'] .= "\n";
+
+ unset($Block['interrupted']);
+ }
+
+ $Block['element']['text']['text'] .= "\n";
+
+ $text = substr($Line['body'], 4);
+
+ $Block['element']['text']['text'] .= $text;
+
+ return $Block;
+ }
+ }
+
+ protected function blockCodeComplete($Block)
+ {
+ $text = $Block['element']['text']['text'];
+
+ $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
+
+ $Block['element']['text']['text'] = $text;
+
+ return $Block;
+ }
+
+ #
+ # Comment
+
+ protected function blockComment($Line)
+ {
+ if ($this->markupEscaped)
+ {
+ return;
+ }
+
+ if (isset($Line['text'][3]) and $Line['text'][3] === '-' and $Line['text'][2] === '-' and $Line['text'][1] === '!')
+ {
+ $Block = array(
+ 'markup' => $Line['body'],
+ );
+
+ if (preg_match('/-->$/', $Line['text']))
+ {
+ $Block['closed'] = true;
+ }
+
+ return $Block;
+ }
+ }
+
+ protected function blockCommentContinue($Line, array $Block)
+ {
+ if (isset($Block['closed']))
+ {
+ return;
+ }
+
+ $Block['markup'] .= "\n" . $Line['body'];
+
+ if (preg_match('/-->$/', $Line['text']))
+ {
+ $Block['closed'] = true;
+ }
+
+ return $Block;
+ }
+
+ #
+ # Fenced Code
+
+ protected function blockFencedCode($Line)
+ {
+ if (preg_match('/^['.$Line['text'][0].']{3,}[ ]*([\w-]+)?[ ]*$/', $Line['text'], $matches))
+ {
+ $Element = array(
+ 'name' => 'code',
+ 'text' => '',
+ );
+
+ if (isset($matches[1]))
+ {
+ $class = 'language-'.$matches[1];
+
+ $Element['attributes'] = array(
+ 'class' => $class,
+ );
+ }
+
+ $Block = array(
+ 'char' => $Line['text'][0],
+ 'element' => array(
+ 'name' => 'pre',
+ 'handler' => 'element',
+ 'text' => $Element,
+ ),
+ );
+
+ return $Block;
+ }
+ }
+
+ protected function blockFencedCodeContinue($Line, $Block)
+ {
+ if (isset($Block['complete']))
+ {
+ return;
+ }
+
+ if (isset($Block['interrupted']))
+ {
+ $Block['element']['text']['text'] .= "\n";
+
+ unset($Block['interrupted']);
+ }
+
+ if (preg_match('/^'.$Block['char'].'{3,}[ ]*$/', $Line['text']))
+ {
+ $Block['element']['text']['text'] = substr($Block['element']['text']['text'], 1);
+
+ $Block['complete'] = true;
+
+ return $Block;
+ }
+
+ $Block['element']['text']['text'] .= "\n".$Line['body'];;
+
+ return $Block;
+ }
+
+ protected function blockFencedCodeComplete($Block)
+ {
+ $text = $Block['element']['text']['text'];
+
+ $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
+
+ $Block['element']['text']['text'] = $text;
+
+ return $Block;
+ }
+
+ #
+ # Header
+
+ protected function blockHeader($Line)
+ {
+ if (isset($Line['text'][1]))
+ {
+ $level = 1;
+
+ while (isset($Line['text'][$level]) and $Line['text'][$level] === '#')
+ {
+ $level ++;
+ }
+
+ if ($level > 6)
+ {
+ return;
+ }
+
+ $text = trim($Line['text'], '# ');
+
+ $Block = array(
+ 'element' => array(
+ 'name' => 'h' . min(6, $level),
+ 'text' => $text,
+ 'handler' => 'line',
+ ),
+ );
+
+ return $Block;
+ }
+ }
+
+ #
+ # List
+
+ protected function blockList($Line)
+ {
+ list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]+[.]');
+
+ if (preg_match('/^('.$pattern.'[ ]+)(.*)/', $Line['text'], $matches))
+ {
+ $Block = array(
+ 'indent' => $Line['indent'],
+ 'pattern' => $pattern,
+ 'element' => array(
+ 'name' => $name,
+ 'handler' => 'elements',
+ ),
+ );
+
+ if($name === 'ol')
+ {
+ $listStart = stristr($matches[0], '.', true);
+
+ if($listStart !== '1')
+ {
+ $Block['element']['attributes'] = array('start' => $listStart);
+ }
+ }
+
+ $Block['li'] = array(
+ 'name' => 'li',
+ 'handler' => 'li',
+ 'text' => array(
+ $matches[2],
+ ),
+ );
+
+ $Block['element']['text'] []= & $Block['li'];
+
+ return $Block;
+ }
+ }
+
+ protected function blockListContinue($Line, array $Block)
+ {
+ if ($Block['indent'] === $Line['indent'] and preg_match('/^'.$Block['pattern'].'(?:[ ]+(.*)|$)/', $Line['text'], $matches))
+ {
+ if (isset($Block['interrupted']))
+ {
+ $Block['li']['text'] []= '';
+
+ unset($Block['interrupted']);
+ }
+
+ unset($Block['li']);
+
+ $text = isset($matches[1]) ? $matches[1] : '';
+
+ $Block['li'] = array(
+ 'name' => 'li',
+ 'handler' => 'li',
+ 'text' => array(
+ $text,
+ ),
+ );
+
+ $Block['element']['text'] []= & $Block['li'];
+
+ return $Block;
+ }
+
+ if ($Line['text'][0] === '[' and $this->blockReference($Line))
+ {
+ return $Block;
+ }
+
+ if ( ! isset($Block['interrupted']))
+ {
+ $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
+
+ $Block['li']['text'] []= $text;
+
+ return $Block;
+ }
+
+ if ($Line['indent'] > 0)
+ {
+ $Block['li']['text'] []= '';
+
+ $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
+
+ $Block['li']['text'] []= $text;
+
+ unset($Block['interrupted']);
+
+ return $Block;
+ }
+ }
+
+ #
+ # Quote
+
+ protected function blockQuote($Line)
+ {
+ if (preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
+ {
+ $Block = array(
+ 'element' => array(
+ 'name' => 'blockquote',
+ 'handler' => 'lines',
+ 'text' => (array) $matches[1],
+ ),
+ );
+
+ return $Block;
+ }
+ }
+
+ protected function blockQuoteContinue($Line, array $Block)
+ {
+ if ($Line['text'][0] === '>' and preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
+ {
+ if (isset($Block['interrupted']))
+ {
+ $Block['element']['text'] []= '';
+
+ unset($Block['interrupted']);
+ }
+
+ $Block['element']['text'] []= $matches[1];
+
+ return $Block;
+ }
+
+ if ( ! isset($Block['interrupted']))
+ {
+ $Block['element']['text'] []= $Line['text'];
+
+ return $Block;
+ }
+ }
+
+ #
+ # Rule
+
+ protected function blockRule($Line)
+ {
+ if (preg_match('/^(['.$Line['text'][0].'])([ ]*\1){2,}[ ]*$/', $Line['text']))
+ {
+ $Block = array(
+ 'element' => array(
+ 'name' => 'hr'
+ ),
+ );
+
+ return $Block;
+ }
+ }
+
+ #
+ # Setext
+
+ protected function blockSetextHeader($Line, array $Block = null)
+ {
+ if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
+ {
+ return;
+ }
+
+ if (chop($Line['text'], $Line['text'][0]) === '')
+ {
+ $Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2';
+
+ return $Block;
+ }
+ }
+
+ #
+ # Markup
+
+ protected function blockMarkup($Line)
+ {
+ if ($this->markupEscaped)
+ {
+ return;
+ }
+
+ if (preg_match('/^<(\w*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches))
+ {
+ $element = strtolower($matches[1]);
+
+ if (in_array($element, $this->textLevelElements))
+ {
+ return;
+ }
+
+ $Block = array(
+ 'name' => $matches[1],
+ 'depth' => 0,
+ 'markup' => $Line['text'],
+ );
+
+ $length = strlen($matches[0]);
+
+ $remainder = substr($Line['text'], $length);
+
+ if (trim($remainder) === '')
+ {
+ if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
+ {
+ $Block['closed'] = true;
+
+ $Block['void'] = true;
+ }
+ }
+ else
+ {
+ if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
+ {
+ return;
+ }
+
+ if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder))
+ {
+ $Block['closed'] = true;
+ }
+ }
+
+ return $Block;
+ }
+ }
+
+ protected function blockMarkupContinue($Line, array $Block)
+ {
+ if (isset($Block['closed']))
+ {
+ return;
+ }
+
+ if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) # open
+ {
+ $Block['depth'] ++;
+ }
+
+ if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) # close
+ {
+ if ($Block['depth'] > 0)
+ {
+ $Block['depth'] --;
+ }
+ else
+ {
+ $Block['closed'] = true;
+ }
+ }
+
+ if (isset($Block['interrupted']))
+ {
+ $Block['markup'] .= "\n";
+
+ unset($Block['interrupted']);
+ }
+
+ $Block['markup'] .= "\n".$Line['body'];
+
+ return $Block;
+ }
+
+ #
+ # Reference
+
+ protected function blockReference($Line)
+ {
+ if (preg_match('/^\[(.+?)\]:[ ]*<?(\S+?)>?(?:[ ]+["\'(](.+)["\')])?[ ]*$/', $Line['text'], $matches))
+ {
+ $id = strtolower($matches[1]);
+
+ $Data = array(
+ 'url' => $matches[2],
+ 'title' => null,
+ );
+
+ if (isset($matches[3]))
+ {
+ $Data['title'] = $matches[3];
+ }
+
+ $this->DefinitionData['Reference'][$id] = $Data;
+
+ $Block = array(
+ 'hidden' => true,
+ );
+
+ return $Block;
+ }
+ }
+
+ #
+ # Table
+
+ protected function blockTable($Line, array $Block = null)
+ {
+ if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
+ {
+ return;
+ }
+
+ if (strpos($Block['element']['text'], '|') !== false and chop($Line['text'], ' -:|') === '')
+ {
+ $alignments = array();
+
+ $divider = $Line['text'];
+
+ $divider = trim($divider);
+ $divider = trim($divider, '|');
+
+ $dividerCells = explode('|', $divider);
+
+ foreach ($dividerCells as $dividerCell)
+ {
+ $dividerCell = trim($dividerCell);
+
+ if ($dividerCell === '')
+ {
+ continue;
+ }
+
+ $alignment = null;
+
+ if ($dividerCell[0] === ':')
+ {
+ $alignment = 'left';
+ }
+
+ if (substr($dividerCell, - 1) === ':')
+ {
+ $alignment = $alignment === 'left' ? 'center' : 'right';
+ }
+
+ $alignments []= $alignment;
+ }
+
+ # ~
+
+ $HeaderElements = array();
+
+ $header = $Block['element']['text'];
+
+ $header = trim($header);
+ $header = trim($header, '|');
+
+ $headerCells = explode('|', $header);
+
+ foreach ($headerCells as $index => $headerCell)
+ {
+ $headerCell = trim($headerCell);
+
+ $HeaderElement = array(
+ 'name' => 'th',
+ 'text' => $headerCell,
+ 'handler' => 'line',
+ );
+
+ if (isset($alignments[$index]))
+ {
+ $alignment = $alignments[$index];
+
+ $HeaderElement['attributes'] = array(
+ 'style' => 'text-align: '.$alignment.';',
+ );
+ }
+
+ $HeaderElements []= $HeaderElement;
+ }
+
+ # ~
+
+ $Block = array(
+ 'alignments' => $alignments,
+ 'identified' => true,
+ 'element' => array(
+ 'name' => 'table',
+ 'handler' => 'elements',
+ ),
+ );
+
+ $Block['element']['text'] []= array(
+ 'name' => 'thead',
+ 'handler' => 'elements',
+ );
+
+ $Block['element']['text'] []= array(
+ 'name' => 'tbody',
+ 'handler' => 'elements',
+ 'text' => array(),
+ );
+
+ $Block['element']['text'][0]['text'] []= array(
+ 'name' => 'tr',
+ 'handler' => 'elements',
+ 'text' => $HeaderElements,
+ );
+
+ return $Block;
+ }
+ }
+
+ protected function blockTableContinue($Line, array $Block)
+ {
+ if (isset($Block['interrupted']))
+ {
+ return;
+ }
+
+ if ($Line['text'][0] === '|' or strpos($Line['text'], '|'))
+ {
+ $Elements = array();
+
+ $row = $Line['text'];
+
+ $row = trim($row);
+ $row = trim($row, '|');
+
+ preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]+`|`)+/', $row, $matches);
+
+ foreach ($matches[0] as $index => $cell)
+ {
+ $cell = trim($cell);
+
+ $Element = array(
+ 'name' => 'td',
+ 'handler' => 'line',
+ 'text' => $cell,
+ );
+
+ if (isset($Block['alignments'][$index]))
+ {
+ $Element['attributes'] = array(
+ 'style' => 'text-align: '.$Block['alignments'][$index].';',
+ );
+ }
+
+ $Elements []= $Element;
+ }
+
+ $Element = array(
+ 'name' => 'tr',
+ 'handler' => 'elements',
+ 'text' => $Elements,
+ );
+
+ $Block['element']['text'][1]['text'] []= $Element;
+
+ return $Block;
+ }
+ }
+
+ #
+ # ~
+ #
+
+ protected function paragraph($Line)
+ {
+ $Block = array(
+ 'element' => array(
+ 'name' => 'p',
+ 'text' => $Line['text'],
+ 'handler' => 'line',
+ ),
+ );
+
+ return $Block;
+ }
+
+ #
+ # Inline Elements
+ #
+
+ protected $InlineTypes = array(
+ '"' => array('SpecialCharacter'),
+ '!' => array('Image'),
+ '&' => array('SpecialCharacter'),
+ '*' => array('Emphasis'),
+ ':' => array('Url'),
+ '<' => array('UrlTag', 'EmailTag', 'Markup', 'SpecialCharacter'),
+ '>' => array('SpecialCharacter'),
+ '[' => array('Link'),
+ '_' => array('Emphasis'),
+ '`' => array('Code'),
+ '~' => array('Strikethrough'),
+ '\\' => array('EscapeSequence'),
+ );
+
+ # ~
+
+ protected $inlineMarkerList = '!"*_&[:<>`~\\';
+
+ #
+ # ~
+ #
+
+ public function line($text)
+ {
+ $markup = '';
+
+ # $excerpt is based on the first occurrence of a marker
+
+ while ($excerpt = strpbrk($text, $this->inlineMarkerList))
+ {
+ $marker = $excerpt[0];
+
+ $markerPosition = strpos($text, $marker);
+
+ $Excerpt = array('text' => $excerpt, 'context' => $text);
+
+ foreach ($this->InlineTypes[$marker] as $inlineType)
+ {
+ $Inline = $this->{'inline'.$inlineType}($Excerpt);
+
+ if ( ! isset($Inline))
+ {
+ continue;
+ }
+
+ # makes sure that the inline belongs to "our" marker
+
+ if (isset($Inline['position']) and $Inline['position'] > $markerPosition)
+ {
+ continue;
+ }
+
+ # sets a default inline position
+
+ if ( ! isset($Inline['position']))
+ {
+ $Inline['position'] = $markerPosition;
+ }
+
+ # the text that comes before the inline
+ $unmarkedText = substr($text, 0, $Inline['position']);
+
+ # compile the unmarked text
+ $markup .= $this->unmarkedText($unmarkedText);
+
+ # compile the inline
+ $markup .= isset($Inline['markup']) ? $Inline['markup'] : $this->element($Inline['element']);
+
+ # remove the examined text
+ $text = substr($text, $Inline['position'] + $Inline['extent']);
+
+ continue 2;
+ }
+
+ # the marker does not belong to an inline
+
+ $unmarkedText = substr($text, 0, $markerPosition + 1);
+
+ $markup .= $this->unmarkedText($unmarkedText);
+
+ $text = substr($text, $markerPosition + 1);
+ }
+
+ $markup .= $this->unmarkedText($text);
+
+ return $markup;
+ }
+
+ #
+ # ~
+ #
+
+ protected function inlineCode($Excerpt)
+ {
+ $marker = $Excerpt['text'][0];
+
+ if (preg_match('/^('.$marker.'+)[ ]*(.+?)[ ]*(?<!'.$marker.')\1(?!'.$marker.')/s', $Excerpt['text'], $matches))
+ {
+ $text = $matches[2];
+ $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
+ $text = preg_replace("/[ ]*\n/", ' ', $text);
+
+ return array(
+ 'extent' => strlen($matches[0]),
+ 'element' => array(
+ 'name' => 'code',
+ 'text' => $text,
+ ),
+ );
+ }
+ }
+
+ protected function inlineEmailTag($Excerpt)
+ {
+ if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<((mailto:)?\S+?@\S+?)>/i', $Excerpt['text'], $matches))
+ {
+ $url = $matches[1];
+
+ if ( ! isset($matches[2]))
+ {
+ $url = 'mailto:' . $url;
+ }
+
+ return array(
+ 'extent' => strlen($matches[0]),
+ 'element' => array(
+ 'name' => 'a',
+ 'text' => $matches[1],
+ 'attributes' => array(
+ 'href' => $url,
+ ),
+ ),
+ );
+ }
+ }
+
+ protected function inlineEmphasis($Excerpt)
+ {
+ if ( ! isset($Excerpt['text'][1]))
+ {
+ return;
+ }
+
+ $marker = $Excerpt['text'][0];
+
+ if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches))
+ {
+ $emphasis = 'strong';
+ }
+ elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches))
+ {
+ $emphasis = 'em';
+ }
+ else
+ {
+ return;
+ }
+
+ return array(
+ 'extent' => strlen($matches[0]),
+ 'element' => array(
+ 'name' => $emphasis,
+ 'handler' => 'line',
+ 'text' => $matches[1],
+ ),
+ );
+ }
+
+ protected function inlineEscapeSequence($Excerpt)
+ {
+ if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters))
+ {
+ return array(
+ 'markup' => $Excerpt['text'][1],
+ 'extent' => 2,
+ );
+ }
+ }
+
+ protected function inlineImage($Excerpt)
+ {
+ if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[')
+ {
+ return;
+ }
+
+ $Excerpt['text']= substr($Excerpt['text'], 1);
+
+ $Link = $this->inlineLink($Excerpt);
+
+ if ($Link === null)
+ {
+ return;
+ }
+
+ $Inline = array(
+ 'extent' => $Link['extent'] + 1,
+ 'element' => array(
+ 'name' => 'img',
+ 'attributes' => array(
+ 'src' => $Link['element']['attributes']['href'],
+ 'alt' => $Link['element']['text'],
+ ),
+ ),
+ );
+
+ $Inline['element']['attributes'] += $Link['element']['attributes'];
+
+ unset($Inline['element']['attributes']['href']);
+
+ return $Inline;
+ }
+
+ protected function inlineLink($Excerpt)
+ {
+ $Element = array(
+ 'name' => 'a',
+ 'handler' => 'line',
+ 'text' => null,
+ 'attributes' => array(
+ 'href' => null,
+ 'title' => null,
+ ),
+ );
+
+ $extent = 0;
+
+ $remainder = $Excerpt['text'];
+
+ if (preg_match('/\[((?:[^][]|(?R))*)\]/', $remainder, $matches))
+ {
+ $Element['text'] = $matches[1];
+
+ $extent += strlen($matches[0]);
+
+ $remainder = substr($remainder, $extent);
+ }
+ else
+ {
+ return;
+ }
+
+ if (preg_match('/^[(]\s*+((?:[^ ()]++|[(][^ )]+[)])++)(?:[ ]+("[^"]*"|\'[^\']*\'))?\s*[)]/', $remainder, $matches))
+ {
+ $Element['attributes']['href'] = $matches[1];
+
+ if (isset($matches[2]))
+ {
+ $Element['attributes']['title'] = substr($matches[2], 1, - 1);
+ }
+
+ $extent += strlen($matches[0]);
+ }
+ else
+ {
+ if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches))
+ {
+ $definition = strlen($matches[1]) ? $matches[1] : $Element['text'];
+ $definition = strtolower($definition);
+
+ $extent += strlen($matches[0]);
+ }
+ else
+ {
+ $definition = strtolower($Element['text']);
+ }
+
+ if ( ! isset($this->DefinitionData['Reference'][$definition]))
+ {
+ return;
+ }
+
+ $Definition = $this->DefinitionData['Reference'][$definition];
+
+ $Element['attributes']['href'] = $Definition['url'];
+ $Element['attributes']['title'] = $Definition['title'];
+ }
+
+ $Element['attributes']['href'] = str_replace(array('&', '<'), array('&amp;', '&lt;'), $Element['attributes']['href']);
+
+ return array(
+ 'extent' => $extent,
+ 'element' => $Element,
+ );
+ }
+
+ protected function inlineMarkup($Excerpt)
+ {
+ if ($this->markupEscaped or strpos($Excerpt['text'], '>') === false)
+ {
+ return;
+ }
+
+ if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w*[ ]*>/s', $Excerpt['text'], $matches))
+ {
+ return array(
+ 'markup' => $matches[0],
+ 'extent' => strlen($matches[0]),
+ );
+ }
+
+ if ($Excerpt['text'][1] === '!' and preg_match('/^<!---?[^>-](?:-?[^-])*-->/s', $Excerpt['text'], $matches))
+ {
+ return array(
+ 'markup' => $matches[0],
+ 'extent' => strlen($matches[0]),
+ );
+ }
+
+ if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w*(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*\/?>/s', $Excerpt['text'], $matches))
+ {
+ return array(
+ 'markup' => $matches[0],
+ 'extent' => strlen($matches[0]),
+ );
+ }
+ }
+
+ protected function inlineSpecialCharacter($Excerpt)
+ {
+ if ($Excerpt['text'][0] === '&' and ! preg_match('/^&#?\w+;/', $Excerpt['text']))
+ {
+ return array(
+ 'markup' => '&amp;',
+ 'extent' => 1,
+ );
+ }
+
+ $SpecialCharacter = array('>' => 'gt', '<' => 'lt', '"' => 'quot');
+
+ if (isset($SpecialCharacter[$Excerpt['text'][0]]))
+ {
+ return array(
+ 'markup' => '&'.$SpecialCharacter[$Excerpt['text'][0]].';',
+ 'extent' => 1,
+ );
+ }
+ }
+
+ protected function inlineStrikethrough($Excerpt)
+ {
+ if ( ! isset($Excerpt['text'][1]))
+ {
+ return;
+ }
+
+ if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches))
+ {
+ return array(
+ 'extent' => strlen($matches[0]),
+ 'element' => array(
+ 'name' => 'del',
+ 'text' => $matches[1],
+ 'handler' => 'line',
+ ),
+ );
+ }
+ }
+
+ protected function inlineUrl($Excerpt)
+ {
+ if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/')
+ {
+ return;
+ }
+
+ if (preg_match('/\bhttps?:[\/]{2}[^\s<]+\b\/*/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE))
+ {
+ $Inline = array(
+ 'extent' => strlen($matches[0][0]),
+ 'position' => $matches[0][1],
+ 'element' => array(
+ 'name' => 'a',
+ 'text' => $matches[0][0],
+ 'attributes' => array(
+ 'href' => $matches[0][0],
+ ),
+ ),
+ );
+
+ return $Inline;
+ }
+ }
+
+ protected function inlineUrlTag($Excerpt)
+ {
+ if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\w+:\/{2}[^ >]+)>/i', $Excerpt['text'], $matches))
+ {
+ $url = str_replace(array('&', '<'), array('&amp;', '&lt;'), $matches[1]);
+
+ return array(
+ 'extent' => strlen($matches[0]),
+ 'element' => array(
+ 'name' => 'a',
+ 'text' => $url,
+ 'attributes' => array(
+ 'href' => $url,
+ ),
+ ),
+ );
+ }
+ }
+
+ # ~
+
+ protected function unmarkedText($text)
+ {
+ if ($this->breaksEnabled)
+ {
+ $text = preg_replace('/[ ]*\n/', "<br />\n", $text);
+ }
+ else
+ {
+ $text = preg_replace('/(?:[ ][ ]+|[ ]*\\\\)\n/', "<br />\n", $text);
+ $text = str_replace(" \n", "\n", $text);
+ }
+
+ return $text;
+ }
+
+ #
+ # Handlers
+ #
+
+ protected function element(array $Element)
+ {
+ $markup = '<'.$Element['name'];
+
+ if (isset($Element['attributes']))
+ {
+ foreach ($Element['attributes'] as $name => $value)
+ {
+ if ($value === null)
+ {
+ continue;
+ }
+
+ $markup .= ' '.$name.'="'.$value.'"';
+ }
+ }
+
+ if (isset($Element['text']))
+ {
+ $markup .= '>';
+
+ if (isset($Element['handler']))
+ {
+ $markup .= $this->{$Element['handler']}($Element['text']);
+ }
+ else
+ {
+ $markup .= $Element['text'];
+ }
+
+ $markup .= '</'.$Element['name'].'>';
+ }
+ else
+ {
+ $markup .= ' />';
+ }
+
+ return $markup;
+ }
+
+ protected function elements(array $Elements)
+ {
+ $markup = '';
+
+ foreach ($Elements as $Element)
+ {
+ $markup .= "\n" . $this->element($Element);
+ }
+
+ $markup .= "\n";
+
+ return $markup;
+ }
+
+ # ~
+
+ protected function li($lines)
+ {
+ $markup = $this->lines($lines);
+
+ $trimmedMarkup = trim($markup);
+
+ if ( ! in_array('', $lines) and substr($trimmedMarkup, 0, 3) === '<p>')
+ {
+ $markup = $trimmedMarkup;
+ $markup = substr($markup, 3);
+
+ $position = strpos($markup, "</p>");
+
+ $markup = substr_replace($markup, '', $position, 4);
+ }
+
+ return $markup;
+ }
+
+ #
+ # Deprecated Methods
+ #
+
+ function parse($text)
+ {
+ $markup = $this->text($text);
+
+ return $markup;
+ }
+
+ #
+ # Static Methods
+ #
+
+ static function instance($name = 'default')
+ {
+ if (isset(self::$instances[$name]))
+ {
+ return self::$instances[$name];
+ }
+
+ $instance = new static();
+
+ self::$instances[$name] = $instance;
+
+ return $instance;
+ }
+
+ private static $instances = array();
+
+ #
+ # Fields
+ #
+
+ protected $DefinitionData;
+
+ #
+ # Read-Only
+
+ protected $specialCharacters = array(
+ '\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!', '|',
+ );
+
+ protected $StrongRegex = array(
+ '*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*[*])+?)[*]{2}(?![*])/s',
+ '_' => '/^__((?:\\\\_|[^_]|_[^_]*_)+?)__(?!_)/us',
+ );
+
+ protected $EmRegex = array(
+ '*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s',
+ '_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us',
+ );
+
+ protected $regexHtmlAttribute = '[a-zA-Z_:][\w:.-]*(?:\s*=\s*(?:[^"\'=<>`\s]+|"[^"]*"|\'[^\']*\'))?';
+
+ protected $voidElements = array(
+ 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source',
+ );
+
+ protected $textLevelElements = array(
+ 'a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont',
+ 'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing',
+ 'i', 'rp', 'del', 'code', 'strike', 'marquee',
+ 'q', 'rt', 'ins', 'font', 'strong',
+ 's', 'tt', 'sub', 'mark',
+ 'u', 'xm', 'sup', 'nobr',
+ 'var', 'ruby',
+ 'wbr', 'span',
+ 'time',
+ );
+}
diff --git a/core/namespace/Post/Attribute.php b/core/namespace/Post/Attribute.php
new file mode 100644
index 0000000..6f20183
--- /dev/null
+++ b/core/namespace/Post/Attribute.php
@@ -0,0 +1,22 @@
+<?php
+namespace Post;
+
+class Attribute extends \Attribute {
+
+ #===============================================================================
+ # Pre-Define database table columns
+ #===============================================================================
+ protected $id = FALSE;
+ protected $user = FALSE;
+ protected $slug = FALSE;
+ protected $name = FALSE;
+ protected $body = FALSE;
+ protected $time_insert = FALSE;
+ protected $time_update = FALSE;
+
+ #===============================================================================
+ # Define database table name
+ #===============================================================================
+ const TABLE = 'post';
+}
+?> \ No newline at end of file
diff --git a/core/namespace/Post/Exception.php b/core/namespace/Post/Exception.php
new file mode 100644
index 0000000..516ddbe
--- /dev/null
+++ b/core/namespace/Post/Exception.php
@@ -0,0 +1,5 @@
+<?php
+namespace Post;
+
+class Exception extends \Exception {}
+?> \ No newline at end of file
diff --git a/core/namespace/Post/Factory.php b/core/namespace/Post/Factory.php
new file mode 100644
index 0000000..34aa5e4
--- /dev/null
+++ b/core/namespace/Post/Factory.php
@@ -0,0 +1,9 @@
+<?php
+namespace Post;
+
+class Factory extends \ItemFactory {
+ public static function buildBySlug($slug): \Item {
+ return self::build(Item::getIDByField('slug', $slug, \Application::getDatabase()));
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/Post/Item.php b/core/namespace/Post/Item.php
new file mode 100644
index 0000000..a269ce4
--- /dev/null
+++ b/core/namespace/Post/Item.php
@@ -0,0 +1,50 @@
+<?php
+namespace Post;
+
+class Item extends \Item {
+ const CONFIGURATION = 'POST';
+
+ #===============================================================================
+ # Return absolute post URL
+ #===============================================================================
+ public function getURL(): string {
+ if(\Application::get('POST.SLUG_URLS')) {
+ return \Application::getPostURL("{$this->Attribute->get('slug')}/");
+ }
+
+ return \Application::getPostURL("{$this->Attribute->get('id')}/");
+ }
+
+ #===============================================================================
+ # Return unique pseudo GUID
+ #===============================================================================
+ public function getGUID(): string {
+ foreach(\Application::get('POST.FEED_GUID') as $attribute) {
+ $attributes[] = $this->Attribute->get($attribute);
+ }
+
+ return sha1(implode(NULL, $attributes));
+ }
+
+ #===============================================================================
+ # Return unique post IDs for search results
+ #===============================================================================
+ public static function getSearchResultIDs($search, array $date, \Database $Database): array {
+ $D = ($D = intval($date[0])) !== 0 ? $D : 'NULL';
+ $M = ($M = intval($date[1])) !== 0 ? $M : 'NULL';
+ $Y = ($Y = intval($date[2])) !== 0 ? $Y : 'NULL';
+
+ $Statement = $Database->prepare(sprintf("SELECT id FROM %s WHERE
+ ({$Y} IS NULL OR YEAR(time_insert) = {$Y}) AND
+ ({$M} IS NULL OR MONTH(time_insert) = {$M}) AND
+ ({$D} IS NULL OR DAY(time_insert) = {$D}) AND
+ MATCH(name, body) AGAINST(? IN BOOLEAN MODE) LIMIT 20", Attribute::TABLE));
+
+ if($Statement->execute([$search])) {
+ return $Statement->fetchAll($Database::FETCH_COLUMN);
+ }
+
+ return [];
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/Template/Exception.php b/core/namespace/Template/Exception.php
new file mode 100644
index 0000000..52c522e
--- /dev/null
+++ b/core/namespace/Template/Exception.php
@@ -0,0 +1,5 @@
+<?php
+namespace Template;
+
+class Exception extends \ExceptionHandler {}
+?> \ No newline at end of file
diff --git a/core/namespace/Template/Factory.php b/core/namespace/Template/Factory.php
new file mode 100644
index 0000000..a90c61e
--- /dev/null
+++ b/core/namespace/Template/Factory.php
@@ -0,0 +1,18 @@
+<?php
+namespace Template;
+
+class Factory extends \Factory implements \FactoryInterface {
+ public static function build($template): Template {
+ $Template = new Template(ROOT.'template/'.\Application::get('TEMPLATE.NAME')."/html/{$template}.php");
+ $Template->set('Language', \Application::getLanguage());
+ $Template->set('BLOGMETA', [
+ 'NAME' => \Application::get('BLOGMETA.NAME'),
+ 'DESC' => \Application::get('BLOGMETA.DESC'),
+ 'MAIL' => \Application::get('BLOGMETA.MAIL'),
+ 'LANG' => \Application::get('BLOGMETA.LANG'),
+ ]);
+
+ return $Template;
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/Template/Template.php b/core/namespace/Template/Template.php
new file mode 100644
index 0000000..0c68f92
--- /dev/null
+++ b/core/namespace/Template/Template.php
@@ -0,0 +1,72 @@
+<?php
+namespace Template;
+
+class Template {
+ private $filename = '';
+ private $parameters = [];
+
+ #===============================================================================
+ # Create template instance
+ #===============================================================================
+ public function __construct($filename) {
+ $this->filename = $filename;
+
+ if(!file_exists($filename)) {
+ throw new Exception("Template {$filename} does not exists.");
+ }
+ }
+
+ #===============================================================================
+ # Set value to array path
+ #===============================================================================
+ public function set($name, $value) {
+ if(!is_array($name)) {
+ return $this->parameters[$name] = $value;
+ }
+
+ $current = &$this->parameters;
+
+ foreach($name as $path) {
+ if(!isset($current[$path])) {
+ $current[$path] = [];
+ }
+ $current = &$current[$path];
+ }
+
+ return $current = $value;
+ }
+
+ #===============================================================================
+ # Add value as item to array path
+ #===============================================================================
+ public function add($paths, $value) {
+ if(!is_array($paths)) {
+ return $this->parameters[$paths][] = $value;
+ }
+
+ $current = &$this->parameters;
+
+ foreach($paths as $path) {
+ if(!isset($current[$path])) {
+ $current[$path] = [];
+ }
+ $current = &$current[$path];
+ }
+
+ return $current[] = $value;
+ }
+
+ #===============================================================================
+ # Return parsed template content
+ #===============================================================================
+ public function __toString() {
+ foreach($this->parameters as $name => $value) {
+ ${$name} = $value;
+ }
+
+ ob_start();
+ require $this->filename;
+ return ob_get_clean();
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/User/Attribute.php b/core/namespace/User/Attribute.php
new file mode 100644
index 0000000..b161fa9
--- /dev/null
+++ b/core/namespace/User/Attribute.php
@@ -0,0 +1,24 @@
+<?php
+namespace User;
+
+class Attribute extends \Attribute {
+
+ #===============================================================================
+ # Pre-Define database table columns
+ #===============================================================================
+ protected $id = FALSE;
+ protected $slug = FALSE;
+ protected $username = FALSE;
+ protected $password = FALSE;
+ protected $fullname = FALSE;
+ protected $mailaddr = FALSE;
+ protected $body = FALSE;
+ protected $time_insert = FALSE;
+ protected $time_update = FALSE;
+
+ #===============================================================================
+ # Define database table name
+ #===============================================================================
+ const TABLE = 'user';
+}
+?> \ No newline at end of file
diff --git a/core/namespace/User/Exception.php b/core/namespace/User/Exception.php
new file mode 100644
index 0000000..b5bcad0
--- /dev/null
+++ b/core/namespace/User/Exception.php
@@ -0,0 +1,5 @@
+<?php
+namespace User;
+
+class Exception extends \Exception {}
+?> \ No newline at end of file
diff --git a/core/namespace/User/Factory.php b/core/namespace/User/Factory.php
new file mode 100644
index 0000000..80e6b49
--- /dev/null
+++ b/core/namespace/User/Factory.php
@@ -0,0 +1,13 @@
+<?php
+namespace User;
+
+class Factory extends \ItemFactory {
+ public static function buildBySlug($slug): \Item {
+ return self::build(Item::getIDByField('slug', $slug, \Application::getDatabase()));
+ }
+
+ public static function buildByUsername($username): \Item {
+ return self::build(Item::getIDByField('username', $username, \Application::getDatabase()));
+ }
+}
+?> \ No newline at end of file
diff --git a/core/namespace/User/Item.php b/core/namespace/User/Item.php
new file mode 100644
index 0000000..129d8f9
--- /dev/null
+++ b/core/namespace/User/Item.php
@@ -0,0 +1,36 @@
+<?php
+namespace User;
+
+class Item extends \Item {
+ const CONFIGURATION = 'USER';
+
+ #===============================================================================
+ # Return absolute user URL
+ #===============================================================================
+ public function getURL(): string {
+ if(\Application::get('USER.SLUG_URLS')) {
+ return \Application::getUserURL("{$this->Attribute->get('slug')}/");
+ }
+
+ return \Application::getUserURL("{$this->Attribute->get('id')}/");
+ }
+
+ #===============================================================================
+ # Return unique pseudo GUID
+ #===============================================================================
+ public function getGUID(): string {
+ foreach(['id', 'time_insert'] as $attribute) {
+ $attributes[] = $this->Attribute->get($attribute);
+ }
+
+ return sha1(implode(NULL, $attributes));
+ }
+
+ #===============================================================================
+ # Compare plaintext password with hashed password from database
+ #===============================================================================
+ public function comparePassword($password): bool {
+ return password_verify($password, $this->Attribute->get('password'));
+ }
+}
+?> \ No newline at end of file