Added config for PHP formatting (PSR2)

I needed some consistent php formatting, so I plugged in a php fixer
config and then reformatted all PHP files so it's all consistent.

Fixed an ID issue with the page-edit template that was causing page
editing to fail.
pull/84/head
Are0h 3 years ago
parent d9c9f7744e
commit 63eaba08e2

@ -0,0 +1,71 @@
<?php
return (new PhpCsFixer\Config())
->setRules([
'@PSR2' => true,
'array_indentation' => true,
'array_syntax' => [
'syntax' => 'short',
],
'combine_consecutive_unsets' => true,
'method_chaining_indentation' => true,
'class_attributes_separation' => [
'elements' => [
'method' => 'none',
'trait_import' => 'none'
],
],
'multiline_whitespace_before_semicolons' => [
'strategy' => 'no_multi_line',
],
'single_quote' => true,
'binary_operator_spaces' => [
'default' => 'single_space',
'operators' => [
'=' => 'align_single_space_minimal',
'=>' => 'align_single_space_minimal',
],
],
'braces' => [
'allow_single_line_closure' => true,
],
'concat_space' => [
'spacing' => 'one',
],
'declare_equal_normalize' => true,
'function_typehint_space' => true,
'single_line_comment_style' => [
'comment_types' => [
'hash',
],
],
'include' => true,
'lowercase_cast' => true,
'no_extra_blank_lines' => [
'tokens' => [
'use',
'curly_brace_block',
'extra',
'parenthesis_brace_block',
'throw',
]
],
'no_multiline_whitespace_around_double_arrow' => true,
'no_spaces_around_offset' => true,
'no_unused_imports' => true,
'no_whitespace_before_comma_in_array' => true,
'no_whitespace_in_blank_line' => true,
'object_operator_without_whitespace' => true,
'single_blank_line_before_namespace' => true,
'ternary_operator_spaces' => true,
'trim_array_spaces' => true,
'unary_operator_spaces' => true,
'whitespace_after_comma_in_array' => true,
'single_line_after_imports' => true,
'ordered_imports' => [
'sort_algorithm' => 'none',
],
])
->setLineEnding("\n");

@ -10,59 +10,56 @@ class AuthAPI
public function __construct()
{
}
public static function status()
{
$result = [];
//internal check for admin action
if (Auth::status()) {
$result = [
"message" => "Authorized",
"type" => "apiUseAuthorized",
"token" => Session::get("token"),
'message' => 'Authorized',
'type' => 'apiUseAuthorized',
'token' => Session::get('token'),
];
} else {
$result = [
"message" => "Not Authorized",
"type" => "apiUseNotAuthorized",
'message' => 'Not Authorized',
'type' => 'apiUseNotAuthorized',
];
}
return $result;
}
public static function login($body)
{
$result = [];
switch (Auth::login($body)) {
case "no_name":
case 'no_name':
$result = [
"message" => "Need to see some id, champ",
"type" => "requestLame",
'message' => 'Need to see some id, champ',
'type' => 'requestLame',
];
break;
case "bad_pass":
case 'bad_pass':
$result = [
"message" => "Check your password, sport",
"type" => "requestLame",
'message' => 'Check your password, sport',
'type' => 'requestLame',
];
break;
default:
$result = [
"message" => "Welcome back",
"type" => "requestGood",
'message' => 'Welcome back',
'type' => 'requestGood',
];
break;
}
return $result;
}
public static function logout($body)
{
Auth::logout($body);
$result = [
"message" => "Till next time, g.",
"type" => "TASK_LOGOUT",
'message' => 'Till next time, g.',
'type' => 'TASK_LOGOUT',
];
return $result;
}

