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.
This commit is contained in:
Are0h 2022-05-16 17:41:15 -07:00
parent d9c9f7744e
commit 63eaba08e2
31 changed files with 1249 additions and 1294 deletions

71
.php-cs-fixer.php Normal file
View file

@ -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");

View file

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

View file

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

View file

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

View file

@ -10,7 +10,6 @@ class MailerAPI
public function __construct() public function __construct()
{ {
} }
public static function handleMail($request, $body, $response) public static function handleMail($request, $body, $response)
{ {
// if testing, verify session is active // if testing, verify session is active
@ -20,8 +19,8 @@ class MailerAPI
$result = Mailer::sendmail($body); $result = Mailer::sendmail($body);
} else { } else {
$result = [ $result = [
'message' => 'You need to be logged in for this, champ.', 'message' => 'You need to be logged in for this, champ.',
'type' => 'MAILER_ERROR', 'type' => 'MAILER_ERROR',
]; ];
} }
} else { } else {

View file

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

View file

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

View file

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

View file

@ -18,44 +18,44 @@ class DashControl
ResponseInterface $response, ResponseInterface $response,
array $args array $args
): ResponseInterface { ): ResponseInterface {
$view = Twig::fromRequest($request); $view = Twig::fromRequest($request);
$pageOptions = []; $pageOptions = [];
$template = ''; $template = '';
if (Setup::status()) { if (Setup::status()) {
switch (isset($args['second']) ? $args['second'] : 'index') { switch (isset($args['second']) ? $args['second'] : 'index') {
case 'settings': case 'settings':
if (Session::active()) { if (Session::active()) {
$config = new Settings(); $config = new Settings();
$settings = $config->getSettings(); $settings = $config->getSettings();
$themes = (new Themes())->getThemes(); // $config->getThemes(); $themes = (new Themes())->getThemes(); // $config->getThemes();
$template = 'dash/settings.twig'; $template = 'dash/settings.twig';
$member = Session::get('member'); $member = Session::get('member');
$form_token = Session::get('form_token'); $form_token = Session::get('form_token');
$updated = new \Moment\Moment($settings['global']['last_backup']); $updated = new \Moment\Moment($settings['global']['last_backup']);
$pageOptions = [ $pageOptions = [
'title' => 'Dash Settings', 'title' => 'Dash Settings',
'private' => $settings['global']['private'], 'private' => $settings['global']['private'],
'renderOnSave' => $settings['global']['renderOnSave'], 'renderOnSave' => $settings['global']['renderOnSave'],
'background' => $settings['global']['background'], 'background' => $settings['global']['background'],
'member' => $member, 'member' => $member,
'ftoken' => $form_token, 'ftoken' => $form_token,
'siteTitle' => $settings['global']['title'], 'siteTitle' => $settings['global']['title'],
'baseUrl' => $settings['global']['base_url'], 'baseUrl' => $settings['global']['base_url'],
'desc' => $settings['global']['descriptions'], 'desc' => $settings['global']['descriptions'],
'lastBackup' => $updated->format('Y M D d'), 'lastBackup' => $updated->format('Y M D d'),
'currentTheme' => $settings['global']['theme'], 'currentTheme' => $settings['global']['theme'],
'themes' => $themes, 'themes' => $themes,
'apiStatus' => isset($settings['global']['externalAPI']) 'apiStatus' => isset($settings['global']['externalAPI'])
? $settings['global']['externalAPI'] ? $settings['global']['externalAPI']
: 'false', : 'false',
'dynamicRenderStatus' => isset( 'dynamicRenderStatus' => isset(
$settings['global']['dynamicRender'] $settings['global']['dynamicRender']
) )
? $settings['global']['dynamicRender'] ? $settings['global']['dynamicRender']
: 'false', : 'false',
'mailOption' => $settings['email']['active'], 'mailOption' => $settings['email']['active'],
'mailConfig' => $settings['email'], 'mailConfig' => $settings['email'],
'status' => Session::active(), 'status' => Session::active(),
]; ];
} else { } else {
header('Location: /dashboard'); header('Location: /dashboard');
@ -65,13 +65,13 @@ class DashControl
break; break;
case 'navigation': case 'navigation':
if (Session::active()) { if (Session::active()) {
$config = new Settings(); $config = new Settings();
$settings = $config->getSettings(); $settings = $config->getSettings();
$template = 'dash/navigation.twig'; $template = 'dash/navigation.twig';
$pageOptions = [ $pageOptions = [
'title' => 'Edit Dash Navigation', 'title' => 'Edit Dash Navigation',
'status' => Session::active(), 'status' => Session::active(),
'menu' => $settings['menu'], 'menu' => $settings['menu'],
]; ];
} else { } else {
header('Location: /dashboard'); header('Location: /dashboard');
@ -81,19 +81,19 @@ class DashControl
case 'pages': case 'pages':
if (Session::active()) { if (Session::active()) {
$currentPage = isset($args['fourth']) ? $args['fourth'] : 1; $currentPage = isset($args['fourth']) ? $args['fourth'] : 1;
$filter = isset($args['third']) ? $args['third'] : 'all'; $filter = isset($args['third']) ? $args['third'] : 'all';
$data = (new Book())->getPages($currentPage, 4, $filter); $data = (new Book())->getPages($currentPage, 4, $filter);
$template = 'dash/book.twig'; $template = 'dash/book.twig';
$pageOptions = [ $pageOptions = [
'title' => 'Contents', 'title' => 'Contents',
'entryCount' => $data['entryCount'], 'entryCount' => $data['entryCount'],
'numOfPages' => $data['numOfPages'], 'numOfPages' => $data['numOfPages'],
'currentPage' => $currentPage, 'currentPage' => $currentPage,
'filter' => $data['paginate']['sort'], 'filter' => $data['paginate']['sort'],
'stats' => $data['stats'], 'stats' => $data['stats'],
'pages' => $data['pages'], 'pages' => $data['pages'],
'paginate' => $data['paginate'], 'paginate' => $data['paginate'],
'status' => Session::active(), 'status' => Session::active(),
]; ];
} else { } else {
header('Location: /dashboard'); header('Location: /dashboard');
@ -103,12 +103,12 @@ class DashControl
case 'page': case 'page':
if (Session::active()) { if (Session::active()) {
$template = 'dash/page-edit.twig'; $template = 'dash/page-edit.twig';
$mode = $args['third']; $mode = $args['third'];
$uuid = $args['fourth']; $uuid = $args['fourth'];
switch ($mode) { switch ($mode) {
case 'edit': case 'edit':
$page = (new Book())->findPageById($uuid); $page = (new Book())->findPageById($uuid);
$views = []; $views = [];
if (str_contains($page['layout'], 'index')) { if (str_contains($page['layout'], 'index')) {
$views = (new Themes())->getCustomIndex(); $views = (new Themes())->getCustomIndex();
@ -117,10 +117,10 @@ class DashControl
} }
$imageList = explode(',', $page['feature']); $imageList = explode(',', $page['feature']);
$fileList = explode(',', $page['files']); $fileList = explode(',', $page['files']);
$images = []; $images = [];
$files = []; $files = [];
foreach ($imageList as $item) { foreach ($imageList as $item) {
$image = trim($item); $image = trim($item);
if (!empty($image)) { if (!empty($image)) {
@ -136,29 +136,28 @@ class DashControl
} }
$pageOptions = [ $pageOptions = [
'title' => 'Fipamo | Edit Page', 'title' => 'Fipamo | Edit Page',
'page' => $page, 'page' => $page,
'mode' => $mode, 'mode' => $mode,
'token' => Session::get('form_token'), 'token' => Session::get('form_token'),
'status' => Session::active(), 'status' => Session::active(),
'images' => $images, 'images' => $images,
'files' => $files, 'files' => $files,
'views' => $views, 'views' => $views,
]; ];
break; break;
case 'preview': case 'preview':
$config = new Settings(); $config = new Settings();
$settings = $config->getSettings(); $settings = $config->getSettings();
$loader = new \Twig\Loader\FilesystemLoader( $loader = new \Twig\Loader\FilesystemLoader(
'../content/themes' '../content/themes'
); );
$display = new \Twig\Environment($loader, []); $display = new \Twig\Environment($loader, []);
$book = new Book(); $book = new Book();
$page = $book->findPageById($uuid); $page = $book->findPageById($uuid);
$pageOptions = Sorting::page($page); $pageOptions = Sorting::page($page);
$preview = $preview = $settings['global']['theme'] .
$settings['global']['theme'] .
'/' . '/' .
$page['layout'] . $page['layout'] .
'.twig'; '.twig';
@ -169,10 +168,10 @@ class DashControl
break; break;
default: default:
$pageOptions = [ $pageOptions = [
'title' => 'Fipamo | Create Page', 'title' => 'Fipamo | Create Page',
'token' => Session::get('form_token'), 'token' => Session::get('form_token'),
'mode' => $mode, 'mode' => $mode,
'status' => Session::active(), 'status' => Session::active(),
]; ];
break; break;
} }
@ -187,29 +186,29 @@ class DashControl
exit(); exit();
break; break;
case 'reset-password': case 'reset-password':
$template = 'dash/reset-password.twig'; $template = 'dash/reset-password.twig';
$pageOptions = [ $pageOptions = [
'title' => 'Reset Password', 'title' => 'Reset Password',
]; ];
break; break;
default: default:
$template = 'dash/start.twig'; $template = 'dash/start.twig';
if (Session::active()) { if (Session::active()) {
$pageOptions = [ $pageOptions = [
'title' => 'Welcome Back', 'title' => 'Welcome Back',
'status' => Session::active(), 'status' => Session::active(),
'data' => (new Book())->getPages(1, 4), 'data' => (new Book())->getPages(1, 4),
]; ];
} else { } else {
$pageOptions = [ $pageOptions = [
'title' => 'Welcome to Fipamo', 'title' => 'Welcome to Fipamo',
'status' => Session::active(), 'status' => Session::active(),
]; ];
} }
break; break;
} }
} else { } else {
$template = 'dash/init.twig'; $template = 'dash/init.twig';
$pageOptions = ['title' => 'Fipamo Setup']; $pageOptions = ['title' => 'Fipamo Setup'];
} }

View file

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

View file

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

View file

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

View file

@ -2,26 +2,24 @@
namespace brain\data; namespace brain\data;
use function _\filter;
use function _\find;
use brain\utility\DocTools; use brain\utility\DocTools;
use brain\utility\FileUploader;
use brain\utility\StringTools; use brain\utility\StringTools;
use brain\utility\FileUploader;
use function _\find;
use function _\filter;
class Book class Book
{ {
public function __construct() public function __construct()
{ {
} }
public function findPageById(string $uuid) public function findPageById(string $uuid)
{ {
$content = $this->getContents(); $content = $this->getContents();
$page = find($content, ['uuid' => $uuid]); $page = find($content, ['uuid' => $uuid]);
return $page; return $page;
} }
public function findPageBySlug(string $slug = null) public function findPageBySlug(string $slug = null)
{ {
$content = $this->getContents(); $content = $this->getContents();
@ -33,7 +31,6 @@ class Book
return $page; return $page;
} }
public function editPage($task, $request) public function editPage($task, $request)
{ {
$content = $this->getContents(); $content = $this->getContents();
@ -45,26 +42,25 @@ class Book
$body = $request->getParsedBody(); $body = $request->getParsedBody();
} }
$page = find($content, ['uuid' => $body['uuid']]); $page = find($content, ['uuid' => $body['uuid']]);
$files = $request->getUploadedFiles(); $files = $request->getUploadedFiles();
$member = Session::get('member'); $member = Session::get('member');
if ($task != 'create') { if ($task != 'create') {
$path = $path = date('Y', date($page['rawCreated'])) .
date('Y', date($page['rawCreated'])). '/' .
'/'.
date('m', date($page['rawCreated'])); date('m', date($page['rawCreated']));
} else { } else {
$path = date('Y').'/'.date('m'); $path = date('Y') . '/' . date('m');
} }
$page_feature = ''; $page_feature = '';
$page_files = ''; $page_files = '';
if (isset($files['page_files'])) { if (isset($files['page_files'])) {
$imageList = ''; $imageList = '';
$fileList = ''; $fileList = '';
// var_dump($files["page_files"] ); // var_dump($files["page_files"] );
foreach ($files['page_files'] as $file) { foreach ($files['page_files'] as $file) {
$type = $file->getClientMediaType(); $type = $file->getClientMediaType();
@ -73,81 +69,78 @@ class Book
case 'image/png': case 'image/png':
case 'image/gif': case 'image/gif':
case 'image/svg': case 'image/svg':
$imagesPath = '/assets/images/blog/'.$path.'/'; $imagesPath = '/assets/images/blog/' . $path . '/';
$imageList = $imageList = $imageList . $imagesPath . urlencode($file->getClientFileName()) . ', ';
$imageList.$imagesPath.urlencode($file->getClientFileName()).', ';
FileUploader::uploadFile( FileUploader::uploadFile(
'../public/assets/images/blog/'.$path.'/', '../public/assets/images/blog/' . $path . '/',
$file $file
); );
break; break;
case 'video/mp4': case 'video/mp4':
$videosPath = '/assets/video/blog/'.$path.'/'; $videosPath = '/assets/video/blog/' . $path . '/';
$imageList = $imageList = $imageList . $videosPath . urlencode($file->getClientFileName()) . ', ';
$imageList.$videosPath.urlencode($file->getClientFileName()).', ';
FileUploader::uploadFile( FileUploader::uploadFile(
'../public/assets/video/blog/'.$path.'/', '../public/assets/video/blog/' . $path . '/',
$file $file
); );
break; break;
case 'audio/mpeg': case 'audio/mpeg':
$soundPath = '/assets/sound/blog/'.$path.'/'; $soundPath = '/assets/sound/blog/' . $path . '/';
$fileList = $fileList.$soundPath.urlencode($file->getClientFileName()).', '; $fileList = $fileList . $soundPath . urlencode($file->getClientFileName()) . ', ';
FileUploader::uploadFile( FileUploader::uploadFile(
'../public/assets/sound/blog/'.$path.'/', '../public/assets/sound/blog/' . $path . '/',
$file $file
); );
break; break;
case 'application/pdf': case 'application/pdf':
case 'text/plain': case 'text/plain':
case 'text/rtf': case 'text/rtf':
$docPath = '/assets/docs/blog/'.$path.'/'; $docPath = '/assets/docs/blog/' . $path . '/';
$fileList = $fileList.$docPath.urlencode($file->getClientFileName()).', '; $fileList = $fileList . $docPath . urlencode($file->getClientFileName()) . ', ';
FileUploader::uploadFile( FileUploader::uploadFile(
'../public/assets/docs/blog/'.$path.'/', '../public/assets/docs/blog/' . $path . '/',
$file $file
); );
break; break;
} }
} }
$page_feature = $imageList; $page_feature = $imageList;
$page_files = $fileList; $page_files = $fileList;
} else { } else {
// if no files, just reset string from page object // if no files, just reset string from page object
$page_feature = $page['feature']; $page_feature = $page['feature'];
$page_files = $page['files']; $page_files = $page['files'];
} }
if ($task == 'delete') { if ($task == 'delete') {
$deleted = 'true'; $deleted = 'true';
$body['menu'] = 'false'; $body['menu'] = 'false';
$body['published'] = 'false'; $body['published'] = 'false';
$body['featured'] = 'false'; $body['featured'] = 'false';
} else { } else {
$deleted = isset($page['deleted']) ? $page['deleted'] : 'false'; $deleted = isset($page['deleted']) ? $page['deleted'] : 'false';
} }
$created = $created = $task != 'create'
$task != 'create'
? new \Moment\Moment($page['rawCreated']) ? new \Moment\Moment($page['rawCreated'])
: new \Moment\Moment(); : new \Moment\Moment();
$updated = new \Moment\Moment(); $updated = new \Moment\Moment();
// grab current index from settings and update // grab current index from settings and update
$id = $task != 'create' ? $body['id'] : Settings::getCurrentIndex(); $id = $task != 'create' ? $body['id'] : Settings::getCurrentIndex();
$uuid = $task != 'create' ? $body['uuid'] : StringTools::createUUID(); $uuid = $task != 'create' ? $body['uuid'] : StringTools::createUUID();
// now that variables are done, set to body object and then convert to markdown to save // now that variables are done, set to body object and then convert to markdown to save
$body['id'] = $id; $body['id'] = $id;
$body['uuid'] = $uuid; $body['uuid'] = $uuid;
$body['feature'] = $page_feature; $body['feature'] = $page_feature;
$body['files'] = $page_files; $body['files'] = $page_files;
$body['path'] = $path; $body['path'] = $path;
$body['author'] = $member['handle']; $body['author'] = $member['handle'];
$body['created'] = $created->format("Y-m-d\TH:i:sP"); $body['created'] = $created->format("Y-m-d\TH:i:sP");
$body['updated'] = $updated->format("Y-m-d\TH:i:sP"); $body['updated'] = $updated->format("Y-m-d\TH:i:sP");
$body['deleted'] = $deleted; $body['deleted'] = $deleted;
@ -159,15 +152,15 @@ class Book
if ($body['layout'] == 'index') { if ($body['layout'] == 'index') {
$writePath = '../content/pages/start/index.md'; $writePath = '../content/pages/start/index.md';
} else { } else {
$writePath = '../content/pages/'.$path.'/'.$body['slug'].'.md'; $writePath = '../content/pages/' . $path . '/' . $body['slug'] . '.md';
} }
$status = DocTools::writePages($task, $path, $writePath, $write); $status = DocTools::writePages($task, $path, $writePath, $write);
if ($status) { if ($status) {
$config = new Settings(); $config = new Settings();
$settings = $config->getSettings(); $settings = $config->getSettings();
$message = ''; $message = '';
if ( if (
$settings['global']['renderOnSave'] == 'true' && $settings['global']['renderOnSave'] == 'true' &&
@ -183,9 +176,9 @@ class Book
} }
$response = [ $response = [
'message' => $message, 'message' => $message,
'type' => $task == 'write' ? 'postUpdated' : 'postAdded', 'type' => $task == 'write' ? 'postUpdated' : 'postAdded',
'id' => $uuid, 'id' => $uuid,
]; ];
// TODO: When form submission is successful, make new form token // TODO: When form submission is successful, make new form token
@ -203,15 +196,14 @@ class Book
} }
} else { } else {
$response = [ $response = [
'message' => "Uh oh. File save problem. Don't panic", 'message' => "Uh oh. File save problem. Don't panic",
'type' => 'postError', 'type' => 'postError',
'id' => $uuid, 'id' => $uuid,
]; ];
} }
return $response; return $response;
} }
public function getPages(int $page, int $limit, string $sort = null) public function getPages(int $page, int $limit, string $sort = null)
{ {
$content = $this->getContents(); $content = $this->getContents();
@ -240,7 +232,7 @@ class Book
break; break;
} }
$numOfPages = ceil(count($filtered) / ($limit + 1)); $numOfPages = ceil(count($filtered) / ($limit + 1));
$folder = []; $folder = [];
if (count($filtered) != 0) { if (count($filtered) != 0) {
if (count($filtered) < $limit) { if (count($filtered) < $limit) {
@ -271,22 +263,21 @@ class Book
} }
return [ return [
'pages' => $folder, 'pages' => $folder,
'numOfPages' => $numOfPages, 'numOfPages' => $numOfPages,
'entryCount' => count($filtered), 'entryCount' => count($filtered),
'paginate' => [ 'paginate' => [
'sort' => $sort, 'sort' => $sort,
'nextPage' => $next, 'nextPage' => $next,
'prevPage' => $prev, 'prevPage' => $prev,
], ],
'stats' => [ 'stats' => [
'all' => count($all), 'all' => count($all),
'published' => count($published), 'published' => count($published),
'deleted' => count($deleted), 'deleted' => count($deleted),
], ],
]; ];
} }
public function getContents() public function getContents()
{ {
// test new contents data class // test new contents data class

View file

@ -2,25 +2,24 @@
namespace brain\data; namespace brain\data;
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\FrontMatter\FrontMatterExtension;
use League\CommonMark\Extension\FrontMatter\Output\RenderedContentWithFrontMatter;
use League\CommonMark\MarkdownConverter;
use League\CommonMark\CommonMarkConverter;
use HtmlSanitizer\Extension\Basic\BasicExtension; use HtmlSanitizer\Extension\Basic\BasicExtension;
use HtmlSanitizer\Extension\Iframe\IframeExtension; use HtmlSanitizer\Extension\Iframe\IframeExtension;
use HtmlSanitizer\Extension\Listing\ListExtension; use HtmlSanitizer\Extension\Listing\ListExtension;
use HtmlSanitizer\SanitizerBuilder; use HtmlSanitizer\SanitizerBuilder;
use League\CommonMark\Environment\Environment;
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 function _\orderBy; use function _\orderBy;
class Contents class Contents
{ {
public $files = []; public $files = [];
public $config = []; public $config = [];
public function __construct($folder) public function __construct($folder)
{ {
$this->read($folder); $this->read($folder);
@ -32,12 +31,11 @@ class Contents
//$this->files[] = $folder . "/"; //$this->files[] = $folder . "/";
$this->read($folder); $this->read($folder);
} }
$files = array_filter(glob("$folder/*md"), "is_file"); $files = array_filter(glob("$folder/*md"), 'is_file');
foreach ($files as $file) { foreach ($files as $file) {
$this->files[] = $file; $this->files[] = $file;
} }
} }
public function getAll() public function getAll()
{ {
$environment = new Environment($this->config); $environment = new Environment($this->config);
@ -59,16 +57,16 @@ class Contents
foreach ($this->files as $file) { foreach ($this->files as $file) {
//get meta and html from file //get meta and html from file
$result = $converter->convertToHtml(file_get_contents($file)); $result = $converter->convertToHtml(file_get_contents($file));
$meta = []; $meta = [];
if ($result instanceof RenderedContentWithFrontMatter) { if ($result instanceof RenderedContentWithFrontMatter) {
$meta = $result->getFrontMatter(); $meta = $result->getFrontMatter();
} }
//get raw markdown from file //get raw markdown from file
$frontMatterExtension = new FrontMatterExtension(); $frontMatterExtension = new FrontMatterExtension();
$parsed = $frontMatterExtension $parsed = $frontMatterExtension
->getFrontMatterParser() ->getFrontMatterParser()
->parse(file_get_contents($file)); ->parse(file_get_contents($file));
//never trust the front end. clean it up //never trust the front end. clean it up
//add what sanitizer extensions we need manually //add what sanitizer extensions we need manually
@ -86,84 +84,84 @@ class Contents
); );
$detergent = [ $detergent = [
"extensions" => ["basic", "list","relative-a", "relative-image", "iframe"], 'extensions' => ['basic', 'list', 'relative-a', 'relative-image', 'iframe'],
"tags" => [ 'tags' => [
"div" => [ 'div' => [
"allowed_attributes" => ["class", "title", "id", "style"], 'allowed_attributes' => ['class', 'title', 'id', 'style'],
], ],
"img" => [ 'img' => [
"allowed_attributes" => ["src", "alt", "title", "class"], 'allowed_attributes' => ['src', 'alt', 'title', 'class'],
], ],
"iframe" => [ 'iframe' => [
"allowed_attributes" => ["height", "width", "title", "src"], 'allowed_attributes' => ['height', 'width', 'title', 'src'],
], ],
], ],
]; ];
$sanitizer = $builder->build($detergent); $sanitizer = $builder->build($detergent);
$scrubbed = $sanitizer->sanitize($result->getContent()); $scrubbed = $sanitizer->sanitize($result->getContent());
$featureList = explode(",", $meta["feature"]); $featureList = explode(',', $meta['feature']);
$docs = ''; $docs = '';
if (isset($meta["files"])) { if (isset($meta['files'])) {
$fileList = explode(",", $meta["files"]); $fileList = explode(',', $meta['files']);
$docs = $meta["files"]; $docs = $meta['files'];
} else { } else {
$fileList = []; $fileList = [];
$docs = ''; $docs = '';
} }
$media = []; $media = [];
$files = []; $files = [];
foreach ($featureList as $file) { foreach ($featureList as $file) {
$item = trim($file); $item = trim($file);
$ext = pathinfo($item, PATHINFO_EXTENSION); $ext = pathinfo($item, PATHINFO_EXTENSION);
if ($item != null || $item != "") { if ($item != null || $item != '') {
array_push($media, ["file" => $item, "type" => trim($ext)]); array_push($media, ['file' => $item, 'type' => trim($ext)]);
} }
} }
foreach ($fileList as $file) { foreach ($fileList as $file) {
$item = trim($file); $item = trim($file);
$ext = pathinfo($item, PATHINFO_EXTENSION); $ext = pathinfo($item, PATHINFO_EXTENSION);
if ($item != null || $item != "") { if ($item != null || $item != '') {
array_push($files, ["file" => $item, "type" => trim($ext)]); array_push($files, ['file' => $item, 'type' => trim($ext)]);
} }
} }
//sort attributes into page object //sort attributes into page object
$page = [ $page = [
"id" => $meta["id"], 'id' => $meta['id'],
"uuid" => $meta["uuid"], 'uuid' => $meta['uuid'],
"title" => $meta["title"], 'title' => $meta['title'],
"feature" => $meta["feature"], 'feature' => $meta['feature'],
"files" => $docs, 'files' => $docs,
"path" => $meta["path"], 'path' => $meta['path'],
"layout" => $meta["layout"], 'layout' => $meta['layout'],
"tags" => $meta["tags"], 'tags' => $meta['tags'],
"author" => $meta["author"], 'author' => $meta['author'],
"created" => date("Y M D d", $meta["created"]), 'created' => date('Y M D d', $meta['created']),
"updated" => date("Y M D d", $meta["updated"]), 'updated' => date('Y M D d', $meta['updated']),
"rawCreated" => $meta["created"], 'rawCreated' => $meta['created'],
"rawUpdated" => $meta["updated"], 'rawUpdated' => $meta['updated'],
"createdYear" => date("Y", $meta["created"]), 'createdYear' => date('Y', $meta['created']),
"createdMonth" => date("m", $meta["created"]), 'createdMonth' => date('m', $meta['created']),
"deleted" => $meta["deleted"], 'deleted' => $meta['deleted'],
"menu" => $meta["menu"], 'menu' => $meta['menu'],
"featured" => $meta["featured"], 'featured' => $meta['featured'],
"published" => $meta["published"], 'published' => $meta['published'],
"slug" => $meta["slug"], 'slug' => $meta['slug'],
"filePath" => $file, 'filePath' => $file,
"content" => $parsed->getContent(), 'content' => $parsed->getContent(),
"html" => $scrubbed, 'html' => $scrubbed,
"media" => $media, 'media' => $media,
"docs" => $files 'docs' => $files
]; ];
//checks for duplicates //checks for duplicates
$uuid = $meta["uuid"]; $uuid = $meta['uuid'];
$found = current( $found = current(
array_filter($contents, function ($item) use ($uuid) { 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); array_push($contents, $page);
} }
} }
$contents = orderBy($contents, ["id"], ["desc"]); $contents = orderBy($contents, ['id'], ['desc']);
return $contents; return $contents;
} }
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -14,7 +14,7 @@ class App
// when a new class is made, run composer dump-autoload // when a new class is made, run composer dump-autoload
// set up cors // set up cors
new HandleCors(); new HandleCors();
$app = AppFactory::create(); $app = AppFactory::create();
$twig = Twig::create('../brain/views/'); $twig = Twig::create('../brain/views/');
$app->add(TwigMiddleware::create($app, $twig)); $app->add(TwigMiddleware::create($app, $twig));
// set up routing // set up routing

View file

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

View file

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

View file

@ -9,37 +9,38 @@ class HandleCors
public function __construct() public function __construct()
{ {
//look to see if settings file exists. kinda important //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 //check settings to see if external api access is allowed
$config = new Settings(); $config = new Settings();
$settings = $config->getSettings(); $settings = $config->getSettings();
if ($settings["global"]["externalAPI"]) { if ($settings['global']['externalAPI']) {
//echo "API STATUS: " . $settings["global"]["externalAPI"]; //echo "API STATUS: " . $settings["global"]["externalAPI"];
if ($settings["global"]["externalAPI"] == "true") { if ($settings['global']['externalAPI'] == 'true') {
//echo "API ACCESS ACTIVE"; //echo "API ACCESS ACTIVE";
// checks to see if origin is set // checks to see if origin is set
if (isset($_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 // You can decide if the origin in $_SERVER['HTTP_ORIGIN']
header("Access-Control-Allow-Origin: {$_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 { } else {
//No HTTP_ORIGIN set, so we allow any. You can disallow if needed here //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 //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-Origin: *");
} }
header("Access-Control-Allow-Credentials: true"); header('Access-Control-Allow-Credentials: true');
header("Access-Control-Max-Age: 600"); // cache for 10 minutes header('Access-Control-Max-Age: 600'); // cache for 10 minutes
if ($_SERVER["REQUEST_METHOD"] == "OPTIONS") { if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"])) { if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
header( 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 } //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( header(
"Access-Control-Allow-Headers: {$_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]}" "Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"
); );
} }

View file

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

View file

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

View file

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

View file

@ -10,13 +10,12 @@ use Mni\FrontYAML\Parser;
class Sorting class Sorting
{ {
private static $_tags = []; private static $_tags = [];
private static $_archive = []; private static $_archive = [];
public function __construct() public function __construct()
{ {
} }
public static function tags() public static function tags()
{ {
$pages = (new Book('../content/pages'))->getContents(); $pages = (new Book('../content/pages'))->getContents();
@ -27,9 +26,9 @@ class Sorting
$label = trim($tag); $label = trim($tag);
if (!find(self::$_tags, ['tag_name' => $label])) { if (!find(self::$_tags, ['tag_name' => $label])) {
array_push(self::$_tags, [ array_push(self::$_tags, [
'tag_name' => $label, 'tag_name' => $label,
'slug' => StringTools::safeString($label), 'slug' => StringTools::safeString($label),
'pages' => self::tagPages($label, $pages), 'pages' => self::tagPages($label, $pages),
]); ]);
} }
} }
@ -37,28 +36,26 @@ class Sorting
return self::$_tags; return self::$_tags;
} }
private static function tagPages($tag, $pages) private static function tagPages($tag, $pages)
{ {
$tagged = []; $tagged = [];
foreach ($pages as $page) { foreach ($pages as $page) {
if (strpos($page['tags'], $tag) !== false) { if (strpos($page['tags'], $tag) !== false) {
array_push($tagged, [ array_push($tagged, [
'title' => $page['title'], 'title' => $page['title'],
'slug' => $page['slug'], 'slug' => $page['slug'],
'path' => $page['path'], 'path' => $page['path'],
'feature' => $page['feature'], 'feature' => $page['feature'],
]); ]);
} }
} }
return $tagged; return $tagged;
} }
public static function archive() public static function archive()
{ {
$pages = (new Book('../content/pages'))->getContents(); $pages = (new Book('../content/pages'))->getContents();
$years = []; $years = [];
$archive = []; $archive = [];
foreach ($pages as $page) { foreach ($pages as $page) {
// $year = date("Y", date($page["rawCreated"])); // $year = date("Y", date($page["rawCreated"]));
@ -68,81 +65,80 @@ class Sorting
$findPages = filter($pages, ['createdYear' => trim($date[0])]); $findPages = filter($pages, ['createdYear' => trim($date[0])]);
// var_dump($findPages); // var_dump($findPages);
array_push($years, [ array_push($years, [
'year' => trim($date[0]), 'year' => trim($date[0]),
'count' => count($findPages), 'count' => count($findPages),
]); ]);
} }
} }
foreach ($years as $year) { foreach ($years as $year) {
$sorted = []; $sorted = [];
$filtered = filter($pages, ['createdYear' => $year['year']]); $filtered = filter($pages, ['createdYear' => $year['year']]);
foreach ($filtered as $obj) { foreach ($filtered as $obj) {
$month = date('m', date($obj['rawCreated'])); $month = date('m', date($obj['rawCreated']));
if (!find($sorted, ['month' => $month])) { if (!find($sorted, ['month' => $month])) {
$perMonth = filter($pages, [ $perMonth = filter($pages, [
'path' => $year['year'].'/'.$month, 'path' => $year['year'] . '/' . $month,
'deleted' => false, 'deleted' => false,
'published' => true, 'published' => true,
'layout' => 'page', 'layout' => 'page',
]); ]);
array_push($sorted, [ array_push($sorted, [
'month' => $month, 'month' => $month,
'full_month' => date('F', date($obj['rawCreated'])), 'full_month' => date('F', date($obj['rawCreated'])),
'count' => count($perMonth), 'count' => count($perMonth),
'pages' => $perMonth, 'pages' => $perMonth,
]); ]);
} }
} }
array_push(self::$_archive, [ array_push(self::$_archive, [
'year' => $year['year'], 'year' => $year['year'],
'year_data' => $sorted, 'year_data' => $sorted,
]); ]);
} }
return self::$_archive; return self::$_archive;
} }
public static function page($page) public static function page($page)
{ {
$config = new Settings(); $config = new Settings();
$settings = $config->getSettings(); $settings = $config->getSettings();
$pageOption = []; $pageOption = [];
$pageInfo = [ $pageInfo = [
'keywords' => isset($settings['global']['keywords']) 'keywords' => isset($settings['global']['keywords'])
? $settings['global']['keywords'] ? $settings['global']['keywords']
: 'fipamo, blog, jamstack, php, markdown, js', : 'fipamo, blog, jamstack, php, markdown, js',
'description' => $settings['global']['descriptions'], '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'], 'baseURL' => $settings['global']['base_url'],
]; ];
$taglist = explode(',', $page['tags']); $taglist = explode(',', $page['tags']);
$tags = []; $tags = [];
foreach ($taglist as $tag) { foreach ($taglist as $tag) {
$label = trim($tag); $label = trim($tag);
array_push($tags, [ array_push($tags, [
'label' => $label.' ', 'label' => $label . ' ',
'slug' => StringTools::safeString($label), 'slug' => StringTools::safeString($label),
]); ]);
} }
$meta = [ $meta = [
'who' => $page['author'], 'who' => $page['author'],
'when' => $page['created'], 'when' => $page['created'],
'tags' => $tags, 'tags' => $tags,
]; ];
// render markdown content and clean it // render markdown content and clean it
$parser = new Parser(); $parser = new Parser();
$rendered = $parser->parse($page['content']); $rendered = $parser->parse($page['content']);
$sanitizer = \HtmlSanitizer\Sanitizer::create([ $sanitizer = \HtmlSanitizer\Sanitizer::create([
'extensions' => ['basic', 'image', 'list', 'code'], 'extensions' => ['basic', 'image', 'list', 'code'],
'tags' => [ 'tags' => [
'img' => [ 'img' => [
'allowed_attributes' => ['src', 'alt', 'title', 'class'], 'allowed_attributes' => ['src', 'alt', 'title', 'class'],
'allowed_hosts' => null, 'allowed_hosts' => null,
], ],
], ],
]); ]);
@ -152,36 +148,36 @@ class Sorting
// just clean renderd string for now, Sanitize doesn't like relative img urls // just clean renderd string for now, Sanitize doesn't like relative img urls
// so another option is needed // so another option is needed
$cleaned = strip_tags($rendered->getContent(), [ $cleaned = strip_tags($rendered->getContent(), [
'a', 'a',
'br', 'br',
'p', 'p',
'strong', 'strong',
'br', 'br',
'img', 'img',
'iframe', 'iframe',
'ul', 'ul',
'li', 'li',
'i', 'i',
'em', 'em',
'h1', 'h1',
'h2', 'h2',
'h3', 'h3',
'pre', 'pre',
'code', 'code',
]); ]);
// if page feature isn't empty, find image from list and set it as background image // if page feature isn't empty, find image from list and set it as background image
// if it is empty, just use global background // if it is empty, just use global background
if ($page['feature'] != '' || $page['feature'] != null) { if ($page['feature'] != '' || $page['feature'] != null) {
$media = explode(',', $page['feature']); $media = explode(',', $page['feature']);
$set = false; $set = false;
foreach ($media as $file) { foreach ($media as $file) {
$item = trim($file); $item = trim($file);
$ext = pathinfo($item, PATHINFO_EXTENSION); $ext = pathinfo($item, PATHINFO_EXTENSION);
if ($ext != 'mp4' && !$set) { if ($ext != 'mp4' && !$set) {
$pageInfo['image'] = $pageInfo['baseURL'].$item; $pageInfo['image'] = $pageInfo['baseURL'] . $item;
$set = true; $set = true;
} }
} }
} }
@ -191,32 +187,31 @@ class Sorting
// $location = "../public/index.html"; // $location = "../public/index.html";
// $dir = null; // $dir = null;
$recent = []; $recent = [];
$featured = []; $featured = [];
$limit = 4; $limit = 4;
$pages = (new Book())->getContents(); $pages = (new Book())->getContents();
foreach ($pages as $item) { foreach ($pages as $item) {
if ( if (!$item['deleted'] &&
!$item['deleted'] &&
$item['published'] && $item['published'] &&
$item['menu'] != 'true' $item['menu'] != 'true'
) { ) {
if (count($recent) < $limit) { if (count($recent) < $limit) {
array_push($recent, [ array_push($recent, [
'path' => $item['path'], 'path' => $item['path'],
'slug' => $item['slug'], 'slug' => $item['slug'],
'title' => $item['title'], 'title' => $item['title'],
'feature' => $item['feature'], 'feature' => $item['feature'],
]); ]);
} }
if ($item['featured'] == true) { if ($item['featured'] == true) {
if (count($featured) < $limit) { if (count($featured) < $limit) {
array_push($featured, [ array_push($featured, [
'path' => $item['path'], 'path' => $item['path'],
'slug' => $item['slug'], 'slug' => $item['slug'],
'title' => $item['title'], 'title' => $item['title'],
'feature' => $item['feature'], 'feature' => $item['feature'],
]); ]);
} }
} }
@ -224,32 +219,32 @@ class Sorting
} }
$pageOptions = [ $pageOptions = [
'title' => $page['title'], 'title' => $page['title'],
'background' => $page['feature'], 'background' => $page['feature'],
'content' => $page['html'], // $cleaned, 'content' => $page['html'], // $cleaned,
'meta' => $meta, 'meta' => $meta,
'recent' => $recent, 'recent' => $recent,
'featured' => $featured, 'featured' => $featured,
'info' => $pageInfo, 'info' => $pageInfo,
'menu' => $settings['menu'], 'menu' => $settings['menu'],
'dynamicRender' => $settings['global']['dynamicRender'], 'dynamicRender' => $settings['global']['dynamicRender'],
'media' => $page['media'], 'media' => $page['media'],
'files' => $page['docs'], 'files' => $page['docs'],
]; ];
} else { } else {
// $template = $this->theme . "/page.twig"; // $template = $this->theme . "/page.twig";
// $location = "../public/" . $page["path"] . "/" . $page["slug"] . ".html"; // $location = "../public/" . $page["path"] . "/" . $page["slug"] . ".html";
// $dir = "../public/" . $page["path"]; // $dir = "../public/" . $page["path"];
$pageOptions = [ $pageOptions = [
'title' => $page['title'], 'title' => $page['title'],
'background' => $page['feature'], 'background' => $page['feature'],
'content' => $page['html'], // $cleaned, 'content' => $page['html'], // $cleaned,
'meta' => $meta, 'meta' => $meta,
'info' => $pageInfo, 'info' => $pageInfo,
'menu' => $settings['menu'], 'menu' => $settings['menu'],
'dynamicRender' => $settings['global']['dynamicRender'], 'dynamicRender' => $settings['global']['dynamicRender'],
'media' => $page['media'], 'media' => $page['media'],
'files' => $page['docs'], 'files' => $page['docs'],
]; ];
} }

View file

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

View file

@ -172,5 +172,5 @@
{% endblock %} {% endblock %}
{% block javascripts %} {% 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 %} {% endblock %}

View file

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

View file

@ -1,93 +1,95 @@
import StringUtils from '../utils/StringUtils'; import StringUtils from '../utils/StringUtils';
export default class PostActions { export default class PostActions {
//-------------------------- //--------------------------
// constructor // constructor
//-------------------------- //--------------------------
constructor() {} constructor() {}
//-------------------------- //--------------------------
// methods // methods
//-------------------------- //--------------------------
collectInfo(files) { collectInfo(files) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let pageInfo = new FormData(); let pageInfo = new FormData();
let txt = document.createElement('textarea'); let txt = document.createElement('textarea');
txt.innerHTML = document.getElementById('highlight-content').innerHTML; txt.innerHTML = document.getElementById('highlight-content').innerHTML;
let html = txt.value; let html = txt.value;
html = html.replace(/<\/?span[^>]*>/g, ''); //removes prism styling html = html.replace(/<\/?span[^>]*>/g, ''); //removes prism styling
html = html.replace(/<\/?br[^>]*>/g, '\n'); //convert back to encoded line break for storage html = html.replace(/<\/?br[^>]*>/g, '\n'); //convert back to encoded line break for storage
pageInfo.append( pageInfo.append(
'id', 'id',
document.getElementById('post-edit-index').getAttribute('data-index') document.getElementById('post-edit-index').getAttribute('data-index')
); );
pageInfo.append( pageInfo.append(
'uuid', 'uuid',
document.getElementById('post-edit-index').getAttribute('data-uuid') document.getElementById('post-edit-index').getAttribute('data-uuid')
); );
pageInfo.append( pageInfo.append(
'layout', 'layout',
document.getElementById('post-edit-index').getAttribute('data-layout') document.getElementById('post-edit-index').getAttribute('data-layout')
); );
pageInfo.append( pageInfo.append(
'current_title', 'current_title',
document.getElementById('post-edit-index').getAttribute('data-slug') document.getElementById('post-edit-index').getAttribute('data-slug')
); );
pageInfo.append('content', html); pageInfo.append('content', html);
pageInfo.append('title', document.getElementById('post_title').value); pageInfo.append('title', document.getElementById('post-title-text').value);
pageInfo.append( pageInfo.append(
'created', 'created',
document.getElementById('post-date').getAttribute('data-raw') document.getElementById('post-date').getAttribute('data-raw')
); );
pageInfo.append( pageInfo.append(
'slug', '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( );
'menu', pageInfo.append('tags', document.getElementById('post-tags').value);
document.getElementById('option-menu-pin').getAttribute('data-active') pageInfo.append(
); 'menu',
pageInfo.append( document.getElementById('option-menu-pin').getAttribute('data-active')
'featured', );
document.getElementById('option-feature').getAttribute('data-active') pageInfo.append(
); 'featured',
pageInfo.append( document.getElementById('option-feature').getAttribute('data-active')
'published', );
document.getElementById('option-published').getAttribute('data-active') pageInfo.append(
); 'published',
pageInfo.append('layout', document.getElementById('page-templates').value); document.getElementById('option-published').getAttribute('data-active')
pageInfo.append('form_token', document.getElementById('form_token').value); );
if (files.length > 0 && files != null) { pageInfo.append('layout', document.getElementById('page-templates').value);
for (var i = 0; i < files.length; i++) { pageInfo.append('form_token', document.getElementById('form_token').value);
var file = files[i]; if (files.length > 0 && files != null) {
if ( for (var i = 0; i < files.length; i++) {
file.type.match('image.*') || var file = files[i];
file.type.match('video.mp4') || if (
file.type.match('audio.mpeg') || file.type.match('image.*') ||
file.type.match('application.pdf') || file.type.match('video.mp4') ||
file.type.match('text.plain') || file.type.match('audio.mpeg') ||
file.type.match('text.rtf') file.type.match('application.pdf') ||
) { file.type.match('text.plain') ||
pageInfo.append('page_files[]', file, file.name); file.type.match('text.rtf')
} else { ) {
reject('Not an image file'); pageInfo.append('page_files[]', file, file.name);
} } else {
} reject('Not an image file');
} else { }
//check to see if image exists }
if (document.getElementById('featured-image')) { } else {
var imageURL = document.getElementById('featured-image').src; //check to see if image exists
imageURL != null || imageURL != undefined if (document.getElementById('featured-image')) {
? pageInfo.append('feature_image', imageURL) var imageURL = document.getElementById('featured-image').src;
: pageInfo.append('feature_image', null); imageURL != null || imageURL != undefined
} else { ? pageInfo.append('feature_image', imageURL)
//pageInfo.append("feature_image", null); : pageInfo.append('feature_image', null);
} } else {
} //pageInfo.append("feature_image", null);
//console.log("FILES", files); }
resolve(pageInfo); }
}); //console.log("FILES", files);
} resolve(pageInfo);
//-------------------------- });
// event handlers }
//-------------------------- //--------------------------
// event handlers
//--------------------------
} }