From: Ben Sherratt Date: Sun, 14 Jan 2024 11:29:28 +0000 (+0000) Subject: Custom markdown for inserting images X-Git-Url: https://git.bts.cx/cx.git/commitdiff_plain/a33491c3a25cf858b67f279c10d93e0eb863ad92?ds=sidebyside;hp=c469f0f84d54065f375698e891da3461abaf661f Custom markdown for inserting images --- diff --git a/cx/lib/images.php b/cx/lib/images.php index fd6d622..dbe55bf 100644 --- a/cx/lib/images.php +++ b/cx/lib/images.php @@ -58,11 +58,30 @@ function cx_images_get(int $limit = 0) { $sql .= ';'; foreach (cx_db_query($sql) as $image) { - $p = new Image($image); - yield $p; + $i = new Image($image); + yield $i; } } +function cx_images_find_image($image_id) { + $sql = 'SELECT + image_id, + image_uid, + image_type, + image_alt_text + FROM images + WHERE image_id == ? + OR image_uid LIKE ? + LIMIT 1;'; + + foreach (cx_db_query($sql, $image_id, $image_id . "%") as $image) { + $i = new Image($image); + return $i; + } + + return null; +} + cx_setup_register(1, function() { cx_db_exec('CREATE TABLE images ( image_id INTEGER PRIMARY KEY, diff --git a/cx/lib/markdown.php b/cx/lib/markdown.php new file mode 100644 index 0000000..8cdc235 --- /dev/null +++ b/cx/lib/markdown.php @@ -0,0 +1,41 @@ +InlineTypes['{'][]= 'BlogImage'; + $this->inlineMarkerList .= '{'; + } + + protected function inlineBlogImage($excerpt) { + if (preg_match('/^{img:([^}]+)}/', $excerpt['text'], $matches)) { + $image_id = $matches[1]; + $image = cx_images_find_image($image_id); + + if ($image == null) { + return; + } + + $permalink = '/data/images/' . $image->url; + + return array( + 'extent' => strlen($matches[0]) + 1, + 'element' => array( + 'name' => 'img', + 'attributes' => array( + 'src' => cx_url($permalink), + 'alt' => $image->alt_text, + ), + ), + ); + } + } +} + +function cx_markdown_generate_html($markdown) { + static $Parsedown = new ExtendedParsedown(); + return $Parsedown->text($markdown); +} diff --git a/cx/lib/posts.php b/cx/lib/posts.php index 0a2ac4d..988d00e 100644 --- a/cx/lib/posts.php +++ b/cx/lib/posts.php @@ -2,13 +2,7 @@ cx_require('lib', 'db.php'); cx_require('lib', 'setup.php'); -cx_require('third_party', 'parsedown', 'Parsedown.php'); - -function mk_markdown($markdown) { - static $Parsedown = new Parsedown(); - - return $Parsedown->text($markdown); -} +cx_require('lib', 'markdown.php'); class PostMetadata { public $hero_image; @@ -37,13 +31,13 @@ class Post { $this->date = $dict['post_date']; $this->is_draft = $dict['post_is_draft']; $this->data = $dict['post_data']; - $this->html_content = mk_markdown($this->data); + $this->html_content = cx_markdown_generate_html($this->data); $this->html_excerpt = null; // Read more... $segments = explode('---', $this->data, 2); if (count($segments) > 1) { - $this->html_excerpt = mk_markdown($segments[0]); + $this->html_excerpt = cx_markdown_generate_html($segments[0]); } }