<?php

    
    include 'data_connect.php';
    include 'log.php';

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



?>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>System check</title>
<link rel="stylesheet" type="text/css" href="cmstyle.css">
<?php
    $cssid = '#settings';
    include 'csstheme.php';
    print '<style>#settings + .dpsub:after{content:"System check"}'.$curval.'</style>' ?>
</head>
<body>
<?php


    include 'mypanel.php'
    
    ?>
    
    <div class="main subpage">
        <h1 class="inbl"><a href="general.php" title="Back to Settings">&larr;</a>System check</h1>
        <div class="center-container subcontainer" style="font-size:15px">    
    
    
    
    <?php
    # System check
    
    # Check number of posts and pages
    # Retrieve accidentally deleted pages from the home dir
    # Update log.xml
    # Update categories.xml
    # Create autosaves.xml
    # Remove unused Tags
    
    
    echo 'MonoCMS 3.0<br>PHP version: '.phpversion().'<br><div class="clear"></div><p>Starting system refresh...</p><br>';



    ##########
    # Pages retrieve
    #####
    
    
    $logxml = simplexml_object('log.xml','e',null);
    $pages = scandir('savedpages');
    $pgsum=$pgr=0;
    
    echo 'Searching for deleted pages...<br>';

    foreach($pages as $page) {

        if (is_file('savedpages/'.$page)) {

            if (substr($page,-4) == '.xml') {
                
                $xmlfile = simplexml_object($page,'l','page');
                if ($xmlfile == ['falsexml'])
                    continue;


                $pgsum++;
                $xmlname = basename($page,'.xml');
                
    
                if (!is_array($xmlfile))
                    if (!is_file('../'.$xmlfile->pageinfo->page->filename.'.php') && $xmlfile->pageinfo->page->published != 'hidden' && $xmlfile->pageinfo->page->published !== false )
                        if (empty($xmlfile->pageinfo->page->path)) {
                            file_put_contents('../'.(string)$xmlfile->pageinfo->page->filename.'.php','<?php $pn = "'.$xmlname.'"; $incp=""; include "monofiles/path.php" ?>');
                            $pgr++;
                        }
            }
        }
    }
    
    echo 'Pages retrieved: '.$pgr.'<br>';




    ##########
    # Posts & pages count
    #####
    
    
    $posts = scandir('autosaves');
    $logxml = simplexml_object('log.xml','e',null);
    $pages = scandir('savedpages');

    $psum=0;
    $pgsum=0;
    foreach ($posts as $post)
        if (is_file('autosaves/'.$post))
            if (substr($post,-4) == '.xml' && substr($post,-6) != 'nu.xml' && $post != 'autosaves.xml')
                $psum++;

    $logxml->info->posts = $psum;
    
    
    foreach($pages as $page)
        if (is_file('savedpages/'.$page))
            if (substr($page,-4) == '.xml')
                if (simplexml_object($page,'l','page') !== ['falsexml'])
                    $pgsum++;
                
    $logxml->info->pages = $pgsum;

    
    # save
    $logxml->info->modified = time();
    simplexml_object_save('log.xml',$logxml,null);

    echo '<p>Total number of posts: '.$psum.'<br> Total number of pages: '.$pgsum.'<br></p>';




    ##########
    # categories update (2.4)
    # 2.3 -> 2.4 versions. categories.xml file change
    #####
    
    
    if (!is_file('filesinfo/categories.xml')) {
    
        echo 'Missing categories xml file.. Creating new file..<br>';
            
        $fpc = file_put_contents('filesinfo/categories.xml','<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL.'<categories><uncat>on</uncat><uncatfolder>uncategorized</uncatfolder><uncatindex>on</uncatindex><uncatlink>on</uncatlink></categories>');
        if (!is_file('../uncategorized/index.php')) {
            if (!is_dir('../uncategorized'))
                if (mkdir('../uncategorized',0777,true) === false)
                    echo 'Error while trying to create folder for category "uncategorized" <br>';
            
                if (file_put_contents('../uncategorized/index.php','<?php $catg=\'uncategorized\'; $incpc= \'../\'; include \'../monofiles/precat.php\' ?>') === false)
                    echo 'Failed to create index file for uncategorized posts...<br>';
        }
        else
            echo 'Index file for uncategorized posts was not created. An index.php file already exists...<br>';
            
    }
    
    if (!isset($fpc) || $fpc !== false) {
    
        $categories_old = file_get_contents('filesinfo/categories.xml');
        $new = simplexml_load_string($categories_old);

        
        if (isset($new->folders)) {
            
            $newcats = get_categories();
            
            
            if ($newcats !== false) {
            
                foreach($new->folders->children() as $folder=>$name) {
                    
                    if (isset($newcats[$folder]))
                        continue;
                    
                    $m=md5(microtime());
                    usleep(1000);
                    
                    $newcats[$m] = [(string)$folder,(string)$name->name];
                }
            }
        
            
            else
                $newcats=[];
                
            
            
            $new = simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL.'<categories></categories>');
            
            
            $c=0;
            foreach ($newcats as $k=>$v) {

                $new->addChild('category',PHP_EOL);
                $new->category[$c]->addChild('cid');
                $new->category[$c]->addChild('folder');
                $new->category[$c]->addChild('name');
                $new->category[$c]->addChild('merge');
                $new->category[$c]->addChild('catindex');
                $new->category[$c]->addChild('catlink');
                $new->category[$c]->cid = $k;
                $new->category[$c]->folder = 'category/'.$v[0];
                $new->category[$c]->name = $v[1];
                $new->category[$c]->catindex = 'on';
                $new->category[$c]->catlink = 'on';
                
            
                $c++;

            }


            simplexml_object_save('categories.xml',$new,null);
            echo '<p>&check; Categories file configured</p>';

        }
    }
    
    else
        echo 'Failed to create a categories file';





    ##########
    # Remove empty tag pages
    #####
    
    
    echo '<br>Searching for unused post tags...<br>';
    $tags = get_tags();
    $tgs=[];
    foreach($tags as $t) {
        $mt = mb_strtolower($t,'UTF-8');
        $tgs[] = str_replace(' ','-',$mt) ;
    }
    
    $tgp = '../tags/';
    $tagfolders = glob('../tags/*',GLOB_ONLYDIR);
    echo '<p>';
    foreach($tagfolders as $v) {
    
        $fold = basename($v);
        if (!in_array($fold,$tgs))
        
            if (is_file($tgp.$fold.'/index.php')) {
                unlink($tgp.$fold.'/index.php');
                #rmdir($tgp.$fold);
                
                echo 'Tag '.$fold.' was removed <br>';
            }
    }
    echo '</p>';
    



    ##########
    # Update categories (category to catid) in posts xmls + create autosaves.xml
    #####
    
    $g='';
    $empty=[];
    $gc = get_categories();
    foreach($gc as $k=>$v)
        $empty[$k] = $v[1];

    if (!is_file('autosaves/autosaves.xml')) {

        $ndi = new DirectoryIterator ('autosaves/');

        foreach($ndi as $file) {

            $fext = $file->getExtension();
            $fname = $file->getFilename();

            if ($fext == 'xml' && $fname != 'autosaves.xml') {
            
            
                $c = simplexml_object($fname,'e','post');
                
                if (!is_array($c)) {

                    if (!empty($c->postinfo->post->category) && strcasecmp((string)$c->postinfo->post->category,'uncategorized') != 0) {
                    
                        $oldcat = (string)$c->postinfo->post->category;
                        $catval = array_search($oldcat,$empty);
                    
                    }    
                            
                    else
                        $catval = ''; # uncategorized
                        
                    
                    if (!isset($c->postinfo->post->catid))
                        $c->postinfo->post->addChild('catid',$catval);
                    
                    
                    $g .= '<savedpost><postinfo><post>';
                    foreach($c->postinfo->post->children() as $k=>$v)
                        $g .= '<'.$k.'>'.str_replace(['"','&'],['&quote;','&amp;'],$v).'</'.$k.'>'.PHP_EOL;


                    $g .= '<file>'.basename($fname,'.xml').'</file>';
                    $g .= '</post></postinfo></savedpost>'.PHP_EOL;
                    
                    simplexml_object_save($fname,$c,'post');
                    
                }    
            }
        }
        
            if (file_put_contents('autosaves/autosaves.xml','<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL.'<autocontent>'.$g.'</autocontent>') !== false)
                echo '<p>&check; autosaves.xml was successfully created</p>';
            else
                echo '<p>Failed to create file autosaves.xml, in autosaves/ </p>';
    }



    ##########
    
        
        echo '<div class="clear-m"></div><p>System check complete - '.date("H:i",time()).'</p><br>';
    
    
        $_SESSION['MONsystemcheck'] = true;
        action_confirm()
            
    ?>
        
        <p><a id="refresh" href="refresh.php?syschk" title="Start system check"><button type="button" style="cursor:pointer" tabindex="-1">&olarr; Start system check</button></a></p>
        </div>
    </div>
</body>
</html>