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