<?php


    # Posts and website content



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

    
    
    # user rights - user info
    $accinfo = get_account($_SESSION['userID']);



    # 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();
        
    
        
        # Sort results
        # GET parameter for res-set.php
        # We use this to set the right sorting parameter in 'delete' and 'change to draft' buttons
        $plink = '';

    
        # get any previous GET parameters and include them inside any 'a' or 'select option'
        if (count($_GET) > 0) {
            $x=0;
            foreach($_GET as $param=>$val) {
                $front = ($x == 0) ? '?' : '&amp;';
                $plink .= $front.$param.'='.$val;
                $x++;
            }
        }

    
        # the number of get parameters that are set
        $filter_parameters = array('filtcategory','filtauthor','filtstatus');
        $params=0;
        foreach ($filter_parameters as $get_value) 
            if(isset($_GET[$get_value]))
                $params++;
    

        # remove the '?' constructor and save parameters only
        $nes = str_replace('?','&amp;',$plink);
    
    
    
        # put in front
        $plink = ($plink == '') ? '?' : $plink.'&amp;';
    
        
        # 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_load_file('autosaves/'.$name.'.xml');
                
                
                $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'];

                }
            }
        }



        # filters
        $filters = array('filtcategory'=>'category','filtauthor'=>'createdby','filtstatus'=>'type');


        # create a link for the 'All' selection
        foreach ($filters as $filter=>$type) {

            if (isset($_GET[$filter])) {
                if ($params == 1)
                    $array_filter_link_types = array('?'.$filter.'='.$_GET[$filter]);
                else 
                    $array_filter_link_types = array('&amp;'.$filter.'='.$_GET[$filter], $filter.'='.$_GET[$filter].'&amp;');
                    $paramlinks[] = str_replace($array_filter_link_types,'',$plink);
            }
            else
                $paramlinks[] = $plink;
        }


    
    
        # correction for the filter menu links
        if (isset($_GET['max'])) {
            $m=0;
            foreach ($paramlinks as $link) {
                $paramlinks[$m] = str_replace(array('max='.$_GET['max'],'?&amp;'),array('','?'),$link);
                $m++;
            }
        }

        
    
    
    
        ### added correction for the 'All' option in filters ###
        $l=0;
        foreach ($paramlinks as $link) {
            if ($link == '&amp;')
                    $linksall[$l] = '';
            else 
                if (substr($link,-5) == '&amp;')
                    $linksall[$l] = substr($link,0,-5);
            else 
                $linksall[$l] = $link;
            $l++;
        }



    ?>

    <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>
            

        <!-- 
        Set filters
        Category 
        -->
            
        Category <select id="selectcategory" onchange="window.location=this.value">
                <?php

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

                    else
                        echo '<option value="#">All</option>';

                    $catlink = ($paramlinks[0] == '&amp;') ? '?' : $paramlinks[0];
                    foreach($ar_cat as $ts)
                        if (isset($_GET['filtcategory']) && $_GET['filtcategory'] != $ts || !isset($_GET['filtcategory']))
                            print '<option value="opensaved.php'.$catlink.'filtcategory='.$ts.'">'.$ts.'</option>'
                ?>
        </select>


        <!-- Author -->
        <?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'.$linksall[1].'">All</option>';

                    else 
                        echo '<option value="#">All</option>';


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

                ?>
        </select>
        <?php endif ?> 

        <!-- status -->
        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'.$linksall[2].'">All</option>';

                    else 

                        echo '<option value="#">All</option>';


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

                ?>
        </select>    
        <div class="results-set">
            <div class="normal-res">
                <span style="font-size:12px">Results per Page &nbsp;</span>
                <?php
                
                pageResults('posts',$plink)
                
                ?>
            </div>
        </div>
    </div>
        
        <div id="main-container">
            <div class="results">
                <div class="pbar">
                    
                    <span id="pbar-title">
                    
                    <!-- Results can be sorted by time or alpha. Create the respective links -->
                    <a href="sort-set.php<?php
                    
                    if ($_SESSION['MONSORT'] == 'sortbytitle')
                        print $plink.'sortbyalpha=1&amp;ref=opensaved.php" title="Reverse alphabetical order (z-a)" class="sort1';
                    
                    elseif ($_SESSION['MONSORT'] == 'sortbyalpha')
                        print $plink.'sortbytitle=1&amp;ref=opensaved.php" title="Alphabetical order (a-z)" class="sort2';
                        
                    else
                        print $plink.'sortbytitle=1&amp;ref=opensaved.php" title="Alphabetical order (a-z)'
                    
                    
                    ?>
">Title</a>
                    
                    </span>
                    <span class="lastmodbar">
                    <a href="sort-set.php<?php 
                    
                    if ($_SESSION['MONSORT'] == 'sortbyrev') 
                        print $plink.'sortbytime=1&amp;ref=opensaved.php" title="Chronological order" class="sort2';
                    
                    elseif ($_SESSION['MONSORT'] == 'sortbytime')
                        print $plink.'sortbyrev=1&amp;ref=opensaved.php" title="Reverse chronological order" class="sort1';
                        
                    else
                        print $plink.'sortbytime=1&amp;ref=opensaved.php" title="Chronological order '
                    
                    ?>
">Last modified</a>
                    </span>
                    
                    
                    <!--
                    <span style="width:101px">Status</span>
                    <span style="width:101px">Author</span>
                    <span class="catbar">Category</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();
                $array_temp = array();

                foreach ($filters as $filt=>$xmlvalue) {
                    foreach ($directory as $fileinfo) {
                        if ($fileinfo->isFile()) {

                            $name = $fileinfo->getFilename();
                            $s = simplexml_load_file('autosaves/'.$name);
                            $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) || (!isset($_GET['filtcategory']) && !isset($_GET['filtauthor']) && !isset($_GET['filtstatus'])) )
                                        $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 ( $params == 0 || $filt_number == $params ) {

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

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


                        $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['MONSORT'] == 'sortbyrev' || $_SESSION['MONSORT'] == 'sortbytitle')
                            # normal
                            ksort($array_res);

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

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

                        $c=0;
                        $r=0;

                        include 'en_code.php';
                        include 'dateform.php';

                        foreach($array_res as $file) {

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

                                $r++;

                                $fxml = simplexml_object($file,'l',null,'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',null,'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.'\'; " 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.'\'" 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>