diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cd2946a --- /dev/null +++ b/.gitignore @@ -0,0 +1,47 @@ +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# ========================= +# Operating System Files +# ========================= + +# OSX +# ========================= + +.DS_Store +.AppleDouble +.LSOverride + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..2725688 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at webmaster@thetempusproject.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..161cfab --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,87 @@ +# Contribution Guidelines for Bedrock +Contributing to Bedrock is completely voluntary and should follow all of the guidelines listed here in order to ensure the highest probability of acceptance. It is highly recommended to use a php linter to automate more of this process. The project is maintained on github and all contributions need to be submitted via pull request to their specific repository under the `dev` branch. In order to contribute, simply follow the instructions for [creating a pull request](#creating-a-pull-request) below. + +## Pull Request Requirements +- All revisions must follow TTP naming conventions (see [Naming Conventions](#naming-conventions) Section) +- Include a clear and concise explanation of the features or changes included in your revision listed by file. +- All code must follow [PSR 2](http://www.php-fig.org/psr/psr-2/) standards +- prefer the use of [] for arrays over array() +- All functions must be documented with the exception of controller methods (see [Documentation](#documentation) Section) +- Controller methods may be doc-blocked when necessary for clarity (see [Documentation](#documentation) Section) +- All new Classes must include a class level doc-block (see [Documentation](#documentation) Section) +- Any new dependencies will have a longer validation process and should be accompanied by the required information (see [Dependencies](#dependencies) Section) + +## Naming Conventions +- File names are to be lower case +- All class names must be upper case +- Any data being stored as a file must be saved in the app directory (with the exception of config which should be stored under config/) +- Controllers must have a constructor and destructor using the constructor and destructor methods found in resources/ +- Views must be named using lowerCamelCase + +## Dependencies +Whenever a dependency is updated or added, pull requests must include a section that answers the following questions. +- Why is this dependency required +- Could this be reasonably accomplished within the app by implementing new features in a later version? explain. +- What is the latest stable version that can be used +- What features are absolutely necessary for your feature or modification to work + +## Documentation +### Classes + +New classes must be prefaced with a doc-block following this style: +``` +/** + * Controllers/admin.php + * + * This is the admin controller. + * + * @version 3.0 + * @author Joey Kimsey + * @link https://TheTempusProject.com/Core + * @license https://opensource.org/licenses/MIT [MIT LICENSE] + */ +``` + +From top to bottom: +- Filename on the second line +- A description for the file +- The TTP version this file was built for +`@version 1.0` +- The Authors name or alias and email +`@author first last ` +- A copy of the MIT license +`@license https://opensource.org/licenses/MIT [MIT LICENSE]` +- May include a link for more information +`@link http://link.com` + +### Functions +Functions must be prefaced with a doc-block following this style: +``` +/** + * Intended as a self-destruct session. If the specified session does not + * exist, it is created. If the specified session does exist, it will be + * destroyed and returned. + * + * @param string $name - Session name to be created or checked + * @param string $string - The string to be used if session needs to be + * created. (optional) + * + * @return bool|string - Returns bool if creating, and a string if the + * check is successful. + */ +``` + +From top to bottom: +- There must be a description of the functions intended usage on the second line +- All parameters should be documented like this +`@param [type] $name - description` +- Any function with a return statement must also be documented as such +`@return [type] - description` + +## Creating a Pull Request +This is a simple explanation of how to create a pull request for changes to Bedrock. You can find a detailed walk-through on how to [create a pull request](https://help.github.com/articles/creating-a-pull-request/) on github. + +1. First ensure you have followed all the contributing guidelines +2. Squash your merge into a single revision. This will make it easier to view the changes as a whole. +3. You can submit a pull request [here](https://github.com/TheTempusProject/Bedrock/compare) +4. Please submit all pull requests to the dev branch or they will be ignored. \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..86794ec --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Joey Kimsey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index e5675ae..ce23a87 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,31 @@ -# Bedrock +# Tempus Project Core +###### Developer(s): Joey Kimsey +Bedrock is the core functionality used by [The Tempus Project](https://github.com/TheTempusProject/TheTempusProject) a rapid prototyping framework. This Library can be utilized outside of the TempusProject, but the functionality has not been tested well as a stand alone library. +This library utilizes the MVC architecture in addition to a custom templating engine designed to make building web applications fast and simple. -## Getting started +**Notice: This Library is provided as is, please use at your own risk.** -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +## Installation and Use +The easiest way to use Bedrock in your application is to install and initialize it via composer. ``` -cd existing_repo -git remote add origin https://170-187-142-254.ip.linodeusercontent.com/the-tempus-project/bedrock.git -git branch -M main -git push -uf origin main +"require": { + "TheTempusProject/Bedrock": "*", +}, + +"autoload": { + "psr-4": { + "Bedrock\": "vendor/TheTempusProject/Bedrock" + } +} ``` -## Integrate with your tools +If you prefer to handle auto-loading via other means, you can simply clone this repository wherever you need it. Please note, you will need to install and load the [TempusDebugger](https://github.com/thetempusproject/TempusDebugger) library in order to utilize the debug to console options. -- [ ] [Set up project integrations](https://170-187-142-254.ip.linodeusercontent.com/the-tempus-project/bedrock/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +### WIP: +- [ ] Expansion of PDO to allow different database types +- [ ] template stuff should really only be called from template/controllers +- [ ] Update installer to account for updates. +- [ ] Implement uniformity in terms of error reporting, exceptions, logging. diff --git a/bin/autoload.php b/bin/autoload.php new file mode 100644 index 0000000..389affe --- /dev/null +++ b/bin/autoload.php @@ -0,0 +1,52 @@ + + * @link https://TheTempusProject.com/Core + * @license https://opensource.org/licenses/MIT [MIT LICENSE] + */ +namespace TheTempusProject\Bedrock; + +use TheTempusProject\Hermes\Classes\Autoloader; + +if ( ! defined('BEDROCK_ROOT_DIRECTORY' ) ) { + define('BEDROCK_ROOT_DIRECTORY', dirname(__DIR__) . DIRECTORY_SEPARATOR); +} +if ( ! defined('BEDROCK_CONFIG_DIRECTORY' ) ) { + define('BEDROCK_CONFIG_DIRECTORY', BEDROCK_ROOT_DIRECTORY . 'config' . DIRECTORY_SEPARATOR); +} +if ( ! defined('BEDROCK_CONSTANTS_LOADED' ) ) { + require_once BEDROCK_CONFIG_DIRECTORY . 'constants.php'; +} +if ( ! class_exists( 'TheTempusProject\Bedrock\Classes\Autoloader' ) ) { + if ( file_exists( BEDROCK_CLASSES_DIRECTORY . 'autoloader.php' ) ) { + require_once BEDROCK_CLASSES_DIRECTORY . 'autoloader.php'; + } +} +if ( ! class_exists( 'TheTempusProject\Bedrock\App' ) ) { + if ( file_exists( BEDROCK_ROOT_DIRECTORY . 'app.php' ) ) { + require_once BEDROCK_ROOT_DIRECTORY . 'app.php'; + } +} + +$autoloader = new Autoloader; +$autoloader->setRootFolder( BEDROCK_ROOT_DIRECTORY ); +$autoloader->addNamespace( + 'TheTempusProject\Bedrock', + 'bin' +); +$autoloader->addNamespace( + 'TheTempusProject\Bedrock\Classes', + 'classes' +); +$autoloader->addNamespace( + 'TheTempusProject\Bedrock\Functions', + 'functions' +); +$autoloader->register(); + +define( 'BEDROCK_AUTOLOADED', true ); diff --git a/bin/bedrock.php b/bin/bedrock.php new file mode 100644 index 0000000..a7542c9 --- /dev/null +++ b/bin/bedrock.php @@ -0,0 +1,263 @@ + + * @link https://TheTempusProject.com/Core + * @license https://opensource.org/licenses/MIT [MIT LICENSE] + */ +namespace TheTempusProject\Bedrock; + +use TheTempusProject\Canary\Canary as Debug; +use TheTempusProject\Hermes\Functions\Route as Routes; +use TheTempusProject\Bedrock\Functions\Input; +use TheTempusProject\Bedrock\Functions\Check; +use TheTempusProject\Bedrock\Functions\Token; +use TheTempusProject\Bedrock\Functions\Sanitize; +use TheTempusProject\Bedrock\Classes\Config; +use TheTempusProject\Hermes\Classes\Autoloader; +use TheTempusProject\Houdini\Classes\Template; +use TheTempusProject\Houdini\Classes\Components; + +class Bedrock { + public static $controllerName = ''; + public static $methodName = ''; + public static $activeConfig = []; + protected $controllerObject = null; + protected $controllerClass = ''; + protected $params = []; + + /** + * The constructor handles the entire process of parsing the url, + * finding the controller/method, and calling the appropriate + * class/function for the application. + * + * @param string $url - A custom URL to be parsed to determine + * controller/method. (GET) url is used by + * default if none is provided + */ + public function __construct( $url = '' ) { + Debug::group( 'Bedrock Application' ); + ob_start(); + self::$activeConfig = new Config( CONFIG_JSON ); + set_error_handler( [ 'TheTempusProject\\Canary\\Canary', 'handle_error' ] ); + set_exception_handler( [ 'TheTempusProject\\Canary\\Canary', 'handle_exception' ] ); + self::$controllerName = DEFAULT_CONTROLLER_CLASS; + self::$methodName = DEFAULT_CONTROLLER_METHOD; + $this->setUrl( $url ); + } + + public function setUrl( $url ) { + if ( empty( $url ) ) { + Debug::log( 'Using GET url.' ); + $url = Input::get( 'url' ); + } + $trimmedUrl = trim( $url, '/' ); + $url = str_ireplace( '.php', '', $trimmedUrl ); + $urlArray = explode( '/', Sanitize::url( $url ) ); + $this->setVarsFromUrlArray( $urlArray ); + } + + public function load() { + $this->loadController(); + $this->loadPage(); + } + + public static function getUrl() { + return Routes::getAddress() . Input::get( 'url' ); + } + + protected function loadPage() { + if ( !method_exists( $this->controllerClass, self::$methodName ) ) { + return false; + } + Components::set( 'META_IMAGE', Routes::getAddress() . Config::getValue( 'main/logoLarge' ) ); + Components::set( 'CURRENT_URL', self::getCurrentUrl() ); + Components::set( 'SITENAME', Config::getValue( 'main/name' ) ); + Components::set( 'AUTHOR', '' ); + call_user_func_array( [ $this->controllerObject, self::$methodName ], $this->params ); + Components::set( 'TITLE', Template::parse( $this->controllerObject::$title ) ); + Components::set( 'PAGE_DESCRIPTION', Template::parse( $this->controllerObject::$pageDescription ) ); + Template::render(); + Debug::closeAllGroups(); + // self::$session->updatePage( self::getUrl() ); // where did this method go? + } + + protected function loadController() { + if ( empty( $this->controllerClass ) ) { + $this->controllerClass = (string) APP_SPACE . '\\Controllers\\' . self::$controllerName; + } + $this->controllerObject = new $this->controllerClass; + } + + protected function setController( $name, $namespace ) { + $controllerClass = $namespace . ucfirst( $name ); + if ( Autoloader::testLoad( $controllerClass ) ) { + $this->controllerClass = $controllerClass; + self::$controllerName = $name; + } + } + + protected function setPage( $name ) { + $name = strtolower( $name ); + if ( !method_exists( $this->controllerClass, $name ) ) { + Debug::info( 'setPage - Method not found: ' . $name ); + return false; + } + self::$methodName = $name; + } + + protected function setVarsFromUrlArray( $urlArray ) { + if ( !empty( $urlArray[0] ) ) { + $urlPart = array_shift( $urlArray ); + if ( $urlPart == 'admin' ) { + $namespace = APP_SPACE . '\\Controllers\\Admin\\'; + if ( empty( $urlArray[0] ) ) { + // if there is no second param, assume they want the home controller + $urlPart = 'home'; + } else { + $urlPart = array_shift( $urlArray ); // to drop the admin + } + if ( $urlPart == 'index' ) { + // if its admin/index, again, assume the home controller + $urlPart = 'home'; + } + } elseif ( $urlPart == 'api' ) { + $namespace = APP_SPACE . '\\Controllers\\Api\\'; + if ( empty( $urlArray[0] ) ) { + // if there is no second param, assume they want the home controller + $urlPart = 'home'; + } else { + $urlPart = array_shift( $urlArray ); // to drop the admin + } + if ( $urlPart == 'index' ) { + // if its admin/index, again, assume the home controller + $urlPart = 'home'; + } + } else { + $namespace = APP_SPACE . '\\Controllers\\'; + } + $this->setController( $urlPart, $namespace ); + } + if ( !empty( $urlArray[0] ) ) { + $urlPart = array_shift( $urlArray ); + $this->setPage( $urlPart ); + } + if ( !empty( $urlArray ) ) { + $this->params = array_values( $urlArray ); + } + } + + public static function getCurrentUrl() { + return Sanitize::url( Input::get( 'url' ) ); + } + + protected function printDebug() { + echo '
'; + echo '

