<?php


    # Posts and website content



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

    
    # user rights - user info
    $acc_info = get_account($_SESSION['userID']);
    
    
    foreach($_GET as $str)
        if (!is_string($str)) {
            header('Location: opensaved.php');
            exit;
        }
    
    
    # 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']);

    */
    


?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Posts</title>
<link rel="stylesheet" type="text/css" href="cmstyle.css">
<?php
    $cssid = '#posts';
    include 'csstheme.php';
    print '<style>'.$curval.'</style>'


?>
<script>
    function conf(form){return confirm('Delete post?');}
    function draft(form){return confirm('Change to Draft?');}
    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];
            }

                    

    
        $ar_cat=$ar_auth=$ar_stat=$gts=[];
        $mrg = merged_categories();
        
        
        # Save categories in an array as id=>[name,merged1,merged2]
        $gc = get_categories();
        

        if ($gc !== false) {
            foreach($gc as $k=>$v) {
                $gts[$k] = [$v[1]];
                if (!empty($v[3]))
                    foreach($v[3] as $val)
                        $gts[$k][] = $val;
            }

        }            
        
        
        $directory=$postinfo=[];
        
        if (is_file('autosaves/autosaves.xml')) {
            
            $adir = simplexml_object('autosaves.xml','l','post');
            if (!is_array($adir))
                foreach($adir->savedpost as $file) {
                    
                    # Get the 'nu' version of a file, if it exists, by checking if there's a similar file without 'nu' at the end of its filename
                    if (is_file('autosaves/'.$file->postinfo->post->file.'nu.xml'))
                        continue;
                        
                    foreach($file->postinfo->post->children() as $k=>$v)
                        $postinfo[$k] = (string)$v;
                        
                
                    $directory[] = $postinfo;
                    $postinfo = [];
                }
        }
        
        else {
            
            # Multiple xml files only - < 2.4
            $dir = new DirectoryIterator('autosaves/');
            foreach($dir as $fileinfo) {
                
                
                $fext = $fileinfo->getExtension();
                $fname = $fileinfo->getFilename(); #i.e 9fr94j.xml
                $base = basename($fname,'.xml');
                
                if (is_file('autosaves/'.$base.'nu.xml') || $fname == 'autosaves.xml')
                    continue;
                
                
                if ($fext == 'xml') {
                    
                    $post = getxmlpost('autosaves/'.$fname);
                        
                    $post['file'] = $base;
                    $directory[] = $post;
                
                }
            }
        }


    
        foreach($directory as $k=>$s)
        
        
            if ($monrights == 'administrator' || $_SESSION['userID'] == (string)$s['createdby']) {
            
                
                if (!isset($s['type'])) echo $s[$k];
                $type = $s['type'];
                
                $ar_stat[] = $type;
                
                
                
                # Save categories for filter menu
                if (isset($s['catid'])) {
                    
                    if (isset($gc[$s['catid']]))
                        $ar_cat[] = $gc[$s['catid']][1];
                        
                    elseif (isset($mrg[$s['catid']]))
                        $ar_cat[] = $gc[$mrg[$s['catid']]][1];
                }
                
                array_unshift($ar_cat,'Uncategorized');                


                $auth = (string)$s['createdby'];
                if (array_search($auth,$ar_auth) === false) {

                    $ar_auth[] = $auth;

                    # $auth is the user's ID (not current user)
                    
                    $gauth = get_account($auth);
                    if (!empty($gauth)) {
                        $author_account = $gauth;
                        $ar_authname[] = $author_account['editorname'];
                    }
                    
                    else
                        $ar_authname[] = '';
                }

            }
            
        

        $ar_cat = array_unique($ar_cat);
        $ar_stat = array_unique($ar_stat);

    ?>

    <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 headposts">
        <div style="clear:both;height:34px"></div>
        Category <select id="selectcategory" onchange="window.location=this.value">
                <?php

                    
                $optall = '<option value="#">All</option>';
                $cclink = $clink == '' ? '?' : $clink.'&';
                $optuncat = '<option value="opensaved.php'.$cclink.'filtcategory=Uncategorized">Uncategorized</option>';
                
                    
                if (isset($_GET['filtcategory']) && in_array($_GET['filtcategory'],$ar_cat)) {
                
                    
                    if ($_GET['filtcategory'] == 'Uncategorized') {
                        echo '<option value="#">Uncategorized</option>';
                        $optuncat = '';
                    }
                    else
                        echo '<option value="#">'. $_GET['filtcategory'].'</option>';
                    
                    
                    echo '<option value="opensaved.php'.$clink.'">All</option>'.PHP_EOL.$optuncat;
                    
                
                }
                
                
                else 
                    echo $optall.PHP_EOL.$optuncat;
                
                
                    
                unset($ar_cat[0]);
                
                echo '<option disabled>------------</option>';
                
                foreach($ar_cat as $ts)
                    if (!isset($_GET['filtcategory']) || $_GET['filtcategory'] != $ts) 
                        print '<option value="opensaved.php'.$cclink.'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;
                
                    echo '<option disabled>------------</option>';

                    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) 
                                print '<option value="opensaved.php'.$alink.'filtauthor='.$id.'">'.$name.'</option>';
                    }

                ?>
        </select>
        <?php endif ?> 
        Status <select id="selectstatus" onchange="window.location=this.value">
                <?php 
                
                    $allstats = ['Posted','Draft','Posted/Not updated'];
                    if (isset($_GET['filtstatus']) && in_array($_GET['filtstatus'],$allstats))
                        echo '<option value="#">'.$_GET['filtstatus'].'</option>'.PHP_EOL.'<option value="opensaved.php'.$slink.'">All</option>';
                    else 
                        echo $optall;
                
                    echo '<option disabled>------------</option>';

                    $slink = $slink == '' ? '?' : $slink.'&';
                    foreach($ar_stat as $ts)
                        if (!isset($_GET['filtstatus']) || $_GET['filtstatus'] != $ts)
                            print '<option value="opensaved.php'.$slink.'filtstatus='.$ts.'">'.$ts.'</option>';
                
                ?>
        </select>
        <div class="results-set">
            <div class="normal-res">
                <input type="text" id="tagsearch" value="" title="Tags quick search (current page only)" placeholder="Tag quick search" list="savedtags" ondrop="return false" oninput="tagshow()" maxlength="120">
                <button class="instag" onclick="document.getElementById('tagsearch').value='';document.getElementById('res-nav').setAttribute('style','');tagshow()">✕</button>
                <datalist id="savedtags" onclick="tagshow()">
                <?php
                    
                    $all_tags = get_tags();
                    asort($all_tags);
                    
                    foreach($all_tags as $val)
                        echo '<option>'.$val.'</option>'
                ?>
                </datalist>
                <script>
                
                
                function tagshow() {
                    
                    const val = document.getElementById('tagsearch').value;
                    
                    if (document.getElementsByClassName('savedfile').length > 0) {
                    
                        const saved = document.getElementsByClassName('savedfile');
                        var tag = 'Tag: ';
                        var c = 0;
                        for (let i=0; i < saved.length; i++) {
                            const ch = saved[i].children;
                            
                            for(let j=0; j < ch.length; j++)
                                
                                if (ch[j].hasAttribute('data')) {
                                
                                const dt = ch[j].getAttribute('data');
                                const spl = dt.split(',');
                                if (val == '') 
                                    var tag = ' ';
                                
                                if ((spl.length > 1  && spl.includes(val)) || (dt == val && val.search(',') == -1) || val == '') {
                
                                    saved[i].setAttribute('style','');
                                    if (val != '') c++; else {var c='';};
                                
                                }
                                
                                else
                                    saved[i].setAttribute('style','display:none');
                            }
                        }
                        
                        document.getElementById('tgsear').innerHTML = tag + val + ' (' + c + ') <button class="tgs" onclick="document.getElementById(\'tagsearch\').value=\'\'; tagshow()">✕</button>';
                        document.getElementById('res-nav').setAttribute('style','opacity:0.4;pointer-events:none;user-select:none');
                        
                        if (val == '') {
                            document.getElementById('res-nav').setAttribute('style','');
                            document.getElementById('tgsear').innerHTML = '';
                        }
                    }

                }
                
                </script>
                <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 id="tgsear"></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 = ['filtcategory'=>'category','filtauthor'=>'createdby','filtstatus'=>'type'];
                
                
                foreach($directory as $k=>$s) {
                
                    
                    if ($acc_info['rights'] == 'administrator' || $s['createdby'] == $_SESSION['userID'])
                        
                        if ($plink == '')
                            $array_temp[] = $k;
                        
                        
                        else {

                            # category
                            if (isset($gts[$s['catid']]))
                                $s['category'] = $gts[$s['catid']][0];
                            else {
                                if (isset($mrg[$s['catid']]))
                                    $s['category'] = $gts[$mrg[$s['catid']]][0];
                                else
                                    $s['category'] = 'Uncategorized';
                                    
                            }

                            $c=0;
                            foreach($filtersxml as $filt=>$xmlvalue)
                                if (isset($_GET[$filt]) && $_GET[$filt] == $s[$xmlvalue])
                                    $c++;
                                    
                            if ($c == $nof)
                                $array_temp[] = $k;
                        }
                }



                if (count($array_temp) > 0) {
                
                    

                    foreach($array_temp as $num)
                        $array_xml[] = $directory[$num];


                    $st=0;
                    foreach($array_xml as $s) {
                                
                        if ($_SESSION['sortposts'] == 'sortbytitle' || $_SESSION['sortposts'] == 'sortbyalpha')
                            $array_param[] = strtolower($s['title']).$st;
                        else
                            $array_param[] = (int)$s['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);
                    

                    $catnum = count($array_res);
                    $cwd = 'posts';
                    include 'navinfo.php';

                    $c=0;
                    $r=0;

                    include 'en_code.php';
                                            
                    foreach($array_res as $fxml) {

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

                            $r++;
                            
                            $file = $fxml['file'].'.xml';

                            $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'];
                            
                            
                            
                            # Find post category
                            $cid = $fxml['catid'];
                            
                            if (isset($gts[$cid])) {
                                $realcat = $gts[$cid][0];
                                $pu = $gc[$cid][2];
                            }
                            elseif (isset($mrg[$cid])) {
                                $realcat = $gts[$mrg[$cid]][0];
                                $pu = $gc[$mrg[$cid]][2];
                            }
                            
                            else {
                
                                $realcat = 'uncategorized';
                                $pu = $gc['uncategorized'][2];
                            }
                            
                            
                            $pu = $pu == 'on' ? 'Category"' : 'Category not public" style="opacity:.6"';
                            
                            $category = '<div class="category" title="'.$pu.'>'.$realcat.' </div>';
                            
                            
                            
                            if(!isset($real_authors))
                                $real_authors = array_combine($ar_auth,$ar_authname);
                            
                            $author = $real_authors[$fxml['createdby']];
                            if (!empty($fxml['editedby']) && !empty(get_account($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/'.$fxml['file'].'.htm';
                            
                            # preview content
                            if (is_file($content_file)) {
                                $cfile = htmlspecialchars_decode(file_get_contents($content_file));
                                $cfile = str_replace('&nbsp;',' ',$cfile);                                    
                                $precon = cut_content($cfile,'80','strip');
                            }

                            if (!isset($precon) || strip_tags($precon) == '')
                                $precon = '(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 data="'.$fxml['tags'].'"></div>
                            <div class="post-text">'.$precon.'</div>
                            <div class="lastmod">'.$ftime.'</div>
                            <div class="type">
                            <span title="'.$fptotime.'">'.$type.'</span>
                            </div>
                            <div class="author" title="Post author">'.$author.$editor_author.'</div>
                            '.$category.'
                            </div>';

                        }

                        $c++;
                        unset($editor_author);
                        unset($precon);

                    }        
                
                }
                
                
                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>';
                        
                        print '<div id="mydata" style="display:none">'.$first.' - '.$l.' of '.$catnum.'</div>';

                        include 'pagenav.php';

                    endif
                
                ?>
            </div>
        </div>
    </div>
</body>
</html>