<?php
/**
 * -------------------------------------------------------------------------
 *
 * Template to display the Settings page.
 *
 * -------------------------------------------------------------------------
 *
 * Inspired by code pen "Snake highlight" of Mikael Ainalem
 * https://codepen.io/ainalem/pen/EQXjOR
 *
 * -------------------------------------------------------------------------
 *
 * @package    MimimiFramework
 * @subpackage Examples / Static Pages only
 * @license    GPL-2.0
 *             https://opensource.org/license/gpl-2-0/
 * @copyright  2022 MiMiMi Community
 *             https://mimimi.software/
 *
 * -------------------------------------------------------------------------
 */

    /**
     * ---------------------------------------------------------------------
     *
     * Execute server logic according to a form on this page.
     *
     * ---------------------------------------------------------------------
     */

    $success = '';
    $error   = '';

    /**
     * ---------------------------------------------------------------------
     *
     * Get all the settings that existed before a form was submitted.
     *
     * ---------------------------------------------------------------------
     */

    $settings = [ 'STATICPAGESONLY_ADMIN_LOGIN'            => STATICPAGESONLY_ADMIN_LOGIN          ,
                  'STATICPAGESONLY_ADMIN_PASSWORD_HASH'    => ''                                   ,
                  'confirm'                                => ''                                   ,
                  'STATICPAGESONLY_DEMO_MODE'              => STATICPAGESONLY_DEMO_MODE            ,
                  'STATICPAGESONLY_SESSION_MODE'           => STATICPAGESONLY_SESSION_MODE         ,
                  'STATICPAGESONLY_STORAGE_SUBDIRECTORY'   => STATICPAGESONLY_STORAGE_SUBDIRECTORY ,
                  'STATICPAGESONLY_TIMEOUT_FOR_LOGIN'      => STATICPAGESONLY_TIMEOUT_FOR_LOGIN    ,
                  'STATICPAGESONLY_TIMEOUT_FOR_DELETE'     => STATICPAGESONLY_TIMEOUT_FOR_DELETE   ,
                  'STATICPAGESONLY_TIMEOUT_FOR_EDIT'       => STATICPAGESONLY_TIMEOUT_FOR_EDIT     ,
                  'STATICPAGESONLY_TIMEOUT_FOR_SETTINGS'   => STATICPAGESONLY_TIMEOUT_FOR_SETTINGS ,
                  'STATICPAGESONLY_CKEDITOR_KEY'           => STATICPAGESONLY_CKEDITOR_KEY         ,
                  'STATICPAGESONLY_CKEDITOR_CUSTOMIZATION' => helperLoadJS ( 'editor.js'         ) ,
                  'STATICPAGESONLY_SCRIPTS_BEFORE'         => helperLoadJS ( 'scripts-before.js' ) ,
                  'STATICPAGESONLY_SCRIPTS_AFTER'          => helperLoadJS ( 'scripts-after.js'  ) ];

    /**
     * ---------------------------------------------------------------------
     *
     * If the admin has submitted a form with the settings entered.
     *
     * ---------------------------------------------------------------------
     */

    if ( getFormInput ( 'submit' ) ) {

        /**
         * -----------------------------------------------------------------
         *
         * Get all the fields of that form.
         *
         * -----------------------------------------------------------------
         */

        $entry = [ 'STATICPAGESONLY_ADMIN_LOGIN'            => getFormInput        ( 'STATICPAGESONLY_ADMIN_LOGIN'            ) ,
                   'STATICPAGESONLY_ADMIN_PASSWORD_HASH'    => mimimiPost          ( 'STATICPAGESONLY_ADMIN_PASSWORD_HASH'    ) ,
                   'confirm'                                => mimimiPost          ( 'confirm'                                ) ,
                   'STATICPAGESONLY_DEMO_MODE'              => helperGetFormFlag   ( 'STATICPAGESONLY_DEMO_MODE'              ) ,
                   'STATICPAGESONLY_SESSION_MODE'           => helperGetFormMode   ( 'STATICPAGESONLY_SESSION_MODE'           ) ,
                   'STATICPAGESONLY_STORAGE_SUBDIRECTORY'   => makeSecureUrl (
                                                                   getFormInput    ( 'STATICPAGESONLY_STORAGE_SUBDIRECTORY'   )
                                                               ) ,
                   'STATICPAGESONLY_TIMEOUT_FOR_LOGIN'      => helperGetFormNumber ( 'STATICPAGESONLY_TIMEOUT_FOR_LOGIN'      ) ,
                   'STATICPAGESONLY_TIMEOUT_FOR_DELETE'     => helperGetFormNumber ( 'STATICPAGESONLY_TIMEOUT_FOR_DELETE'     ) ,
                   'STATICPAGESONLY_TIMEOUT_FOR_EDIT'       => helperGetFormNumber ( 'STATICPAGESONLY_TIMEOUT_FOR_EDIT'       ) ,
                   'STATICPAGESONLY_TIMEOUT_FOR_SETTINGS'   => helperGetFormNumber ( 'STATICPAGESONLY_TIMEOUT_FOR_SETTINGS'   ) ,
                   'STATICPAGESONLY_CKEDITOR_KEY'           => getFormInput        ( 'STATICPAGESONLY_CKEDITOR_KEY'           ) ,
                   'STATICPAGESONLY_CKEDITOR_CUSTOMIZATION' => helperGetFormJs     ( 'STATICPAGESONLY_CKEDITOR_CUSTOMIZATION' ) ,
                   'STATICPAGESONLY_SCRIPTS_BEFORE'         => helperGetFormJs     ( 'STATICPAGESONLY_SCRIPTS_BEFORE'         ) ,
                   'STATICPAGESONLY_SCRIPTS_AFTER'          => helperGetFormJs     ( 'STATICPAGESONLY_SCRIPTS_AFTER'          ) ];

        /**
         * -----------------------------------------------------------------
         *
         * Now we check if the security timeout has expired. Note that we
         * have also set a new timeout period to ensure the safety of the
         * next action.
         *
         * -----------------------------------------------------------------
         */

        $expired = helperCheckForTimeout ( 'settings'                                       );
                   helperSetTimeout      ( 'settings', STATICPAGESONLY_TIMEOUT_FOR_SETTINGS );
        if ( $expired ) {

            /**
             * -------------------------------------------------------------
             *
             * After that, we must get the entered login and check it.
             *
             * -------------------------------------------------------------
             */

            if ( $entry[ 'STATICPAGESONLY_ADMIN_LOGIN' ] != '' ) {

                /**
                 * ---------------------------------------------------------
                 *
                 * Then we must get the password entered by the admin and
                 * check it in a similar manner.
                 *
                 * ---------------------------------------------------------
                 */

                $areEqual = $entry[ 'STATICPAGESONLY_ADMIN_PASSWORD_HASH' ] === $entry[ 'confirm' ];
                if ( $areEqual || $entry[ 'STATICPAGESONLY_ADMIN_PASSWORD_HASH' ] != '' ) {
                    if ( $areEqual ) {

                        /**
                         * -------------------------------------------------
                         *
                         * Now we must check the storage path.
                         *
                         * -------------------------------------------------
                         */

                        $entry[ 'STATICPAGESONLY_STORAGE_SUBDIRECTORY' ] = preg_replace ( '~^/+~u', '', $entry[ 'STATICPAGESONLY_STORAGE_SUBDIRECTORY' ] . '/' );
                        if ( $entry[ 'STATICPAGESONLY_STORAGE_SUBDIRECTORY' ] != '' ) {

                            /**
                             * ---------------------------------------------
                             *
                             * Check if the site works in production mode now.
                             *
                             * ---------------------------------------------
                             */

                            if ( ! helperIsDemo ( ) ) {

                                /**
                                 * -----------------------------------------
                                 *
                                 * Try to save the settings that have been
                                 * changed.
                                 *
                                 * -----------------------------------------
                                 */

                                foreach ( $settings as $name => & $value ) {
                                    if ( $value !== $entry[ $name ] ) {
                                        $value = $entry[ $name ];
                                        switch ( $name ) {
                                            case 'confirm':
                                                 break;
                                            case 'STATICPAGESONLY_ADMIN_PASSWORD_HASH':
                                                 helperUpdateSetting ( $name, helperComputeHash ( $value ) );
                                                 break;
                                            case 'STATICPAGESONLY_CKEDITOR_CUSTOMIZATION':
                                                 helperSaveJS ( 'editor.js', $value );
                                                 break;
                                            case 'STATICPAGESONLY_SCRIPTS_BEFORE':
                                                 helperSaveJS ( 'scripts-before.js', $value );
                                                 break;
                                            case 'STATICPAGESONLY_SCRIPTS_AFTER':
                                                 helperSaveJS ( 'scripts-after.js', $value );
                                                 break;
                                            default:
                                                 helperUpdateSetting ( $name, $value );
                                        }
                                    }
                                }

                                /**
                                 * -----------------------------------------
                                 *
                                 * Redirect the admin to the home page.
                                 *
                                 * -----------------------------------------
                                 */

                                helperGotoHome ( );

                            /**
                             * ---------------------------------------------
                             *
                             * Otherwise, prepare an appropriate error message.
                             *
                             * ---------------------------------------------
                             */

                            } else {
                                $success = 'Everything is fine! However, you are currently in demo mode. Any change to the settings is only simulated in this mode. To see how it really works, download this package and install it on your site or localhost.';
                            }
                        } else {
                            $success = 'Please enter a non-empty storage path!';
                        }
                    } else {
                        $error = 'The password and its confirmation must be the same!';
                    }
                } else {
                    $error = 'Please enter a non-empty password!';
                }
            } else {
                $error = 'Please enter a valid login!';
            }
        } else {
            $error = 'Your previous attempts were too frequent! To avoid attacks on settings, the site uses a pause between critical actions (such as editing settings). Try again in ' . STATICPAGESONLY_TIMEOUT_FOR_SETTINGS . ' seconds.';
        }

        /**
         * -----------------------------------------------------------------
         *
         * We will need to display the already edited settings below, so we
         * are using the ones obtained above from the submitted form.
         *
         * -----------------------------------------------------------------
         */

        $settings = $entry;
    }

    /**
     * ---------------------------------------------------------------------
     *
     * Send headers matching this page.
     *
     * ---------------------------------------------------------------------
     */

    sendHeaderHTML         (   );
    sendStatus200          (   );
    sendHeaderExpires      ( 0 );
    sendHeaderLastModified (   );

    /**
     * ---------------------------------------------------------------------
     *
     * Now we can generate the page content.
     *
     * ---------------------------------------------------------------------
     */

