3 * @file src/Core/System.php
5 namespace Friendica\Core;
7 use Friendica\BaseObject;
8 use Friendica\Network\HTTPException\InternalServerErrorException;
9 use Friendica\Util\XML;
12 * @file include/Core/System.php
14 * @brief Contains the class with system relevant stuff
19 * @brief System methods
21 class System extends BaseObject
24 * @brief Retrieves the Friendica instance base URL
26 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
27 * @return string Friendica server base URL
28 * @throws InternalServerErrorException
30 public static function baseUrl($ssl = false)
32 return self::getApp()->getBaseURL($ssl);
36 * @brief Removes the baseurl from an url. This avoids some mixed content problems.
38 * @param string $orig_url The url to be cleaned
40 * @return string The cleaned url
43 public static function removedBaseUrl($orig_url)
45 return self::getApp()->removeBaseURL($orig_url);
49 * @brief Returns a string with a callstack. Can be used for logging.
50 * @param integer $depth optional, default 4
53 public static function callstack($depth = 4)
55 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
57 // We remove the first two items from the list since they contain data that we don't need.
62 $previous = ['class' => '', 'function' => ''];
64 // The ignore list contains all functions that are only wrapper functions
65 $ignore = ['fetchUrl', 'call_user_func_array'];
67 while ($func = array_pop($trace)) {
68 if (!empty($func['class'])) {
69 // Don't show multiple calls from the "dba" class to show the essential parts of the callstack
70 if ((($previous['class'] != $func['class']) || ($func['class'] != 'Friendica\Database\DBA')) && ($previous['function'] != 'q')) {
71 $classparts = explode("\\", $func['class']);
72 $callstack[] = array_pop($classparts).'::'.$func['function'];
75 } elseif (!in_array($func['function'], $ignore)) {
76 $callstack[] = $func['function'];
83 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
84 $callstack2[] = array_pop($callstack);
87 return implode(', ', $callstack2);
92 * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
93 * of $st and an optional text <message> of $message and terminates the current process.
96 * @param string $message
99 public static function xmlExit($st, $message = '')
101 $result = ['status' => $st];
103 if ($message != '') {
104 $result['message'] = $message;
108 Logger::log('xml_status returning non_zero: ' . $st . " message=" . $message);
111 header("Content-type: text/xml");
113 $xmldata = ["result" => $result];
115 echo XML::fromArray($xmldata, $xml);
121 * @brief Send HTTP status header and exit.
123 * @param integer $val HTTP status result value
124 * @param array $description optional message
125 * 'title' => header title
126 * 'description' => optional message
127 * @throws InternalServerErrorException
129 public static function httpExit($val, $description = [])
133 if (!empty($description['title'])) {
134 $err = $description['title'];
137 '400' => L10n::t('Error 400 - Bad Request'),
138 '401' => L10n::t('Error 401 - Unauthorized'),
139 '403' => L10n::t('Error 403 - Forbidden'),
140 '404' => L10n::t('Error 404 - Not Found'),
141 '500' => L10n::t('Error 500 - Internal Server Error'),
142 '503' => L10n::t('Error 503 - Service Unavailable'),
144 $err = defaults($title, $val, 'Error ' . $val);
145 $description['title'] = $err;
147 if (empty($description['description'])) {
148 // Explanations are taken from https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
150 '400' => L10n::t('The server cannot or will not process the request due to an apparent client error.'),
151 '401' => L10n::t('Authentication is required and has failed or has not yet been provided.'),
152 '403' => L10n::t('The request was valid, but the server is refusing action. The user might not have the necessary permissions for a resource, or may need an account.'),
153 '404' => L10n::t('The requested resource could not be found but may be available in the future.'),
154 '500' => L10n::t('An unexpected condition was encountered and no more specific message is suitable.'),
155 '503' => L10n::t('The server is currently unavailable (because it is overloaded or down for maintenance). Please try again later.'),
157 if (!empty($explanation[$val])) {
158 $description['description'] = $explanation[$val];
163 if ($val >= 200 && $val < 300) {
167 Logger::log('http_status_exit ' . $val);
168 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
170 if (isset($description["title"])) {
171 $tpl = Renderer::getMarkupTemplate('http_status.tpl');
172 echo Renderer::replaceMacros($tpl, ['$title' => $description["title"],
173 '$description' => defaults($description, 'description', '')]);
180 * @brief Encodes content to json.
182 * This function encodes an array to json format
183 * and adds an application/json HTTP header to the output.
184 * After finishing the process is getting killed.
186 * @param array $x The input content.
187 * @param string $content_type Type of the input (Default: 'application/json').
189 public static function jsonExit($x, $content_type = 'application/json') {
190 header("Content-type: $content_type");
191 echo json_encode($x);
196 * Generates a random string in the UUID format
198 * @param bool|string $prefix A given prefix (default is empty)
199 * @return string a generated UUID
202 public static function createUUID($prefix = '')
204 $guid = System::createGUID(32, $prefix);
205 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
209 * Generates a GUID with the given parameters
211 * @param int $size The size of the GUID (default is 16)
212 * @param bool|string $prefix A given prefix (default is empty)
213 * @return string a generated GUID
216 public static function createGUID($size = 16, $prefix = '')
218 if (is_bool($prefix) && !$prefix) {
220 } elseif (empty($prefix)) {
221 $prefix = hash('crc32', self::getApp()->getHostName());
224 while (strlen($prefix) < ($size - 13)) {
225 $prefix .= mt_rand();
229 $prefix = substr($prefix, 0, $size - 22);
230 return str_replace('.', '', uniqid($prefix, true));
232 $prefix = substr($prefix, 0, max($size - 13, 0));
233 return uniqid($prefix);
238 * Generates a process identifier for the logging
240 * @param string $prefix A given prefix
242 * @return string a generated process identifier
244 public static function processID($prefix)
246 // We aren't calling any other function here.
247 // Doing so could easily create an endless loop
248 $trailer = $prefix . ':' . getmypid() . ':';
249 return substr($trailer . uniqid('') . mt_rand(), 0, 26);
253 * Returns the current Load of the System
257 public static function currentLoad()
259 if (!function_exists('sys_getloadavg')) {
263 $load_arr = sys_getloadavg();
265 if (!is_array($load_arr)) {
269 return max($load_arr[0], $load_arr[1]);
273 * Redirects to an external URL (fully qualified URL)
274 * If you want to route relative to the current Friendica base, use App->internalRedirect()
276 * @param string $url The new Location to redirect
277 * @throws InternalServerErrorException If the URL is not fully qualified
279 public static function externalRedirect($url)
281 if (empty(parse_url($url, PHP_URL_SCHEME))) {
282 throw new InternalServerErrorException("'$url' is not a fully qualified URL, please use App->internalRedirect() instead");
285 header("Location: $url");
290 * @brief Returns the system user that is executing the script
292 * This mostly returns something like "www-data".
294 * @return string system username
296 public static function getUser()
298 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
302 $processUser = posix_getpwuid(posix_geteuid());
303 return $processUser['name'];
307 * @brief Checks if a given directory is usable for the system
310 * @param bool $check_writable
312 * @return boolean the directory is usable
314 public static function isDirectoryUsable($directory, $check_writable = true)
316 if ($directory == '') {
317 Logger::log('Directory is empty. This shouldn\'t happen.', Logger::DEBUG);
321 if (!file_exists($directory)) {
322 Logger::log('Path "' . $directory . '" does not exist for user ' . static::getUser(), Logger::DEBUG);
326 if (is_file($directory)) {
327 Logger::log('Path "' . $directory . '" is a file for user ' . static::getUser(), Logger::DEBUG);
331 if (!is_dir($directory)) {
332 Logger::log('Path "' . $directory . '" is not a directory for user ' . static::getUser(), Logger::DEBUG);
336 if ($check_writable && !is_writable($directory)) {
337 Logger::log('Path "' . $directory . '" is not writable for user ' . static::getUser(), Logger::DEBUG);
344 /// @todo Move the following functions from boot.php
347 function local_user()
348 function public_contact()
349 function remote_user()
352 function is_site_admin()
353 function get_server()
354 function get_temppath()
355 function get_cachefile($file, $writemode = true)
356 function get_itemcachepath()
357 function get_spoolpath()