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