<?php

$cms["modules"]["pages.mod.php"] = array(
    "name"        => __( "pages_module_name" ),
    "description" => __( "pages_module_description" ),
    "files"       => array(
        ".cms/mod/pages.mod.php",
        ".cms/js/pages.js",
        ".cms/css/pages.css",
        ".cms/lang/ru_RU.UTF-8/pages.mod.php",
        ".cms/lang/en_US.UTF-8/pages.mod.php",
        ".cms/lang/uk_UA.UTF-8/pages.mod.php",
    ),
);

// Return if module disabled
if ( ! empty( $cms["config"]["pages.mod.php"]["disabled"] ) ) {

    return;

} else {
    
    if ( is_admin() ) {
        if ( empty( $_COOKIE["pages_pager"] ) ) {
            if ( PHP_VERSION_ID < 70300 ) {
                setcookie( "pages_pager", 100 );
            } else {
                setcookie( "pages_pager", 100, array( "SameSite" => "Lax" ) );
            }
        }
        
        hook_add_fn( "create_tables", "cms_pages_create_tables" );
        hook_add_fn( "admin", "cms_pages_admin" );
        hook_add_fn( "admin_header", "cms_pages_admin_header" );
        hook_add_fn( "api", "cms_pages_api" );
        hook_add_fn( "mod_menu_item", "cms_pages_menu_item" );
    }
    hook_add_fn( "query", "cms_pages_query" );
    hook_add_fn( "menu", "cms_pages_menu" );

}

function cms_pages_menu_item() {
    global $cms;
    if ( empty( $cms["menu.mod.php"]["item"]["found"] ) ) {
        $q = "SELECT id, title FROM pages WHERE id={$cms["menu.mod.php"]["item"]['id']}";
        if ( $res_page = mysqli_query( $cms["base"], $q ) ) {
            if ( $page = mysqli_fetch_assoc( $res_page ) ) {
                $cms["menu.mod.php"]["item"]["link_title"] = $page["title"];
                $cms["menu.mod.php"]["item"]["select_title"] = $page["title"];
                $cms["menu.mod.php"]["item"]["found"] = true;
            } else {
                $cms["menu.mod.php"]["item"]["link_title"] = __( "deleted_page" );
                $cms["menu.mod.php"]["item"]["select_title"] = __( "deleted_page" );
                $cms["menu.mod.php"]["item"]["found"] = false;
            }
        }
    }
}
    
function cms_pages_admin_header() {
    global $cms;
    $hide = true;
    foreach ( $cms["config"]["pages.mod.php"]["menu"] as $menu ) {
        $hide = $hide && ( ! empty( $menu["hide"] ) || ! empty( $cms["config"]["admin_sections"][ $menu["section"] ]["hide"] ) );
    }
    if ( ! $hide ) {
    echo "<link rel=stylesheet href='{$cms['base_path']}css/pages.css'>";
    echo "<link rel=stylesheet href='{$cms['base_path']}lib/codemirror/lib/codemirror.css'>";
    echo "<link rel=stylesheet href='{$cms['base_path']}lib/codemirror/addon/hint/show-hint.css'>";
    echo "<link rel=stylesheet href='{$cms['base_path']}lib/codemirror/addon/dialog/dialog.css'>";
    echo "<script src='{$cms['base_path']}lib/codemirror/lib/codemirror.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/hint/show-hint.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/hint/xml-hint.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/hint/html-hint.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/hint/javascript-hint.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/hint/anyword-hint.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/hint/css-hint.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/selection/active-line.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/search/search.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/search/searchcursor.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/search/jump-to-line.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/dialog/dialog.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/edit/matchbrackets.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/edit/matchtags.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/edit/closebrackets.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/edit/closetag.js'></script>";
    #region folding
    echo "<link rel=stylesheet href='{$cms['base_path']}lib/codemirror/addon/fold/foldgutter.css'>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/fold/foldcode.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/fold/foldgutter.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/fold/brace-fold.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/fold/xml-fold.js'></script>";
    //echo "<script src='{$cms['base_path']}lib/codemirror/addon/fold/indent-fold.js'></script>";
    //echo "<script src='{$cms['base_path']}lib/codemirror/addon/fold/markdown-fold.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/addon/fold/comment-fold.js'></script>";
    #endregion
    echo "<script src='{$cms['base_path']}lib/codemirror/mode/htmlmixed/htmlmixed.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/mode/xml/xml.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/mode/javascript/javascript.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/mode/css/css.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/mode/clike/clike.js'></script>";
    echo "<script src='{$cms['base_path']}lib/codemirror/mode/php/php.js'></script>";
    echo "<script src='{$cms['base_path']}js/pages.js'></script>";
    }
}


