3 * @file src/Core/System.php
5 namespace Friendica\Core;
7 use Friendica\App\BaseURL;
8 use Friendica\BaseObject;
10 use Friendica\Network\HTTPException\InternalServerErrorException;
11 use Friendica\Util\XML;
14 * @file include/Core/System.php
16 * @brief Contains the class with system relevant stuff
21 * @brief System methods
23 class System extends BaseObject
26 * @brief Retrieves the Friendica instance base URL
28 * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
29 * @return string Friendica server base URL
30 * @throws InternalServerErrorException
32 public static function baseUrl($ssl = false)
34 return self::getClass(BaseURL::class)->get($ssl);
38 * @brief Removes the baseurl from an url. This avoids some mixed content problems.
40 * @param string $orig_url The url to be cleaned
42 * @return string The cleaned url
45 public static function removedBaseUrl(string $orig_url)
47 return DI::app()->removeBaseURL($orig_url);
51 * @brief Returns a string with a callstack. Can be used for logging.
52 * @param integer $depth optional, default 4
55 public static function callstack($depth = 4)
57 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
59 // We remove the first two items from the list since they contain data that we don't need.
64 $previous = ['class' => '', 'function' => ''];
66 // The ignore list contains all functions that are only wrapper functions
67 $ignore = ['fetchUrl', 'call_user_func_array'];
69 while ($func = array_pop($trace)) {
70 if (!empty($func['class'])) {
71 // Don't show multiple calls from the "dba" class to show the essential parts of the callstack
72 if ((($previous['class'] != $func['class']) || ($func['class'] != 'Friendica\Database\DBA')) && ($previous['function'] != 'q')) {
73 $classparts = explode("\\", $func['class']);
74 $callstack[] = array_pop($classparts).'::'.$func['function'];
77 } elseif (!in_array($func['function'], $ignore)) {
78 $callstack[] = $func['function'];
85 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
86 $callstack2[] = array_pop($callstack);
89 return implode(', ', $callstack2);
94 * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
95 * of $st and an optional text <message> of $message and terminates the current process.
98 * @param string $message
101 public static function xmlExit($st, $message = '')
103 $result = ['status' => $st];
105 if ($message != '') {
106 $result['message'] = $message;
110 Logger::log('xml_status returning non_zero: ' . $st . " message=" . $message);
113 header("Content-type: text/xml");
115 $xmldata = ["result" => $result];
117 echo XML::fromArray($xmldata, $xml);
123 * @brief Send HTTP status header and exit.
125 * @param integer $val HTTP status result value
126 * @param string $message Error message. Optional.
127 * @param string $content Response body. Optional.
130 public static function httpExit($val, $message = '', $content = '')
132 Logger::log('http_status_exit ' . $val);
133 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $message);
140 public static function jsonError($httpCode, $data, $content_type = 'application/json')
142 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $httpCode);
143 self::jsonExit($data, $content_type);
147 * @brief Encodes content to json.
149 * This function encodes an array to json format
150 * and adds an application/json HTTP header to the output.
151 * After finishing the process is getting killed.
153 * @param mixed $x The input content.
154 * @param string $content_type Type of the input (Default: 'application/json').
156 public static function jsonExit($x, $content_type = 'application/json') {
157 header("Content-type: $content_type");
158 echo json_encode($x);
163 * Generates a random string in the UUID format
165 * @param bool|string $prefix A given prefix (default is empty)
166 * @return string a generated UUID
169 public static function createUUID($prefix = '')
171 $guid = System::createGUID(32, $prefix);
172 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
176 * Generates a GUID with the given parameters
178 * @param int $size The size of the GUID (default is 16)
179 * @param bool|string $prefix A given prefix (default is empty)
180 * @return string a generated GUID
183 public static function createGUID($size = 16, $prefix = '')
185 if (is_bool($prefix) && !$prefix) {
187 } elseif (empty($prefix)) {
188 $prefix = hash('crc32', DI::app()->getHostName());
191 while (strlen($prefix) < ($size - 13)) {
192 $prefix .= mt_rand();
196 $prefix = substr($prefix, 0, $size - 22);
197 return str_replace('.', '', uniqid($prefix, true));
199 $prefix = substr($prefix, 0, max($size - 13, 0));
200 return uniqid($prefix);
205 * Returns the current Load of the System
209 public static function currentLoad()
211 if (!function_exists('sys_getloadavg')) {
215 $load_arr = sys_getloadavg();
217 if (!is_array($load_arr)) {
221 return max($load_arr[0], $load_arr[1]);
225 * Redirects to an external URL (fully qualified URL)
226 * If you want to route relative to the current Friendica base, use App->internalRedirect()
228 * @param string $url The new Location to redirect
229 * @param int $code The redirection code, which is used (Default is 302)
231 * @throws InternalServerErrorException If the URL is not fully qualified
233 public static function externalRedirect($url, $code = 302)
235 if (empty(parse_url($url, PHP_URL_SCHEME))) {
236 throw new InternalServerErrorException("'$url' is not a fully qualified URL, please use App->internalRedirect() instead");
241 // this is the default code for a REDIRECT
242 // We don't need a extra header here
245 header('HTTP/1.1 301 Moved Permanently');
248 header('HTTP/1.1 307 Temporary Redirect');
252 header("Location: $url");
257 * @brief Returns the system user that is executing the script
259 * This mostly returns something like "www-data".
261 * @return string system username
263 public static function getUser()
265 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
269 $processUser = posix_getpwuid(posix_geteuid());
270 return $processUser['name'];
274 * @brief Checks if a given directory is usable for the system
277 * @param bool $check_writable
279 * @return boolean the directory is usable
281 public static function isDirectoryUsable($directory, $check_writable = true)
283 if ($directory == '') {
284 Logger::log('Directory is empty. This shouldn\'t happen.', Logger::DEBUG);
288 if (!file_exists($directory)) {
289 Logger::log('Path "' . $directory . '" does not exist for user ' . static::getUser(), Logger::DEBUG);
293 if (is_file($directory)) {
294 Logger::log('Path "' . $directory . '" is a file for user ' . static::getUser(), Logger::DEBUG);
298 if (!is_dir($directory)) {
299 Logger::log('Path "' . $directory . '" is not a directory for user ' . static::getUser(), Logger::DEBUG);
303 if ($check_writable && !is_writable($directory)) {
304 Logger::log('Path "' . $directory . '" is not writable for user ' . static::getUser(), Logger::DEBUG);
311 /// @todo Move the following functions from boot.php
314 function local_user()
315 function public_contact()
316 function remote_user()
319 function is_site_admin()
320 function get_server()
321 function get_temppath()
322 function get_cachefile($file, $writemode = true)
323 function get_itemcachepath()
324 function get_spoolpath()