Ported Template class from Hanyuu project.

This commit is contained in:
flash 2019-12-04 19:16:22 +01:00
parent 9cee637094
commit 96ea7772cb
51 changed files with 148 additions and 184 deletions

View file

@ -50,7 +50,6 @@ require_once 'src/otp.php';
require_once 'src/pagination.php';
require_once 'src/perms.php';
require_once 'src/string.php';
require_once 'src/tpl.php';
require_once 'src/twitter.php';
require_once 'src/url.php';
require_once 'src/zalgo.php';
@ -402,24 +401,20 @@ MIG;
mkdirs($twigCache, true);
}
tpl_init([
'debug' => MSZ_DEBUG,
'auto_reload' => MSZ_DEBUG,
'cache' => $twigCache ?? false,
]);
Template::init($twigCache ?? null, MSZ_DEBUG);
tpl_var('globals', [
Template::set('globals', [
'site_name' => Config::get('site.name', Config::TYPE_STR, 'Misuzu'),
'site_description' => Config::get('site.desc', Config::TYPE_STR),
'site_url' => Config::get('site.url', Config::TYPE_STR),
'site_twitter' => Config::get('social.twitter', Config::TYPE_STR),
]);
tpl_add_path(MSZ_ROOT . '/templates');
Template::addPath(MSZ_ROOT . '/templates');
if(file_exists(MSZ_ROOT . '/.migrating')) {
http_response_code(503);
echo tpl_render('home.migration');
Template::render('home.migration');
exit;
}
@ -499,14 +494,14 @@ MIG;
}
if(!empty($userDisplayInfo)) {
tpl_var('current_user', $userDisplayInfo);
Template::set('current_user', $userDisplayInfo);
}
$inManageMode = starts_with($_SERVER['REQUEST_URI'], '/manage');
$hasManageAccess = !empty($userDisplayInfo['user_id'])
&& !user_warning_check_restriction($userDisplayInfo['user_id'])
&& perms_check_user(MSZ_PERMS_GENERAL, $userDisplayInfo['user_id'], MSZ_PERM_GENERAL_CAN_MANAGE);
tpl_var('has_manage_access', $hasManageAccess);
Template::set('has_manage_access', $hasManageAccess);
if($inManageMode) {
if(!$hasManageAccess) {
@ -514,6 +509,6 @@ MIG;
exit;
}
tpl_var('manage_menu', manage_get_menu($userDisplayInfo['user_id'] ?? 0));
Template::set('manage_menu', manage_get_menu($userDisplayInfo['user_id'] ?? 0));
}
}

View file

