<?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 filename ('nu' -> not updated).
    # This file replaces the standard xml file, for as long as you keep the 'not updated' version unpublished.
    

    include_once 'data_connect.php';
    include_once 'log.php';
    include 'en_code.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') {
        
        if (isset($_POST['uniqueid'])) {
            
            $postfile = $_POST['uniqueid'].'.xml';
            
            if (is_file('autosaves/'.$postfile)) {
                
                $userinfo = simplexml_object($postfile,'l','post');
                
                if ($userinfo->postinfo->post->createdby != $_SESSION['userID']) {
                    
                    if (isset($_POST['savebutton']))
                        exit('You cannot edit this file');
                    
                    else {
                        $_SESSION['errorpost'] = true;
                        header('Location:opensaved.php');
                    }
                }
            }
        }
    }




    
# xml file structure
$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>
            <category></category>
            <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;
        $xmlname = substr($xmlname,-2) == 'nu' ? substr($xmlname,0,-2) : $xmlname;
        
        if ($filename !== false) {
        
            $filename = str_replace(
                array('&','/',' ','$','+',',',':',';','=','?','@','<','>','#','%','{','}','|','^','~','[',']','`','\\','\'','"'),'',$filename);
            $filename = str_replace(array("\n","\r"),'',$filename);
            
        
            if ($filename == '') {
                $filename = 'post_'.time();
            
            }
            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);
                
                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;
        }
        
        else
            return false;
    }







    # 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');
        
        
        if ($saved[0] == 'missingfile') {
            
            $saved = new simpleXMLElement($GLOBALS['xmlfile']);
            $saved->postinfo->post->createdby = $_SESSION['userID'];
            $saved->postinfo->post->type = 'Draft';
            
            $sum += 1;
        }
            
        
        
        $saved->postinfo->post->title = $post->title;
        $saved->postinfo->post->description = str_replace(array("\n","\r"),'',(string)$post->description);
        $saved->postinfo->post->tags = str_replace(array("\n","\r"),'',(string)$post->tags);
        $saved->postinfo->post->category = $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';
        
        }
        else
            $nuornot = $post->uniqueid.'.htm';
            
        if ($post->content != '')
            file_put_contents('autosaves/content/'.$nuornot,str_replace('<?','',$post->content));
        
        
        if (simplexml_object_save($xmlname,$saved,'post') !== false)
            update_log('posts',$sum);
                
        echo 'saved - '.date('H:i',time());
        
        return true;
    }





    # post() - Publish a new post or Update
    function post() {
            
        
        # includes
        include_once 'en_code.php';
        

        # create class object
        $post = (object)$_POST;
        
        $sum = get_log()['posts'];
        $xmlname = (string)$post->uniqueid;
        $xmlname = substr($xmlname,-2) == 'nu' ? substr($xmlname,0,-2) : $xmlname;
        $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
            $fname = filename_check();
            
            if ($fname != false && $fname != $oldname) {
                
                file_put_contents('../'.$oldpath.$fname.'.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 = str_replace(array("\n","\r"),'',(string)$post->tags);
        
        $saved->postinfo->post->title = $title;
        $saved->postinfo->post->description = $description;
        $saved->postinfo->post->tags = $tags;
        $saved->postinfo->post->category = $post->category;
        $saved->postinfo->post->filename = isset($fname) ? $fname : filename_check();
        $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(array('<?','?>'),'',$post->content));
        
        
        

        # Post: excerpt limit - Find the 'read more' position  inside $content
        preg_match_all('/(?<=\<hr)(.*?)(?=\>)/',$post->content,$excerpt_cut,PREG_SET_ORDER);

        $excerpt = 'none';
        foreach($excerpt_cut as $pregres) {
            foreach ($pregres as $res) {
                $excpos = strpos($res,'id="monreadmoreHr"');
                if ($excpos !== false) {
                    $excerpt = strpos($post->content,$res) - 3;
                    break;
                }
            }
        }
        # save excerpt. note: The excerpt is an integer indicating the position of the text limit
        $saved->postinfo->post->excerpt = $excerpt;
        
        
        # Post: Create folders and files for tags
        $sep = array_values(preg_split('/[,]/',$tags,PREG_SPLIT_NO_EMPTY));
        $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.' ?>');
            }
        }
        
        
        
        
        #Post: 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;
            $filename = filename_check();
            file_put_contents('../'.$path.$filename.'.php','<?php $fn = \''.$xmlname.'.xml\'; include \'../../monofiles/prepost.php\' ?>');

        }

        
        
        # Post: 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);
            
        
        
        
        $_SESSION['newpost'] = 'posted';
        
        
        
        return true;
        
    }
    



    # Get the post action
    $action = array('savebutton','postbutton','previewbutton');
    foreach($action as $ac) {
        if (isset($_POST[$ac])) {
            $btn = $ac;
            break;
        }
    }
    
    
    switch($btn) {
        case 'savebutton':
            save();
            break;
        case 'postbutton':
            post();
            header('Location:opensaved.php');
            break;
        case 'previewbutton':
            preview();
            header('Location:preview.php');
            break;
        default:
            echo 'no action found...';
    }


    # plugins
    include 'execute.php';

        
?>