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 * Contains the class with system relevant stuff
24 * Returns a string with a callstack. Can be used for logging.
26 * @param integer $depth optional, default 4
29 public static function callstack($depth = 4)
31 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
33 // We remove the first two items from the list since they contain data that we don't need.
38 $previous = ['class' => '', 'function' => ''];
40 // The ignore list contains all functions that are only wrapper functions
41 $ignore = ['fetchUrl', 'call_user_func_array'];
43 while ($func = array_pop($trace)) {
44 if (!empty($func['class'])) {
45 // Don't show multiple calls from the "dba" class to show the essential parts of the callstack
46 if ((($previous['class'] != $func['class']) || ($func['class'] != 'Friendica\Database\DBA')) && ($previous['function'] != 'q')) {
47 $classparts = explode("\\", $func['class']);
48 $callstack[] = array_pop($classparts).'::'.$func['function'];
51 } elseif (!in_array($func['function'], $ignore)) {
52 $callstack[] = $func['function'];
59 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
60 $callstack2[] = array_pop($callstack);
63 return implode(', ', $callstack2);
68 * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
69 * of $st and an optional text <message> of $message and terminates the current process.
72 * @param string $message
75 public static function xmlExit($st, $message = '')
77 $result = ['status' => $st];
80 $result['message'] = $message;
84 Logger::log('xml_status returning non_zero: ' . $st . " message=" . $message);
87 header("Content-type: text/xml");
89 $xmldata = ["result" => $result];
91 echo XML::fromArray($xmldata, $xml);
97 * Send HTTP status header and exit.
99 * @param integer $val HTTP status result value
100 * @param string $message Error message. Optional.
101 * @param string $content Response body. Optional.
104 public static function httpExit($val, $message = '', $content = '')
106 Logger::log('http_status_exit ' . $val);
107 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $message);
114 public static function jsonError($httpCode, $data, $content_type = 'application/json')
116 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $httpCode);
117 self::jsonExit($data, $content_type);
121 * Encodes content to json.
123 * This function encodes an array to json format
124 * and adds an application/json HTTP header to the output.
125 * After finishing the process is getting killed.
127 * @param mixed $x The input content.
128 * @param string $content_type Type of the input (Default: 'application/json').
130 public static function jsonExit($x, $content_type = 'application/json') {
131 header("Content-type: $content_type");
132 echo json_encode($x);
137 * Generates a random string in the UUID format
139 * @param bool|string $prefix A given prefix (default is empty)
140 * @return string a generated UUID
143 public static function createUUID($prefix = '')
145 $guid = System::createGUID(32, $prefix);
146 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
150 * Generates a GUID with the given parameters
152 * @param int $size The size of the GUID (default is 16)
153 * @param bool|string $prefix A given prefix (default is empty)
154 * @return string a generated GUID
157 public static function createGUID($size = 16, $prefix = '')
159 if (is_bool($prefix) && !$prefix) {
161 } elseif (empty($prefix)) {
162 $prefix = hash('crc32', DI::baseUrl()->getHostname());
165 while (strlen($prefix) < ($size - 13)) {
166 $prefix .= mt_rand();
170 $prefix = substr($prefix, 0, $size - 22);
171 return str_replace('.', '', uniqid($prefix, true));
173 $prefix = substr($prefix, 0, max($size - 13, 0));
174 return uniqid($prefix);
179 * Returns the current Load of the System
183 public static function currentLoad()
185 if (!function_exists('sys_getloadavg')) {
189 $load_arr = sys_getloadavg();
191 if (!is_array($load_arr)) {
195 return max($load_arr[0], $load_arr[1]);
199 * Redirects to an external URL (fully qualified URL)
200 * If you want to route relative to the current Friendica base, use App->internalRedirect()
202 * @param string $url The new Location to redirect
203 * @param int $code The redirection code, which is used (Default is 302)
205 * @throws InternalServerErrorException If the URL is not fully qualified
207 public static function externalRedirect($url, $code = 302)
209 if (empty(parse_url($url, PHP_URL_SCHEME))) {
210 throw new InternalServerErrorException("'$url' is not a fully qualified URL, please use App->internalRedirect() instead");
215 // this is the default code for a REDIRECT
216 // We don't need a extra header here
219 header('HTTP/1.1 301 Moved Permanently');
222 header('HTTP/1.1 307 Temporary Redirect');
226 header("Location: $url");
231 * Returns the system user that is executing the script
233 * This mostly returns something like "www-data".
235 * @return string system username
237 public static function getUser()
239 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
243 $processUser = posix_getpwuid(posix_geteuid());
244 return $processUser['name'];
248 * Checks if a given directory is usable for the system
251 * @param bool $check_writable
253 * @return boolean the directory is usable
255 public static function isDirectoryUsable($directory, $check_writable = true)
257 if ($directory == '') {
258 Logger::log('Directory is empty. This shouldn\'t happen.', Logger::DEBUG);
262 if (!file_exists($directory)) {
263 Logger::log('Path "' . $directory . '" does not exist for user ' . static::getUser(), Logger::DEBUG);
267 if (is_file($directory)) {
268 Logger::log('Path "' . $directory . '" is a file for user ' . static::getUser(), Logger::DEBUG);
272 if (!is_dir($directory)) {
273 Logger::log('Path "' . $directory . '" is not a directory for user ' . static::getUser(), Logger::DEBUG);
277 if ($check_writable && !is_writable($directory)) {
278 Logger::log('Path "' . $directory . '" is not writable for user ' . static::getUser(), Logger::DEBUG);
285 /// @todo Move the following functions from boot.php
287 function local_user()
288 function public_contact()
289 function remote_user()
292 function is_site_admin()
293 function get_temppath()
294 function get_cachefile($file, $writemode = true)
295 function get_itemcachepath()
296 function get_spoolpath()