summaryrefslogtreecommitdiff
path: root/lib/markup.php
blob: 9872dae2a0dc426c07d55ffa160389681684301d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php

require_once 'lib/ext/MyParsedown.php';

class markup {

    public static function markdownToHtml(string $md, bool $use_image_previews = true): string {
        $pd = new MyParsedown(useImagePreviews: $use_image_previews);
        return $pd->text($md);
    }

    public static function toc(string $md): string {
        $pd = new MyParsedown([
            'toc' => [
                'lowercase' => true,
                'transliterate' => true,
                'urlencode' => false,
                'headings' => ['h1', 'h2', 'h3']
            ]
        ]);
        $pd->text($md);
        return $pd->contentsList();
    }

    public static function htmlToText(string $html): string {
        $text = html_entity_decode(strip_tags($html));
        $lines = explode("\n", $text);
        $lines = array_map('trim', $lines);
        $text = implode("\n", $lines);
        $text = preg_replace("/(\r?\n){2,}/", "\n\n", $text);
        return $text;
    }

    public static function htmlImagesFix(string $html, bool $is_retina, string $user_theme): string {
        global $config;
        $is_dark_theme = $user_theme === 'dark';
        return preg_replace_callback(
            '/('.preg_quote($config['uploads_host'], '/').'\/\w{8}\/)([ap])(\d+)x(\d+)(\.jpg)/',
            function($match) use ($is_retina, $is_dark_theme) {
                $mult = $is_retina ? 2 : 1;
                $is_alpha = $match[2] == 'a';
                return $match[1].$match[2].(intval($match[3])*$mult).'x'.(intval($match[4])*$mult).($is_alpha && $is_dark_theme ? '_dark' : '').$match[5];
            },
            $html
        );
    }

}