aboutsummaryrefslogtreecommitdiff
path: root/engine/skin.php
blob: 6150668f614b4b0fa04bf9c693ea35c81749b370 (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
<?php

require_once 'lib/themes.php';

$SkinState = new class {
    public array $lang = [];
    public string $title = 'title';
    public array $meta = [];
    public array $options = [
        'full_width' => false,
        'wide' => false,
        'dynlogo_enabled' => true,
        'logo_path_map' => [],
        'logo_link_map' => [],
    ];
    public array $static = [];
};

function render($f, ...$vars): void {
    global $SkinState;

    $f = '\\skin\\'.str_replace('/', '\\', $f);
    $ctx = new SkinContext(substr($f, 0, ($pos = strrpos($f, '\\'))));
    $body = call_user_func_array([$ctx, substr($f, $pos + 1)], $vars);
    if (is_array($body))
        list($body, $js) = $body;
    else
        $js = null;

    $theme = getUserTheme();
    if ($theme != 'auto' && !themeExists($theme))
        $theme = 'auto';

    $layout_ctx = new SkinContext('\\skin\\base');

    $lang = [];
    foreach ($SkinState->lang as $key)
        $lang[$key] = lang($key);
    $lang = !empty($lang) ? json_encode($lang, JSON_UNESCAPED_UNICODE) : '';

    $html = $layout_ctx->layout(
        static: $SkinState->static,
        theme: $theme,
        title: $SkinState->title,
        opts: $SkinState->options,
        js: $js,
        meta: $SkinState->meta,
        unsafe_lang: $lang,
        unsafe_body: $body,
        exec_time: exectime()
    );
    echo $html;
    exit;
}

function set_title(string $title): void {
    global $SkinState;
    if (str_starts_with($title, '$'))
        $title = lang(substr($title, 1));
    else if (str_starts_with($title, '\\$'))
        $title = substr($title, 1);
    $SkinState->title = $title;
}

function set_skin_opts(array $options) {
    global $SkinState;
    $SkinState->options = array_merge($SkinState->options, $options);
}

function add_skin_strings(array $keys): void {
    global $SkinState;
    $SkinState->lang = array_merge($SkinState->lang, $keys);
}

function add_skin_strings_re(string $re): void {
    global $__lang;
    add_skin_strings($__lang->search($re));
}

function add_static(string ...$files): void {
    global $SkinState;
    foreach ($files as $file)
        $SkinState->static[] = $file;
}

function add_meta(array ...$data) {
    global $SkinState;
    $SkinState->meta = array_merge($SkinState->meta, $data);
}


class SkinContext {

    protected string $ns;
    protected array $data = [];

    function __construct(string $namespace) {
        $this->ns = $namespace;
        require_once APP_ROOT.str_replace('\\', DIRECTORY_SEPARATOR, $namespace).'.skin.php';
    }

    function __call($name, array $arguments) {
        $plain_args = array_is_list($arguments);

        $fn = $this->ns.'\\'.$name;
        $refl = new ReflectionFunction($fn);
        $fparams = $refl->getParameters();
        assert(count($fparams) == count($arguments) + 1, "$fn: invalid number of arguments (".count($fparams)." != ".(count($arguments) + 1).")");

        foreach ($fparams as $n => $param) {
            if ($n == 0)
                continue; // skip $ctx

            $key = $plain_args ? $n - 1 : $param->name;
            if (!$plain_args && !array_key_exists($param->name, $arguments)) {
                if (!$param->isDefaultValueAvailable())
                    throw new InvalidArgumentException('argument '.$param->name.' not found');
                else
                    continue;
            }

            if (is_string($arguments[$key]) || $arguments[$key] instanceof SkinString) {
                if (is_string($arguments[$key]))
                    $arguments[$key] = new SkinString($arguments[$key]);

                if (($pos = strpos($param->name, '_')) !== false) {
                    $mod_type = match (substr($param->name, 0, $pos)) {
                        'unsafe' => SkinStringModificationType::RAW,
                        'urlencoded' => SkinStringModificationType::URL,
                        'jsonencoded' => SkinStringModificationType::JSON,
                        'addslashes' => SkinStringModificationType::ADDSLASHES,
                        default => SkinStringModificationType::HTML
                    };
                } else {
                    $mod_type = SkinStringModificationType::HTML;
                }
                $arguments[$key]->setModType($mod_type);
            }
        }

        array_unshift($arguments, $this);
        return call_user_func_array($fn, $arguments);
    }

    function &__get(string $name) {
        $fn = $this->ns.'\\'.$name;
        if (function_exists($fn)) {
            $f = [$this, $name];
            return $f;
        }

        if (array_key_exists($name, $this->data))
            return $this->data[$name];
    }

    function __set(string $name, $value) {
        $this->data[$name] = $value;
    }

    function if_not($cond, $callback, ...$args) {
        return $this->_if_condition(!$cond, $callback, ...$args);
    }

    function if_true($cond, $callback, ...$args) {
        return $this->_if_condition($cond, $callback, ...$args);
    }

    function if_admin($callback, ...$args) {
        return $this->_if_condition(is_admin(), $callback, ...$args);
    }

    function if_dev($callback, ...$args) {
        return $this->_if_condition(is_dev(), $callback, ...$args);
    }

    function if_then_else($cond, $cb1, $cb2) {
        return $cond ? $this->_return_callback($cb1) : $this->_return_callback($cb2);
    }

    function csrf($key): string {
        return csrf_get($key);
    }

    protected function _if_condition($condition, $callback, ...$args) {
        if (is_string($condition) || $condition instanceof Stringable)
            $condition = (string)$condition !== '';
        if ($condition)
            return $this->_return_callback($callback, $args);
        return '';
    }

    protected function _return_callback($callback, $args = []) {
        if (is_callable($callback))
            return call_user_func_array($callback, $args);
        else if (is_string($callback))
            return $callback;
    }

    function for_each(array $iterable, callable $callback) {
        $html = '';
        foreach ($iterable as $k => $v)
            $html .= call_user_func($callback, $v, $k);
        return $html;
    }

    function lang(...$args): string {
        return htmlescape($this->langRaw(...$args));
    }

    function langRaw(string $key, ...$args) {
        $val = lang($key);
        return empty($args) ? $val : sprintf($val, ...$args);
    }

}


enum SkinStringModificationType {
    case RAW;
    case URL;
    case HTML;
    case JSON;
    case ADDSLASHES;
}

class SkinString implements Stringable {
    protected SkinStringModificationType $modType;

    function __construct(protected string $string) {}
    function setModType(SkinStringModificationType $modType) { $this->modType = $modType; }

    function __toString(): string {
        return match ($this->modType) {
            SkinStringModificationType::HTML => htmlescape($this->string),
            SkinStringModificationType::URL => urlencode($this->string),
            SkinStringModificationType::JSON => json_encode($this->string, JSON_UNESCAPED_UNICODE),
            SkinStringModificationType::ADDSLASHES => addslashes($this->string),
            default => $this->string,
        };
    }
}