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