]> git.mxchange.org Git - friendica.git/blob - src/Core/System.php
Refactor namespaces
[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\Network\HTTPException\InternalServerErrorException;
9 use Friendica\Util\XML;
10
11 /**
12  * @file include/Core/System.php
13  *
14  * @brief Contains the class with system relevant stuff
15  */
16
17
18 /**
19  * @brief System methods
20  */
21 class System extends BaseObject
22 {
23         /**
24          * @brief Retrieves the Friendica instance base URL
25          *
26          * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
27          * @return string Friendica server base URL
28          * @throws InternalServerErrorException
29          */
30         public static function baseUrl($ssl = false)
31         {
32                 return self::getApp()->getBaseURL($ssl);
33         }
34
35         /**
36          * @brief Removes the baseurl from an url. This avoids some mixed content problems.
37          *
38          * @param string $orig_url The url to be cleaned
39          *
40          * @return string The cleaned url
41          * @throws \Exception
42          */
43         public static function removedBaseUrl($orig_url)
44         {
45                 return self::getApp()->removeBaseURL($orig_url);
46         }
47
48         /**
49          * @brief Returns a string with a callstack. Can be used for logging.
50          * @param integer $depth optional, default 4
51          * @return string
52          */
53         public static function callstack($depth = 4)
54         {
55                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
56
57                 // We remove the first two items from the list since they contain data that we don't need.
58                 array_shift($trace);
59                 array_shift($trace);
60
61                 $callstack = [];
62                 $counter = 0;
63                 $previous = ['class' => '', 'function' => ''];
64
65                 // The ignore list contains all functions that are only wrapper functions
66                 $ignore = ['fetchUrl', 'call_user_func_array'];
67
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'];
74                                         $previous = $func;
75                                 }
76                         } elseif (!in_array($func['function'], $ignore)) {
77                                 $callstack[] = $func['function'];
78                                 $func['class'] = '';
79                                 $previous = $func;
80                         }
81                 }
82
83                 $callstack2 = [];
84                 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
85                         $callstack2[] = array_pop($callstack);
86                 }
87
88                 return implode(', ', $callstack2);
89         }
90
91         /**
92          * Generic XML return
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.
95          *
96          * @param        $st
97          * @param string $message
98          * @throws \Exception
99          */
100         public static function xmlExit($st, $message = '')
101         {
102                 $result = ['status' => $st];
103
104                 if ($message != '') {
105                         $result['message'] = $message;
106                 }
107
108                 if ($st) {
109                         Logger::log('xml_status returning non_zero: ' . $st . " message=" . $message);
110                 }
111
112                 header("Content-type: text/xml");
113
114                 $xmldata = ["result" => $result];
115
116                 echo XML::fromArray($xmldata, $xml);
117
118                 exit();
119         }
120
121         /**
122          * @brief Send HTTP status header and exit.
123          *
124          * @param integer $val         HTTP status result value
125          * @param array   $description optional message
126          *                             'title' => header title
127          *                             'description' => optional message
128          * @throws InternalServerErrorException
129          */
130         public static function httpExit($val, $description = [])
131         {
132                 $err = '';
133                 if ($val >= 400) {
134                         if (!empty($description['title'])) {
135                                 $err = $description['title'];
136                         } else {
137                                 $title = [
138                                         '400' => L10n::t('Error 400 - Bad Request'),
139                                         '401' => L10n::t('Error 401 - Unauthorized'),
140                                         '403' => L10n::t('Error 403 - Forbidden'),
141                                         '404' => L10n::t('Error 404 - Not Found'),
142                                         '500' => L10n::t('Error 500 - Internal Server Error'),
143                                         '503' => L10n::t('Error 503 - Service Unavailable'),
144                                         ];
145                                 $err = defaults($title, $val, 'Error ' . $val);
146                                 $description['title'] = $err;
147                         }
148                         if (empty($description['description'])) {
149                                 // Explanations are taken from https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
150                                 $explanation = [
151                                         '400' => L10n::t('The server cannot or will not process the request due to an apparent client error.'),
152                                         '401' => L10n::t('Authentication is required and has failed or has not yet been provided.'),
153                                         '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.'),
154                                         '404' => L10n::t('The requested resource could not be found but may be available in the future.'),
155                                         '500' => L10n::t('An unexpected condition was encountered and no more specific message is suitable.'),
156                                         '503' => L10n::t('The server is currently unavailable (because it is overloaded or down for maintenance). Please try again later.'),
157                                         ];
158                                 if (!empty($explanation[$val])) {
159                                         $description['description'] = $explanation[$val];
160                                 }
161                         }
162                 }
163
164                 if ($val >= 200 && $val < 300) {
165                         $err = 'OK';
166                 }
167
168                 Logger::log('http_status_exit ' . $val);
169                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
170
171                 if (isset($description["title"])) {
172                         $tpl = Renderer::getMarkupTemplate('http_status.tpl');
173                         echo Renderer::replaceMacros($tpl, ['$title' => $description["title"],
174                                 '$description' => defaults($description, 'description', '')]);
175                 }
176
177                 exit();
178         }
179
180         /**
181          * @brief Encodes content to json.
182          *
183          * This function encodes an array to json format
184          * and adds an application/json HTTP header to the output.
185          * After finishing the process is getting killed.
186          *
187          * @param array  $x The input content.
188          * @param string $content_type Type of the input (Default: 'application/json').
189          */
190         public static function jsonExit($x, $content_type = 'application/json') {
191                 header("Content-type: $content_type");
192                 echo json_encode($x);
193                 exit();
194         }
195
196         /**
197          * Generates a random string in the UUID format
198          *
199          * @param bool|string $prefix A given prefix (default is empty)
200          * @return string a generated UUID
201          * @throws \Exception
202          */
203         public static function createUUID($prefix = '')
204         {
205                 $guid = System::createGUID(32, $prefix);
206                 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
207         }
208
209         /**
210          * Generates a GUID with the given parameters
211          *
212          * @param int         $size   The size of the GUID (default is 16)
213          * @param bool|string $prefix A given prefix (default is empty)
214          * @return string a generated GUID
215          * @throws \Exception
216          */
217         public static function createGUID($size = 16, $prefix = '')
218         {
219                 if (is_bool($prefix) && !$prefix) {
220                         $prefix = '';
221                 } elseif (empty($prefix)) {
222                         $prefix = hash('crc32', self::getApp()->getHostName());
223                 }
224
225                 while (strlen($prefix) < ($size - 13)) {
226                         $prefix .= mt_rand();
227                 }
228
229                 if ($size >= 24) {
230                         $prefix = substr($prefix, 0, $size - 22);
231                         return str_replace('.', '', uniqid($prefix, true));
232                 } else {
233                         $prefix = substr($prefix, 0, max($size - 13, 0));
234                         return uniqid($prefix);
235                 }
236         }
237
238         /**
239          * Generates a process identifier for the logging
240          *
241          * @param string $prefix A given prefix
242          *
243          * @return string a generated process identifier
244          */
245         public static function processID($prefix)
246         {
247                 // We aren't calling any other function here.
248                 // Doing so could easily create an endless loop
249                 $trailer = $prefix . ':' . getmypid() . ':';
250                 return substr($trailer . uniqid('') . mt_rand(), 0, 26);
251         }
252
253         /**
254          * Returns the current Load of the System
255          *
256          * @return integer
257          */
258         public static function currentLoad()
259         {
260                 if (!function_exists('sys_getloadavg')) {
261                         return false;
262                 }
263
264                 $load_arr = sys_getloadavg();
265
266                 if (!is_array($load_arr)) {
267                         return false;
268                 }
269
270                 return max($load_arr[0], $load_arr[1]);
271         }
272
273         /**
274          * Redirects to an external URL (fully qualified URL)
275          * If you want to route relative to the current Friendica base, use App->internalRedirect()
276          *
277          * @param string $url The new Location to redirect
278          * @throws InternalServerErrorException If the URL is not fully qualified
279          */
280         public static function externalRedirect($url)
281         {
282                 if (empty(parse_url($url, PHP_URL_SCHEME))) {
283                         throw new InternalServerErrorException("'$url' is not a fully qualified URL, please use App->internalRedirect() instead");
284                 }
285
286                 header("Location: $url");
287                 exit();
288         }
289
290         /// @todo Move the following functions from boot.php
291         /*
292         function killme()
293         function local_user()
294         function public_contact()
295         function remote_user()
296         function notice($s)
297         function info($s)
298         function is_site_admin()
299         function get_server()
300         function get_temppath()
301         function get_cachefile($file, $writemode = true)
302         function get_itemcachepath()
303         function get_spoolpath()
304         */
305 }