<?php


    # Posts and website content



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

    
    
    # user rights - user info
    $accinfo = get_account($_SESSION['userID']);
    
    
    
    # sort posts
    # GET parameters to include and return back to posts or pages page
    if (isset($_GET['sortposts'])) {
        
        
        $params = ['filtauthor','filtcategory','filtstatus'];
        $p = '';
        
        foreach($params as $v) 
            if (isset($_GET[$v]))
                $p = $p == '' ? '?'.$v.'='.$_GET[$v] : $p.'&'.$v.'='.$_GET[$v];
                

        # save in session and user account
        $_SESSION['sortposts'] = $_GET['sortposts'];
        edit_useraccount('sortposts',$_GET['sortposts']);

        header('Location:opensaved.php'.$p);
        exit;
    }


    # extensions
    include 'command.php'

    

?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Posts</title>
<link rel="stylesheet" type="text/css" href="cmstyle.css">
<?php include 'csstheme.php' ?>
<script type="text/javascript">function conf(form){return confirm('Delete post?');}</script>
<script type="text/javascript">function draft(form){return confirm('Change to Draft?');}</script>
</head>
<body>
    <style>
    #posts{<?php include 'cmcurrentpage.css' ?>}
    </style>
    <?php
        
    
        include 'mypanel.php';
        action_confirm();
        
        
        # get the filters and create link parameters for filters menu
        $plink=$clink=$alink=$slink='';
        $filters = ['filtcategory'=>['alink','slink'],'filtauthor'=>['clink','slink'],'filtstatus'=>['clink','alink']];
        $nof=0;
        foreach ($filters as $f=>$a)
            if (isset($_GET[$f])) {
                $plink .= '&'.$f.'='.$_GET[$f];
                $nof++;
                foreach($a as $v)
                    $$v = $$v == '' ? '?'.$f.'='.$_GET[$f] : $$v.'&'.$f.'='.$_GET[$f];
            }

                    
        # search through files and get type, category and createdby values as filter information
        $directory = new DirectoryIterator('autosaves/');
        
        $ar_cat = [];
        $ar_auth = [];
        $ar_stat = [];
    
        foreach($directory as $fileinfo) {

            
            if ($fileinfo->isFile()) {
                
                
                # if there is a 'nu' version of the file, we ignore the current file
                $name = basename($fileinfo->getFilename(),'.xml');
                if (is_file('autosaves/'.$name.'nu.xml'))
                    continue;

                
                $s = simplexml_object($name.'.xml','l','post');
                
                
                $type = (string)$s->postinfo->post->type;

                if (array_search($type,$ar_stat) === false)
                    $ar_stat[] = $type;

                $catgr = (string)$s->postinfo->post->category;
                if (array_search($catgr,$ar_cat) === false)
                    $ar_cat[] = $catgr;

                $auth = (string)$s->postinfo->post->createdby;
                if (array_search($auth,$ar_auth) === false) {

                    $ar_auth[] = $auth;

                    # $auth is the user's ID (not current user)
                    $author_account = get_account($auth);
                    $ar_authname[] = $author_account['editorname'];

                }
            }
        }

    ?>

    <div class="main">
        <h1>Posts <a class="newpostbut" href="newpage.php" id="newpost" title="Write a post"><span class="addnew">+</span>&nbsp;Write a post</a></h1>
        <div class="headpages">
        <div style="clear:both;height:34px"></div>
            
        Category <select id="selectcategory" onchange="window.location=this.value">
                <?php

                    $optall = '<option value="#">All</option>';
                    
                    if (isset($_GET['filtcategory']))
                        echo '<option value="#">'. $_GET['filtcategory'].'</option>'.PHP_EOL.'<option value="opensaved.php'.$clink.'">All</option>';
                    else
                        echo $optall;

                    $clink = $clink == '' ? '?' : $clink.'&';
                    foreach($ar_cat as $ts)
                        if (isset($_GET['filtcategory']) && $_GET['filtcategory'] != $ts || !isset($_GET['filtcategory']))
                            print '<option value="opensaved.php'.$clink.'filtcategory='.$ts.'">'.$ts.'</option>'
                ?>
        </select>
        <?php if ($monrights == 'administrator') : ?>
        Author <select id="selectauthor" onchange="window.location=this.value">
                <?php         

                    if (isset($_GET['filtauthor']))
                        echo '<option value="#">'.get_account($_GET['filtauthor'])['editorname'].'</option>'.PHP_EOL.'<option value="opensaved.php'.$alink.'">All</option>';
                    else 
                        echo $optall;

                    if (!empty($ar_authname)) {
                        $real_authors = array_combine($ar_auth,$ar_authname);
                        $alink = $alink == '' ? '?' : $alink.'&';
                        foreach($real_authors as $id=>$name)
                            if (isset($_GET['filtauthor']) && $_GET['filtauthor'] != $id || !isset($_GET['filtauthor'])) 
                                print '<option value="opensaved.php'.$alink.'filtauthor='.$id.'">'.$name.'</option>';
                    }

                ?>
        </select>
        <?php endif ?> 
        Status <select id="selectstatus" onchange="window.location=this.value">
                <?php 

                    if (isset($_GET['filtstatus']))
                        echo '<option value="#">'. $_GET['filtstatus'].'</option>'.PHP_EOL.'<option value="opensaved.php'.$slink.'">All</option>';
                    else 
                        echo $optall;

                    $slink = $slink == '' ? '?' : $slink.'&';
                    foreach($ar_stat as $ts)
                        if (isset($_GET['filtstatus']) && $_GET['filtstatus'] != $ts || !isset($_GET['filtstatus']))
                            print '<option value="opensaved.php'.$slink.'filtstatus='.$ts.'">'.$ts.'</option>';

                ?>
        </select>    
        <div class="results-set">
            <div class="normal-res">
                <span style="font-size:12px">Results per page &nbsp;</span>
                <?php
                
                $spv = ['sortbyalpha','sortbytime','sortbytitle','sortbyrev','Alphabetical order (z-a)','Chronological order','Reverse alphabetical order (z-a)','Reverse chronological order'];
                # Menu with get values
                $sort_params = ['sortbytitle'=>[$spv[0],$spv[1],1,'',$spv[6],$spv[5]],
                                'sortbyalpha'=>['sortbytitle','sortbytime',2,'','Alphabetical order (a-z)','Chronological order'],
                                'sortbyrev'=>['sortbytitle','sortbytime','',2,'Alphabetical order (a-z)','Chronological order'],
                                'sortbytime'=>['sortbytitle','sortbyrev','',1,'Alphabetical order (a-z)','Reverse chronological order']];    

                foreach ($sort_params as $key=>$val)
                    
                    if ($_SESSION['sortposts'] == $key) {
                        
                        $partitle = '?sortposts='.$val[0];
                        $parlastmod = '?sortposts='.$val[1];
                        $class_title = $val[2];
                        $class_lastmod = $val[3];
                        $title_attr_val = $val[4];
                        $lastmod_attr_val = $val[5];
                        break;
                        
                    }
                
                pageResults('posts',$plink)
                
                ?>
            </div>
        </div>
    </div>
        
        <div id="main-container">
            <div class="results">
                <div class="pbar">
                    
                    <span id="pbar-title">
                        <a href="opensaved.php<?php
                    
                    print $partitle.$plink.'" title="'.$title_attr_val.'" class="sort'.$class_title; 
                    
                    ?>
