3 * @file src/Core/System.php
5 namespace Friendica\Core;
7 use Friendica\BaseObject;
8 use Friendica\Core\Logger;
9 use Friendica\Core\Renderer;
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 SSL_POLICY_SELFSIGN
29 * @return string Friendica server base URL
30 * @throws InternalServerErrorException
32 public static function baseUrl($ssl = false)
34 return self::getApp()->getBaseURL($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($orig_url)
47 return self::getApp()->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.
65 $previous = ['class' => '', 'function' => ''];
67 // The ignore list contains all functions that are only wrapper functions
68 $ignore = ['fetchUrl', 'call_user_func_array'];
70 while ($func = array_pop($trace)) {
71 if (!empty($func['class'])) {
72 // Don't show multiple calls from the "dba" class to show the essential parts of the callstack
73 if ((($previous['class'] != $func['class']) || ($func['class'] != 'Friendica\Database\DBA')) && ($previous['function'] != 'q')) {
74 $classparts = explode("\\", $func['class']);
75 $callstack[] = array_pop($classparts).'::'.$func['function'];
78 } elseif (!in_array($func['function'], $ignore)) {
79 $callstack[] = $func['function'];
86 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
87 $callstack2[] = array_pop($callstack);
90 return implode(', ', $callstack2);
95 * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
96 * of $st and an optional text <message> of $message and terminates the current process.
99 * @param string $message
102 public static function xmlExit($st, $message = '')
104 $result = ['status' => $st];
106 if ($message != '') {
107 $result['message'] = $message;
111 Logger::log('xml_status returning non_zero: ' . $st . " message=" . $message);
114 header("Content-type: text/xml");
116 $xmldata = ["result" => $result];
118 echo XML::fromArray($xmldata, $xml);
124 * @brief Send HTTP status header and exit.
126 * @param integer $val HTTP status result value
127 * @param array $description optional message
128 * 'title' => header title
129 * 'description' => optional message
130 * @throws InternalServerErrorException
132 public static function httpExit($val, $description = [])
136 if (!empty($description['title'])) {
137 $err = $description['title'];
140 '400' => L10n::t('Error 400 - Bad Request'),
141 '401' => L10n::t('Error 401 - Unauthorized'),
142 '403' => L10n::t('Error 403 - Forbidden'),
143 '404' => L10n::t('Error 404 - Not Found'),
144 '500' => L10n::t('Error 500 - Internal Server Error'),
145 '503' => L10n::t('Error 503 - Service Unavailable'),
147 $err = defaults($title, $val, 'Error ' . $val);
148 $description['title'] = $err;
150 if (empty($description['description'])) {
151 // Explanations are taken from https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
153 '400' => L10n::t('The server cannot or will not process the request due to an apparent client error.'),
154 '401' => L10n::t('Authentication is required and has failed or has not yet been provided.'),
155 '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.'),
156 '404' => L10n::t('The requested resource could not be found but may be available in the future.'),
157 '500' => L10n::t('An unexpected condition was encountered and no more specific message is suitable.'),
158 '503' => L10n::t('The server is currently unavailable (because it is overloaded or down for maintenance). Please try again later.'),
160 if (!empty($explanation[$val])) {
161 $description['description'] = $explanation[$val];
166 if ($val >= 200 && $val < 300) {
170 Logger::log('http_status_exit ' . $val);
171 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
173 if (isset($description["title"])) {
174 $tpl = Renderer::getMarkupTemplate('http_status.tpl');
175 echo Renderer::replaceMacros($tpl, ['$title' => $description["title"],
176 '$description' => defaults($description, 'description', '')]);
183 * @brief Encodes content to json.
185 * This function encodes an array to json format
186 * and adds an application/json HTTP header to the output.
187 * After finishing the process is getting killed.
189 * @param array $x The input content.
190 * @param string $content_type Type of the input (Default: 'application/json').
192 public static function jsonExit($x, $content_type = 'application/json') {
193 header("Content-type: $content_type");
194 echo json_encode($x);
199 * Generates a random string in the UUID format
201 * @param bool|string $prefix A given prefix (default is empty)
202 * @return string a generated UUID
205 public static function createUUID($prefix = '')
207 $guid = System::createGUID(32, $prefix);
208 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
212 * Generates a GUID with the given parameters
214 * @param int $size The size of the GUID (default is 16)
215 * @param bool|string $prefix A given prefix (default is empty)
216 * @return string a generated GUID
219 public static function createGUID($size = 16, $prefix = '')
221 if (is_bool($prefix) && !$prefix) {
223 } elseif (empty($prefix)) {
224 $prefix = hash('crc32', self::getApp()->getHostName());
227 while (strlen($prefix) < ($size - 13)) {
228 $prefix .= mt_rand();
232 $prefix = substr($prefix, 0, $size - 22);
233 return str_replace('.', '', uniqid($prefix, true));
235 $prefix = substr($prefix, 0, max($size - 13, 0));
236 return uniqid($prefix);
241 * Generates a process identifier for the logging
243 * @param string $prefix A given prefix
245 * @return string a generated process identifier
247 public static function processID($prefix)
249 // We aren't calling any other function here.
250 // Doing so could easily create an endless loop
251 $trailer = $prefix . ':' . getmypid() . ':';
252 return substr($trailer . uniqid('') . mt_rand(), 0, 26);
256 * Returns the current Load of the System
260 public static function currentLoad()
262 if (!function_exists('sys_getloadavg')) {
266 $load_arr = sys_getloadavg();
268 if (!is_array($load_arr)) {
272 return max($load_arr[0], $load_arr[1]);
276 * Redirects to an external URL (fully qualified URL)
277 * If you want to route relative to the current Friendica base, use App->internalRedirect()
279 * @param string $url The new Location to redirect
280 * @throws InternalServerErrorException If the URL is not fully qualified
282 public static function externalRedirect($url)
284 if (empty(parse_url($url, PHP_URL_SCHEME))) {
285 throw new InternalServerErrorException("'$url' is not a fully qualified URL, please use App->internalRedirect() instead");
288 header("Location: $url");
292 /// @todo Move the following functions from boot.php
295 function local_user()
296 function public_contact()
297 function remote_user()
300 function is_site_admin()
301 function get_server()
302 function get_temppath()
303 function get_cachefile($file, $writemode = true)
304 function get_itemcachepath()
305 function get_spoolpath()