3 namespace Friendica\Util;
6 * Util class for filesystem manipulation
11 * @var string a error message
13 private $errorMessage;
16 * Creates a directory based on a file, which gets accessed
18 * @param string $file The file
20 * @return string The directory name (empty if no directory is found, like urls)
22 public function createDir(string $file)
25 $pos = strpos($file, '://');
28 $dirname = realpath(dirname($file));
31 if (substr($file, 0, 7) === 'file://') {
32 $dirname = realpath(dirname(substr($file, 7)));
35 if (isset($dirname) && !is_dir($dirname)) {
36 set_error_handler([$this, 'customErrorHandler']);
37 $status = mkdir($dirname, 0777, true);
38 restore_error_handler();
40 if (!$status && !is_dir($dirname)) {
41 throw new \UnexpectedValueException(sprintf('Directory "%s" cannot get created: ' . $this->errorMessage, $dirname));
45 } elseif (isset($dirname) && is_dir($dirname)) {
53 * Creates a stream based on a URL (could be a local file or a real URL)
55 * @param string $url The file/url
57 * @return false|resource the open stream ressource
59 public function createStream(string $url)
61 $directory = $this->createDir($url);
62 set_error_handler([$this, 'customErrorHandler']);
63 if (!empty($directory)) {
64 $url = $directory . DIRECTORY_SEPARATOR . pathinfo($url, PATHINFO_BASENAME);
67 $stream = fopen($url, 'ab');
68 restore_error_handler();
70 if (!is_resource($stream)) {
71 throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: ' . $this->errorMessage, $url));
77 private function customErrorHandler($code, $msg)
79 $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);