function cms_pages_api() {
    global $cms;
    
    if ( ! empty( $_POST["fn"] ) ) {
        
        switch ( $_POST["fn"] ) {

            case "create_page":
                
                // Read template settings
                cms_template_load_settings();

                $tpl = "page";
                
                // Default text for new page from template
                if ( ! empty( $cms["templates"][ $cms["template"] ]["page_templates"][$tpl] ) ) {
                    $text = mysqli_real_escape_string( $cms["base"], $cms["templates"][ $cms["template"] ]["page_templates"][$tpl] );
                } else {
                    $text = "";
                }
                
                $modified = number_format( microtime( true ), 6, ".", "" );
                //$modified = 0; // Это позволит исключить новые страницы из RSS, но сортировка страниц в админке по этому полю
                $created = date( "Y-m-d H:i:s", $modified );
                
                $q = "INSERT INTO pages SET created='{$created}', modified='{$modified}', tpl='{$tpl}', text='{$text}'";
                if ( $r = mysqli_query( $cms["base"], $q ) ) {
                    $id = mysqli_insert_id( $cms["base"] );
                } else {
                    echo( json_encode( array(
                        "info_text"  => __( "error_creating_page" ) . mysqli_error( $cms["base"] ),
                        "info_class" => "info-error",
                        "info_time"  => 5000,
                    ) ) );
                    return;
                }

                // Create title, url and update in database
                $title     = __( "page_default_title" );
                $url       = "{$id}";
                
                // Если страница одна, то сделать ее главной
                $q = "SELECT COUNT(*) FROM pages";
                $r = mysqli_query( $cms["base"], $q );
                $c = mysqli_fetch_assoc( $r )["COUNT(*)"];
                if ( $c == 1 ) {
                    $url = "";
                    $title = __( "home_page" );
                }
                
                $q = "UPDATE pages SET title='{$title}', url='{$url}' WHERE id={$id}";
                if ( $r = mysqli_query( $cms["base"], $q ) ) {
                    $_POST["where"] = "id={$id}";
                    $r = cms_pages_get_pages_list();
                    $r = array_merge( $r,
                        array(
                            "info_text"  => __( "page_created" ),
                            "info_class" => "info-success",
                            "info_time"  => 5000,
                        )
                    );
                    echo( json_encode( $r ) );
                    return;
                } else {
                    echo( json_encode( array(
                        "info_text"  => __( "error_creating_page" ) . mysqli_error( $cms["base"] ),
                        "info_class" => "info-error",
                        "info_time"  => 5000,
                    ) ) );
                    return;
                }
            break;

            case "save_prop":

                $_POST["url"] = trim( $_POST["url"] );
                if ( substr( $_POST["url"], 0, 1 ) === "/" ) {
                    $_POST["url"]  = substr( $_POST["url"], 1 );
                }

                // Read template settings
                cms_template_load_settings();
                
                $id          = (int) $_POST["id"];
                $title       = mysqli_real_escape_string( $cms["base"], $_POST["title"] );
                $seo_title   = mysqli_real_escape_string( $cms["base"], $_POST["seo_title"] );
                $description = mysqli_real_escape_string( $cms["base"], $_POST["description"] );
                $tags        = mysqli_real_escape_string( $cms["base"], $_POST["tags"] );

                // get page text
                $q    = "SELECT `text` FROM `pages` WHERE `id`={$id}";
                $r    = mysqli_query( $cms["base"], $q );
                $row  = mysqli_fetch_assoc( $r );
                $text = $row["text"];

                $update_text = "";
                // Default text for old_template
                if ( ! empty( $cms["templates"][ $cms["template"] ]["page_templates"][ $_POST["old_template"] ] ) ) {
                    $text2 = $cms["templates"][ $cms["template"] ]["page_templates"][ $_POST["old_template"] ];
                } else {
                    $text2 = "";
                }

                // Change template text
                if ( $_POST["old_template"] !== $_POST["template"] and $text === $text2 ) {
                    // Default text for template
                    if ( ! empty( $cms["templates"][ $cms["template"] ]["page_templates"][ $_POST["template"] ] ) ) {
                        $text = mysqli_real_escape_string( $cms["base"], $cms["templates"][ $cms["template"] ]["page_templates"][ $_POST["template"] ] );
                        $update_text = ", `text`='{$text}'";
                    }
                }

                $esc_url = mysqli_real_escape_string( $cms["base"], $_POST["url"] );

                // Check dupl
                if ( $r = mysqli_query( $cms["base"], "SELECT COUNT(*) FROM `pages` WHERE `url`='{$esc_url}' AND `id`<>{$id}" ) ) {
                    if ( $cnt = mysqli_fetch_assoc( $r ) ) {
                        if ( $cnt["COUNT(*)"] > 0 ) {
                            $_POST["url"] = cms_admin_pass_gen();
                            $esc_url = mysqli_real_escape_string( $cms["base"], $_POST["url"] );
                        }
                    }
                }

                if ( empty( $_POST["date"] ) ) { $_POST["date"] = "0000-00-00"; }
                if ( empty( $_POST["time"] ) ) { $_POST["time"] = "00:00"; }
                $created = mysqli_real_escape_string( $cms["base"], $_POST["date"] . " " . $_POST["time"] . ":00" );
                $tpl = mysqli_real_escape_string( $cms["base"], $_POST["template"] );
                $modified = str_replace( ",", ".", microtime( true ) );
                $q = "UPDATE `pages` SET 
                        `title`='{$title}', 
                        `seo_title`='{$seo_title}', 
                        `description`='{$description}', 
                        `tags`='{$tags}', 
                        `created`='{$created}',
                        `modified`='{$modified}',
                        `tpl`='{$tpl}', 
                        `url`='{$esc_url}'
                        {$update_text}
                      WHERE id={$id}";

                // clear cache before change url
                if ( function_exists( "cms_clear_cache" ) ) {
                    cms_clear_cache();
                }
                if ( $r = mysqli_query( $cms["base"], $q ) ) {
                    if ( strtotime( $created ) > time() ) {
                        $planned = true;
                    } else {
                        $planned = false;
                    }
                    $time = strtotime( $created );
                    $created = date( "d.m.Y", $time )."<br>".date( "H:i", $time );
                    $r = array(
                        "info_text"  => __( "updated" ),
                        "info_class" => "info-success",
                        "info_time"  => 1000,
                        "title"      => htmlspecialchars( $_POST["title"] ),
                        "url"        => $_POST["url"],
                        "base_path"   => $cms["base_path"],
                        "created"    => $created,
                        "planned"    => $planned,
                        "ok"         => "true",
                    );
                    if ( function_exists( "cms_sitemap_update" ) ) {
                        cms_sitemap_update();
                    }
                    if ( function_exists( "cms_rss_update" ) ) {
                        cms_rss_update();
                    }

                    // Если страница задействована в меню, то нужно сообщить,
                    // что требуется перезагрузить страницу меню
                    $q = "SELECT * FROM `menu` WHERE `id`={$id}";
                    if ( mysqli_query( $cms["base"], $q ) and mysqli_affected_rows( $cms["base"] ) ) {
                        $r["update_menu"] = "true";
                    } else {
                        $r["update_menu"] = "false";
                    }

                    echo( json_encode( $r ) );
                    return;
                }
            break;

            case "save_page":

                $_POST["url"] = trim( $_POST["url"] );
                if ( substr( $_POST["url"], 0, 1 ) === "/" && strlen( $_POST["url"] ) > 1 ) {
                    $_POST["url"]  = substr( $_POST["url"], 1 );
                }

                // Read template settings
                cms_template_load_settings();
                
                // hook for save page
                do_hook( "save_page" );
                
                $id           = (int) $_POST["id"];
                $old_modified = mysqli_real_escape_string( $cms["base"], $_POST["modified"] );
                $modified     = number_format( microtime( true ), 6, ".", "" );
                $text         = mysqli_real_escape_string( $cms["base"], $_POST["text"] );

                // Default text for old_template
                if ( ! empty( $cms["templates"][ $cms["template"] ]["page_templates"][ $_POST["old_template"] ] ) ) {
                    $text2 = mysqli_real_escape_string( $cms["base"], $cms["templates"][ $cms["template"] ]["page_templates"][ $_POST["old_template"] ] );
                } else {
                    $text2 = "";
                }

                // Change template text
                $new_text = "";
                if ( $_POST["old_template"] !== $_POST["template"] and $text === $text2 ) {
                    // Default text for template
                    if ( ! empty( $cms["templates"][ $cms["template"] ]["page_templates"][ $_POST["template"] ] ) ) {
                        $new_text = $cms["templates"][ $cms["template"] ]["page_templates"][ $_POST["template"] ];
                        $text = mysqli_real_escape_string( $cms["base"], $new_text );
                    }
                }


                $title       = mysqli_real_escape_string( $cms["base"], $_POST["title"] );
                $seo_title   = mysqli_real_escape_string( $cms["base"], $_POST["seo_title"] );
                $description = mysqli_real_escape_string( $cms["base"], $_POST["description"] );
                $tags        = mysqli_real_escape_string( $cms["base"], $_POST["tags"] );

                
                $esc_url = mysqli_real_escape_string( $cms["base"], $_POST["url"] );

                // Check dupl
                if ( $r = mysqli_query( $cms["base"], "SELECT COUNT(*) FROM `pages` WHERE `url`='{$esc_url}' AND `id`<>{$id}" ) ) {
                    if ( $cnt = mysqli_fetch_assoc( $r ) ) {
                        if ( $cnt["COUNT(*)"] > 0 ) {
                            $_POST["url"] = cms_admin_pass_gen();
                            $esc_url = mysqli_real_escape_string( $cms["base"], $_POST["url"] );
                        }
                    }
                }

                if ( empty( $_POST["date"] ) ) { $_POST["date"] = "0000-00-00"; }
                if ( empty( $_POST["time"] ) ) { $_POST["time"] = "00:00"; }
                $created = mysqli_real_escape_string( $cms["base"], $_POST["date"] . " " . $_POST["time"] . ":00" );
                $tpl = mysqli_real_escape_string( $cms["base"], $_POST["template"] );

                $q = "UPDATE pages SET 
                        text='{$text}', 
                        modified={$modified},
                        title='{$title}', 
                        seo_title='{$seo_title}', 
                        description='{$description}',
                        tags='{$tags}',
                        created='{$created}',
                        tpl='{$tpl}', 
                        url='{$esc_url}'
                      WHERE id={$id} AND modified={$old_modified}";
                
                // clear cache before change url
                if ( function_exists( "cms_clear_cache" ) ) {
                    cms_clear_cache();
                }

                if ( mysqli_query( $cms["base"], $q ) ) {
                    
                    if ( ! mysqli_affected_rows( $cms["base"] ) ) {
                        echo( json_encode( array(
                            "ok"        => "false",
                            "info_text" => __( "page_changed" ),
                            "info_class" => "info-error",
                            "info_time"  => 5000,
                        ) ) );
                        return;
                    }

                    // update sitemap and rss
                    if ( function_exists( "cms_sitemap_update" ) ) {
                        cms_sitemap_update();
                    }
                    if ( function_exists( "cms_rss_update" ) ) {
                        cms_rss_update();
                    }

                    if ( strtotime( $created ) > time() ) {
                        $planned = true;
                    } else {
                        $planned = false;
                    }

                    echo( json_encode( array(
                        "ok"          => "true",
                        "info_text"   => __( "saved" ),
                        "info_class"  => "info-success",
                        "info_time"   => 5000,
                        "modified"    => $modified,
                        "planned"     => $planned,
                        "title"       => htmlspecialchars( $_POST["title"] ),
                        "url"         => $_POST["url"],
                        "base_path"   => $cms["base_path"],
                        "new_text"    => $new_text,
                    ) ) );
                    return;
                } else {
                    echo( json_encode( array(
                        "ok"         => "false",
                        "info_text"  => mysqli_error( $cms["base"] ),
                        "info_class" => "info-error",
                        "info_time"  => 5000,
                    ) ) );
                    return;
                }
            break;

            case "page_pin":
                $id  = (int) $_POST['id'];
                $pin = (int) $_POST['pin'];
                $q   = "UPDATE `pages` SET `pin`={$pin} WHERE `id`={$id}";
                if ( $res = mysqli_query( $cms["base"], $q ) ) {
                    echo( json_encode( array(
                        "ok" => "true",
                    ) ) );
                    return;
                }
            break;
            
            case "page_publish":
                $id        = (int) $_POST['id'];
                $published = (int) $_POST['published'];
                $q         = "UPDATE `pages` SET `published`={$published} WHERE `id`={$id}";
                if ( $res = mysqli_query( $cms["base"], $q ) ) {
                    echo( json_encode( array(
                        "ok" => "true",
                    ) ) );
                    return;
                }
            break;

            case "get_page":
                if ( $id = (int) $_POST['id'] and $res = mysqli_query( $cms["base"], "SELECT * FROM `pages` WHERE `id`={$id}" ) ) {
                    if ( $page = mysqli_fetch_assoc( $res ) ) {

                        // date and time
                        $date = date( "Y-m-d", strtotime( $page["created"] ) );
                        $time = date( "H:i", strtotime( $page["created"] ) );

                        // template
                        $templates_list = array();
                        $expr = "{$cms['cms_dir']}/{$cms['config']['template.mod.php']['template']}/*.php";
                        foreach ( glob( $expr ) as $tpl ) {
                            $name = preg_replace( "/.*\/([^\/]+)\.php/u", "$1", $tpl );
                            if ( $name !== "html" && strpos( $name, "." ) === false ) {
                                array_push( $templates_list, $name );
                            }
                        }

                        cms_template_load_settings();
                        $current_template = $cms["config"]["template.mod.php"]["template"];

                        $template_options = "";
                        foreach( $templates_list as $tpl ) {
                            if ( $tpl !== $page['tpl'] ) {
                                $template_options .= "<div class=option value='{$tpl}'>" . __( $tpl, $current_template ) . "</div>";
                            }
                        }
                        // Добавляем текущий подшаблон страницы в список если его там нет.
                        // Такое может быть если переключен главный шаблон.
                        if ( ! in_array( $page['tpl'], $templates_list ) && ! empty( $page['tpl'] ) ) {
                            $template_options .= "<div class=option value='{$page['tpl']}'>" . __( $page['tpl'], $current_template ) . "</div>";
                        }

                        
                        // files
                        $farr = array();
                        foreach ( glob( "{$cms['site_dir']}/uploads/{$page['id']}/*", GLOB_NOSORT ) as $path ) {
                            if ( is_file( $path ) ) {
                                $farr[] = array( "path" => $path, "sort" => filemtime( $path ) );
                            }
                        }
                        cms_asort( $farr );

                        $flist = "";
                        foreach ( $farr as $f ) {
                            // cut path
                            $path_name = str_replace( $_SERVER["DOCUMENT_ROOT"], "", $f["path"] );
                            //$rel_path_name = str_replace( $cms['site_dir'], "$", $f["path"] );
                            $name      = preg_replace( "/.*\//u", "", $path_name );
                            $ext       = strtolower( preg_replace( "/.*\./u", ".", $path_name ) ); // .jpg
                            // icon file
                            if ( file_exists( "{$cms['cms_dir']}/img/icon{$ext}.svg" ) ) {
                                $icon = "{$cms['base_path']}img/icon{$ext}.svg";
                            } else {
                                $icon = "{$cms['base_path']}img/icon.default.svg";
                            }
                            // no need icon for image
                            switch ( $ext ) {
                                case ".webp":
                                case ".tiff":
                                case ".jpeg":
                                case ".jpg":
                                case ".png":
                                case ".svg":
                                case ".gif":
                                case ".bmp":
                                case ".ico":
                                    $size = getimagesize( $f["path"] );
                                    if ( ! empty( $size[3] ) ) {
                                        $size = $size[3];
                                    } else {
                                        $size = "";
                                    }
                                    // $upd = time();
                                    // ?upd={$upd}
                                    $flist = "<div class=file-block><div class=media-name>{$name}</div><img src='{$path_name}' data-src='{$path_name}' {$size}><input type=checkbox><div class=ext>{$ext}</div></div>{$flist}";
                                break;
                                
                                default:
                                    $flist = "<div class=file-block><div class=media-name>{$name}</div><img src='{$icon}' data-src='{$path_name}'><input type=checkbox><div class=ext>{$ext}</div></div>{$flist}";
                                break;
                            }
                        }
                        echo( json_encode( array(
                            "result"    => "ok",
                            "page"      => $page,
                            "base_path" => $cms["base_path"],
                            "flist"     => $flist,
                            "date"      => $date,
                            "time"      => $time,
                            "options"   => $template_options,
                            "option"    => $page['tpl'],
                            "option_tr" => __( $page['tpl'], $current_template ),
                        ) ) );
                        return;
                    }
                }
            break;

            case "del_files":
                foreach ( $_POST["flist"] as $path_name ) {
                    $f = "{$cms['site_dir']}/{$path_name}";
                    if ( is_file( $f ) ) {
                        unlink( $f );
                    }
                }
                $dir = dirname( $f );
                if ( is_dir_and_empty( $dir ) ) {
                    rmdir( $dir );
                }
                echo( json_encode( array(
                    "info_text"  => __( "files_deleted" ),
                    "info_class" => "info-success",
                    "info_time"  => 5000,
                ) ) );
                return;
            break;

            case "get_pages_list":
                echo( json_encode( cms_pages_get_pages_list() ) );
                return;
            break;

            case "del_pages":
                // Clear cache
                if ( function_exists( "cms_clear_cache" ) ) {
                    cms_clear_cache();
                }
                foreach( $_POST["ids"] as $id ) {
                    if ( $id = (int) $id ) {

                        // Delete page from base
                        mysqli_query( $cms["base"], "DELETE FROM `pages` WHERE `id`={$id}" );

                        // Delete page files
                        foreach ( glob( "{$cms['site_dir']}/uploads/{$id}/*", GLOB_NOSORT ) as $f ) {
                            if ( is_file( $f ) ) {
                                unlink( $f );
                            }
                        }
                        
                        if ( isset( $f ) ) {
                            $dir = dirname( $f );
                            if ( is_dir_and_empty( $dir ) ) {
                                rmdir( $dir );
                            }
                        }

                    }
                }

                // update sitemap and rss
                if ( function_exists( "cms_sitemap_update" ) ) {
                    cms_sitemap_update();
                }
                if ( function_exists( "cms_rss_update" ) ) {
                    cms_rss_update();
                }

                // Если страницы задействованы в меню, то нужно сообщить,
                // что требуется перезагрузить страницу меню
                $q = "SELECT * FROM `menu` WHERE `id` IN ( " . implode( ",", $_POST["ids"] ) . " )";
                if ( mysqli_query( $cms["base"], $q ) and mysqli_affected_rows( $cms["base"] ) ) {
                    $update_menu = "true";
                } else {
                    $update_menu = "false";
                }

                echo( json_encode( array(
                    "info_text"   => __( "pages_deleted" ),
                    "info_class"  => "info-success",
                    "info_time"   => 5000,
                    "update_menu" => $update_menu,
                ) ) );
                return;
            break;

            case "upload_files":
                $id   = (int) $_POST["id"];
                $path = "{$cms['base_path']}uploads/{$id}";
                $dir  = $_SERVER["DOCUMENT_ROOT"] . $path;
                // create dir if not exists
                if ( ! is_dir( $dir ) && ! mkdir( $dir, 0777, true ) ) {
                    echo( json_encode( array(
                        "info_text"  => __( "error_create_folder" ) . " " . $dir,
                        "info_class" => "info-error",
                        "info_time"  => 5000,
                    ) ) );
                    return;
                }
                $flist = "";
                $success = true;
                foreach ( $_FILES["myfile"]["name"] as $n => $name ) {
                    if ( $_FILES["myfile"]["error"][$n] ) {
                        $success = false;
                        $text = __( "error_upload_file" ) . " \"{$name}\"";
                        break;
                    }
                    // Транслит
                    $ext  = strtolower( preg_replace( "/.*\./u", ".", $name ) );
                    $name = substr( $name, 0, strlen( $name ) - strlen( $ext ) );
                    $name = strtolower( cms_translit_file( $name ) );
                    $name = "{$name}{$ext}";
                    // Перемещение с заменой. Проверка на одинаковость и предупреждение об этом сделано на js
                    if ( ! move_uploaded_file( $_FILES["myfile"]["tmp_name"][$n], "{$dir}/{$name}" ) ) {
                        $success = false;
                        $text = __( "file_move_error" ) . " \"{$dir}/{$name}\"";
                        break;
                    }
                    if ( file_exists( "{$cms['cms_dir']}/img/icon{$ext}.svg" ) ) {
                        $icon = "{$cms['base_path']}img/icon{$ext}.svg";
                    } else {
                        $icon = "{$cms['base_path']}img/icon.default.svg";
                    }
                    if ( $success ) {
                        switch ( $ext ) {
                            case ".webp":
                            case ".tiff":
                            case ".jpeg":
                            case ".jpg":
                            case ".png":
                            case ".svg":
                            case ".gif":
                            case ".bmp":
                            case ".ico":
                                $size = getimagesize( "{$cms['site_dir']}{$path}/{$name}" );
                                if ( ! empty( $size[3] ) ) {
                                    $size = $size[3];
                                } else {
                                    $size = "";
                                }
                                $upd = time();
                                $flist .= "<div class='file-block'><div class=media-name>{$name}</div><img src='{$path}/{$name}?upd={$upd}' data-src='{$path}/{$name}' {$size}><input type=checkbox><div class=ext>{$ext}</div></div>";
                            break;
                            
                            default:
                                $flist .= "<div class='file-block'><div class=media-name>{$name}</div><img src='{$icon}' data-src='{$path}/{$name}'><input type=checkbox><div class=ext>{$ext}</div></div>";
                            break;
                        }
                        
                    }
                }

                if ( $success ) {
                    $text = __( "files_uploaded" );
                    echo( json_encode( array(
                        "info_text"  => $text,
                        "info_class" => "info-success",
                        "info_time"  => 5000,
                        "flist"      => $flist,
                    ) ) );
                    return;
                } else {
                    echo( json_encode( array(
                        "info_text"  => $text,
                        "info_class" => "info-error",
                        "info_time"  => 5000,
                    ) ) );
                    return;
                }
            break;

            case "replace_in_pages":
                $table  = mysqli_real_escape_string( $cms["base"], $_POST["table"] );
                $id_col = mysqli_real_escape_string( $cms["base"], $_POST["id_col"] );
                $column = mysqli_real_escape_string( $cms["base"], $_POST["column"] );
                $q = "SELECT `{$id_col}`, `{$column}` FROM `{$table}`";
                if ( ! empty( trim( $_POST["search_regex"] ) ) ) {
                    if ( $res = mysqli_query( $cms["base"], $q ) ) {
                        $regex = preg_replace( "/\//u", "\\/", $_POST["search_regex"] ); // Escape / for regexp
                        while( $page = mysqli_fetch_assoc( $res ) ) {
                            $new_text = preg_replace( "/{$regex}/u", $_POST["replace"], $page[$_POST["column"]] );
                            $text = mysqli_real_escape_string( $cms["base"], $new_text );
                            $id_val = $page[$_POST["id_col"]];
                            $q = "UPDATE `{$table}` SET `{$column}`='{$text}' WHERE `{$id_col}`='{$id_val}'";
                            mysqli_query( $cms["base"], $q );
                        }
                    }
                }

                echo( json_encode( array(
                    "info_text"  => __( "replace_ok" ),
                    "info_class" => "info-success",
                    "info_time"  => 5000,
                ) ) );
                return;
            break;
        }
    }
}

