<?php
/**
 * -------------------------------------------------------------------------
 *
 * Template to display the Edit bbCode page.
 *
 * -------------------------------------------------------------------------
 *
 * Input parameters are:
 *
 *     $params = Text contents of this bbCode file.
 *
 * -------------------------------------------------------------------------
 *
 * @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 the CSS entry that existed before a form was submitted.
     *
     * ---------------------------------------------------------------------
     */

    $item = [ 'url'  => helperGetBBcodeUrl ( ) ,
              'body' => $params                ];

        /**
         * -----------------------------------------------------------------
         *
         * For the Copy page, we will have to forcefully change the URL.
         *
         * -----------------------------------------------------------------
         */

        if ( helperIsCopyUrl ( ) ) {
            $item[ 'url' ] = preg_replace ( '~(\.tpl)$~ui' ,
                                            '-copy$1'      ,
                                            $item[ 'url' ] );
        }

    /**
     * ---------------------------------------------------------------------
     *
     * If the admin has submitted a form with the bbCode body.
     *
     * ---------------------------------------------------------------------
     */

    if ( getFormInput ( 'submit' ) ) {

        /**
         * -----------------------------------------------------------------
         *
         * Get all the fields of that form. Note that the FALSE parameter
         * means that PHP tags are enabled for bbCode files.
         *
         * -----------------------------------------------------------------
         */

        $entry = [ 'url'  => makeSecureUrl (
                                 getFormInput ( 'url' )
                             ) ,
                   'body' => helperGetFormTpl ( 'body', FALSE ) ];

        /**
         * -----------------------------------------------------------------
         *
         * 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 ( 'edit'                                   );
                   helperSetTimeout      ( 'edit', STATICPAGESONLY_TIMEOUT_FOR_EDIT );
        if ( $expired ) {

            /**
             * -------------------------------------------------------------
             *
             * After that, we must check the entered URL.
             *
             * -------------------------------------------------------------
             */

            if ( helperValidateBBcodeUrl ( $entry[ 'url' ] ) ) {

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

                if ( ! helperIsDemo ( ) ) {

                    /**
                     * -----------------------------------------------------
                     *
                     * Make sure there are no conflicts due to an early
                     * requested URL being unexpectedly renamed by an admin.
                     *
                     * -----------------------------------------------------
                     */

                    $params = $item[ 'url' ] != $entry[ 'url' ] ? helperLoadBBcode ( $entry[ 'url' ] )
                                                                : '';
                    if ( $params == '' ) {

                        /**
                         * -------------------------------------------------
                         *
                         * Try to save this file and redirect the admin
                         * to the bbCode Blocks page.
                         *
                         * -------------------------------------------------
                         */
 
                        helperSaveBBcode ( $entry[ 'url' ], $entry[ 'body' ] );
                        helperGotoPage ( 'bbcodes' );

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

                    } else {
                        $error = 'You are trying to save a bbCode file to another URL that is already taken! To do this, you need to edit the bbCode using a direct link to its file.';
                    }
                } else {
                    $success = 'Everything is fine! However, you are currently in demo mode. Any saving is only simulated in this mode. To see how it really works, download this package and install it on your site or localhost.';
                }
            } else {
                $error = 'Please enter a valid URL! It can only contain Latin letters, numbers, hyphens, underscores and periods. It must start with a letter or number and may optionally have a nested path structure, where each path segment is separated by a slash. It also must not start with "bbcodes/" and certain editor commands. It should also end with the extension ".tpl".';
            }
        } else {
            $error = 'Your previous attempts were too frequent! To avoid attacks on bbCode files storage, the site uses a pause between critical actions (such as editing a bbCode file). Try again in ' . STATICPAGESONLY_TIMEOUT_FOR_EDIT . ' seconds.';
        }

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

        $item = $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>
            <?php        if ( helperIsAddUrl  ( ) ) { ?> Add a bbCode file
            <?php } else if ( helperIsCopyUrl ( ) ) { ?> Copy a bbCode file
            <?php } else                            { ?> Edit a bbCode file
            <?php } ?>
        </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">
                        <?php        if ( helperIsAddUrl  ( ) ) { ?> Add bbCode
                        <?php } else if ( helperIsCopyUrl ( ) ) { ?> Copy bbCode
                        <?php } else                            { ?> Edit bbCode
                        <?php } ?>
                    </h1>
                    <p>Please edit the contents of this bbCode file as you wish. If you have any questions, contact your web programmer.</p>

                    <a class="btn" href="<?php printSiteUrl ( ) ?>bbcodes" title="Return to the list of existing bbCode files">
                        Cancel
                    </a>
                </div>

                <div class="right">
                    <div class="form">
                        <label>
                            <span> File URL: </span>
                            <input name="url"
                                   type="text"
                                   maxlength="255"
                                   value="<?php printValue ( $item[ 'url' ] ) ?>"
                                   required
                                   tabindex="1">
                            <a class="misc" onclick="generateBBcodeUrl ( this )" title="Generate a random URL to make it difficult for someone to guess how to access the file directly">
                                &bullet;&bullet;&bullet;
                            </a>
                        </label>

                        <label>
                            <span> File Content: </span>
                            <textarea class="bbcode"
                                      name="body"
                                      maxlength="262144"
                                      tabindex="2"><?php
                                printValue ( $item[ 'body' ] )
                            ?></textarea>
                        </label>

                        <button class="btn"
                                name="submit"
                                type="submit"
                                tabindex="3">
                            Save
                        </button>

                        <br>
                        <h2>Do you know...</h2>
                        <p>BBCode is actually a regular TPL file that will be saved in a specific storage directory among your website files. This means that this file can in principle be accessed via a URL.</p>
                        <p>However, the TPL file is usually HTML markup with server-side PHP logic, which can theoretically contain any unsafe tag or sensitive data if the file is browsed directly.</p>
                        <p>So, you might want to generate a random URL for such a file to make it harder for someone else to guess. There is a button inside the URL field for this purpose.</p>

                        <h4>Naming</h4>
                        <p>To give your bbCode a virtual name, use the <code>&lt;!-- Name: Something --&gt;</code> pseudo directive. You can also use the alternative, the single-line <code>// Name: Something</code> or the multi-line <code>/* Name: Something */</code> pseudo directive. Otherwise, that bbCode will be listed anywhere under its file name.</p>
                    </div>
                </div>
            </main>

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

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