<?php
/**
 * -------------------------------------------------------------------------
 *
 * Template to display the Upload Fragment Block page.
 *
 * -------------------------------------------------------------------------
 *
 * Input parameters are:
 *
 *     $params = A contents of the previous Fragment file.
 *
 * -------------------------------------------------------------------------
 *
 * 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   = '';
    $url     = helperGetFragmentUrl ( );

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

    if ( getFormInput ( 'submit' ) ) {

        $newUrl = makeSecureUrl (
                      getFormInput ( 'url' )
                  );

        /**
         * -----------------------------------------------------------------
         *
         * 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 ( $newUrl ) ) {

                /**
                 * ---------------------------------------------------------
                 *
                 * Then we must check the uploaded file.
                 *
                 * ---------------------------------------------------------
                 */

                $data = mimimiFiles ( 'upload' );
                if ( helperValidateFragmentFile ( $data ) ) {

                    /**
                     * -----------------------------------------------------
                     *
                     * 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 = $url != $newUrl ? helperLoadFragment ( $newUrl )
                                                  : '';
                        if ( $params == '' ) {

                            /**
                             * ---------------------------------------------
                             *
                             * Try to upload this file and redirect the admin
                             * to the Fragment Blocks page.
                             *
                             * ---------------------------------------------
                             */
 
                            helperUploadFragment ( $newUrl, $data );
                            helperGotoPage ( 'fragments' );

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

                        } else {
                            $error = 'You are trying to upload a TPL file to another URL that is already taken! To do this, you need to upload the Fragment using a direct link to its file.';
                        }
                    } else {
                        $success = 'Everything is fine! However, you are currently in demo mode. Any uploading 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 = 'Sorry, you must select a TPL, HTM, or HTML file!';
                }
            } 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 uploading a TPL file). Try again in ' . STATICPAGESONLY_TIMEOUT_FOR_EDIT . ' seconds.';
        }

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

        $url = $newUrl;
    }

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

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

    /**
     * ---------------------------------------------------------------------
     *
     * Now we can generate the page content.
     *
     * ---------------------------------------------------------------------
     *
     * Please note that the input form below is protected by a <div> tag
     * instead of the classic <form> tag. Additionally, its submit button is
     * protected by removing the "value=1" attribute. Automatic removal of
     * protection is performed by calling the secureForm() function
     * implemented in the "static.pages.only/Themes/default/js/login.js"
     * file.
     *
     * This trivial protection allows you to protect the site from many spam
     * bots that try to send any form found on your site.
     *
     * ---------------------------------------------------------------------
     */

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

        <title>
            Upload Fragment File
        </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/upload.css">
    </head>

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

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

            <main class="content">
                <div class="left">
                    <h1 class="title">
                        Upload Fragment
                    </h1>
                    <p>If you have a TPL, HTM, or HTML file, you can upload it to the desired URL relative to the <code title="<?php printValue ( helperGetFragmentsPath ( ) ) ?>"></code> directory.</p>

                    <a class="btn" href="<?php printSiteUrl ( ) ?>fragments" title="Return to the list of existing Fragment blocks">
                        Cancel
                    </a>
                </div>

                <div class="right">
                    <svg viewBox="0 0 320 300">
                        <defs>
                            <linearGradient inkscape:collect="always"
                                            id="linearGradient"
                                            x1="13"
                                            y1="193.49992"
                                            x2="307"
                                            y2="193.49992"
                                            gradientUnits="userSpaceOnUse">
                                <stop style="stop-color:#ff00ff;"
                                      offset="0"
                                      id="stop876" />
                                <stop style="stop-color:#ff0000;"
                                      offset="1"
                                      id="stop878" />
                            </linearGradient>
                        </defs>
                        <path d="m 40,120.00016 239.99984,-3.2e-4 c 0,0 24.99263,0.79932 25.00016,35.00016 0.008,34.20084 -25.00016,35 -25.00016,35 h -239.99984 c 0,-0.0205 -25,4.01348 -25,38.5 0,34.48652 25,38.5 25,38.5 h 215 c 0,0 20,-0.99604 20,-25 0,-24.00396 -20,-25 -20,-25 h -190 c 0,0 -20,1.71033 -20,25 0,24.00396 20,25 20,25 h 168.57143" />
                    </svg>

                    <div class="form" enctype="multipart/form-data">
                        <label>
                            Relative URL:
                            <input name="url"
                                   type="text"
                                   maxlength="255"
                                   value="<?php printValue ( $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>
                            HTML File:
                            <input name="upload"
                                   type="file"
                                   accept=".tpl, .htm, .html"
                                   required
                                   tabindex="2">
                        </label>

                        <button class="btn"
                                name="submit"
                                type="submit"
                                tabindex="3">
                            Upload
                        </button>
                    </div>
                </div>
            </main>

            <footer class="footnote">
                <a href="<?php printSiteUrl ( ) ?>" title="Go to the home page">
                    Home
                </a>

                <a href="<?php printSiteUrl ( ) ?>credits" title="Gratitude to third party developers">
                    Credits
                </a>
            </footer>
        </div>

        <script src="<?php printThemeUrl ( ) ?>js/animejs-2.2.0.min.js"></script>
        <script src="<?php printThemeUrl ( ) ?>js/upload.js"></script>
    </body>
</html>
