<?php


    ## Create or edit a post



    # login
    include_once 'data_connect.php';
    include_once 'log.php';


    
    ## user rights - user info
    # no admin rights or user info is needed but you can't edit somebody else's post if you're an author



    # Load post information or load a new empty form
    function loadpost() {
        
        if (isset($_GET['savedname'])) {
            
            $savedname = $_GET['savedname'];
            $xmlfile = simplexml_object($savedname,'l','post');

            if ($xmlfile == ['falsexml'])
                return 'File has errors';
            
            elseif ($xmlfile == ['missingfile'])
                return 'File is missing';
            
            else {

                # Check if access to the post file is allowed
                if (($_SESSION['userID'] == $xmlfile->postinfo->post->createdby) || (get_account($_SESSION['userID'])['rights'] == 'administrator')) {
                    # Either normal or 'nu' file
                    $filebase = basename($savedname,".xml");
                    $category = ($xmlfile->postinfo->post->category !== false) ? $xmlfile->postinfo->post->category : 'uncategorized';
                    $tags  = ($xmlfile->postinfo->post->tags !== false) ? $xmlfile->postinfo->post->tags : '';
                    $html_content = is_file('autosaves/content/'.$filebase.'.htm') ? file_get_contents('autosaves/content/'.$filebase.'.htm') : '';
                    $btnvalue = ($xmlfile->postinfo->post->type == 'Draft') ? 'Publish' : 'Update';
                    $values = ['title' => $xmlfile->postinfo->post->title,
                               'filename' => $xmlfile->postinfo->post->filename,
                               'metadescription' => $xmlfile->postinfo->post->description,
                               'filebase' => $filebase,
                               'category' => $category,
                               'tags' => $tags,
                               'html_content' => $html_content,
                               'btnvalue' => $btnvalue,
                               'dates' => 'dates'
                              ];
                    
                    return $values;
                }
                
                else 
                    return 'You cannot edit this post';
            }
        }
    
        else {
            
            $values = ['title' => '',
                       'filename' => '',
                       'metadescription' => '',
                       'category' => 'uncategorized',
                       'tags' => '',
                       'html_content' => '',
                       'btnvalue' => 'Publish',
                       'date' => date('d F Y'),
                       'filebase' => $_SESSION['userID'].time()
                      ];
            
            return $values;
        }
    
    }


    $pval = loadpost();
    $ctgr = $pval['category'];

    if (!is_array($pval)) {
        $_SESSION['ERROR'] = $pval;
        header('Location:opensaved.php');
        exit();
    }


    $texteditor = get_account($_SESSION['userID'])['texteditor'];



    ## extensions
    include 'command.php'



?>
<!doctype html>
<html>
<head>
<title>Post</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="cmstyle.css">
<?php include 'csstheme.php' ?>
</head>
<body>
    <style>
        .main{left:0;position:relative;width:100%;margin-right:0;max-width:88%;float:right;margin-top:80px}
        #newpost{<?php include 'cmcurrentpage.css' ?>}
    </style>
<?php



    # panel
    include 'mypanel.php';
    include 'en_code.php'



?>
    <div class="main">
        <form action="post.php" method="post" id="mainform"></form>
        <div class="clear"></div>
        <?php
            if ($texteditor == 'on') include 'text-editor-controls.php'
        ?>
        <div id="page" class="nocontent">
        <div id="action-block">
            <div id="result-block">
                <div id="resultt"></div>
            </div>
            
            <div class="postmore" tabindex="0">
                <span class="dot"></span>
                <span class="dot"></span>
                <span class="dot"></span>
                <div class="pmoptions">
                <!--<input type="submit" value="Preview" form="mainform" formtarget="preview" class="prev-but" name="previewbutton">&nbsp;|&nbsp;--><button class="close-but" onclick="closeEditor();location.href='opensaved.php'" type="button">Close</button>
                </div>
            </div>            
        
            <!-- Save , Post, Update-->
            <input name="savebutton" type="button" id="sd" class="stylish-button" value="Save" onclick="saveTime();sendTopost()">
            <input type="text" id="uuid" name="uniqueid" value="<?php print $pval['filebase'] ?>" form="mainform" hidden>
            <input name="postbutton" type="submit" class="stylish-button" id="pd" onclick="closeEditor()" onsubmit="document.getElementById('page').className = 'nocontent'" value="<?php print $pval['btnvalue'] ?>" form="mainform">
        </div>
            <div class="newpageleft">
                <div id="editor-container">
                    <textarea name="title" class="grow" id="headline" form="mainform" placeholder="Title"><?php print $pval['title'] ?></textarea>
                    
                    
                    <?php if ($texteditor == 'on') : ?> 
                    <div id="editor" contenteditable></div>
                    <div id="output-container" class="hide">
                    <?php else : ?>
                        
                        <div id="output-container">
                        
                        
                        <?php endif ?>
                        
                        
                        <textarea name="content" id="output" autocomplete="off" form="mainform"><?php

                           if (isset($pval['html_content']))
                               print $pval['html_content']

                          ?>