// Create pages list
// $_POST["where"] = "id=123"; нужно для момента создания страницы
// $_POST["count"] = "1000";
// $_POST["search"] = "test";
// $_COOKIE["pages_pager"] = 10;
function cms_pages_get_pages_list() {
    global $cms;

    if ( empty( $cms["base"] ) ) {
        return array(
            "no_database"  => "<span class=no-database>" . __( "no_connect_db" ) . "</span>",
        );
    }
    
    $templates_list = array();
    $expr = "{$cms['cms_dir']}/{$cms['config']['template.mod.php']['template']}/*.php";
    foreach ( glob( $expr ) as $tpl ) {
        $name = preg_replace( "/.*\/([^\/]+)\.php/u", "$1", $tpl );
        if ( $name !== "html" && strpos( $name, "." ) === false ) {
            array_push( $templates_list, $name );
        }
    }

    if ( ! empty( $_POST["where"] ) ) {
        $where = $_POST["where"];
    } else {
        $where = "1";
    }

    if ( empty( $_COOKIE["pages_pager"] ) ) {
        $pager = 100;
    } else {
        $pager = (int) $_COOKIE["pages_pager"];
    }

    if ( empty( $_POST["offset"] ) ) {
        $_POST["offset"] = 0;
    }
    $offset = $_POST["offset"];

    if ( ! empty( $_POST["count"] ) ) {
        $pager = $_POST["count"];
    }
    $limit = "LIMIT {$offset}, {$pager}";

    if ( ! empty( $_POST["search"] ) ) {
        /* не получается с MULTILINE в MariaDB 10.3.39
        if ( $_POST["Ctrl"] === "true" && $_POST["Shift"] === "true" && $_POST["Alt"] === "true" ) {
            mysqli_query( $cms["base"], "SET default_regex_flags='MULTILINE'" );
            $s = mysqli_real_escape_string( $cms["base"], $_POST["search"] );
            $search = "( text REGEXP '{$s}' )";
            $q_count = "SELECT COUNT(*) FROM `pages` WHERE {$search}";
        } else 
        */
        if ( $_POST["Ctrl"] === "true" && $_POST["Shift"] === "true" ) {
            $s = mysqli_real_escape_string( $cms["base"], $_POST["search"] );
            $search = "( text REGEXP '{$s}' )";
            $q_count = "SELECT COUNT(*) FROM `pages` WHERE {$search}";
        } else if ( $_POST["Ctrl"] === "true" ) {
            $s = mysqli_real_escape_string( $cms["base"], $_POST["search"] );
            $search = "( text LIKE '%{$s}%' )";
            $q_count = "SELECT COUNT(*) FROM `pages` WHERE {$search}";
        } else {
            $s = preg_replace( "/\s/u", "", $_POST["search"] );
            $s = preg_split( '//u', $s, -1, PREG_SPLIT_NO_EMPTY );
            foreach( $s as $n => $ch ) {
                $s[$n] = mysqli_real_escape_string( $cms["base"], $ch );
            }
            $s = implode( "%", $s );
            $search = "( title LIKE '%{$s}%' OR url LIKE '%{$s}%' OR tpl LIKE '%{$s}%' OR tags LIKE '%{$s}%' )";
            $q_count = "SELECT COUNT(*) FROM `pages` WHERE {$search}";
        }
    } else {
        $search = "1";
        $q_count = "SELECT COUNT(*) FROM `pages`";
    }
    // count pages
    if ( ! $res = mysqli_query( $cms["base"], $q_count ) ) {
        return array(
            "no_database"  => "<span class=no-tables>" . __( "no_tables_db" ) . "</span>",
        );
    }
    $res = mysqli_fetch_assoc( $res );
    $count = $res["COUNT(*)"];

    $pages = array();
    $start = microtime( true );
    $overload = false;
    $q = "SELECT `id`, `published`, `pin`, `title`, `seo_title`, `description`, `created`, `url`, `tpl`, `tags`, `modified` FROM `pages` WHERE {$search} AND {$where} ORDER BY `pin` DESC, FROM_UNIXTIME( `modified` ) DESC {$limit}";
    
    if ( $res = mysqli_query( $cms["base"], $q ) ) {

        $tTitle           = __( "title" );
        $tDescription     = __( "description" );
        $tSeoTitle        = __( "seo_title" );
        $tTemplate        = __( "template" );
        $tPublished       = __( "published" );
        $tUnPublished     = __( "unpublished" );
        $tDate            = __( "date" );
        $tTime            = __( "time" );
        $tSave            = __( "save" );
        $tProperties      = __( "properties" );
        $tEdit            = __( "edit" );

        cms_template_load_settings();
        $current_template = $cms["config"]["template.mod.php"]["template"];
        
        while ( $page = mysqli_fetch_assoc( $res ) ) {
            
            $time = strtotime( $page["created"] );
            if ( time() >= $time ) {
                $date_class     = "past";
            } else {
                $date_class     = "future";
            }
            $created = date( "d.m.Y", $time ) . "<br>" . date( "H:i", $time );
            $date    = date( "Y-m-d", $time );
            $time    = date( "H:i", $time );

            $template_options = "";
            foreach( $templates_list as $tpl ) {
                if ( $tpl !== $page['tpl'] ) {
                    $template_options .= "<div class=option value='{$tpl}'>" . __( $tpl, $current_template ) . "</div>";
                }
            }
            // Добавляем текущий подшаблон страницы в список если его там нет.
            // Такое может быть если переключен главный шаблон.
            if ( ! in_array( $page['tpl'], $templates_list ) && ! empty( $page['tpl'] ) ) {
                $template_options .= "<div class=option value='{$page['tpl']}'>" . __( $page['tpl'], $current_template ) . "</div>";
            }

            if ( $page["published"] ) {
                $tpub = $tPublished;
            } else {
                $tpub = $tUnPublished;
            }

            if ( $page["url"] == "" ) {
                $class = "class=home";
            } else {
                $class = "";
            }

            if ( empty( $page["tpl"] ) ) {
                $tpl_translated = __( "no_template" );
            } else {
                $tpl_translated = __( $page['tpl'], $current_template );
            }

            $html = "
<div {$class} data-id={$page['id']} data-pin={$page['pin']} data-published={$page['published']}>

    <a class=page-name href='{$cms['base_path']}{$page["url"]}' target=_blank title='id={$page['id']}'>{$page['title']}</a>
    <div class=pin></div>
    <div class=published title='{$tpub}'></div>
    <div class=page-buttons>
        <div class=page-edit-btn>{$tEdit}</div>
        <div class=page-prop-btn>{$tProperties}</div>
        <div class=page-prop-save-btn>{$tSave}</div>
    </div>
    <div class='page-date {$date_class}'>{$created}</div>
    <input type=checkbox>
    
    <div class=page-prop>

        <div class='page title'>{$tTitle}:</div>
        <input name=title type=text value='{$page['title']}'>

        <div class='url title'>URL:</div>
        <div class=url-input>
            <input name=url type=text value='{$page['url']}' placeholder='" . __( "front_url" ) . "'>
            <div class=url-translit title='" . __( "url_translit" ) . "'></div>
        </div>

        <div class='seo title'>{$tSeoTitle}:</div>
        <input name=seo_title type=text value='{$page['seo_title']}'>

        <div class='description title'>{$tDescription}:</div>
        <textarea name=description rows=3>{$page['description']}</textarea>

        <div class='template title'>{$tTemplate}:</div>
        <div class=template-select-grid>
            <div class=field-select data-template='{$page['tpl']}' data-old-template='{$page['tpl']}'>
                <div class=value>{$tpl_translated}</div>
                <div class=icon></div>
            </div>
            <div class=field-options>
                {$template_options}
            </div>
        </div>

        <div class='date title'>{$tDate}:</div>
        <input name=date type=date value='{$date}'>
        <div class='time title'>{$tTime}:</div>
        <input name=time type=time value='{$time}'>

        <div class='tags title'>" . __( "tags" ) . ":</div>
        <textarea name=tags rows=3>" . htmlspecialchars( $page["tags"] ) . "</textarea>

    </div>

</div>";
            array_push( $pages, array( "id" => (int) $page["id"], "html" => $html ) );
            if ( microtime( true ) - $start > 1 ) {
                $overload = true;
                break;
            }
        }
    }
    if ( isset( $_POST["search"] ) ) {
        $search = trim( $_POST["search"] );
    } else {
        $search = "";
    }
    /* Срабатывает когда не нужно. При удалении страниц пугает.
    if ( count( $pages ) === 0 ) {
        return array(
            "no_database"  => "<span class=no-database>" . __( "add_page_hint" ) . "</span>",
        );
    }
    */
    return array(
        "pages"    => $pages, 
        "offset"   => $_POST["offset"], 
        "count"    => $count, 
        "overload" => $overload,
        "search"   => $search,
    );
}


