diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php new file mode 100644 index 0000000..7f73a4c --- /dev/null +++ b/.php-cs-fixer.php @@ -0,0 +1,71 @@ +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"); diff --git a/brain/api/v1/AuthAPI.php b/brain/api/v1/AuthAPI.php index a95dd47..0114d48 100644 --- a/brain/api/v1/AuthAPI.php +++ b/brain/api/v1/AuthAPI.php @@ -10,59 +10,56 @@ class AuthAPI public function __construct() { } - public static function status() { $result = []; //internal check for admin action if (Auth::status()) { $result = [ - "message" => "Authorized", - "type" => "apiUseAuthorized", - "token" => Session::get("token"), + 'message' => 'Authorized', + 'type' => 'apiUseAuthorized', + 'token' => Session::get('token'), ]; } else { $result = [ - "message" => "Not Authorized", - "type" => "apiUseNotAuthorized", + 'message' => 'Not Authorized', + 'type' => 'apiUseNotAuthorized', ]; } return $result; } - public static function login($body) { $result = []; switch (Auth::login($body)) { - case "no_name": + case 'no_name': $result = [ - "message" => "Need to see some id, champ", - "type" => "requestLame", + 'message' => 'Need to see some id, champ', + 'type' => 'requestLame', ]; break; - case "bad_pass": + case 'bad_pass': $result = [ - "message" => "Check your password, sport", - "type" => "requestLame", + 'message' => 'Check your password, sport', + 'type' => 'requestLame', ]; break; default: $result = [ - "message" => "Welcome back", - "type" => "requestGood", + 'message' => 'Welcome back', + 'type' => 'requestGood', ]; break; } return $result; } - public static function logout($body) { Auth::logout($body); $result = [ - "message" => "Till next time, g.", - "type" => "TASK_LOGOUT", + 'message' => 'Till next time, g.', + 'type' => 'TASK_LOGOUT', ]; return $result; } diff --git a/brain/api/v1/ImagesAPI.php b/brain/api/v1/ImagesAPI.php index 03896b8..944d0d3 100644 --- a/brain/api/v1/ImagesAPI.php +++ b/brain/api/v1/ImagesAPI.php @@ -11,68 +11,64 @@ class ImagesAPI public function __construct() { } - public static function uploadImage($request, $type = null) { - $file = $request->getUploadedFiles(); - $uploadPath = ""; - $path = date("Y") . "/" . date("m"); - $response = []; + $file = $request->getUploadedFiles(); + $uploadPath = ''; + $path = date('Y') . '/' . date('m'); + $response = []; switch ($type) { - case "avatar": - $image = $file["avatar_upload"]; - $uploadPath = "../public/assets/images/user/" . $path; + case 'avatar': + $image = $file['avatar_upload']; + $uploadPath = '../public/assets/images/user/' . $path; break; - case "background": - $image = $file["background_upload"]; - $uploadPath = "../public/assets/images/user/" . $path; + case 'background': + $image = $file['background_upload']; + $uploadPath = '../public/assets/images/user/' . $path; break; default: - $image = $file["post_image"]; - $path = date("Y") . "/" . date("m"); - $uploadPath = "../public/assets/images/blog/" . $path; + $image = $file['post_image']; + $path = date('Y') . '/' . date('m'); + $uploadPath = '../public/assets/images/blog/' . $path; break; } $result = FileUploader::uploadFile($uploadPath, $image); switch ($type) { - case "avatar": + case 'avatar': $response = [ - "message" => "Avatar Added. You look great!", - "type" => "avatarUploaded", - "url" => - "/assets/images/user/" . $path . "/" . $image->getClientFileName(), + 'message' => 'Avatar Added. You look great!', + 'type' => 'avatarUploaded', + 'url' => '/assets/images/user/' . $path . '/' . $image->getClientFileName(), ]; //update member data Member::updateData( - "avi", - "/assets/images/user/" . $path . "/" . $image->getClientFileName() + 'avi', + '/assets/images/user/' . $path . '/' . $image->getClientFileName() ); break; - case "background": + case 'background': $response = [ - "message" => "Background plugged in. That's nice!", - "type" => "siteBackgroundUploaded", - "url" => - "/assets/images/user/" . $path . "/" . $image->getClientFileName(), + 'message' => "Background plugged in. That's nice!", + 'type' => 'siteBackgroundUploaded', + 'url' => '/assets/images/user/' . $path . '/' . $image->getClientFileName(), ]; //update settings file Settings::updateGlobalData( - "background", - "/assets/images/user/" . $path . "/" . $image->getClientFileName() + 'background', + '/assets/images/user/' . $path . '/' . $image->getClientFileName() ); break; default: $response = [ - "message" => "Image Added. Very slick", - "type" => "postImageAdded", - "url" => - "/assets/images/blog/" . $path . "/" . $image->getClientFileName(), + 'message' => 'Image Added. Very slick', + 'type' => 'postImageAdded', + 'url' => '/assets/images/blog/' . $path . '/' . $image->getClientFileName(), ]; break; } diff --git a/brain/api/v1/InitAPI.php b/brain/api/v1/InitAPI.php index 4c67320..33597d8 100644 --- a/brain/api/v1/InitAPI.php +++ b/brain/api/v1/InitAPI.php @@ -9,7 +9,6 @@ class InitAPI public function __construct() { } - public static function handleInitTasks($task, $request) { //check if a site config already exists. if it does, deny set up request @@ -17,13 +16,13 @@ class InitAPI //through settings. if (Setup::status()) { - $result = ["type" => "blogInitFail", "message" => "Site already set up"]; + $result = ['type' => 'blogInitFail', 'message' => 'Site already set up']; } else { switch ($task) { - case "init": + case 'init': $result = Setup::init($request); break; - case "restore": + case 'restore': $result = Setup::restore($request); break; } diff --git a/brain/api/v1/MailerAPI.php b/brain/api/v1/MailerAPI.php index c81dfba..f9ad009 100644 --- a/brain/api/v1/MailerAPI.php +++ b/brain/api/v1/MailerAPI.php @@ -10,7 +10,6 @@ class MailerAPI public function __construct() { } - public static function handleMail($request, $body, $response) { // if testing, verify session is active @@ -20,8 +19,8 @@ class MailerAPI $result = Mailer::sendmail($body); } else { $result = [ - 'message' => 'You need to be logged in for this, champ.', - 'type' => 'MAILER_ERROR', + 'message' => 'You need to be logged in for this, champ.', + 'type' => 'MAILER_ERROR', ]; } } else { diff --git a/brain/api/v1/PagesAPI.php b/brain/api/v1/PagesAPI.php index 89f1d9f..aa74d65 100644 --- a/brain/api/v1/PagesAPI.php +++ b/brain/api/v1/PagesAPI.php @@ -2,13 +2,10 @@ namespace brain\api\v1; -use Mni\FrontYAML\Parser; -use brain\api\v1\ImagesAPI; use brain\data\Book; use brain\data\Settings; use brain\data\Session; use brain\utility\StringTools; - use function _\filter; class PagesAPI @@ -16,128 +13,126 @@ class PagesAPI public function __construct() { } - public static function getPageContent($request, $args) { - $task = $args["fourth"]; - $pages = (new Book("../content/pages"))->getContents(); + $task = $args['fourth']; + $pages = (new Book('../content/pages'))->getContents(); $content = []; foreach ($pages as $page) { $entry = [ - "id" => $page["id"], - "uuid" => $page["uuid"], - "title" => $page["title"], - "feature" => $page["feature"], - "path" => $page["path"], - "layout" => $page["layout"], - "tags" => $page["tags"], - "author" => $page["author"], - "created" => $page["created"], - "updated" => $page["updated"], - "deleted" => $page["deleted"], - "menu" => $page["menu"], - "featured" => $page["featured"], - "published" => $page["published"], - "slug" => $page["slug"], - "content" => StringTools::sanitizeContent($page["content"]), + 'id' => $page['id'], + 'uuid' => $page['uuid'], + 'title' => $page['title'], + 'feature' => $page['feature'], + 'path' => $page['path'], + 'layout' => $page['layout'], + 'tags' => $page['tags'], + 'author' => $page['author'], + 'created' => $page['created'], + 'updated' => $page['updated'], + 'deleted' => $page['deleted'], + 'menu' => $page['menu'], + 'featured' => $page['featured'], + 'published' => $page['published'], + 'slug' => $page['slug'], + 'content' => StringTools::sanitizeContent($page['content']), ]; array_push($content, $entry); } switch ($task) { - case "published": + case 'published': $published = filter($content, function ($item) { - return $item["published"] == true && $item["deleted"] == false; + return $item['published'] == true && $item['deleted'] == false; }); - $result = ["pages" => $published, "totalItems" => count($published)]; + $result = ['pages' => $published, 'totalItems' => count($published)]; break; - case "featured": + case 'featured': $featured = filter($content, function ($item) { - return $item["featured"] == true && $item["deleted"] == false; + return $item['featured'] == true && $item['deleted'] == false; }); $result = [ - "pages" => $featured, - "totalItems" => count($featured), + 'pages' => $featured, + 'totalItems' => count($featured), ]; break; - case "menu": + case 'menu': $menu = filter($content, function ($item) { - return $item["menu"] == true && $item["deleted"] == false; + return $item['menu'] == true && $item['deleted'] == false; }); - $result = ["pages" => $menu, "totalItems" => count($menu)]; + $result = ['pages' => $menu, 'totalItems' => count($menu)]; break; - case "single": - $uuid = $args["fifth"]; - $page = (new Book("../content/pages"))->findPageById($uuid); + case 'single': + $uuid = $args['fifth']; + $page = (new Book('../content/pages'))->findPageById($uuid); $entry = [ - "id" => $page["id"], - "uuid" => $page["uuid"], - "title" => $page["title"], - "feature" => $page["feature"], - "path" => $page["path"], - "layout" => $page["layout"], - "tags" => $page["tags"], - "author" => $page["author"], - "created" => $page["created"], - "updated" => $page["updated"], - "deleted" => $page["deleted"], - "menu" => $page["menu"], - "featured" => $page["featured"], - "published" => $page["published"], - "slug" => $page["slug"], - "content" => StringTools::sanitizeContent($page["content"]), + 'id' => $page['id'], + 'uuid' => $page['uuid'], + 'title' => $page['title'], + 'feature' => $page['feature'], + 'path' => $page['path'], + 'layout' => $page['layout'], + 'tags' => $page['tags'], + 'author' => $page['author'], + 'created' => $page['created'], + 'updated' => $page['updated'], + 'deleted' => $page['deleted'], + 'menu' => $page['menu'], + 'featured' => $page['featured'], + 'published' => $page['published'], + 'slug' => $page['slug'], + 'content' => StringTools::sanitizeContent($page['content']), ]; $result = $entry; break; - case "tags": + case 'tags': $result = Settings::getTags(); break; default: $result = [ - "message" => "Hm, no task. That's unfortunate", - "type" => "TASK_NONE", + 'message' => "Hm, no task. That's unfortunate", + 'type' => 'TASK_NONE', ]; break; } return $result; } - public static function handlePageTask($request, $args) { - $task = $args["fourth"]; + $task = $args['fourth']; switch ($task) { - case "delete": - case "create": - case "write": - $body = $request->getParsedBody(); + case 'delete': + case 'create': + case 'write': + $body = $request->getParsedBody(); $passed = true; - if (!isset($body["form_token"])) { + if (!isset($body['form_token'])) { $result = [ - "message" => "No form token. Not good, sport.", - "type" => "TASK_FORM_AUTH", + 'message' => 'No form token. Not good, sport.', + 'type' => 'TASK_FORM_AUTH', ]; } else { - if ($body["form_token"] == Session::get("form_token")) { + if ($body['form_token'] == Session::get('form_token')) { //TODO: Verify form fields $keys = [ - "id", - "uuid", - "layout", - "current_title", - "content", - "title", - "created", - "slug", - "tags", - "menu", - "featured", - "published", - "form_token", - "feature_image", + 'id', + 'uuid', + 'layout', + 'current_title', + 'content', + 'title', + 'created', + 'slug', + 'tags', + 'menu', + 'featured', + 'published', + 'form_token', + 'feature_image', ]; foreach ($body as $key => $item) { @@ -150,27 +145,26 @@ class PagesAPI $result = (new Book())->editPage($task, $request); } else { $result = [ - "message" => - "Unneccessary key found. Post not authorized, slick.", - "type" => "TASK_FORM_AUTH", + 'message' => 'Unneccessary key found. Post not authorized, slick.', + 'type' => 'TASK_FORM_AUTH', ]; } } else { $result = [ - "message" => "Form token, auth failed. Uh oh.", - "type" => "TASK_FORM_AUTH", + 'message' => 'Form token, auth failed. Uh oh.', + 'type' => 'TASK_FORM_AUTH', ]; } } break; - case "add-entry-image": + case 'add-entry-image': $result = ImagesAPI::uploadImage($request); break; default: $result = [ - "message" => "Hm, no task. That's unfortunate", - "type" => "TASK_NONE", + 'message' => "Hm, no task. That's unfortunate", + 'type' => 'TASK_NONE', ]; break; } diff --git a/brain/api/v1/SettingsAPI.php b/brain/api/v1/SettingsAPI.php index e2e4c7c..822ecdd 100644 --- a/brain/api/v1/SettingsAPI.php +++ b/brain/api/v1/SettingsAPI.php @@ -2,8 +2,6 @@ namespace brain\api\v1; -use Slim\Views\Twig; -use brain\api\v1\ImagesApi; use brain\data\Render; use brain\data\Settings; use brain\data\Session; @@ -14,45 +12,43 @@ class SettingsAPI public function __construct() { } - public static function handleSettingsTask($request, $args, $body = null) { - $task = $args["fourth"]; + $task = $args['fourth']; switch ($task) { - case "publish": + case 'publish': //check settings to see if site is a one pager - $config = new Settings(); - $settings = $config->getSettings(); - $theme = $settings["global"]["theme"]; + $config = new Settings(); + $settings = $config->getSettings(); + $theme = $settings['global']['theme']; $themeConfig = json_decode( - file_get_contents("../content/themes/" . $theme . "/theme.json"), + file_get_contents('../content/themes/' . $theme . '/theme.json'), true ); //check to see if dynamic rendering is active - if ( - isset($settings["global"]["dynamicRender"]) && - $settings["global"]["dynamicRender"] === "true" + if (isset($settings['global']['dynamicRender']) && + $settings['global']['dynamicRender'] === 'true' ) { $result = [ - "message" => "Dynamic Render Active! You're good!", - "type" => "RENDER_SUCCESS", - ]; + 'message' => "Dynamic Render Active! You're good!", + 'type' => 'RENDER_SUCCESS', + ]; } else { $render = new Render(); - if (isset($themeConfig["render"])) { - if (!$themeConfig["render"] || $themeConfig["render"] === "false") { + if (isset($themeConfig['render'])) { + if (!$themeConfig['render'] || $themeConfig['render'] === 'false') { $render->renderIndex(); $result = [ - "message" => "Index Rendered. HAND CLAPS", - "type" => "RENDER_SUCCESS", + 'message' => 'Index Rendered. HAND CLAPS', + 'type' => 'RENDER_SUCCESS', ]; } else { $render->renderTags(); $render->renderArchive(); $render->renderPages(); $result = [ - "message" => "Site Rendered. GOOD EFFORT", - "type" => "RENDER_SUCCESS", + 'message' => 'Site Rendered. GOOD EFFORT', + 'type' => 'RENDER_SUCCESS', ]; } } else { @@ -61,8 +57,8 @@ class SettingsAPI $render->renderArchive(); $render->renderPages(); $result = [ - "message" => "Site Rendered. GOOD EFFORT", - "type" => "RENDER_SUCCESS", + 'message' => 'Site Rendered. GOOD EFFORT', + 'type' => 'RENDER_SUCCESS', ]; } } @@ -71,81 +67,79 @@ class SettingsAPI //otherwise, render all pages according to theme template files break; - case "add-avatar": - $result = ImagesAPI::uploadImage($request, "avatar"); + case 'add-avatar': + $result = ImagesAPI::uploadImage($request, 'avatar'); break; - case "add-feature-background": - $result = ImagesAPI::uploadImage($request, "background"); + case 'add-feature-background': + $result = ImagesAPI::uploadImage($request, 'background'); break; - case "sync": + case 'sync': Settings::sync($body); $result = [ - "message" => "Settings Synced. You're doing great!", - "type" => "settingsUpdated", + 'message' => "Settings Synced. You're doing great!", + 'type' => 'settingsUpdated', ]; break; - case "nav-sync": + case 'nav-sync': Settings::navSync($body); $result = [ - "message" => "Navigation updated. Very slick!", - "type" => "menuUpdated", + 'message' => 'Navigation updated. Very slick!', + 'type' => 'menuUpdated', ]; break; default: $result = [ - "message" => "Hm, no task. That's unfortunate", - "type" => "TASK_NONE", + 'message' => "Hm, no task. That's unfortunate", + 'type' => 'TASK_NONE', ]; break; } return $result; } - public static function getInfo($request, $args) { - $task = $args["fourth"]; + $task = $args['fourth']; switch ($task) { - case "site": - $config = new Settings(); + case 'site': + $config = new Settings(); $settings = $config->getSettings(); - $data = [ - "title" => $settings["global"]["title"], - "base_url" => $settings["global"]["base_url"], - "description" => $settings["global"]["descriptions"], + $data = [ + 'title' => $settings['global']['title'], + 'base_url' => $settings['global']['base_url'], + 'description' => $settings['global']['descriptions'], ]; $result = [ - "message" => "Settings Found", - "type" => "GET_SETTINGS", - "data" => $data, + 'message' => 'Settings Found', + 'type' => 'GET_SETTINGS', + 'data' => $data, ]; break; - case "member": + case 'member': if (Session::active()) { - $member = $member = Session::get("member"); - $data = ["handle" => $member["handle"], "email" => $member["email"]]; + $member = $member = Session::get('member'); + $data = ['handle' => $member['handle'], 'email' => $member['email']]; $result = [ - "message" => "Member Info Found", - "type" => "GET_MEMBER_INFO", - "data" => $data, + 'message' => 'Member Info Found', + 'type' => 'GET_MEMBER_INFO', + 'data' => $data, ]; } else { $result = [ - "message" => "Not logged in. C'mon, bruh", - "type" => "TASK_NONE", + 'message' => "Not logged in. C'mon, bruh", + 'type' => 'TASK_NONE', ]; } break; default: $result = [ - "message" => "No Settings found. Frowny Face", - "type" => "TASK_NONE", + 'message' => 'No Settings found. Frowny Face', + 'type' => 'TASK_NONE', ]; break; } return $result; } - public static function createBackup() { $result = Maintenance::makeBackup(); diff --git a/brain/controller/APIControl.php b/brain/controller/APIControl.php index ad20f2b..132d59a 100644 --- a/brain/controller/APIControl.php +++ b/brain/controller/APIControl.php @@ -5,7 +5,6 @@ namespace brain\controller; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use brain\api\v1\AuthAPI; -use brain\api\v1\ImagesAPI; use brain\api\v1\PagesAPI; use brain\api\v1\SettingsAPI; use brain\api\v1\InitAPI; @@ -20,54 +19,54 @@ class APIControl ResponseInterface $response, array $args ): ResponseInterface { - $filename = ""; - switch (isset($args["third"]) ? $args["third"] : "none") { - case "status": + $filename = ''; + switch (isset($args['third']) ? $args['third'] : 'none') { + case 'status': $result = AuthAPI::status(); break; - case "page": + case 'page': //echo - if (Member::verifyKey($_GET["key"])) { + if (Member::verifyKey($_GET['key'])) { $result = PagesAPI::getPageContent($request, $args); } else { $result = [ - "message" => "API access denied, homie", - "type" => "API_ERROR", + 'message' => 'API access denied, homie', + 'type' => 'API_ERROR', ]; } break; - case "settings": - $token = $request->getHeader("fipamo-access-token"); + case 'settings': + $token = $request->getHeader('fipamo-access-token'); //Verify token to get site info if (isset($token[0])) { if (Session::verifyToken($token[0])) { $result = SettingsAPI::getInfo($request, $args); } else { $result = [ - "message" => "Invalid token, API access denied, homie", - "type" => "API_ERROR", + 'message' => 'Invalid token, API access denied, homie', + 'type' => 'API_ERROR', ]; } } else { $result = [ - "message" => "No token, API access denied, homie", - "type" => "API_ERROR", + 'message' => 'No token, API access denied, homie', + 'type' => 'API_ERROR', ]; } break; - case "files": + case 'files': if (Session::active()) { - if ($args["third"] == "backup") { - $filename = "../config/backups/latest_backup.zip"; + if ($args['third'] == 'backup') { + $filename = '../config/backups/latest_backup.zip'; if (file_exists($filename)) { - header("Content-Type: application/zip"); + header('Content-Type: application/zip'); header( 'Content-Disposition: attachment; filename="' . basename($filename) . '"' ); - header("Content-Length: " . filesize($filename)); + header('Content-Length: ' . filesize($filename)); flush(); // return readfile($filename); @@ -78,8 +77,8 @@ class APIControl } } else { $result = [ - "message" => "API access denied, homie", - "type" => "API_ERROR", + 'message' => 'API access denied, homie', + 'type' => 'API_ERROR', ]; } // no break @@ -89,19 +88,19 @@ class APIControl $freshResponse = $response; - if ($args["third"] == "files") { + if ($args['third'] == 'files') { $freshResponse ->getBody() - ->write(file_get_contents("../config/backups/latest_back.zip")); + ->write(file_get_contents('../config/backups/latest_back.zip')); - $freshResponse->withHeader("Content-Type", "application/zip"); + $freshResponse->withHeader('Content-Type', 'application/zip'); return $freshResponse->withAddedHeader( - "Content-Disposition", - "attachment; filename=latest_backup.zip" + 'Content-Disposition', + 'attachment; filename=latest_backup.zip' ); } else { $response->getBody()->write(json_encode($result)); - return $response->withHeader("Content-Type", "application/json"); + return $response->withHeader('Content-Type', 'application/json'); } } public static function post( @@ -109,26 +108,26 @@ class APIControl ResponseInterface $response, array $args ): ResponseInterface { - $contentType = $request->getHeader("Content-Type"); + $contentType = $request->getHeader('Content-Type'); switch ($contentType[0]) { - case "application/json": - $body = json_decode(file_get_contents("php://input"), true); + case 'application/json': + $body = json_decode(file_get_contents('php://input'), true); break; default: break; } - switch (isset($args["third"]) ? $args["third"] : "none") { - case "restore": //move to 'api/auth' - case "init": //move to 'api/auth' - $task = $args["third"]; + switch (isset($args['third']) ? $args['third'] : 'none') { + case 'restore': //move to 'api/auth' + case 'init': //move to 'api/auth' + $task = $args['third']; $result = InitApi::handleInitTasks( $task, - $task == "init" ? $body : $request + $task == 'init' ? $body : $request ); break; - case "backup": //move to 'api/auth' - $token = $request->getHeader("fipamo-access-token"); + case 'backup': //move to 'api/auth' + $token = $request->getHeader('fipamo-access-token'); //Verify token for admin tasks $result = SettingsAPI::createBackup(); /* @@ -143,15 +142,15 @@ class APIControl } */ break; - case "login": //move to 'api/auth' + case 'login': //move to 'api/auth' //check if request is remote and if so, verify token - if ($body["remote"] || $body["remote"] == "true") { - if (Member::verifyKey($body["key"])) { + if ($body['remote'] || $body['remote'] == 'true') { + if (Member::verifyKey($body['key'])) { $result = AuthAPI::login($body); } else { $result = [ - "message" => "API access denied, homie", - "type" => "API_ERROR", + 'message' => 'API access denied, homie', + 'type' => 'API_ERROR', ]; } } else { @@ -160,46 +159,46 @@ class APIControl } break; - case "logout": //move to 'api/auth' + case 'logout': //move to 'api/auth' $result = AuthAPI::logout($body); break; - case "get-secret": //move to 'api/auth' + case 'get-secret': //move to 'api/auth' $result = AuthAPI::requestSecret($body); break; - case "reset-password": //move to 'api/auth' + case 'reset-password': //move to 'api/auth' $result = AuthAPI::resetPassword($body); break; - case "page": - $token = $request->getHeader("fipamo-access-token"); + case 'page': + $token = $request->getHeader('fipamo-access-token'); //Verify token for admin tasks if (isset($token[0])) { if (Session::verifyToken($token[0])) { $result = PagesAPI::handlePageTask($request, $args); } else { $result = [ - "message" => "Invalid token, API access denied, homie", - "type" => "API_ERROR", + 'message' => 'Invalid token, API access denied, homie', + 'type' => 'API_ERROR', ]; } } else { $result = [ - "message" => "No token, API access denied, homie", - "type" => "API_ERROR", + 'message' => 'No token, API access denied, homie', + 'type' => 'API_ERROR', ]; } break; - case "settings": + case 'settings': if (isset($body)) { $postBody = $body; } else { $postBody = null; } - $task = $args["fourth"]; - if ($task == "add-feature-background" || $task == "add-avatar") { + $task = $args['fourth']; + if ($task == 'add-feature-background' || $task == 'add-avatar') { $result = SettingsAPI::handleSettingsTask($request, $args, $postBody); } else { - $token = $request->getHeader("fipamo-access-token"); + $token = $request->getHeader('fipamo-access-token'); if (Session::verifyToken($token[0])) { $result = SettingsAPI::handleSettingsTask( $request, @@ -208,25 +207,25 @@ class APIControl ); } else { $result = [ - "message" => "API access denied, homie", - "type" => "API_ERROR", + 'message' => 'API access denied, homie', + 'type' => 'API_ERROR', ]; } } break; - case "mailer": + case 'mailer': $result = MailerAPI::handleMail($request, $body, $response); break; default: $result = [ - "message" => "Oh, nothing to do. That's unfortunate", - "type" => "TASK_NONE", + 'message' => "Oh, nothing to do. That's unfortunate", + 'type' => 'TASK_NONE', ]; break; } $response->getBody()->write(json_encode($result)); - return $response->withHeader("Content-Type", "application/json"); + return $response->withHeader('Content-Type', 'application/json'); } } diff --git a/brain/controller/DashControl.php b/brain/controller/DashControl.php index 6f2d3a6..e507a89 100644 --- a/brain/controller/DashControl.php +++ b/brain/controller/DashControl.php @@ -18,44 +18,44 @@ class DashControl ResponseInterface $response, array $args ): ResponseInterface { - $view = Twig::fromRequest($request); + $view = Twig::fromRequest($request); $pageOptions = []; - $template = ''; + $template = ''; if (Setup::status()) { switch (isset($args['second']) ? $args['second'] : 'index') { case 'settings': if (Session::active()) { - $config = new Settings(); - $settings = $config->getSettings(); - $themes = (new Themes())->getThemes(); // $config->getThemes(); - $template = 'dash/settings.twig'; - $member = Session::get('member'); - $form_token = Session::get('form_token'); - $updated = new \Moment\Moment($settings['global']['last_backup']); + $config = new Settings(); + $settings = $config->getSettings(); + $themes = (new Themes())->getThemes(); // $config->getThemes(); + $template = 'dash/settings.twig'; + $member = Session::get('member'); + $form_token = Session::get('form_token'); + $updated = new \Moment\Moment($settings['global']['last_backup']); $pageOptions = [ - 'title' => 'Dash Settings', - 'private' => $settings['global']['private'], - 'renderOnSave' => $settings['global']['renderOnSave'], - 'background' => $settings['global']['background'], - 'member' => $member, - 'ftoken' => $form_token, - 'siteTitle' => $settings['global']['title'], - 'baseUrl' => $settings['global']['base_url'], - 'desc' => $settings['global']['descriptions'], - 'lastBackup' => $updated->format('Y M D d'), - 'currentTheme' => $settings['global']['theme'], - 'themes' => $themes, - 'apiStatus' => isset($settings['global']['externalAPI']) - ? $settings['global']['externalAPI'] - : 'false', - 'dynamicRenderStatus' => isset( - $settings['global']['dynamicRender'] - ) - ? $settings['global']['dynamicRender'] - : 'false', - 'mailOption' => $settings['email']['active'], - 'mailConfig' => $settings['email'], - 'status' => Session::active(), + 'title' => 'Dash Settings', + 'private' => $settings['global']['private'], + 'renderOnSave' => $settings['global']['renderOnSave'], + 'background' => $settings['global']['background'], + 'member' => $member, + 'ftoken' => $form_token, + 'siteTitle' => $settings['global']['title'], + 'baseUrl' => $settings['global']['base_url'], + 'desc' => $settings['global']['descriptions'], + 'lastBackup' => $updated->format('Y M D d'), + 'currentTheme' => $settings['global']['theme'], + 'themes' => $themes, + 'apiStatus' => isset($settings['global']['externalAPI']) + ? $settings['global']['externalAPI'] + : 'false', + 'dynamicRenderStatus' => isset( + $settings['global']['dynamicRender'] + ) + ? $settings['global']['dynamicRender'] + : 'false', + 'mailOption' => $settings['email']['active'], + 'mailConfig' => $settings['email'], + 'status' => Session::active(), ]; } else { header('Location: /dashboard'); @@ -65,13 +65,13 @@ class DashControl break; case 'navigation': if (Session::active()) { - $config = new Settings(); - $settings = $config->getSettings(); - $template = 'dash/navigation.twig'; + $config = new Settings(); + $settings = $config->getSettings(); + $template = 'dash/navigation.twig'; $pageOptions = [ - 'title' => 'Edit Dash Navigation', - 'status' => Session::active(), - 'menu' => $settings['menu'], + 'title' => 'Edit Dash Navigation', + 'status' => Session::active(), + 'menu' => $settings['menu'], ]; } else { header('Location: /dashboard'); @@ -81,19 +81,19 @@ class DashControl case 'pages': if (Session::active()) { $currentPage = isset($args['fourth']) ? $args['fourth'] : 1; - $filter = isset($args['third']) ? $args['third'] : 'all'; - $data = (new Book())->getPages($currentPage, 4, $filter); - $template = 'dash/book.twig'; + $filter = isset($args['third']) ? $args['third'] : 'all'; + $data = (new Book())->getPages($currentPage, 4, $filter); + $template = 'dash/book.twig'; $pageOptions = [ - 'title' => 'Contents', - 'entryCount' => $data['entryCount'], - 'numOfPages' => $data['numOfPages'], - 'currentPage' => $currentPage, - 'filter' => $data['paginate']['sort'], - 'stats' => $data['stats'], - 'pages' => $data['pages'], - 'paginate' => $data['paginate'], - 'status' => Session::active(), + 'title' => 'Contents', + 'entryCount' => $data['entryCount'], + 'numOfPages' => $data['numOfPages'], + 'currentPage' => $currentPage, + 'filter' => $data['paginate']['sort'], + 'stats' => $data['stats'], + 'pages' => $data['pages'], + 'paginate' => $data['paginate'], + 'status' => Session::active(), ]; } else { header('Location: /dashboard'); @@ -103,12 +103,12 @@ class DashControl case 'page': if (Session::active()) { $template = 'dash/page-edit.twig'; - $mode = $args['third']; - $uuid = $args['fourth']; + $mode = $args['third']; + $uuid = $args['fourth']; switch ($mode) { case 'edit': - $page = (new Book())->findPageById($uuid); + $page = (new Book())->findPageById($uuid); $views = []; if (str_contains($page['layout'], 'index')) { $views = (new Themes())->getCustomIndex(); @@ -117,10 +117,10 @@ class DashControl } $imageList = explode(',', $page['feature']); - $fileList = explode(',', $page['files']); + $fileList = explode(',', $page['files']); $images = []; - $files = []; + $files = []; foreach ($imageList as $item) { $image = trim($item); if (!empty($image)) { @@ -136,29 +136,28 @@ class DashControl } $pageOptions = [ - 'title' => 'Fipamo | Edit Page', - 'page' => $page, - 'mode' => $mode, - 'token' => Session::get('form_token'), - 'status' => Session::active(), - 'images' => $images, - 'files' => $files, - 'views' => $views, + 'title' => 'Fipamo | Edit Page', + 'page' => $page, + 'mode' => $mode, + 'token' => Session::get('form_token'), + 'status' => Session::active(), + 'images' => $images, + 'files' => $files, + 'views' => $views, ]; break; case 'preview': - $config = new Settings(); + $config = new Settings(); $settings = $config->getSettings(); - $loader = new \Twig\Loader\FilesystemLoader( + $loader = new \Twig\Loader\FilesystemLoader( '../content/themes' ); $display = new \Twig\Environment($loader, []); - $book = new Book(); - $page = $book->findPageById($uuid); + $book = new Book(); + $page = $book->findPageById($uuid); $pageOptions = Sorting::page($page); - $preview = - $settings['global']['theme'] . + $preview = $settings['global']['theme'] . '/' . $page['layout'] . '.twig'; @@ -169,10 +168,10 @@ class DashControl break; default: $pageOptions = [ - 'title' => 'Fipamo | Create Page', - 'token' => Session::get('form_token'), - 'mode' => $mode, - 'status' => Session::active(), + 'title' => 'Fipamo | Create Page', + 'token' => Session::get('form_token'), + 'mode' => $mode, + 'status' => Session::active(), ]; break; } @@ -187,29 +186,29 @@ class DashControl exit(); break; case 'reset-password': - $template = 'dash/reset-password.twig'; + $template = 'dash/reset-password.twig'; $pageOptions = [ - 'title' => 'Reset Password', + 'title' => 'Reset Password', ]; break; default: $template = 'dash/start.twig'; if (Session::active()) { $pageOptions = [ - 'title' => 'Welcome Back', - 'status' => Session::active(), - 'data' => (new Book())->getPages(1, 4), + 'title' => 'Welcome Back', + 'status' => Session::active(), + 'data' => (new Book())->getPages(1, 4), ]; } else { $pageOptions = [ - 'title' => 'Welcome to Fipamo', - 'status' => Session::active(), + 'title' => 'Welcome to Fipamo', + 'status' => Session::active(), ]; } break; } } else { - $template = 'dash/init.twig'; + $template = 'dash/init.twig'; $pageOptions = ['title' => 'Fipamo Setup']; } diff --git a/brain/controller/IndexControl.php b/brain/controller/IndexControl.php index 07fab53..fd74731 100644 --- a/brain/controller/IndexControl.php +++ b/brain/controller/IndexControl.php @@ -7,7 +7,6 @@ use Psr\Http\Message\ServerRequestInterface; use Slim\Views\Twig; use brain\data\Settings; use brain\utility\Sorting; - use function _\find; class IndexControl @@ -17,54 +16,53 @@ class IndexControl ResponseInterface $response, array $args ): ResponseInterface { - //unset($_SESSION); - $config = new Settings(); + //unset($_SESSION); + $config = new Settings(); $settings = $config->getSettings(); - $view = Twig::fromRequest($request); - //checks dynamic render flag for site render status - if ($settings["global"]["dynamicRender"]) { - if ($settings["global"]["dynamicRender"] == "true") { - $loader = new \Twig\Loader\FilesystemLoader("../content/themes"); - $display = new \Twig\Environment($loader, []); - $template = ""; + $view = Twig::fromRequest($request); + //checks dynamic render flag for site render status + if ($settings['global']['dynamicRender']) { + if ($settings['global']['dynamicRender'] == 'true') { + $loader = new \Twig\Loader\FilesystemLoader('../content/themes'); + $display = new \Twig\Environment($loader, []); + $template = ''; $pageOptions = []; $pageInfo = [ - "keywords" => isset($settings["global"]["keywords"]) - ? $settings["global"]["keywords"] - : "fipamo, blog, jamstack, php, markdown, js", - "description" => $settings["global"]["descriptions"], - "image" => - $settings["global"]["base_url"] . $settings["global"]["background"], - "baseURL" => $settings["global"]["base_url"], + 'keywords' => isset($settings['global']['keywords']) + ? $settings['global']['keywords'] + : 'fipamo, blog, jamstack, php, markdown, js', + 'description' => $settings['global']['descriptions'], + 'image' => $settings['global']['base_url'] . $settings['global']['background'], + 'baseURL' => $settings['global']['base_url'], ]; - if (isset($args["first"])) { - switch ($args["first"]) { - case "tags": - $template = $settings["global"]["theme"] . "/tags.twig"; - $tag = trim($args["second"]); - $taglist = Sorting::tags(); - $item = find($taglist, ["tag_name" => $tag]); + if (isset($args['first'])) { + switch ($args['first']) { + case 'tags': + $template = $settings['global']['theme'] . '/tags.twig'; + $tag = trim($args['second']); + $taglist = Sorting::tags(); + $item = find($taglist, ['tag_name' => $tag]); $pageOptions = [ - "title" => "Pages Tagged as " . $item["tag_name"], - "background" => $pageInfo["image"], - "tag_list" => $item["pages"], - "info" => $pageInfo, - "menu" => $settings["menu"], - "dynamicRender" => $settings["global"]["dynamicRender"], + 'title' => 'Pages Tagged as ' . $item['tag_name'], + 'background' => $pageInfo['image'], + 'tag_list' => $item['pages'], + 'info' => $pageInfo, + 'menu' => $settings['menu'], + 'dynamicRender' => $settings['global']['dynamicRender'], ]; break; - case "archives": - $archive = Sorting::archive(); - $template = $settings["global"]["theme"] . "/archive.twig"; + case 'archives': + $archive = Sorting::archive(); + $template = $settings['global']['theme'] . '/archive.twig'; $pageOptions = [ - "title" => "Archive", - "background" => $pageInfo["image"], - "archives" => $archive, - "info" => $pageInfo, - "menu" => $settings["menu"], - "dynamicRender" => $settings["global"]["dynamicRender"], + 'title' => 'Archive', + 'background' => $pageInfo['image'], + 'archives' => $archive, + 'info' => $pageInfo, + 'menu' => $settings['menu'], + 'dynamicRender' => $settings['global']['dynamicRender'], ]; break; @@ -72,23 +70,21 @@ class IndexControl //check if page is a menu item, if not render along path as usual $page = []; $book = new Book(); - if (is_numeric($args["first"])) { - $page = $book->findPageBySlug($args["third"]); + if (is_numeric($args['first'])) { + $page = $book->findPageBySlug($args['third']); } else { - $page = $book->findPageBySlug($args["first"]); + $page = $book->findPageBySlug($args['first']); } - $template = - $settings["global"]["theme"] . "/" . $page["layout"] . ".twig"; + $template = $settings['global']['theme'] . '/' . $page['layout'] . '.twig'; $pageOptions = Sorting::page($page); break; } } else { - //index - $template = - $settings["global"]["theme"] . "/" . $page["layout"] . ".twig"; - $book = new Book(""); - $page = $book->findPageBySlug(); + //index + $template = $settings['global']['theme'] . '/' . $page['layout'] . '.twig'; + $book = new Book(''); + $page = $book->findPageBySlug(); $pageOptions = Sorting::page($page); } @@ -96,16 +92,16 @@ class IndexControl $response->getBody()->write($html); return $response; } else { - //if dynamic flag is false, load up html + //if dynamic flag is false, load up html $view = Twig::fromRequest($request); - $html = file_get_contents("../public/index.html"); + $html = file_get_contents('../public/index.html'); $response->getBody()->write($html); return $response; } } else { - //if flag is not present, default to static html + //if flag is not present, default to static html $view = Twig::fromRequest($request); - $html = file_get_contents("../public/index.html"); + $html = file_get_contents('../public/index.html'); $response->getBody()->write($html); return $response; } diff --git a/brain/controller/RouteControl.php b/brain/controller/RouteControl.php index f7a935c..7749362 100644 --- a/brain/controller/RouteControl.php +++ b/brain/controller/RouteControl.php @@ -4,9 +4,6 @@ namespace brain\controller; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; -use brain\controller\DashControl; -use brain\controller\APIControl; -use brain\controller\IndexControl; class RouteControl { @@ -15,11 +12,11 @@ class RouteControl ResponseInterface $response, array $args ): ResponseInterface { - switch (isset($args["first"]) ? $args["first"] : "index") { - case "dashboard": + switch (isset($args['first']) ? $args['first'] : 'index') { + case 'dashboard': return DashControl::start($request, $response, $args); break; - case "api": + case 'api': return APIControl::get($request, $response, $args); break; default: @@ -27,14 +24,13 @@ class RouteControl break; } } - public function post( ServerRequestInterface $request, ResponseInterface $response, array $args ): ResponseInterface { - switch (isset($args["first"]) ? $args["first"] : "index") { - case "api": + switch (isset($args['first']) ? $args['first'] : 'index') { + case 'api': //$result = APIControl::post($request, $response, $args); //var_dump($result); return APIControl::post($request, $response, $args); diff --git a/brain/data/Auth.php b/brain/data/Auth.php index fa2444c..5f9c59d 100644 --- a/brain/data/Auth.php +++ b/brain/data/Auth.php @@ -3,9 +3,6 @@ namespace brain\data; use ReallySimpleJWT\Token; -use brain\data\Settings; -use brain\data\Session; - use function _\find; class Auth @@ -13,20 +10,18 @@ class Auth public function __construct() { } - public static function sessionStatus() { - if (isset($_SESSION["member"])) { + if (isset($_SESSION['member'])) { return true; } else { return false; } //return $this->secret; } - public static function status() { - $result = ""; + $result = ''; if (Session::active()) { $result = true; } else { @@ -34,124 +29,119 @@ class Auth } return $result; } - public static function login($who) { //grab member list $folks = (new Settings())->getFolks(); - $found = find($folks, ["handle" => $who["handle"]]); + $found = find($folks, ['handle' => $who['handle']]); if ($found) { //name is found, verify password - if (password_verify($who["password"], $found["password"])) { + if (password_verify($who['password'], $found['password'])) { $member = [ - "handle" => $found["handle"], - "email" => $found["email"], - "role" => $found["role"], - "avatar" => $found["avi"], - "key" => $found["key"], + 'handle' => $found['handle'], + 'email' => $found['email'], + 'role' => $found['role'], + 'avatar' => $found['avi'], + 'key' => $found['key'], ]; $token = Token::create( - $found["key"], - $found["secret"], + $found['key'], + $found['secret'], time() + 3600, - "localhost" + 'localhost' ); //expires in an hour $form_token = md5(uniqid(microtime(), true)); Session::start(); - Session::set("member", $member); - Session::set("token", $token); - Session::set("form_token", $form_token); + Session::set('member', $member); + Session::set('token', $token); + Session::set('form_token', $form_token); - $result = "good_login"; + $result = 'good_login'; } else { - $result = "bad_pass"; + $result = 'bad_pass'; } } else { //if name is not found - $result = "no_name"; + $result = 'no_name'; } return $result; } - public static function findSecret($data) { $result = []; - $folks = (new Settings())->getFolks(); + $folks = (new Settings())->getFolks(); - if ( - !empty($data["email"]) && - filter_var($data["email"], FILTER_VALIDATE_EMAIL) + if (!empty($data['email']) && + filter_var($data['email'], FILTER_VALIDATE_EMAIL) ) { - $found = find($folks, ["email" => $data["email"]]); + $found = find($folks, ['email' => $data['email']]); if ($found) { //if email is cool, check mail relay status //if set up, send secret there, if not just return it - $config = new Settings(); + $config = new Settings(); $settings = $config->getSettings(); - $email = $settings["email"]["active"]; - if ($email != "option-none") { - $data["mail_task"] = "SEND_SECRET"; - $data["secret"] = $found["secret"]; - $result = Mailer::sendmail($data); + $email = $settings['email']['active']; + if ($email != 'option-none') { + $data['mail_task'] = 'SEND_SECRET'; + $data['secret'] = $found['secret']; + $result = Mailer::sendmail($data); } else { $result = [ - "message" => "Valid email, but no email set up!", - "type" => "secretFound", - "secret" => $found["secret"], + 'message' => 'Valid email, but no email set up!', + 'type' => 'secretFound', + 'secret' => $found['secret'], ]; } } else { $result = [ - "message" => "No valid email, no goodies, pleighboi", - "type" => "secretNotFound", + 'message' => 'No valid email, no goodies, pleighboi', + 'type' => 'secretNotFound', ]; } } else { $result = [ - "message" => "Aye, this address is not right, slick.", - "type" => "secretNotFound", + 'message' => 'Aye, this address is not right, slick.', + 'type' => 'secretNotFound', ]; } return $result; } - public static function makeNewPassword($data) { //check if passwordsmatch - if ($data["newPass"] == $data["newPassConfirm"]) { + if ($data['newPass'] == $data['newPassConfirm']) { //verify secret $folks = (new Settings())->getFolks(); - $found = find($folks, ["secret" => $data["secret"]]); + $found = find($folks, ['secret' => $data['secret']]); if ($found) { //create new pass and secret key, then update file - $hash = password_hash($data["newPass"], PASSWORD_DEFAULT); + $hash = password_hash($data['newPass'], PASSWORD_DEFAULT); $freshSecret = StringTools::randomString(12); - Member::updateData("password", $hash, $data["secret"]); - Member::updateData("secret", $freshSecret, $data["secret"]); + Member::updateData('password', $hash, $data['secret']); + Member::updateData('secret', $freshSecret, $data['secret']); $result = [ - "message" => "Password Updated. Very nice!", - "type" => "passCreated", + 'message' => 'Password Updated. Very nice!', + 'type' => 'passCreated', ]; } else { $result = [ - "message" => "Secret key is invalid. Try to retrieve it again", - "type" => "passNotCreated", + 'message' => 'Secret key is invalid. Try to retrieve it again', + 'type' => 'passNotCreated', ]; } } else { $result = [ - "message" => "Passwords don't match. Try it again.", - "type" => "passNotCreated", + 'message' => "Passwords don't match. Try it again.", + 'type' => 'passNotCreated', ]; } return $result; } - public static function logout() { Session::kill(); diff --git a/brain/data/Book.php b/brain/data/Book.php index 237f66a..642df40 100644 --- a/brain/data/Book.php +++ b/brain/data/Book.php @@ -2,26 +2,24 @@ namespace brain\data; -use function _\filter; -use function _\find; use brain\utility\DocTools; -use brain\utility\FileUploader; use brain\utility\StringTools; +use brain\utility\FileUploader; +use function _\find; +use function _\filter; class Book { public function __construct() { } - public function findPageById(string $uuid) { $content = $this->getContents(); - $page = find($content, ['uuid' => $uuid]); + $page = find($content, ['uuid' => $uuid]); return $page; } - public function findPageBySlug(string $slug = null) { $content = $this->getContents(); @@ -33,7 +31,6 @@ class Book return $page; } - public function editPage($task, $request) { $content = $this->getContents(); @@ -45,26 +42,25 @@ class Book $body = $request->getParsedBody(); } - $page = find($content, ['uuid' => $body['uuid']]); + $page = find($content, ['uuid' => $body['uuid']]); $files = $request->getUploadedFiles(); $member = Session::get('member'); if ($task != 'create') { - $path = - date('Y', date($page['rawCreated'])). - '/'. + $path = date('Y', date($page['rawCreated'])) . + '/' . date('m', date($page['rawCreated'])); } else { - $path = date('Y').'/'.date('m'); + $path = date('Y') . '/' . date('m'); } $page_feature = ''; - $page_files = ''; + $page_files = ''; if (isset($files['page_files'])) { $imageList = ''; - $fileList = ''; + $fileList = ''; // var_dump($files["page_files"] ); foreach ($files['page_files'] as $file) { $type = $file->getClientMediaType(); @@ -73,81 +69,78 @@ class Book case 'image/png': case 'image/gif': case 'image/svg': - $imagesPath = '/assets/images/blog/'.$path.'/'; - $imageList = - $imageList.$imagesPath.urlencode($file->getClientFileName()).', '; + $imagesPath = '/assets/images/blog/' . $path . '/'; + $imageList = $imageList . $imagesPath . urlencode($file->getClientFileName()) . ', '; FileUploader::uploadFile( - '../public/assets/images/blog/'.$path.'/', + '../public/assets/images/blog/' . $path . '/', $file ); break; case 'video/mp4': - $videosPath = '/assets/video/blog/'.$path.'/'; - $imageList = - $imageList.$videosPath.urlencode($file->getClientFileName()).', '; + $videosPath = '/assets/video/blog/' . $path . '/'; + $imageList = $imageList . $videosPath . urlencode($file->getClientFileName()) . ', '; FileUploader::uploadFile( - '../public/assets/video/blog/'.$path.'/', + '../public/assets/video/blog/' . $path . '/', $file ); break; case 'audio/mpeg': - $soundPath = '/assets/sound/blog/'.$path.'/'; - $fileList = $fileList.$soundPath.urlencode($file->getClientFileName()).', '; + $soundPath = '/assets/sound/blog/' . $path . '/'; + $fileList = $fileList . $soundPath . urlencode($file->getClientFileName()) . ', '; FileUploader::uploadFile( - '../public/assets/sound/blog/'.$path.'/', + '../public/assets/sound/blog/' . $path . '/', $file ); break; case 'application/pdf': case 'text/plain': case 'text/rtf': - $docPath = '/assets/docs/blog/'.$path.'/'; - $fileList = $fileList.$docPath.urlencode($file->getClientFileName()).', '; + $docPath = '/assets/docs/blog/' . $path . '/'; + $fileList = $fileList . $docPath . urlencode($file->getClientFileName()) . ', '; FileUploader::uploadFile( - '../public/assets/docs/blog/'.$path.'/', + '../public/assets/docs/blog/' . $path . '/', $file ); break; } } $page_feature = $imageList; - $page_files = $fileList; + $page_files = $fileList; } else { // if no files, just reset string from page object $page_feature = $page['feature']; - $page_files = $page['files']; + $page_files = $page['files']; } if ($task == 'delete') { - $deleted = 'true'; - $body['menu'] = 'false'; + $deleted = 'true'; + $body['menu'] = 'false'; $body['published'] = 'false'; - $body['featured'] = 'false'; + $body['featured'] = 'false'; } else { $deleted = isset($page['deleted']) ? $page['deleted'] : 'false'; } - $created = - $task != 'create' + $created = $task != 'create' ? new \Moment\Moment($page['rawCreated']) : new \Moment\Moment(); $updated = new \Moment\Moment(); // 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(); // now that variables are done, set to body object and then convert to markdown to save - $body['id'] = $id; - $body['uuid'] = $uuid; + $body['id'] = $id; + $body['uuid'] = $uuid; $body['feature'] = $page_feature; - $body['files'] = $page_files; - $body['path'] = $path; - $body['author'] = $member['handle']; + $body['files'] = $page_files; + $body['path'] = $path; + $body['author'] = $member['handle']; $body['created'] = $created->format("Y-m-d\TH:i:sP"); $body['updated'] = $updated->format("Y-m-d\TH:i:sP"); $body['deleted'] = $deleted; @@ -159,15 +152,15 @@ class Book if ($body['layout'] == 'index') { $writePath = '../content/pages/start/index.md'; } else { - $writePath = '../content/pages/'.$path.'/'.$body['slug'].'.md'; + $writePath = '../content/pages/' . $path . '/' . $body['slug'] . '.md'; } $status = DocTools::writePages($task, $path, $writePath, $write); if ($status) { - $config = new Settings(); + $config = new Settings(); $settings = $config->getSettings(); - $message = ''; + $message = ''; if ( $settings['global']['renderOnSave'] == 'true' && @@ -183,9 +176,9 @@ class Book } $response = [ - 'message' => $message, - 'type' => $task == 'write' ? 'postUpdated' : 'postAdded', - 'id' => $uuid, + 'message' => $message, + 'type' => $task == 'write' ? 'postUpdated' : 'postAdded', + 'id' => $uuid, ]; // TODO: When form submission is successful, make new form token @@ -203,15 +196,14 @@ class Book } } else { $response = [ - 'message' => "Uh oh. File save problem. Don't panic", - 'type' => 'postError', - 'id' => $uuid, + 'message' => "Uh oh. File save problem. Don't panic", + 'type' => 'postError', + 'id' => $uuid, ]; } return $response; } - public function getPages(int $page, int $limit, string $sort = null) { $content = $this->getContents(); @@ -240,7 +232,7 @@ class Book break; } $numOfPages = ceil(count($filtered) / ($limit + 1)); - $folder = []; + $folder = []; if (count($filtered) != 0) { if (count($filtered) < $limit) { @@ -271,22 +263,21 @@ class Book } return [ - 'pages' => $folder, - 'numOfPages' => $numOfPages, - 'entryCount' => count($filtered), - 'paginate' => [ - 'sort' => $sort, - 'nextPage' => $next, - 'prevPage' => $prev, - ], - 'stats' => [ - 'all' => count($all), - 'published' => count($published), - 'deleted' => count($deleted), - ], + 'pages' => $folder, + 'numOfPages' => $numOfPages, + 'entryCount' => count($filtered), + 'paginate' => [ + 'sort' => $sort, + 'nextPage' => $next, + 'prevPage' => $prev, + ], + 'stats' => [ + 'all' => count($all), + 'published' => count($published), + 'deleted' => count($deleted), + ], ]; } - public function getContents() { // test new contents data class diff --git a/brain/data/Contents.php b/brain/data/Contents.php index 9fd6b41..74cf95c 100644 --- a/brain/data/Contents.php +++ b/brain/data/Contents.php @@ -2,25 +2,24 @@ 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\Iframe\IframeExtension; use HtmlSanitizer\Extension\Listing\ListExtension; 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; class Contents { - public $files = []; + public $files = []; public $config = []; + public function __construct($folder) { $this->read($folder); @@ -32,12 +31,11 @@ class Contents //$this->files[] = $folder . "/"; $this->read($folder); } - $files = array_filter(glob("$folder/*md"), "is_file"); + $files = array_filter(glob("$folder/*md"), 'is_file'); foreach ($files as $file) { $this->files[] = $file; } } - public function getAll() { $environment = new Environment($this->config); @@ -59,16 +57,16 @@ class Contents foreach ($this->files as $file) { //get meta and html from file $result = $converter->convertToHtml(file_get_contents($file)); - $meta = []; + $meta = []; if ($result instanceof RenderedContentWithFrontMatter) { $meta = $result->getFrontMatter(); } //get raw markdown from file $frontMatterExtension = new FrontMatterExtension(); - $parsed = $frontMatterExtension - ->getFrontMatterParser() - ->parse(file_get_contents($file)); + $parsed = $frontMatterExtension + ->getFrontMatterParser() + ->parse(file_get_contents($file)); //never trust the front end. clean it up //add what sanitizer extensions we need manually @@ -86,84 +84,84 @@ class Contents ); $detergent = [ - "extensions" => ["basic", "list","relative-a", "relative-image", "iframe"], - "tags" => [ - "div" => [ - "allowed_attributes" => ["class", "title", "id", "style"], - ], - "img" => [ - "allowed_attributes" => ["src", "alt", "title", "class"], - ], - "iframe" => [ - "allowed_attributes" => ["height", "width", "title", "src"], - ], - ], + 'extensions' => ['basic', 'list', 'relative-a', 'relative-image', 'iframe'], + 'tags' => [ + 'div' => [ + 'allowed_attributes' => ['class', 'title', 'id', 'style'], + ], + 'img' => [ + 'allowed_attributes' => ['src', 'alt', 'title', 'class'], + ], + 'iframe' => [ + 'allowed_attributes' => ['height', 'width', 'title', 'src'], + ], + ], ]; $sanitizer = $builder->build($detergent); - $scrubbed = $sanitizer->sanitize($result->getContent()); - $featureList = explode(",", $meta["feature"]); - $docs = ''; - if (isset($meta["files"])) { - $fileList = explode(",", $meta["files"]); - $docs = $meta["files"]; + $scrubbed = $sanitizer->sanitize($result->getContent()); + $featureList = explode(',', $meta['feature']); + $docs = ''; + if (isset($meta['files'])) { + $fileList = explode(',', $meta['files']); + $docs = $meta['files']; } else { $fileList = []; - $docs = ''; + $docs = ''; } $media = []; $files = []; foreach ($featureList as $file) { $item = trim($file); - $ext = pathinfo($item, PATHINFO_EXTENSION); - if ($item != null || $item != "") { - array_push($media, ["file" => $item, "type" => trim($ext)]); + $ext = pathinfo($item, PATHINFO_EXTENSION); + if ($item != null || $item != '') { + array_push($media, ['file' => $item, 'type' => trim($ext)]); } } foreach ($fileList as $file) { $item = trim($file); - $ext = pathinfo($item, PATHINFO_EXTENSION); - if ($item != null || $item != "") { - array_push($files, ["file" => $item, "type" => trim($ext)]); + $ext = pathinfo($item, PATHINFO_EXTENSION); + if ($item != null || $item != '') { + array_push($files, ['file' => $item, 'type' => trim($ext)]); } } //sort attributes into page object $page = [ - "id" => $meta["id"], - "uuid" => $meta["uuid"], - "title" => $meta["title"], - "feature" => $meta["feature"], - "files" => $docs, - "path" => $meta["path"], - "layout" => $meta["layout"], - "tags" => $meta["tags"], - "author" => $meta["author"], - "created" => date("Y M D d", $meta["created"]), - "updated" => date("Y M D d", $meta["updated"]), - "rawCreated" => $meta["created"], - "rawUpdated" => $meta["updated"], - "createdYear" => date("Y", $meta["created"]), - "createdMonth" => date("m", $meta["created"]), - "deleted" => $meta["deleted"], - "menu" => $meta["menu"], - "featured" => $meta["featured"], - "published" => $meta["published"], - "slug" => $meta["slug"], - "filePath" => $file, - "content" => $parsed->getContent(), - "html" => $scrubbed, - "media" => $media, - "docs" => $files + 'id' => $meta['id'], + 'uuid' => $meta['uuid'], + 'title' => $meta['title'], + 'feature' => $meta['feature'], + 'files' => $docs, + 'path' => $meta['path'], + 'layout' => $meta['layout'], + 'tags' => $meta['tags'], + 'author' => $meta['author'], + 'created' => date('Y M D d', $meta['created']), + 'updated' => date('Y M D d', $meta['updated']), + 'rawCreated' => $meta['created'], + 'rawUpdated' => $meta['updated'], + 'createdYear' => date('Y', $meta['created']), + 'createdMonth' => date('m', $meta['created']), + 'deleted' => $meta['deleted'], + 'menu' => $meta['menu'], + 'featured' => $meta['featured'], + 'published' => $meta['published'], + 'slug' => $meta['slug'], + 'filePath' => $file, + 'content' => $parsed->getContent(), + 'html' => $scrubbed, + 'media' => $media, + 'docs' => $files ]; //checks for duplicates - $uuid = $meta["uuid"]; + $uuid = $meta['uuid']; $found = current( array_filter($contents, function ($item) use ($uuid) { - return isset($item["uuid"]) && $uuid == $item["uuid"]; + return isset($item['uuid']) && $uuid == $item['uuid']; }) ); @@ -172,7 +170,7 @@ class Contents array_push($contents, $page); } } - $contents = orderBy($contents, ["id"], ["desc"]); + $contents = orderBy($contents, ['id'], ['desc']); return $contents; } } diff --git a/brain/data/Member.php b/brain/data/Member.php index 00e342f..fa1e7f4 100644 --- a/brain/data/Member.php +++ b/brain/data/Member.php @@ -2,10 +2,7 @@ namespace brain\data; -use brain\data\Settings; -use brain\data\Session; use brain\utility\DocTools; - use function _\find; class Member @@ -13,12 +10,11 @@ class Member public function __construct() { } - public static function verifyKey(string $key) { if (isset($key)) { $folks = (new Settings())->getFolks(); - $found = find($folks, ["key" => $key]); + $found = find($folks, ['key' => $key]); if ($found) { return true; } else { @@ -28,35 +24,34 @@ class Member return false; } } - public static function updateData(string $key, string $data, $secret = null) { $folks = (new Settings())->getFolks(); if (isset($secret)) { - $found = find($folks, ["secret" => $secret]); + $found = find($folks, ['secret' => $secret]); } else { - $member = Session::get("member"); - $found = find($folks, ["handle" => $member["handle"]]); + $member = Session::get('member'); + $found = find($folks, ['handle' => $member['handle']]); } $found[$key] = $data; //record time updated - $updated = new \Moment\Moment(); - $found["updated"] = $updated->format("Y-m-d\TH:i:sP"); - $newFolks = []; + $updated = new \Moment\Moment(); + $found['updated'] = $updated->format("Y-m-d\TH:i:sP"); + $newFolks = []; array_push($newFolks, $found); //save updated file - DocTools::writeSettings("../config/folks.json", $newFolks); + DocTools::writeSettings('../config/folks.json', $newFolks); //update member data in session if (!isset($secret)) { $member = [ - "handle" => $found["handle"], - "email" => $found["email"], - "role" => $found["role"], - "avatar" => $found["avi"], - "key" => $found["key"], + 'handle' => $found['handle'], + 'email' => $found['email'], + 'role' => $found['role'], + 'avatar' => $found['avi'], + 'key' => $found['key'], ]; - Session::set("member", $member); + Session::set('member', $member); } } } diff --git a/brain/data/Render.php b/brain/data/Render.php index 9fecabe..83916af 100644 --- a/brain/data/Render.php +++ b/brain/data/Render.php @@ -2,12 +2,8 @@ namespace brain\data; -use Mni\FrontYAML\Parser; -use brain\data\Settings; -use brain\data\Book; use brain\utility\Sorting; use brain\utility\DocTools; - use function _\find; class Render @@ -17,38 +13,37 @@ class Render public $pageInfo; public $menu; public $background; + public function __construct() { $config = new Settings(); //TODO: Add theme folder to loader - $settings = $config->getSettings(); - $this->menu = $settings["menu"]; - $this->theme = $settings["global"]["theme"]; - $this->loader = new \Twig\Loader\FilesystemLoader("../content/themes/" . $this->theme); - $this->twig = new \Twig\Environment($this->loader, []); + $settings = $config->getSettings(); + $this->menu = $settings['menu']; + $this->theme = $settings['global']['theme']; + $this->loader = new \Twig\Loader\FilesystemLoader('../content/themes/' . $this->theme); + $this->twig = new \Twig\Environment($this->loader, []); $this->pageInfo = [ - "keywords" => isset($settings["global"]["keywords"]) - ? $settings["global"]["keywords"] - : "fipamo, blog, jamstack, php, markdown, js", - "description" => $settings["global"]["descriptions"], - "image" => - $settings["global"]["base_url"] . $settings["global"]["background"], - "baseURL" => $settings["global"]["base_url"], + 'keywords' => isset($settings['global']['keywords']) + ? $settings['global']['keywords'] + : 'fipamo, blog, jamstack, php, markdown, js', + 'description' => $settings['global']['descriptions'], + 'image' => $settings['global']['base_url'] . $settings['global']['background'], + 'baseURL' => $settings['global']['base_url'], ]; //move global theme image assets to public folder - foreach ( - new \DirectoryIterator("../content/themes/" . $this->theme . "/assets/images/global/") as $file + foreach (new \DirectoryIterator('../content/themes/' . $this->theme . '/assets/images/global/') as $file ) { if ($file->isDot()) { continue; } - if (!is_file("../public/assets/images/global/" . $file->getFileName())) { + if (!is_file('../public/assets/images/global/' . $file->getFileName())) { copy( - "../content/themes/" . + '../content/themes/' . $this->theme . - "/assets/images/global/" . + '/assets/images/global/' . $file->getFileName(), - "../public/assets/images/global/" . $file->getFileName() + '../public/assets/images/global/' . $file->getFileName() ); } else { //image is already there, so chill @@ -72,56 +67,54 @@ class Render $scripts = glob('../public/assets/scripts/*'); // get all file names foreach ($scripts as $file) { // iterate files if (is_file($file)) { - if (!$file == "../public/assets/scripts/Start.js") { + if (!$file == '../public/assets/scripts/Start.js') { unlink($file); // delete file } } } //copy theme assets to public - $newcss = glob("../content/themes/" . $this->theme . "/assets/css/*"); + $newcss = glob('../content/themes/' . $this->theme . '/assets/css/*'); foreach ($newcss as $file) { // iterate files if (is_file($file)) { - $path = explode("/", $file); - copy($file, "../public/assets/css/" . $path[6]); + $path = explode('/', $file); + copy($file, '../public/assets/css/' . $path[6]); } } - $newjs = glob("../content/themes/" . $this->theme . "/assets/scripts/*"); + $newjs = glob('../content/themes/' . $this->theme . '/assets/scripts/*'); foreach ($newjs as $file) { // iterate files if (is_file($file)) { - $path = explode("/", $file); - copy($file, "../public/assets/scripts/" . $path[6]); + $path = explode('/', $file); + copy($file, '../public/assets/scripts/' . $path[6]); } } } - public function renderPages() { - $pages = (new Book())->getContents(); - $recent = []; + $pages = (new Book())->getContents(); + $recent = []; $featured = []; - $limit = 4; + $limit = 4; foreach ($pages as $page) { $pageOptions = Sorting::page($page); - $layout = $page["layout"]; + $layout = $page['layout']; //new pages have no layout, so defautl for now - if ($layout == "" || $layout == null) { - $layout = "page"; + if ($layout == '' || $layout == null) { + $layout = 'page'; } - $template = $layout . ".twig"; - if (str_contains($page["layout"], "index")) { - $location = "../public/index.html"; - $dir = null; + $template = $layout . '.twig'; + if (str_contains($page['layout'], 'index')) { + $location = '../public/index.html'; + $dir = null; } else { // if page is a menu item, render the page on public root - if ($page["menu"] == "true") { - $location = "../public/" . $page["slug"] . ".html"; - $dir = "../public/"; + if ($page['menu'] == 'true') { + $location = '../public/' . $page['slug'] . '.html'; + $dir = '../public/'; } else { - $location = - "../public/" . $page["path"] . "/" . $page["slug"] . ".html"; - $dir = "../public/" . $page["path"]; + $location = '../public/' . $page['path'] . '/' . $page['slug'] . '.html'; + $dir = '../public/' . $page['path']; } } @@ -129,75 +122,72 @@ class Render DocTools::writeHTML($location, $html, $dir); } } - public function renderArchive() { - $archive = Sorting::archive(); - $template = "archive.twig"; + $archive = Sorting::archive(); + $template = 'archive.twig'; $pageOptions = [ - "title" => "Archive", - "background" => $this->pageInfo["image"], - "archives" => $archive, - "info" => $this->pageInfo, - "menu" => $this->menu, + 'title' => 'Archive', + 'background' => $this->pageInfo['image'], + 'archives' => $archive, + 'info' => $this->pageInfo, + 'menu' => $this->menu, ]; - $html = $this->twig->render($template, $pageOptions); - $location = "../public/archives.html"; + $html = $this->twig->render($template, $pageOptions); + $location = '../public/archives.html'; DocTools::writeHTML($location, $html); } - public function renderTags() { $list = Sorting::tags(); foreach ($list as $item) { - $template = "tags.twig"; + $template = 'tags.twig'; $pageOptions = [ - "title" => "Pages Tagged as " . $item["tag_name"], - "background" => $this->pageInfo["image"], - "tag_list" => $item["pages"], - "info" => $this->pageInfo, - "menu" => $this->menu, + 'title' => 'Pages Tagged as ' . $item['tag_name'], + 'background' => $this->pageInfo['image'], + 'tag_list' => $item['pages'], + 'info' => $this->pageInfo, + 'menu' => $this->menu, ]; $html = $this->twig->render($template, $pageOptions); - $location = "../public/tags/" . $item["slug"] . ".html"; + $location = '../public/tags/' . $item['slug'] . '.html'; //if tags folder doesn't exist, make it - if (!is_dir("../public/tags")) { - mkdir("../public/tags", 0755, true); + if (!is_dir('../public/tags')) { + mkdir('../public/tags', 0755, true); } else { } if (!is_file($location)) { file_put_contents($location, $html); } else { - ($new = fopen($location, "w")) or die("Unable to open file!"); + ($new = fopen($location, 'w')) or die('Unable to open file!'); fwrite($new, $html); fclose($new); } } } - public function renderIndex() { //TODO: Need to fix this to account for new index templating system - $pages = (new Book())->getContents(); - $index = find($pages, ["layout" => "index"]); - $template = "index.twig"; - $location = "../public/index.html"; - $dir = null; + $pages = (new Book())->getContents(); + $index = find($pages, ['layout' => 'index']); + $template = 'index.twig'; + $location = '../public/index.html'; + $dir = null; $meta = [ - "who" => $index["author"], - "when" => $index["created"], + 'who' => $index['author'], + 'when' => $index['created'], ]; $pageOptions = [ - "title" => $index["title"], - "background" => $index["feature"], - "meta" => $meta, + 'title' => $index['title'], + 'background' => $index['feature'], + 'meta' => $meta, ]; $html = $this->twig->render($template, $pageOptions); diff --git a/brain/data/Session.php b/brain/data/Session.php index b4a0561..dc8d7b8 100644 --- a/brain/data/Session.php +++ b/brain/data/Session.php @@ -4,41 +4,38 @@ namespace brain\data; use ReallySimpleJWT\Token; -use function _\find; - class Session { - private static $file = "../content/.session"; + private static $file = '../content/.session'; private static $data = [ - "member" => "", - "token" => "", - "form_token" => "", + 'member' => '', + 'token' => '', + 'form_token' => '', ]; + public static function start() { if (!is_file(self::$file)) { file_put_contents(self::$file, json_encode(self::$data)); } else { - ($new = fopen(self::$file, "w")) or die("Unable to open file!"); + ($new = fopen(self::$file, 'w')) or die('Unable to open file!'); fwrite($new, json_encode(self::$data)); fclose($new); } } - public static function active() { if (!is_file(self::$file)) { return false; } else { $data = json_decode(file_get_contents(self::$file), true); - if ($data["member"] != null) { - $secret = (new Settings())->getFolks("secret"); + if ($data['member'] != null) { + $secret = (new Settings())->getFolks('secret'); if ($secret == null) { return false; } else { - if ( - Token::validate($data["token"], $secret) && - Token::validateExpiration($data["token"], $secret) + if (Token::validate($data['token'], $secret) && + Token::validateExpiration($data['token'], $secret) ) { return true; } else { @@ -50,14 +47,12 @@ class Session } } } - public static function verifyToken($token) { $data = json_decode(file_get_contents(self::$file), true); - if ($data["member"] != null) { - $secret = (new Settings())->getFolks("secret"); - if ( - Token::validate($token, $secret) && + if ($data['member'] != null) { + $secret = (new Settings())->getFolks('secret'); + if (Token::validate($token, $secret) && Token::validateExpiration($token, $secret) ) { return true; @@ -68,26 +63,23 @@ class Session return false; } } - public static function set($key, $value) { - $data = json_decode(file_get_contents(self::$file), true); + $data = json_decode(file_get_contents(self::$file), true); $data[$key] = $value; - ($fresh = fopen(self::$file, "w")) or die("Unable to open file!"); + ($fresh = fopen(self::$file, 'w')) or die('Unable to open file!'); fwrite($fresh, json_encode($data)); fclose($fresh); } - public static function get($key) { $data = json_decode(file_get_contents(self::$file), true); return $data[$key]; } - public static function kill() { - ($fresh = fopen(self::$file, "w")) or die("Unable to open file!"); + ($fresh = fopen(self::$file, 'w')) or die('Unable to open file!'); fwrite($fresh, json_encode(self::$data)); fclose($fresh); } diff --git a/brain/data/Settings.php b/brain/data/Settings.php index 71b3c21..8ad9102 100644 --- a/brain/data/Settings.php +++ b/brain/data/Settings.php @@ -2,10 +2,8 @@ namespace brain\data; -use brain\data\Member; use brain\utility\DocTools; use brain\utility\Sorting; - use function _\find; use function _\pull; use function _\remove; @@ -19,92 +17,88 @@ class Settings public function __construct() { //gets all settings files and converts to php objects - $this->folks = json_decode(file_get_contents("../config/folks.json"), true); - self::$tags = json_decode(file_get_contents("../config/tags.json"), true); + $this->folks = json_decode(file_get_contents('../config/folks.json'), true); + self::$tags = json_decode(file_get_contents('../config/tags.json'), true); self::$settings = json_decode( - file_get_contents("../config/settings.json"), + file_get_contents('../config/settings.json'), true ); } - public static function sync($data) { - $settings = self::$settings; - $settings["global"]["base_url"] = $data["global"]["base_url"]; - $settings["global"]["title"] = $data["global"]["title"]; - $settings["global"]["descriptions"] = $data["global"]["descriptions"]; - $settings["global"]["base_url"] = $data["global"]["base_url"]; - $settings["global"]["private"] = $data["global"]["private"]; - $settings["global"]["renderOnSave"] = $data["global"]["renderOnSave"]; - $settings["global"]["theme"] = $data["global"]["theme"]; - $settings["global"]["externalAPI"] = $data["global"]["externalAPI"]; - $settings["global"]["dynamicRender"] = $data["global"]["dynamicRender"]; + $settings = self::$settings; + $settings['global']['base_url'] = $data['global']['base_url']; + $settings['global']['title'] = $data['global']['title']; + $settings['global']['descriptions'] = $data['global']['descriptions']; + $settings['global']['base_url'] = $data['global']['base_url']; + $settings['global']['private'] = $data['global']['private']; + $settings['global']['renderOnSave'] = $data['global']['renderOnSave']; + $settings['global']['theme'] = $data['global']['theme']; + $settings['global']['externalAPI'] = $data['global']['externalAPI']; + $settings['global']['dynamicRender'] = $data['global']['dynamicRender']; - Member::updateData("handle", $data["member"]["handle"]); - Member::updateData("email", $data["member"]["email"]); + Member::updateData('handle', $data['member']['handle']); + Member::updateData('email', $data['member']['email']); - $settings["email"]["active"] = $data["email"]["active"]; - $settings["email"]["smtp"] = $data["email"]["smtp"]; - $settings["email"]["mailgun"] = $data["email"]["mailgun"]; + $settings['email']['active'] = $data['email']['active']; + $settings['email']['smtp'] = $data['email']['smtp']; + $settings['email']['mailgun'] = $data['email']['mailgun']; - DocTools::writeSettings("../config/settings.json", $settings); + DocTools::writeSettings('../config/settings.json', $settings); } - public static function navSync($data) { $settings = self::$settings; - $remove = $data["remove"]; + $remove = $data['remove']; //if remove contains id, find nav item page and set menu to false - if ($remove != null || $remove != "") { - $page = (new Book("../content/pages"))->findPageById($remove); - $page["menu"] = "false"; - $page["published"] - ? ($page["published"] = "true") - : ($page["published"] = "false"); - $page["featured"] - ? ($page["featured"] = "true") - : ($page["featured"] = "false"); - $page["deleted"] - ? ($page["deleted"] = "true") - : ($page["deleted"] = "false"); - $updated = new \Moment\Moment(); - $created = new \Moment\Moment($page["rawCreated"]); - $page["created"] = $created->format("Y-m-d\TH:i:sP"); - $page["updated"] = $updated->format("Y-m-d\TH:i:sP"); + if ($remove != null || $remove != '') { + $page = (new Book('../content/pages'))->findPageById($remove); + $page['menu'] = 'false'; + $page['published'] + ? ($page['published'] = 'true') + : ($page['published'] = 'false'); + $page['featured'] + ? ($page['featured'] = 'true') + : ($page['featured'] = 'false'); + $page['deleted'] + ? ($page['deleted'] = 'true') + : ($page['deleted'] = 'false'); + $updated = new \Moment\Moment(); + $created = new \Moment\Moment($page['rawCreated']); + $page['created'] = $created->format("Y-m-d\TH:i:sP"); + $page['updated'] = $updated->format("Y-m-d\TH:i:sP"); $md = DocTools::objectToMD($page); - if ($page["layout"] == "index") { - $writePath = "../content/pages/start/index.md"; + if ($page['layout'] == 'index') { + $writePath = '../content/pages/start/index.md'; } else { - $writePath = - "../content/pages/" . $page["path"] . "/" . $page["slug"] . ".md"; + $writePath = '../content/pages/' . $page['path'] . '/' . $page['slug'] . '.md'; } - DocTools::writePages("write", $page["path"], $writePath, $md); + DocTools::writePages('write', $page['path'], $writePath, $md); } - $settings["menu"] = []; - $items = $data["menu"]; + $settings['menu'] = []; + $items = $data['menu']; foreach ($items as $item) { - array_push($settings["menu"], [ - "title" => $item["title"], - "id" => $item["id"], - "uuid" => $item["uuid"], - "slug" => $item["slug"], - "path" => $item["path"], + array_push($settings['menu'], [ + 'title' => $item['title'], + 'id' => $item['id'], + 'uuid' => $item['uuid'], + 'slug' => $item['slug'], + 'path' => $item['path'], ]); } - DocTools::writeSettings("../config/settings.json", $settings); + DocTools::writeSettings('../config/settings.json', $settings); } - public function getFolks($key = null) { if (isset($key)) { - $member = Session::get("member"); - $found = find($this->folks, ["handle" => $member["handle"]]); + $member = Session::get('member'); + $found = find($this->folks, ['handle' => $member['handle']]); if ($found) { return $found[$key]; } @@ -112,66 +106,58 @@ class Settings return $this->folks; } } - public function getSettings($key = null) { return self::$settings; } - public static function getTags() { return self::$tags; } - public static function updateGlobalData($key, $data) { - $settings = self::$settings; - $settings["global"][$key] = $data; - DocTools::writeSettings("../config/settings.json", $settings); + $settings = self::$settings; + $settings['global'][$key] = $data; + DocTools::writeSettings('../config/settings.json', $settings); } - public static function getCurrentIndex() { $settings = self::$settings; - return $settings["library_stats"]["current_index"]; + return $settings['library_stats']['current_index']; } - public static function updateIndex() { $settings = self::$settings; - $settings["library_stats"]["current_index"] = - $settings["library_stats"]["current_index"] + 1; + $settings['library_stats']['current_index'] = $settings['library_stats']['current_index'] + 1; - DocTools::writeSettings("../config/settings.json", $settings); + DocTools::writeSettings('../config/settings.json', $settings); } - public static function updateMenu($body) { $settings = self::$settings; //$menu = $settings["menu"]; $item = [ - "title" => $body["title"], - "id" => $body["id"], - "uuid" => $body["uuid"], - "slug" => $body["slug"], - "path" => $body["path"], + 'title' => $body['title'], + 'id' => $body['id'], + 'uuid' => $body['uuid'], + 'slug' => $body['slug'], + 'path' => $body['path'], ]; - if ($body["menu"] == "true") { - if (!find($settings["menu"], ["uuid" => $item["uuid"]])) { - array_push($settings["menu"], $item); + if ($body['menu'] == 'true') { + if (!find($settings['menu'], ['uuid' => $item['uuid']])) { + array_push($settings['menu'], $item); } } else { - if (find($settings["menu"], ["uuid" => $item["uuid"]])) { - pull($settings["menu"], $item); + if (find($settings['menu'], ['uuid' => $item['uuid']])) { + pull($settings['menu'], $item); } } - DocTools::writeSettings("../config/settings.json", $settings); + DocTools::writeSettings('../config/settings.json', $settings); } - public static function updateTags() { $tags = Sorting::tags(); - DocTools::writeSettings("../config/tags.json", $tags); + DocTools::writeSettings('../config/tags.json', $tags); } } diff --git a/brain/data/Themes.php b/brain/data/Themes.php index 3c15bf4..f8897b8 100644 --- a/brain/data/Themes.php +++ b/brain/data/Themes.php @@ -2,60 +2,55 @@ namespace brain\data; -use brain\data\Settings; - class Themes { private $themes = []; public function __construct() { - $_themes = glob("../content/themes/*", GLOB_ONLYDIR); + $_themes = glob('../content/themes/*', GLOB_ONLYDIR); foreach ($_themes as $theme) { array_push( $this->themes, - json_decode(file_get_contents($theme . "/theme.json"), true) + json_decode(file_get_contents($theme . '/theme.json'), true) ); } } - public function getThemes() { return $this->themes; } - public function getCustomIndex() { - $settings = (new Settings())->getSettings(); - $currentTheme = $settings["global"]["theme"]; - $folder = "../content/themes/" . $currentTheme; - $files = array_filter(glob("$folder/*twig"), "is_file"); - $views = []; + $settings = (new Settings())->getSettings(); + $currentTheme = $settings['global']['theme']; + $folder = '../content/themes/' . $currentTheme; + $files = array_filter(glob("$folder/*twig"), 'is_file'); + $views = []; foreach ($files as $file) { - $path = explode("/", $file); + $path = explode('/', $file); $fileName = $path[4]; - if (str_contains($fileName, "index")) { - $page = explode(".", $fileName); + if (str_contains($fileName, 'index')) { + $page = explode('.', $fileName); $views[] = $page[0]; } } return $views; } - public function getCustomViews() { - $settings = (new Settings())->getSettings(); - $currentTheme = $settings["global"]["theme"]; - $folder = "../content/themes/" . $currentTheme; - $files = array_filter(glob("$folder/*twig"), "is_file"); - $views = []; + $settings = (new Settings())->getSettings(); + $currentTheme = $settings['global']['theme']; + $folder = '../content/themes/' . $currentTheme; + $files = array_filter(glob("$folder/*twig"), 'is_file'); + $views = []; foreach ($files as $file) { - $path = explode("/", $file); + $path = explode('/', $file); $fileName = $path[4]; - if (str_contains($fileName, "page")) { - $page = explode(".", $fileName); + if (str_contains($fileName, 'page')) { + $page = explode('.', $fileName); $views[] = $page[0]; } } diff --git a/brain/init/App.php b/brain/init/App.php index 6674ddd..8b0d650 100644 --- a/brain/init/App.php +++ b/brain/init/App.php @@ -14,7 +14,7 @@ class App // when a new class is made, run composer dump-autoload // set up cors new HandleCors(); - $app = AppFactory::create(); + $app = AppFactory::create(); $twig = Twig::create('../brain/views/'); $app->add(TwigMiddleware::create($app, $twig)); // set up routing diff --git a/brain/utility/DocTools.php b/brain/utility/DocTools.php index 72e2c12..55ddd92 100644 --- a/brain/utility/DocTools.php +++ b/brain/utility/DocTools.php @@ -7,18 +7,17 @@ class DocTools public function __construct() { } - public static function writePages($task, $path, $fileLocation, $fileContents) { try { - if ($task == "create") { - if (!is_dir("../content/pages/" . $path)) { + if ($task == 'create') { + if (!is_dir('../content/pages/' . $path)) { //Directory does not exist, so lets create it. - mkdir("../content/pages/" . $path, 0755, true); + mkdir('../content/pages/' . $path, 0755, true); } file_put_contents($fileLocation, $fileContents); } else { - ($new = fopen($fileLocation, "w")) or die("Unable to open file!"); + ($new = fopen($fileLocation, 'w')) or die('Unable to open file!'); fwrite($new, $fileContents); fclose($new); } @@ -28,18 +27,16 @@ class DocTools return false; } } - public static function writeSettings($fileLocation, $fileContents) { if (!is_file($fileLocation)) { file_put_contents($fileLocation, json_encode($fileContents)); } else { - ($new = fopen($fileLocation, "w")) or die("Unable to open file!"); + ($new = fopen($fileLocation, 'w')) or die('Unable to open file!'); fwrite($new, json_encode($fileContents)); fclose($new); } } - public static function writeHTML($location, $html, $path = null) { if ($path != null) { @@ -51,12 +48,11 @@ class DocTools if (!is_file($location)) { file_put_contents($location, $html); } else { - ($new = fopen($location, "w")) or die("Unable to open file!"); + ($new = fopen($location, 'w')) or die('Unable to open file!'); fwrite($new, $html); fclose($new); } } - public static function deleteFolder($path) { if (!empty($path) && is_dir($path)) { @@ -83,62 +79,60 @@ class DocTools rmdir($path); } } - public static function objectToMD($object) { - $markdown = - "---\n" . - "id: " . - $object["id"] . + $markdown = "---\n" . + 'id: ' . + $object['id'] . "\n" . - "uuid: " . - $object["uuid"] . + 'uuid: ' . + $object['uuid'] . "\n" . - "title: " . + 'title: ' . "'" . - $object["title"] . + $object['title'] . "'" . "\n" . - "feature: " . - $object["feature"] . + 'feature: ' . + $object['feature'] . "\n" . - "files: " . - $object["files"] . + 'files: ' . + $object['files'] . "\n" . - "path: " . - $object["path"] . + 'path: ' . + $object['path'] . "\n" . - "layout: " . - $object["layout"] . + 'layout: ' . + $object['layout'] . "\n" . - "tags: " . - $object["tags"] . + 'tags: ' . + $object['tags'] . "\n" . - "author: " . - $object["author"] . + 'author: ' . + $object['author'] . "\n" . - "created: " . - $object["created"] . + 'created: ' . + $object['created'] . "\n" . - "updated: " . - $object["updated"] . + 'updated: ' . + $object['updated'] . "\n" . - "deleted: " . - $object["deleted"] . + 'deleted: ' . + $object['deleted'] . "\n" . - "slug: " . - $object["slug"] . + 'slug: ' . + $object['slug'] . "\n" . - "menu: " . - $object["menu"] . + 'menu: ' . + $object['menu'] . "\n" . - "published: " . - $object["published"] . + 'published: ' . + $object['published'] . "\n" . - "featured: " . - $object["featured"] . + 'featured: ' . + $object['featured'] . "\n---\n" . - $object["content"]; + $object['content']; return $markdown; } diff --git a/brain/utility/FileUploader.php b/brain/utility/FileUploader.php index c40b2a5..6790f4a 100644 --- a/brain/utility/FileUploader.php +++ b/brain/utility/FileUploader.php @@ -21,9 +21,9 @@ class FileUploader // echo "**FILE** " . $file->getClientFileName(); - $file->moveTo($directory.'/'.urlencode($file->getClientFileName())); + $file->moveTo($directory . '/' . urlencode($file->getClientFileName())); } catch (RuntimeException $e) { - echo 'ERROR '.$e->getMessage(); + echo 'ERROR ' . $e->getMessage(); // echo "failed to upload image: " . $e->getMessage(); // throw new Error("Failed to upload image file"); diff --git a/brain/utility/HandleCors.php b/brain/utility/HandleCors.php index 7082fdd..78207e4 100644 --- a/brain/utility/HandleCors.php +++ b/brain/utility/HandleCors.php @@ -9,37 +9,38 @@ class HandleCors public function __construct() { //look to see if settings file exists. kinda important - if (file_exists("../config/settings.json")) { + if (file_exists('../config/settings.json')) { //check settings to see if external api access is allowed - $config = new Settings(); + $config = new Settings(); $settings = $config->getSettings(); - if ($settings["global"]["externalAPI"]) { + if ($settings['global']['externalAPI']) { //echo "API STATUS: " . $settings["global"]["externalAPI"]; - if ($settings["global"]["externalAPI"] == "true") { + if ($settings['global']['externalAPI'] == 'true') { //echo "API ACCESS ACTIVE"; // checks to see if origin is set - if (isset($_SERVER["HTTP_ORIGIN"])) { - // You can decide if the origin in $_SERVER['HTTP_ORIGIN'] is something you want to allow, or as we do here, just allow all - header("Access-Control-Allow-Origin: {$_SERVER["HTTP_ORIGIN"]}"); + if (isset($_SERVER['HTTP_ORIGIN'])) { + // You can decide if the origin in $_SERVER['HTTP_ORIGIN'] + //is something you want to allow, or as we do here, just allow all + header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); } else { //No HTTP_ORIGIN set, so we allow any. You can disallow if needed here //never allow just any domain, so turn CORS off if no No HTTP_ORIGIN is set //header("Access-Control-Allow-Origin: *"); } - header("Access-Control-Allow-Credentials: true"); - header("Access-Control-Max-Age: 600"); // cache for 10 minutes + header('Access-Control-Allow-Credentials: true'); + header('Access-Control-Max-Age: 600'); // cache for 10 minutes - if ($_SERVER["REQUEST_METHOD"] == "OPTIONS") { - if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"])) { + if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { + if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) { header( - "Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT" + 'Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT' ); } //Make sure you remove those you do not want to support - if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"])) { + if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) { header( - "Access-Control-Allow-Headers: {$_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]}" + "Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}" ); } diff --git a/brain/utility/Mailer.php b/brain/utility/Mailer.php index 81bec42..1c4afa1 100644 --- a/brain/utility/Mailer.php +++ b/brain/utility/Mailer.php @@ -2,7 +2,6 @@ namespace brain\utility; -use Slim\Views\Twig; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; use brain\data\Settings; @@ -12,60 +11,58 @@ class Mailer { public static function sendMail($body) { - $config = new Settings(); - $settings = $config->getSettings(); - $mailConfig = $settings["email"]; - $mail = new PHPMailer(); + $config = new Settings(); + $settings = $config->getSettings(); + $mailConfig = $settings['email']; + $mail = new PHPMailer(); - switch ($body["mail_task"]) { - case "TESTING": - $html = - "