<?php
/**
 * -------------------------------------------------------------------------
 *
 * Template to display the Edit Fragment page.
 *
 * -------------------------------------------------------------------------
 *
 * Input parameters are:
 *
 *     $params = A contents of this Fragment 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'  => helperGetFragmentUrl ( ) ,
              '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 TRUE parameter
         * means that PHP tags are disabled for Fragment files.
         *
         * -----------------------------------------------------------------
         */

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

        /**
         * -----------------------------------------------------------------
         *
         * 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 ( helperValidateFragmentUrl ( $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' ] ? helperLoadFragment ( $entry[ 'url' ] )
                                                                : '';
                    if ( $params == '' ) {

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

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

                    } else {
                        $error = 'You are trying to save a Fragment file to another URL that is already taken! To do this, you need to edit the Fragment 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 "fragments/" and certain editor commands. It should also end with the extension ".tpl".';
            }
        } else {
            $error = 'Your previous attempts were too frequent! To avoid attacks on Fragment files storage, the site uses a pause between critical actions (such as editing a Fragment 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 Fragment file
            <?php } else if ( helperIsCopyUrl ( ) ) { ?> Copy a Fragment file
            <?php } else                            { ?> Edit a Fragment 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 Fragment
                        <?php } else if ( helperIsCopyUrl ( ) ) { ?> Copy Fragment
                        <?php } else                            { ?> Edit Fragment
                        <?php } ?>
                    </h1>
                    <p>Please edit the markup of this Fragment file as you wish. If you have any questions, contact your webmaster.</p>

                    <a class="btn" href="<?php printSiteUrl ( ) ?>fragments" title="Return to the list of existing Fragment 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="generateFragmentUrl ( 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>Fragment 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, this TPL file is simple HTML markup, which can theoretically contain 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 Fragment a virtual name, use the <code>&lt;!-- Name: Something --&gt;</code> pseudo directive. Otherwise, that Fragment 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>
