pub / rememori

Simple file-based bookmarking and notes application
git clone https://src.jayvii.de/pub/rememori.git
Home | Log | Files | Exports | Refs | README | RSS

commit 9c69f0b14db3754cab84272ba564a9c442694791
parent 4e7d5aea6d31d59a72952ce804f006a17001e5f9
Author: JayVii <jayvii[AT]posteo[DOT]de>
Date:   Tue, 29 Oct 2024 11:34:09 +0100

feat: cleanup empty categories

Diffstat:
Mlib/delete.php | 3+++
Mlib/edit.php | 2++
Mlib/helpers.php | 42++++++++++++++++++++++++++++++++++++++++++
3 files changed, 47 insertions(+), 0 deletions(-)

diff --git a/lib/delete.php b/lib/delete.php @@ -13,6 +13,9 @@ function delete_note( /* delete note */ $status = unlink($filepath); + /* cleanup directories and removed empty categories */ + remove_empty_categories($user, $category); + /* return status of deletion action */ return $status; } diff --git a/lib/edit.php b/lib/edit.php @@ -22,6 +22,8 @@ function edit_note( if ($renamed === false) { return false; } + /* cleanup directories and removed empty categories */ + remove_empty_categories($user, basename(dirname($filepath_t1, 1))); } /* Update content of note if necessary^ */ diff --git a/lib/helpers.php b/lib/helpers.php @@ -205,4 +205,46 @@ function generate_filename(string $content) { return $filename; } +function remove_empty_categories( + string $user, + string $category = "" +) { + + /* gather all categories of the given user or use the given category */ + if (empty($category)) { + $categories_path = glob($GLOBALS["data_dir"] . "/" . $user . "/*"); + } else { + $categories_path = array( + $GLOBALS["data_dir"] . "/" . $user . "/" . $category + ); + } + + /* loop through categories and remove those that are empty */ + foreach ($categories_path as $category_path) { + + /* ensure that we are indeed within a category FOLDER */ + if (is_dir($category_path) && is_readable($category_path)) { + + /* list all files in the category path, remove "." and ".." */ + $files_in_cat = array_filter( + scandir($category_path), + function($x) { return ($x != "." && $x != ".."); } + ); + + /* if directory is empty, remove it */ + if (count($files_in_cat) === 0) { + $removed = rmdir($category_path); + /* if removale failed, exit immediately and return "false" */ + if ($removed === false) { + return false; + } + } + } + } + + /* return "true" on success */ + return true; + +} + ?>