+# return the extension this path should have WITHOUT the period
+function path_or_mime_to_ext($path, $mime = 'text/plain', $default = 'txt') {
+ $last_dot = strrpos($path, '.');
+ if($last_dot === false || $last_dot === 0 || $last_dot === (strlen($path) - 1)) {
+ # no extension
+ if(isset($GLOBALS['mime_to_ext'][$mime])) {
+ return $GLOBALS['mime_to_ext'][$mime];
+ } else {
+ return $default;
+ }
+ } else {
+ $ext = strtolower(substr($path, $last_dot + 1));
+ if(isset($GLOBALS['ext_to_ext'][$ext])) {
+ return $GLOBALS['ext_to_ext'][$ext];
+ }
+ return $ext;
+ }
+}
+
+# Add or fix extension on path
+# This just does string manipulation (ie doesn't move/open/etc any files.)
+# Mime type used to generate extension ONLY IF it doesn't have one already.
+function path_fix_ext($path, $mime = 'text/plain', $default_ext = '.txt') {
+ $last_dot = strrpos($path, '.');
+ if($last_dot === false || $last_dot === 0) { # no extension
+ $path .= '.' . path_or_mime_to_ext($path, $mime, $default_ext);
+ } else {
+ $basename = substr($path, 0, $last_dot + 1); # keep dot
+ $path = $basename . path_or_mime_to_ext($path, $mime, $default_ext);
+ }
+
+ return $path;
+}