3 * @copyright Copyright (C) 2010-2023, the Friendica project
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\Core\Logger\Util;
24 use Friendica\Core\Logger\Exception\LoggerUnusableException;
27 * Util class for filesystem manipulation for Logger classes
32 * @var string a error message
34 private $errorMessage;
37 * Creates a directory based on a file, which gets accessed
39 * @param string $file The file
41 * @return string The directory name (empty if no directory is found, like urls)
43 * @throws LoggerUnusableException
45 public function createDir(string $file): string
48 $pos = strpos($file, '://');
51 $dirname = realpath(dirname($file));
54 if (substr($file, 0, 7) === 'file://') {
55 $dirname = realpath(dirname(substr($file, 7)));
58 if (isset($dirname) && !is_dir($dirname)) {
59 set_error_handler([$this, 'customErrorHandler']);
60 $status = mkdir($dirname, 0777, true);
61 restore_error_handler();
63 if (!$status && !is_dir($dirname)) {
64 throw new LoggerUnusableException(sprintf('Directory "%s" cannot get created: ' . $this->errorMessage, $dirname));
68 } elseif (isset($dirname) && is_dir($dirname)) {
76 * Creates a stream based on a URL (could be a local file or a real URL)
78 * @param string $url The file/url
80 * @return resource the open stream resource
82 * @throws LoggerUnusableException
84 public function createStream(string $url)
86 $directory = $this->createDir($url);
87 set_error_handler([$this, 'customErrorHandler']);
88 if (!empty($directory)) {
89 $url = $directory . DIRECTORY_SEPARATOR . pathinfo($url, PATHINFO_BASENAME);
92 $stream = fopen($url, 'ab');
93 restore_error_handler();
95 if (!is_resource($stream)) {
96 throw new LoggerUnusableException(sprintf('The stream or file "%s" could not be opened: ' . $this->errorMessage, $url));
102 private function customErrorHandler($code, $msg)
104 $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);