<?php


    # Posts and website content



    # login
    include 'data_connect.php';
    include '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;
    }
    
    
    
    
    
    /*
    if (isset($_GET['pin']))
        pin_post($_GET['pin']);
        
    if (isset($_GET['unpin']))
        pin_post($_GET['unpin']);

    */

    # 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>
<script type="text/javascript">function mdel(form){return confirm('Delete posts?');}</script>
</head>
<body>
    <?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 = getxmlpost('autosaves/'.$name.'.xml');
                
                if ($monrights == 'administrator' || ($monrights != 'administrator' && $_SESSION['userID'] == (string)$s['createdby'])) {
                
                    
                    $type = $s['type'];

                    if (array_search($type,$ar_stat) === false)
                        $ar_stat[] = $type;
                    
                    $catgr = (string)$s['category'];
                    if (array_search($catgr,$ar_cat) === false)
                        $ar_cat[] = $catgr;

                    $auth = (string)$s['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>
            <!-- delete multiple posts
            <form id="maction" action="medit.php" method="post"></form>
            <button type="submit" form="maction" method="post" name="delaction" onclick="mdel(this)">Delete</button>
            -->
        </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 = $array_all = $array_pin =[];
                $filtersxml = array('filtcategory'=>'category','filtauthor'=>'createdby','filtstatus'=>'type');
                
                
                
                foreach ($filtersxml as $filt=>$xmlvalue) {
                    foreach ($directory as $fileinfo) {
                        
                        if ($fileinfo->isFile()) {

                            $name = $fileinfo->getFilename();
                            
                            
                            $s = getxmlpost('autosaves/'.$name);
                            $mtime = (int)$s['modified'];
                            $creator = $s['createdby'];
                            $posttitle = $s['title'] == '' ? '(no title)': $s['title'];
                            
                            $array_all[$mtime] = $name;
                            if (isset($s['top']) && $s['top'] != '')
                                $array_pin[(int)$s['top']] = $name;
                            
                            $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[$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 = getxmlpost('autosaves/'.$val);
                            
                            if ($_SESSION['sortposts'] == 'sortbytitle' || $_SESSION['sortposts'] == 'sortbyalpha')
                                $array_param[] = strtolower($file['title']).$st;
                            else
                                $array_param[] = (int)$file['modified']+$st;
                            
                            $st++;
                        }


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


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

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

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

                        
                        
                        
                    
                        # Show only pinned or show pinned on top        
                        if (count($array_pin) > 0) {
                        
                            $array_pinned = [];
                            
                            krsort($array_pin);
                            
                            
                            foreach($array_pin as $key=>$val) {
                        
                                $array_pinned[] = $val;
                                $k = array_search($val,$array_res);
                                unset($array_res[$k]);
                            
                            }
                            
                            if (isset($_GET['pinned']))
                                $array_res = $array_pinned;
                            else
                                $array_res = array_merge($array_pinned,$array_res);
                                
                                #print '<span title="pinned posts">(p)</span>';
                        }
                        
                        
                        
                        
                        
                        $catnum = count($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 = getxmlpost('autosaves/'.$file);

                                $title = load_xml($fxml['title']);
                                $type = $fxml['type'];
                                $filename = $fxml['filename'];
                                $visitname = str_replace('nu.xml','.xml',$file);
                                if (is_file('autosaves/'.$visitname)) {
                                    
                                    $nfile = getxmlpost('autosaves/'.$visitname);
                                    $visitname = $nfile['filename'];
                                        
                                }
                                
                                $path = $fxml['path'];
                                $utime = (int)$fxml['modified'];

                                if ($fxml['category'] != '')
                                    $category = '<div class="category">'.$fxml['category'].' </div>';

                                if(!isset($real_authors))
                                    $real_authors = array_combine($ar_auth,$ar_authname);
                                $author = $real_authors[$fxml['createdby']];
                                if (!empty($fxml['editedby'])) {
                                    $editor_author = get_account($fxml['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['ptime']);
                                    

                                }

                                else {

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

                                }


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

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

                                $ftime = date_form($utime);
                                
                                # Show post information button
                                #$postinfo = '<span class="options-button"><a href="postinfo.php?postxml='.$file.'" class="postinfo options-button" target="_blank">Ιnfo</a></span>';
                                
                                
                                $cssbg = $type != 'Draft' && $type != 'Posted' ? ' -bg' : '';
                                
                                
                                # Pin a post on top button
                                /*
                                if (!isset($fxml['top']) || $fxml['top'] == '')
                                    $pinpost = '<a href="?max='.$ofp.'&pin='.$file.$plink.'" class="options-button">Pin to top</a>';
                                else {
                                    $pinpost = '<a href="?max='.$ofp.'&unpin='.$file.$plink.'" class="options-button">Unpin</a>';
                                    $cssbg = ' -pin';
                                }
                                */
                                
                                
                                #checkbox for each post
                                #$checkbox = '<input type="checkbox" id="ch'.$c.'" name="filechecked'.$c.'" value="'.$file.'" form="maction" class="savedfch">
                                #<label for="ch'.$c.'" class="svchlb"></label>';
                                
                                    
                                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>