<?php
    
    
    
    
    
    # Hide/show sidemenu
    function togglesidemenu() {
    
        $i = get_account($_SESSION['userID']);    
        $sidem = $i['sidemenu'] == '' || $i['sidemenu'] == 'on' ? 'off' : 'on';
    
        edit_useraccount('sidemenu',$sidem);
        
        return true;    
    
    
    }
    
    ### ### ###    
    # toggle sidemenu # Do not remove
    if (isset($_GET['sidemenu'])) {
    
        unset($_GET['sidemenu']);
        # Keep or remove some GET values
        $plink = '';
        
        if (count($_GET) > 0) {
            $x=0;
            foreach($_GET as $param=>$val) {
                $front = ($x == 0) ? '?' : '&';
                $plink .= $front.$param.'='.$val;
                $x++;
            }
        }
        
        togglesidemenu();
        $loc = basename($_SERVER['PHP_SELF']);
        header('Location: '.$loc.$plink);
        exit;
    }
    
    ### ### ###




    # Load the settings file and return an error message if the file is missing    
    function getXMLSettings() {
            
            
            $file = 'filesinfo/settings.xml';
            
            if (is_file($file)) {
                
                $f = simplexml_load_file($file);
                
                if ($f !== false) :

                $settings = ['ownerid' => $f->general->ownerid,
                            'title' => $f->general->title,
                            'description' => $f->general->description,
                            'indexresults' => $f->general->indexposts->results,
                            'indexlastmod' => $f->general->indexposts->lastmod,
                            'dateshow' => $f->general->dateshow,
                            'maximagesize' => $f->general->maximagesize,
                            'modified' => $f->general->modified,
                            'togsign' => $f->general->togsign,
                            'togcategories' => $f->general->togcategories,
                            'togtags' => $f->general->togtags,
                            'togreadold' => $f->general->togreadold,
                            'revorder' => $f->general->revorder,
                            'sort' => $f->general->sort,
                            'total' => $f->general->total,
                            'mainblog' => $f->general->mainblog,
                            'togtime'=> $f->general->togtime,
                            'togptitle'=> $f->general->togptitle,
                            'togexc'=> $f->general->togexc,
                            'exclimit'=> $f->general->exclimit,
                            'unidates'=> $f->general->unidates,
                            'togreadmore'=> $f->general->togreadmore,
                            'tagstext' => $f->general->tagstext
                ];
                
                    
                else :
                
                $_SESSION['ERROR:Settings'] = true;
                

                endif;
            }
            
            return $settings;
        }
    
    
    
    
    # Simple getxmlpost function, will find any xml tag of a post xml file.
    function getxmlpost($file) {
    
        if (is_file($file)) {
            
            $cfile = file_get_contents($file);
            $f=simplexml_load_string($cfile);
            $x=0;
            $all=[];
            foreach($f->postinfo->post->children() as $key=>$val) {
                $all[$key]=(string)$val;
                $x++;    
            }
                
            return($all);
            
        }
    }
    




    # Load a xml system file from filesinfo folder or a page or a post, as an object. You can use a simplexml class to gain control over a file
    # instead of getting or applying predefined object elements, like update_log() or get_log() functions do.
    # $a [l -> load a xml , e -> create new simplexml element]  $type[post,page,null]
    # 2.4 : removed fourth parameter, $path.
    function simplexml_object($filename,$a='l',$type='null') {
        
        $folders = ['post'=>'autosaves/','page'=>'savedpages/',''=>'filesinfo/'];
        $fold = '';
        foreach($folders as $key=>$val) {
            
            if ($type == $key) {
                $fold = $val;
                break;
            }
        }
        
        
        $mf = 'monofiles';
        $filename = basename($filename);
        
        
        # Search for the right path    - (found in print_tags())
        if (file_exists($fold))
            $file = $fold.$filename;
    
        
        else {
        
            $p='';
            $x=0;
            if (!file_exists($mf.'/'.$fold))
                for ($p=''; $x<50; $p=$p.'../') {
                     if (file_exists($p.$mf) && is_file($p.$mf.'/filesinfo/log.xml'))
                        break;
                    $x++;
                    }
                        
            $file = $p.$mf.'/'.$fold.$filename;
                    
                    
        }
        
        
        
        $error = ['missingfile'];
        
        if (is_file($file)) {
            
            $falsexml = ['falsexml'];
            libxml_use_internal_errors(true);
            simplexml_load_file($file);

            if (!empty(libxml_get_errors())) {
                $object = $falsexml;
                libxml_clear_errors();
             }
            
            else  {
            
            if ($a == 'l') 
                $object = simplexml_load_file($file);
            
            elseif ($a == 'e') 
                $object = new simpleXMLElement($file,0,true);
            
            }
            
        }

        else
            $object = $error;
        
        
        return $object;

    }


    

    # Save an xml file from a xml object - type can be post, page or null - search for the right path, 2.4
    function simplexml_object_save($file,$obj,$type=null) {
        
        libxml_use_internal_errors();
        
        $folders = ['post'=>'autosaves/','page'=>'savedpages/',''=>'filesinfo/'];
        foreach($folders as $key=>$val) {
            if ($type == $key) {
                $fold = $val;
                break;
            }
        }
        
        
        # Search for the right path
        $mf = 'monofiles';
        $filename = basename($file);
                
        if (file_exists($fold))
            $file = $fold.$filename;
        
        else {
        
            $p='';
            $x=0;
            if (!file_exists($mf.'/'.$fold))
                for ($p=''; $x<50; $p=$p.'../') {    
                     if (file_exists($p.$mf) && is_file($p.$mf.'/filesinfo/log.xml'))
                        break;
                    $x++;    
                    }
                        
            $file = $p.$mf.'/'.$fold.$filename;
        }
        
        
        # Save
        if (!is_array($obj)) {
            $obj->asXML($file);
            return true;
        }

        else
            return false;

    }




    # Load settings on your website pages
    # $path added in 2.2
    # $path dropped in 2.4
    function cmsetup() {

        libxml_clear_errors();
        libxml_use_internal_errors(true);

        $set = simplexml_object('settings.xml','l',null);

        $a = ['website_title' => $set->general->title,
              'website_description' => $set->general->description,
              'results_per_page' => $set->general->indexposts->results,
              'results_per_page_lastmod' => $set->general->indexposts->lastmod,
              'show_date' => $set->general->dateshow,
              'sign_posts' => $set->general->togsign,
              'show_category' => $set->general->togcategories,
              'show_tags' => $set->general->togtags,
              'read_old_link' => $set->general->togreadold,
              'reverse_order' => $set->general->revorder,
              'sort' => $set->general->sort,
              'total' => $set->general->total,
              'ptitle' => $set->general->togptitle,
              'exc' => $set->general->togexc,
              'exclimit' => $set->general->exclimit,
              'unidates' => $set->general->unidates,
              'togreadmore' => $set->general->togreadmore,
              'tagstext' => $set->general->tagstext 
              ];
        
        
        return $a;

    }



    # get_categories
    # Write  all categories into an array [folder name => category name]
    # if $obj is set to true, it includes the categories xml file as a simplexml object
    function get_categories($obj=null) {
        
        $cats = simplexml_object('categories.xml','e',null);
        
        if (!is_array($cats)) {
            $ctgs = [];
            
        foreach($cats->children() as $key=>$val) {
        
            if ($val->cid != '') {
            
                $catinfo = [(string)$val->folder,(string)$val->name];
                $catinfo[] = (string)$val->main;
                
                if (!empty($val->merge)) {
                        $mrg=[];
                        foreach($val->merge->cat as $l)
                            $mrg[] = (string)$l;
                        
                        $catinfo[] = $mrg;
                    }
                else
                    $catinfo[] = [];
                
                $catinfo[] = (string)$val->catindex;
                $catinfo[] = (string)$val->catlink;

                $ctgs[(string)$val->cid] = $catinfo;
            }
        }
        
        # Uncategorized is also a category
        # <uncat>on</uncat><uncatfolder>uncategorized</uncatfolder><uncatindex>on</uncatindex><uncatlink>off</uncatlink>
        $ctgs['uncategorized'] = [(string)$cats->uncatfolder,'uncategorized',(string)$cats->uncat,[],(string)$cats->uncatindex,(string)$cats->uncatlink];
        
        
        
        if ($obj === true)
            $ctgs['?'] = $cats;
    
        return $ctgs;
        
        }
        
        else
            return false;
    }
    
    

    
    # Get all tags from posts. Works for the panel only.
    function get_tags(){
        
        
        if (is_file('autosaves/autosaves.xml')) {

            $tgs='';            
            $asaves = file('autosaves/autosaves.xml');
            foreach($asaves as $ent) {
            
                $st = strpos($ent,'<tags>');
                $en = strpos($ent,'</tags>');
                
                if ($st !== false)
                    $tgs .= substr($ent,($st+6),$en-($st+6)).','; 
            
            
                #$tgs = preg_match('/(?<=<tags>)(.*)(?=<\/tags>)/', ......
            }
            $tgs = rtrim($tgs,',');
            $tgs = htmlspecialchars_decode($tgs);
            $tags = explode(',',$tgs);
        
        }
        
        else {
            
            $tags=[];
            $directory = new DirectoryIterator('autosaves/');
            foreach($directory as $fileinfo) {

                if ($fileinfo->isFile()) {
                    
                    $fname = $fileinfo->getFilename();
                    if (strpos($fname,'.xml') !== false) {

                        $filexml = simplexml_object($fname,'l','post');
                        if (!empty($filexml->postinfo->post->tags)) {
                            
                            $ts = (string)$filexml->postinfo->post->tags;
                            if (strpos($ts,',') !== false) {
                                $tgs = explode(',',$ts);
                                foreach($tgs as $v)
                                    $tags[] = $v;
                            }
                            else
                                $tags[] = $ts;
                        }
                    }
                }
            }
        }
        
        
        $tags = array_unique($tags);
        return $tags;
    
    }
    
    
    
    
    # print categories with options . Sorting, limit results, exclude categories
    function print_categories($sort='',$lim=0,$ar=[]) {
    
        $gc = get_categories();
            
        $ctgs=[];
        # results : name -> folder
        foreach($gc as $v)    
            if (!in_array($v[1],$ar))
                $ctgs[$v[1]] = $v[0];
    
    
        if ($sort == 'alpha')
            ksort($ctgs);
            
        elseif ($sort == 'reverse')
            krsort($ctgs);
    
    
    
        if ($lim > 0)
            $ctgs = array_slice($ctgs,0,$lim);
            
            
        return $ctgs;    
    
    
    }
    
    
    
    
    # Get Tags with options . Sorting limit results exclude tags
    function print_tags($sort='alpha',$lim='0',$ar=[]) {
        
        
        
        # Search for the right path    
        $dir = 'monofiles/autosaves/';
        $p='';
        $x=0;
        
        if (!file_exists($dir))
            for ($p=''; $x<50; $p=$p.'../')    {
                 if (file_exists($p.$dir) && is_file($p.'monofiles/filesinfo/log.xml'))
                    break;
                $x++;    
            }
                
                
        if (!is_file($p.$dir.'autosaves.xml')) {
            
            $directory = new DirectoryIterator($p.$dir);
            $tags=[];
            $c=0;
            foreach($directory as $fileinfo) {

                if ($fileinfo->isFile()) {
                    
                    $fname = $fileinfo->getFilename();
                    if (strpos($fname,'.xml') !== false) {

                        $filexml = simplexml_object($fname,'l','post');
                        if (!empty($filexml->postinfo->post->tags)) {
                            
                            $ts = (string)$filexml->postinfo->post->tags;
                            if ($filexml->postinfo->post->type == 'Posted') {
                                
                                $tgs = explode(',',$ts);
                                foreach($tgs as $v)
                                    if (!in_array($v,$ar))
                                        if (isset($tags[$v]))
                                            $tags[$v]++;
                                        else
                                            $tags[$v] = 1;
                            }    
                        }
                    }
                }
            }
        }
        
        else {
            
            $xmlfile =  simplexml_object('autosaves.xml','l','post');
            if (!is_array($xmlfile)) {
                
                foreach($xmlfile->savedpost as $file) {
                
                    $ts = (string)$file->postinfo->post->tags; 
                    
                    if ($file->postinfo->post->type == 'Posted') {

                        $tgs = explode(',',$ts);
                        foreach($tgs as $v)
                            if (!in_array($v,$ar))
                                if (isset($tags[$v]))
                                    $tags[$v]++;
                                else
                                    $tags[$v] = 1;
                    }
                }
            }
        }
        
        
        unset($tags['']);
        
        if (!empty($tags)) {
        
            if ($sort == 'alpha')
                ksort($tags);
            else
                arsort($tags);
        
            
            if ($lim > 0)
                $tags = array_slice($tags,0,$lim);
            
            
            
        }
        
        foreach($tags as $k=>$t)
            echo '<a href="'.$p.'tags/'.str_replace(' ','-',mb_strtolower($k)).'" class="tag">'.$k,'</a>';
            
        
        return $tags;
    
    
    }
    
    
    
    
    # Load basic log info
    function get_log() {
        
        $loginfoxml = simplexml_object('log.xml','l',null);
        
        $i_log = ['posts' => (string)$loginfoxml->info->posts,
                  'pages' => (string)$loginfoxml->info->pages,
                  'failed' => (string)$loginfoxml->info->failed,
                  'modified' => (string)$loginfoxml->info->modified
                  ];
        
        return $i_log;
        
    }




    /*
    # Load installed plugins. get_plugins returns an array with all the plugins, containing the plugin name,
    # title & description, plugin status (on/off) and plugin directory
    # Dropped in 2.4
    function get_plugins() {}
    */




    # Load account info using a parameter of 'userID'
    function get_account($id) {
        

        $log = simplexml_object('log.xml','l',null);
        $account_info = [];
        
        $c=0;
        foreach($log->user as $i) {
            
            if ($i->userID == $id) {
                
                $account_info = ['name' => (string)$i->name,
                                 'pshs' => (string)$i->pshs,
                                 'rights' => (string)$i->rights,
                                 'login' => (string)$i->login,
                                 'ip' => (string)$i->ip,
                                 'icon' => (string)$i->icon,
                                 'userID' => (string)$i->userID,
                                 'editorname' => (string)$i->editorname,
                                 'created' => (string)$i->created,
                                 'results_posts' => (string)$i->results->posts,
                                 'results_pages' => (string)$i->results->pages,
                                 'results_images' => (string)$i->results->images,
                                 'status' => (string)$i->status,
                                 'urlicon'=>(string)$i->urlicon,
                                 'texteditor'=>(string)$i->texteditor,
                                 'theme'=>(string)$i->theme,
                                 'sortposts'=>(string)$i->sortposts,
                                 'sortpages'=>(string)$i->sortpages,
                                 'cphomepage'=>(string)$i->cphomepage,
                                 'animations'=>(string)$i->animations,
                                 'listall'=>(string)$i->listall,
                                 'userinfo'=>(string)$i->userinfo,
                                 'sidemenu'=>(string)$i->sidemenu,
                                 ];
                break;
            }
            
            $c++;
        }
        
        if (empty($account_info) && $id == $_SESSION['userID']) {
            session_destroy();
            header('Location:login.php?bye');
            exit;
        }
        
        else
            return $account_info;

    }
    



    # Save log
    function update_log($tag,$value) {
        
        $log_element = simplexml_object('log.xml','e',null);
        
        $log_element->info->$tag = $value;
        $log_element->info->modified = time();
        
        simplexml_object_save('log.xml',$log_element,null);

        return true;

    }


    
    
    # Save account info using userID and an action, from a POST method submitted form.
    function update_account($id,$action = 'set') {
        
        $logsave = simplexml_object('log.xml','e',null);
        
        $c=0;
        $upd = false;
        foreach($logsave->user as $user) {
                
            if ($user->userID == $id && $user->pshs != '-') {

                if ($action == 'delete') {

                    $logsave->user[$c]->name = (string)$logsave->user[$c]->name.'[deleted]';
                    $logsave->user[$c]->pshs = '-';
                    $logsave->user[$c]->rights = '-';
                    $logsave->user[$c]->icon = '-';
                    $logsave->user[$c]->description = '-';
                    $logsave->user[$c]->editorname = (string)$logsave->user[$c]->editorname.'[deleted]';
                    $logsave->user[$c]->created = '-';
                    $logsave->user[$c]->results->posts = '-';
                    $logsave->user[$c]->results->pages = '-';
                    $logsave->user[$c]->results->images = '-';
                    $logsave->user[$c]->texteditor = '-';
                    $logsave->user[$c]->theme = '-';
                    $logsave->user[$c]->status = 'del';
                    $logsave->user[$c]->sortposts = '-';
                    $logsave->user[$c]->sortpages = '-';
                    $logsave->user[$c]->cphomepage = '-';
                    $logsave->user[$c]->animations = '-';
                    $logsave->user[$c]->listall = '-';
                    $logsave->user[$c]->userinfo = '-';
                    $logsave->user[$c]->sidemenu = '-';


                    if ($_SESSION['userID'] == $id)
                        session_destroy();
                }

                if ($action == 'set') {

                    $values = array(['name' => 'username',
                                     'pshs' => 'password', # new value of POST['password']
                                     'rights' => 'accounttype',
                                     'editorname' => 'usereditorname',
                                     'created' => 'created',
                                     'urlicon' => 'urlicon',
                                     'texteditor' => 'texteditor',
                                     'theme' => 'theme',
                                     'cphomepage' => 'cphomepage',
                                     'animations' => 'animations',
                                     'listall' => 'listall',
                                     'userinfo'=>'userinfo',
                                     'sidemenu'=>'sidemenu'
                                    ],
                                    ['posts' => 'postsperpage',
                                     'pages' => 'pagesperpage',
                                     'images' => 'imgsperpage'
                                    ],
                                    ['icon' => 'usericon',
                                     'sortposts' => 'sortposts',
                                     'sortpages' => 'sortpages'
                                    ]
                                );

                    foreach($values[0] as $key => $val)
                            if (isset($_POST[$val]))
                                $user->$key = $_POST[$val];
                    
                    foreach($values[1] as $key => $val)
                        if (isset($_GET[$val]))
                            $user->results->$key = $_GET[$val];
                        
                    foreach($values[2] as $key => $val)
                        if (isset($_SESSION[$val]))
                                $user->$key = $_SESSION[$val];        
                        
                
                }

                simplexml_object_save('log.xml',$logsave,null);
                $upd = true;
                break;
            }
            $c++;
        }
        
        return $upd;
    }



    # Quickly edit your account by giving a tag name and a value
    function edit_useraccount($tag,$value) {
    
            $log = simplexml_object('log.xml','e',null);
            $c=0;
            foreach($log->user as $userval) {
                
                if ($userval->userID == $_SESSION['userID']) {
                    $log->user[$c]->$tag = $value;
                    simplexml_object_save('log.xml',$log,null);
                }
                
                $c++;
            }
            
        return $log;
    }


    

    # Load your own posts as a panel user, admin or author.
    function myPosts() {

        $myID = $_SESSION['userID'];
        $myp=[0];
    
        $asaves = simplexml_object('autosaves.xml','l','post');
        
        if (!is_array($asaves)) {
        
            foreach ($asaves->savedpost as $entry)
                if (strpos($entry->postinfo->post->file,'nu.xml') === false && $entry->postinfo->post->createdby == $myID) {
                    $myp[] = $entry;
                    $myp[0]++;
                }
        }
        
        
        else { 
            
            $directory = new DirectoryIterator('autosaves/');

            foreach($directory as $fileinfo) {

                if ($fileinfo->isFile()) {
                    $fname = $fileinfo->getFilename();

                    if (strpos($fname,'nu.xml') === false && strpos($fname,'.xml') !== false && $fname != 'autosaves.xml') {

                        $filexml = simplexml_object($fname,'l','post');
                        if ($filexml->postinfo->post->createdby == $myID) {
                            $myp[] = $fname;
                            $myp[0]++;

                        }
                    }
                }
            }
        }
        

        return $myp;
    }




    ## this is for older versions support only ##
    # Make a string or an array of a php date() valid format, from a string or an object($dates_custom)
    
    

    
    # Put multiple dates from xml into an array
    function phpdate($mydate) {

        $dates = array();        
        if (is_object($mydate))
            foreach($mydate as $format)
                $dates[] = $format;
        
        return($dates);
    }

    

    
    # format date for use in control panel, depending on dateform.xml
    function date_form($datestr) {

        $dif = time() - (int)$datestr;
        $day = 86400; # 1 day
        $a = simplexml_object('dateform.xml','l',null);
        
        # recent value is = < of 24h
        # old value is > of 24h
        
        $recent = (string)$a->dates->recent->dd;
        $old = (string)$a->dates->old->dd;
        
        
        if ($dif > $day)
            $date = date($old,$datestr);
        

        else {
            
            if (date('d') != date('d',$datestr))
                $date = date($old,$datestr);
            else                 
                $date = date($recent,$datestr);
        }
        
        
        return $date;
    
    }




    # Find errors in date format
    function dateval($date) {
        
        try {
        $datech = new DateTimeImmutable((string)$date);
         }
         
        catch (Exception $e) {
        
        if (DateTimeImmutable::getLastErrors() !== false)
            foreach(DateTimeImmutable::getLastErrors() as $key=>$val)
                if ($key == 'errors')
                    foreach($val as $v)
                        if ($v == 'Unexpected character')
                            echo 'old format found';
        }
    }




    # Show a notification to confirm a user action or report an error
    function action_confirm() {
        

        $lang_actions = ['newpost'=>'Post saved as published',
                        'errorpost'=>'You cannot edit this post',
                        'MONchanged_to_draft'=>'Post changed to draft',
                        'MONdeleted'=>'Post deleted',
                        'MONpostsdeleted'=>'Posts were deleted',
                        'MONno_postsdeleted'=>'No posts to delete',
                        'MON_editpost_not_exist'=>'Post was not found',
                        'MON_editpost_is_draft'=>'Post is already draft',
                        'settingsset'=>'Settings saved',
                        'settingssetuser'=>'Settings saved',
                        'panelset'=>'Saved',
                        'MONsystemcheck'=>'System check complete',
                        'MONimg_notuploaded'=>'Failed to upload file',
                        'MONimg_wrongtype'=>'A file type was incorrect',
                        'MONimg_upload_success'=>'File was uploaded',
                        'MONimg_upload_error'=>'Could not upload file',
                        'MONimg_upload_file_type'=>'File type is not supported',
                        'MONimg_removed'=>'File removed',
                        'MONimg_removed_failed'=>'Failed to delete file',
                        'MON_newcat'=>'Category created',
                        'MON_cat_invalid'=>'Category name was not valid. Please choose a different category name',
                        'MON_delcat'=>'Category deleted',
                        'MON_cat_notset'=>'Category or folder name is missing',
                        'MON_cat_exists'=>'Category name or folder already exists',
                        'MON_uncat_exists'=>'Category folder name already exists',
                        'MON_uncat_post_send_failed'=>'One or more posts could not be found',
                        'MON_uncat_post_fail_all'=>'Could not merge categories',
                        'MON_cat_update'=>'Category saved',
                        'MON_cat_falsexml'=>'An error was found',
                        'MON_cat_main_set'=>'Categories saved',
                        'MON_cat_maincat_saved'=>'Categories saved',
                        'MON_cat_files_error'=>'Could not create the category files',
                        'MON_catfolder_error'=>'Could not write in this folder',
                        'MON_get_is_array'=>'Category not found',
                        'MON_cat_not_found'=>'Category not found',
                        'MON_cat_xmlnotfound'=>'Could not save category - categories xml file is missing',
                        'ERROR:xmlpost'=>'Errors were found in post file',
                        'ERROR:Settings'=>'Settings file is corrupt',
                        'ERROR:maximagesize'=>'Max upload image size was not valid',
                        'ERROR:indexposts'=>'Results per page was not valid',
                        'ERROR:editorname'=>'Editor name was not valid',
                        'ERROR:cphome'=>'Control panel home page not found',
                        'ERROR:total'=>'Limit results must be an integer greater than or equal to 0',
                        'ERROR:exclimit'=>'Excerpt limit was not valid',
                        'ERROR::post_not_exist'=>'Post does not exist',
                        'account_username_not_valid'=>'Username must be between 3-70 characters',
                        'account_missing'=>'Account does not exist',
                        'account_modified'=>'Account saved',
                        'account_username_exists'=>'Username is already in use',
                        'account_created'=>'Account created',
                        'account_owner_del'=>'Cannot delete this account',
                        'account_deleted'=>'Account deleted',
                        'account_set_to_owner'=>'Account set to owner',
                        'account_cannot_set'=>'Could not set to owner',
                        'account_could_not_modify'=>'Could not edit account',
                        'owner_account_could_not_modify'=>'Cannot edit this account',
                        'user_enter'=>'MonoCMS was succesfully installed',
                        'User_logged_in'=>'Welcome, '.get_account($_SESSION['userID'])['editorname'],
                        'iconerror'=>'Error while uploading icon',
                        'iconfiletype'=>'File type was incorrect',
                        'pass_try_again'=>'Please try again',
                        'pass_match'=>'Passwords did not match',
                        'MONpagedeleted'=>'Page deleted',
                        'MONpagepublished_on'=>'Page has been published',
                        'MONpagepublished_hidden'=>'Page marked as unpublished',
                        'MON_page_not_exist'=>'Page does not exist'
                        ];
                        
                        
        foreach($lang_actions as $key=>$val) {
            if (isset($_SESSION[$key])) {
                print '<div id="action-confirm" onclick="this.style.display=\'none\'">
                    <div class="ac-con">'.$val.'<div class="closeicon"><b>&times;</b></div></div></div>';
                unset($_SESSION[$key]);
                break;
            }
        }
        
        return true;
    }




    # Results per page. $files should be one of 'posts', 'pages' or 'images'
    function pageResults($files,$link_param=null) {
        
        $get_num = simplexml_object('results_pages.xml','l',null);
        
        foreach($get_num->value as $val) { 
            if ($val == 0 || strlen($val) > 4)
                continue;
            $numbers[] = abs((int)$val);
        }
        
        $numbers = array_unique($numbers);
        
        $filetypes = ['posts'=>['results_posts','postsperpage'],
                      'pages'=>['results_pages','pagesperpage'],
                      'images'=>['results_images','imgsperpage']
                     ];
        
        $file_type = (string)$filetypes[$files][0];
        $file_type_param = $filetypes[$files][1];
        $account_results = get_account($_SESSION['userID'])[$file_type];
        
        print '<select id="presults" onchange="window.location=this.value">'.PHP_EOL.'<option value="#">'.$account_results.'</option>';
        
        $del = array_search($account_results,$numbers);
        if ($del !== false)
            unset($numbers[$del]);
        
        $link_param = $link_param != '' ? '?'.ltrim($link_param,'&').'&' : '?';
        foreach($numbers as $option)
            echo '<option value="res-set.php'.$link_param.$file_type_param.'='.$option.'">'.$option.'</option>';

        
        print PHP_EOL.'</select>';
        
        return true;

    }




    # Get number of pages, published unpublished status included
    function numberofpages() {
    
        if (file_exists('savedpages')) {
                
            $directory = new DirectoryIterator('savedpages/');
                    
            $s=$p=$u=0;
            $info=[];
            foreach ($directory as $fileinfo) {
                
                if ($fileinfo->isFile() && substr($fileinfo->getBasename(),-4) == '.xml' && $fileinfo->getSize() > 0) {
                
                    $name = $fileinfo->getBasename(); # file name
                    $pfile = (string)$sp->pageinfo->page->filename; # page name
                    $ppath = (string)$sp->pageinfo->page->path; # path
                    $sp = simplexml_object($name,'l','page');
                    $mtime = $sp->pageinfo->page->modified;
                    $pubstat = $sp->pageinfo->page->published;
                    if ($pubstat == 'hidden') 
                        $u=$u+1;
                    else 
                        $p=$p+1;
                    
                    
                    $ifile[] = $pfile;
                    $ipath[] = $ppath;
                    
                    $s++;
                }
            }
            return [$s,$p,$u,$ifile,$ipath];
        }
    
    }
    
    

    # Delete a post
    function delete_post($xmlfile) {
        
        
        
        $check_file = simplexml_object($xmlfile,'l','post');
        
        
        if (!is_array($check_file)) {
        
            $creator = $check_file->postinfo->post->createdby;
        
            # if file belongs to the author or user is an administrator
            if ($_SESSION['userID'] == $creator || get_account($_SESSION['userID'])['rights'] == 'administrator' && $creator != '') {
        

                $type = $check_file->postinfo->post->type;
                $filename = $check_file->postinfo->post->filename;
                $normalname = str_replace('nu.xml','.xml',$xmlfile);

                if (is_file('autosaves/'.$normalname)) {

                    $truename = simplexml_object($normalname,'l','post');
                    $filename = $truename->postinfo->post->filename;

                }

                $path = $check_file->postinfo->post->path;

                $xmlfile = str_replace(array('nu.xml','.xml'),'',$xmlfile);
                $files_to_del = ['autosaves/'.$xmlfile.'.xml',
                                 '../'.$path.$filename.'.php',
                                 'autosaves/'.$xmlfile.'nu.xml',
                                 'autosaves/content/'.$xmlfile.'.htm',
                                 'autosaves/content/'.$xmlfile.'nu.htm'
                                ];

                foreach ($files_to_del as $file)
                    if (is_file($file))
                        unlink($file);
                    
                
                
                # turbomode - autosaves.xml - 2.4
                $heavy = simplexml_object('autosaves.xml','e','post');
                    
                if (!is_array($heavy)) {
                    
                    $base = basename($xmlfile,'.xml');
                    
                    $c=0;
                    foreach($heavy->savedpost as $f) {

                        if ($f->postinfo->post->file == $base) {
                            $uns = $c;
                            continue;
                        }

                        if ($f->postinfo->post->file == $base.'nu') {    
                            $unsnu = $c;
                            break;
                        }

                        $c++;
                    }
                    
                    
                    # delete entries (outside loop)
                    if (isset($unsnu))
                        unset($heavy->savedpost[$unsnu]);
                    if (isset($uns))
                        unset($heavy->savedpost[$uns]);


                    simplexml_object_save('autosaves.xml',$heavy,'post');

                }

            return true;
            
            }
                
            else
                return false;
        
        }
        
        else {
            
            $_SESSION['MON_editpost_not_exist'] = true;
            return false;
        }
    }




    # Numbers only string. Integers greater than or equal to 0
    function numonly($value) {
        
        if ($value != '') {
            $num = [0,1,2,3,4,5,6,7,8,9];
            $rep = str_replace($num,'',$value);
        }
        
        if (isset($rep) && $rep == '')
            return true;    
        else 
            return false;

    }
    
    
    
    
    # Get merged categories
    function merged_categories() {
    
        
        $cats = simplexml_object('categories.xml','e',null);
        
        if (!is_array($cats)) {
            
            $ctgs = [];
            
            foreach($cats->children() as $key=>$val)
    
                if (!empty($val->merge->cat)) {                
                    $id = $val->merge->cat;
            
                    foreach($id as $v)
                        $ctgs[(string)$v] = (string)$val->cid; # merged => container
                }

            return $ctgs;
        
        }
        
        else 
            return false;


    }


?>