]> git.mxchange.org Git - friendica.git/blob - src/Core/System.php
45a88fe0937b6d92c349d527c8985eab28e04c05
[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                 $previous = ['class' => '', 'function' => ''];
63
64                 // The ignore list contains all functions that are only wrapper functions
65                 $ignore = ['fetchUrl', 'call_user_func_array'];
66
67                 while ($func = array_pop($trace)) {
68                         if (!empty($func['class'])) {
69                                 // Don't show multiple calls from the "dba" class to show the essential parts of the callstack
70                                 if ((($previous['class'] != $func['class']) || ($func['class'] != 'Friendica\Database\DBA')) && ($previous['function'] != 'q')) {
71                                         $classparts = explode("\\", $func['class']);
72                                         $callstack[] = array_pop($classparts).'::'.$func['function'];
73                                         $previous = $func;
74                                 }
75                         } elseif (!in_array($func['function'], $ignore)) {
76                                 $callstack[] = $func['function'];
77                                 $func['class'] = '';
78                                 $previous = $func;
79                         }
80                 }
81
82                 $callstack2 = [];
83                 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
84                         $callstack2[] = array_pop($callstack);
85                 }
86
87                 return implode(', ', $callstack2);
88         }
89
90         /**
91          * Generic XML return
92          * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
93          * of $st and an optional text <message> of $message and terminates the current process.
94          *
95          * @param        $st
96          * @param string $message
97          * @throws \Exception
98          */
99         public static function xmlExit($st, $message = '')
100         {
101                 $result = ['status' => $st];
102
103                 if ($message != '') {
104                         $result['message'] = $message;
105                 }
106
107                 if ($st) {
108                         Logger::log('xml_status returning non_zero: ' . $st . " message=" . $message);
109                 }
110
111                 header("Content-type: text/xml");
112
113                 $xmldata = ["result" => $result];
114
115                 echo XML::fromArray($xmldata, $xml);
116
117                 exit();
118         }
119
120         /**
121          * @brief Send HTTP status header and exit.
122          *
123          * @param integer $val         HTTP status result value
124          * @param array   $description optional message
125          *                             'title' => header title
126          *                             'description' => optional message
127          * @throws InternalServerErrorException
128          */
129         public static function httpExit($val, $description = [])
130         {
131                 $err = '';
132                 if ($val >= 400) {
133                         if (!empty($description['title'])) {
134                                 $err = $description['title'];
135                         } else {
136                                 $title = [
137                                         '400' => L10n::t('Error 400 - Bad Request'),
138                                         '401' => L10n::t('Error 401 - Unauthorized'),
139                                         '403' => L10n::t('Error 403 - Forbidden'),
140                                         '404' => L10n::t('Error 404 - Not Found'),
141                                         '500' => L10n::t('Error 500 - Internal Server Error'),
142                                         '503' => L10n::t('Error 503 - Service Unavailable'),
143                                         ];
144                                 $err = defaults($title, $val, 'Error ' . $val);
145                                 $description['title'] = $err;
146                         }
147                         if (empty($description['description'])) {
148                                 // Explanations are taken from https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
149                                 $explanation = [
150                                         '400' => L10n::t('The server cannot or will not process the request due to an apparent client error.'),
151                                         '401' => L10n::t('Authentication is required and has failed or has not yet been provided.'),
152                                         '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.'),
153                                         '404' => L10n::t('The requested resource could not be found but may be available in the future.'),
154                                         '500' => L10n::t('An unexpected condition was encountered and no more specific message is suitable.'),
155                                         '503' => L10n::t('The server is currently unavailable (because it is overloaded or down for maintenance). Please try again later.'),
156                                         ];
157                                 if (!empty($explanation[$val])) {
158                                         $description['description'] = $explanation[$val];
159                                 }
160                         }
161                 }
162
163                 if ($val >= 200 && $val < 300) {
164                         $err = 'OK';
165                 }
166
167                 Logger::log('http_status_exit ' . $val);
168                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
169
170                 if (isset($description["title"])) {
171                         $tpl = Renderer::getMarkupTemplate('http_status.tpl');
172                         echo Renderer::replaceMacros($tpl, ['$title' => $description["title"],
173                                 '$description' => defaults($description, 'description', '')]);
174                 }
175
176                 exit();
177         }
178
179         public static function jsonError($httpCode, $data, $content_type = 'application/json')
180         {
181                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $httpCode);
182                 self::jsonExit($data, $content_type);
183         }
184
185         /**
186          * @brief Encodes content to json.
187          *
188          * This function encodes an array to json format
189          * and adds an application/json HTTP header to the output.
190          * After finishing the process is getting killed.
191          *
192          * @param array  $x The input content.
193          * @param string $content_type Type of the input (Default: 'application/json').
194          */
195         public static function jsonExit($x, $content_type = 'application/json') {
196                 header("Content-type: $content_type");
197                 echo json_encode($x);
198                 exit();
199         }
200
201         /**
202          * Generates a random string in the UUID format
203          *
204          * @param bool|string $prefix A given prefix (default is empty)
205          * @return string a generated UUID
206          * @throws \Exception
207          */
208         public static function createUUID($prefix = '')
209         {
210                 $guid = System::createGUID(32, $prefix);
211                 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
212         }
213
214         /**
215          * Generates a GUID with the given parameters
216          *
217          * @param int         $size   The size of the GUID (default is 16)
218          * @param bool|string $prefix A given prefix (default is empty)
219          * @return string a generated GUID
220          * @throws \Exception
221          */
222         public static function createGUID($size = 16, $prefix = '')
223         {
224                 if (is_bool($prefix) && !$prefix) {
225                         $prefix = '';
226                 } elseif (empty($prefix)) {
227                         $prefix = hash('crc32', self::getApp()->getHostName());
228                 }
229
230                 while (strlen($prefix) < ($size - 13)) {
231                         $prefix .= mt_rand();
232                 }
233
234                 if ($size >= 24) {
235                         $prefix = substr($prefix, 0, $size - 22);
236                         return str_replace('.', '', uniqid($prefix, true));
237                 } else {
238                         $prefix = substr($prefix, 0, max($size - 13, 0));
239                         return uniqid($prefix);
240                 }
241         }
242
243         /**
244          * Returns the current Load of the System
245          *
246          * @return integer
247          */
248         public static function currentLoad()
249         {
250                 if (!function_exists('sys_getloadavg')) {
251                         return false;
252                 }
253
254                 $load_arr = sys_getloadavg();
255
256                 if (!is_array($load_arr)) {
257                         return false;
258                 }
259
260                 return max($load_arr[0], $load_arr[1]);
261         }
262
263         /**
264          * Redirects to an external URL (fully qualified URL)
265          * If you want to route relative to the current Friendica base, use App->internalRedirect()
266          *
267          * @param string $url The new Location to redirect
268          * @throws InternalServerErrorException If the URL is not fully qualified
269          */
270         public static function externalRedirect($url)
271         {
272                 if (empty(parse_url($url, PHP_URL_SCHEME))) {
273                         throw new InternalServerErrorException("'$url' is not a fully qualified URL, please use App->internalRedirect() instead");
274                 }
275
276                 header("Location: $url");
277                 exit();
278         }
279
280         /**
281          * @brief Returns the system user that is executing the script
282          *
283          * This mostly returns something like "www-data".
284          *
285          * @return string system username
286          */
287         public static function getUser()
288         {
289                 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
290                         return '';
291                 }
292
293                 $processUser = posix_getpwuid(posix_geteuid());
294                 return $processUser['name'];
295         }
296
297         /**
298          * @brief Checks if a given directory is usable for the system
299          *
300          * @param      $directory
301          * @param bool $check_writable
302          *
303          * @return boolean the directory is usable
304          */
305         public static function isDirectoryUsable($directory, $check_writable = true)
306         {
307                 if ($directory == '') {
308                         Logger::log('Directory is empty. This shouldn\'t happen.', Logger::DEBUG);
309                         return false;
310                 }
311
312                 if (!file_exists($directory)) {
313                         Logger::log('Path "' . $directory . '" does not exist for user ' . static::getUser(), Logger::DEBUG);
314                         return false;
315                 }
316
317                 if (is_file($directory)) {
318                         Logger::log('Path "' . $directory . '" is a file for user ' . static::getUser(), Logger::DEBUG);
319                         return false;
320                 }
321
322                 if (!is_dir($directory)) {
323                         Logger::log('Path "' . $directory . '" is not a directory for user ' . static::getUser(), Logger::DEBUG);
324                         return false;
325                 }
326
327                 if ($check_writable && !is_writable($directory)) {
328                         Logger::log('Path "' . $directory . '" is not writable for user ' . static::getUser(), Logger::DEBUG);
329                         return false;
330                 }
331
332                 return true;
333         }
334
335         /// @todo Move the following functions from boot.php
336         /*
337         function killme()
338         function local_user()
339         function public_contact()
340         function remote_user()
341         function notice($s)
342         function info($s)
343         function is_site_admin()
344         function get_server()
345         function get_temppath()
346         function get_cachefile($file, $writemode = true)
347         function get_itemcachepath()
348         function get_spoolpath()
349         */
350 }