]> git.mxchange.org Git - friendica.git/blob - src/Core/System.php
todo removed
[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 Exception;
25 use Friendica\DI;
26 use Friendica\Network\HTTPException\FoundException;
27 use Friendica\Network\HTTPException\MovedPermanentlyException;
28 use Friendica\Network\HTTPException\TemporaryRedirectException;
29 use Friendica\Util\BasePath;
30 use Friendica\Util\XML;
31
32 /**
33  * Contains the class with system relevant stuff
34  */
35 class System
36 {
37         /**
38          * Returns a string with a callstack. Can be used for logging.
39          *
40          * @param integer $depth  How many calls to include in the stacks after filtering
41          * @param int     $offset How many calls to shave off the top of the stack, for example if
42          *                        this is called from a centralized method that isn't relevant to the callstack
43          * @return string
44          */
45         public static function callstack(int $depth = 4, int $offset = 0)
46         {
47                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
48
49                 // We remove at least the first two items from the list since they contain data that we don't need.
50                 $trace = array_slice($trace, 2 + $offset);
51
52                 $callstack = [];
53                 $previous = ['class' => '', 'function' => '', 'database' => false];
54
55                 // The ignore list contains all functions that are only wrapper functions
56                 $ignore = ['call_user_func_array'];
57
58                 while ($func = array_pop($trace)) {
59                         if (!empty($func['class'])) {
60                                 if (in_array($previous['function'], ['insert', 'fetch', 'toArray', 'exists', 'count', 'selectFirst', 'selectToArray',
61                                         'select', 'update', 'delete', 'selectFirstForUser', 'selectForUser'])
62                                         && (substr($previous['class'], 0, 15) === 'Friendica\Model')) {
63                                         continue;
64                                 }
65
66                                 // Don't show multiple calls from the Database classes to show the essential parts of the callstack
67                                 $func['database'] = in_array($func['class'], ['Friendica\Database\DBA', 'Friendica\Database\Database']);
68                                 if (!$previous['database'] || !$func['database']) {     
69                                         $classparts = explode("\\", $func['class']);
70                                         $callstack[] = array_pop($classparts).'::'.$func['function'];
71                                         $previous = $func;
72                                 }
73                         } elseif (!in_array($func['function'], $ignore)) {
74                                 $func['database'] = ($func['function'] == 'q');
75                                 $callstack[] = $func['function'];
76                                 $func['class'] = '';
77                                 $previous = $func;
78                         }
79                 }
80
81                 $callstack2 = [];
82                 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
83                         $callstack2[] = array_pop($callstack);
84                 }
85
86                 return implode(', ', $callstack2);
87         }
88
89         /**
90          * Generic XML return
91          * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
92          * of $st and an optional text <message> of $message and terminates the current process.
93          *
94          * @param        $st
95          * @param string $message
96          * @throws \Exception
97          */
98         public static function xmlExit($st, $message = '')
99         {
100                 $result = ['status' => $st];
101
102                 if ($message != '') {
103                         $result['message'] = $message;
104                 }
105
106                 if ($st) {
107                         Logger::notice('xml_status returning non_zero: ' . $st . " message=" . $message);
108                 }
109
110                 header("Content-type: text/xml");
111
112                 $xmldata = ["result" => $result];
113
114                 echo XML::fromArray($xmldata, $xml);
115
116                 exit();
117         }
118
119         /**
120          * Send HTTP status header and exit.
121          *
122          * @param integer $val     HTTP status result value
123          * @param string  $message Error message. Optional.
124          * @param string  $content Response body. Optional.
125          * @throws \Exception
126          */
127         public static function httpExit($val, $message = '', $content = '')
128         {
129                 if ($val >= 400) {
130                         Logger::debug('Exit with error', ['code' => $val, 'message' => $message, 'callstack' => System::callstack(20), 'method' => $_SERVER['REQUEST_METHOD'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
131                 }
132                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $message);
133
134                 echo $content;
135
136                 exit();
137         }
138
139         public static function jsonError($httpCode, $data, $content_type = 'application/json')
140         {
141                 if ($httpCode >= 400) {
142                         Logger::debug('Exit with error', ['code' => $httpCode, 'content_type' => $content_type, 'callstack' => System::callstack(20), 'method' => $_SERVER['REQUEST_METHOD'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
143                 }
144                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $httpCode);
145                 self::jsonExit($data, $content_type);
146         }
147
148         /**
149          * Encodes content to json.
150          *
151          * This function encodes an array to json format
152          * and adds an application/json HTTP header to the output.
153          * After finishing the process is getting killed.
154          *
155          * @param mixed   $x The input content.
156          * @param string  $content_type Type of the input (Default: 'application/json').
157          * @param integer $options JSON options
158          */
159         public static function jsonExit($x, $content_type = 'application/json', int $options = 0) {
160                 header("Content-type: $content_type");
161                 echo json_encode($x, $options);
162                 exit();
163         }
164
165         /**
166          * Generates a random string in the UUID format
167          *
168          * @param bool|string $prefix A given prefix (default is empty)
169          * @return string a generated UUID
170          * @throws \Exception
171          */
172         public static function createUUID($prefix = '')
173         {
174                 $guid = System::createGUID(32, $prefix);
175                 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
176         }
177
178         /**
179          * Generates a GUID with the given parameters
180          *
181          * @param int         $size   The size of the GUID (default is 16)
182          * @param bool|string $prefix A given prefix (default is empty)
183          * @return string a generated GUID
184          * @throws \Exception
185          */
186         public static function createGUID($size = 16, $prefix = '')
187         {
188                 if (is_bool($prefix) && !$prefix) {
189                         $prefix = '';
190                 } elseif (empty($prefix)) {
191                         $prefix = hash('crc32', DI::baseUrl()->getHostname());
192                 }
193
194                 while (strlen($prefix) < ($size - 13)) {
195                         $prefix .= mt_rand();
196                 }
197
198                 if ($size >= 24) {
199                         $prefix = substr($prefix, 0, $size - 22);
200                         return str_replace('.', '', uniqid($prefix, true));
201                 } else {
202                         $prefix = substr($prefix, 0, max($size - 13, 0));
203                         return uniqid($prefix);
204                 }
205         }
206
207         /**
208          * Returns the current Load of the System
209          *
210          * @return integer
211          */
212         public static function currentLoad()
213         {
214                 if (!function_exists('sys_getloadavg')) {
215                         return false;
216                 }
217
218                 $load_arr = sys_getloadavg();
219
220                 if (!is_array($load_arr)) {
221                         return false;
222                 }
223
224                 return max($load_arr[0], $load_arr[1]);
225         }
226
227         /**
228          * Redirects to an external URL (fully qualified URL)
229          * If you want to route relative to the current Friendica base, use App->internalRedirect()
230          *
231          * @param string $url  The new Location to redirect
232          * @param int    $code The redirection code, which is used (Default is 302)
233          */
234         public static function externalRedirect($url, $code = 302)
235         {
236                 if (empty(parse_url($url, PHP_URL_SCHEME))) {
237                         Logger::warning('No fully qualified URL provided', ['url' => $url, 'callstack' => self::callstack(20)]);
238                         DI::baseUrl()->redirect($url);
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::info('Directory is empty. This shouldn\'t happen.');
284                         return false;
285                 }
286
287                 if (!file_exists($directory)) {
288                         Logger::info('Path "' . $directory . '" does not exist for user ' . static::getUser());
289                         return false;
290                 }
291
292                 if (is_file($directory)) {
293                         Logger::info('Path "' . $directory . '" is a file for user ' . static::getUser());
294                         return false;
295                 }
296
297                 if (!is_dir($directory)) {
298                         Logger::info('Path "' . $directory . '" is not a directory for user ' . static::getUser());
299                         return false;
300                 }
301
302                 if ($check_writable && !is_writable($directory)) {
303                         Logger::info('Path "' . $directory . '" is not writable for user ' . static::getUser());
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         /**
329          * Fetch the temp path of the system
330          *
331          * @return string Path for temp files
332          */
333         public static function getTempPath()
334         {
335                 $temppath = DI::config()->get("system", "temppath");
336
337                 if (($temppath != "") && System::isDirectoryUsable($temppath)) {
338                         // We have a temp path and it is usable
339                         return BasePath::getRealPath($temppath);
340                 }
341
342                 // We don't have a working preconfigured temp path, so we take the system path.
343                 $temppath = sys_get_temp_dir();
344
345                 // Check if it is usable
346                 if (($temppath != "") && System::isDirectoryUsable($temppath)) {
347                         // Always store the real path, not the path through symlinks
348                         $temppath = BasePath::getRealPath($temppath);
349
350                         // To avoid any interferences with other systems we create our own directory
351                         $new_temppath = $temppath . "/" . DI::baseUrl()->getHostname();
352                         if (!is_dir($new_temppath)) {
353                                 /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
354                                 mkdir($new_temppath);
355                         }
356
357                         if (System::isDirectoryUsable($new_temppath)) {
358                                 // The new path is usable, we are happy
359                                 DI::config()->set("system", "temppath", $new_temppath);
360                                 return $new_temppath;
361                         } else {
362                                 // We can't create a subdirectory, strange.
363                                 // But the directory seems to work, so we use it but don't store it.
364                                 return $temppath;
365                         }
366                 }
367
368                 // Reaching this point means that the operating system is configured badly.
369                 return '';
370         }
371
372         /**
373          * Returns the path where spool files are stored
374          *
375          * @return string Spool path
376          */
377         public static function getSpoolPath()
378         {
379                 $spoolpath = DI::config()->get('system', 'spoolpath');
380                 if (($spoolpath != "") && System::isDirectoryUsable($spoolpath)) {
381                         // We have a spool path and it is usable
382                         return $spoolpath;
383                 }
384
385                 // We don't have a working preconfigured spool path, so we take the temp path.
386                 $temppath = self::getTempPath();
387
388                 if ($temppath != "") {
389                         // To avoid any interferences with other systems we create our own directory
390                         $spoolpath = $temppath . "/spool";
391                         if (!is_dir($spoolpath)) {
392                                 mkdir($spoolpath);
393                         }
394
395                         if (System::isDirectoryUsable($spoolpath)) {
396                                 // The new path is usable, we are happy
397                                 DI::config()->set("system", "spoolpath", $spoolpath);
398                                 return $spoolpath;
399                         } else {
400                                 // We can't create a subdirectory, strange.
401                                 // But the directory seems to work, so we use it but don't store it.
402                                 return $temppath;
403                         }
404                 }
405
406                 // Reaching this point means that the operating system is configured badly.
407                 return "";
408         }
409 }