<?php
    

    # Saved Pages
    


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


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

    # Delete a page
    function pagedelete() {
            
        $pagexml = 'savedpages/'.$_GET['savedpage'];
        
        $pgx = simplexml_object($_GET['savedpage'],'l','page');
        $rt = empty($pgx->pageinfo->page->path) ? '' : $pgx->pageinfo->page->path;
        
        $page = '../'.$rt.$_GET['page'].'.php';

        if (file_exists($pagexml)) {
            
            unlink($pagexml);
            $_SESSION['MONpagedeleted'] = true;
            $sum = get_log()['pages'];
            $sum -= 1;
            update_log('pages',$sum);

        }
        
        if (file_exists($page))
            unlink($page);
    
        return true;
    }

    

    # Update info of a page
    function page_updateinfo() {
                        
        $values = ['published'=>['on','hidden']];
        
        # Do not repeat these
        $unwanted = ['savedpage','published','value'];
        
        
        # get the GET parameters
        foreach ($_GET as $k=>$v)
            $gets['&'.$k] = $v;

        # remove unwanted parameters
        foreach ($unwanted as $val)
            if (isset($gets['&'.$val]))
                unset($gets['&'.$val]);

        
        # keep parameters
        $pars = '';    
        if (count($gets) > 0) {

            foreach ($gets as $key=>$val)
                $pars .= $key.'='.$val;

            $pars = '?'.ltrim($pars,'&');
        }

                
        foreach ($values as $key=>$val) {

            if (isset($_GET[$key])) {
                
                
                $xmlname = $_GET[$key];
                $pxml = simplexml_object($xmlname,'e','page');
                $xval = $_GET['value'];
                
                
                $rt = empty($pxml->pageinfo->page->path) ? '' : $pxml->pageinfo->page->path;    
                $inc = empty($pxml->pageinfo->page->incpath) ? '' : $pxml->pageinfo->page->incpath;

                $page = '../'.$rt.$pxml->pageinfo->page->filename.'.php';

                if (in_array($xval,$values[$key])) {

                    $pxml->pageinfo->page->$key = $xval;


                    # published removes or rewrites a page php file
                    if ($xval == 'hidden') {
                        if (is_file($page)) 
                            unlink($page);
                    
                    }

                    elseif ($xval == 'on') {

                        $con = '<?php $pn = "'.basename($xmlname,'.xml').'"; $incp = "'.$inc.'"; include "'.$inc.'monofiles/path.php" ?>';
                        file_put_contents($page,$con);
                        
                    }

                    
                    simplexml_object_save($xmlname,$pxml,'page');

                    $_SESSION['MONpage'.$key.'_'.$xval] = true;
                    header('Location:pages.php'.$pars);
                    exit;                    
                }
            }
        }

        return true;
    }
    
    
    
    # sort results
    function pages_sort() {
            
        $params = ['showpub','showunp','folder'];
        $plink = '?';
        
        foreach($params as $val) 
            if (isset($_GET[$val]))
                $plink .= '&'.$val.'='.$_GET[$val];                
            

        $_SESSION['sortpages'] = $_GET['sortpages'];
        edit_useraccount('sortpages',$_GET['sortpages']);
        
        header('Location:pages.php'.$plink);
        exit;
    }




    $setactions = ['pagedelete'=>['savedpage'],'page_updateinfo'=>['published'],'pages_sort'=>['sortpages']];

    foreach ($setactions as $key=>$val)
        foreach ($val as $fun)
            if(isset($_GET[$fun]) && function_exists($key)) {
               call_user_func($key);
               break;
            }



    #extensions
    include 'command.php'