@ -11,68 +11,64 @@ class ImagesAPI
public function __construct()
{
}
public static function uploadImage($request, $type = null)
{
$file = $request->getUploadedFiles();
$uploadPath = "";
$path = date("Y") . "/" . date("m");
$uploadPath = '';
$path = date('Y') . '/' . date('m');
$response = [];
switch ($type) {
case "avatar":
$image = $file["avatar_upload"];
$uploadPath = "../public/assets/images/user/" . $path;
case 'avatar':
$image = $file['avatar_upload'];
$uploadPath = '../public/assets/images/user/' . $path;
break;
case "background":
$image = $file["background_upload"];
$uploadPath = "../public/assets/images/user/" . $path;
case 'background':
$image = $file['background_upload'];
$uploadPath = '../public/assets/images/user/' . $path;
break;
default:
$image = $file["post_image"];
$path = date("Y") . "/" . date("m");
$uploadPath = "../public/assets/images/blog/" . $path;
$image = $file['post_image'];
$path = date('Y') . '/' . date('m');
$uploadPath = '../public/assets/images/blog/' . $path;
break;
}
$result = FileUploader::uploadFile($uploadPath, $image);
switch ($type) {
case "avatar":
case 'avatar':
$response = [
"message" => "Avatar Added. You look great!",
"type" => "avatarUploaded",
"url" =>
"/assets/images/user/" . $path . "/" . $image->getClientFileName(),
'message' => 'Avatar Added. You look great!',
'type' => 'avatarUploaded',
'url' => '/assets/images/user/' . $path . '/' . $image->getClientFileName(),
];
//update member data
Member::updateData(
"avi",
"/assets/images/user/" . $path . "/" . $image->getClientFileName()
'avi',
'/assets/images/user/' . $path . '/' . $image->getClientFileName()
);
break;
case "background":
case 'background':
$response = [
"message" => "Background plugged in. That's nice!",
"type" => "siteBackgroundUploaded",
"url" =>
"/assets/images/user/" . $path . "/" . $image->getClientFileName(),
'message' => "Background plugged in. That's nice!",
'type' => 'siteBackgroundUploaded',
'url' => '/assets/images/user/' . $path . '/' . $image->getClientFileName(),
];
//update settings file
Settings::updateGlobalData(
"background",
"/assets/images/user/" . $path . "/" . $image->getClientFileName()
'background',
'/assets/images/user/' . $path . '/' . $image->getClientFileName()
);
break;
default:
$response = [
"message" => "Image Added. Very slick",
"type" => "postImageAdded",
"url" =>
"/assets/images/blog/" . $path . "/" . $image->getClientFileName(),
'message' => 'Image Added. Very slick',
'type' => 'postImageAdded',
'url' => '/assets/images/blog/' . $path . '/' . $image->getClientFileName(),
];
break;
}

@ -9,7 +9,6 @@ class InitAPI
public function __construct()
{
}
public static function handleInitTasks($task, $request)
{
//check if a site config already exists. if it does, deny set up request
@ -17,13 +16,13 @@ class InitAPI
//through settings.
if (Setup::status()) {
$result = ["type" => "blogInitFail", "message" => "Site already set up"];
$result = ['type' => 'blogInitFail', 'message' => 'Site already set up'];
} else {
switch ($task) {
case "init":
case 'init':
$result = Setup::init($request);
break;
case "restore":
case 'restore':
$result = Setup::restore($request);
break;
}

@ -10,7 +10,6 @@ class MailerAPI
public function __construct()
{
}
public static function handleMail($request, $body, $response)
{
// if testing, verify session is active

@ -2,13 +2,10 @@
namespace brain\api\v1;
use Mni\FrontYAML\Parser;
use brain\api\v1\ImagesAPI;
use brain\data\Book;
use brain\data\Settings;
use brain\data\Session;
use brain\utility\StringTools;
use function _\filter;
class PagesAPI
@ -16,128 +13,126 @@ class PagesAPI
public function __construct()
{
}
public static function getPageContent($request, $args)
{
$task = $args["fourth"];
$pages = (new Book("../content/pages"))->getContents();
$task = $args['fourth'];
$pages = (new Book('../content/pages'))->getContents();
$content = [];
foreach ($pages as $page) {
$entry = [
"id" => $page["id"],
"uuid" => $page["uuid"],
"title" => $page["title"],
"feature" => $page["feature"],
"path" => $page["path"],
"layout" => $page["layout"],
"tags" => $page["tags"],
"author" => $page["author"],
"created" => $page["created"],
"updated" => $page["updated"],
"deleted" => $page["deleted"],
"menu" => $page["menu"],
"featured" => $page["featured"],
"published" => $page["published"],
"slug" => $page["slug"],
"content" => StringTools::sanitizeContent($page["content"]),
'id' => $page['id'],
'uuid' => $page['uuid'],
'title' => $page['title'],
'feature' => $page['feature'],
'path' => $page['path'],
'layout' => $page['layout'],
'tags' => $page['tags'],
'author' => $page['author'],
'created' => $page['created'],
'updated' => $page['updated'],
'deleted' => $page['deleted'],
'menu' => $page['menu'],
'featured' => $page['featured'],
'published' => $page['published'],
'slug' => $page['slug'],
'content' => StringTools::sanitizeContent($page['content']),
];
array_push($content, $entry);
}
switch ($task) {
case "published":
case 'published':
$published = filter($content, function ($item) {
return $item["published"] == true && $item["deleted"] == false;
return $item['published'] == true && $item['deleted'] == false;
});
$result = ["pages" => $published, "totalItems" => count($published)];
$result = ['pages' => $published, 'totalItems' => count($published)];
break;
case "featured":
case 'featured':
$featured = filter($content, function ($item) {
return $item["featured"] == true && $item["deleted"] == false;
return $item['featured'] == true && $item['deleted'] == false;
});
$result = [
"pages" => $featured,
"totalItems" => count($featured),
'pages' => $featured,
'totalItems' => count($featured),
];
break;
case "menu":
case 'menu':
$menu = filter($content, function ($item) {
return $item["menu"] == true && $item["deleted"] == false;
return $item['menu'] == true && $item['deleted'] == false;
});
$result = ["pages" => $menu, "totalItems" => count($menu)];
$result = ['pages' => $menu, 'totalItems' => count($menu)];
break;
case "single":
$uuid = $args["fifth"];
$page = (new Book("../content/pages"))->findPageById($uuid);
case 'single':
$uuid = $args['fifth'];
$page = (new Book('../content/pages'))->findPageById($uuid);
$entry = [
"id" => $page["id"],
"uuid" => $page["uuid"],
"title" => $page["title"],
"feature" => $page["feature"],
"path" => $page["path"],
"layout" => $page["layout"],
"tags" => $page["tags"],
"author" => $page["author"],
"created" => $page["created"],
"updated" => $page["updated"],
"deleted" => $page["deleted"],
"menu" => $page["menu"],
"featured" => $page["featured"],
"published" => $page["published"],
"slug" => $page["slug"],
"content" => StringTools::sanitizeContent($page["content"]),
'id' => $page['id'],
'uuid' => $page['uuid'],
'title' => $page['title'],
'feature' => $page['feature'],
'path' => $page['path'],
'layout' => $page['layout'],
'tags' => $page['tags'],
'author' => $page['author'],
'created' => $page['created'],
'updated' => $page['updated'],
'deleted' => $page['deleted'],
'menu' => $page['menu'],
'featured' => $page['featured'],
'published' => $page['published'],
'slug' => $page['slug'],
'content' => StringTools::sanitizeContent($page['content']),
];
$result = $entry;
break;
case "tags":
case 'tags':
$result = Settings::getTags();
break;
default:
$result = [
"message" => "Hm, no task. That's unfortunate",
"type" => "TASK_NONE",
'message' => "Hm, no task. That's unfortunate",
'type' => 'TASK_NONE',
];
break;
}
return $result;
}
public static function handlePageTask($request, $args)
{
$task = $args["fourth"];
$task = $args['fourth'];
switch ($task) {
case "delete":
case "create":
case "write":
case 'delete':
case 'create':
case 'write':
$body = $request->getParsedBody();
$passed = true;
if (!isset($body["form_token"])) {
if (!isset($body['form_token'])) {
$result = [
"message" => "No form token. Not good, sport.",
"type" => "TASK_FORM_AUTH",
'message' => 'No form token. Not good, sport.',
'type' => 'TASK_FORM_AUTH',
];
} else {
if ($body["form_token"] == Session::get("form_token")) {
if ($body['form_token'] == Session::get('form_token')) {
//TODO: Verify form fields
$keys = [
"id",
"uuid",
"layout",
"current_title",
"content",
"title",
"created",
"slug",
"tags",
"menu",
"featured",
"published",
"form_token",
"feature_image",
'id',
'uuid',
'layout',
'current_title',
'content',
'title',
'created',
'slug',
'tags',
'menu',
'featured',
'published',
'form_token',
'feature_image',
];
foreach ($body as $key => $item) {
@ -150,27 +145,26 @@ class PagesAPI
$result = (new Book())->editPage($task, $request);
} else {
$result = [
"message" =>
"Unneccessary key found. Post not authorized, slick.",
"type" => "TASK_FORM_AUTH",
'message' => 'Unneccessary key found. Post not authorized, slick.',
'type' => 'TASK_FORM_AUTH',
];
}
} else {
$result = [
"message" => "Form token, auth failed. Uh oh.",
"type" => "TASK_FORM_AUTH",
'message' => 'Form token, auth failed. Uh oh.',
'type' => 'TASK_FORM_AUTH',
];
}
}
break;
case "add-entry-image":
case 'add-entry-image':
$result = ImagesAPI::uploadImage($request);
break;
default:
$result = [
"message" => "Hm, no task. That's unfortunate",
"type" => "TASK_NONE",
'message' => "Hm, no task. That's unfortunate",
'type' => 'TASK_NONE',
];
break;
}

@ -2,8 +2,6 @@
namespace brain\api\v1;
use Slim\Views\Twig;
use brain\api\v1\ImagesApi;
use brain\data\Render;
use brain\data\Settings;
use brain\data\Session;
@ -14,45 +12,43 @@ class SettingsAPI
public function __construct()
{
}
public static function handleSettingsTask($request, $args, $body = null)
{
$task = $args["fourth"];
$task = $args['fourth'];
switch ($task) {
case "publish":
case 'publish':
//check settings to see if site is a one pager
$config = new Settings();
$settings = $config->getSettings();
$theme = $settings["global"]["theme"];
$theme = $settings['global']['theme'];
$themeConfig = json_decode(
file_get_contents("../content/themes/" . $theme . "/theme.json"),
file_get_contents('../content/themes/' . $theme . '/theme.json'),
true
);
//check to see if dynamic rendering is active
if (
isset($settings["global"]["dynamicRender"]) &&
$settings["global"]["dynamicRender"] === "true"
if (isset($settings['global']['dynamicRender']) &&
$settings['global']['dynamicRender'] === 'true'
) {
$result = [
"message" => "Dynamic Render Active! You're good!",
"type" => "RENDER_SUCCESS",
'message' => "Dynamic Render Active! You're good!",
'type' => 'RENDER_SUCCESS',
];
} else {
$render = new Render();
if (isset($themeConfig["render"])) {
if (!$themeConfig["render"] || $themeConfig["render"] === "false") {
if (isset($themeConfig['render'])) {
if (!$themeConfig['render'] || $themeConfig['render'] === 'false') {
$render->renderIndex();
$result = [
"message" => "Index Rendered. HAND CLAPS",
"type" => "RENDER_SUCCESS",
'message' => 'Index Rendered. HAND CLAPS',
'type' => 'RENDER_SUCCESS',
];
} else {
$render->renderTags();
$render->renderArchive();
$render->renderPages();
$result = [
"message" => "Site Rendered. GOOD EFFORT",
"type" => "RENDER_SUCCESS",
'message' => 'Site Rendered. GOOD EFFORT',
'type' => 'RENDER_SUCCESS',
];
}
} else {
@ -61,8 +57,8 @@ class SettingsAPI
$render->renderArchive();
$render->renderPages();
$result = [
"message" => "Site Rendered. GOOD EFFORT",
"type" => "RENDER_SUCCESS",
'message' => 'Site Rendered. GOOD EFFORT',
'type' => 'RENDER_SUCCESS',
];
}
}
@ -71,81 +67,79 @@ class SettingsAPI
//otherwise, render all pages according to theme template files
break;
case "add-avatar":
$result = ImagesAPI::uploadImage($request, "avatar");
case 'add-avatar':
$result = ImagesAPI::uploadImage($request, 'avatar');
break;
case "add-feature-background":
$result = ImagesAPI::uploadImage($request, "background");
case 'add-feature-background':
$result = ImagesAPI::uploadImage($request, 'background');
break;
case "sync":
case 'sync':
Settings::sync($body);
$result = [
"message" => "Settings Synced. You're doing great!",
"type" => "settingsUpdated",
'message' => "Settings Synced. You're doing great!",
'type' => 'settingsUpdated',
];
break;
case "nav-sync":
case 'nav-sync':
Settings::navSync($body);
$result = [
"message" => "Navigation updated. Very slick!",
"type" => "menuUpdated",
'message' => 'Navigation updated. Very slick!',
'type' => 'menuUpdated',
];
break;
default:
$result = [
"message" => "Hm, no task. That's unfortunate",
"type" => "TASK_NONE",
'message' => "Hm, no task. That's unfortunate",
'type' => 'TASK_NONE',
];
break;
}
return $result;
}
public static function getInfo($request, $args)
{
$task = $args["fourth"];
$task = $args['fourth'];
switch ($task) {
case "site":
case 'site':
$config = new Settings();
$settings = $config->getSettings();
$data = [
"title" => $settings["global"]["title"],
"base_url" => $settings["global"]["base_url"],
"description" => $settings["global"]["descriptions"],
'title' => $settings['global']['title'],
'base_url' => $settings['global']['base_url'],
'description' => $settings['global']['descriptions'],
];
$result = [
"message" => "Settings Found",
"type" => "GET_SETTINGS",
"data" => $data,
'message' => 'Settings Found',
'type' => 'GET_SETTINGS',
'data' => $data,
];
break;
case "member":
case 'member':
if (Session::active()) {
$member = $member = Session::get("member");
$data = ["handle" => $member["handle"], "email" => $member["email"]];
$member = $member = Session::get('member');
$data = ['handle' => $member['handle'], 'email' => $member['email']];
$result = [
"message" => "Member Info Found",
"type" => "GET_MEMBER_INFO",
"data" => $data,
'message' => 'Member Info Found',
'type' => 'GET_MEMBER_INFO',
'data' => $data,
];
} else {
$result = [
"message" => "Not logged in. C'mon, bruh",
"type" => "TASK_NONE",
'message' => "Not logged in. C'mon, bruh",
'type' => 'TASK_NONE',
];
}
break;
default:
$result = [
"message" => "No Settings found. Frowny Face",
"type" => "TASK_NONE",
'message' => 'No Settings found. Frowny Face',
'type' => 'TASK_NONE',
];
break;
}
return $result;
}
public static function createBackup()
{
$result = Maintenance::makeBackup();

@ -5,7 +5,6 @@ namespace brain\controller;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use brain\api\v1\AuthAPI;
use brain\api\v1\ImagesAPI;
use brain\api\v1\PagesAPI;
use brain\api\v1\SettingsAPI;
use brain\api\v1\InitAPI;
@ -20,54 +19,54 @@ class APIControl
ResponseInterface $response,
array $args
): ResponseInterface {
$filename = "";
switch (isset($args["third"]) ? $args["third"] : "none") {
case "status":
$filename = '';
switch (isset($args['third']) ? $args['third'] : 'none') {
case 'status':
$result = AuthAPI::status();
break;
case "page":
case 'page':
//echo
if (Member::verifyKey($_GET["key"])) {
if (Member::verifyKey($_GET['key'])) {
$result = PagesAPI::getPageContent($request, $args);
} else {
$result = [
"message" => "API access denied, homie",
"type" => "API_ERROR",
'message' => 'API access denied, homie',
'type' => 'API_ERROR',
];
}
break;
case "settings":
$token = $request->getHeader("fipamo-access-token");
case 'settings':
$token = $request->getHeader('fipamo-access-token');
//Verify token to get site info
if (isset($token[0])) {
if (Session::verifyToken($token[0])) {
$result = SettingsAPI::getInfo($request, $args);
} else {
$result = [
"message" => "Invalid token, API access denied, homie",
"type" => "API_ERROR",
'message' => 'Invalid token, API access denied, homie',
'type' => 'API_ERROR',
];
}
} else {
$result = [
"message" => "No token, API access denied, homie",
"type" => "API_ERROR",
'message' => 'No token, API access denied, homie',
'type' => 'API_ERROR',
];
}
break;
case "files":
case 'files':
if (Session::active()) {
if ($args["third"] == "backup") {
$filename = "../config/backups/latest_backup.zip";
if ($args['third'] == 'backup') {
$filename = '../config/backups/latest_backup.zip';
if (file_exists($filename)) {
header("Content-Type: application/zip");
header('Content-Type: application/zip');
header(
'Content-Disposition: attachment; filename="' .
basename($filename) .
'"'
);
header("Content-Length: " . filesize($filename));
header('Content-Length: ' . filesize($filename));
flush();
// return readfile($filename);
@ -78,8 +77,8 @@ class APIControl
}
} else {
$result = [
"message" => "API access denied, homie",
"type" => "API_ERROR",
'message' => 'API access denied, homie',
'type' => 'API_ERROR',
];
}
// no break
@ -89,19 +88,19 @@ class APIControl
$freshResponse = $response;
if ($args["third"] == "files") {
if ($args['third'] == 'files') {
$freshResponse
->getBody()
->write(file_get_contents("../config/backups/latest_back.zip"));
->write(file_get_contents('../config/backups/latest_back.zip'));
$freshResponse->withHeader("Content-Type", "application/zip");
$freshResponse->withHeader('Content-Type', 'application/zip');
return $freshResponse->withAddedHeader(
"Content-Disposition",
"attachment; filename=latest_backup.zip"
'Content-Disposition',
'attachment; filename=latest_backup.zip'
);
} else {
$response->getBody()->write(json_encode($result));
return $response->withHeader("Content-Type", "application/json");
return $response->withHeader('Content-Type', 'application/json');
}
}
public static function post(
@ -109,26 +108,26 @@ class APIControl
ResponseInterface $response,
array $args
): ResponseInterface {
$contentType = $request->getHeader("Content-Type");
$contentType = $request->getHeader('Content-Type');
switch ($contentType[0]) {
case "application/json":
$body = json_decode(file_get_contents("php://input"), true);
case 'application/json':
$body = json_decode(file_get_contents('php://input'), true);
break;
default:
break;
}
switch (isset($args["third"]) ? $args["third"] : "none") {
case "restore": //move to 'api/auth'
case "init": //move to 'api/auth'
$task = $args["third"];
switch (isset($args['third']) ? $args['third'] : 'none') {
case 'restore': //move to 'api/auth'
case 'init': //move to 'api/auth'
$task = $args['third'];
$result = InitApi::handleInitTasks(
$task,
$task == "init" ? $body : $request
$task == 'init' ? $body : $request
);
break;
case "backup": //move to 'api/auth'
$token = $request->getHeader("fipamo-access-token");
case 'backup': //move to 'api/auth'
$token = $request->getHeader('fipamo-access-token');
//Verify token for admin tasks
$result = SettingsAPI::createBackup();
/*
@ -143,15 +142,15 @@ class APIControl
}
*/
break;
case "login": //move to 'api/auth'
case 'login': //move to 'api/auth'
//check if request is remote and if so, verify token
if ($body["remote"] || $body["remote"] == "true") {
if (Member::verifyKey($body["key"])) {
if ($body['remote'] || $body['remote'] == 'true') {
if (Member::verifyKey($body['key'])) {
$result = AuthAPI::login($body);
} else {
$result = [
"message" => "API access denied, homie",
"type" => "API_ERROR",
'message' => 'API access denied, homie',
'type' => 'API_ERROR',
];
}
} else {
@ -160,46 +159,46 @@ class APIControl
}
break;
case "logout": //move to 'api/auth'
case 'logout': //move to 'api/auth'
$result = AuthAPI::logout($body);
break;
case "get-secret": //move to 'api/auth'
case 'get-secret': //move to 'api/auth'
$result = AuthAPI::requestSecret($body);
break;
case "reset-password": //move to 'api/auth'
case 'reset-password': //move to 'api/auth'
$result = AuthAPI::resetPassword($body);
break;
case "page":
$token = $request->getHeader("fipamo-access-token");
case 'page':
$token = $request->getHeader('fipamo-access-token');
//Verify token for admin tasks
if (isset($token[0])) {
if (Session::verifyToken($token[0])) {
$result = PagesAPI::handlePageTask($request, $args);
} else {
$result = [
"message" => "Invalid token, API access denied, homie",
"type" => "API_ERROR",
'message' => 'Invalid token, API access denied, homie',
'type' => 'API_ERROR',
];
}
} else {
$result = [
"message" => "No token, API access denied, homie",
"type" => "API_ERROR",
'message' => 'No token, API access denied, homie',
'type' => 'API_ERROR',
];
}
break;
case "settings":
case 'settings':
if (isset($body)) {
$postBody = $body;
} else {
$postBody = null;
}
$task = $args["fourth"];
if ($task == "add-feature-background" || $task == "add-avatar") {
$task = $args['fourth'];
if ($task == 'add-feature-background' || $task == 'add-avatar') {
$result = SettingsAPI::handleSettingsTask($request, $args, $postBody);
} else {
$token = $request->getHeader("fipamo-access-token");
$token = $request->getHeader('fipamo-access-token');
if (Session::verifyToken($token[0])) {
$result = SettingsAPI::handleSettingsTask(
$request,
@ -208,25 +207,25 @@ class APIControl
);
} else {
$result = [
"message" => "API access denied, homie",
"type" => "API_ERROR",
'message' => 'API access denied, homie',
'type' => 'API_ERROR',
];
}
}
break;
case "mailer":
case 'mailer':
$result = MailerAPI::handleMail($request, $body, $response);
break;
default:
$result = [
"message" => "Oh, nothing to do. That's unfortunate",
"type" => "TASK_NONE",
'message' => "Oh, nothing to do. That's unfortunate",
'type' => 'TASK_NONE',
];
break;
}
$response->getBody()->write(json_encode($result));
return $response->withHeader("Content-Type", "application/json");
return $response->withHeader('Content-Type', 'application/json');
}
}

@ -157,8 +157,7 @@ class DashControl
$book = new Book();
$page = $book->findPageById($uuid);
$pageOptions = Sorting::page($page);
$preview =
$settings['global']['theme'] .
$preview = $settings['global']['theme'] .
'/' .
$page['layout'] .
'.twig';

@ -7,7 +7,6 @@ use Psr\Http\Message\ServerRequestInterface;
use Slim\Views\Twig;
use brain\data\Settings;
use brain\utility\Sorting;
use function _\find;
class IndexControl
@ -22,49 +21,48 @@ class IndexControl
$settings = $config->getSettings();
$view = Twig::fromRequest($request);
//checks dynamic render flag for site render status
if ($settings["global"]["dynamicRender"]) {
if ($settings["global"]["dynamicRender"] == "true") {
$loader = new \Twig\Loader\FilesystemLoader("../content/themes");
if ($settings['global']['dynamicRender']) {
if ($settings['global']['dynamicRender'] == 'true') {
$loader = new \Twig\Loader\FilesystemLoader('../content/themes');
$display = new \Twig\Environment($loader, []);
$template = "";
$template = '';
$pageOptions = [];
$pageInfo = [
"keywords" => isset($settings["global"]["keywords"])
? $settings["global"]["keywords"]
: "fipamo, blog, jamstack, php, markdown, js",
"description" => $settings["global"]["descriptions"],
"image" =>
$settings["global"]["base_url"] . $settings["global"]["background"],
"baseURL" => $settings["global"]["base_url"],
'keywords' => isset($settings['global']['keywords'])
? $settings['global']['keywords']
: 'fipamo, blog, jamstack, php, markdown, js',
'description' => $settings['global']['descriptions'],
'image' => $settings['global']['base_url'] . $settings['global']['background'],
'baseURL' => $settings['global']['base_url'],
];
if (isset($args["first"])) {
switch ($args["first"]) {
case "tags":
$template = $settings["global"]["theme"] . "/tags.twig";
$tag = trim($args["second"]);
if (isset($args['first'])) {
switch ($args['first']) {
case 'tags':
$template = $settings['global']['theme'] . '/tags.twig';
$tag = trim($args['second']);
$taglist = Sorting::tags();
$item = find($taglist, ["tag_name" => $tag]);
$item = find($taglist, ['tag_name' => $tag]);
$pageOptions = [
"title" => "Pages Tagged as " . $item["tag_name"],
"background" => $pageInfo["image"],
"tag_list" => $item["pages"],
"info" => $pageInfo,
"menu" => $settings["menu"],
"dynamicRender" => $settings["global"]["dynamicRender"],
'title' => 'Pages Tagged as ' . $item['tag_name'],
'background' => $pageInfo['image'],
'tag_list' => $item['pages'],
'info' => $pageInfo,
'menu' => $settings['menu'],
'dynamicRender' => $settings['global']['dynamicRender'],
];
break;
case "archives":
case 'archives':
$archive = Sorting::archive();
$template = $settings["global"]["theme"] . "/archive.twig";
$template = $settings['global']['theme'] . '/archive.twig';
$pageOptions = [
"title" => "Archive",
"background" => $pageInfo["image"],
"archives" => $archive,
"info" => $pageInfo,
"menu" => $settings["menu"],
"dynamicRender" => $settings["global"]["dynamicRender"],
'title' => 'Archive',
'background' => $pageInfo['image'],
'archives' => $archive,
'info' => $pageInfo,
'menu' => $settings['menu'],
'dynamicRender' => $settings['global']['dynamicRender'],
];
break;
@ -72,22 +70,20 @@ class IndexControl
//check if page is a menu item, if not render along path as usual
$page = [];
$book = new Book();
if (is_numeric($args["first"])) {
$page = $book->findPageBySlug($args["third"]);
if (is_numeric($args['first'])) {
$page = $book->findPageBySlug($args['third']);
} else {
$page = $book->findPageBySlug($args["first"]);
$page = $book->findPageBySlug($args['first']);
}
$template =
$settings["global"]["theme"] . "/" . $page["layout"] . ".twig";
$template = $settings['global']['theme'] . '/' . $page['layout'] . '.twig';
$pageOptions = Sorting::page($page);
break;
}
} else {
//index
$template =
$settings["global"]["theme"] . "/" . $page["layout"] . ".twig";
$book = new Book("");
$template = $settings['global']['theme'] . '/' . $page['layout'] . '.twig';
$book = new Book('');
$page = $book->findPageBySlug();
$pageOptions = Sorting::page($page);
}
@ -98,14 +94,14 @@ class IndexControl
} else {
//if dynamic flag is false, load up html
$view = Twig::fromRequest($request);
$html = file_get_contents("../public/index.html");
$html = file_get_contents('../public/index.html');
$response->getBody()->write($html);
return $response;
}
} else {
//if flag is not present, default to static html
$view = Twig::fromRequest($request);
$html = file_get_contents("../public/index.html");
$html = file_get_contents('../public/index.html');
$response->getBody()->write($html);
return $response;
}

@ -4,9 +4,6 @@ namespace brain\controller;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use brain\controller\DashControl;
use brain\controller\APIControl;
use brain\controller\IndexControl;
class RouteControl
{
@ -15,11 +12,11 @@ class RouteControl
ResponseInterface $response,
array $args
): ResponseInterface {
switch (isset($args["first"]) ? $args["first"] : "index") {
case "dashboard":
switch (isset($args['first']) ? $args['first'] : 'index') {
case 'dashboard':
return DashControl::start($request, $response, $args);
break;
case "api":
case 'api':
return APIControl::get($request, $response, $args);
break;
default:
@ -27,14 +24,13 @@ class RouteControl
break;
}
}
public function post(
ServerRequestInterface $request,
ResponseInterface $response,
array $args
): ResponseInterface {
switch (isset($args["first"]) ? $args["first"] : "index") {
case "api":
switch (isset($args['first']) ? $args['first'] : 'index') {
case 'api':
//$result = APIControl::post($request, $response, $args);
//var_dump($result);
return APIControl::post($request, $response, $args);

@ -3,9 +3,6 @@
namespace brain\data;
use ReallySimpleJWT\Token;
use brain\data\Settings;
use brain\data\Session;
use function _\find;
class Auth
@ -13,20 +10,18 @@ class Auth
public function __construct()
{
}
public static function sessionStatus()
{
if (isset($_SESSION["member"])) {
if (isset($_SESSION['member'])) {
return true;
} else {
return false;
}
//return $this->secret;
}
public static function status()
{
$result = "";
$result = '';
if (Session::active()) {
$result = true;
} else {
@ -34,124 +29,119 @@ class Auth
}
return $result;
}
public static function login($who)
{
//grab member list
$folks = (new Settings())->getFolks();
$found = find($folks, ["handle" => $who["handle"]]);
$found = find($folks, ['handle' => $who['handle']]);
if ($found) {
//name is found, verify password
if (password_verify($who["password"], $found["password"])) {
if (password_verify($who['password'], $found['password'])) {
$member = [
"handle" => $found["handle"],
"email" => $found["email"],
"role" => $found["role"],
"avatar" => $found["avi"],
"key" => $found["key"],
'handle' => $found['handle'],
'email' => $found['email'],
'role' => $found['role'],
'avatar' => $found['avi'],
'key' => $found['key'],
];
$token = Token::create(
$found["key"],
$found["secret"],
$found['key'],
$found['secret'],
time() + 3600,
"localhost"
'localhost'
); //expires in an hour
$form_token = md5(uniqid(microtime(), true));
Session::start();
Session::set("member", $member);
Session::set("token", $token);
Session::set("form_token", $form_token);
Session::set('member', $member);
Session::set('token', $token);
Session::set('form_token', $form_token);
$result = "good_login";
$result = 'good_login';
} else {
$result = "bad_pass";
$result = 'bad_pass';
}
} else {
//if name is not found
$result = "no_name";
$result = 'no_name';
}
return $result;
}
public static function findSecret($data)
{
$result = [];
$folks = (new Settings())->getFolks();
if (
!empty($data["email"]) &&
filter_var($data["email"], FILTER_VALIDATE_EMAIL)
if (!empty($data['email']) &&
filter_var($data['email'], FILTER_VALIDATE_EMAIL)
) {
$found = find($folks, ["email" => $data["email"]]);
$found = find($folks, ['email' => $data['email']]);
if ($found) {
//if email is cool, check mail relay status
//if set up, send secret there, if not just return it
$config = new Settings();
$settings = $config->getSettings();
$email = $settings["email"]["active"];
if ($email != "option-none") {
$data["mail_task"] = "SEND_SECRET";
$data["secret"] = $found["secret"];
$email = $settings['email']['active'];
if ($email != 'option-none') {
$data['mail_task'] = 'SEND_SECRET';
$data['secret'] = $found['secret'];
$result = Mailer::sendmail($data);
} else {
$result = [
"message" => "Valid email, but no email set up!",
"type" => "secretFound",
"secret" => $found["secret"],
'message' => 'Valid email, but no email set up!',
'type' => 'secretFound',
'secret' => $found['secret'],
];
}
} else {
$result = [
"message" => "No valid email, no goodies, pleighboi",
"type" => "secretNotFound",
'message' => 'No valid email, no goodies, pleighboi',
'type' => 'secretNotFound',
];
}
} else {
$result = [
"message" => "Aye, this address is not right, slick.",
"type" => "secretNotFound",
'message' => 'Aye, this address is not right, slick.',
'type' => 'secretNotFound',
];
}
return $result;
}
public static function makeNewPassword($data)
{
//check if passwordsmatch
if ($data["newPass"] == $data["newPassConfirm"]) {
if ($data['newPass'] == $data['newPassConfirm']) {
//verify secret
$folks = (new Settings())->getFolks();
$found = find($folks, ["secret" => $data["secret"]]);
$found = find($folks, ['secret' => $data['secret']]);
if ($found) {
//create new pass and secret key, then update file
$hash = password_hash($data["newPass"], PASSWORD_DEFAULT);
$hash = password_hash($data['newPass'], PASSWORD_DEFAULT);
$freshSecret = StringTools::randomString(12);
Member::updateData("password", $hash, $data["secret"]);
Member::updateData("secret", $freshSecret, $data["secret"]);
Member::updateData('password', $hash, $data['secret']);
Member::updateData('secret', $freshSecret, $data['secret']);
$result = [
"message" => "Password Updated. Very nice!",
"type" => "passCreated",
'message' => 'Password Updated. Very nice!',
'type' => 'passCreated',
];
} else {
$result = [
"message" => "Secret key is invalid. Try to retrieve it again",
"type" => "passNotCreated",
'message' => 'Secret key is invalid. Try to retrieve it again',
'type' => 'passNotCreated',
];
}
} else {
$result = [
"message" => "Passwords don't match. Try it again.",
"type" => "passNotCreated",
'message' => "Passwords don't match. Try it again.",
'type' => 'passNotCreated',
];
}
return $result;
}
public static function logout()
{
Session::kill();

@ -2,18 +2,17 @@
namespace brain\data;
use function _\filter;
use function _\find;
use brain\utility\DocTools;
use brain\utility\FileUploader;
use brain\utility\StringTools;
use brain\utility\FileUploader;
use function _\find;
use function _\filter;
class Book
{
public function __construct()
{
}
public function findPageById(string $uuid)
{
$content = $this->getContents();
@ -21,7 +20,6 @@ class Book
return $page;
}
public function findPageBySlug(string $slug = null)
{
$content = $this->getContents();
@ -33,7 +31,6 @@ class Book
return $page;
}
public function editPage($task, $request)
{
$content = $this->getContents();
@ -51,12 +48,11 @@ class Book
$member = Session::get('member');
if ($task != 'create') {
$path =
date('Y', date($page['rawCreated'])).
'/'.
$path = date('Y', date($page['rawCreated'])) .
'/' .
date('m', date($page['rawCreated']));
} else {
$path = date('Y').'/'.date('m');
$path = date('Y') . '/' . date('m');
}
$page_feature = '';
@ -73,42 +69,40 @@ class Book
case 'image/png':
case 'image/gif':
case 'image/svg':
$imagesPath = '/assets/images/blog/'.$path.'/';
$imageList =
$imageList.$imagesPath.urlencode($file->getClientFileName()).', ';
$imagesPath = '/assets/images/blog/' . $path . '/';
$imageList = $imageList . $imagesPath . urlencode($file->getClientFileName()) . ', ';
FileUploader::uploadFile(
'../public/assets/images/blog/'.$path.'/',
'../public/assets/images/blog/' . $path . '/',
$file
);
break;
case 'video/mp4':
$videosPath = '/assets/video/blog/'.$path.'/';
$imageList =
$imageList.$videosPath.urlencode($file->getClientFileName()).', ';
$videosPath = '/assets/video/blog/' . $path . '/';
$imageList = $imageList . $videosPath . urlencode($file->getClientFileName()) . ', ';
FileUploader::uploadFile(
'../public/assets/video/blog/'.$path.'/',
'../public/assets/video/blog/' . $path . '/',
$file
);
break;
case 'audio/mpeg':
$soundPath = '/assets/sound/blog/'.$path.'/';
$fileList = $fileList.$soundPath.urlencode($file->getClientFileName()).', ';
$soundPath = '/assets/sound/blog/' . $path . '/';
$fileList = $fileList . $soundPath . urlencode($file->getClientFileName()) . ', ';
FileUploader::uploadFile(
'../public/assets/sound/blog/'.$path.'/',
'../public/assets/sound/blog/' . $path . '/',
$file
);
break;
case 'application/pdf':
case 'text/plain':
case 'text/rtf':
$docPath = '/assets/docs/blog/'.$path.'/';
$fileList = $fileList.$docPath.urlencode($file->getClientFileName()).', ';
$docPath = '/assets/docs/blog/' . $path . '/';
$fileList = $fileList . $docPath . urlencode($file->getClientFileName()) . ', ';
FileUploader::uploadFile(
'../public/assets/docs/blog/'.$path.'/',
'../public/assets/docs/blog/' . $path . '/',
$file
);
break;
@ -131,8 +125,7 @@ class Book
$deleted = isset($page['deleted']) ? $page['deleted'] : 'false';
}
$created =
$task != 'create'
$created = $task != 'create'
? new \Moment\Moment($page['rawCreated'])
: new \Moment\Moment();
$updated = new \Moment\Moment();
@ -159,7 +152,7 @@ class Book
if ($body['layout'] == 'index') {
$writePath = '../content/pages/start/index.md';
} else {
$writePath = '../content/pages/'.$path.'/'.$body['slug'].'.md';
$writePath = '../content/pages/' . $path . '/' . $body['slug'] . '.md';
}
$status = DocTools::writePages($task, $path, $writePath, $write);
@ -211,7 +204,6 @@ class Book
return $response;
}
public function getPages(int $page, int $limit, string $sort = null)
{
$content = $this->getContents();
@ -286,7 +278,6 @@ class Book
],
];
}
public function getContents()
{
// test new contents data class

@ -2,25 +2,24 @@
namespace brain\data;
use HtmlSanitizer\Extension\Basic\BasicExtension;
use HtmlSanitizer\Extension\Iframe\IframeExtension;
use HtmlSanitizer\Extension\Listing\ListExtension;
use HtmlSanitizer\SanitizerBuilder;
use League\CommonMark\Environment\Environment;
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension;
use League\CommonMark\Extension\Strikethrough\StrikethroughExtension;
use League\CommonMark\Extension\Attributes\AttributesExtension;
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension;
use League\CommonMark\Extension\FrontMatter\FrontMatterExtension;
use League\CommonMark\Extension\FrontMatter\Output\RenderedContentWithFrontMatter;
use League\CommonMark\Extension\Strikethrough\StrikethroughExtension;
use League\CommonMark\MarkdownConverter;
use League\CommonMark\CommonMarkConverter;
use HtmlSanitizer\Extension\Basic\BasicExtension;
use HtmlSanitizer\Extension\Iframe\IframeExtension;
use HtmlSanitizer\Extension\Listing\ListExtension;
use HtmlSanitizer\SanitizerBuilder;
use function _\orderBy;
class Contents
{
public $files = [];
public $config = [];
public function __construct($folder)
{
$this->read($folder);
@ -32,12 +31,11 @@ class Contents
//$this->files[] = $folder . "/";
$this->read($folder);
}
$files = array_filter(glob("$folder/*md"), "is_file");
$files = array_filter(glob("$folder/*md"), 'is_file');
foreach ($files as $file) {
$this->files[] = $file;
}
}
public function getAll()
{
$environment = new Environment($this->config);
@ -86,16 +84,16 @@ class Contents
);
$detergent = [
"extensions" => ["basic", "list","relative-a", "relative-image", "iframe"],
"tags" => [
"div" => [
"allowed_attributes" => ["class", "title", "id", "style"],
'extensions' => ['basic', 'list', 'relative-a', 'relative-image', 'iframe'],
'tags' => [
'div' => [
'allowed_attributes' => ['class', 'title', 'id', 'style'],
],
"img" => [
"allowed_attributes" => ["src", "alt", "title", "class"],
'img' => [
'allowed_attributes' => ['src', 'alt', 'title', 'class'],
],
"iframe" => [
"allowed_attributes" => ["height", "width", "title", "src"],
'iframe' => [
'allowed_attributes' => ['height', 'width', 'title', 'src'],
],
],
];
@ -103,11 +101,11 @@ class Contents
$sanitizer = $builder->build($detergent);
$scrubbed = $sanitizer->sanitize($result->getContent());
$featureList = explode(",", $meta["feature"]);
$featureList = explode(',', $meta['feature']);
$docs = '';
if (isset($meta["files"])) {
$fileList = explode(",", $meta["files"]);
$docs = $meta["files"];
if (isset($meta['files'])) {
$fileList = explode(',', $meta['files']);
$docs = $meta['files'];
} else {
$fileList = [];
$docs = '';
@ -118,52 +116,52 @@ class Contents
foreach ($featureList as $file) {
$item = trim($file);
$ext = pathinfo($item, PATHINFO_EXTENSION);
if ($item != null || $item != "") {
array_push($media, ["file" => $item, "type" => trim($ext)]);
if ($item != null || $item != '') {
array_push($media, ['file' => $item, 'type' => trim($ext)]);
}
}
foreach ($fileList as $file) {
$item = trim($file);
$ext = pathinfo($item, PATHINFO_EXTENSION);
if ($item != null || $item != "") {
array_push($files, ["file" => $item, "type" => trim($ext)]);
if ($item != null || $item != '') {
array_push($files, ['file' => $item, 'type' => trim($ext)]);
}
}
//sort attributes into page object
$page = [
"id" => $meta["id"],
"uuid" => $meta["uuid"],
"title" => $meta["title"],
"feature" => $meta["feature"],
"files" => $docs,
"path" => $meta["path"],
"layout" => $meta["layout"],
"tags" => $meta["tags"],
"author" => $meta["author"],
"created" => date("Y M D d", $meta["created"]),
"updated" => date("Y M D d", $meta["updated"]),
"rawCreated" => $meta["created"],
"rawUpdated" => $meta["updated"],
"createdYear" => date("Y", $meta["created"]),
"createdMonth" => date("m", $meta["created"]),
"deleted" => $meta["deleted"],
"menu" => $meta["menu"],
"featured" => $meta["featured"],
"published" => $meta["published"],
"slug" => $meta["slug"],
"filePath" => $file,
"content" => $parsed->getContent(),
"html" => $scrubbed,
"media" => $media,
"docs" => $files
'id' => $meta['id'],
'uuid' => $meta['uuid'],
'title' => $meta['title'],
'feature' => $meta['feature'],
'files' => $docs,
'path' => $meta['path'],
'layout' => $meta['layout'],
'tags' => $meta['tags'],
'author' => $meta['author'],
'created' => date('Y M D d', $meta['created']),
'updated' => date('Y M D d', $meta['updated']),
'rawCreated' => $meta['created'],
'rawUpdated' => $meta['updated'],
'createdYear' => date('Y', $meta['created']),
'createdMonth' => date('m', $meta['created']),
'deleted' => $meta['deleted'],
'menu' => $meta['menu'],
'featured' => $meta['featured'],
'published' => $meta['published'],
'slug' => $meta['slug'],
'filePath' => $file,
'content' => $parsed->getContent(),
'html' => $scrubbed,
'media' => $media,
'docs' => $files
];
//checks for duplicates
$uuid = $meta["uuid"];
$uuid = $meta['uuid'];
$found = current(
array_filter($contents, function ($item) use ($uuid) {
return isset($item["uuid"]) && $uuid == $item["uuid"];
return isset($item['uuid']) && $uuid == $item['uuid'];
})
);
@ -172,7 +170,7 @@ class Contents
array_push($contents, $page);
}
}
$contents = orderBy($contents, ["id"], ["desc"]);
$contents = orderBy($contents, ['id'], ['desc']);
return $contents;
}
}

@ -2,10 +2,7 @@
namespace brain\data;
use brain\data\Settings;
use brain\data\Session;
use brain\utility\DocTools;
use function _\find;
class Member
@ -13,12 +10,11 @@ class Member
public function __construct()
{
}
public static function verifyKey(string $key)
{
if (isset($key)) {
$folks = (new Settings())->getFolks();
$found = find($folks, ["key" => $key]);
$found = find($folks, ['key' => $key]);
if ($found) {
return true;
} else {
@ -28,35 +24,34 @@ class Member
return false;
}
}
public static function updateData(string $key, string $data, $secret = null)
{
$folks = (new Settings())->getFolks();
if (isset($secret)) {
$found = find($folks, ["secret" => $secret]);
$found = find($folks, ['secret' => $secret]);
} else {
$member = Session::get("member");
$found = find($folks, ["handle" => $member["handle"]]);
$member = Session::get('member');
$found = find($folks, ['handle' => $member['handle']]);
}
$found[$key] = $data;
//record time updated
$updated = new \Moment\Moment();
$found["updated"] = $updated->format("Y-m-d\TH:i:sP");
$found['updated'] = $updated->format("Y-m-d\TH:i:sP");
$newFolks = [];
array_push($newFolks, $found);
//save updated file
DocTools::writeSettings("../config/folks.json", $newFolks);
DocTools::writeSettings('../config/folks.json', $newFolks);
//update member data in session
if (!isset($secret)) {
$member = [
"handle" => $found["handle"],
"email" => $found["email"],
"role" => $found["role"],
"avatar" => $found["avi"],
"key" => $found["key"],
'handle' => $found['handle'],
'email' => $found['email'],
'role' => $found['role'],
'avatar' => $found['avi'],
'key' => $found['key'],
];
Session::set("member", $member);
Session::set('member', $member);
}
}
}

@ -2,12 +2,8 @@
namespace brain\data;
use Mni\FrontYAML\Parser;
use brain\data\Settings;
use brain\data\Book;
use brain\utility\Sorting;
use brain\utility\DocTools;
use function _\find;
class Render
@ -17,38 +13,37 @@ class Render
public $pageInfo;
public $menu;
public $background;
public function __construct()
{
$config = new Settings();
//TODO: Add theme folder to loader
$settings = $config->getSettings();
$this->menu = $settings["menu"];
$this->theme = $settings["global"]["theme"];
$this->loader = new \Twig\Loader\FilesystemLoader("../content/themes/" . $this->theme);
$this->menu = $settings['menu'];
$this->theme = $settings['global']['theme'];
$this->loader = new \Twig\Loader\FilesystemLoader('../content/themes/' . $this->theme);
$this->twig = new \Twig\Environment($this->loader, []);
$this->pageInfo = [
"keywords" => isset($settings["global"]["keywords"])
? $settings["global"]["keywords"]
: "fipamo, blog, jamstack, php, markdown, js",
"description" => $settings["global"]["descriptions"],
"image" =>
$settings["global"]["base_url"] . $settings["global"]["background"],
"baseURL" => $settings["global"]["base_url"],
'keywords' => isset($settings['global']['keywords'])
? $settings['global']['keywords']
: 'fipamo, blog, jamstack, php, markdown, js',
'description' => $settings['global']['descriptions'],
'image' => $settings['global']['base_url'] . $settings['global']['background'],
'baseURL' => $settings['global']['base_url'],
];
//move global theme image assets to public folder
foreach (
new \DirectoryIterator("../content/themes/" . $this->theme . "/assets/images/global/") as $file
foreach (new \DirectoryIterator('../content/themes/' . $this->theme . '/assets/images/global/') as $file
) {
if ($file->isDot()) {
continue;
}
if (!is_file("../public/assets/images/global/" . $file->getFileName())) {
if (!is_file('../public/assets/images/global/' . $file->getFileName())) {
copy(
"../content/themes/" .
'../content/themes/' .
$this->theme .
"/assets/images/global/" .
'/assets/images/global/' .
$file->getFileName(),
"../public/assets/images/global/" . $file->getFileName()
'../public/assets/images/global/' . $file->getFileName()
);
} else {
//image is already there, so chill
@ -72,28 +67,27 @@ class Render
$scripts = glob('../public/assets/scripts/*'); // get all file names
foreach ($scripts as $file) { // iterate files
if (is_file($file)) {
if (!$file == "../public/assets/scripts/Start.js") {
if (!$file == '../public/assets/scripts/Start.js') {
unlink($file); // delete file
}
}
}
//copy theme assets to public
$newcss = glob("../content/themes/" . $this->theme . "/assets/css/*");
$newcss = glob('../content/themes/' . $this->theme . '/assets/css/*');
foreach ($newcss as $file) { // iterate files
if (is_file($file)) {
$path = explode("/", $file);
copy($file, "../public/assets/css/" . $path[6]);
$path = explode('/', $file);
copy($file, '../public/assets/css/' . $path[6]);
}
}
$newjs = glob("../content/themes/" . $this->theme . "/assets/scripts/*");
$newjs = glob('../content/themes/' . $this->theme . '/assets/scripts/*');
foreach ($newjs as $file) { // iterate files
if (is_file($file)) {
$path = explode("/", $file);
copy($file, "../public/assets/scripts/" . $path[6]);
$path = explode('/', $file);
copy($file, '../public/assets/scripts/' . $path[6]);
}
}
}
public function renderPages()
{
$pages = (new Book())->getContents();
@ -103,25 +97,24 @@ class Render
foreach ($pages as $page) {
$pageOptions = Sorting::page($page);
$layout = $page["layout"];
$layout = $page['layout'];
//new pages have no layout, so defautl for now
if ($layout == "" || $layout == null) {
$layout = "page";
if ($layout == '' || $layout == null) {
$layout = 'page';
}
$template = $layout . ".twig";
if (str_contains($page["layout"], "index")) {
$location = "../public/index.html";
$template = $layout . '.twig';
if (str_contains($page['layout'], 'index')) {
$location = '../public/index.html';
$dir = null;
} else {
// if page is a menu item, render the page on public root
if ($page["menu"] == "true") {
$location = "../public/" . $page["slug"] . ".html";
$dir = "../public/";
if ($page['menu'] == 'true') {
$location = '../public/' . $page['slug'] . '.html';
$dir = '../public/';
} else {
$location =
"../public/" . $page["path"] . "/" . $page["slug"] . ".html";
$dir = "../public/" . $page["path"];
$location = '../public/' . $page['path'] . '/' . $page['slug'] . '.html';
$dir = '../public/' . $page['path'];
}
}
@ -129,75 +122,72 @@ class Render
DocTools::writeHTML($location, $html, $dir);
}
}
public function renderArchive()
{
$archive = Sorting::archive();
$template = "archive.twig";
$template = 'archive.twig';
$pageOptions = [
"title" => "Archive",
"background" => $this->pageInfo["image"],
"archives" => $archive,
"info" => $this->pageInfo,
"menu" => $this->menu,
'title' => 'Archive',
'background' => $this->pageInfo['image'],
'archives' => $archive,
'info' => $this->pageInfo,
'menu' => $this->menu,
];
$html = $this->twig->render($template, $pageOptions);
$location = "../public/archives.html";
$location = '../public/archives.html';
DocTools::writeHTML($location, $html);
}
public function renderTags()
{
$list = Sorting::tags();
foreach ($list as $item) {
$template = "tags.twig";
$template = 'tags.twig';
$pageOptions = [
"title" => "Pages Tagged as " . $item["tag_name"],
"background" => $this->pageInfo["image"],
"tag_list" => $item["pages"],
"info" => $this->pageInfo,
"menu" => $this->menu,
'title' => 'Pages Tagged as ' . $item['tag_name'],
'background' => $this->pageInfo['image'],
'tag_list' => $item['pages'],
'info' => $this->pageInfo,
'menu' => $this->menu,
];
$html = $this->twig->render($template, $pageOptions);
$location = "../public/tags/" . $item["slug"] . ".html";
$location = '../public/tags/' . $item['slug'] . '.html';
//if tags folder doesn't exist, make it
if (!is_dir("../public/tags")) {
mkdir("../public/tags", 0755, true);
if (!is_dir('../public/tags')) {
mkdir('../public/tags', 0755, true);
} else {
}
if (!is_file($location)) {
file_put_contents($location, $html);
} else {
($new = fopen($location, "w")) or die("Unable to open file!");
($new = fopen($location, 'w')) or die('Unable to open file!');
fwrite($new, $html);
fclose($new);
}
}
}
public function renderIndex()
{
//TODO: Need to fix this to account for new index templating system
$pages = (new Book())->getContents();
$index = find($pages, ["layout" => "index"]);
$template = "index.twig";
$location = "../public/index.html";
$index = find($pages, ['layout' => 'index']);
$template = 'index.twig';
$location = '../public/index.html';
$dir = null;
$meta = [
"who" => $index["author"],
"when" => $index["created"],
'who' => $index['author'],
'when' => $index['created'],
];
$pageOptions = [
"title" => $index["title"],
"background" => $index["feature"],
"meta" => $meta,
'title' => $index['title'],
'background' => $index['feature'],
'meta' => $meta,
];
$html = $this->twig->render($template, $pageOptions);

@ -4,41 +4,38 @@ namespace brain\data;
use ReallySimpleJWT\Token;
use function _\find;
class Session
{
private static $file = "../content/.session";
private static $file = '../content/.session';
private static $data = [
"member" => "",
"token" => "",
"form_token" => "",
'member' => '',
'token' => '',
'form_token' => '',
];
public static function start()
{
if (!is_file(self::$file)) {
file_put_contents(self::$file, json_encode(self::$data));
} else {
($new = fopen(self::$file, "w")) or die("Unable to open file!");
($new = fopen(self::$file, 'w')) or die('Unable to open file!');
fwrite($new, json_encode(self::$data));
fclose($new);
}
}
public static function active()
{
if (!is_file(self::$file)) {
return false;
} else {
$data = json_decode(file_get_contents(self::$file), true);
if ($data["member"] != null) {
$secret = (new Settings())->getFolks("secret");
if ($data['member'] != null) {
$secret = (new Settings())->getFolks('secret');
if ($secret == null) {
return false;
} else {
if (
Token::validate($data["token"], $secret) &&
Token::validateExpiration($data["token"], $secret)
if (Token::validate($data['token'], $secret) &&
Token::validateExpiration($data['token'], $secret)
) {
return true;
} else {
@ -50,14 +47,12 @@ class Session
}
}
}
public static function verifyToken($token)
{
$data = json_decode(file_get_contents(self::$file), true);
if ($data["member"] != null) {
$secret = (new Settings())->getFolks("secret");
if (
Token::validate($token, $secret) &&
if ($data['member'] != null) {
$secret = (new Settings())->getFolks('secret');
if (Token::validate($token, $secret) &&
Token::validateExpiration($token, $secret)
) {
return true;
@ -68,26 +63,23 @@ class Session
return false;
}
}
public static function set($key, $value)
{
$data = json_decode(file_get_contents(self::$file), true);
$data[$key] = $value;
($fresh = fopen(self::$file, "w")) or die("Unable to open file!");
($fresh = fopen(self::$file, 'w')) or die('Unable to open file!');
fwrite($fresh, json_encode($data));
fclose($fresh);
}
public static function get($key)
{
$data = json_decode(file_get_contents(self::$file), true);
return $data[$key];
}
public static function kill()
{
($fresh = fopen(self::$file, "w")) or die("Unable to open file!");
($fresh = fopen(self::$file, 'w')) or die('Unable to open file!');
fwrite($fresh, json_encode(self::$data));
fclose($fresh);
}

@ -2,10 +2,8 @@
namespace brain\data;
use brain\data\Member;
use brain\utility\DocTools;
use brain\utility\Sorting;
use function _\find;
use function _\pull;
use function _\remove;
@ -19,92 +17,88 @@ class Settings
public function __construct()
{
//gets all settings files and converts to php objects
$this->folks = json_decode(file_get_contents("../config/folks.json"), true);
self::$tags = json_decode(file_get_contents("../config/tags.json"), true);
$this->folks = json_decode(file_get_contents('../config/folks.json'), true);
self::$tags = json_decode(file_get_contents('../config/tags.json'), true);
self::$settings = json_decode(
file_get_contents("../config/settings.json"),
file_get_contents('../config/settings.json'),
true
);
}
public static function sync($data)
{
$settings = self::$settings;
$settings["global"]["base_url"] = $data["global"]["base_url"];
$settings["global"]["title"] = $data["global"]["title"];
$settings["global"]["descriptions"] = $data["global"]["descriptions"];
$settings["global"]["base_url"] = $data["global"]["base_url"];
$settings["global"]["private"] = $data["global"]["private"];
$settings["global"]["renderOnSave"] = $data["global"]["renderOnSave"];
$settings["global"]["theme"] = $data["global"]["theme"];
$settings["global"]["externalAPI"] = $data["global"]["externalAPI"];
$settings["global"]["dynamicRender"] = $data["global"]["dynamicRender"];
$settings['global']['base_url'] = $data['global']['base_url'];
$settings['global']['title'] = $data['global']['title'];
$settings['global']['descriptions'] = $data['global']['descriptions'];
$settings['global']['base_url'] = $data['global']['base_url'];
$settings['global']['private'] = $data['global']['private'];
$settings['global']['renderOnSave'] = $data['global']['renderOnSave'];
$settings['global']['theme'] = $data['global']['theme'];
$settings['global']['externalAPI'] = $data['global']['externalAPI'];
$settings['global']['dynamicRender'] = $data['global']['dynamicRender'];
Member::updateData("handle", $data["member"]["handle"]);
Member::updateData("email", $data["member"]["email"]);
Member::updateData('handle', $data['member']['handle']);
Member::updateData('email', $data['member']['email']);
$settings["email"]["active"] = $data["email"]["active"];
$settings["email"]["smtp"] = $data["email"]["smtp"];
$settings["email"]["mailgun"] = $data["email"]["mailgun"];
$settings['email']['active'] = $data['email']['active'];
$settings['email']['smtp'] = $data['email']['smtp'];
$settings['email']['mailgun'] = $data['email']['mailgun'];
DocTools::writeSettings("../config/settings.json", $settings);
DocTools::writeSettings('../config/settings.json', $settings);
}
public static function navSync($data)
{
$settings = self::$settings;
$remove = $data["remove"];
$remove = $data['remove'];
//if remove contains id, find nav item page and set menu to false
if ($remove != null || $remove != "") {
$page = (new Book("../content/pages"))->findPageById($remove);
$page["menu"] = "false";
$page["published"]
? ($page["published"] = "true")
: ($page["published"] = "false");
$page["featured"]
? ($page["featured"] = "true")
: ($page["featured"] = "false");
$page["deleted"]
? ($page["deleted"] = "true")
: ($page["deleted"] = "false");
if ($remove != null || $remove != '') {
$page = (new Book('../content/pages'))->findPageById($remove);
$page['menu'] = 'false';
$page['published']
? ($page['published'] = 'true')
: ($page['published'] = 'false');
$page['featured']
? ($page['featured'] = 'true')
: ($page['featured'] = 'false');
$page['deleted']
? ($page['deleted'] = 'true')
: ($page['deleted'] = 'false');
$updated = new \Moment\Moment();
$created = new \Moment\Moment($page["rawCreated"]);
$page["created"] = $created->format("Y-m-d\TH:i:sP");
$page["updated"] = $updated->format("Y-m-d\TH:i:sP");
$created = new \Moment\Moment($page['rawCreated']);
$page['created'] = $created->format("Y-m-d\TH:i:sP");
$page['updated'] = $updated->format("Y-m-d\TH:i:sP");
$md = DocTools::objectToMD($page);
if ($page["layout"] == "index") {
$writePath = "../content/pages/start/index.md";
if ($page['layout'] == 'index') {
$writePath = '../content/pages/start/index.md';
} else {
$writePath =
"../content/pages/" . $page["path"] . "/" . $page["slug"] . ".md";
$writePath = '../content/pages/' . $page['path'] . '/' . $page['slug'] . '.md';
}
DocTools::writePages("write", $page["path"], $writePath, $md);
DocTools::writePages('write', $page['path'], $writePath, $md);
}
$settings["menu"] = [];
$items = $data["menu"];
$settings['menu'] = [];
$items = $data['menu'];
foreach ($items as $item) {
array_push($settings["menu"], [
"title" => $item["title"],
"id" => $item["id"],
"uuid" => $item["uuid"],
"slug" => $item["slug"],
"path" => $item["path"],
array_push($settings['menu'], [
'title' => $item['title'],
'id' => $item['id'],
'uuid' => $item['uuid'],
'slug' => $item['slug'],
'path' => $item['path'],
]);
}
DocTools::writeSettings("../config/settings.json", $settings);
DocTools::writeSettings('../config/settings.json', $settings);
}
public function getFolks($key = null)
{
if (isset($key)) {
$member = Session::get("member");
$found = find($this->folks, ["handle" => $member["handle"]]);
$member = Session::get('member');
$found = find($this->folks, ['handle' => $member['handle']]);
if ($found) {
return $found[$key];
}
@ -112,66 +106,58 @@ class Settings
return $this->folks;
}
}
public function getSettings($key = null)
{
return self::$settings;
}
public static function getTags()
{
return self::$tags;
}
public static function updateGlobalData($key, $data)
{
$settings = self::$settings;
$settings["global"][$key] = $data;
DocTools::writeSettings("../config/settings.json", $settings);
$settings['global'][$key] = $data;
DocTools::writeSettings('../config/settings.json', $settings);
}
public static function getCurrentIndex()
{
$settings = self::$settings;
return $settings["library_stats"]["current_index"];
return $settings['library_stats']['current_index'];
}
public static function updateIndex()
{
$settings = self::$settings;
$settings["library_stats"]["current_index"] =
$settings["library_stats"]["current_index"] + 1;
$settings['library_stats']['current_index'] = $settings['library_stats']['current_index'] + 1;
DocTools::writeSettings("../config/settings.json", $settings);
DocTools::writeSettings('../config/settings.json', $settings);
}
public static function updateMenu($body)
{
$settings = self::$settings;
//$menu = $settings["menu"];
$item = [
"title" => $body["title"],
"id" => $body["id"],
"uuid" => $body["uuid"],
"slug" => $body["slug"],
"path" => $body["path"],
'title' => $body['title'],
'id' => $body['id'],
'uuid' => $body['uuid'],
'slug' => $body['slug'],
'path' => $body['path'],
];
if ($body["menu"] == "true") {
if (!find($settings["menu"], ["uuid" => $item["uuid"]])) {
array_push($settings["menu"], $item);
if ($body['menu'] == 'true') {
if (!find($settings['menu'], ['uuid' => $item['uuid']])) {
array_push($settings['menu'], $item);
}
} else {
if (find($settings["menu"], ["uuid" => $item["uuid"]])) {
pull($settings["menu"], $item);
if (find($settings['menu'], ['uuid' => $item['uuid']])) {
pull($settings['menu'], $item);
}
}
DocTools::writeSettings("../config/settings.json", $settings);
DocTools::writeSettings('../config/settings.json', $settings);
}
public static function updateTags()
{
$tags = Sorting::tags();
DocTools::writeSettings("../config/tags.json", $tags);
DocTools::writeSettings('../config/tags.json', $tags);
}
}

@ -2,60 +2,55 @@
namespace brain\data;
use brain\data\Settings;
class Themes
{
private $themes = [];
public function __construct()
{
$_themes = glob("../content/themes/*", GLOB_ONLYDIR);
$_themes = glob('../content/themes/*', GLOB_ONLYDIR);
foreach ($_themes as $theme) {
array_push(
$this->themes,
json_decode(file_get_contents($theme . "/theme.json"), true)
json_decode(file_get_contents($theme . '/theme.json'), true)
);
}
}
public function getThemes()
{
return $this->themes;
}
public function getCustomIndex()
{
$settings = (new Settings())->getSettings();
$currentTheme = $settings["global"]["theme"];
$folder = "../content/themes/" . $currentTheme;
$files = array_filter(glob("$folder/*twig"), "is_file");
$currentTheme = $settings['global']['theme'];
$folder = '../content/themes/' . $currentTheme;
$files = array_filter(glob("$folder/*twig"), 'is_file');
$views = [];
foreach ($files as $file) {
$path = explode("/", $file);
$path = explode('/', $file);
$fileName = $path[4];
if (str_contains($fileName, "index")) {
$page = explode(".", $fileName);
if (str_contains($fileName, 'index')) {
$page = explode('.', $fileName);
$views[] = $page[0];
}
}
return $views;
}
public function getCustomViews()
{
$settings = (new Settings())->getSettings();
$currentTheme = $settings["global"]["theme"];
$folder = "../content/themes/" . $currentTheme;
$files = array_filter(glob("$folder/*twig"), "is_file");
$currentTheme = $settings['global']['theme'];
$folder = '../content/themes/' . $currentTheme;
$files = array_filter(glob("$folder/*twig"), 'is_file');
$views = [];
foreach ($files as $file) {
$path = explode("/", $file);
$path = explode('/', $file);
$fileName = $path[4];
if (str_contains($fileName, "page")) {
$page = explode(".", $fileName);
if (str_contains($fileName, 'page')) {
$page = explode('.', $fileName);
$views[] = $page[0];
}
}

@ -7,18 +7,17 @@ class DocTools
public function __construct()
{
}
public static function writePages($task, $path, $fileLocation, $fileContents)
{
try {
if ($task == "create") {
if (!is_dir("../content/pages/" . $path)) {
if ($task == 'create') {
if (!is_dir('../content/pages/' . $path)) {
//Directory does not exist, so lets create it.
mkdir("../content/pages/" . $path, 0755, true);
mkdir('../content/pages/' . $path, 0755, true);
}
file_put_contents($fileLocation, $fileContents);
} else {
($new = fopen($fileLocation, "w")) or die("Unable to open file!");
($new = fopen($fileLocation, 'w')) or die('Unable to open file!');
fwrite($new, $fileContents);
fclose($new);
}
@ -28,18 +27,16 @@ class DocTools
return false;
}
}
public static function writeSettings($fileLocation, $fileContents)
{
if (!is_file($fileLocation)) {
file_put_contents($fileLocation, json_encode($fileContents));
} else {
($new = fopen($fileLocation, "w")) or die("Unable to open file!");
($new = fopen($fileLocation, 'w')) or die('Unable to open file!');
fwrite($new, json_encode($fileContents));
fclose($new);
}
}
public static function writeHTML($location, $html, $path = null)
{
if ($path != null) {
@ -51,12 +48,11 @@ class DocTools
if (!is_file($location)) {
file_put_contents($location, $html);
} else {
($new = fopen($location, "w")) or die("Unable to open file!");
($new = fopen($location, 'w')) or die('Unable to open file!');
fwrite($new, $html);
fclose($new);
}
}
public static function deleteFolder($path)
{
if (!empty($path) && is_dir($path)) {
@ -83,62 +79,60 @@ class DocTools
rmdir($path);
}
}
public static function objectToMD($object)
{
$markdown =
"---\n" .
"id: " .
$object["id"] .
$markdown = "---\n" .
'id: ' .
$object['id'] .
"\n" .
"uuid: " .
$object["uuid"] .
'uuid: ' .
$object['uuid'] .
"\n" .
"title: " .
'title: ' .
"'" .
$object["title"] .
$object['title'] .
"'" .
"\n" .
"feature: " .
$object["feature"] .
'feature: ' .
$object['feature'] .
"\n" .
"files: " .
$object["files"] .
'files: ' .
$object['files'] .
"\n" .
"path: " .
$object["path"] .
'path: ' .
$object['path'] .
"\n" .
"layout: " .
$object["layout"] .
'layout: ' .
$object['layout'] .
"\n" .
"tags: " .
$object["tags"] .
'tags: ' .
$object['tags'] .
"\n" .
"author: " .
$object["author"] .
'author: ' .
$object['author'] .
"\n" .
"created: " .
$object["created"] .
'created: ' .
$object['created'] .
"\n" .
"updated: " .
$object["updated"] .
'updated: ' .
$object['updated'] .
"\n" .
"deleted: " .
$object["deleted"] .
'deleted: ' .
$object['deleted'] .
"\n" .
"slug: " .
$object["slug"] .
'slug: ' .
$object['slug'] .
"\n" .
"menu: " .
$object["menu"] .
'menu: ' .
$object['menu'] .
"\n" .
"published: " .
$object["published"] .
'published: ' .
$object['published'] .
"\n" .
"featured: " .
$object["featured"] .
'featured: ' .
$object['featured'] .
"\n---\n" .
$object["content"];
$object['content'];
return $markdown;
}

@ -21,9 +21,9 @@ class FileUploader
// echo "**FILE** " . $file->getClientFileName();
$file->moveTo($directory.'/'.urlencode($file->getClientFileName()));
$file->moveTo($directory . '/' . urlencode($file->getClientFileName()));
} catch (RuntimeException $e) {
echo 'ERROR '.$e->getMessage();
echo 'ERROR ' . $e->getMessage();
// echo "failed to upload image: " . $e->getMessage();
// throw new Error("Failed to upload image file");

@ -9,37 +9,38 @@ class HandleCors
public function __construct()
{
//look to see if settings file exists. kinda important
if (file_exists("../config/settings.json")) {
if (file_exists('../config/settings.json')) {
//check settings to see if external api access is allowed
$config = new Settings();
$settings = $config->getSettings();
if ($settings["global"]["externalAPI"]) {
if ($settings['global']['externalAPI']) {
//echo "API STATUS: " . $settings["global"]["externalAPI"];
if ($settings["global"]["externalAPI"] == "true") {
if ($settings['global']['externalAPI'] == 'true') {
//echo "API ACCESS ACTIVE";
// checks to see if origin is set
if (isset($_SERVER["HTTP_ORIGIN"])) {
// You can decide if the origin in $_SERVER['HTTP_ORIGIN'] is something you want to allow, or as we do here, just allow all
header("Access-Control-Allow-Origin: {$_SERVER["HTTP_ORIGIN"]}");
if (isset($_SERVER['HTTP_ORIGIN'])) {
// You can decide if the origin in $_SERVER['HTTP_ORIGIN']
//is something you want to allow, or as we do here, just allow all
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
} else {
//No HTTP_ORIGIN set, so we allow any. You can disallow if needed here
//never allow just any domain, so turn CORS off if no No HTTP_ORIGIN is set
//header("Access-Control-Allow-Origin: *");
}
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 600"); // cache for 10 minutes
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 600'); // cache for 10 minutes
if ($_SERVER["REQUEST_METHOD"] == "OPTIONS") {
if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"])) {
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
header(
"Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT"
'Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT'
);
} //Make sure you remove those you do not want to support
if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"])) {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
header(
"Access-Control-Allow-Headers: {$_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]}"
"Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"
);
}

@ -2,7 +2,6 @@
namespace brain\utility;
use Slim\Views\Twig;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use brain\data\Settings;
@ -14,58 +13,56 @@ class Mailer
{
$config = new Settings();
$settings = $config->getSettings();
$mailConfig = $settings["email"];
$mailConfig = $settings['email'];
$mail = new PHPMailer();
switch ($body["mail_task"]) {
case "TESTING":
$html =
"<h1>Hi! It's Fipamo!</h1><br>" .
switch ($body['mail_task']) {
case 'TESTING':
$html = "<h1>Hi! It's Fipamo!</h1><br>" .
"<strong>It's just a test</strong><br>" .
$body["content"];
$member = Session::get("member");
$mail->addAddress($member["email"], ""); //pull email address from current user
$mail->Subject = "A test email";
$body['content'];
$member = Session::get('member');
$mail->addAddress($member['email'], ''); //pull email address from current user
$mail->Subject = 'A test email';
break;
case "SEND_SECRET":
$html =
"<h1>Hi! It's Fipamo!</h1><br>" .
"<strong>This is your secret key.</strong><br><br>" .
"<h3>" .
$body["secret"] .
"</h3>" .
"<br> Use this key to reset your password.";
$mail->addAddress($body["email"], ""); //pull email address from current user
case 'SEND_SECRET':
$html = "<h1>Hi! It's Fipamo!</h1><br>" .
'<strong>This is your secret key.</strong><br><br>' .
'<h3>' .
$body['secret'] .
'</h3>' .
'<br> Use this key to reset your password.';
$mail->addAddress($body['email'], ''); //pull email address from current user
$mail->Subject = "Shhhh! It's a secret!";
break;
default:
return $result = [
"type" => "noMailService",
"message" => "Mail task is undefined. What are you doing??",
'type' => 'noMailService',
'message' => 'Mail task is undefined. What are you doing??',
];
break;
}
//set values based on current active protocol
switch ($mailConfig["active"]) {
case "option-smtp":
$mail->setFrom($mailConfig["smtp"]["email"], "System Email");
$mail->Host = "playvicio.us";
$mail->Username = $mailConfig["smtp"]["email"];
$mail->Password = $mailConfig["smtp"]["password"];
switch ($mailConfig['active']) {
case 'option-smtp':
$mail->setFrom($mailConfig['smtp']['email'], 'System Email');
$mail->Host = 'playvicio.us';
$mail->Username = $mailConfig['smtp']['email'];
$mail->Password = $mailConfig['smtp']['password'];
break;
case "option-mg":
$mail->setFrom($mailConfig["mailgun"]["domain"], "No Reply");
$mail->Host = "smtp.mailgun.org";
$mail->Username = $mailConfig["mailgun"]["domain"];
$mail->Password = $mailConfig["mailgun"]["key"];
case 'option-mg':
$mail->setFrom($mailConfig['mailgun']['domain'], 'No Reply');
$mail->Host = 'smtp.mailgun.org';
$mail->Username = $mailConfig['mailgun']['domain'];
$mail->Password = $mailConfig['mailgun']['key'];
break;
default:
//no mail service
return $result = [
"type" => "noMailService",
"message" => "Mail is not configured. Handle that.",
'type' => 'noMailService',
'message' => 'Mail is not configured. Handle that.',
];
break;
}
@ -74,7 +71,7 @@ class Mailer
$mail->IsHTML(true);
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
// Uncomment for debug info
@ -83,13 +80,13 @@ class Mailer
/* Finally send the mail. */
try {
$mail->send();
$result = ["type" => "mailSent", "message" => "Message Away!"];
$result = ['type' => 'mailSent', 'message' => 'Message Away!'];
} catch (Exception $e) {
//echo $e->errorMessage();
$result = [
"type" => "mailNotSent",
"message" => "Message Not Away!",
"error" => $e->errorMessage(),
'type' => 'mailNotSent',
'message' => 'Message Not Away!',
'error' => $e->errorMessage(),
];
}

@ -9,96 +9,93 @@ class Maintenance
public function __construct()
{
}
public static function makeBackup()
{
//make sure back directory is there
if (!is_dir("../config/backups")) {
mkdir("../config/backups", 0755, true);
if (!is_dir('../config/backups')) {
mkdir('../config/backups', 0755, true);
}
//creat backup zip
$zip = new \ZipArchive();
$zip->open(
"../config/backups/latest_back.zip",
'../config/backups/latest_back.zip',
\ZipArchive::CREATE | \ZipArchive::OVERWRITE
);
//gather data and path info for md pages
$pagePath = "../content/pages";
$yearPaths = glob($pagePath . "/*", GLOB_ONLYDIR);
$pagePath = '../content/pages';
$yearPaths = glob($pagePath . '/*', GLOB_ONLYDIR);
foreach ($yearPaths as $years) {
$year = explode("/", $years);
$year = explode('/', $years);
//grap the index and save it
if (trim($year[3]) == "start") {
if (trim($year[3]) == 'start') {
$options = [
"add_path" => "content/pages/" . $year[3] . "/",
"remove_all_path" => true,
'add_path' => 'content/pages/' . $year[3] . '/',
'remove_all_path' => true,
];
$zip->addGlob($years . "/*.md", GLOB_BRACE, $options);
$zip->addGlob($years . '/*.md', GLOB_BRACE, $options);
}
$monthsPath = glob($pagePath . "/" . $year[3] . "/*", GLOB_ONLYDIR);
$monthsPath = glob($pagePath . '/' . $year[3] . '/*', GLOB_ONLYDIR);
foreach ($monthsPath as $months) {
$month = explode("/", $months);
$month = explode('/', $months);
//once info is collected, add md pages to zip
$options = [
"add_path" => "content/pages/" . $year[3] . "/" . $month[4] . "/",
"remove_all_path" => true,
'add_path' => 'content/pages/' . $year[3] . '/' . $month[4] . '/',
'remove_all_path' => true,
];
$zip->addGlob($months . "/*.md", GLOB_BRACE, $options);
$zip->addGlob($months . '/*.md', GLOB_BRACE, $options);
}
}
//gather data and path info for blog images
$blogImagesPath = "../public/assets/images/blog";
$yearPaths = glob($blogImagesPath . "/*", GLOB_ONLYDIR);
$blogImagesPath = '../public/assets/images/blog';
$yearPaths = glob($blogImagesPath . '/*', GLOB_ONLYDIR);
foreach ($yearPaths as $years) {
$year = explode("/", $years);
$monthsPath = glob($blogImagesPath . "/" . $year[5] . "/*", GLOB_ONLYDIR);
$year = explode('/', $years);
$monthsPath = glob($blogImagesPath . '/' . $year[5] . '/*', GLOB_ONLYDIR);
foreach ($monthsPath as $months) {
$month = explode("/", $months);
$month = explode('/', $months);
//once info is collected, add images pages to zip
$options = [
"add_path" =>
"public/assets/images/blog/" . $year[5] . "/" . $month[6] . "/",
"remove_all_path" => true,
'add_path' => 'public/assets/images/blog/' . $year[5] . '/' . $month[6] . '/',
'remove_all_path' => true,
];
$zip->addGlob($months . "/*.*", GLOB_BRACE, $options);
$zip->addGlob($months . '/*.*', GLOB_BRACE, $options);
}
}
//gather data and path info for user images
$userImagesPath = "../public/assets/images/user";
$yearPaths = glob($userImagesPath . "/*", GLOB_ONLYDIR);
$userImagesPath = '../public/assets/images/user';
$yearPaths = glob($userImagesPath . '/*', GLOB_ONLYDIR);
foreach ($yearPaths as $years) {
$year = explode("/", $years);
$monthsPath = glob($userImagesPath . "/" . $year[5] . "/*", GLOB_ONLYDIR);
$year = explode('/', $years);
$monthsPath = glob($userImagesPath . '/' . $year[5] . '/*', GLOB_ONLYDIR);
foreach ($monthsPath as $months) {
$month = explode("/", $months);
$month = explode('/', $months);
//once info is collected, add images pages to zip
$options = [
"add_path" =>
"public/assets/images/user/" . $year[5] . "/" . $month[6] . "/",
"remove_all_path" => true,
'add_path' => 'public/assets/images/user/' . $year[5] . '/' . $month[6] . '/',
'remove_all_path' => true,
];
$zip->addGlob($months . "/*.*", GLOB_BRACE, $options);
$zip->addGlob($months . '/*.*', GLOB_BRACE, $options);
}
}
//add directory for settings and save them
$zip->addEmptyDir("settings");
$zip->addFile("../config/settings.json", "settings/settings.json");
$zip->addFile("../config/folks.json", "settings/folks.json");
$zip->addFile("../config/tags.json", "settings/tags.json");
$zip->addEmptyDir('settings');
$zip->addFile('../config/settings.json', 'settings/settings.json');
$zip->addFile('../config/folks.json', 'settings/folks.json');
$zip->addFile('../config/tags.json', 'settings/tags.json');
//save zip file
$zip->close();
//update settings file with latest back up date
$updated = new \Moment\Moment();
Settings::updateGlobalData(
"last_backup",
'last_backup',
$updated->format("Y-m-d\TH:i:sP")
);
$result = ["message" => "Backup created. THIS IS A SAFE SPACE!"];
$result = ['message' => 'Backup created. THIS IS A SAFE SPACE!'];
return $result;
}
}

@ -8,130 +8,127 @@ class SetUp
{
public static function status()
{
if (file_exists("../config/settings.json")) {
if (file_exists('../config/settings.json')) {
return true;
} else {
return false;
}
}
public static function init($body)
{
//grab template files
$newFolks = json_decode(
file_get_contents("../config/init/folks-template.json"),
file_get_contents('../config/init/folks-template.json'),
true
);
$newSettings = json_decode(
file_get_contents("../config/init/settings-template.json"),
file_get_contents('../config/init/settings-template.json'),
true
);
//get form values
//$body = $request->getParsedBody();
$handle = $body["new_member_handle"];
$email = $body["new_member_email"];
$pass = $body["new_member_pass"];
$title = $body["new_member_title"];
$handle = $body['new_member_handle'];
$email = $body['new_member_email'];
$pass = $body['new_member_pass'];
$title = $body['new_member_title'];
$now = new \Moment\Moment();
//setup folks config
$hash = password_hash($pass, PASSWORD_DEFAULT);
$newFolks[0]["id"] = 0;
$newFolks[0]["handle"] = $handle;
$newFolks[0]["email"] = $email;
$newFolks[0]["password"] = $hash;
$newFolks[0]["key"] = password_hash($email, PASSWORD_DEFAULT);
$newFolks[0]["secret"] = StringTools::randomString(12);
$newFolks[0]["role"] = "hnic";
$newFolks[0]["created"] = $now->format("Y-m-d\TH:i:sP");
$newFolks[0]["updated"] = $now->format("Y-m-d\TH:i:sP");
$newFolks[0]['id'] = 0;
$newFolks[0]['handle'] = $handle;
$newFolks[0]['email'] = $email;
$newFolks[0]['password'] = $hash;
$newFolks[0]['key'] = password_hash($email, PASSWORD_DEFAULT);
$newFolks[0]['secret'] = StringTools::randomString(12);
$newFolks[0]['role'] = 'hnic';
$newFolks[0]['created'] = $now->format("Y-m-d\TH:i:sP");
$newFolks[0]['updated'] = $now->format("Y-m-d\TH:i:sP");
//set up settings config
$newSettings["global"]["title"] = $title;
$newSettings['global']['title'] = $title;
//create index file
//$rightNow = $now->format("Y-m-d\TH:i:sP");
//var_dump($now->format("Y-m-d\TH:i:sP"));
$index = [
"id" => 1,
"uuid" => StringTools::createUUID(),
"title" => "FIRST!",
"feature" => "/assets/images/global/default-bg.jpg",
"files" => "",
"path" => "content/pages/start",
"layout" => "index",
"tags" => "start, welcome",
"author" => $handle,
"created" => $now->format("Y-m-d\TH:i:sP"),
"updated" => $now->format("Y-m-d\TH:i:sP"),
"deleted" => "false",
"slug" => "first",
"menu" => "false",
"featured" => "false",
"published" => "true",
"content" =>
"# F**k Yes \n\nIf you're seeing this, you're up and running. NICE WORK!\n\nFrom here, feel free to start dropping pages to your heart's content.\n\nFor some tips about using Fipamo, check out the ![docs](https://code.playvicio.us/Are0h/Fipamo/wiki/02-Usage)\n\nAll good? Feel free to edit this page to whatever you want!\n\nYOU'RE THE CAPTAIN NOW.",
'id' => 1,
'uuid' => StringTools::createUUID(),
'title' => 'FIRST!',
'feature' => '/assets/images/global/default-bg.jpg',
'files' => '',
'path' => 'content/pages/start',
'layout' => 'index',
'tags' => 'start, welcome',
'author' => $handle,
'created' => $now->format("Y-m-d\TH:i:sP"),
'updated' => $now->format("Y-m-d\TH:i:sP"),
'deleted' => 'false',
'slug' => 'first',
'menu' => 'false',
'featured' => 'false',
'published' => 'true',
'content' => "# F**k Yes \n\nIf you're seeing this, you're up and running. NICE WORK!\n\nFrom here, feel free to start dropping pages to your heart's content.\n\nFor some tips about using Fipamo, check out the ![docs](https://code.playvicio.us/Are0h/Fipamo/wiki/02-Usage)\n\nAll good? Feel free to edit this page to whatever you want!\n\nYOU'RE THE CAPTAIN NOW.",
];
$freshIndex = DocTools::objectToMD($index);
//once all files created, write down
DocTools::writeSettings("../config/settings.json", $newSettings);
DocTools::writeSettings("../config/folks.json", $newFolks);
DocTools::writeSettings("../config/tags.json", []);
DocTools::writeSettings('../config/settings.json', $newSettings);
DocTools::writeSettings('../config/folks.json', $newFolks);
DocTools::writeSettings('../config/tags.json', []);
DocTools::writePages(
"create",
"start",
"../content/pages/start/index.md",
'create',
'start',
'../content/pages/start/index.md',
$freshIndex
);
//if there is an older session file, get rid of it
if (is_file("../content/.session")) {
unlink("../content/.session");
if (is_file('../content/.session')) {
unlink('../content/.session');
}
$result = ["type" => "blogInitGood", "message" => "Site Created"];
$result = ['type' => 'blogInitGood', 'message' => 'Site Created'];
return $result;
}
public static function restore($request)
{
$result = [
"type" => "requestLame",
"message" => "Still working on it.",
'type' => 'requestLame',
'message' => 'Still working on it.',
];
$body = $request->getParsedBody();
$backup = $request->getUploadedFiles();
$file = $backup["backup-upload"];
$file = $backup['backup-upload'];
//NOTE: If this fails check 'post_max_size' in php.ini
$size = $file->getSize();
$name = $file->getClientFileName();
//park it so it can be read
$file->moveTo("../content" . "/" . $name);
$file->moveTo('../content' . '/' . $name);
//open it and get files to verify user
$zip = new \ZipArchive();
if ($zip->open("../content" . "/" . $name) === true) {
$folks = json_decode($zip->getFromName("settings/folks.json"), true);
$found = find($folks, ["handle" => $body["restore_member_handle"]]);
if ($zip->open('../content' . '/' . $name) === true) {
$folks = json_decode($zip->getFromName('settings/folks.json'), true);
$found = find($folks, ['handle' => $body['restore_member_handle']]);
//if member is found in back up, check pass
if ($found) {
if (password_verify($body["restore_member_pass"], $found["password"])) {
if (password_verify($body['restore_member_pass'], $found['password'])) {
//backup verified, restore site
//set new secret key for older folks configs
$newFolks = [];
if (!isset($found["secret"])) {
$found["secret"] = StringTools::randomString(12);
if (!isset($found['secret'])) {
$found['secret'] = StringTools::randomString(12);
}
array_push($newFolks, $found);
//dump files in folder
$zip->extractTo("../content");
$zip->extractTo('../content');
//move to appropriate spots
/*
@ -143,49 +140,49 @@ class SetUp
//load up old config file
$newConfig = json_decode(
file_get_contents("../content/settings/settings.json"),
file_get_contents('../content/settings/settings.json'),
true
);
//check for key, add if not there
if (!isset($newConfig["global"]["externalAPI"])) {
$newConfig["global"]["externalAPI"] = "false";
if (!isset($newConfig['global']['externalAPI'])) {
$newConfig['global']['externalAPI'] = 'false';
}
//write new config file
DocTools::writeSettings("../config/settings.json", $newConfig);
DocTools::writeSettings('../config/settings.json', $newConfig);
//rename("../content/settings/folks.json", "../config/folks.json");
DocTools::writeSettings("../config/folks.json", $newFolks);
DocTools::writeSettings('../config/folks.json', $newFolks);
rename("../content/settings/tags.json", "../config/tags.json");
rename('../content/settings/tags.json', '../config/tags.json');
//images path for blog and user
$blogImagePath = "../public/assets/images/blog";
$userImagePath = "../public/assets/images/user";
$blogImagePath = '../public/assets/images/blog';
$userImagePath = '../public/assets/images/user';
//check to see if image dirs are empty, if not chill
if ($globs = glob($blogImagePath . "/*")) {
if ($globs = glob($blogImagePath . '/*')) {
//directory not empty, relax
} else {
rename("../content/public/assets/images/blog", $blogImagePath);
rename('../content/public/assets/images/blog', $blogImagePath);
}
if ($globs = glob($userImagePath . "/*")) {
if ($globs = glob($userImagePath . '/*')) {
//directory not empty, relax
} else {
rename("../content/public/assets/images/user", $userImagePath);
rename('../content/public/assets/images/user', $userImagePath);
}
rename("../content/content/pages/", "../content/pages");
rename('../content/content/pages/', '../content/pages');
//legacy check for old file structure
if (is_file("../content/pages/index.md")) {
if (!is_dir("../content/pages/start")) {
if (is_file('../content/pages/index.md')) {
if (!is_dir('../content/pages/start')) {
//Directory does not exist, so lets create it.
mkdir("../content/pages/start", 0755, true);
mkdir('../content/pages/start', 0755, true);
//move start page to appropriate spot
rename(
"../content/pages/index.md",
"../content/pages/start/index.md"
'../content/pages/index.md',
'../content/pages/start/index.md'
);
}
} else {
@ -194,34 +191,34 @@ class SetUp
//clean up
DocTools::deleteFolder("../content/settings");
DocTools::deleteFolder("../content/public");
DocTools::deleteFolder("../content/content");
DocTools::deleteFolder('../content/settings');
DocTools::deleteFolder('../content/public');
DocTools::deleteFolder('../content/content');
$result = [
"type" => "requestGood",
"message" => "Site Restored! Redirecting",
'type' => 'requestGood',
'message' => 'Site Restored! Redirecting',
];
} else {
$result = [
"type" => "requestLame",
"message" => "Check that password, champ.",
'type' => 'requestLame',
'message' => 'Check that password, champ.',
];
}
} else {
$result = [
"type" => "requestLame",
"message" => "No member found by that name, hoss",
'type' => 'requestLame',
'message' => 'No member found by that name, hoss',
];
}
$zip->close();
$zipPath = "../content/" . $name;
$zipPath = '../content/' . $name;
//trash zip when done
unlink($zipPath);
} else {
$result = [
"type" => "requestLame",
"message" => "Could not open backup. RATS!",
'type' => 'requestLame',
'message' => 'Could not open backup. RATS!',
];
}
return $result;

@ -16,7 +16,6 @@ class Sorting
public function __construct()
{
}
public static function tags()
{
$pages = (new Book('../content/pages'))->getContents();
@ -37,7 +36,6 @@ class Sorting
return self::$_tags;
}
private static function tagPages($tag, $pages)
{
$tagged = [];
@ -54,7 +52,6 @@ class Sorting
return $tagged;
}
public static function archive()
{
$pages = (new Book('../content/pages'))->getContents();
@ -81,7 +78,7 @@ class Sorting
$month = date('m', date($obj['rawCreated']));
if (!find($sorted, ['month' => $month])) {
$perMonth = filter($pages, [
'path' => $year['year'].'/'.$month,
'path' => $year['year'] . '/' . $month,
'deleted' => false,
'published' => true,
'layout' => 'page',
@ -102,7 +99,6 @@ class Sorting
return self::$_archive;
}
public static function page($page)
{
$config = new Settings();
@ -114,7 +110,7 @@ class Sorting
? $settings['global']['keywords']
: 'fipamo, blog, jamstack, php, markdown, js',
'description' => $settings['global']['descriptions'],
'image' => $settings['global']['base_url'].$settings['global']['background'],
'image' => $settings['global']['base_url'] . $settings['global']['background'],
'baseURL' => $settings['global']['base_url'],
];
@ -123,7 +119,7 @@ class Sorting
foreach ($taglist as $tag) {
$label = trim($tag);
array_push($tags, [
'label' => $label.' ',
'label' => $label . ' ',
'slug' => StringTools::safeString($label),
]);
}
@ -180,7 +176,7 @@ class Sorting
$ext = pathinfo($item, PATHINFO_EXTENSION);
if ($ext != 'mp4' && !$set) {
$pageInfo['image'] = $pageInfo['baseURL'].$item;
$pageInfo['image'] = $pageInfo['baseURL'] . $item;
$set = true;
}
}
@ -196,8 +192,7 @@ class Sorting
$limit = 4;
$pages = (new Book())->getContents();
foreach ($pages as $item) {
if (
!$item['deleted'] &&
if (!$item['deleted'] &&
$item['published'] &&
$item['menu'] != 'true'
) {

@ -10,12 +10,12 @@ class StringTools
{
public static function createUUID()
{
if (function_exists("com_create_guid") === true) {
return trim(com_create_guid(), "{}");
if (function_exists('com_create_guid') === true) {
return trim(com_create_guid(), '{}');
}
return sprintf(
"%04X%04X-%04X-%04X-%04X-%04X%04X%04X",
'%04X%04X-%04X-%04X-%04X-%04X%04X%04X',
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535),
@ -26,17 +26,16 @@ class StringTools
mt_rand(0, 65535)
);
}
public static function sanitizeContent($entry)
{
$parser = new Parser();
$rendered = $parser->parse($entry);
$sanitizer = HtmlSanitizer\Sanitizer::create([
"extensions" => ["basic", "image", "list", "code"],
"tags" => [
"img" => [
"allowed_attributes" => ["src", "alt", "title", "class"],
"allowed_hosts" => null,
'extensions' => ['basic', 'image', 'list', 'code'],
'tags' => [
'img' => [
'allowed_attributes' => ['src', 'alt', 'title', 'class'],
'allowed_hosts' => null,
],
],
]);
@ -44,57 +43,54 @@ class StringTools
$preclean = $sanitizer->sanitize($rendered->getContent());
$cleaned = strip_tags($rendered->getContent(), [
"a",
"br",
"p",
"strong",
"br",
"img",
"iframe",
"ul",
"li",
"i",
"h1",
"h2",
"h3",
"pre",
"code",
'a',
'br',
'p',
'strong',
'br',
'img',
'iframe',
'ul',
'li',
'i',
'h1',
'h2',
'h3',
'pre',
'code',
]);
return $cleaned;
}
public static function safeString($string)
{
return strtolower(
trim(
preg_replace(
"~[^0-9a-z]+~i",
"_",
'~[^0-9a-z]+~i',
'_',
html_entity_decode(
preg_replace(
"~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i",
'~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i',
'$1',
htmlentities($string, ENT_QUOTES, "UTF-8")
htmlentities($string, ENT_QUOTES, 'UTF-8')
),
ENT_QUOTES,
"UTF-8"
'UTF-8'
)
),
"-"
'-'
)
);
}
public static function randomString(int $length)
{
$alphanum =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
$alphanum = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$special = '*&!@%^#$';
$alphabet = $alphanum . $special;
$random = openssl_random_pseudo_bytes($length);
$alphabet_length = strlen($alphabet);
$string = "";
$string = '';
for ($i = 0; $i < $length; ++$i) {
$string .= $alphabet[ord($random[$i]) % $alphabet_length];
}
@ -102,7 +98,7 @@ class StringTools
//secret needs to be a valid token
if ($length == 12) {
try {
$secret = Token::create(12, $string, time() + 3600, "localhost");
$secret = Token::create(12, $string, time() + 3600, 'localhost');
return $string;
} catch (BuildException $e) {
//bad secret, so try agiain
@ -117,10 +113,9 @@ class StringTools
}
}
}
private static function checkSpecial($string)
{
$specials = ["*", "&", "!", "@", "%", "^", "#", "$"];
$specials = ['*', '&', '!', '@', '%', '^', '#', '$'];
$valid = false;
foreach ($specials as $item) {
if (strpos($string, $item)) {

@ -172,5 +172,5 @@
{% endblock %}
{% block javascripts %}
<script src="/assets/scripts/Start.js?=tyuo" type="text/javascript"></script>
<script src="/assets/scripts/Start.js?=wryui" type="text/javascript"></script>
{% endblock %}

@ -1798,10 +1798,10 @@ class PostActions {
pageInfo.append('layout', document.getElementById('post-edit-index').getAttribute('data-layout'));
pageInfo.append('current_title', document.getElementById('post-edit-index').getAttribute('data-slug'));
pageInfo.append('content', html);
pageInfo.append('title', document.getElementById('post_title').value);
pageInfo.append('title', document.getElementById('post-title-text').value);
pageInfo.append('created', document.getElementById('post-date').getAttribute('data-raw'));
pageInfo.append('slug', new _stringUtilsDefault.default().cleanString(document.getElementById('post_title').value));
pageInfo.append('tags', document.getElementById('post_tags').value);
pageInfo.append('slug', new _stringUtilsDefault.default().cleanString(document.getElementById('post-title-text').value));
pageInfo.append('tags', document.getElementById('post-tags').value);
pageInfo.append('menu', document.getElementById('option-menu-pin').getAttribute('data-active'));
pageInfo.append('featured', document.getElementById('option-feature').getAttribute('data-active'));
pageInfo.append('published', document.getElementById('option-published').getAttribute('data-active'));

@ -32,16 +32,18 @@ export default class PostActions {
document.getElementById('post-edit-index').getAttribute('data-slug')
);
pageInfo.append('content', html);
pageInfo.append('title', document.getElementById('post_title').value);
pageInfo.append('title', document.getElementById('post-title-text').value);
pageInfo.append(
'created',
document.getElementById('post-date').getAttribute('data-raw')
);
pageInfo.append(
'slug',
new StringUtils().cleanString(document.getElementById('post_title').value)
new StringUtils().cleanString(
document.getElementById('post-title-text').value
)
);
pageInfo.append('tags', document.getElementById('post_tags').value);
pageInfo.append('tags', document.getElementById('post-tags').value);
pageInfo.append(
'menu',
document.getElementById('option-menu-pin').getAttribute('data-active')

Loading…
Cancel
Save