@ -1,15 +1,13 @@
<?php
namespace Misuzu;
// Delete this file in April 2019
require_once '../misuzu.php';
$mode = !empty($_GET['m']) && is_string($_GET['m']) ? $_GET['m'] : '';
switch($mode) {
case 'logout':
echo tpl_render('auth.logout');
Template::render('auth.logout');
break;
case 'reset':

View file

@ -116,7 +116,7 @@ $sitePrivateMessage = $siteIsPrivate ? Config::get('private.msg', Config::TYPE_S
$canResetPassword = $siteIsPrivate ? Config::get('private.allow_password_reset', Config::TYPE_BOOL, true) : true;
$canRegisterAccount = !$siteIsPrivate;
echo tpl_render('auth.login', [
Template::render('auth.login', [
'login_notices' => $notices,
'login_username' => $loginUsername,
'login_redirect' => $loginRedirect,

View file

@ -15,4 +15,4 @@ if(csrf_verify_request()) {
return;
}
echo tpl_render('auth.logout');
Template::render('auth.logout');

View file

@ -126,7 +126,7 @@ while($canResetPassword) {
break;
}
echo tpl_render($userId > 0 ? 'auth.password_reset' : 'auth.password_forgot', [
Template::render($userId > 0 ? 'auth.password_reset' : 'auth.password_forgot', [
'password_notices' => $notices,
'password_email' => !empty($forget['email']) && is_string($forget['email']) ? $forget['email'] : '',
'password_attempts_remaining' => $remainingAttempts,

View file

@ -85,7 +85,7 @@ while(!$restricted && !empty($register)) {
return;
}
echo tpl_render('auth.register', [
Template::render('auth.register', [
'register_notices' => $notices,
'register_username' => !empty($register['username']) && is_string($register['username']) ? $register['username'] : '',
'register_email' => !empty($register['email']) && is_string($register['email']) ? $register['email'] : '',

View file

@ -80,7 +80,7 @@ while(!empty($twofactor)) {
return;
}
echo tpl_render('auth.twofactor', [
Template::render('auth.twofactor', [
'twofactor_notices' => $notices,
'twofactor_redirect' => !empty($_GET['redirect']) && is_string($_GET['redirect']) ? $_GET['redirect'] : url('index'),
'twofactor_attempts_remaining' => $remainingAttempts,

View file

@ -8,7 +8,7 @@ $changelogDate = !empty($_GET['d']) && is_string($_GET['d']) ? (string)$_GET['d'
$changelogUser = !empty($_GET['u']) && is_string($_GET['u']) ? (int)$_GET['u'] : 0;
$changelogTags = !empty($_GET['t']) && is_string($_GET['t']) ? (string)$_GET['t'] : '';
tpl_var('comments_perms', $commentPerms = comments_get_perms(user_session_current('user_id', 0)));
Template::set('comments_perms', $commentPerms = comments_get_perms(user_session_current('user_id', 0)));
if($changelogChange > 0) {
$change = changelog_change_get($changelogChange);
@ -18,7 +18,7 @@ if($changelogChange > 0) {
return;
}
echo tpl_render('changelog.change', [
Template::render('changelog.change', [
'change' => $change,
'tags' => changelog_change_tags_get($change['change_id']),
'comments_category' => $commentsCategory = comments_category_info(
@ -53,13 +53,13 @@ if(!$changes) {
}
if(!empty($changelogDate) && count($changes) > 0) {
tpl_vars([
Template::set([
'comments_category' => $commentsCategory = comments_category_info("changelog-date-{$changelogDate}", true),
'comments' => comments_category_get($commentsCategory['category_id'], user_session_current('user_id', 0)),
]);
}
echo tpl_render('changelog.index', [
Template::render('changelog.index', [
'changes' => $changes,
'changelog_count' => $changesCount,
'changelog_date' => $changelogDate,

View file

@ -30,7 +30,7 @@ if(user_warning_check_restriction($forumUserId)) {
$perms &= ~MSZ_FORUM_PERM_SET_WRITE;
}
tpl_var('forum_perms', $perms);
Template::set('forum_perms', $perms);
if($forum['forum_type'] == MSZ_FORUM_TYPE_LINK) {
forum_increment_clicks($forum['forum_id']);
@ -69,7 +69,7 @@ if($forumMayHaveChildren) {
}
}
echo tpl_render('forum.forum', [
Template::render('forum.forum', [
'forum_breadcrumbs' => forum_get_breadcrumbs($forum['forum_id']),
'global_accent_colour' => forum_get_colour($forum['forum_id']),
'forum_may_have_topics' => $forumMayHaveTopics,

View file

@ -40,7 +40,7 @@ switch($indexMode) {
}
}
echo tpl_render('forum.index', [
Template::render('forum.index', [
'forum_categories' => $categories,
'forum_empty' => $blankForum,
]);

View file

@ -46,10 +46,10 @@ MD;
$markdown .= sprintf("| %s | [%s](%s%s) | %s |\r\n", $user['rank'], $user['username'], url_prefix(false), url('user-profile', ['user' => $user['user_id']]), $user['posts']);
}
tpl_var('leaderboard_markdown', $markdown);
Template::set('leaderboard_markdown', $markdown);
}
echo tpl_render('forum.leaderboard', [
Template::render('forum.leaderboard', [
'leaderboard_id' => $leaderboardId,
'leaderboard_name' => $leaderboardName,
'leaderboard_categories' => $leaderboards,

View file

@ -121,7 +121,7 @@ switch($postMode) {
]);
break;
} elseif(!$postRequestVerified) {
echo tpl_render('forum.confirm', [
Template::render('forum.confirm', [
'title' => 'Confirm post deletion',
'class' => 'far fa-trash-alt',
'message' => sprintf('You are about to delete post #%d. Are you sure about that?', $postInfo['post_id']),
@ -171,7 +171,7 @@ switch($postMode) {
]);
break;
} elseif(!$postRequestVerified) {
echo tpl_render('forum.confirm', [
Template::render('forum.confirm', [
'title' => 'Confirm post nuke',
'class' => 'fas fa-radiation',
'message' => sprintf('You are about to PERMANENTLY DELETE post #%d. Are you sure about that?', $postInfo['post_id']),
@ -213,7 +213,7 @@ switch($postMode) {
]);
break;
} elseif(!$postRequestVerified) {
echo tpl_render('forum.confirm', [
Template::render('forum.confirm', [
'title' => 'Confirm post restore',
'class' => 'fas fa-magic',
'message' => sprintf('You are about to restore post #%d. Are you sure about that?', $postInfo['post_id']),

View file

@ -238,16 +238,16 @@ if(!empty($_POST)) {
}
if(!empty($topic)) {
tpl_var('posting_topic', $topic);
Template::set('posting_topic', $topic);
}
if($mode === 'edit') { // $post is pretty much sure to be populated at this point
tpl_var('posting_post', $post);
Template::set('posting_post', $post);
}
$displayInfo = forum_posting_info(user_session_current('user_id'));
echo tpl_render('forum.posting', [
Template::render('forum.posting', [
'posting_breadcrumbs' => forum_get_breadcrumbs($forumId),
'global_accent_colour' => forum_get_colour($forumId),
'posting_forum' => $forum,

View file

@ -163,7 +163,7 @@ if(in_array($moderationMode, $validModerationModes, true)) {
if(!$isXHR) {
if(!isset($_GET['confirm'])) {
echo tpl_render('forum.confirm', [
Template::render('forum.confirm', [
'title' => 'Confirm topic deletion',
'class' => 'far fa-trash-alt',
'message' => sprintf('You are about to delete topic #%d. Are you sure about that?', $topic['topic_id']),
@ -215,7 +215,7 @@ if(in_array($moderationMode, $validModerationModes, true)) {
if(!$isXHR) {
if(!isset($_GET['confirm'])) {
echo tpl_render('forum.confirm', [
Template::render('forum.confirm', [
'title' => 'Confirm topic restore',
'class' => 'fas fa-magic',
'message' => sprintf('You are about to restore topic #%d. Are you sure about that?', $topic['topic_id']),
@ -258,7 +258,7 @@ if(in_array($moderationMode, $validModerationModes, true)) {
if(!$isXHR) {
if(!isset($_GET['confirm'])) {
echo tpl_render('forum.confirm', [
Template::render('forum.confirm', [
'title' => 'Confirm topic nuke',
'class' => 'fas fa-radiation',
'message' => sprintf('You are about to PERMANENTLY DELETE topic #%d. Are you sure about that?', $topic['topic_id']),
@ -351,7 +351,7 @@ if(!pagination_is_valid_offset($postsOffset)) {
return;
}
tpl_var('topic_perms', $perms);
Template::set('topic_perms', $perms);
$posts = forum_post_listing(
$topic['topic_id'],
@ -369,7 +369,7 @@ $canReply = !$topicIsArchived && !$topicIsLocked && !$topicIsDeleted && perms_ch
forum_topic_mark_read($topicUserId, $topic['topic_id'], $topic['forum_id']);
echo tpl_render('forum.topic', [
Template::render('forum.topic', [
'topic_breadcrumbs' => forum_get_breadcrumbs($topic['forum_id']),
'global_accent_colour' => forum_get_colour($topic['forum_id']),
'topic_info' => $topic,

View file

@ -11,7 +11,7 @@ if($requestPath !== '/' && $requestPath !== $_SERVER['PHP_SELF']) {
}
if(Config::get('social.embed_linked', Config::TYPE_BOOL)) {
tpl_var('linked_data', [
Template::set('linked_data', [
'name' => Config::get('site.name', Config::TYPE_STR, 'Misuzu'),
'url' => Config::get('site.url', Config::TYPE_STR),
'logo' => Config::get('site.ext_logo', Config::TYPE_STR),
@ -91,7 +91,7 @@ $onlineUsers = DB::query('
LIMIT 104
')->fetchAll();
tpl_vars([
Template::set([
'statistics' => $stats,
'latest_user' => $latestUser,
'online_users' => $onlineUsers,
@ -100,4 +100,4 @@ tpl_vars([
'featured_news' => $news,
]);
echo tpl_render('home.landing');
Template::render('home.landing');

View file

@ -6,7 +6,7 @@ require_once '../misuzu.php';
$pathInfo = $_SERVER['PATH_INFO'] ?? '';
if(empty($pathInfo) || $pathInfo === '/') {
echo tpl_render('info.index');
Template::render('info.index');
return;
}
@ -59,6 +59,6 @@ if(empty($document['title'])) {
}
}
echo tpl_render('info.view', [
Template::render('info.view', [
'document' => $document,
]);

View file

@ -122,7 +122,7 @@ $getChangeTags = DB::prepare('
$getChangeTags->bind('change_id', $change['change_id'] ?? 0);
$changeTags = $getChangeTags->fetchAll();
echo tpl_render('manage.changelog.change', [
Template::render('manage.changelog.change', [
'change' => $change ?? null,
'change_tags' => $changeTags,
'change_actions' => $actions,

View file

@ -55,7 +55,7 @@ for($i = 0; $i < count($changes); $i++) {
$changes[$i]['tags'] = $getTags->fetchAll();
}
echo tpl_render('manage.changelog.changes', [
Template::render('manage.changelog.changes', [
'changelog_changes' => $changes,
'changelog_changes_count' => $changesCount,
'changelog_pagination' => $changelogPagination,

View file

@ -54,11 +54,11 @@ if($tagId > 0) {
$tag = $getTag->fetch();
if($tag) {
tpl_var('edit_tag', $tag);
Template::set('edit_tag', $tag);
} else {
url_redirect('manage-changelog-tags');
return;
}
}
echo tpl_render('manage.changelog.tag');
Template::render('manage.changelog.tag');

View file

@ -20,6 +20,6 @@ $getTags = DB::prepare('
ORDER BY t.`tag_id` ASC
');
echo tpl_render('manage.changelog.tags', [
Template::render('manage.changelog.tags', [
'changelog_tags' => $getTags->fetchAll(),
]);

View file

@ -21,4 +21,4 @@ if(!$forum) {
return;
}
echo tpl_render('manage.forum.forum', compact('forum'));
Template::render('manage.forum.forum', compact('forum'));

View file

@ -15,7 +15,7 @@ $perms = manage_forum_perms_list($rawPerms);
if(!empty($_POST['perms']) && is_array($_POST['perms'])) {
$finalPerms = manage_perms_apply($perms, $_POST['perms'], $rawPerms);
$perms = manage_forum_perms_list($finalPerms);
tpl_var('calculated_perms', $finalPerms);
Template::set('calculated_perms', $finalPerms);
}
echo tpl_render('manage.forum.listing', compact('forums', 'perms'));
Template::render('manage.forum.listing', compact('forums', 'perms'));

View file

@ -42,7 +42,7 @@ if(!empty($_POST)) {
}
}
echo tpl_render('manage.general.blacklist', [
Template::render('manage.general.blacklist', [
'notices' => $notices,
'blacklist' => ip_blacklist_list(),
]);

View file

@ -34,6 +34,6 @@ if(csrf_verify_request()
}
}
echo tpl_render('manage.general.emoticon', [
Template::render('manage.general.emoticon', [
'emote_info' => $emoteInfo ?? null,
]);

View file

@ -24,6 +24,6 @@ if(csrf_verify_request() && !empty($_GET['emote']) && is_string($_GET['emote']))
return;
}
echo tpl_render('manage.general.emoticons', [
Template::render('manage.general.emoticons', [
'emotes' => emotes_list(PHP_INT_MAX),
]);

View file

@ -177,6 +177,6 @@ if(!empty($_GET['poll'])) {
return;
}
echo tpl_render('manage.general.overview', [
Template::render('manage.general.overview', [
'statistics' => $statistics,
]);

View file

@ -18,7 +18,7 @@ if(!pagination_is_valid_offset($logsOffset)) {
$logs = audit_log_list($logsOffset, $logsPagination['range']);
echo tpl_render('manage.general.logs', [
Template::render('manage.general.logs', [
'global_logs' => $logs,
'global_logs_pagination' => $logsPagination,
'global_logs_strings' => MSZ_AUDIT_LOG_STRINGS,

View file

@ -8,4 +8,4 @@ if(!perms_check_user(MSZ_PERMS_GENERAL, user_session_current('user_id'), MSZ_PER
return;
}
echo tpl_render('manage.general.settings');
Template::render('manage.general.settings');

View file

@ -18,7 +18,7 @@ if(!pagination_is_valid_offset($categoriesOffset)) {
$categories = news_categories_get($categoriesOffset, $categoriesPagination['range'], true, false, true);
echo tpl_render('manage.news.categories', [
Template::render('manage.news.categories', [
'news_categories' => $categories,
'categories_pagination' => $categoriesPagination,
]);

View file

@ -33,4 +33,4 @@ if($categoryId > 0) {
$category = news_category_get($categoryId);
}
echo tpl_render('manage.news.category', compact('category'));
Template::render('manage.news.category', compact('category'));

View file

@ -54,4 +54,4 @@ if($postId > 0) {
$post = news_post_get($postId);
}
echo tpl_render('manage.news.post', compact('post', 'categories'));
Template::render('manage.news.post', compact('post', 'categories'));

View file

@ -18,7 +18,7 @@ if(!pagination_is_valid_offset($postsOffset)) {
$posts = news_posts_get($postsOffset, $postsPagination['range'], null, false, true, false);
echo tpl_render('manage.news.posts', [
Template::render('manage.news.posts', [
'news_posts' => $posts,
'posts_pagination' => $postsPagination,
]);

View file

@ -38,7 +38,7 @@ $getManageUsers->bind('offset', $usersOffset);
$getManageUsers->bind('take', $usersPagination['range']);
$manageUsers = $getManageUsers->fetchAll();
echo tpl_render('manage.users.users', [
Template::render('manage.users.users', [
'manage_users' => $manageUsers,
'manage_users_pagination' => $usersPagination,
]);

View file

@ -179,10 +179,10 @@ if($roleId !== null) {
return;
}
tpl_vars(['edit_role' => $editRole]);
Template::set(['edit_role' => $editRole]);
}
echo tpl_render('manage.users.role', [
Template::render('manage.users.role', [
'can_manage_perms' => $canEditPerms,
'permissions' => $permissions ?? [],
]);

View file

@ -36,7 +36,7 @@ $getManageRoles->bind('offset', $rolesOffset);
$getManageRoles->bind('take', $rolesPagination['range']);
$manageRoles = $getManageRoles->fetchAll();
echo tpl_render('manage.users.roles', [
Template::render('manage.users.roles', [
'manage_roles' => $manageRoles,
'manage_roles_pagination' => $rolesPagination,
]);

View file

@ -239,7 +239,7 @@ $getRoles = DB::prepare('
$getRoles->bind('user_id', $manageUser['user_id']);
$roles = $getRoles->fetchAll();
echo tpl_render('manage.users.user', [
Template::render('manage.users.user', [
'manage_user' => $manageUser,
'manage_notices' => $notices,
'manage_roles' => $roles,

View file

@ -147,7 +147,7 @@ $warningDurations = array_flip([
'Until (strtotime) ->' => -3,
]);
echo tpl_render('manage.users.warnings', [
Template::render('manage.users.warnings', [
'warnings' => [
'notices' => $notices,
'pagination' => $warningsPagination,

View file

@ -166,7 +166,7 @@ if(empty($users)) {
http_response_code(404);
}
echo tpl_render('user.listing', [
Template::render('user.listing', [
'roles' => $roles,
'role' => $role,
'users' => $users,

View file

@ -27,7 +27,7 @@ $posts = news_posts_get(
$featured = news_posts_get(0, 10, $category['category_id'], true);
echo tpl_render('news.category', [
Template::render('news.category', [
'category' => $category,
'posts' => $posts,
'featured' => $featured,

View file

@ -25,7 +25,7 @@ if(!$posts) {
return;
}
echo tpl_render('news.index', [
Template::render('news.index', [
'categories' => $categories,
'posts' => $posts,
'news_pagination' => $newsPagination,

View file

@ -25,7 +25,7 @@ if($post['comment_section_id'] === null) {
$commentsInfo = comments_category_info($post['comment_section_id']);
}
echo tpl_render('news.post', [
Template::render('news.post', [
'post' => $post,
'comments_perms' => comments_get_perms(user_session_current('user_id', 0)),
'comments_category' => $commentsInfo,

View file

@ -13,7 +13,7 @@ $profileUser = User::findForProfile($userId);
if(empty($profileUser)) {
http_response_code(404);
echo tpl_render('profile.index');
Template::render('profile.index');
return;
}
@ -52,7 +52,7 @@ if($isEditing) {
'edit_signature' => MSZ_PERM_USER_EDIT_SIGNATURE,
]);
tpl_vars([
Template::set([
'perms' => $perms,
'guidelines' => [
'avatar' => $avatarProps = user_avatar_default_options(),
@ -305,7 +305,7 @@ if(is_file($backgroundPath)) {
$backgroundInfo = getimagesize($backgroundPath);
if($backgroundInfo) {
tpl_var('site_background', [
Template::set('site_background', [
'url' => url('user-background', ['user' => $profileUser->user_id]),
'width' => $backgroundInfo[0],
'height' => $backgroundInfo[1],
@ -335,8 +335,8 @@ switch($profileMode) {
$followingOffset, $currentUserId
);
tpl_vars([
'title' => $profile['username'] . ' / following',
Template::set([
'title' => $profileUser->username . ' / following',
'canonical_url' => url('user-profile-following', ['user' => $profileUser->user_id]),
'profile_users' => $following,
'profile_relation_pagination' => $followingPagination,
@ -356,8 +356,8 @@ switch($profileMode) {
$followers = user_relation_users_to($profileUser->user_id, MSZ_USER_RELATION_FOLLOW, $followerPagination['range'], $followerOffset, $currentUserId);
tpl_vars([
'title' => $profile['username'] . ' / followers',
Template::set([
'title' => $profileUser->username . ' / followers',
'canonical_url' => url('user-profile-followers', ['user' => $profileUser->user_id]),
'profile_users' => $followers,
'profile_relation_pagination' => $followerPagination,
@ -377,8 +377,8 @@ switch($profileMode) {
$topics = forum_topic_listing_user($profileUser->user_id, $currentUserId, $topicsOffset, $topicsPagination['range']);
tpl_vars([
'title' => $profile['username'] . ' / topics',
Template::set([
'title' => $profileUser->username . ' / topics',
'canonical_url' => url('user-profile-forum-topics', ['user' => $profileUser->user_id, 'page' => pagination_param()]),
'profile_topics' => $topics,
'profile_topics_pagination' => $topicsPagination,
@ -398,8 +398,8 @@ switch($profileMode) {
$posts = forum_post_listing($profileUser->user_id, $postsOffset, $postsPagination['range'], false, true);
tpl_vars([
'title' => $profile['username'] . ' / posts',
Template::set([
'title' => $profileUser->username . ' / posts',
'canonical_url' => url('user-profile-forum-posts', ['user' => $profileUser->user_id, 'page' => pagination_param()]),
'profile_posts' => $posts,
'profile_posts_pagination' => $postsPagination,
@ -422,7 +422,7 @@ switch($profileMode) {
)
);
tpl_vars([
Template::set([
'profile_warnings' => $warnings,
'profile_warnings_view_private' => $viewingOwnProfile,
'profile_warnings_can_manage' => $canManageWarnings,
@ -431,7 +431,7 @@ switch($profileMode) {
}
if(!empty($template)) {
echo tpl_render($template, [
Template::render($template, [
'profile_user' => $profileUser,
'profile_stats' => $profileStats,
'profile_mode' => $profileMode,

View file

@ -69,7 +69,7 @@ if(!empty($searchQuery)) {
$users = $findUsers->fetchAll();
}
echo tpl_render('home.search', [
Template::render('home.search', [
'search_query' => $searchQuery,
'forum_topics' => $forumTopics ?? [],
'forum_posts' => $forumPosts ?? [],

View file

@ -41,7 +41,7 @@ if($isVerifiedRequest && isset($_POST['tfa']['enable']) && (bool)$twoFactorInfo[
if((bool)$_POST['tfa']['enable']) {
$tfaKey = totp_generate_key();
tpl_vars([
Template::set([
'settings_2fa_code' => $tfaKey,
'settings_2fa_image' => totp_qrcode(totp_uri(
sprintf(
@ -121,7 +121,7 @@ if($isVerifiedRequest && !empty($_POST['current_password'])) {
$userRoles = user_role_all_user($currentUserId);
echo tpl_render('settings.account', [
Template::render('settings.account', [
'errors' => $errors,
'current_email' => $currentEmail,
'user_roles' => $userRoles,

View file

@ -81,6 +81,6 @@ if(isset($_POST['action']) && is_string($_POST['action'])) {
}
}
echo tpl_render('settings.data', [
Template::render('settings.data', [
'errors' => $errors,
]);

View file

@ -34,7 +34,7 @@ $accountLogList = audit_log_list(
$currentUserId
);
echo tpl_render('settings.logs', [
Template::render('settings.logs', [
'login_history_list' => $loginHistoryList,
'login_history_pagination' => $loginHistoryPagination,
'account_log_list' => $accountLogList,

View file

@ -57,7 +57,7 @@ $sessionList = user_session_list(
$currentUserId
);
echo tpl_render('settings.sessions', [
Template::render('settings.sessions', [
'errors' => $errors,
'session_list' => $sessionList,
'session_active_id' => $sessionActive,

58
src/Template.php Normal file
View file

@ -0,0 +1,58 @@
<?php
namespace Misuzu;
use InvalidArgumentException;
use Twig_Environment;
use Twig_Extensions_Extension_Date;
use Twig_Loader_Filesystem;
class Template {
private const FILE_EXT = '.twig';
private static $loader;
private static $env;
private static $vars = [];
public static function init(?string $cache = null, bool $debug = false): void {
self::$loader = new Twig_Loader_Filesystem;
self::$env = new Twig_Environment(self::$loader, [
'cache' => $cache ?? false,
'strict_variables' => true,
'auto_reload' => $debug,
'debug' => $debug,
]);
self::$env->addExtension(new Twig_Extensions_Extension_Date);
self::$env->addExtension(new TwigMisuzu);
}
public static function addPath(string $path): void {
self::$loader->addPath($path);
}
public static function renderRaw(string $file, array $vars = []): string {
if(!defined('MSZ_TPL_RENDER')) {
define('MSZ_TPL_RENDER', microtime(true));
}
if(!ends_with($file, self::FILE_EXT)) {
$file = str_replace('.', DIRECTORY_SEPARATOR, $file) . self::FILE_EXT;
}
return self::$env->render($file, array_merge(self::$vars, $vars));
}
public static function render(string $file, array $vars = []): void {
echo self::renderRaw($file, $vars);
}
/// DEPRECATED: Will be removed in the future, use the $vars param for render and renderRaw instead.
public static function set($arrayOrKey, $value = null): void {
if(is_string($arrayOrKey)) {
self::$vars[$arrayOrKey] = $value;
} elseif(is_array($arrayOrKey)) {
self::$vars = array_merge(self::$vars, $arrayOrKey);
} else {
throw new InvalidArgumentException('First parameter must be of type array or string.');
}
}
}

View file

@ -1,23 +0,0 @@
<?php
namespace Misuzu;
use Twig_Environment;
use Twig_LoaderInterface;
use UnexpectedValueException;
final class Twig extends Twig_Environment {
protected static $instance = null;
public static function instance(): Twig_Environment {
return self::$instance;
}
public function __construct(Twig_LoaderInterface $loader, array $options = []) {
if(self::$instance !== null) {
throw new UnexpectedValueException('Instance of Twig already present, use the static instance() function.');
}
parent::__construct($loader, $options);
self::$instance = $this;
}
}

View file

@ -1,64 +0,0 @@
<?php
use Misuzu\Twig;
use Misuzu\TwigMisuzu;
define('MSZ_TPL_FILE_EXT', '.twig');
function tpl_init(array $options = []): void {
$options = array_merge([
'cache' => false,
'strict_variables' => true,
'auto_reload' => false,
'debug' => false,
], $options);
$loader = new Twig_Loader_Filesystem;
$twig = new Twig($loader, $options);
$twig->addExtension(new Twig_Extensions_Extension_Date);
$twig->addExtension(new TwigMisuzu);
}
function tpl_var(string $key, $value): void {
tpl_vars([$key => $value]);
}
function tpl_vars(array $append = []): array {
static $vars = [];
if(!empty($append)) {
$vars = array_merge_recursive($vars, $append);
}
return $vars;
}
function tpl_add_path(string $path): void {
Twig::instance()->getLoader()->addPath($path);
}
function tpl_sanitise_path(string $path): string {
// if the .twig extension if already present just assume that the path is already correct
if(ends_with($path, MSZ_TPL_FILE_EXT)) {
return $path;
}
return str_replace('.', DIRECTORY_SEPARATOR, $path) . MSZ_TPL_FILE_EXT;
}
function tpl_exists(string $path): bool {
return Twig::instance()->getLoader()->exists(tpl_sanitise_path($path));
}
function tpl_render(string $path, array $vars = []): string {
if(!defined('MSZ_TPL_RENDER')) {
define('MSZ_TPL_RENDER', microtime(true));
}
$path = tpl_sanitise_path($path);
if(count($vars)) {
tpl_vars($vars);
}
return Twig::instance()->render($path, tpl_vars());
}

View file

@ -70,19 +70,19 @@ function render_info(?string $message, int $httpCode, string $template = 'errors
http_response_code($httpCode);
try {
tpl_var('http_code', $httpCode);
\Misuzu\Template::set('http_code', $httpCode);
if(mb_strlen($message)) {
tpl_var('message', $message);
\Misuzu\Template::set('message', $message);
}
$template = sprintf($template, $httpCode);
if(!tpl_exists($template)) {
/*if(!tpl_exists($template)) {
$template = 'errors.master';
}
}*/
return tpl_render(sprintf($template, $httpCode));
return Template::renderRaw(sprintf($template, $httpCode));
} catch(Exception $ex) {
echo $ex->getMessage();
return $message ?? '';