<?php

namespace onespace\tools\widgets\tinyfilebrowser\traits;

trait PathClean {

    /**
     * Clean path
     * @param string $path
     * @return string
     */
    protected function fm_clean_path($path, $trim = true) {
        return self::clean_path($path, $trim);
    }


    public static function clean_path($path, $trim = true) {
        $path = $trim ? trim($path) : $path;
        $path = trim($path, '\\/');
        $path = str_replace(array('../', '..\\'), '', $path);
        $path =  self::get_absolute_path_a($path);
        if ($path == '..') {
            $path = '';
        }
        return str_replace('\\', '/', $path);
    }


    /**
     * Path traversal prevention and clean the url
     * It replaces (consecutive) occurrences of / and \\ with whatever is in DIRECTORY_SEPARATOR, and processes /. and /.. fine.
     * @param $path
     * @return string
     */
    private static function get_absolute_path_a($path) {
        $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
        $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
        $absolutes = [];
        foreach ($parts as $part) {
            if ('.' == $part) continue;
            if ('..' == $part) {
                array_pop($absolutes);
            } else {
                $absolutes[] = $part;
            }
        }
        return implode(DIRECTORY_SEPARATOR, $absolutes);
    }
}
