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 BaseURL::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 string $message Error message. Optional.
125 * @param string $content Response body. Optional.
128 public static function httpExit($val, $message = '', $content = '')
130 Logger::log('http_status_exit ' . $val);
131 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $message);
138 public static function jsonError($httpCode, $data, $content_type = 'application/json')
140 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $httpCode);
141 self::jsonExit($data, $content_type);
145 * @brief Encodes content to json.
147 * This function encodes an array to json format
148 * and adds an application/json HTTP header to the output.
149 * After finishing the process is getting killed.
151 * @param array $x The input content.
152 * @param string $content_type Type of the input (Default: 'application/json').
154 public static function jsonExit($x, $content_type = 'application/json') {
155 header("Content-type: $content_type");
156 echo json_encode($x);
161 * Generates a random string in the UUID format
163 * @param bool|string $prefix A given prefix (default is empty)
164 * @return string a generated UUID
167 public static function createUUID($prefix = '')
169 $guid = System::createGUID(32, $prefix);
170 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
174 * Generates a GUID with the given parameters
176 * @param int $size The size of the GUID (default is 16)
177 * @param bool|string $prefix A given prefix (default is empty)
178 * @return string a generated GUID
181 public static function createGUID($size = 16, $prefix = '')
183 if (is_bool($prefix) && !$prefix) {
185 } elseif (empty($prefix)) {
186 $prefix = hash('crc32', self::getApp()->getHostName());
189 while (strlen($prefix) < ($size - 13)) {
190 $prefix .= mt_rand();
194 $prefix = substr($prefix, 0, $size - 22);
195 return str_replace('.', '', uniqid($prefix, true));
197 $prefix = substr($prefix, 0, max($size - 13, 0));
198 return uniqid($prefix);
203 * Returns the current Load of the System
207 public static function currentLoad()
209 if (!function_exists('sys_getloadavg')) {
213 $load_arr = sys_getloadavg();
215 if (!is_array($load_arr)) {
219 return max($load_arr[0], $load_arr[1]);
223 * Redirects to an external URL (fully qualified URL)
224 * If you want to route relative to the current Friendica base, use App->internalRedirect()
226 * @param string $url The new Location to redirect
227 * @param int $code The redirection code, which is used (Default is 302)
229 * @throws InternalServerErrorException If the URL is not fully qualified
231 public static function externalRedirect($url, $code = 302)
233 if (empty(parse_url($url, PHP_URL_SCHEME))) {
234 throw new InternalServerErrorException("'$url' is not a fully qualified URL, please use App->internalRedirect() instead");
239 // this is the default code for a REDIRECT
240 // We don't need a extra header here
243 header('HTTP/1.1 301 Moved Permanently');
247 header("Location: $url");
252 * @brief Returns the system user that is executing the script
254 * This mostly returns something like "www-data".
256 * @return string system username
258 public static function getUser()
260 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
264 $processUser = posix_getpwuid(posix_geteuid());
265 return $processUser['name'];
269 * @brief Checks if a given directory is usable for the system
272 * @param bool $check_writable
274 * @return boolean the directory is usable
276 public static function isDirectoryUsable($directory, $check_writable = true)
278 if ($directory == '') {
279 Logger::log('Directory is empty. This shouldn\'t happen.', Logger::DEBUG);
283 if (!file_exists($directory)) {
284 Logger::log('Path "' . $directory . '" does not exist for user ' . static::getUser(), Logger::DEBUG);
288 if (is_file($directory)) {
289 Logger::log('Path "' . $directory . '" is a file for user ' . static::getUser(), Logger::DEBUG);
293 if (!is_dir($directory)) {
294 Logger::log('Path "' . $directory . '" is not a directory for user ' . static::getUser(), Logger::DEBUG);
298 if ($check_writable && !is_writable($directory)) {
299 Logger::log('Path "' . $directory . '" is not writable for user ' . static::getUser(), Logger::DEBUG);
306 /// @todo Move the following functions from boot.php
309 function local_user()
310 function public_contact()
311 function remote_user()
314 function is_site_admin()
315 function get_server()
316 function get_temppath()
317 function get_cachefile($file, $writemode = true)
318 function get_itemcachepath()
319 function get_spoolpath()