3 * @file src/Core/System.php
5 namespace Friendica\Core;
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
24 * @brief Retrieves the Friendica instance base URL
26 * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
27 * @return string Friendica server base URL
29 public static function baseUrl($ssl = false)
31 return DI::baseUrl()->get($ssl);
35 * @brief Removes the baseurl from an url. This avoids some mixed content problems.
37 * @param string $orig_url The url to be cleaned
39 * @return string The cleaned url
42 public static function removedBaseUrl(string $orig_url)
44 return DI::baseUrl()->remove($orig_url);
48 * @brief Returns a string with a callstack. Can be used for logging.
49 * @param integer $depth optional, default 4
52 public static function callstack($depth = 4)
54 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
56 // We remove the first two items from the list since they contain data that we don't need.
61 $previous = ['class' => '', 'function' => ''];
63 // The ignore list contains all functions that are only wrapper functions
64 $ignore = ['fetchUrl', 'call_user_func_array'];
66 while ($func = array_pop($trace)) {
67 if (!empty($func['class'])) {
68 // Don't show multiple calls from the "dba" class to show the essential parts of the callstack
69 if ((($previous['class'] != $func['class']) || ($func['class'] != 'Friendica\Database\DBA')) && ($previous['function'] != 'q')) {
70 $classparts = explode("\\", $func['class']);
71 $callstack[] = array_pop($classparts).'::'.$func['function'];
74 } elseif (!in_array($func['function'], $ignore)) {
75 $callstack[] = $func['function'];
82 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
83 $callstack2[] = array_pop($callstack);
86 return implode(', ', $callstack2);
91 * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
92 * of $st and an optional text <message> of $message and terminates the current process.
95 * @param string $message
98 public static function xmlExit($st, $message = '')
100 $result = ['status' => $st];
102 if ($message != '') {
103 $result['message'] = $message;
107 Logger::log('xml_status returning non_zero: ' . $st . " message=" . $message);
110 header("Content-type: text/xml");
112 $xmldata = ["result" => $result];
114 echo XML::fromArray($xmldata, $xml);
120 * @brief Send HTTP status header and exit.
122 * @param integer $val HTTP status result value
123 * @param string $message Error message. Optional.
124 * @param string $content Response body. Optional.
127 public static function httpExit($val, $message = '', $content = '')
129 Logger::log('http_status_exit ' . $val);
130 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $message);
137 public static function jsonError($httpCode, $data, $content_type = 'application/json')
139 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $httpCode);
140 self::jsonExit($data, $content_type);
144 * @brief Encodes content to json.
146 * This function encodes an array to json format
147 * and adds an application/json HTTP header to the output.
148 * After finishing the process is getting killed.
150 * @param mixed $x The input content.
151 * @param string $content_type Type of the input (Default: 'application/json').
153 public static function jsonExit($x, $content_type = 'application/json') {
154 header("Content-type: $content_type");
155 echo json_encode($x);
160 * Generates a random string in the UUID format
162 * @param bool|string $prefix A given prefix (default is empty)
163 * @return string a generated UUID
166 public static function createUUID($prefix = '')
168 $guid = System::createGUID(32, $prefix);
169 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
173 * Generates a GUID with the given parameters
175 * @param int $size The size of the GUID (default is 16)
176 * @param bool|string $prefix A given prefix (default is empty)
177 * @return string a generated GUID
180 public static function createGUID($size = 16, $prefix = '')
182 if (is_bool($prefix) && !$prefix) {
184 } elseif (empty($prefix)) {
185 $prefix = hash('crc32', DI::baseUrl()->getHostname());
188 while (strlen($prefix) < ($size - 13)) {
189 $prefix .= mt_rand();
193 $prefix = substr($prefix, 0, $size - 22);
194 return str_replace('.', '', uniqid($prefix, true));
196 $prefix = substr($prefix, 0, max($size - 13, 0));
197 return uniqid($prefix);
202 * Returns the current Load of the System
206 public static function currentLoad()
208 if (!function_exists('sys_getloadavg')) {
212 $load_arr = sys_getloadavg();
214 if (!is_array($load_arr)) {
218 return max($load_arr[0], $load_arr[1]);
222 * Redirects to an external URL (fully qualified URL)
223 * If you want to route relative to the current Friendica base, use App->internalRedirect()
225 * @param string $url The new Location to redirect
226 * @param int $code The redirection code, which is used (Default is 302)
228 * @throws InternalServerErrorException If the URL is not fully qualified
230 public static function externalRedirect($url, $code = 302)
232 if (empty(parse_url($url, PHP_URL_SCHEME))) {
233 throw new InternalServerErrorException("'$url' is not a fully qualified URL, please use App->internalRedirect() instead");
238 // this is the default code for a REDIRECT
239 // We don't need a extra header here
242 header('HTTP/1.1 301 Moved Permanently');
245 header('HTTP/1.1 307 Temporary Redirect');
249 header("Location: $url");
254 * @brief Returns the system user that is executing the script
256 * This mostly returns something like "www-data".
258 * @return string system username
260 public static function getUser()
262 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
266 $processUser = posix_getpwuid(posix_geteuid());
267 return $processUser['name'];
271 * @brief Checks if a given directory is usable for the system
274 * @param bool $check_writable
276 * @return boolean the directory is usable
278 public static function isDirectoryUsable($directory, $check_writable = true)
280 if ($directory == '') {
281 Logger::log('Directory is empty. This shouldn\'t happen.', Logger::DEBUG);
285 if (!file_exists($directory)) {
286 Logger::log('Path "' . $directory . '" does not exist for user ' . static::getUser(), Logger::DEBUG);
290 if (is_file($directory)) {
291 Logger::log('Path "' . $directory . '" is a file for user ' . static::getUser(), Logger::DEBUG);
295 if (!is_dir($directory)) {
296 Logger::log('Path "' . $directory . '" is not a directory for user ' . static::getUser(), Logger::DEBUG);
300 if ($check_writable && !is_writable($directory)) {
301 Logger::log('Path "' . $directory . '" is not writable for user ' . static::getUser(), Logger::DEBUG);
308 /// @todo Move the following functions from boot.php
311 function local_user()
312 function public_contact()
313 function remote_user()
316 function is_site_admin()
317 function get_server()
318 function get_temppath()
319 function get_cachefile($file, $writemode = true)
320 function get_itemcachepath()
321 function get_spoolpath()