From fe126cb4bf103b59fe66fe5f0921560c62f80165 Mon Sep 17 00:00:00 2001 From: czaks Date: Sun, 11 May 2014 14:10:53 +0200 Subject: [PATCH] rewrite filename truncation code; ref #53 --- inc/display.php | 10 ---------- .../Twig/Extensions/Extension/Tinyboard.php | 18 +++++++++++++++++- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/inc/display.php b/inc/display.php index a859fbdb3..c836247eb 100644 --- a/inc/display.php +++ b/inc/display.php @@ -253,16 +253,6 @@ function truncate($body, $url, $max_lines = false, $max_chars = false) { return $body; } -function truncate_filename($filename, $length) { - if (strlen($filename) <= $length) return $filename; - $matches = array(); - if (!preg_match("/.*(\\..+)/", $filename, $matches)) return $filename // what, no extension - $length -= strlen($matches[1]); - if ($length <= 0) return '(...)' . $matches[1]; // lmao - $filename = substr($filename, 0, $length) . '(...)' . $matches[1]; - return $filename; -} - function bidi_cleanup($data) { // Closes all embedded RTL and LTR unicode formatting blocks in a string so that // it can be used inside another without controlling its direction. diff --git a/inc/lib/Twig/Extensions/Extension/Tinyboard.php b/inc/lib/Twig/Extensions/Extension/Tinyboard.php index e5dff9934..986ecf452 100644 --- a/inc/lib/Twig/Extensions/Extension/Tinyboard.php +++ b/inc/lib/Twig/Extensions/Extension/Tinyboard.php @@ -13,7 +13,7 @@ class Twig_Extensions_Extension_Tinyboard extends Twig_Extension new Twig_SimpleFilter('filesize', 'format_bytes'), new Twig_SimpleFilter('truncate', 'twig_truncate_filter'), new Twig_SimpleFilter('truncate_body', 'truncate'), - new Twig_SimpleFilter('truncate_filename', 'truncate_filename'), + new Twig_SimpleFilter('truncate_filename', 'twig_filename_truncate_filter'), new Twig_SimpleFilter('extension', 'twig_extension_filter'), new Twig_SimpleFilter('sprintf', 'sprintf'), new Twig_SimpleFilter('capcode', 'capcode'), @@ -104,6 +104,22 @@ function twig_truncate_filter($value, $length = 30, $preserve = false, $separato return $value; } +function twig_filename_truncate_filter($value, $length = 30, $separator = '…') { + if (mb_strlen($value) > $length) { + $value = strrev($value); + $array = array_reverse(explode(".", $value, 2)); + $array = array_map("strrev", $array); + + $filename = &$array[0]; + $extension = isset($array[1]) ? $array[1] : false; + + $filename = mb_substr($filename, 0, $length - ($extension ? mb_strlen($extension) + 1 : 0)) . $separator; + + return implode(".", $array); + } + return $value; +} + function twig_ratio_function($w, $h) { return fraction($w, $h, ':'); }