<?php

    # post.php - Create, save and edit posts

    # If you want to modify a published post and save the changes to review later, a new file is created
    # with the string 'nu' at the end of the file's name ('nu' -> not updated).
    # This file replaces the standard xml file, for as long as you keep the 'not updated' version unpublished.
    # If post is changed to Draft, the 'nu' file remains and only if you publish again, it is removed.
    


    include_once 'data_connect.php';
    include_once 'log.php';


    
    # Postlog values :uniqueid, title, description, content, tags, category, filename
    # $plog = (object)$_POST;
    

    
    # Usertype
    define('USERTYPE',get_account($_SESSION['userID'])['rights']);


    # Prevent an author from editing somebody else's file
    if (USERTYPE != 'administrator' && isset($_POST['uniqueid'])) {
        
        $userinfo = simplexml_object($_POST['uniqueid'].'.xml','l','post');    
        if (!is_array($userinfo) && $userinfo->postinfo->post->createdby != $_SESSION['userID']) {
                
            if (isset($_POST['savebutton']))
                exit('You cannot edit this file');
                
            else {
        
                $_SESSION['errorpost'] = true;
                header('Location:opensaved.php');
                exit;
            }
        }
    }




    
# xml file structure Tag 'file' not included, added later
$xmlfile = '<?xml version="1.0" encoding="UTF-8"?>
<savedpost>
<title>Savedpost</title>
<postinfo>
<post>
    <createdby></createdby>
    <filename></filename>
    <title></title>
    <excerpt></excerpt>
    <description></description>
    <type></type>
    <modified></modified>
    <tags></tags>
    <catid></catid>
    <editedby></editedby>
    <path></path>
    <ptime></ptime>
    <firstpost></firstpost>
    </post>