function cms_pages_query() {
    global $cms;
    
    // Skip SQL query if file exists
    if ( is_file( $cms["cms_file"] ) ) {
        return;
    }
    
    // fix template warnings
    $cms["page"]["id"] = 0;
    $cms["page"]["tpl"] = "";
    
    if ( empty( $cms["base"] ) ) return; // fix 500 error
    $url = mysqli_real_escape_string( $cms["base"], $cms["url"]["path"] );
    if ( $res = mysqli_query( $cms["base"], "SELECT * FROM pages WHERE url = '{$url}' OR CONCAT( url, '/' ) = '{$url}' OR url = CONCAT( '{$url}', '/' )" ) ) {
        if ( $page = mysqli_fetch_assoc( $res ) ) {
            $cms["page"] = $page;
            if ( $cms["page"]["created"] <= date( "Y-m-d H:i:s" ) && $cms["page"]["published"] ) {
                $cms["status"] = "200";
            } else {
                $cms["status"] = "404"; // disable write to disk but echo if admin
            }
        }
    }
}

function cms_pages_create_tables() {
    global $cms;

    mysqli_query( $cms["base"], "
    CREATE TABLE IF NOT EXISTS `pages` (
        `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        `pin` tinyint(1) NOT NULL DEFAULT 0,
        `published` tinyint(1) NOT NULL DEFAULT 1,
        `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
        `modified` double NOT NULL DEFAULT 0,
        `tpl` varchar(64) DEFAULT NULL,
        `title` varchar(255) DEFAULT NULL,
        `seo_title` varchar(255) DEFAULT NULL,
        `text` longtext DEFAULT NULL,
        `url` varchar(255) DEFAULT NULL,
        `description` varchar(2048) NOT NULL DEFAULT '',
        `tags` varchar(2048) NOT NULL DEFAULT '',
        UNIQUE KEY `id` (`id`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    ");

}


function cms_pages_admin() {
    global $cms;

    $conf = @$cms["config"]["pages.mod.php"]["menu"]["pages"];
    if ( empty( $conf["hide"] ) && empty( $cms["config"]["admin_sections"][ $conf["section"] ]["hide"] ) ) {

    // Read template settings
    cms_template_load_settings();
    
    $tMaxUploadSize  = __( "max_size" ) . number_format( file_upload_max_size(), 0, ".", " " ) . __( "bytes" );

    $help_file = "{$cms['config']['template.mod.php']['template']}/instruction.{$cms['config']['locale']}.html";
    if ( is_file( "{$cms['cms_dir']}/{$help_file}" ) ) {
        $help_blanks = "<a target=_blank href='{$cms['base_path']}{$help_file}'>" . __( "blanks" ) . "</a>";
    } else {
        $help_blanks = "";
    }

    $help_file = "man/{$cms['config']['locale']}/codemirror.html";
    if ( is_file( "{$cms['cms_dir']}/{$help_file}" ) ) {
        $help_codemirror = "<a target=_blank href='{$cms['base_path']}{$help_file}'>" . __( "codemirror" ) . "</a>";
    } else {
        $help_codemirror = "";
    }

    $files_panel = "
<div class=mediateka-grid>
    <div class=mediateka-files-hscroll>
        <div class=mediateka-files-grid>
            
        </div>
    </div>
    
    <div class=mediateka-buttons>
        <div class=upload-files>
            <input id=upload-btn type=file name='myfile[]' multiple class=inputfile title='{$tMaxUploadSize}'>
            <label for=upload-btn title='{$tMaxUploadSize}'>" . __( "upload" ) . "</label>
        </div>
        <div class=link-file>
            <span class=link-file-tag></span>
            <span class=link-file-copy-btn>" . __( "copy" ) . "</span>
        </div>
        <div class='del-uploaded-files disabled'>" . __( "delete" ) . "</div>
    </div>
    
</div>";

    $buttons  = "<div class=save-page-button>" . __( "save" ) . "</div>";
    $buttons .= "<div class=open-properties>" . __( "properties" ) . "</div>";
    $buttons .= "<div class=open-mediateka>" . __( "mediateka" ) . "</div>";
    $buttons .= "<div class=tags-helper>" . __( "tags" ) . "</div>";
    $buttons .= "<div class=codemirror-replace>" . __( "replace" ) . "</div>";
    $buttons .= $help_blanks;
    $buttons .= $help_codemirror;

    $page = "
<div class=main-header>
    
    <div class=search-wrapper>
        <input class=page-search type=text
            placeholder='" . __( "search" ) . "'
            title='" . __( "search_with_ctrl" ) . "'
            autocomplete=off data-result-of=''>
        <div class=reset></div>
        <button class=page-search-button></button>
    </div>

    <div class=add-page-btn>
        <div class=x1></div>
        <div class=x2></div>
    </div>
    
    <div> </div>

    <a class=del-pages-btn>
        <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'><defs><style>.a-del,.b-del{fill:none;}.a-del{stroke:#000;stroke-miterlimit:10;}</style></defs><line class='a-del' x1='5.51' y1='6.96' x2='14.51' y2='6.96'/><line class='a-del' x1='8.66' y1='5.08' x2='11.36' y2='5.08'/><path class='a-del' d='M13.65,8.52v5.05a1.53,1.53,0,0,1-1.53,1.51H7.91A1.53,1.53,0,0,1,6.4,13.57V8.52'/><line class='a-del' x1='8.77' y1='9.16' x2='8.77' y2='12.63'/><line class='a-del' x1='11.26' y1='9.16' x2='11.26' y2='12.63'/><rect class='b-del' width='20' height='20'/></svg>
    </a>
    
</div>

<div class=main-main>
    
    <div class=pages-grid>
    </div>
    
</div>

<div class=main-footer>
    <div class=pager></div>
    <div class=counters>
        <input class=loaded value=0 autocomplete=off data-offset=0>
        <span>" . __( "of" ) . "</span>
        <span class=count>0</span>
    </div>
</div>

<div class='page-editor-bg hidden'>
    <div class='page-editor-grid editor-grid'>

        <div class=page-editor-header>
            <div class=close-page-button></div>
            <a data-page-title class=page-editor-title target=_blank></a>
        </div>

        <div class=page-editor-buttons>{$buttons}</div>
        
        <div class='page-properties hidden'>

            <div class='page title'>" . __( "title" ) . ":</div>
            <input name=title type=text>

            <div class='url title'>URL:</div>
            <div class=url-input>
                <input name=url type=text placeholder='" . __( "front_url" ) . "'>
                <div class=url-translit title='" . __( "url_translit" ) . "'></div>
            </div>

            <div class='seo title'>" . __( "seo_title" ) . ":</div>
            <input name=seo_title type=text>

            <div class='description title'>" . __( "description" ) . ":</div>
            <textarea name=description rows=3></textarea>

            <div class='template title'>" . __( "template" ) . ":</div>
            <div class=template-select-grid>
                <div class=field-select data-template data-old-template>
                    <div class=value></div>
                    <div class=icon></div>
                </div>
                <div class=field-options>
                    
                </div>
            </div>

            <div class='date title'>" . __( "date" ) . ":</div>
            <input name=date type=date>
            <div class='time title'>" . __( "time" ) . ":</div>
            <input name=time type=time>

            <div class='tags title'>" . __( "tags" ) . ":</div>
            <textarea name=tags rows=3></textarea>

        </div>

        <div class='page-editor-panel hidden'>
            <div class=upload-progress></div>
            {$files_panel}
        </div>

        <div class=page-editor>
            <textarea data-modified class=coffee-editorpage-area name=add_editorpage></textarea>
        </div>

        <div class=tags>
            <div class=tags-grid>
                <div data-type=wrap data-otag='<h1>' data-ctag='</h1>' data-len=4><span>" . __( "h1" ) . "</span><span class=tag>&lt;h1></span></div>
                <div data-type=wrap data-otag='<h2>' data-ctag='</h2>' data-len=4><span>" . __( "h1" ) . "</span><span class=tag>&lt;h2></span></div>
                <div data-type=wrap data-otag='<p>' data-ctag='</p>' data-len=3><span>" . __( "p" ) . "</span><span class=tag>&lt;p></span></div>
                <div data-type=wrap data-otag='<div>' data-ctag='</div>' data-len=5><span>" . __( "div" ) . "</span><span class=tag>&lt;div></span></div>
                <div data-type=wrap-a><span>" . __( "link" ) . "</span><span class=tag>&lt;a></span></div>
                <div data-type=wrap data-otag='<code>' data-ctag='</code>' data-len=6><span>" . __( "code" ) . "</span><span class=tag>&lt;code></span></div>
                <div data-type=wrap data-otag='<pre><code>' data-ctag='</code></pre>' data-len=11><span>" . __( "code" ) . "</span><span class=tag>&lt;pre>&lt;code></span></div>
                <div data-type=wrap data-otag='<span>' data-ctag='</span>' data-len=6><span>" . __( "span" ) . "</span><span class=tag>&lt;span></span></div>
                <div data-type=wrap data-otag='<blockquote>' data-ctag='</blockquote>' data-len=12><span>" . __( "cite" ) . "</span><span class=tag>&lt;blockquote></span></div>
                <div data-type=wrap-list data-tag=ul><span>" . __( "ul" ) . "</span><span class=tag>&lt;ul></span></div>
                <div data-type=wrap-list data-tag=ol><span>" . __( "ol" ) . "</span><span class=tag>&lt;ol></span></div>
                <div data-type=wrap data-otag='<li>' data-ctag='</li>' data-len=4><span>" . __( "li" ) . "</span><span class=tag>&lt;li></span></div>
                <div data-type=wrap data-otag='<figure>\n    ' data-ctag='\n    <figcaption></figcaption>\n</figure>' data-ch=4 data-line=1><span>" . __( "figure" ) . "</span><span class=tag>&lt;figure></span></div>
                <div data-type=wrap data-otag='<!-- ' data-ctag=' -->' data-len=5><span class=tag>&lt;!--</span>&nbsp;<span>" . __( "comment" ) . "</span>&nbsp;<span class=tag>--></span></div>
                <div data-type=wrap data-otag='<b>' data-ctag='</b>' data-len=3><span>" . __( "bold" ) . "</span><span class=tag>&lt;b></span></div>
            </div>
        </div>
    </div>
</div>";

    // Create menu item if not exists
    if ( empty( $cms["config"]["pages.mod.php"]["menu"]["pages"] ) ) {
        $cms["config"]["pages.mod.php"]["menu"]["pages"] = array(
            "title"    => "pages_module_name",
            "sort"     => 10,
            "section"  => "content",
        );
        cms_save_config();
    }

    $cms["admin_pages"]["pages"] = $page;

    }
    
    
    
    $conf = @$cms["config"]["pages.mod.php"]["menu"]["pages-utils"];
    if ( empty( $conf["hide"] ) && empty( $cms["config"]["admin_sections"][ $conf["section"] ]["hide"] ) ) {
    
    // Create menu item if not exists
    if ( empty( $cms["config"]["pages.mod.php"]["menu"]["pages-utils"] ) ) {
        $cms["config"]["pages.mod.php"]["menu"]["pages-utils"] = array(
            "title"    => "pages_utils",
            "sort"     => 15,
            "section"  => "content",
            "hide"     => true,
        );
        cms_save_config();
    }


    $page = "
<div class=pages-utils-main>
    <div class=replace-util>
        <p>" . __( "replace_instruction" ) . "</p>
        <div class=replace-inputs>
            <div class=replace_table>
                <div class=title>" . __( "replace_table" ) . "</div>
                <input type=text name=table autocomplete=off value=pages>
            </div>
            <div class=stub></div>
            <div class=replace_id_col>
                <div class=title>" . __( "replace_id_col" ) . "</div>
                <input type=text name=id_col autocomplete=off value=id>
            </div>
            <div class=replace_column>
                <div class=title>" . __( "replace_column" ) . "</div>
                <input type=text name=column autocomplete=off value=text>
            </div>
            <div class=regex>
                <div class=title>" . __( "regex_title" ) . "</div>
                <input type=text name=search_regex autocomplete=off>
            </div>
            <div class=replace>
                <div class=title>" . __( "replace_title" ) . "</div>
                <input type=text name=replace autocomplete=off>
            </div>
        </div>
        <div class=replace-btn>" . __( "replace_btn" ) . "</div>
    </div>
</div>
    ";

    $cms["admin_pages"]["pages-utils"] = $page;
    
    }
}


function cms_pages_menu() {
    global $cms;

    foreach( $cms["menu"] as $id => $menu ) {
        if ( is_array( $menu["items"] ) ) {
            cms_pages_menu_items( $cms["menu"][$id]["items"] );
        }
    }
}


function cms_pages_menu_items( &$items ) {
    global $cms;

    foreach( $items as $id => $item ) {
        if ( $item["id"] ) {
            $q_pages = "SELECT * FROM pages WHERE id={$item['id']}";
            if ( $res_p = mysqli_query( $cms["base"], $q_pages ) ) {
                if ( $page = mysqli_fetch_assoc( $res_p ) ) {
                    if ( empty( $items[$id]["title"] ) ) {
                        $items[$id]["title"] = $page["title"];
                    }
                    $items[$id]["url"] = $page["url"];
                } else {
                    $items[$id]["title"] = __( "deteled_page" );
                }
            }
        }
        if ( is_array( $items[$id]["items"] ) ) {
            cms_pages_menu_items( $items[$id]["items"] );
        }
    }
}
