]> git.mxchange.org Git - friendica.git/blob - src/Core/System.php
44419ad1796a95cb9c3fd2055217d7a2c69a3c70
[friendica.git] / src / Core / System.php
1 <?php
2 /**
3  * @file src/Core/System.php
4  */
5 namespace Friendica\Core;
6
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;
12
13 /**
14  * @file include/Core/System.php
15  *
16  * @brief Contains the class with system relevant stuff
17  */
18
19
20 /**
21  * @brief System methods
22  */
23 class System extends BaseObject
24 {
25         /**
26          * @brief Retrieves the Friendica instance base URL
27          *
28          * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
29          * @return string Friendica server base URL
30          * @throws InternalServerErrorException
31          */
32         public static function baseUrl($ssl = false)
33         {
34                 return self::getApp()->getBaseURL($ssl);
35         }
36
37         /**
38          * @brief Removes the baseurl from an url. This avoids some mixed content problems.
39          *
40          * @param string $orig_url The url to be cleaned
41          *
42          * @return string The cleaned url
43          * @throws \Exception
44          */
45         public static function removedBaseUrl($orig_url)
46         {
47                 return self::getApp()->removeBaseURL($orig_url);
48         }
49
50         /**
51          * @brief Returns a string with a callstack. Can be used for logging.
52          * @param integer $depth optional, default 4
53          * @return string
54          */
55         public static function callstack($depth = 4)
56         {
57                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
58
59                 // We remove the first two items from the list since they contain data that we don't need.
60                 array_shift($trace);
61                 array_shift($trace);
62
63                 $callstack = [];
64                 $counter = 0;
65                 $previous = ['class' => '', 'function' => ''];
66
67                 // The ignore list contains all functions that are only wrapper functions
68                 $ignore = ['fetchUrl', 'call_user_func_array'];
69
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'];
76                                         $previous = $func;
77                                 }
78                         } elseif (!in_array($func['function'], $ignore)) {
79                                 $callstack[] = $func['function'];
80                                 $func['class'] = '';
81                                 $previous = $func;
82                         }
83                 }
84
85                 $callstack2 = [];
86                 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
87                         $callstack2[] = array_pop($callstack);
88                 }
89
90                 return implode(', ', $callstack2);
91         }
92
93         /**
94          * Generic XML return
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.
97          *
98          * @param        $st
99          * @param string $message
100          * @throws \Exception
101          */
102         public static function xmlExit($st, $message = '')
103         {
104                 $result = ['status' => $st];
105
106                 if ($message != '') {
107                         $result['message'] = $message;
108                 }
109
110                 if ($st) {
111                         Logger::log('xml_status returning non_zero: ' . $st . " message=" . $message);
112                 }
113
114                 header("Content-type: text/xml");
115
116                 $xmldata = ["result" => $result];
117
118                 echo XML::fromArray($xmldata, $xml);
119
120                 exit();
121         }
122
123         /**
124          * @brief Send HTTP status header and exit.
125          *
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
131          */
132         public static function httpExit($val, $description = [])
133         {
134                 $err = '';
135                 if ($val >= 400) {
136                         if (!empty($description['title'])) {
137                                 $err = $description['title'];
138                         } else {
139                                 $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'),
146                                         ];
147                                 $err = defaults($title, $val, 'Error ' . $val);
148                                 $description['title'] = $err;
149                         }
150                         if (empty($description['description'])) {
151                                 // Explanations are taken from https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
152                                 $explanation = [
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.'),
159                                         ];
160                                 if (!empty($explanation[$val])) {
161                                         $description['description'] = $explanation[$val];
162                                 }
163                         }
164                 }
165
166                 if ($val >= 200 && $val < 300) {
167                         $err = 'OK';
168                 }
169
170                 Logger::log('http_status_exit ' . $val);
171                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
172
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', '')]);
177                 }
178
179                 exit();
180         }
181
182         /**
183          * @brief Encodes content to json.
184          *
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.
188          *
189          * @param array  $x The input content.
190          * @param string $content_type Type of the input (Default: 'application/json').
191          */
192         public static function jsonExit($x, $content_type = 'application/json') {
193                 header("Content-type: $content_type");
194                 echo json_encode($x);
195                 exit();
196         }
197
198         /**
199          * Generates a random string in the UUID format
200          *
201          * @param bool|string $prefix A given prefix (default is empty)
202          * @return string a generated UUID
203          * @throws \Exception
204          */
205         public static function createUUID($prefix = '')
206         {
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);
209         }
210
211         /**
212          * Generates a GUID with the given parameters
213          *
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
217          * @throws \Exception
218          */
219         public static function createGUID($size = 16, $prefix = '')
220         {
221                 if (is_bool($prefix) && !$prefix) {
222                         $prefix = '';
223                 } elseif (empty($prefix)) {
224                         $prefix = hash('crc32', self::getApp()->getHostName());
225                 }
226
227                 while (strlen($prefix) < ($size - 13)) {
228                         $prefix .= mt_rand();
229                 }
230
231                 if ($size >= 24) {
232                         $prefix = substr($prefix, 0, $size - 22);
233                         return str_replace('.', '', uniqid($prefix, true));
234                 } else {
235                         $prefix = substr($prefix, 0, max($size - 13, 0));
236                         return uniqid($prefix);
237                 }
238         }
239
240         /**
241          * Generates a process identifier for the logging
242          *
243          * @param string $prefix A given prefix
244          *
245          * @return string a generated process identifier
246          */
247         public static function processID($prefix)
248         {
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);
253         }
254
255         /**
256          * Returns the current Load of the System
257          *
258          * @return integer
259          */
260         public static function currentLoad()
261         {
262                 if (!function_exists('sys_getloadavg')) {
263                         return false;
264                 }
265
266                 $load_arr = sys_getloadavg();
267
268                 if (!is_array($load_arr)) {
269                         return false;
270                 }
271
272                 return max($load_arr[0], $load_arr[1]);
273         }
274
275         /**
276          * Redirects to an external URL (fully qualified URL)
277          * If you want to route relative to the current Friendica base, use App->internalRedirect()
278          *
279          * @param string $url The new Location to redirect
280          * @throws InternalServerErrorException If the URL is not fully qualified
281          */
282         public static function externalRedirect($url)
283         {
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");
286                 }
287
288                 header("Location: $url");
289                 exit();
290         }
291
292         /// @todo Move the following functions from boot.php
293         /*
294         function killme()
295         function local_user()
296         function public_contact()
297         function remote_user()
298         function notice($s)
299         function info($s)
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()
306         */
307 }