diff options
author | Thomas Lange <code@nerdmind.de> | 2017-02-24 21:27:59 +0100 |
---|---|---|
committer | Thomas Lange <code@nerdmind.de> | 2017-02-24 21:27:59 +0100 |
commit | 52b077a48c743ba4d08ac00520a0bf1ef6deef5f (patch) | |
tree | b4205c194167e0e03e273957cdd0aab3be9fdf01 /core/namespace | |
download | blog-52b077a48c743ba4d08ac00520a0bf1ef6deef5f.tar.gz blog-52b077a48c743ba4d08ac00520a0bf1ef6deef5f.tar.xz blog-52b077a48c743ba4d08ac00520a0bf1ef6deef5f.zip |
Initial commit.v1.0
Diffstat (limited to 'core/namespace')
28 files changed, 2589 insertions, 0 deletions
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('&', '<'), $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' => '&', + '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('&', '<'), $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 |