]> git.mxchange.org Git - friendica.git/blob - src/Core/System.php
Improved http error handling
[friendica.git] / src / Core / System.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Core;
23
24 use Friendica\DI;
25 use Friendica\Network\HTTPException\BadRequestException;
26 use Friendica\Network\HTTPException\FoundException;
27 use Friendica\Network\HTTPException\MovedPermanentlyException;
28 use Friendica\Network\HTTPException\TemporaryRedirectException;
29 use Friendica\Util\XML;
30
31 /**
32  * Contains the class with system relevant stuff
33  */
34 class System
35 {
36         /**
37          * Returns a string with a callstack. Can be used for logging.
38          *
39          * @param integer $depth  How many calls to include in the stacks after filtering
40          * @param int     $offset How many calls to shave off the top of the stack, for example if
41          *                        this is called from a centralized method that isn't relevant to the callstack
42          * @return string
43          */
44         public static function callstack(int $depth = 4, int $offset = 0)
45         {
46                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
47
48                 // We remove at least the first two items from the list since they contain data that we don't need.
49                 $trace = array_slice($trace, 2 + $offset);
50
51                 $callstack = [];
52                 $previous = ['class' => '', 'function' => '', 'database' => false];
53
54                 // The ignore list contains all functions that are only wrapper functions
55                 $ignore = ['call_user_func_array'];
56
57                 while ($func = array_pop($trace)) {
58                         if (!empty($func['class'])) {
59                                 if (in_array($previous['function'], ['insert', 'fetch', 'toArray', 'exists', 'count', 'selectFirst', 'selectToArray',
60                                         'select', 'update', 'delete', 'selectFirstForUser', 'selectForUser'])
61                                         && (substr($previous['class'], 0, 15) === 'Friendica\Model')) {
62                                         continue;
63                                 }
64
65                                 // Don't show multiple calls from the Database classes to show the essential parts of the callstack
66                                 $func['database'] = in_array($func['class'], ['Friendica\Database\DBA', 'Friendica\Database\Database']);
67                                 if (!$previous['database'] || !$func['database']) {     
68                                         $classparts = explode("\\", $func['class']);
69                                         $callstack[] = array_pop($classparts).'::'.$func['function'];
70                                         $previous = $func;
71                                 }
72                         } elseif (!in_array($func['function'], $ignore)) {
73                                 $func['database'] = ($func['function'] == 'q');
74                                 $callstack[] = $func['function'];
75                                 $func['class'] = '';
76                                 $previous = $func;
77                         }
78                 }
79
80                 $callstack2 = [];
81                 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
82                         $callstack2[] = array_pop($callstack);
83                 }
84
85                 return implode(', ', $callstack2);
86         }
87
88         /**
89          * Generic XML return
90          * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
91          * of $st and an optional text <message> of $message and terminates the current process.
92          *
93          * @param        $st
94          * @param string $message
95          * @throws \Exception
96          */
97         public static function xmlExit($st, $message = '')
98         {
99                 $result = ['status' => $st];
100
101                 if ($message != '') {
102                         $result['message'] = $message;
103                 }
104
105                 if ($st) {
106                         Logger::log('xml_status returning non_zero: ' . $st . " message=" . $message);
107                 }
108
109                 header("Content-type: text/xml");
110
111                 $xmldata = ["result" => $result];
112
113                 echo XML::fromArray($xmldata, $xml);
114
115                 exit();
116         }
117
118         /**
119          * Send HTTP status header and exit.
120          *
121          * @param integer $val     HTTP status result value
122          * @param string  $message Error message. Optional.
123          * @param string  $content Response body. Optional.
124          * @throws \Exception
125          */
126         public static function httpExit($val, $message = '', $content = '')
127         {
128                 if ($val >= 400) {
129                         Logger::debug('Exit with error', ['code' => $val, 'message' => $message, 'callstack' => System::callstack(20), 'method' => $_SERVER['REQUEST_METHOD'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
130                 }
131                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $message);
132
133                 echo $content;
134
135                 exit();
136         }
137
138         public static function jsonError($httpCode, $data, $content_type = 'application/json')
139         {
140                 if ($httpCode >= 400) {
141                         Logger::debug('Exit with error', ['code' => $httpCode, 'content_type' => $content_type, 'callstack' => System::callstack(20), 'method' => $_SERVER['REQUEST_METHOD'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
142                 }
143                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $httpCode);
144                 self::jsonExit($data, $content_type);
145         }
146
147         /**
148          * Encodes content to json.
149          *
150          * This function encodes an array to json format
151          * and adds an application/json HTTP header to the output.
152          * After finishing the process is getting killed.
153          *
154          * @param mixed   $x The input content.
155          * @param string  $content_type Type of the input (Default: 'application/json').
156          * @param integer $options JSON options
157          */
158         public static function jsonExit($x, $content_type = 'application/json', int $options = 0) {
159                 header("Content-type: $content_type");
160                 echo json_encode($x, $options);
161                 exit();
162         }
163
164         /**
165          * Generates a random string in the UUID format
166          *
167          * @param bool|string $prefix A given prefix (default is empty)
168          * @return string a generated UUID
169          * @throws \Exception
170          */
171         public static function createUUID($prefix = '')
172         {
173                 $guid = System::createGUID(32, $prefix);
174                 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
175         }
176
177         /**
178          * Generates a GUID with the given parameters
179          *
180          * @param int         $size   The size of the GUID (default is 16)
181          * @param bool|string $prefix A given prefix (default is empty)
182          * @return string a generated GUID
183          * @throws \Exception
184          */
185         public static function createGUID($size = 16, $prefix = '')
186         {
187                 if (is_bool($prefix) && !$prefix) {
188                         $prefix = '';
189                 } elseif (empty($prefix)) {
190                         $prefix = hash('crc32', DI::baseUrl()->getHostname());
191                 }
192
193                 while (strlen($prefix) < ($size - 13)) {
194                         $prefix .= mt_rand();
195                 }
196
197                 if ($size >= 24) {
198                         $prefix = substr($prefix, 0, $size - 22);
199                         return str_replace('.', '', uniqid($prefix, true));
200                 } else {
201                         $prefix = substr($prefix, 0, max($size - 13, 0));
202                         return uniqid($prefix);
203                 }
204         }
205
206         /**
207          * Returns the current Load of the System
208          *
209          * @return integer
210          */
211         public static function currentLoad()
212         {
213                 if (!function_exists('sys_getloadavg')) {
214                         return false;
215                 }
216
217                 $load_arr = sys_getloadavg();
218
219                 if (!is_array($load_arr)) {
220                         return false;
221                 }
222
223                 return max($load_arr[0], $load_arr[1]);
224         }
225
226         /**
227          * Redirects to an external URL (fully qualified URL)
228          * If you want to route relative to the current Friendica base, use App->internalRedirect()
229          *
230          * @param string $url  The new Location to redirect
231          * @param int    $code The redirection code, which is used (Default is 302)
232          *
233          * @throws BadRequestException If the URL is not fully qualified
234          */
235         public static function externalRedirect($url, $code = 302)
236         {
237                 if (empty(parse_url($url, PHP_URL_SCHEME))) {
238                         throw new BadRequestException("'$url' is not a fully qualified URL, please use App->internalRedirect() instead");
239                 }
240
241                 header("Location: $url");
242
243                 switch ($code) {
244                         case 302:
245                                 throw new FoundException();
246                         case 301:
247                                 throw new MovedPermanentlyException();
248                         case 307:
249                                 throw new TemporaryRedirectException();
250                 }
251
252                 exit();
253         }
254
255         /**
256          * Returns the system user that is executing the script
257          *
258          * This mostly returns something like "www-data".
259          *
260          * @return string system username
261          */
262         public static function getUser()
263         {
264                 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
265                         return '';
266                 }
267
268                 $processUser = posix_getpwuid(posix_geteuid());
269                 return $processUser['name'];
270         }
271
272         /**
273          * Checks if a given directory is usable for the system
274          *
275          * @param      $directory
276          * @param bool $check_writable
277          *
278          * @return boolean the directory is usable
279          */
280         public static function isDirectoryUsable($directory, $check_writable = true)
281         {
282                 if ($directory == '') {
283                         Logger::log('Directory is empty. This shouldn\'t happen.', Logger::DEBUG);
284                         return false;
285                 }
286
287                 if (!file_exists($directory)) {
288                         Logger::log('Path "' . $directory . '" does not exist for user ' . static::getUser(), Logger::DEBUG);
289                         return false;
290                 }
291
292                 if (is_file($directory)) {
293                         Logger::log('Path "' . $directory . '" is a file for user ' . static::getUser(), Logger::DEBUG);
294                         return false;
295                 }
296
297                 if (!is_dir($directory)) {
298                         Logger::log('Path "' . $directory . '" is not a directory for user ' . static::getUser(), Logger::DEBUG);
299                         return false;
300                 }
301
302                 if ($check_writable && !is_writable($directory)) {
303                         Logger::log('Path "' . $directory . '" is not writable for user ' . static::getUser(), Logger::DEBUG);
304                         return false;
305                 }
306
307                 return true;
308         }
309
310         /**
311          * Exit method used by asynchronous update modules
312          *
313          * @param string $o
314          */
315         public static function htmlUpdateExit($o)
316         {
317                 header("Content-type: text/html");
318                 echo "<!DOCTYPE html><html><body>\r\n";
319                 // We can remove this hack once Internet Explorer recognises HTML5 natively
320                 echo "<section>";
321                 // reportedly some versions of MSIE don't handle tabs in XMLHttpRequest documents very well
322                 echo str_replace("\t", "       ", $o);
323                 echo "</section>";
324                 echo "</body></html>\r\n";
325                 exit();
326         }
327
328         /// @todo Move the following functions from boot.php
329         /*
330         function local_user()
331         function public_contact()
332         function remote_user()
333         function notice($s)
334         function info($s)
335         function is_site_admin()
336         function get_temppath()
337         function get_spoolpath()
338         */
339 }