">Title</a>
                    </span>
                    <span class="lastmodbar">
                    <a href="opensaved.php<?php 
                    
                    print $parlastmod.$plink.'" title="'.$lastmod_attr_val.'" class="sort'.$class_lastmod;
                    
                    ?>
">Last modified</a>
                    </span>
                
                
                </div>
                <?php
                        
                # Get all posts    
                # Use the $directory class to get files, then 
                # print results based on sorting values and filters
                        
                        
                $array_xml = $array_temp = [];
                $filtersxml = array('filtcategory'=>'category','filtauthor'=>'createdby','filtstatus'=>'type');
                
                foreach ($filtersxml as $filt=>$xmlvalue) {
                    foreach ($directory as $fileinfo) {
                        
                        if ($fileinfo->isFile()) {

                            $name = $fileinfo->getFilename();
                            $s = simplexml_object($name,'l','post');
                            $mtime = (int)$s->postinfo->post->modified;
                            $creator = $s->postinfo->post->createdby;
                            $posttitle = ($s->postinfo->post->title == '') ? '(no title)': $s->postinfo->post->title;
                            
                            $nuname = basename($name,'.xml');
                            # Get the 'nu' version of a file, if it exists
                            if (!is_file('autosaves/'.$nuname.'nu.xml')) {
                                if ( ($accinfo['rights'] == 'administrator') || ($creator == $_SESSION['userID']) ) {
                                    if (isset($_GET[$filt]) && $_GET[$filt] == $s->postinfo->post->$xmlvalue || $plink == '')
                                        $array_temp[] = 'autosaves/'.$name;
                                }
                            }
                        }
                    }
                    
                    unset($creator);
                }

                if (count($array_temp) > 0) {
                
                    $realarray = array_count_values($array_temp);
                    $filt_number =  max($realarray);


                    # if filters are 0 or ALL the filters that are applied are found, then we print the results
                    if ($plink == '' || $filt_number == $nof) {

                        foreach($realarray as $val=>$rep)
                            if ($rep == $filt_number)
                                $array_xml[] = basename($val);

                        $st=0;
                        foreach($array_xml as $val) {
                        
                            $file = simplexml_object($val,'l','post');
                            
                            if ($_SESSION['sortposts'] == 'sortbytitle' || $_SESSION['sortposts'] == 'sortbyalpha')
                                $array_param[] = strtolower($file->postinfo->post->title).$st;
                            else
                                $array_param[] = (int)$file->postinfo->post->modified+$st;
                            
                            $st++;
                        }


                        $array_res = array_combine($array_param,$array_xml);

                        $catnum = count($array_res);

                        # Note: to Show results from a to z (alphabetically) we set normal order and
                        # to show results from new to old(chronologically), we set reverse order.

                        if ($_SESSION['sortposts'] == 'sortbyrev' || $_SESSION['sortposts'] == 'sortbytitle')
                            # normal
                            ksort($array_res);

                        elseif ($_SESSION['sortposts'] == 'sortbyalpha' || $_SESSION['sortposts'] == 'sortbytime')
                            # reverse
                            krsort($array_res);

                        $cwd = 'posts';
                        include 'navinfo.php';

                        $c=0;
                        $r=0;

                        include 'en_code.php';

                        foreach($array_res as $file) {

                            if (($c >= $first) && ($c < $last)) {

                                $r++;

                                $fxml = simplexml_object($file,'l','post');

                                $title = load_xml($fxml->postinfo->post->title);
                                $type = $fxml->postinfo->post->type;
                                $filename = $fxml->postinfo->post->filename;
                                $visitname = str_replace('nu.xml','.xml',$file);
                                if (is_file('autosaves/'.$visitname)) {
                                    
                                    $nfile = simplexml_object($visitname,'l','post');
                                    $visitname = $nfile->postinfo->post->filename;
                                        
                                }
                                
                                $path = $fxml->postinfo->post->path;
                                $utime = (int)$fxml->postinfo->post->modified;

                                if ($fxml->postinfo->post->category != '')
                                    $category = '<div class="category">'.$fxml->postinfo->post->category.' </div>';


                                $author = $real_authors[(string)$fxml->postinfo->post->createdby];
                                if ($fxml->postinfo->post->editedby != '' && $fxml->postinfo->post->editedby !== false) {
                                    $editor_author = get_account((string)$fxml->postinfo->post->editedby)['editorname'];
                                    $editor_author = ($author != $editor_author) ? '(edited by '.$editor_author.')' : '';

                                }
                                else
                                    $editor_author = '';




                                if ($type != 'Draft')    {

                                    $postedit = '<a href="javascript:" onclick="if (draft(this)) window.location.href=\'editpost.php?editfile='.$file.'&amp;max='.$ofp.$plink.'\'; " class="options-button not" title="Change to Draft">Change to draft</a>';
                                    $visitpage = '<a href="../'.$path.$visitname.'.php" target="_blank" class="options-button">Visit</a>';
                                    $fptotime = 'posted on '.date('M d, Y',(int)$fxml->postinfo->post->ptime);

                                }

                                else {

                                $postedit = '';
                                $visitpage = '';
                                $fptotime = 'Draft';

                                }


                                $content_file = 'autosaves/content/'.basename($file,'.xml').'.htm';
                                if (is_file($content_file))
                                    $preview_content = cut_content(file_get_contents($content_file),'80');
                                else
                                    $preview_content = '(no content)';

                                if ($title == '') 
                                    $title = '(no title)';

                                $ftime = date_form($utime);
                                //$cssbg = (($r % 2) == 1) ? ' -bg' : '';
                                $cssbg = ($type != 'Draft' && $type != 'Posted') ? ' -bg' : '';

                                print '<div class="savedfile'.$cssbg.'">
                                <span class="post-title" title="'.$title.'"><a href="newpage.php?savedname='.$file.'">'.$title.'</a></span>
                                <div class="post-options"><a href="newpage.php?savedname='.$file.'" title="Edit post" class="options-button">Edit post</a><a href="javascript:" onclick="if (conf(this)) window.location.href=\'editpost.php?file='.$file.'&amp;max='.$ofp.$plink.'\'" class="options-button not" title="Delete post">Delete</a>'.$postedit.$visitpage.'</div>
                                <div class="post-text">'.$preview_content.'</div>
                                <div class="lastmod">'.$ftime.'</div>
                                <div class="type">
                                <span title="'.$fptotime.'">'.$type.'</span>
                                </div>
                                <div class="author">'.$author.$editor_author.'</div>
                                '.$category.'
                                </div>';

                            }

                            $c++;
                            unset($editor_author);

                        }        
                    }
                    
                    else
                        echo '<i id="no-results">:: 0 results</i>';
                }
                
                
                else 
                    print '<i id="no-results">:: no posts found</i>';                    
            ?>
            </div>

            <div id="res-nav">
                <?php
                                 
                    # paginate results
                    if (isset($array_res)) :
                             
                        print '<div id="cur-res">';
                                 
                        $l = $first + $r;
                        echo $first.' - '.$l.' of &nbsp;'.$catnum;


                        print '</div>';

                        include 'pagenav.php';

                    endif
                
                ?>
            </div>
        </div>
    </div>
    <?php
    
        #plugins
        include 'execute.php'
    
    ?>
</body>
</html>