</postinfo>
</savedpost>';




    # Filename check
    function filename_check() {
        
        $plog = (object)$_POST;
        
        $filename = $plog->filename;
        $xmlname = $plog->uniqueid;
        
        if (substr($xmlname,-2) == 'nu')
            $xmlname = substr($xmlname,0,-2);
        
        
        $filename = str_replace(['&','/',' ','$','+',',',':',';','=','?','@','<','>','#','%','{','}','|','^','~','[',']','`','\\','\'','"'],'',$filename);
        $filename = str_replace(["\n","\r"],'',$filename);
        
    
        if ($filename == '')
            $filename = 'post_'.bin2hex(random_bytes(4));
        
        
        else {
            
            
            # We take all xml files, excluding the current one(if it exists), then check all their filenames.
            $pinball = glob('autosaves/*.xml');
            $cur_xml = 'autosaves/'.$xmlname.'.xml';
            $cur_nu = 'autosaves/'.$xmlname.'nu.xml';
            
            
            $cur_xml_pos = array_search($cur_xml,$pinball);
            $cur_nu_pos = array_search($cur_nu,$pinball);
            $as = array_search('autosaves/autosaves.xml',$pinball);
            
            unset($pinball[$as]);
            
            if ($cur_xml_pos !== false)
                unset($pinball[$cur_xml_pos]);
            
            if ($cur_nu_pos !== false)
                unset($pinball[$cur_nu_pos]);

            
            foreach ($pinball as $post) {
                
                $file = simplexml_object($post,'l','post');
                $name = $file->postinfo->post->filename;
                if ($name == $filename) {
                    $filename = '_'.$name;
                    break;
                }
            }
        }
    

        return $filename;
        
    }







    # save() - Save a post, as 'Draft' or 'Posted\Not updated'
    function save() {
            
        
        $post = (object)$_POST;
        
        $sum = get_log()['posts'];
        $xmlname = $post->uniqueid.'.xml';
        $saved = simplexml_object($xmlname,'e','post');
        $heavy = simplexml_object('autosaves.xml','e','post');
        $heavyname = $post->uniqueid;
        
        if (is_array($saved)) {
            
            $saved = new simpleXMLElement($GLOBALS['xmlfile']);
            $saved->postinfo->post->createdby = $_SESSION['userID'];
            $saved->postinfo->post->type = 'Draft';
            
            $sum += 1;
        }
            
        
            
        # Tags version 2.4
        $notallowed = ['montag-','\\',',','"','.','\'','#','%','^','/'];
        $posttags = '';
        foreach($_POST as $k=>$v)
            if (substr($k,0,7) == 'montag-')
                $posttags .= $v.',';
        
        $tags = rtrim($posttags,',');
        
        
    
        # save
        $saved->postinfo->post->title = $post->title;
        $saved->postinfo->post->description = str_replace(array("\n","\r"),'',(string)$post->description);
        $saved->postinfo->post->tags = $tags;
        $saved->postinfo->post->catid = $post->category;
        $saved->postinfo->post->filename = filename_check();
        $saved->postinfo->post->editedby = $_SESSION['userID'];
        $saved->postinfo->post->modified = time();
        
        
        if ($saved->postinfo->post->type != 'Draft' && $saved->postinfo->post->type != 'Posted/Not updated') {
            
            $saved->postinfo->post->type = 'Posted/Not updated';
            $xmlname = $post->uniqueid.'nu.xml';
            $nuornot = $post->uniqueid.'nu.htm';
            $heavyname = $post->uniqueid.'nu';
        
        }
        else
            $nuornot = $post->uniqueid.'.htm';

        file_put_contents('autosaves/content/'.$nuornot,str_replace('<?','',$post->content));
        if (simplexml_object_save($xmlname,$saved,'post') !== false)
            update_log('posts',$sum);


        # Turbomode - save in autosaves.xml - 2.4v
        if (!is_array($heavy)) {
            
            $saved->postinfo->post->file = $heavyname;
            $r=count($heavy);
            $rc=0;
            foreach($heavy->savedpost as $f) {
                if ($f->postinfo->post->file == $heavyname) {
                    $r = $rc;
                    break;
                }
                $rc++;
            }
            

            # creating a new line will help get_tags() function
            $heavy->savedpost[$r] = PHP_EOL;

            foreach($saved->postinfo->post->children() as $tag=>$val)    
                $heavy->savedpost[$r]->postinfo->post->$tag = $val;
        
            
            simplexml_object_save('autosaves.xml',$heavy,'post');

        }
        
            
                
        echo 'saved - '.date('H:i',time());
        
        
        
        return true;
    }





    # Publish a new post or Update
    function post() {
            
        
        # includes
        include 'en_code.php';
        
        # filename
        $filename = filename_check();

        # create class object
        $post = (object)$_POST;
        
        $sum = get_log()['posts'];
        $xmlname = (string)$post->uniqueid;
            
        if (substr($xmlname,-2) == 'nu')
            $xmlname = substr($xmlname,0,-2);

    
        $saved = simplexml_object($xmlname.'.xml','e','post');
        
        
            
        if ($saved[0] == 'missingfile') {
            
            $saved = new simpleXMLElement($GLOBALS['xmlfile']);
            $sum += 1;
            $saved->postinfo->post->firstpost = time();
        }

        
        if ($saved->postinfo->post->type != 'Posted/Not updated' && $saved->postinfo->post->type != 'Posted') {

            $saved->postinfo->post->createdby = $_SESSION['userID'];
            $ptime = time();

            $saved->postinfo->post->ptime = $ptime;
            
        }
        
        
        else {
            
            $oldpath = $saved->postinfo->post->path;
            $oldname = $saved->postinfo->post->filename;
            
            # Post: If the filename of an updated post has changed, write a new file and delete the old
            
            if ($filename !== false && $filename != $oldname) {
                
                file_put_contents('../'.$oldpath.$filename.'.php','<?php $fn =\''.$xmlname.'.xml\';include \'../../monofiles/prepost.php\' ?>');
                if (is_file('../'.$oldpath.$oldname.'.php'))
                    unlink('../'.$oldpath.$oldname.'.php');
            
            }
        }
        
        
        $title = remove_tags((string)$post->title);
        $description = remove_tags((string)$post->description);
        $description = str_replace(array("\n","\r"),'',$description);
        
        
        # Tags version 2.4
        $notallowed = ['montag-','\\',',','"','.','\'','#','%','^','/'];
        $posttags = '';
        foreach($_POST as $k=>$v)
            if (substr($k,0,7) == 'montag-')
                $posttags .= $v.',';
        
        $tags = rtrim($posttags,',');
        
        
        $saved->postinfo->post->title = $title;
        $saved->postinfo->post->description = $description;
        $saved->postinfo->post->tags = $tags;
        $saved->postinfo->post->catid = $post->category;
        $saved->postinfo->post->filename = $filename;
        $saved->postinfo->post->editedby = $_SESSION['userID'];
        $saved->postinfo->post->modified = time();
        $saved->postinfo->post->type = 'Posted';
        file_put_contents('autosaves/content/'.$xmlname.'.htm',str_replace(['<?','?>'],'',$post->content));
        
        
        $content = (string)$post->content;


        # Post: excerpt limit - Find the 'read more' position inside $content
        # See also en_code.php

        $strip = substr($content,0,strpos($content,'<hr id="monreadmoreHr"'));
        $strip = str_replace(PHP_EOL,'',$strip);
        $strip = preg_replace('/  +/',' ',$strip);
        $strip = html_entity_decode(str_replace('&nbsp;',' ',$strip),ENT_HTML5);
        $excerpt = mb_strlen(strip_tags($strip));


        if ($excerpt == 0)
            $excerpt = 'none';
            
        # save excerpt. note: The excerpt is an integer indicating the position of the text limit
        $saved->postinfo->post->excerpt = $excerpt;
        
        
        # Create folders and files for tags
        $sep = explode(',',$tags);
        $tagsroot = '../tags/';
        foreach($sep as $k=>$val) {

            $low = mb_strtolower($val,'UTF-8');
            # also replace spaces with '-'
            $low = str_replace(' ','-',$low);
            
            if (!is_dir($tagsroot.$low)) 
                mkdir($tagsroot.$low,0777,true);
    
            $tagscontent = 'include "../../monofiles/path.php"';
            file_put_contents($tagsroot.$low.'/index.php','<?php $tagg="'.$val.'";'.$tagscontent.' ?>');
            
            
        }
        
        
        
        # Create folders and files of new post
        if (isset($ptime)) {
            
            $dir = date('Y',time()).'/'.date('m',time());
            if (!is_dir('../'.$dir))
                mkdir('../'.$dir,0777,true);
                
            $path = $dir.'/';
            $saved->postinfo->post->path = $path;
            
            file_put_contents('../'.$path.$filename.'.php','<?php $fn = \''.$xmlname.'.xml\'; include \'../../monofiles/prepost.php\' ?>');
    
        }

        

        
        # Remove  the 'nu' files
        if (is_file('autosaves/'.$xmlname.'nu.xml'))
            unlink('autosaves/'.$xmlname.'nu.xml');

        if (is_file('autosaves/content/'.$xmlname.'nu.htm'))
            unlink('autosaves/content/'.$xmlname.'nu.htm');

                
        if (simplexml_object_save($xmlname.'.xml',$saved,'post') !== false)
            update_log('posts',$sum);
        
        
        
        # Turbomode - save in autosaves.xml - 2.4
        $heavy = simplexml_object('autosaves.xml','e','post');
        
        if (!is_array($heavy)) {
        
            $saved->postinfo->post->file = $xmlname;
            $r=count($heavy);
            $rc=0;
            foreach($heavy->savedpost as $f) {
                
                if ($f->postinfo->post->file == $xmlname)
                    $r = $rc;

                if ($f->postinfo->post->file == $xmlname.'nu')
                    $uns = $rc; # normally, nu entry comes after normal
     
                $rc++;
            }
            
            if (isset($uns))
                unset($heavy->savedpost[$uns]);
            
            
            
            #needed for tags to work properly(?)
            $heavy->savedpost[$r] = PHP_EOL;
            
            
            foreach($saved->postinfo->post->children() as $tag=>$val)
                $heavy->savedpost[$r]->postinfo->post->$tag = $val;

            simplexml_object_save('autosaves.xml',$heavy,'post');            


        }
        

        $_SESSION['newpost'] = 'posted';
        
        
        return true;
        
    }
    


    # Get the post action
    if (isset($_POST['savebutton']))
        save();
    
    elseif (isset($_POST['postbutton'])) {
        
        post();
        header('Location:opensaved.php');
    
    }


?>