</textarea>
                    </div>
                </div>
                <div class="clear"></div>
            </div>
        
        
            <!-- Meta & info -->
            <div class="newpageright">
                <!--<div class="postinfo">Image</div>
                <textarea type="text" name="postimage" id="postimage" form="mainform"></textarea>-->
                <div class="postinfo">Filename</div>
                <textarea type="text" name="filename" id="filename" form="mainform"><?php print $pval['filename'] ?></textarea>
                <div class="postinfo">Meta description</div>
                <textarea type="text" name="description" id="metades" form="mainform"><?php print $pval['metadescription'] ?></textarea>
                <div class="postinfo">Tags (separate with ',')</div>
                <textarea type="text" name="tags" id="tags" form="mainform"><?php print $pval['tags'] ?></textarea>
                <!--<div class="postinfo">Pick Date</div>-->
                <div class="postinfo">Category</div>
                <div class="categories">
                    <select name="category" class="selcat" onchange="warning();" form="mainform">
                        <option value="<?php print $ctgr ?>"><?php echo $ctgr ?></option>
                        <?php 
                        if ($ctgr != 'uncategorized') 
                            print '<option value="uncategorized">uncategorized</option>'; 

                        # see get_categories() function
                        $folders = get_categories();
                            
                        foreach($folders as $name) 
                            if ($name != $ctgr)
                                echo '<option value="'.$name.'">'.$name.'</option>';    
                        
                        ?>
                    </select>
                </div>
            </div>
        </div>
        <script>
            function warning() {
                var d = document.getElementById('page'); 
                if (d.className == 'nocontent')
                    d.className = 'nocontent warn'; }
            
            function closeEditor() {
                document.getElementById('sd').setAttribute('disabled','true'); }    

            function inputEnabled() {
                var inps = document.getElementsByTagName('input');
                    for (i=0; i<inps.length; i++)
                        inps[i].removeAttribute('disabled'); }

            function saveTime() {
            document.getElementById('sd').setAttribute('disabled','true');
            document.getElementById('pd').setAttribute('disabled','true'); }

            
            function sendTopost() {
                var mes = document.getElementById('resultt');
                var pag = document.getElementById('page');
                var myForm = document.getElementById('mainform');
                var sendpost = new XMLHttpRequest();
                
                var myData = new FormData(myForm);
                myData.append('savebutton','true');
                

                mes.innerHTML = '';
                pag.setAttribute("style","opacity:.5");
                
                sendpost.open('POST','post.php',true);
                sendpost.onreadystatechange = function() {

                    if (this.readyState == 4) {
                        pag.setAttribute("style","opacity:1");
                        pag.setAttribute("class","nocontent");
                        inputEnabled();

                        if (this.status == 200) {
                            var savetxt = sendpost.responseText;
                            mes.innerHTML = '<span class="posted">' + savetxt + '</span>';
                        }

                        else
                            mes.innerHTML = '<span class="posted" style="color:red">**Error:could not save</span>';
                    }
                }
                sendpost.send(myData);
            }

            
        </script>
        <script>
            var ar = ['filename','headline','output','metades','tags'];
            function wwarn(idval) {
                document.getElementById(idval).onkeyup = function() { warning(); }
                document.getElementById(idval).onpaste = function() { warning(); }
            }
            ar.forEach(wwarn);
        </script>
        <script>
            window.onbeforeunload = function() {
                if (document.querySelector('.warn') !== null) {
                    inputEnabled();
                    return false;
                }
            }
            
        </script>
        <?php    
        
            if ($texteditor == 'on') :
            
        ?>
            
        <script src="javascript/text-editor.js"></script>
            
    </div>
    <?php
        
    endif;
        
        
        
    #plugins
    include 'execute.php'



?>
</body>
</html>