PHP Info

'; + echo ''; + echo ''; + echo ''; + echo ''; + echo '
PHP version: ' . phpversion() . '
PDO Loaded version: ' . extension_loaded( 'pdo' ) . '
PHP extensions:
';
+        foreach ( get_loaded_extensions() as $i => $ext ) {
+            echo $ext . ' => ' . phpversion( $ext ) . '
'; + } + echo '

'; + echo '

Tempus Core Info

'; + echo ''; + // Just in case + echo ''; + // Checks + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + // Routes + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + // Debugging + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + // Main + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + // Constants + echo ''; + // Debugging + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + // Tempus Debugger + echo ''; + echo ''; + echo ''; + // Tokens + echo ''; + echo ''; + echo ''; + // Cookies + echo ''; + echo ''; + echo ''; + // Directories + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + // other + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo '
_SERVER:
';
+        echo var_export( $_SERVER, true );
+        echo '

Checks

Uploads work?: ' . var_export( Check::uploads(), true ) . '
PHP: ' . var_export( Check::php(), true ) . '
Mail works?: ' . var_export( Check::mail(), true ) . '
Is safe mode?: ' . var_export( Check::safe(), true ) . '
Sessions work?: ' . var_export( Check::sessions(), true ) . '
Cookies work?: ' . var_export( Check::cookies(), true ) . '
is Apache?: ' . var_export( Check::isApache(), true ) . '
is Nginx?: ' . var_export( Check::isNginx(), true ) . '
Is token enabled?: ' . var_export( Token::isTokenEnabled(), true ) . '

Routes

Root: ' . var_export( Routes::getRoot(), true ) . '
Address: ' . var_export( Routes::getAddress(), true ) . '
Protocol: ' . var_export( Routes::getProtocol(), true ) . '
App URL: ' . var_export( self::getUrl(), true ) . '

Debugging

Console Debugging Enabled: ' . var_export( Debug::status( 'console' ), true ) . '
Debug Trace Enabled: ' . var_export( Debug::status( 'trace' ), true ) . '
Debugging Enabled: ' . var_export( Debug::status( 'debug' ), true ) . '
Rendering Enabled: ' . var_export( Debug::status( 'render' ), true ) . '

Main App Variables

Template Location: ' . var_export( Template::getLocation(), true ) . '
Configuration:
' . var_export( Config::$config, true ) . '
Check Errors:
' . var_export( Check::systemErrors(), true ) . '
GET:
' . var_export( $_GET, true ) . '

Constants

Debugging:
HERMES_REDIRECTS_ENABLED: ' . var_export( HERMES_REDIRECTS_ENABLED, true ) . '
CANARY_TRACE_ENABLED: ' . var_export( CANARY_TRACE_ENABLED, true ) . '
CANARY_ENABLED: ' . var_export( CANARY_ENABLED, true ) . '
CANARY_DEBUG_TO_CONSOLE: ' . var_export( CANARY_DEBUG_TO_CONSOLE, true ) . '
CANARY_DEBUG_TO_FILE: ' . var_export( CANARY_DEBUG_TO_FILE, true ) . '
Tempus Debugger:
CANARY_SECURE_HASH: ' . var_export( CANARY_SECURE_HASH, true ) . '
CANARY_SHOW_LINES: ' . var_export( CANARY_SHOW_LINES, true ) . '
Tokens:
DEFAULT_TOKEN_NAME: ' . var_export( DEFAULT_TOKEN_NAME, true ) . '
TOKEN_ENABLED: ' . var_export( TOKEN_ENABLED, true ) . '
Cookies:
DEFAULT_COOKIE_EXPIRATION: ' . var_export( DEFAULT_COOKIE_EXPIRATION, true ) . '
DEFAULT_COOKIE_PREFIX: ' . var_export( DEFAULT_COOKIE_PREFIX, true ) . '
Directories:
APP_ROOT_DIRECTORY: ' . var_export( APP_ROOT_DIRECTORY, true ) . '
BIN_DIRECTORY: ' . var_export( BIN_DIRECTORY, true ) . '
UPLOAD_DIRECTORY: ' . var_export( UPLOAD_DIRECTORY, true ) . '
IMAGE_UPLOAD_DIRECTORY: ' . var_export( IMAGE_UPLOAD_DIRECTORY, true ) . '
CLASSES_DIRECTORY: ' . var_export( CLASSES_DIRECTORY, true ) . '
CONFIG_DIRECTORY: ' . var_export( CONFIG_DIRECTORY, true ) . '
FUNCTIONS_DIRECTORY: ' . var_export( FUNCTIONS_DIRECTORY, true ) . '
TEMPLATE_DIRECTORY: ' . var_export( TEMPLATE_DIRECTORY, true ) . '
VIEW_DIRECTORY: ' . var_export( VIEW_DIRECTORY, true ) . '
ERRORS_DIRECTORY: ' . var_export( ERRORS_DIRECTORY, true ) . '
RESOURCES_DIRECTORY: ' . var_export( RESOURCES_DIRECTORY, true ) . '
BEDROCK_ROOT_DIRECTORY: ' . var_export( BEDROCK_ROOT_DIRECTORY, true ) . '
BEDROCK_BIN_DIRECTORY: ' . var_export( BEDROCK_BIN_DIRECTORY, true ) . '
BEDROCK_CLASSES_DIRECTORY: ' . var_export( BEDROCK_CLASSES_DIRECTORY, true ) . '
BEDROCK_CONFIG_DIRECTORY: ' . var_export( BEDROCK_CONFIG_DIRECTORY, true ) . '
BEDROCK_FUNCTIONS_DIRECTORY: ' . var_export( BEDROCK_FUNCTIONS_DIRECTORY, true ) . '
BEDROCK_RESOURCES_DIRECTORY: ' . var_export( BEDROCK_RESOURCES_DIRECTORY, true ) . '
BEDROCK_VIEW_DIRECTORY: ' . var_export( BEDROCK_VIEW_DIRECTORY, true ) . '
BEDROCK_ERRORS_DIRECTORY: ' . var_export( BEDROCK_ERRORS_DIRECTORY, true ) . '
Other:
MINIMUM_PHP_VERSION: ' . var_export( MINIMUM_PHP_VERSION, true ) . '
DATA_TITLE_PREG: ' . var_export( DATA_TITLE_PREG, true ) . '
PATH_PREG_REQS: ' . var_export( PATH_PREG_REQS, true ) . '
SIMPLE_NAME_PREG: ' . var_export( SIMPLE_NAME_PREG, true ) . '
ALLOWED_IMAGE_UPLOAD_EXTENTIONS: ' . var_export( ALLOWED_IMAGE_UPLOAD_EXTENTIONS, true ) . '
MAX_RESULTS_PER_PAGE: ' . var_export( MAX_RESULTS_PER_PAGE, true ) . '
DEFAULT_RESULTS_PER_PAGE: ' . var_export( DEFAULT_RESULTS_PER_PAGE, true ) . '
DEFAULT_SESSION_PREFIX: ' . var_export( DEFAULT_SESSION_PREFIX, true ) . '
DEFAULT_CONTROLLER_CLASS: ' . var_export( DEFAULT_CONTROLLER_CLASS, true ) . '
'; + } +} diff --git a/classes/config.php b/classes/config.php new file mode 100644 index 0000000..cb3bae7 --- /dev/null +++ b/classes/config.php @@ -0,0 +1,367 @@ + + * @link https://TheTempusProject.com/Core + * @license https://opensource.org/licenses/MIT [MIT LICENSE] + */ +namespace TheTempusProject\Bedrock\Classes; + +use TheTempusProject\Canary\Canary as Debug; +use TheTempusProject\Bedrock\Functions\Check; +use TheTempusProject\Bedrock\Functions\Input; + +class Config { + public static $config = false; + private static $location = false; + private static $initialized = false; + + /** + * Default constructor which will attempt to load the config from the location specified. + * + * @param {string} [$location] + * @return {null|object} + */ + public function __construct( $location = '' ) { + if ( self::$initialized !== false ) { + Debug::log( 'Config already initialized.' ); + return $this; + } + if ( empty( $location ) ) { + $location = CONFIG_JSON; + } + self::$initialized = $this->load( $location ); + if ( self::$initialized !== false ) { + Debug::log( 'Config initialization succeeded.' ); + return $this; + } + Debug::warn( 'Config initialization failed.' ); + } + + /** + * Attempts to retrieve then set the configuration from a file. + * @note This function will reset the config every time it is used. + * + * @param {string} $location + * @return {bool} + */ + public function load( $location ) { + self::$config = $this->getConfigFile( $location ); + self::$location = $location; + if ( self::$config === false || empty( self::$config ) ) { + Debug::warn( 'Config load failed.' ); + return false; + } + Debug::log( 'Config load succeeded.' ); + return true; + } + + /** + * Opens and decodes the config json from the location provided. + * + * @param {string} [$location] + * @return {bool|array} + */ + public function getConfigFile( $location ) { + if ( file_exists( $location ) ) { + Debug::debug( "Config json found: $location" ); + return json_decode( file_get_contents( $location ), true ); + } else { + Debug::warn( "Config json not found: $location" ); + return false; + } + } + + /** + * Add a new config option for the specified category. + * + * NOTE: Use a default option when using this function to + * aid in fail safe execution. + * + * @param {string} [$category] - The primary category to add the option to. + * @param {string} [$node] - The name of the new option. + * @param {wild} [$value] - The desired value for the new option. + * @param {bool} [$createMissing] - Whether or not to create missing options. + * @param {bool} [$save] - Whether or not to save the config. + * @param {bool} [$saveDefault] - Whether or not to save the default config. + * @return {bool} + */ + public function update( $category, $node, $value, $createMissing = false, $save = false, $saveDefault = false ) { + // @todo: createMissing is unused here + if ( self::$config === false ) { + Debug::warn( 'Config not loaded.' ); + return false; + } + if ( !Check::simpleName( $category ) ) { + Debug::warn( "Category name invalid: $categoryName" ); + return false; + } + if ( !isset( self::$config[$category] ) ) { + Debug::warn( "No such category: $category" ); + return false; + } + if ( !Check::simpleName( $node ) ) { + Debug::warn( "Node name invalid: $categoryName" ); + return false; + } + if ( !isset( self::$config[$category][$node] ) ) { + Debug::warn( 'Config not found.' ); + return false; + } + if ( $value === 'true' ) { + $value = true; + } + if ( $value === 'false' ) { + $value = false; + } + self::$config[$category][$node]['value'] = $value; + if ( $save ) { + $this->save( $saveDefault ); + } + return true; + } + + public function updateFromForm( $save = false, $saveDefault = false ) { + if ( self::$config === false ) { + Debug::warn( 'Config not loaded.' ); + return; + } + foreach ( self::$config as $category => $fields ) { + if ( empty( self::$config[ $category ] ) ) { + Debug::warn( "Config category not found: $category" ); + continue; + } + foreach ( self::$config[ $category ] as $field => $node ) { + $name = $category . '/' . $field; + if ( empty( $node ) ) { + continue; + } + if ( !empty( $node['protected'] ) ) { + continue; + } + $fieldname = str_ireplace( '/', '-', $name ); + if ( Input::exists( $fieldname ) ) { + $this->update( $category, $field, Input::post( $fieldname ) ); + } + } + } + if ( $save ) { + return $this->save( $saveDefault ); + } + return true; + } + + /** + * Saves the current config. + * + * @param {bool} [$default] - Whether or not to save a default copy. + * @return {bool} + */ + public function save( $default = false ) { + if ( self::$config === false ) { + Debug::warn( 'Config not loaded.' ); + return false; + } + if ( self::$location === false ) { + Debug::warn( 'Config location not set.' ); + return false; + } + if ( $default ) { + $locationArray = explode( '.', self::$location ); + $locationArray[] = 'bak'; + $backupLoction = implode( '.', $locationArray ); + if ( !file_put_contents( $backupLoction, json_encode( self::$config ) ) ) { + return false; + } + } + if ( file_put_contents( self::$location, json_encode( self::$config ) ) ) { + return true; + } + return false; + } + + /** + * Adds a new category to the $config array. + * + * @param {string} [$categoryName] + * @return {bool} + */ + public function addCategory( $categoryName ) { + if ( self::$config === false ) { + self::$config = []; + } + if ( !Check::simpleName( $categoryName ) ) { + Debug::warn( "Category name invalid: $categoryName" ); + return false; + } + if ( isset( self::$config[$categoryName] ) ) { + Debug::warn( "Category already exists: $categoryName" ); + return false; + } + self::$config[$categoryName] = []; + return true; + } + + /** + * Removes an existing category from the $config array. + * + * @param {string} [$categoryName] + * @param {string} [$save] + * @return {bool} + */ + public function removeCategory( $categoryName, $save = false, $saveDefault = true ) { + if ( self::$config === false ) { + Debug::warn( 'Config not loaded.' ); + return; + } + if ( !isset( self::$config[$categoryName] ) ) { + Debug::warn( "Config does not have category: $categoryName" ); + return true; + } + unset( self::$config[$categoryName] ); + if ( $save ) { + $this->save( $saveDefault ); + } + return true; + } + + /** + * Add a new config node for the specified category. + * + * @param {string} [$category] - The primary category to add the option to. + * @param {string} [$node] - The name of the new option. + * @param {wild} [$value] - The desired value for the new option. + * @return {bool} + */ + public function add( $category, $node, $details, $updateExisting = false ) { + if ( self::$config === false ) { + Debug::warn( 'Config not loaded.' ); + return false; + } + if ( !Check::simpleName( $category ) ) { + Debug::warn( "Category name invalid: $category" ); + return false; + } + if ( !isset( self::$config[$category] ) ) { + Debug::warn( "No such category: $category" ); + return false; + } + if ( !Check::simpleName( $node ) ) { + Debug::warn( "Category Node name invalid: $node" ); + return false; + } + if ( isset( self::$config[$category][$node] ) ) { + if ( $updateExisting ) { + $details = array_replace(self::$config[$category][$node], $details ); + } else { + Debug::warn( "Config already exists: $node" ); + return false; + } + } + if ( !isset( $details['value'] ) ) { + $details['value'] = $details['default']; + } + self::$config[$category][$node] = $details; + return true; + } + + public function generate( $location, $mods = [] ) { + self::$location = $location; + if ( !empty( $mods ) ) { + foreach ( $mods as $category => $node ) { + $this->addCategory( $category ); + foreach ( $node as $name => $details ) { + $this->add( $category, $name, $details, true ); + } + } + } + if ( $this->save( true ) ) { + Debug::info( 'config file generated successfully.' ); + return true; + } + return false; + } + + /** + * Retrieves the config option for $name. + * + * @param {string} [$name] - Must be in /