?>
<!doctype html>
<html>
<head>
<title>Pages</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="cmstyle.css">
<?php include 'csstheme.php' ?>
<script>function conf(form){return confirm('Delete page?');}</script>
<script>function unpub(form){return confirm('Unpublish page?');}</script>
<script>function pub(form){return confirm('Publish page?');}</script>
</head>
<body>
<?php

    # panel
    include 'mypanel.php';
    action_confirm()

    
    ?>
    <div class="main">
        <h1>Pages <a class="newpostbut" href="createpage.php" id="newpage" title="Create a page"><span class="addnew">+</span>&nbsp;Publish a new page</a></h1>
        <div class="headpages">
        <div class="clear-m"></div>
        <?php

            
            # Get all pages
            $array_xml = $array_param = $array_path = array();
            $directory = new DirectoryIterator('savedpages/');
            
            $sortpages = isset($_SESSION['sortpages']) ? $_SESSION['sortpages'] : $_GET['sortpages'];

            
            # create pages arrays
            $num = 1;
            $nofp=[0=>0,1=>0,2=>0];
            foreach ($directory as $fileinfo) {
                
                if ($fileinfo->isFile() && substr($fileinfo->getBasename(),-4) == '.xml' && $fileinfo->getSize() > 0) {
                                    
                    $name = $fileinfo->getBasename();

                    $sp = simplexml_object($name,'l','page');
                    
                    $nofp[0]++;
                    if ($sp->pageinfo->page->published == 'hidden') 
                        $nofp[2]++;
                    else
                        $nofp[1]++;
                    
                    $mtime = $sp->pageinfo->page->modified;
                    
                    $array_xml[]= $name;
                    $array_path[] = empty($sp->pageinfo->page->path) ? '' : rtrim($sp->pageinfo->page->path,'/');
                    $array_param[] = $sortpages == 'sortbytitle' || $sortpages == 'sortbyalpha' ? strtolower($sp->pageinfo->page->title).$num : $mtime;
                }
                $num++;
            }
            
            # remove duplicates page folders
            $uarray_path = array_unique($array_path);
            
            
            # rearrange based on dir depth, then alphabetically
            if (count($uarray_path) > 0) {
                
                $rearr=[];
                foreach($uarray_path as $val)
                    $rearr[substr_count($val,'/')][] = $val;
                
                
                ksort($rearr);
                $uarray_path = [];
                
                
                foreach($rearr as $key=>$val)
                    sort($rearr[$key]);
                
                 foreach($rearr as $key=>$val)
                    foreach($val as $pagef)
                        $uarray_path[] = $pagef;
                
            }
                
        
        
            # homedir
            $homedir = basename(realpath('../'));
        
            
            
            # Combine pages arrays
            $array_res = array_combine($array_param,$array_xml);
            
            if ($sortpages == 'sortbyrev' || $sortpages == 'sortbytitle')
                #normal order
                ksort($array_res);
                
            else
                #reverse order
                krsort($array_res);
            
            
            
            #
            if (isset($_GET['showpub']) || isset($_GET['showunp'])) {
                
                $array_pubunp=[];
                
                foreach ($array_res as $key=>$val) {
                
                    $fxml = simplexml_object($val,'l','page');
                    $published = $fxml->pageinfo->page->published;
                    
                    if ((isset($_GET['showpub']) && $published != 'hidden') || (isset($_GET['showunp']) && $published == 'hidden'))
                        $array_pubunp[$key] = $val;
                
                }
                
                $array_res = $array_pubunp;
                
            }
                    
                            

            if (isset($_GET['folder'])) {
            
                # set new values for All | Published | Unpublished
                $nofp=[0=>0,1=>0,2=>0];
                foreach($array_xml as $val) {
                
                    $pxml = simplexml_object($val,'l','page');
                    
                    if ($_GET['folder'] == rtrim($pxml->pageinfo->page->path,'/')) {
                        $nofp[0]++;
                        if ($pxml->pageinfo->page->published == 'hidden') 
                            $nofp[2]++;
                        else
                            $nofp[1]++;
                    }
                }
                
                
                
                # filter results based on folder param
                $array_folder=[];
                foreach($array_res as $key=>$val) {
                
                    $pxml = simplexml_object($val,'l','page');
                    $folder = $pxml->pageinfo->page->path;
                
                    if ($_GET['folder'] == rtrim($folder,'/'))
                        $array_folder[$key] = $val;
                }
                
                //if (in_array($_GET['folder'],$uarray_path))
                    $array_res = $array_folder;
            }
        
            
            
            
            
            ?>
            
        <span style="font-size:12px">Folder &nbsp;</span>
        <select onchange="window.location=this.value" title="Select folder">
        <?php
            
            
            # Folder select
            if (isset($_GET['folder'])) {
            
                if (in_array($_GET['folder'],$uarray_path)) {
                    
                    $arrsear = array_search($_GET['folder'],$uarray_path);
                    unset($uarray_path[$arrsear]);
                
                    if ($_GET['folder'] == '')
                        print '<option value="#">'.$homedir.'</option>';
                    
                    else
                        print '<option value="#">'.$_GET['folder'].'</option>';
                
                }
                
                else
                    print '<option value="#">---</option>';

                
                print '<option value="?">All folders</option>';
                
            }
            
            else
                print '<option value="pages.php">All folders</option>';
            
            
            foreach($uarray_path as $key=>$empstr)
                if ($empstr == '') {
                    print '<option value="?folder=">'.$homedir.'</option>';
                    unset($uarray_path[$key]);
                    break;
                }


            foreach($uarray_path as $val)
                print '<option value="?folder='.$val.'">'.$val.'</option>'
                
                
            ### ###
            
                
        ?>
        </select>
        <div class="clear"></div>
        <div class="clear"></div>
        
        <?php
            
            
            ### ###
            
            
            
            
            # Menu with get values
            $sort_params = ['sortbytitle'=>['sortbyalpha','sortbytime',1,'','Reverse alphabetical order (z-a)','Chronological order'],
                            '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']];


            # show published unpublished
            $show_params = ['showpub'=>['#','?showunp=1',0,'','Published'],'showunp'=>['?showpub=1','#','',0,'Unpublished']];
            
            
            # folder
            if (isset($_GET['folder']) && in_array($_GET['folder'],$uarray_path)) {
                $foldr = '&folder='.$_GET['folder'];
                $foldn = $_GET['folder'] == '' ? $homedir : $_GET['folder'];
            }
            
            else
                $foldr = '';


            # show default values
            $showp = '?showpub=1';
            $showunp = '?showunp=1';
            $def = 'All';
    
    
            # keep values from other menus
            $optionval = '';
            foreach ($sort_params as $key=>$val)
                if (isset($_GET['sortpages'])) {
                    $optionval = '&sortpages='.$_GET['sortpages'];
                    break;
                }

            foreach ($show_params as $key=>$val)
                if (isset($_GET[$key])) {
                    $showp = $val[0];
                    $showunp = $val[1];
                    $def = $val[4];
                    break;
                }
    
            ### ###
        
        
        
            # print "All | Published | Unpublished" menu
            $showmenu = ['All'=>'pages.php?all=1'.$foldr.'">All ['.$nofp[0].']',
                        'Published'=>$showp.$foldr.'">Published ['.$nofp[1].']',
                        'Unpublished'=>$showunp.$foldr.'">Unpublished ['.$nofp[2].']'];


            $c=0;
            foreach($showmenu as $key=>$val) {
                
                if ($key == $def)
                    print '<span class="pubselected" title="'.$key.'">'.$key.'['.$nofp[$c].']</span>'.PHP_EOL;
                else
                    print '<a title="Show '.$key.' pages" href="'.$val.'</a>'.PHP_EOL;
                
                if ($key != 'Unpublished') 
                    echo ' | ';
                
                $c++;
            }
            
            ### ###             
            
            
        ?>
        
            
        <div class="results-set results-set-pages">
            <div class="normal-res">
                <span style="font-size:12px">Results per page &nbsp;</span>

                <?php
                
                    
                    # include menu parameters
                    $parpub = '';
                    foreach ($show_params as $key=>$val)
                        if (isset($_GET[$key])) {
                            $parpub = '&'.$key.'=1';
                            break;
                    }
                    
                    # include folder parameter
                    $parpub .= $foldr;

                    foreach ($sort_params as $key=>$val)
                        if ($_SESSION['sortpages'] == $key) {
                            $partitle = '?sortpages='.$val[0];
                            $parlastmod = '?sortpages='.$val[1];
                            $class_title = $val[2];
                            $class_lastmod = $val[3];
                            $title_attr_val = $val[4];
                            $lastmod_attr_val = $val[5];
                            break;
                        }

                    
                    pageResults('pages',$parpub)
                    

                ?>
                </div>    
            </div>
        </div>
        <div id="main-container">
            <div class="resultspages">
                <div class="pbar">
                    <span style="width:61%;padding-left:17px;text-align:left;float:left"><a href="pages.php<?php
                
                    
                    print $partitle.$parpub.$foldr.'" title="'.$title_attr_val.'" class="sort'.$class_title;
        
                                ?>