?><!DOCTYPE html>
<html>
    <head>
        <base href="<?php printSiteUrl ( ) ?>">
        <meta charset="UTF-8">

        <title>
            Settings
        </title>

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots"   content="noindex, nofollow">

        <link rel="canonical"     href="<?php printPageUrl ( ) ?>">
        <link rel="shortcut icon" href="<?php printThemeUrl ( ) ?>images/favicon.ico" type="image/ico">
        <link rel="stylesheet"    href="<?php printThemeUrl ( ) ?>css/settings.css">
    </head>

    <body>
        <div class="wrapper">
            <header class="success"><?php
                printValue ( $success )
            ?></header>

            <aside class="error"><?php
                printValue ( $error )
            ?></aside>

            <main class="content list">
                <div class="left">
                    <h1 class="title">
                        Settings
                    </h1>
                    <p>Please customize the site as you wish using the following settings form.</p>

                    <a class="btn" href="<?php printSiteUrl ( ) ?>" title="Return to the home page">
                        Cancel
                    </a>
                </div>

                <div class="right">
                    <div class="form">
                        <h4> Who can be authorized? </h4>

                        <p>You can use the following three settings to register a new administrator. If you do not need to change the current admin password, leave the Password and Confirm Password fields blank.</p>

                        <label class="third">
                            <span> Its Login: </span>
                            <input name="STATICPAGESONLY_ADMIN_LOGIN"
                                   type="text"
                                   maxlength="50"
                                   value="<?php printValue ( $settings[ 'STATICPAGESONLY_ADMIN_LOGIN' ] ) ?>"
                                   required
                                   tabindex="1">
                        </label>

                        <label class="third">
                            <span> Confirm Password: </span>
                            <input name="confirm"
                                   type="text"
                                   maxlength="100"
                                   value="<?php printValue ( $settings[ 'confirm' ] ) ?>"
                                   placeholder="********"
                                   tabindex="3">
                        </label>

                        <label class="third">
                            <span> Its Password: </span>
                            <input name="STATICPAGESONLY_ADMIN_PASSWORD_HASH"
                                   type="text"
                                   maxlength="100"
                                   value="<?php printValue ( $settings[ 'STATICPAGESONLY_ADMIN_PASSWORD_HASH' ] ) ?>"
                                   placeholder="********"
                                   tabindex="2">
                            <a class="misc" onclick="generatePassword ( this )" title="Generate a random password">
                                &bullet;&bullet;&bullet;
                            </a>
                        </label>

                        <p>To enhance site security, you can generate a random password using the button located inside the password field.</p>

                        <h4> Timeouts </h4>
                        <p>The following settings defines safety timers for various activities. They set a pause in seconds that the user must wait before performing the next action of a certain type.</p>

                        <label class="quarter">
                            <span> For Log In: </span>
                            <input name="STATICPAGESONLY_TIMEOUT_FOR_LOGIN"
                                   type="number"
                                   min="0"
                                   max="300"
                                   step="1"
                                   value="<?php printValue ( max ( 0, intval ( $settings[ 'STATICPAGESONLY_TIMEOUT_FOR_LOGIN' ] ) ) ) ?>"
                                   required
                                   tabindex="4">
                        </label>

                        <label class="quarter">
                            <span> For Delete: </span>
                            <input name="STATICPAGESONLY_TIMEOUT_FOR_DELETE"
                                   type="number"
                                   min="0"
                                   max="300"
                                   step="1"
                                   value="<?php printValue ( max ( 0, intval ( $settings[ 'STATICPAGESONLY_TIMEOUT_FOR_DELETE' ] ) ) ) ?>"
                                   required
                                   tabindex="5">
                        </label>

                        <label class="quarter">
                            <span> For Edit: </span>
                            <input name="STATICPAGESONLY_TIMEOUT_FOR_EDIT"
                                   type="number"
                                   min="0"
                                   max="300"
                                   step="1"
                                   value="<?php printValue ( max ( 0, intval ( $settings[ 'STATICPAGESONLY_TIMEOUT_FOR_EDIT' ] ) ) ) ?>"
                                   required
                                   tabindex="6">
                        </label>

                        <label class="quarter">
                            <span> For Settings: </span>
                            <input name="STATICPAGESONLY_TIMEOUT_FOR_SETTINGS"
                                   type="number"
                                   min="0"
                                   max="300"
                                   step="1"
                                   value="<?php printValue ( max ( 0, intval ( $settings[ 'STATICPAGESONLY_TIMEOUT_FOR_SETTINGS' ] ) ) ) ?>"
                                   required
                                   tabindex="7">
                        </label>

                        <p>For example, if an administrator logs out, he will be able to log in only after waiting <?php printValue ( STATICPAGESONLY_TIMEOUT_FOR_LOGIN ) ?> seconds. The same rule will apply to an error during authorization.</p>
                        <p>Another example: if an admin deletes a page, he can delete another page only after waiting <?php printValue ( STATICPAGESONLY_TIMEOUT_FOR_DELETE ) ?> seconds. The same rule will apply to errors between deletions.</p>

                        <h4> Launch options </h4>

                        <p>The first option below is a switch that allows you to launch this site in showcase mode. Unlike production mode, showcase mode will prevent any page from saving changes made during the demo run, all those changes will only simulate saving.</p>

                        <label class="half">
                            <span> Site Mode: </span>
                            <select name="STATICPAGESONLY_DEMO_MODE"
                                    tabindex="8">
                                <option value="0" <?php printValue ( $settings[ 'STATICPAGESONLY_DEMO_MODE' ] ? ''         : 'selected' ) ?>> Production </option>
                                <option value="1" <?php printValue ( $settings[ 'STATICPAGESONLY_DEMO_MODE' ] ? 'selected' : ''         ) ?>> Showcase   </option>
                            </select>
                        </label>

                        <label class="half">
                            <span> Session Mode: </span>
                            <select name="STATICPAGESONLY_SESSION_MODE"
                                    tabindex="9">
                                <option value="1" <?php printValue ( TRUE  ===   $settings[ 'STATICPAGESONLY_SESSION_MODE' ]   ? 'selected' : '' ) ?>> Classic    </option>
                                <option value="0" <?php printValue ( FALSE ===   $settings[ 'STATICPAGESONLY_SESSION_MODE' ]   ? 'selected' : '' ) ?>> Tied to IP </option>
                                <option value=""  <?php printValue ( is_string ( $settings[ 'STATICPAGESONLY_SESSION_MODE' ] ) ? 'selected' : '' ) ?>> Optimal    </option>
                            </select>
                        </label>

                        <p>The second option above is a launch mode for the Session module. It can take one of 3 values:</p>
                        <ul>
                            <li>Classic is a completely randomly generated session ID. Note that is not tamper-proof because allows an attacker to hijack your session simply by intercepting the session ID.</li>
                            <li>Tied to IP is strictly associated with the visitor's IP. It provides good security but is not suitable for use through a public proxy since all users using that proxy will have the same session ID.</li>
                            <li>Optimal is tied to the visitor's IP with some randomness.</li>
                        </ul>

                        <h4> "Database" </h4>

                        <p>The following setting is relative subpath to the "database" directory where your site's static pages are stored as TPL files. It must end with a slash. Note that this subpath is relative to the root directory of your site.</p>

                        <label>
                            <span> Storage Path: </span>
                            <input name="STATICPAGESONLY_STORAGE_SUBDIRECTORY"
                                   type="text"
                                   maxlength="255"
                                   value="<?php printValue ( $settings[ 'STATICPAGESONLY_STORAGE_SUBDIRECTORY' ] ) ?>"
                                   required
                                   tabindex="10">
                            <a class="misc" onclick="generatePath ( this )" title="Generate a random storage path">
                                &bullet;&bullet;&bullet;
                            </a>
                        </label>

                        <p>If you want to hide the "database" storage as efficiently as possible, you can click the button located inside the path field to generate a random path.</p>
                        <p>However, this only makes sense if you are using HTML markup on the page without any secondary elements (such as images, for example) that would be loaded directly from the same storage.</p>

                        <h4> CKEditor </h4>

                        <p>The built-in <a href="add" rel="nofollow">HTML editor</a> supports a certain set of paid and free plugins depending on which license key is used for this editor.</p>

                        <label>
                            <span> License Key: </span>
                            <input name="STATICPAGESONLY_CKEDITOR_KEY"
                                   type="text"
                                   maxlength="510"
                                   value="<?php printValue ( $settings[ 'STATICPAGESONLY_CKEDITOR_KEY' ] ) ?>"
                                   required
                                   tabindex="11">
                        </label>

                        <p>This key should be set to "GPL" if you are using the freeware version of CKEditor.</p>

                        <label>
                            <span> Editor Customization: </span>
                            <textarea class="js"
                                      name="STATICPAGESONLY_CKEDITOR_CUSTOMIZATION"
                                      maxlength="98304"
                                      rows="20"
                                      tabindex="12"><?php
                                printValue ( $settings[ 'STATICPAGESONLY_CKEDITOR_CUSTOMIZATION' ] )
                            ?></textarea>
                        </label>

                        <p>If you have any questions about the field above, contact your webmaster, who will configure the built-in HTML editor, and your content manager, who will tell you what editor tools he needs to edit the site pages.</p>

                        <h4> Metrics </h4>

                        <p>Sometimes you may need to embed third-party JavaScript into the page, for example an analytics counter, a call tracking script, or something else. Typically, such a script is launch first on the page, i.e. before the page starts loading. In this case, its program code should be written below:</p>

                        <label>
                            <span> Scripts Before: </span>
                            <textarea class="js"
                                      name="STATICPAGESONLY_SCRIPTS_BEFORE"
                                      maxlength="49152"
                                      tabindex="13"><?php
                                printValue ( $settings[ 'STATICPAGESONLY_SCRIPTS_BEFORE' ] )
                            ?></textarea>
                        </label>

                        <p>If you want, you can also use client-side JavaScript, which will launch after the page has finished loading.</p>

                        <label>
                            <span> Scripts After: </span>
                            <textarea class="js"
                                      name="STATICPAGESONLY_SCRIPTS_AFTER"
                                      maxlength="49152"
                                      tabindex="14"><?php
                                printValue ( $settings[ 'STATICPAGESONLY_SCRIPTS_AFTER' ] )
                            ?></textarea>
                        </label>

                        <p>If you have any questions for two fields above, contact your SEO master.</p>

                        <button class="btn"
                                name="submit"
                                type="submit"
                                tabindex="15">
                            Save
                        </button>
                    </div>
                </div>
            </main>

            <footer class="footnote"></footer>
        </div>

        <script src="<?php printThemeUrl ( ) ?>js/settings.js"></script>
    </body>
</html>
