<?php


    # pagepost.php - Create or save a page


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


    # user rights- admins only
    if (get_account($_SESSION['userID'])['rights'] != 'administrator') {
        header('Location:panel.php');
        exit();
    }
    


    # POST values: uniqueid, title, description, content, filename, path



    # Create a page
    function pagepost() {
        
        
        $p = $_POST;
        
        $page = $p['uniqueid'].'.xml';
        $pagexml = simplexml_object($page,'l','page');
        $xml_struc = '<?xml version="1.0" encoding="utf-8"?><savedpage><title>Saved Page</title><pageinfo></pageinfo></savedpage>';

        
        # filename check
        if ($p['filename'] != '') {


            $filename = str_replace(array('&','/',' ','$','+',',',':',';','=','?','@','<','>','#','%','{','}','|','^','~','[',']','`','\\','\'','"'),'',$p['filename']);
            $filename = str_replace(array("\n","\r"),"",$filename);
            
                        
            # Filenames to be excluded
            # path => filename
            $names = [''=>'index',
                      '' => 'pagep'
                      ];


            
            if (array_search($filename,$names) === $p['catalogue']) {
                $filename = '_'.$filename;
            }
            
            
            
            # find out if the filename already exists
            $pages = glob('savedpages/*.xml');
            $cur = array_search('savedpages/'.$page,$pages);
            
            if ($cur !== false) 
                unset($pages[$cur]);
            
            foreach ($pages as $pg) {
                $file = simplexml_object(basename($pg),'l','page');
                if(!is_array($file)) {
                    $fname = $file->pageinfo->page->filename;
                    if ($filename == $fname && $file->pageinfo->page->path == $p['catalogue'])
                        $filename = '_'.$fname;
                }
            }
        
            

            # if the filename has changed by the user, delete the old one and also delete the respective page
            if (!is_array($pagexml)) {
                $oldname = $pagexml->pageinfo->page->filename;
                $pathxml = $pagexml->pageinfo->page->path;
                if ($oldname != $filename && is_file('../'.$pathxml.'/'.$oldname.'.php'))
                    unlink('../'.$pathxml.'/'.$oldname.'.php');
            }
        }
        
        else
            $filename = !is_array($pagexml) ? $pagexml->pageinfo->page->filename : '_'.time();
        
        
        
        
        # manage path/catalogue submit
        $pd = $p['catalogue'];
        $pagedir = str_replace([" ","\n","\r"],["-","",""],$pd);
        $pagedir = mb_strtolower($pagedir,'UTF-8');

        
        
        $denylist = simplexml_object('pages_na.xml','l',null);
        
        if ($denylist == ['missingfile']) {
        
            file_put_contents('filesinfo/pages_na.xml','<?xml version="1.0" encoding="utf-8"?><folders><foldername>..</foldername><foldername>.</foldername></folders>');
            $na = ['.','..','monofiles'];
        }
        
        else
            foreach($denylist->foldername as $val)
                $na[] = (string)$val;    
        
        

        $pagefolders = array_values(preg_split('/[\/]/',$pagedir,0,PREG_SPLIT_NO_EMPTY));
        
        $final = array_diff($pagefolders,$na);
        $depth = count($final);
        $path = $incpath = '';
        
        if ($depth > 0) {
            
            foreach ($final as $val)    
                $path .= $val.'/';
            
        
            $incpath = str_repeat('../',$depth);
            if (!is_dir('../'.$path))
                mkdir('../'.$path,0777,true);
        
        }
                
        # if the path has changed, remove page from previous path 
        if ($pagexml != ['missingfile'])
            if ($pagexml->pageinfo->page->path != $path)
                if (is_file('../'.$pagexml->pageinfo->page->path.'/'.$pagexml->pageinfo->page->filename.'.php'))
                    unlink('../'.$pagexml->pageinfo->page->path.'/'.$pagexml->pageinfo->page->filename.'.php');
                        


        


        
        # create file and update log
        if ($pagexml == ['missingfile']) {
            
            touch('savedpages/'.$page);
            $sum = get_log()['pages'];
            $sum += 1;
            update_log('pages',$sum);
        }
        
        $title = remove_tags($p['title']);
        $description = str_replace(array("\n","\r"),'',$p['description']);
        

        if (is_array($pagexml))
            $saved = new simpleXMLElement($xml_struc);
        else
            $saved = simplexml_object($page,'e','page');

        $saved->pageinfo->page->filename = $filename;
        $saved->pageinfo->page->title = $title;
        $saved->pageinfo->page->description = $description;
        $saved->pageinfo->page->editor = $_SESSION['userID'];
        $saved->pageinfo->page->path = $path;
        $saved->pageinfo->page->incpath = $incpath;
        $saved->pageinfo->page->modified = time();
        
        file_put_contents('savedpages/'.$p['uniqueid'].'.htm',str_replace(array('<?','?>'),'',$p['content']));    
        
        
        
            
        # Save the page
        if ($saved->pageinfo->page->published != 'hidden') {
        
            $pagecontent ='<?php $pn = "'.$p['uniqueid'].'"; $incp = "'.$incpath.'"; include "'.$incpath.'monofiles/path.php" ?>';
            
            $saved->pageinfo->page->lastmodpage = time();
            
            file_put_contents('../'.$path.$filename.'.php',$pagecontent);
            $visit = '<a href="../'.$path.$filename.'.php" target="_blank">Visit page</a>';
        
        }
        
        
        
        
        # Save xml
        simplexml_object_save($page,$saved,'page');
        
        
        # different messages for published and unpublished
        $visit = isset($visit) ? $visit : '<span>Unpublished</span>';
        echo 'Page saved - '.date("H:i",time()).'&nbsp;-&nbsp;'.$visit;
        
        return true;
    }

        
    if (isset($_POST['uniqueid']))
        pagepost()

?>