<?php


    # Create posts categories 


    # 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;
    }
    
    
    
    # Get categories
    $gc = get_categories();
    
    
    # Remove array from GET
    foreach($_GET as $str)
        if (!is_string($str)) {
            header('Location: catmanage.php');
            exit;
        }

    
    # Clean foldernames in 'path/destination_folder/' and allow only valid values
    if (isset($_POST['foldername'])) {
        
        
        # Categories xml missing error
        if ($gc === false) {
            $_SESSION['MON_cat_xmlnotfound'] = true;
            header('Location:catmanage.php');
            exit;
        }
        
        
        # Path and folder - single input cleaning
        $rem_chars = ['&','$','+',',',':',';','=','?','@','<','>','#','%','{','}','|','^','~','[',']','`','\\','\'','"','\n','\r'];
        $folder = str_replace($rem_chars,'',$_POST['foldername']);
        $folder = str_replace(' ','-',$folder);
        $folder = preg_replace('/--+/','',$folder);
        $folder = preg_replace('/\/\/+/','/',$folder);        
        $folder = mb_strtolower($folder,'UTF-8');

        if ($folder == '') {
        
            $par = isset($_POST['hiddencatid']) && isset($gc[$_POST['hiddencatid']]) ? '?catid='.$_POST['hiddencatid'] : '' ;
            $_SESSION['MON_catfolder_error'] = true;
            header('Location:category.php'.$par);
            exit;
        }
        
        elseif (substr($folder,-1) != '/')
            $folder .= '/';
        
        
        # Deny foldernames if in pages_na.xml (catfoldername)
        $denylist = simplexml_object('pages_na.xml','l',null);

        if ($denylist == ['missingfile'] || empty($denylist->catfoldername)) {
        
            file_put_contents('filesinfo/pages_na.xml','<?xml version="1.0" encoding="utf-8"?><pagesna><pagefilename></pagefilename><pagefolder>..</pagefolder><pagefolder>.</pagefolder><pagefolder></pagefolder><pagefolder>monofiles</pagefolder><pagefolder>index</pagefolder><pagefolder>pagep</pagefolder><catfoldername>.</catfoldername><catfoldername>..</catfoldername><catfoldername>monofiles</catfoldername><catfoldername></catfoldername></pagesna>');
            $na = ['catfoldername'=>['.','..','monofiles','']];
        }


        else
            foreach($denylist as $k=>$v)
                $na[$k][] = (string)$v;
        
        #black list foldernames in an array 
        $nacf = $na['catfoldername'];
        $catfolders = explode('/',rtrim($folder,'/'));



        # difference between submitted and restricted foldernames
        $cleancf = array_diff($catfolders,$nacf);
        

        
        # Not allowed to contain foldernames from denylist or  write inside tags/ & monofiles/ folders        
        if ($cleancf != $catfolders ||  substr($folder,0,5) == 'tags/' || substr($folder,0,10) == 'monofiles/') {
            
            $_SESSION['MON_catfolder_error'] = true;
            header('Location:category.php?catid='.$_POST['hiddencatid']);
            exit;
            
        }
}
    
    
    
    
    # Save 'uncategorized' category
    if (isset($_POST['hiddencatid']) && $_POST['hiddencatid'] == 'uncategorized') {


        
        ### Files
        
        # full path/index
        $foldname = '../'.$folder.'index.php';
        
        
        # existing folder of uncategorized
        $oldfolder = $gc['uncategorized'][0];
        unset($gc['uncategorized']);
        
        
        
        if (substr($oldfolder,-1) != '/')
            $oldfolder = $oldfolder.'/';
        
        
        
        # get all category folders(except uncategorized)
        $all=[];
        foreach($gc as $v)
            $all[] = $v[0];
            
            
        # Cannot write over another category
        # Only checks for existing categories (not for existing index files)
        if (in_array($folder,$all)) {
            $_SESSION['MON_uncat_exists'] = true;
            header('Location:category.php?catid=uncategorized');
            exit;
        }
        
        
        
        # Cannot write folder if index.php already exists and doesn't belong to uncategorized
        if (is_file($foldname) && $folder != $oldfolder) {
            $_SESSION['MON_catfolder_error'] = true;
            header('Location:category.php?catid=uncategorized');
            exit;
        }
        
        
        
        # incpath looks like ../../../
        $final = explode('/',$folder);
        $depth = count($final)-1; # -1 removes an empty string passed from explode, because if the '/' at the end of folder
        $incpathc = str_repeat('../',$depth);
        
    
        # Check if folder already exists and write new folder
        if (!is_dir('../'.$folder))
            if (mkdir('../'.$folder,0777,true) === false) {
                $_SESSION['MON_cat_files_error'] = true;
                header('Location:category.php?catid=uncategorized');
                exit;
            }


        # Write new index
        file_put_contents($foldname,'<?php $catg=\'uncategorized\'; $incpc= \''.$incpathc.'\'; include \''.$incpathc.'monofiles/precat.php\' ?>');
        


        # if the folder name of uncategorized has changed, remove old folder
        if ($oldfolder != $folder && is_file('../'.$oldfolder.'index.php'))
            unlink('../'.$oldfolder.'index.php');

        
        
        ### XML
        $cxml = simplexml_object('categories.xml','e',null);
        
        # Write categories.xml
        #if (!is_file('filesinfo/categories.xml'))
        /*    file_put_contents('filesinfo/categories.xml','<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL.'<categories></categories>');*/


        # On/off values
        $tog = ['maininc','catindex','catlink'];
        foreach($tog as $v)
            $_POST[$v] = isset($_POST[$v]) ? 'on' : 'off';
    
        
        #<uncat>on</uncat><uncatfolder>uncategorized</uncatfolder><uncatindex>on</uncatindex><uncatlink>off</uncatlink>    
        $cxml->uncat = $_POST['maininc'];
        $cxml->uncatindex = $_POST['catindex'];
        $cxml->uncatlink = $_POST['catlink'];
        $cxml->uncatfolder = $folder;


        
        # Save
        simplexml_object_save('categories.xml',$cxml,null);
        
        
        $_SESSION['MON_cat_update'] = true;
        header('Location: catmanage.php');
        exit;



    }



    
    # Writing a category
    # if ...path.../index.php exists, you either have no right to save, or you save over the current category
    # else you write the file and if it's an existing category, replace old category info and remove old index.
    
        
    # Save a category
    if (isset($_POST['merge'])) {
    
    
        $cat_chk = get_categories(true);
        
        if ($cat_chk !== false) {
        
        
            ### Files
            
            #categories info
            $catmainall = (string)$cat_chk['?']->mainall;
            unset($cat_chk['?']);
            
            # submitted info
            $cid = $_POST['hiddencatid'];
            $indexcat = isset($_POST['catindex']) ? 'on' : 'off';
            $postlink = isset($_POST['catlink']) ? 'on' : 'off';
            #$cname = preg_replace('/\s\s+/',' ',$_POST['newcat']); There's a check later
            
            
            # Collect info
            # place [folders => names] in an array and save the $GET_ param.
            $get='';
            $name_fold=[];
            foreach($cat_chk as $key=>$val) {

                if ($key == $cid) {
                    # keep GET value
                    $get = '?catid='.$cid;
                    continue;
                }

                $name_fold[$val[0]] = $val[1];
            }
            
            
            
            
            if ($_POST['newcat'] != '' && $cid != '' && $_POST['foldername'] != '') {


                # Filename check
                $rem_chars = ['&','$','+','/',',',':',';','=','?','@','<','>','#','%','{','}','|','^','~','[',']','`','\\','\'','"'];
                $newcat = str_replace($rem_chars,'-',$_POST['newcat']);
                $newcat = preg_replace('/--+/','-',$newcat);
                $newcat = preg_replace('/ +/',' ',$newcat);
                
                
                if ($newcat == ' ') {
                    $_SESSION['MON_cat_invalid'] = true;
                    header('Location:category.php'.$get);
                    exit;    
                }
                
                
                # ../path
                $newfolder = '../'.$folder;
                
                # incpathc looks like ../../../
                $final = explode('/',$folder);
                $depth = count($final)-1; # -1 removes an empty string passed from explode, because if the '/' at the end of folder
                $incpathc = str_repeat('../',$depth);


                # oldfolder
                $oldfolder = isset($cat_chk[$cid][0]) ? (string)$cat_chk[$cid][0] : '';
                if (substr($oldfolder,-1) != '/')
                    $oldfolder = $oldfolder.'/';
                
                
                # Find the categories submitted as 'merge'                
                # Multiple names support, separated by ','
            
                $merged = explode(',',$_POST['merge']);
                $to_del=[];
                $c=0;
                foreach($merged as $val) {
                    if(!in_array($val,$name_fold))
                        unset($merged[$c]);
                    else {
                        if    ($val != 'uncategorized')
                            $to_del[] = array_search($val,$name_fold);
                    }
                    $c++;
                }            


                # already merged
                $oldmerge = [];
                if(!empty($merged))
                    foreach($cat_chk as $id=>$i)
                        if (in_array($i[1],$merged))
                            if(!empty($i[3]))
                                foreach($i[3] as $m)
                                    $oldmerge[] = $m;
                # maybe an alternative
                #$oldmerge = merged_categories();
                #$oldmerge = array_flip($oldmerge);
                


                
                
                # allow a 'submitted as merged' category to be overwritten         
                foreach($name_fold as $k=>$v)
                    if ($_POST['merge'] == $v)
                        unset($name_fold[$k]);
                
                                
                # Cannot write over existing category. Checking categories only, not index files. ('Catch' the error)
                if (in_array($newcat,$name_fold) || isset($name_fold[$folder]) || strcasecmp($newcat,'uncategorized') == 0) {
                    $_SESSION['MON_cat_exists'] = true;
                    header('Location:category.php'.$get);
                    exit;

                }
                
        
                # Cannot write an index.php that already exists and doesn't belong to the category
                if (is_file($newfolder.'index.php') && $folder != $oldfolder) {
                    $_SESSION['MON_catfolder_error'] = true;
                    header('Location:category.php'.$get);
                    exit;
                }
                
                
                # write dir and category index file
                if (!is_dir($newfolder))
                    if(mkdir($newfolder,0777,true) === false) {
                        $_SESSION['MON_cat_files_error'] = true;
                        header('Location:category.php'.$get);
                        exit;
                    }
                
                
                # write only if new or name or folder has changed (?)
                if (!isset($cat_chk[$cid]) || ($cat_chk[$cid][1] != $newcat || $oldfolder != $folder ))
                file_put_contents($newfolder.'/index.php','<?php $catg=\''.$newcat.'\'; $incpc= \''.$incpathc.'\'; include \''.$incpathc.'monofiles/precat.php\' ?>');
                
                
                # Remove files
                # if the folder name has changed, remove old folder
                if ($folder != $oldfolder && $oldfolder != '/' && is_file('../'.$oldfolder.'index.php'))
                    unlink('../'.$oldfolder.'index.php');
                
                
                # remove indexes of merged files(except uncategorized-removed above)
                if (!empty($to_del))
                    foreach($to_del as $fl)
                        if (is_file('../'.$fl.'index.php'))
                            unlink('../'.$fl.'index.php');

                ###
                
                

                ### Write XML info, after all checks are finished
                
                if (!is_file('filesinfo/categories.xml'))
                    file_put_contents('filesinfo/categories.xml','<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL.'<categories></categories>');
                
                
                # Update existing category or add new
                $addcat = simplexml_object('categories.xml','e',null);
                if (!is_array($addcat)) { 
                    
                    
                    # merge find ids
                    $mrg=[];
                    foreach($cat_chk as $k=>$v)
                        if (in_array($v[1],$merged))
                            if ($k != 'uncategorized')
                                $mrg[] = $k;
                    
                    
                    
                    # already merged
                    if (isset($cat_chk[$cid]))
                        if(!empty($cat_chk[$cid][3]))
                            foreach($cat_chk[$cid][3] as $m)
                                $mrg[] = $m;
                    
                    # add oldmerged
                    $mrg = array_merge($mrg,$oldmerge);
                            

                    ####

                    # Update a category
                    if (isset($cat_chk[$cid])) {
                        
                        $c=0;
                        foreach($addcat->category as $key=>$val) {

                            if ($val->cid == $cid) {
                                
                                $addcat->category[$c]->folder = $folder;
                                $addcat->category[$c]->name = $newcat;
                                $addcat->category[$c]->main = isset($_POST['maininc']) ? 'on' : 'off';
                                $addcat->category[$c]->merge = '';
                                
                                $cc=0;
                                foreach($mrg as $val) {
                                    $addcat->category[$c]->merge->cat[$cc] = $val;
                                    $cc++;
                                }
                                
                                $addcat->category[$c]->catindex = $indexcat;
                                $addcat->category[$c]->catlink = $postlink;
                                    
                                break;
                            }
                            $c++;
                        }
                        
                        $_SESSION['MON_cat_update'] = true;
                    
                    }
                    
                    
                    # Add a new category
                    else {

                        $get = '';

                        $addc = $addcat->addChild('category',PHP_EOL);
                        $addc->addChild('cid',$cid);
                        $addc->addChild('folder',$folder);
                        $addc->addChild('name',$newcat);
                        $adm = isset($_POST['maininc']) ? 'on' : 'off';
                        $addc->addChild('main',$adm);
                        $addm = $addc->addChild('merge');
                        
                        foreach($mrg as $mcat)
                            $addm->addChild('cat',$mcat);
                        
                        $addc->addChild('catindex',$indexcat);
                        $addc->addChild('catlink',$postlink);
                        $_SESSION['MON_newcat'] = true;
                    }


                    # Delete of merged categories and save xml file
                    # mrg contains the submitted 'merged' categories
                    if (count($mrg) > 0) {
                        
                        $addmrg=[];
                        $c=0;
                        foreach($addcat->category as $val) {
                            $cc=0;
                            foreach($val as $k=>$v) {
                                if(!empty($v->cat)) {
                                    $a=[];
                                    foreach($v->cat as $b)
                                        $a[] = (string)$b;
                                    $addmrg[$c][$cc] = $a;
                                }
                                else
                                    $addmrg[$c][$cc] = (string)$v;
                                $cc++;
                            }
                            $c++;
                        }
                        unset($addcat->category);
                        
                        foreach ($addmrg as $k=>$v)
                            if (!in_array($v[0],$mrg)) {
                            
                                $addc = $addcat->addChild('category',PHP_EOL);
                                $addc->addChild('cid',$v[0]);
                                $addc->addChild('folder',$v[1]);
                                $addc->addChild('name',$v[2]);
                                $addc->addChild('main',$v[3]);
                                $addm = $addc->addChild('merge');

                                if(!empty($v[4]))
                                    foreach($v[4] as $l)
                                        $addm->addChild('cat',$l);
                                                                                
                                $addc->addChild('catindex',$v[5]);
                                $addc->addChild('catlink',$v[6]);
                        }
                        
                    }



                    # Move uncategorized posts to another category
                    if (in_array('uncategorized',$merged)) {
                
                        
                        if (isset($cat_chk['uncategorized'])) {

                            
                            # Find post files
                            $xmlfiles=[];
                            $ndi = new DirectoryIterator('autosaves/');

                            foreach($ndi as $file) {

                                $fext = $file->getExtension();
                                $fname = $file->getFilename();
                                $lname = str_replace('.xml','',$fname);
                                
                                if (is_file('autosaves/'.$lname.'nu.xml'))
                                    continue;
                                    
                                if ($fext == 'xml' && $lname != 'autosaves') {
                                    
                                    $fcatid = getxmlpost('autosaves/'.$fname)['catid'];
                                    
                                    # if catid of a post is empty or it cannot be found in get_categories() & $mrg, merged categories, regard as uncategorized
                                    if ($fcatid === '' || (!isset($cat_chk[$fcatid]) && !in_array($fcatid,$mrg)))
                                        $xmlfiles[] = $fname;
                                }
                            }

                            if (count($xmlfiles) > 0) {
                                
                                $new_id = md5(microtime());
                
                                foreach($xmlfiles as $file) {
                                    
                                    $f = simplexml_object($file,'e','post');
                                    $f->postinfo->post->catid = $new_id;
                                    #$f->modified = time();
                                    
                                    if (simplexml_object_save($file,$f,'post') === false)
                                        $_SESSION['MON_uncat_post_send_failed'] = true;
                                    elseif (!isset($r))
                                        $r=true;
                                }
                                
                                
                                # autosaves.xml - turbomode 2.4
                                if (is_file('autosaves/autosaves.xml')) {
                                
                                    $asaves = simplexml_object('autosaves.xml','e','post');
                                    if (!is_array($asaves)) {
                                        
                                        $xmlfiles = array_flip($xmlfiles);
                                        $c=0;
                                        foreach($asaves->savedpost as $afile) {
                                            $file = $afile->postinfo->post->file;
                                            if (isset($xmlfiles[$file.'.xml']))
                                                $afile[$c]->postinfo->post->catid = $new_id;
                                            $c++;
                                        }
                                        
                                        simplexml_object_save('autosaves.xml',$asaves,'post');
                                    }
                                }
                                

                                if (!isset($r)) {
                                    $_SESSION['MON_uncat_post_fail_all'] = true;
                                    header('Location:category.php'.$get);
                                    exit;
                                }
                                
                                
                                $c=0;
                                foreach($addcat->category as $k=>$v) {
                                                    
                                    if ($v->cid == $cid)
                                        $addcat->category[$c]->merge->addChild('cat',$new_id);
                                    $c++;
                                }
                            }
                        }
                    }
    
                    
                    # save
                    simplexml_object_save('categories.xml',$addcat,null);
                    header('Location:catmanage.php'.$get);
                    exit;
                    
                }
            }

            else {
                
                $_SESSION['MON_cat_notset'] = true;
                header('Location:catmanage.php'.$get);
                exit;
            }    
        }
        
        else {
            
            $_SESSION['MON_cat_falsexml'] = true;
            header('Location:catmanage.php'.$get);
            exit;
        }

    }



    # Published category edit
    if (isset($_POST['mcat'])) {
    
        $ctgs = get_categories(true);        
        
        if ($ctgs !== false) {
            
            
            
            #if (isset($_POST['mainall']))
            #    $mainall = $_POST['mainall'];
            
            
            
            /*$mname = $_POST['mname'];
            foreach($ctgs as $k=>$v)    
                if ($mname == $v[1]) {        
                    $_SESSION['MON_cat_false_maincat_name'] = true;
                    header('Location:category.php');
                    exit;
                }
            
                
            # unset the non checkboxes
            unset($_POST['mname']);
        

            $xml->maincatname = $mname;    
            */
            
            
            $xml = $ctgs['?'];
            
            $onoff = ['mainall'];
            
            foreach($onoff as $v)
                if (!isset($_POST[$v]))
                    $xml->$v = 'off';
                else
                    $xml->$v = 'on';
                
            
            
            if (simplexml_object_save('categories.xml',$xml,null) !== false) {
            
                $_SESSION['MON_cat_maincat_saved'] = true;
                header('Location:catmanage.php');
                exit;
            }
        }
        
        else {
            
            $_SESSION['MON_cat_falsexml'] = true;
            header('Location:category.php');
            exit;
        }

    }

?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Categories</title>
<link rel="stylesheet" type="text/css" href="cmstyle.css">
<?php
    $cssid = '#categories';
    include 'csstheme.php';
    print '<style>'.$curval.'</style>' ?>
<script type="text/javascript">function conf(form){ return confirm('Save category?'); }</script>
</head>
<body>
    <?php


        # panel
        include 'mypanel.php';
        action_confirm();
        
        $goback = $acc_info['rights'] == 'administrator' ? '<a href="catmanage.php" title="Back to Categories">&larr;</a> ' : '<span style="display:inline-block;width:21px"></span> ';

        $ftrue = get_categories(true);
        if (isset($_GET['catid'])) {
            
            if ($_GET['catid'] == 'uncategorized') {
                
                $hcatid = 'uncategorized';
                
                if ($ftrue !== false) {
                    $catfold = $ftrue['?']->uncatfolder;
                    $catpub = $ftrue['?']->uncat;
                    $catindex = $ftrue['?']->uncatindex;
                    $catlink = $ftrue['?']->uncatlink;
                }
                else {
                    $catfold = '';
                    $catpub = 'on';
                    $catindex = 'on';
                    $catlink = 'on';
                }
                
                $cred = 'Uncategorized';
                print '<style>#categories + .dpsub:after{content:"Uncategorized"}</style>';
            }
            elseif (isset($gc[$_GET['catid']])) { 
                
                $hcatid = $_GET['catid'];
                $catfold = $gc[$hcatid][0];
                $catname = $gc[$hcatid][1];
                $catpub = $gc[$hcatid][2];
                $catindex = $gc[$hcatid][4];
                $catlink = $gc[$hcatid][5];
                $subm = 'Update';
                $cred = 'Categories &rsaquo; '.$catname;
                print '<style>#categories + .dpsub:after{content:"Edit category"}</style>';
            }
            
                
            elseif ($_GET['catid'] == 'maincategory') {
            
                $cred = 'Categories settings';
                print '<style>#categories+.dpsub:after{content:"Settings"}</style>';
                
            }
            
            else {
            
            $_SESSION['MON_cat_not_found'] = true;
            header('Location:catmanage.php');
            exit;
            
            }
        
        }
        
        else {
                $hcatid = md5(microtime().rand());
                $catfold = $catname = $catindex = $catlink = $catpub = '';
                $subm = 'Submit';
                $cred = 'Create category';
                print '<style>#categories+.dpsub:after{content:"Create category"}</style>';
            }
    
        

    ?>
    
    <div class="main subpage">
        <h1 class="inbl"><?php print $goback.$cred ?></h1>
        <div class="center-container subcontainer">
                
                
            <?php 
                
            
            
            if (!in_array('maincategory',$_GET,true)) : ?>
                
                
            <form action="category.php" id="MONform" method="POST" onkeypress="if (event.key === 'Enter') {event.preventDefault(); if(conf(this)) this.submit()}">
                <?php if ($hcatid != 'uncategorized') : ?>
                <div class="sel subsel">
                <label for="category-name" class="subcatname">Name</label>
                <div class="clear-m"></div>
                <div class="clear"></div>
                <div class="newoptions"></div>
                <div class="clear-m"></div>
                
                </div>
                <input name="newcat" id="category-name" type="text" value="<?php echo $catname ?>" class="inp-2" placeholder="Category name">
                <?php endif ?>
                <input name="hiddencatid" type="text" value="<?php  print $hcatid ?>" hidden>
                <div class="clear"></div>
                <div class="clear"></div>
                <div class="sel">
                    <label for="category-folder">Folder</label>
                    <span class="des">Path and folder.</span>
                </div>
                <input name="foldername" id="category-folder" type="text" value="<?php echo $catfold ?>" class="inp-2" placeholder="Folder" style="margin-top:2px">
                
                
                
                <div class="clear-m"></div>
                
                <div class="sel">
                    <label for="monoff-m" title="Publish">Main feed</label>
                    <span class="des">Include this category on index pages (homepage and tag indexes) in your site's main content stream.<i> Note: This setting will have no effect if 'Publish all in main feed' is enabled in the categories settings.</i></span>
                </div>
                <input name="maininc" type="checkbox" id="monoff-m" class="moncheck" value="on" title="Include in published categories"<?php
                if ($catpub == 'on')
                    echo ' checked';
                    
                $lock = $ftrue['?']->mainall == 'on' ? '<img src="images/lock.png" class="catlock" title="Publish all in main feed is on">' : '';
                ?>
>
                
                <label for="monoff-m" class="lab-5" title="Publish"></label><?php echo $lock ?>
                <div class="clear-m"></div>
                    <?php #endif ?>
                
                
                <!-- Both create and edit-->
                <!-- Index -->
                
                <div class="sel">
                    <label for="monoff-ind" class="lab-1" title="Category index page">Category index page</label>
                </div>
                    <input name="catindex" type="checkbox" id="monoff-ind" class="moncheck" value="on" title="Category home page"<?php 
                    
                    if ($catindex == 'on')
                        echo
                            ' checked'
                    
                    
                    ?>
>
                    <label for="monoff-ind" class="lab-5" title="Category index page"></label>
                <div class="clear-m"></div>
                
                <!-- Link -->
                <div class="sel">
                    <label for="monoff-lnk" class="lab-1" title="Post links">Post links</label>
                    <span class="des">Publish this category's Posts.</span>
                </div>
                <input name="catlink" type="checkbox" id="monoff-lnk" class="moncheck" value="on" title="Posts link"<?php 
                
                    if ($catlink != 'off')
                        echo
                            ' checked'
                    
                    
                    ?>
>
                <label for="monoff-lnk" class="lab-5" title="Post links"></label>
                <div class="clear-m"></div>
                <div class="clear"></div>
                
                <?php 
                    
                    if ($hcatid != 'uncategorized') : 
                ?>
                <div class="newoptions"></div>
                <div class="clear-m"></div>
                <div class="clear"></div>
                <div class="clear"></div>
                <div class="sel">
                    <label for="catmerge">Import category</label><br>
                    <span class="des mrg">Merge with another category, retaining this category's name and folder.</span>
                </div>
                
                <input type="text" id="catmerge" class="inp-2" name="merge" list="mergecats" maxlength="100" placeholder="No categories">
                <?php
                
                    endif;
                    /*$cm=[];
                    $c=0;
                    foreach($gc as $k=>$v)
                        if ($hcatid == $k && !empty($v[3]))
                            foreach($v[3]->cat as $id) {
                                foreach($gc as $f=>$l)
                                    if($id == $f) {
                                        
                                        print
                                
                                        '<div class="sel subsel">

                                            <label for="monoff-'.$c.'" title="Merge with this category">'.$l[1].'</label>
                                            <input name="monmerge-'.$c.'" type="checkbox" id="monoff-'.$c.'" class="moncheck" value="'.$id.'" title="'.$l[1].'" checked>
                                            <label for="monoff-'.$c.'" class="lab-5 sublab" title="Merge with this category"></label>
                                         </div>
                                         <div class="clear"></div>
                                         ';
                                         
                                        $cm[] = $id; 
                                        
                                        }
                                $c++;
                            
                            }
                
                */
                ?>
                <div class="clear-m"></div>
                <datalist id="mergecats">
                <?php
                    if ($gc !== false) {
                        $ctg = merged_categories();
                        foreach($gc as $k=>$v)
                            if ($k != $hcatid && !isset($ctg[$k]))
                                print'<option>'.$v[1].'</option>';
                    }
                ?>
                </datalist>
                <div class="clear"></div>
                <div class="clear"></div>

                <?php 
                
                 else :
                     
                     
                     if ($gc !== false)
                        $mainallch = $ftrue['?']->mainall == 'on' ? 'checked' : '';
                                                            
                    else
                        $mainallch = ''
                    
                ?>
            <form action="category.php" id="MONform" method="POST">
                <input name="mcat" type="text" value="main" hidden>
                <div class="clear"></div>
                <div class="sel subsel">
                    <label for="monoff-all" title="Publish all in main feed">Publish all in main feed</label>
                    <span class="des desall">Publish all categories in your website's main posts feed. Turn off to control each category separately.</span>
                </div>
                    <input name="mainall" type="checkbox" id="monoff-all" class="moncheck" value="on" title="include all categories" <?php print $mainallch ?>>
                    <label for="monoff-all" class="lab-5" title="Publish all in main feed"></label>
                
                <?php endif ?>
            </form>
            <div class="clear"></div>

            <!-- For Authors only-->
            <div class="ctg">
            <?php
                
                # For authors only
                if ($monrights == 'author') {

                    print '<div class="newoptions"></div><div class="clear"></div>';
                    
                    print '<style>h1.inbl{margin-left:-12px}</style>';


                    if ($gc !== false) {
                        $agc=[];
                        foreach($gc as $key=>$val)
                            $agc[$key] = $val;
                        
                        asort($agc);
                                    
                        $c=0;
                        foreach($agc as $key=>$val) {
                            echo '<span class="cat">'.$val[1].'</span>';
                            $c++;
                        }
                        if ($c == 0)
                            echo '<i id="no-results">:: No categories</i>';
                    }
                                
                    else
                        echo '<i id="no-results">:: Error was found in categories file</i>';
                        
                }

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