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
31 public static function baseUrl($ssl = false)
33 return self::getApp()->getBaseURL($ssl);
37 * @brief Removes the baseurl from an url. This avoids some mixed content problems.
39 * @param string $orig_url The url to be cleaned
41 * @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.
63 $previous = ['class' => '', 'function' => ''];
65 // The ignore list contains all functions that are only wrapper functions
66 $ignore = ['fetchUrl', 'call_user_func_array'];
68 while ($func = array_pop($trace)) {
69 if (!empty($func['class'])) {
70 // Don't show multiple calls from the "dba" class to show the essential parts of the callstack
71 if ((($previous['class'] != $func['class']) || ($func['class'] != 'Friendica\Database\DBA')) && ($previous['function'] != 'q')) {
72 $classparts = explode("\\", $func['class']);
73 $callstack[] = array_pop($classparts).'::'.$func['function'];
76 } elseif (!in_array($func['function'], $ignore)) {
77 $callstack[] = $func['function'];
84 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
85 $callstack2[] = array_pop($callstack);
88 return implode(', ', $callstack2);
93 * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
94 * of $st and an optional text <message> of $message and terminates the current process.
96 public static function xmlExit($st, $message = '')
98 $result = ['status' => $st];
100 if ($message != '') {
101 $result['message'] = $message;
105 Logger::log('xml_status returning non_zero: ' . $st . " message=" . $message);
108 header("Content-type: text/xml");
110 $xmldata = ["result" => $result];
112 echo XML::fromArray($xmldata, $xml);
118 * @brief Send HTTP status header and exit.
120 * @param integer $val HTTP status result value
121 * @param array $description optional message
122 * 'title' => header title
123 * 'description' => optional message
125 public static function httpExit($val, $description = [])
129 if (!empty($description['title'])) {
130 $err = $description['title'];
133 '400' => L10n::t('Error 400 - Bad Request'),
134 '401' => L10n::t('Error 401 - Unauthorized'),
135 '403' => L10n::t('Error 403 - Forbidden'),
136 '404' => L10n::t('Error 404 - Not Found'),
137 '500' => L10n::t('Error 500 - Internal Server Error'),
138 '503' => L10n::t('Error 503 - Service Unavailable'),
140 $err = defaults($title, $val, 'Error ' . $val);
141 $description['title'] = $err;
143 if (empty($description['description'])) {
144 // Explanations are taken from https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
146 '400' => L10n::t('The server cannot or will not process the request due to an apparent client error.'),
147 '401' => L10n::t('Authentication is required and has failed or has not yet been provided.'),
148 '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.'),
149 '404' => L10n::t('The requested resource could not be found but may be available in the future.'),
150 '500' => L10n::t('An unexpected condition was encountered and no more specific message is suitable.'),
151 '503' => L10n::t('The server is currently unavailable (because it is overloaded or down for maintenance). Please try again later.'),
153 if (!empty($explanation[$val])) {
154 $description['description'] = $explanation[$val];
159 if ($val >= 200 && $val < 300) {
163 Logger::log('http_status_exit ' . $val);
164 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
166 if (isset($description["title"])) {
167 $tpl = Renderer::getMarkupTemplate('http_status.tpl');
168 echo Renderer::replaceMacros($tpl, ['$title' => $description["title"],
169 '$description' => defaults($description, 'description', '')]);
176 * @brief Encodes content to json.
178 * This function encodes an array to json format
179 * and adds an application/json HTTP header to the output.
180 * After finishing the process is getting killed.
182 * @param array $x The input content.
183 * @param string $content_type Type of the input (Default: 'application/json').
185 public static function jsonExit($x, $content_type = 'application/json') {
186 header("Content-type: $content_type");
187 echo json_encode($x);
192 * Generates a random string in the UUID format
194 * @param bool|string $prefix A given prefix (default is empty)
195 * @return string a generated UUID
197 public static function createUUID($prefix = '')
199 $guid = System::createGUID(32, $prefix);
200 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
204 * Generates a GUID with the given parameters
206 * @param int $size The size of the GUID (default is 16)
207 * @param bool|string $prefix A given prefix (default is empty)
208 * @return string a generated GUID
210 public static function createGUID($size = 16, $prefix = '')
212 if (is_bool($prefix) && !$prefix) {
214 } elseif (empty($prefix)) {
215 $prefix = hash('crc32', self::getApp()->getHostName());
218 while (strlen($prefix) < ($size - 13)) {
219 $prefix .= mt_rand();
223 $prefix = substr($prefix, 0, $size - 22);
224 return str_replace('.', '', uniqid($prefix, true));
226 $prefix = substr($prefix, 0, max($size - 13, 0));
227 return uniqid($prefix);
232 * Generates a process identifier for the logging
234 * @param string $prefix A given prefix
236 * @return string a generated process identifier
238 public static function processID($prefix)
240 // We aren't calling any other function here.
241 // Doing so could easily create an endless loop
242 $trailer = $prefix . ':' . getmypid() . ':';
243 return substr($trailer . uniqid('') . mt_rand(), 0, 26);
247 * Returns the current Load of the System
251 public static function currentLoad()
253 if (!function_exists('sys_getloadavg')) {
257 $load_arr = sys_getloadavg();
259 if (!is_array($load_arr)) {
263 return max($load_arr[0], $load_arr[1]);
267 * Redirects to an external URL (fully qualified URL)
268 * If you want to route relative to the current Friendica base, use App->internalRedirect()
270 * @param string $url The new Location to redirect
271 * @throws InternalServerErrorException If the URL is not fully qualified
273 public static function externalRedirect($url)
275 if (empty(parse_url($url, PHP_URL_SCHEME))) {
276 throw new InternalServerErrorException("'$url' is not a fully qualified URL, please use App->internalRedirect() instead");
279 header("Location: $url");
283 /// @todo Move the following functions from boot.php
286 function local_user()
287 function public_contact()
288 function remote_user()
291 function is_site_admin()
292 function get_server()
293 function get_temppath()
294 function get_cachefile($file, $writemode = true)
295 function get_itemcachepath()
296 function get_spoolpath()