ILIAS  release_9 Revision v9.13-25-g2c18ec4c24f
PathHelper.php
Go to the documentation of this file.
1 <?php
2 
19 declare(strict_types=1);
20 
22 
27 
31 trait PathHelper
32 {
33  protected function isPathIgnored(string $path, Options $options): bool
34  {
35  $regex = '(' . implode('|', $options->getIgnoredPathSnippets()) . ')';
36  return preg_match($regex, $path) > 0;
37  }
38 
39  protected function ensureDirectorySeperator(string $path): string
40  {
41  return rtrim($path, "/") . "/";
42  }
43 
47  private function realpath(string $path): string
48  {
49  $path = array_reduce(explode('/', $path), function ($a, $b) {
50  if ($a === null) {
51  $a = "/";
52  }
53  if ($b === "" || $b === ".") {
54  return $a;
55  }
56  if ($b === "..") {
57  return dirname($a);
58  }
59 
60  return preg_replace("/\/+/", "/", "$a/$b");
61  });
62  return trim($path, "/");
63  }
64 
65  protected function normalizePath($path, $separator = '\\/'): string
66  {
67  // if the ZIP name ist just a ../name.zip we stop here since it's hard to generate to real path for that.
68  // consumers must adopt their code
69  if (str_starts_with($path, '..')) {
70  throw new \InvalidArgumentException('The ZIP name must not start with ../. Please provide a real path for the output file.');
71  }
72 
73  // we prepend a ./ to paths without a leading slash to make sure that the path is relative
74  if (!str_starts_with($path, './')) {
75  $path = './' . $path;
76  }
77 
78  if (str_starts_with($path, './') && ($realpath = realpath($path)) !== false) {
79  $path = $realpath;
80  }
81 
82  $normalized = preg_replace('#\p{C}+|^\./#u', '', $path);
83  $normalized = preg_replace('#/\.(?=/)|^\./|\./$#', '', $normalized);
84  $regex = '#\/*[^/\.]+/\.\.#Uu';
85 
86  while (preg_match($regex, $normalized)) {
87  $normalized = preg_replace($regex, '', $normalized);
88  }
89 
90  if (preg_match('#/\.{2}|\.{2}/#', $normalized)) {
91  throw new \LogicException(
92  'Path is outside of the defined root, path: [' . $path . '], resolved: [' . $normalized . ']'
93  );
94  }
95 
96  // We prepend a ./ to paths without a leading slash to make sure that the path is relative
97  if (!str_starts_with($normalized, './') && !str_starts_with($normalized, '/')) {
98  $normalized = './' . $normalized;
99  }
100 
101  // Check if this is a path we can use
102  LegacyPathHelper::deriveLocationFrom($normalized); // Throws exception if path is invalid
103 
104  return $normalized;
105  }
106 }
$path
Definition: ltiservices.php:32
static deriveLocationFrom(string $absolute_path)
$a
thx to https://mlocati.github.io/php-cs-fixer-configurator for the examples