">Title</a></span>
                    <span style="width:90px;margin-right:10px"><a href="pages.php<?php 
                                
                        print $parlastmod.$parpub.$foldr.'" title="'.$lastmod_attr_val.'" class="sort'.$class_lastmod;

                            ?>
">Last modified</a></span>
                </div>
                <?php

                    
                    
                    # Multiple menu values
                    #publish_unpublish_array 
                    $pa = ['on'=>['unpub','Unpublish','<a href="../$rt$filename" class="options-button" title="Visit page" target="_blank">Visit</a>','hidden','',''],
                          'hidden'=>['pub','Publish','<span class="options-button option-off" title="Page is unpublished">Visit</span>','on',/*css class*/' pbopacity','<span class="unp" title="Unpublished">[u]</span>']];

                    
                    
                    
            
                    # Print results
                    $cwd = 'pages';
                    $catnum = count($array_res);
                    include 'navinfo.php';
                    
                    
                
                    $c=0;
                    $r=0;
                
                    include 'en_code.php';
                    
                    
                    foreach($array_res as $file) {

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


                            $fxml = simplexml_object($file,'l','page');
                            $published = $fxml->pageinfo->page->published;
    

                            $r++;


                            $title = $fxml->pageinfo->page->title;
                            $filename = $fxml->pageinfo->page->filename;
                            $rt = empty($fxml->pageinfo->page->path) ? '' : $fxml->pageinfo->page->path;                            
                            $utime = (int)$fxml->pageinfo->page->modified;
                            $ftime = date_form($utime);
                            $foldn = $rt == '' ? '' : $homedir.'/'.$rt;
                            
                            
                            
                            if ($title == '') 
                                $title = '(no title)';
                            
                            
                            $pb = $published == '' || $published == 'on' ? $pa['on'] : $pa['hidden'];
                            
                            if (isset($_GET['showpub']))
                                $g='&showpub';
                            elseif(isset($_GET['showunp']))
                                $g='&showunp';
                            else
                                $g='';
                                    
                                    
                            #$cssbg = (($c % 2) == 1) ? ' -bg' : '';

                                echo '<div class="savedpage'.$pb[4].'">
                                <span class="page-title" title="'.$foldn.$filename.'">'.$pb[5].'<a href="createpage.php?savedname='.$file.$g.'">'.load_xml($title).'</a></span>
                                <div class="page-options"><a href="createpage.php?savedname='.$file.$g.'" class="options-button" title="Edit page">Edit Page</a>
                                <a href="javascript:" onclick="if (conf(this)) window.location.href=\'pages.php?max='.$ofp.'&page='.$filename.$parpub.'&amp;savedpage='.$file.'\'" class="options-button not" title="Delete page">Delete</a>
                                <a href="javascript:" onclick="if ('.$pb[0].'(this)) window.location.href=\'pages.php?max='.$ofp.'&published='.$file.$parpub.$foldr.'&amp;value='.$pb[3].'\'" class="options-button not" title="'.$pb[1].' page">'.$pb[1].'</a>                            
                                '.str_replace(['$rt','$filename'],[$rt,$filename],$pb[2]).'
                                </div>
                                <div class="lastmod" title="'.date("H:i",$utime).'">'.$ftime.'</div>
                                </div>';
                            }
                        
                        
                            $c++;
                        }
                    
                    if ($c==0)
                        print '<i id="no-results">:: no pages found</i>';
                    
                    
                    ?>
                    
                <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>
    </div>
    <?php
    
    
    
    # plugins
    include 'execute.php'        
    

    
    ?>
</body>
</html>