3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Util;
25 * Util class for filesystem manipulation
30 * @var string a error message
32 private $errorMessage;
35 * Creates a directory based on a file, which gets accessed
37 * @param string $file The file
39 * @return string The directory name (empty if no directory is found, like urls)
41 public function createDir(string $file)
44 $pos = strpos($file, '://');
47 $dirname = realpath(dirname($file));
50 if (substr($file, 0, 7) === 'file://') {
51 $dirname = realpath(dirname(substr($file, 7)));
54 if (isset($dirname) && !is_dir($dirname)) {
55 set_error_handler([$this, 'customErrorHandler']);
56 $status = mkdir($dirname, 0777, true);
57 restore_error_handler();
59 if (!$status && !is_dir($dirname)) {
60 throw new \UnexpectedValueException(sprintf('Directory "%s" cannot get created: ' . $this->errorMessage, $dirname));
64 } elseif (isset($dirname) && is_dir($dirname)) {
72 * Creates a stream based on a URL (could be a local file or a real URL)
74 * @param string $url The file/url
76 * @return false|resource the open stream ressource
78 public function createStream(string $url)
80 $directory = $this->createDir($url);
81 set_error_handler([$this, 'customErrorHandler']);
82 if (!empty($directory)) {
83 $url = $directory . DIRECTORY_SEPARATOR . pathinfo($url, PATHINFO_BASENAME);
86 $stream = fopen($url, 'ab');
87 restore_error_handler();
89 if (!is_resource($stream)) {
90 throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: ' . $this->errorMessage, $url));
96 private function customErrorHandler($code, $msg)
98 $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);