Initial commit

This commit is contained in:
2020-12-26 07:42:48 +01:00
commit 55f70d036b
18 changed files with 1151 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
session/*
+2
View File
@@ -0,0 +1,2 @@
# OsuOptimizerPHP
Swiss Army Knife style osu! library manager
+3
View File
@@ -0,0 +1,3 @@
<?php
if (!file_exists("session")) mkdir("session");
require "main.php";
+157
View File
@@ -0,0 +1,157 @@
<?php
class optimizer
{
public static function blacken_image(string $file) : void
{
$black_png = "./resources/black.png";
$black_jpg = "./resources/black.jpg";
$ext = strtolower(pathinfo($file)["extension"]);
if ($ext == "jpg" || $ext == "jpeg")
{
copy($black_jpg, $file);
}
else
{
copy($black_png, $file);
}
}
public static function blacken_backgrounds(osu_library $library) : void
{
foreach ($library->get_backgrounds() as $file) self::blacken_image($file);
}
public static function remove_videos(osu_library $library)
{
foreach ($library->get_videos() as $file)
{
unlink($file);
}
}
public static function remove_storyboards(osu_library $library) : void
{
foreach ($library->get_storyboards() as $file)
{
unlink($file);
}
foreach ($library->get_storyboard_files() as $file)
{
unlink($file);
}
$empty = self::build_empty_dir_list($library);
foreach ($empty as $folder)
{
rmdir($folder);
}
}
private static function build_removand_sublist(string $folder) : array
{
$queue = array();
foreach (glob(utils::globsafe($folder) . "/*") as $file)
{
if (is_dir($file))
{
$queue = array_merge($queue, self::build_removand_sublist($file)); // recursion
}
else
{
$queue[] = strtolower($file);
}
}
return $queue;
}
public static function build_removand_list(osu_library $library) : array
{
$queue = array();
foreach ($library->get_folders() as $folder)
{
$queue = array_merge($queue, self::build_removand_sublist($folder));
}
return $queue;
}
public static function build_empty_dir_sublist(string $folder) : array
{
$queue = array();
$glob = glob(utils::globsafe($folder) . "/*");
if (empty($glob))
{
$queue[] = strtolower($file);
}
else
{
foreach ($glob as $file)
{
if (is_dir($file))
{
$queue = array_merge($queue, self::build_empty_dir_sublist($file));
}
}
}
return $queue;
}
public static function build_empty_dir_list(osu_library $library) : array
{
$queue = array();
foreach ($library->get_folders() as $folder)
{
$queue = array_merge($queue, self::build_empty_dir_sublist($folder));
}
return $queue;
}
public static function build_excluded_list(osu_library $library) : array
{
$bg = $library->get_backgrounds();
$vid = $library->get_videos();
$sb = $library->get_storyboards();
$a = $library->get_audiofiles();
$sbf = $library->get_storyboard_files();
$osf = $library->get_osu_files();
$excluded = array_merge($bg, $vid, $sb, $a, $sbf, $osf);
$lowercase = array();
foreach ($excluded as $key => $value)
{
$lowercase[$key] = strtolower($value);
}
return $lowercase;
}
public static function remove_other(osu_library $library) : void
{
// $time_start = microtime(true);
$removand = self::build_removand_list($library);
$exclusions = self::build_excluded_list($library);
$final = array_diff($removand, $exclusions);
foreach ($final as $file)
{
unlink($file);
}
$empty = self::build_empty_dir_list($library);
foreach ($empty as $folder)
{
rmdir($folder);
}
// $time_end = microtime(true);
// $time = $time_end - $time_start;
// echo " in {$time} seconds.";
}
}
+565
View File
@@ -0,0 +1,565 @@
<?php
class osu_library
{
private static $song_library_folder = "Songs";
private static $db_file_location = "session/optimizer_data.json";
private $db;
public function __construct(string $db_file = NULL)
{
if ($db_file === NULL) $db_file = self::$db_file_location;
$this->load_db($db_file);
}
public function scan_library(string $root) : void
{
$root = str_ireplace("\\", "/", $root); // fuck windows backslash
$root = rtrim($root, "/"); // remove trailing slash(es)
$this->set_root($root); // update db entry
foreach(glob($this->get_library_folder() . "/*", GLOB_ONLYDIR) as $folder)
{
$this->scan_add_folder($folder);
}
}
public function rescan_library(string $root) : void
{
$this->clear_library_cache();
$this->scan_library($root);
}
private function clear_library_cache() : void
{
unset($this->db["library"]);
}
private function scan_add_folder(string $folder) : void
{
$key = basename($folder);
$difficulties = array();
$osu_glob = glob(utils::globsafe($folder) . "/*.osu");
// if (count($osu_glob) < 1) return; // nothing to do here...
foreach ($osu_glob as $osu_file)
{
if (isset($this->db["library"][$key][$osu_file]["hash"]))
{
if ($this->db["library"][$key][$osu_file]["hash"] == hash_file("md5", $osu_file)) continue;
else unset($this->db["library"][$key][$osu_file]); // recalculate
}
$diff = $this->scan_parse_osu_file($osu_file);
$diff["key"] = basename($osu_file);
$diff["path"] = $osu_file;
$difficulties[basename($osu_file)] = $diff;
}
foreach (glob(utils::globsafe($folder) . "/*.osb") as $osb_file)
{
if (isset($this->db["library"][$key][$osb_file]["hash"]))
{
if ($this->db["library"][$key][$osb_file]["hash"] == hash_file("md5", $osb_file)) continue;
else unset($this->db["library"][$key][$osb_file]); // recalculate
}
$diff = $this->scan_parse_osb_file($osb_file);
$diff["key"] = basename($osb_file);
$diff["path"] = $osb_file;
$difficulties[basename($osb_file)] = $diff;
}
$temp = explode(" ", basename($folder))[0];
if (is_numeric($temp))
{
$set_id = $temp;
}
else
{
$set_id = "";
}
$entry = array(
"key" => $key,
"path" => $folder,
"id" => $set_id,
"difficulties" => $difficulties,
);
if (!isset($this->db["library"])) $this->db["library"] = array();
$this->db["library"][$key] = $entry;
}
private function scan_parse_osu_file(string $osu_file) : array
{
$time_start = microtime(true);
$file = file($osu_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// osu files can get big, but why not load the full thing :3
if (stripos($file[0], "osu file format") === false) return [ "error..." ];
// some files had "ZERO WIDTH NO-BREAK SPACE" characters...
$format = explode("osu file format ", $file[0])[1];
unset($file[0]); // no longer needed
$osu = array("Format" => $format);
$current_section = "UnofficialComments";
$osu[$current_section] = array();
$storyboard = array();
foreach ($file as $key => $line)
{
if (strpos($line, "[") === 0 && strpos($line, "]") === (strlen($line)-1))
{
$current_section = str_replace([ "[", "]" ], "", $line);
if (!isset($osu[$current_section]))
{
$osu[$current_section] = array();
}
// peppy is retarded so i have to do this...
switch ($current_section) {
case "General":
case "Editor":
$section_type = "key-value pairs";
$delimiter = ": ";
break;
case "Metadata":
case "Difficulty":
$section_type = "key-value pairs";
$delimiter = ":"; // notice the missing space
break;
case "Colours":
$section_type = "key-value pairs";
$delimiter = " : "; // WHY WOULD YOU DO THIS IF YOU ALREADY HAVE TWO TYPES OF KEY-VALUE PAIRS???????????????????
break;
case "Events":
case "TimingPoints":
case "HitObjects":
$section_type = "lists"; // yes, listS because one list per line
$delimiter = ",";
break;
default:
$section_type = "unknown";
}
continue;
}
// only parse the ones needed
switch ($current_section) {
case "General":
case "Metadata":
case "Difficulty":
case "Events":
$skip = false;
break;
default:
$skip = true;
}
if ($skip) continue;
if (strpos($line, "//") === 0) // there were commented files that broke my script
{
}
else if ($section_type == "key-value pairs")
{
$delimiter_position = strpos($line, $delimiter);
$value = substr($line, $delimiter_position + strlen($delimiter_position));
$osu[$current_section][substr($line, 0, $delimiter_position)] = $value;
}
else if ($section_type == "lists")
{
$list = explode($delimiter, $line);
// group events by type and start time
if ($current_section == "Events")
{
if (strpos($line, " ") === 0) continue; // skip storyboard details lines
// event types: https://github.com/ppy/osu/blob/master/osu.Game/Beatmaps/Legacy/LegacyEventType.cs
$list[0] = str_replace(
[ "Background", "Video", "Break", "Colour", "Sprite", "Sample", "Animation" ],
[ "0", "1", "2", "3", "4", "5", "6" ],
$list[0]
);
if ($list[0] == "5" || $list[0] == "4")
{
$storyboard[] = trim(str_replace("\\", "/", $list[3]), "\"");
}
if ($list[0] == "6")
{
$story_base = pathinfo(trim(str_replace("\\", "/", $list[3]), "\""));
if (empty($story_base["extension"])) $ext = "";
else $ext = "." . $story_base["extension"];
if (empty($story_base["dirname"])) $dir = "";
else $dir = $story_base["dirname"] . "/";
for ($i = 0; $i < intval($list[6]); $i++)
{
$storyboard[] = $dir . $story_base["filename"] . $i . $ext;
}
}
if (!isset($osu[$current_section][$list[0]]))
{
$osu[$current_section][$list[0]] = array();
}
if (!isset($osu[$current_section][$list[0]][$list[1]]))
{
$osu[$current_section][$list[0]][$list[1]] = array();
}
$osu[$current_section][$list[0]][$list[1]][] = $list;
}
else
{
$osu[$current_section][] = $list;
}
}
else
{
$osu[$current_section][] = $line; // just dump the unknown...
}
}
unset($file); // remove the memory leak
// return $osu;
$set_id = $osu["Metadata"]["BeatmapSetID"] ?? false;
if ($set_id === false)
{
$temp = explode(" ", basename(dirname($osu_file)))[0];
if (is_numeric($temp))
{
$set_id = $temp;
}
else
{
$set_id = "";
}
}
$background = str_replace("\\", "/", trim($osu["Events"][0][0][0][2] ?? "", "\""));
$audio = str_replace("\\", "/", trim($osu["General"]["AudioFilename"] ?? "", "\""));
$video = str_replace("\\", "/", trim($osu["Events"][1][array_key_first($osu["Events"][1] ?? array())][0][2] ?? "", "\""));
$storyboard = array_unique($storyboard);
$map_id = intval($osu["Metadata"]["BeatmapID"] ?? 0);
if ($map_id < 1) $map_id = "";
$return = array(
"format" => $osu["Format"] ?? "",
"title" => $osu["Metadata"]["Title"] ?? "",
"artist" => $osu["Metadata"]["Artist"] ?? "",
"mapper" => $osu["Metadata"]["Creator"] ?? "",
"difficulty" => $osu["Metadata"]["Version"] ?? "",
"tags" => $osu["Metadata"]["Tags"] ?? "",
"background" => $background,
"audio" => $audio,
"video" => $video,
"storyboard" => $storyboard,
"id" => $map_id,
"set_id" => $set_id,
);
$time_end = microtime(true);
$time = $time_end - $time_start;
$return["process_time"] = $time;
$return["hash"] = hash_file("md5", $osu_file);
return $return;
}
private function scan_parse_osb_file(string $osb_file) : array
{
$time_start = microtime(true);
$file = file($osb_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$storyboard = array();
$current_section = "UnofficialComments";
foreach ($file as $key => $line)
{
if (strpos($line, "[") === 0 && strpos($line, "]") === (strlen($line)-1))
{
$current_section = str_replace([ "[", "]" ], "", $line);
continue;
}
if (!($current_section == "Events")) continue; // skip rest
$list = explode(",", $line);
$list[0] = str_replace(
[ "Background", "Video", "Break", "Colour", "Sprite", "Sample", "Animation" ],
[ "0", "1", "2", "3", "4", "5", "6" ],
$list[0]
);
if ($list[0] == "5" || $list[0] == "4")
{
$storyboard[] = trim(str_replace("\\", "/", $list[3]), "\"");
}
if ($list[0] == "6")
{
$story_base = pathinfo(trim(str_replace("\\", "/", $list[3]), "\""));
if (empty($story_base["extension"])) $ext = "";
else $ext = "." . $story_base["extension"];
if (empty($story_base["dirname"])) $dir = "";
else $dir = $story_base["dirname"] . "/";
for ($i = 0; $i < intval($list[6]); $i++)
{
$storyboard[] = $dir . $story_base["filename"] . $i . $ext;
}
}
$temp = explode(" ", basename(dirname($osb_file)))[0];
if (is_numeric($temp))
{
$set_id = $temp;
}
else
{
$set_id = "";
}
}
$storyboard = array_unique($storyboard);
$return = array(
"format" => "storyboard",
"storyboard" => $storyboard,
"set_id" => $set_id,
);
$time_end = microtime(true);
$time = $time_end - $time_start;
$return["process_time"] = $time;
$return["hash"] = hash_file("md5", $osb_file);
return $return;
}
public function get_root() : string
{
return $this->db["root"];
}
public function set_root(string $root) : void
{
$this->db["root"] = $root;
}
public function save_db() : void
{
$raw_json = json_encode($this->db); // re-encode the db
file_put_contents($this->get_db_file_location(), $raw_json); // save to the file
}
public function load_db(string $db_file) : void
{
if (file_exists($db_file))
{
// load json db to the db array
$raw_json = file_get_contents($db_file);
$this->db = json_decode($raw_json, true);
}
else
{
$this->db = array(); // empty db
}
$this->set_db_file_location($db_file); // override the loaded location
}
public function set_db_file_location(string $db_file) : void
{
$this->db["db_file"] = $db_file;
}
public function get_db_file_location() : string
{
if (empty($this->db["db_file"]))
{
$this->set_db_file_location(self::$db_file_location);
return self::$db_file_location;
}
else
{
return $this->db["db_file"];
}
}
public function get_library_folder() : string
{
return $this->get_root() . "/" . self::$song_library_folder;
}
public function get_library() : array
{
return $this->db["library"] ?? array(); // todo: filter white/black list
}
public function get_full_library() : array
{
return $this->db["library"];
}
public function get_folders() : array
{
$db = $this->get_library();
$folders = array();
foreach ($db as $beatmapset)
{
$backgrounds[] = $beatmapset["path"];
}
$backgrounds = array_unique($backgrounds);
return $backgrounds;
}
public function get_backgrounds() : array
{
$db = $this->get_library();
$backgrounds = array();
foreach ($db as $beatmapset)
{
foreach($beatmapset["difficulties"] as $beatmap)
{
if (!empty($beatmap["background"]))
{
$backgrounds[] = $beatmapset["path"] . "/" . $beatmap["background"];
}
}
}
$backgrounds = array_unique($backgrounds);
return $backgrounds;
}
public function get_videos() : array
{
$db = $this->get_library();
$videos = array();
foreach ($db as $beatmapset)
{
foreach($beatmapset["difficulties"] as $beatmap)
{
if (!empty($beatmap["video"]))
{
$videos[] = $beatmapset["path"] . "/" . $beatmap["video"];
}
}
}
$videos = array_unique($videos);
return $videos;
}
public function get_osu_files() : array
{
$db = $this->get_library();
$osu_files = array();
foreach ($db as $beatmapset)
{
foreach($beatmapset["difficulties"] as $beatmap)
{
if (!empty($beatmap["format"]) && $beatmap["format"] != "storyboard")
{
$osu_files[] = $beatmap["path"];
}
}
}
$osu_files = array_unique($osu_files);
return $osu_files;
}
public function get_storyboard_files() : array
{
$db = $this->get_library();
$storyboard_files = array();
foreach ($db as $beatmapset)
{
foreach($beatmapset["difficulties"] as $beatmap)
{
if (!empty($beatmap["format"]) && $beatmap["format"] == "storyboard")
{
$storyboard_files[] = $beatmap["path"];
}
}
}
$storyboard_files = array_unique($storyboard_files);
return $storyboard_files;
}
public function get_storyboards() : array
{
$db = $this->get_library();
$storyboards = array();
foreach ($db as $beatmapset)
{
foreach($beatmapset["difficulties"] as $beatmap)
{
foreach ($beatmap["storyboard"] ?? array() as $storyelement)
{
$storyboards[] = $beatmapset["path"] . "/" . $storyelement;
}
}
}
$storyboards = array_unique($storyboards);
return $storyboards;
}
public function get_audiofiles() : array
{
$db = $this->get_library();
$audiofiles = array();
foreach ($db as $beatmapset)
{
foreach($beatmapset["difficulties"] as $beatmap)
{
if (!empty($beatmap["audio"]))
{
$audiofiles[] = $beatmapset["path"] . "/" . $beatmap["audio"];
}
}
}
$audiofiles = array_unique($audiofiles);
return $audiofiles;
}
}
+5
View File
@@ -0,0 +1,5 @@
<?php
class osu_parser
{
}
+12
View File
@@ -0,0 +1,12 @@
<?php
// this could have been done better but whatever
header ('Content-Type: image/png');
$file = "./black.png";
if (!empty($_GET["path"]) && file_exists($_GET["path"]) && !is_dir($_GET["path"]))
{
$file = $_GET["path"];
}
echo file_get_contents($file);
+40
View File
@@ -0,0 +1,40 @@
<?php
class utils
{
public static function globsafe(string $path) : string
{
$path = str_replace('[', '\[', $path);
$path = str_replace(']', '\]', $path);
$path = str_replace('\[', '[[]', $path);
$path = str_replace('\]', '[]]', $path);
return $path;
}
public static function recursive_zip_map($zip, $root, $path)
{
$files = glob($path . "/*");
foreach ($files as $file)
{
if (is_dir($file))
{
recursive_zip_map($zip, $root, $file);
}
else
{
$relative = str_replace(array("@-".$root."/", "@-".$root), "", "@-".$file);
$zip->addFile($file, $relative);
}
}
}
// $folder = $my_db[$beatmap_id];
// $name = basename($folder) . ".osz";
// echo "Zipping " . $name;
// $path = $collection_location . "/" . $name;
// $zip = new ZipArchive;
// $zip->open($path, ZipArchive::CREATE);
// echo ".";
// recursive_zip_map($zip, $fol
}
+105
View File
@@ -0,0 +1,105 @@
<?php
// todo: whitelist / blacklist
// todo: repack osz file
set_time_limit(300000);
require "libraries/osu_library.php";
require "libraries/optimizer.php";
require "libraries/utils.php";
require "temp/dump.php";
$lib = new osu_library();
$root = "S:/test";
function redirect($path)
{
header('Location: ' . $path);
exit(0); // TERMINATE CURRENT SCRIPT!
}
if (isset($_GET["rescan"]))
{
$lib->scan_library($root);
$lib->save_db();
redirect("./");
}
if (isset($_GET["blacken"]))
{
@optimizer::blacken_backgrounds($lib);
redirect("./");
}
if (isset($_GET["nosb"]))
{
@optimizer::remove_storyboards($lib);
redirect("./");
}
if (isset($_GET["novid"]))
{
@optimizer::remove_videos($lib);
redirect("./");
}
if (isset($_GET["purify"]))
{
@optimizer::remove_other($lib);
redirect("./");
}
$start = file_get_contents("resources/start.html");
$start = str_replace("{{ STYLE }}", file_get_contents("resources/style.css"), $start);
echo $start;
// dump($lib, "lib");
echo '<a href="./?rescan">[Rescan]</a> ';
echo '<a href="./?blacken">[Blacken]</a> ';
echo '<a href="./?nosb">[NoSB]</a> ';
echo '<a href="./?novid">[Novid]</a> ';
echo '<a href="./?purify">[Purify]</a> ';
echo '<br /><br /><br /><a href="./splitter.php?page=1">[Explore]</a> ';
echo "<h2>" . count($lib->get_library()) . " mapsets loaded.</h2>";
echo "<h3>osu! folder: " . $lib->get_root() . "</h3>";
$proc_time = 0;
foreach ($lib->get_library() as $set)
{
foreach ($set["difficulties"] as $map)
{
$proc_time += $map["process_time"];
}
}
echo "<h3>Process time: " . $proc_time . " seconds</h3>";
// foreach ($lib->get_library() as $mapset)
// {
// echo '<div class="beatmapset">';
// echo '<h2>Beatmapset: ';
// if (!empty($mapset["id"])) echo $mapset["id"];
// else echo '???';
// echo '</h2>';
// foreach ($mapset["difficulties"] as $beatmap)
// {
// $beatmap["format-2"] = substr($beatmap["format"] ?? "v1", 1);
// if (is_numeric(substr($beatmap["format"] ?? "v1", 1)))
// {
// echo '<div class="beatmap">';
// echo '<h3>Title: ' . $beatmap["title"];
// if (!empty($beatmap["id"])) echo '<br />ID: ' . $beatmap["id"];
// echo '<br />Artist: ' . $beatmap["artist"];
// echo '<br />Mapper: ' . $beatmap["mapper"];
// echo '<br />Format: ' . $beatmap["format"];
// echo '</h3>';
// echo '<img class="small-background" src="./proxy.php?path=' . urlencode($mapset["path"] . "/" . $beatmap["background"]) . '" />';
// echo '</div>';
// }
// else
// {
// echo '<div class="beatmap">';
// echo '<h3>Extra: ' . $beatmap["format"];
// echo '</h3>';
// echo '</div>';
// }
// }
// echo '</div>';
// }
Binary file not shown.

After

Width:  |  Height:  |  Size: 723 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 B

+6
View File
@@ -0,0 +1,6 @@
<html>
<head>
<title>osu! Optimizer by Thayol</title>
<style>{{ STYLE }}</style>
</head>
<body id="body">
+20
View File
@@ -0,0 +1,20 @@
html {
font-family: Roboto, sans-serif;
background-color: #111111;
color: White;
}
.beatmapset, .beatmap {
border: 1px solid white;
}
.beatmap {
margin: 5px 0;
padding: 10px;
}
a:link, a:hover, a:active, a:visited {
color: HotPink;
text-decoration: inherit;
}
.small-background {
max-height: 100px;
}
+58
View File
@@ -0,0 +1,58 @@
<?php
require "libraries/osu_library.php";
$page = $_GET["page"];
$page = intval($page);
if ($page < 1) $page = 1;
$pagesize = 100;
$lib = new osu_library();
$library = $lib->get_library();
$library_size = count($library);
$maxpage = ceil($library_size/$pagesize);
if ($page > $maxpage) $page = $maxpage;
$startindex = ($page - 1) * $pagesize;
$start = file_get_contents("resources/start.html");
$start = str_replace("{{ STYLE }}", file_get_contents("resources/style.css"), $start);
echo $start;
$partial_library = array_slice($library, $startindex, $pagesize);
$previous = $page - 1;
if ($previous < 1) $previous = 1;
$next = $page + 1;
if ($next > $maxpage) $next = $maxpage;
echo '<h2>Page ' . $page . '/' . $maxpage . ' of osu! songs</h2>';
echo '<a href="./splitter.php?page=' . $previous . '">[Previous]</a> ';
echo '<a href="./splitter.php?page=' . $next . '">[Next]</a> ';
echo "<pre>";
// print_r($partial_library);
// foreach ($partial_library as $key => $value)
// {
// $firstdiff = $value["difficulties"][array_key_first($value["difficulties"])];
// echo $firstdiff["artist"] . " - " . $firstdiff["title"] . " (" . count($value["difficulties"]) . " difficulties)\n";
// }
$proc_times = array();
foreach ($library as $key => $set)
{
$tiempo = 0;
foreach ($set["difficulties"] as $map)
{
$tiempo += $map["process_time"];
}
$proc_times[$key] = $tiempo;
}
arsort($proc_times);
foreach ($proc_times as $key => $tiempo)
{
$value = $library[$key];
$firstdiff = $value["difficulties"][array_key_first($value["difficulties"])];
echo str_pad(round($tiempo, 5), 7, "0") . "s " . $value["id"] . ": " . $firstdiff["artist"] . " - " . $firstdiff["title"] . " (" . count($value["difficulties"]) . " difficulties)\n";
}
echo "</pre>";
+35
View File
@@ -0,0 +1,35 @@
<?php
function dump($var, $title=NULL, $use_textarea=false)
{
echo '<pre style="text-align:left;background-color:#666666;color:#EEEEEE;padding:20px;border:1px solid #444444;border-radius:5px;">';
echo '<details>';
echo '<summary style="padding:20px;margin:-20px;">variable dump';
if ($title !== NULL)
{
echo ' of ' . $title;
}
echo '</summary>';
if ($use_textarea)
{
echo '<textarea style="margin-top:30px; width:100%; height:300px; resize: vertical;">';
}
else
{
echo '<div style="margin-top:30px;">';
}
print_r($var); // actual dump
if ($use_textarea)
{
echo '</textarea>';
}
else
{
echo '</div>';
}
echo '</details>';
echo '</pre>';
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+140
View File
@@ -0,0 +1,140 @@
<?php
class template_engine
{
public static $base_block = "BASE";
public $blocks = array();
public $templates = array();
private $block_pattern = '/\w*/';
private $block_pattern_chars = '[\w,_,-]*';
private $block_pattern_prefix = '{{ ';
private $block_pattern_suffix = ' }}';
private $source_files = array();
private $template_folder = "./templates/";
private function init_templates(array $source_files) : void
{
foreach ($source_files as $name => $source)
{
$this->templates[$name] = file_get_contents($source);
}
}
private function discover_templates(string $template_folder) : void
{
foreach (glob($template_folder."*") as $file)
{
$info = pathinfo($file);
$template_id = strtoupper(str_replace("-", "_", $info["filename"]));
$this->source_files[$template_id] = $file;
}
}
public function __construct()
{
$this->block_pattern = '/' . $this->block_pattern_prefix . $this->block_pattern_chars . $this->block_pattern_suffix . '/';
$this->discover_templates($this->template_folder);
$this->init_templates($this->source_files);
$this->new();
}
public function new() : void
{
$this->blocks = array();
foreach ($this->templates as $key => $template)
{
$this->blocks[$key] = $template;
}
// $this->blocks[self::$base_block] = $this->templates[self::$base_block];
}
public function get_block_names() : array
{
$all_matches = array();
foreach ($this->blocks as $block)
{
$matches = array();
preg_match_all($this->block_pattern, $block, $matches);
$all_matches = array_merge($all_matches, $matches[0]);
}
$block_names = array();
foreach (array_unique($all_matches) as $match)
{
$block_name = str_replace([$this->block_pattern_prefix, $this->block_pattern_suffix], "", $match);
$block_names[$block_name] = array_key_exists($block_name, $this->blocks) ? true : false;
}
return $block_names;
}
public function set_block_template(string $block, string $template) : void
{
$this->blocks[$block] = $this->templates[$template];
}
public function set_block(string $block, string $content) : void
{
$this->blocks[$block] = $content;
}
public function append_block(string $block, string $content) : void
{
if (empty($this->blocks[$block])) $this->blocks[$block] = "";
$this->blocks[$block] .= $content;
}
public function append_block_template(string $block, string $template) : void
{
if (empty($this->blocks[$block])) $this->blocks[$block] = "";
$this->blocks[$block] .= $this->templates[$template];
}
public function append_built_block(string $block, string $block_name) : void
{
$this->append_block($block, $this->build_block($block_name));
}
public function append_argumented_block(string $block, string $block_name, array $args) : void
{
$this->append_block($block, $this->build_argumented_block($block_name, $args));
}
public function build_argumented_block(string $block, array $args) : string
{
foreach ($args as $key => $value) $this->set_block($key, $value);
return $this->build_block($block);
}
public function build_block(string $block) : string
{
$matches = array();
$html = $this->blocks[$block];
$from = array();
$to = array();
foreach ($this->get_block_names() as $block_name => $has_block)
{
$from[] = $this->block_pattern_prefix . $block_name . $this->block_pattern_suffix;
if ($has_block) $to[] = $this->blocks[$block_name];
else $to[] = "";
}
while (preg_match_all($this->block_pattern, $html) > 0)
{
$html = str_replace($from, $to, $html);
}
return $html;
}
public function get_raw_html() : string
{
return $this->build_block(self::$base_block);
}
public function get_html() : string
{
$strip = [ "\t" ];
return str_replace($strip, "", $this->get_raw_html());
}
}