<?php
/**
 * -------------------------------------------------------------------------
 *
 * Template to display the Edit Static Page page.
 *
 * -------------------------------------------------------------------------
 *
 * Input parameters are:
 *
 *     $params = HTML contents of this page.
 *
 * -------------------------------------------------------------------------
 *
 * @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.
     *
     * ---------------------------------------------------------------------
     */

    $styles  = helperCollectStyles ( TRUE );
    $success = '';

    /**
     * ---------------------------------------------------------------------
     *
     * Get the page entry that existed before a form was submitted.
     *
     * ---------------------------------------------------------------------
     */

    $item = [ 'url'        => helperGetPageUrl    (                        ) ,
              'title'      => helperGetTitle      ( $params                ) ,
              'meta'       => helperGetMeta       ( $params                ) ,
              'css'        => helperExtractStyle  ( $params, 'default.css' ) ,
              'body'       => helperExtractBody   ( $params                ) ,
              'permission' => helperGetPermission ( $params                ) ];

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

        if ( helperIsCopyUrl ( ) ) {
            $item[ 'url' ] .= '-copy';
        }

    /**
     * ---------------------------------------------------------------------
     *
     * Check if there are no problems with the editing permission.
     *
     * ---------------------------------------------------------------------
     */

    $error = helperIsConstructUrl ( ) && $item[ 'permission' ] != 'constructor' && $item[ 'permission' ] != ''
                                  ?   'Sorry, you are trying to change a page that has not been allowed to edit in the built-in constructor!'
                                  :   ( helperIsCopyUrl ( ) && $item[ 'permission' ] != 'editor' && $item[ 'permission' ] != ''
                                                        ?   'Sorry, you are trying to copy a page that has not been allowed to edit in the built-in HTML editor!'
                                                        :   ( helperIsEditUrl ( ) && $item[ 'permission' ] != 'editor' && $item[ 'permission' ] != ''
                                                                              ?   'Sorry, you are trying to edit a page that has not been allowed to edit in the built-in HTML editor!'
                                                                              :   '' ) );

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

    if ( $error == ''
    &&   ( getFormInput ( 'submit'  )
        || getFormInput ( 'submit2' )
        || getFormInput ( 'submit3' ) ) ) {

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

        $entry = [ 'url'        => makeSecureUrl   ( getFormInput     ( 'url'                ) ) ,
                   'title'      =>                   getFormInput     ( 'title'              )   ,
                   'meta'       =>                   getFormInput     ( 'meta'               )   ,
                   'css'        => makeSecureUrl   ( getFormInput     ( 'css', 'default.css' ) ) ,
                   'body'       => helperCleanBody ( helperGetFormTpl ( 'body'               ) ) ,
                   'permission' =>                   getFormInput     ( 'permission'         )   ];

        /**
         * -----------------------------------------------------------------
         *
         * 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 ( helperValidatePageUrl ( $entry[ 'url' ] ) ) {

                /**
                 * ---------------------------------------------------------
                 *
                 * Make sure the admin has selected an allowed CSS file.
                 *
                 * ---------------------------------------------------------
                 */

                if ( in_array ( $entry[ 'css' ], $styles ) ) {

                    /**
                     * -----------------------------------------------------
                     *
                     * Make sure the title and body exist.
                     *
                     * -----------------------------------------------------
                     */

                    if ( $entry[ 'title' ] != '' ) {
                        if ( $entry[ 'body' ] != '' ) {

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

                                    /**
                                     * -------------------------------------
                                     *
                                     * Try to save this file and redirect
                                     * the admin to the Static Pages page.
                                     *
                                     * -------------------------------------
                                     */
 
                                    $content = helperCompilePage ( $entry );
                                    helperSavePage ( $entry[ 'url' ], $content );
                                    helperGotoPage ( 'pages' );

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

                                } else {
                                    $error = 'You are trying to save a Static Page to another URL that is already taken! To do this, you need to edit the Static Page using a direct link to its page.';
                                }
                            } 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 non-empty Page Body!';
                        }
                    } else {
                        $error = 'Please enter a non-empty Page Title!';
                    }
                } else {
                    $error = 'Sorry, you are using a CSS file that is not in the list of allowed page styles!';
                }
            } 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 "pages/" or certain editor commands, and must not end with an extension like ".tpl", ".xml", ".css", ".js", or ".php".';
            }
        } else {
            $error = 'Your previous attempts were too frequent! To avoid attacks on pages storage, the site uses a pause between critical actions (such as editing a page). Try again in ' . STATICPAGESONLY_TIMEOUT_FOR_EDIT . ' seconds.';
        }

        /**
         * -----------------------------------------------------------------
         *
         * We will need to display the already edited page content 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 Page
            <?php } else if ( helperIsConstructUrl ( ) ) { ?> Construct a Page
            <?php } else if ( helperIsCopyUrl      ( ) ) { ?> Copy a Page
            <?php } else if ( helperIsMarkupUrl    ( ) ) { ?> Edit a Page as HTML Source
            <?php } else                                 { ?> Edit a Page
            <?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 (                               );
                                              printValue    ( 'css/pages/' . $item[ 'css' ] ) ?>"
                                  id="stylesheet-tag"
                                  data-path="<?php printThemeUrl ( ) ?>css/pages/">

        <link rel="stylesheet" href="<?php printThemeUrl ( ) ?>css/edit.css">
        <?php
            mimimiModule ( 'snippets/editor-styles.tpl'      );
            mimimiModule ( 'snippets/constructor-styles.tpl' );
        ?>
    </head>

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

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

                        <label>
                            <span> Page Title: </span>
                            <input name="title"
                                   type="text"
                                   maxlength="100"
                                   value="<?php printValue ( $item[ 'title' ] ) ?>"
                                   required>
                        </label>

                        <label>
                            <span> Meta Description: </span>
                            <textarea name="meta"
                                      maxlength="250"><?php
                                printValue ( $item[ 'meta' ] )
                            ?></textarea>
                        </label>

                        <label>
                            <span> Page URL: </span>
                            <input name="url"
                                   type="text"
                                   maxlength="255"
                                   value="<?php printValue ( $item[ 'url' ] ) ?>"
                                   required>
                            <a class="misc" onclick="generateUrl ( this )" title="Generate a random URL">
                                &bullet;&bullet;&bullet;
                            </a>
                        </label>

                        <label>
                            <span>
                                Page CSS: <a href="<?php printSiteUrl ( ) ?>styles" title="Manage page styles" rel="nofollow" tabindex="-1">
                                              edit
                                          </a>
                            </span>
                            <select name="css">
                                <?php
                                    if ( $styles ) {
                                        foreach ( $styles as $filename ) {
                                            $attr = $item[ 'css' ] == $filename ? 'selected'
                                                                                : '';
                                            ?>
                                            <option <?php printValue ( $attr ) ?>>
                                                <?php printValue ( $filename ) ?>
                                            </option>
                                            <?php
                                        }
                                    }
                                ?>
                            </select>
                        </label>

                        <label>
                            <span> Permission to edit next time: </span>
                            <select name="permission">
                                <option value="">
                                    Wherever you want
                                </option>
                                <option value="editor" <?php      echo $item[ 'permission' ] == 'editor' ? 'selected' : '' ?>>
                                    In the built-in HTML editor only
                                </option>
                                <option value="constructor" <?php echo $item[ 'permission' ] == 'constructor' ? 'selected' : '' ?>>
                                    In the built-in constructor only
                                </option>
                            </select>
                        </label>

                        <button class="btn"
                                name="submit2"
                                type="submit"
                                title="Save the changes you made on this page"
                                onclick="getEditorContent ( this )">
                            Save
                        </button>
                        <a class="btn" href="<?php printSiteUrl ( ) ?>pages" title="Return to the list of existing pages">
                            Cancel
                        </a>

                        <?php
                            /**
                             * ---------------------------------------------
                             *
                             * Links to another editors.
                             *
                             * ---------------------------------------------
                             */

                            $pageUrl = mimimiUri ( FALSE );
                            if ( helperIsConstructUrl ( ) ) {
                                $pattern = '~^(?:pages/)?construct(/.*)?$~uis';
                                $url1 = preg_replace ( $pattern, 'edit$1',   $pageUrl );
                                $url2 = preg_replace ( $pattern, 'markup$1', $pageUrl );
                                ?>
                                <p>Oops, I want to edit this page in a built-in <a href="<?php printSiteUrl (       );
                                                                                               printValue   ( $url1 ) ?>">HTML editor</a>
                                                                       or as an <a href="<?php printSiteUrl (       );
                                                                                               printValue   ( $url2 ) ?>">HTML Source</a> only.</p>
                                <?php
                            } else if ( helperIsMarkupUrl ( ) ) {
                                $pattern = '~^(?:pages/)?markup(/.*)?$~uis';
                                $url1 = preg_replace ( $pattern, 'construct$1', $pageUrl );
                                $url2 = preg_replace ( $pattern, 'edit$1',      $pageUrl );
                                ?>
                                <p>Oops, I want to edit this page in a built-in <a href="<?php printSiteUrl (       );
                                                                                               printValue   ( $url1 ) ?>">Constructor</a>
                                                               or in a built-in <a href="<?php printSiteUrl (       );
                                                                                               printValue   ( $url2 ) ?>">HTML editor</a>.</p>
                                <?php
                            } else {
                                $pattern = '~^(?:pages/)?[^/]+(/.*)?$~uis';
                                $url1 = preg_replace ( $pattern, 'construct$1', $pageUrl );
                                $url2 = preg_replace ( $pattern, 'markup$1',    $pageUrl );
                                ?>
                                <p>Oops, I want to edit this page in a built-in <a href="<?php printSiteUrl (       );
                                                                                               printValue   ( $url1 ) ?>">Constructor</a>
                                                                       or as an <a href="<?php printSiteUrl (       );
                                                                                               printValue   ( $url2 ) ?>">HTML Source</a> only.</p>
                                <?php
                            }
                        ?>
                    </div>

                    <?php
                        mimimiModule ([ 'snippets/editor-textarea.tpl',      $item ]);
                        mimimiModule ([ 'snippets/constructor-textarea.tpl', $item ]);
                        mimimiModule ([ 'snippets/markup-textarea.tpl',      $item ]);
                    ?>

                    <div class="right">
                        <button class="btn"
                                name="submit"
                                type="submit"
                                title="Save the changes you made on this page"
                                onclick="getEditorContent ( this )">
                            Save
                        </button>
                        <a class="btn" href="<?php printSiteUrl ( ) ?>pages" title="Return to the list of existing pages">
                            Cancel
                        </a>
                    </div>
                </div>
            </div>

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

        <?php
            mimimiModule ( 'snippets/editor-scripts.tpl'      );
            mimimiModule ( 'snippets/constructor-scripts.tpl' );
        ?>
        <script src="<?php printThemeUrl ( ) ?>js/edit.js"></script>
    </body>
</html>
