]> git.mxchange.org Git - friendica.git/blob - src/Core/System.php
Remove deprecated App::removeBaseURL - process methods to DI::baseUrl()->remove()
[friendica.git] / src / Core / System.php
1 <?php
2 /**
3  * @file src/Core/System.php
4  */
5 namespace Friendica\Core;
6
7 use Friendica\DI;
8 use Friendica\Network\HTTPException\InternalServerErrorException;
9 use Friendica\Util\XML;
10
11 /**
12  * @file include/Core/System.php
13  *
14  * @brief Contains the class with system relevant stuff
15  */
16
17
18 /**
19  * @brief System methods
20  */
21 class System
22 {
23         /**
24          * @brief Retrieves the Friendica instance base URL
25          *
26          * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
27          * @return string Friendica server base URL
28          */
29         public static function baseUrl($ssl = false)
30         {
31                 return DI::baseUrl()->get($ssl);
32         }
33
34         /**
35          * @brief Removes the baseurl from an url. This avoids some mixed content problems.
36          *
37          * @param string $orig_url The url to be cleaned
38          *
39          * @return string The cleaned url
40          * @throws \Exception
41          */
42         public static function removedBaseUrl(string $orig_url)
43         {
44                 return DI::baseUrl()->remove($orig_url);
45         }
46
47         /**
48          * @brief Returns a string with a callstack. Can be used for logging.
49          * @param integer $depth optional, default 4
50          * @return string
51          */
52         public static function callstack($depth = 4)
53         {
54                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
55
56                 // We remove the first two items from the list since they contain data that we don't need.
57                 array_shift($trace);
58                 array_shift($trace);
59
60                 $callstack = [];
61                 $previous = ['class' => '', 'function' => ''];
62
63                 // The ignore list contains all functions that are only wrapper functions
64                 $ignore = ['fetchUrl', 'call_user_func_array'];
65
66                 while ($func = array_pop($trace)) {
67                         if (!empty($func['class'])) {
68                                 // Don't show multiple calls from the "dba" class to show the essential parts of the callstack
69                                 if ((($previous['class'] != $func['class']) || ($func['class'] != 'Friendica\Database\DBA')) && ($previous['function'] != 'q')) {
70                                         $classparts = explode("\\", $func['class']);
71                                         $callstack[] = array_pop($classparts).'::'.$func['function'];
72                                         $previous = $func;
73                                 }
74                         } elseif (!in_array($func['function'], $ignore)) {
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::log('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          * @brief 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                 Logger::log('http_status_exit ' . $val);
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                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $httpCode);
140                 self::jsonExit($data, $content_type);
141         }
142
143         /**
144          * @brief Encodes content to json.
145          *
146          * This function encodes an array to json format
147          * and adds an application/json HTTP header to the output.
148          * After finishing the process is getting killed.
149          *
150          * @param mixed  $x The input content.
151          * @param string $content_type Type of the input (Default: 'application/json').
152          */
153         public static function jsonExit($x, $content_type = 'application/json') {
154                 header("Content-type: $content_type");
155                 echo json_encode($x);
156                 exit();
157         }
158
159         /**
160          * Generates a random string in the UUID format
161          *
162          * @param bool|string $prefix A given prefix (default is empty)
163          * @return string a generated UUID
164          * @throws \Exception
165          */
166         public static function createUUID($prefix = '')
167         {
168                 $guid = System::createGUID(32, $prefix);
169                 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
170         }
171
172         /**
173          * Generates a GUID with the given parameters
174          *
175          * @param int         $size   The size of the GUID (default is 16)
176          * @param bool|string $prefix A given prefix (default is empty)
177          * @return string a generated GUID
178          * @throws \Exception
179          */
180         public static function createGUID($size = 16, $prefix = '')
181         {
182                 if (is_bool($prefix) && !$prefix) {
183                         $prefix = '';
184                 } elseif (empty($prefix)) {
185                         $prefix = hash('crc32', DI::app()->getHostName());
186                 }
187
188                 while (strlen($prefix) < ($size - 13)) {
189                         $prefix .= mt_rand();
190                 }
191
192                 if ($size >= 24) {
193                         $prefix = substr($prefix, 0, $size - 22);
194                         return str_replace('.', '', uniqid($prefix, true));
195                 } else {
196                         $prefix = substr($prefix, 0, max($size - 13, 0));
197                         return uniqid($prefix);
198                 }
199         }
200
201         /**
202          * Returns the current Load of the System
203          *
204          * @return integer
205          */
206         public static function currentLoad()
207         {
208                 if (!function_exists('sys_getloadavg')) {
209                         return false;
210                 }
211
212                 $load_arr = sys_getloadavg();
213
214                 if (!is_array($load_arr)) {
215                         return false;
216                 }
217
218                 return max($load_arr[0], $load_arr[1]);
219         }
220
221         /**
222          * Redirects to an external URL (fully qualified URL)
223          * If you want to route relative to the current Friendica base, use App->internalRedirect()
224          *
225          * @param string $url  The new Location to redirect
226          * @param int    $code The redirection code, which is used (Default is 302)
227          *
228          * @throws InternalServerErrorException If the URL is not fully qualified
229          */
230         public static function externalRedirect($url, $code = 302)
231         {
232                 if (empty(parse_url($url, PHP_URL_SCHEME))) {
233                         throw new InternalServerErrorException("'$url' is not a fully qualified URL, please use App->internalRedirect() instead");
234                 }
235
236                 switch ($code) {
237                         case 302:
238                                 // this is the default code for a REDIRECT
239                                 // We don't need a extra header here
240                                 break;
241                         case 301:
242                                 header('HTTP/1.1 301 Moved Permanently');
243                                 break;
244                         case 307:
245                                 header('HTTP/1.1 307 Temporary Redirect');
246                                 break;
247                 }
248
249                 header("Location: $url");
250                 exit();
251         }
252
253         /**
254          * @brief 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          * @brief 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         /// @todo Move the following functions from boot.php
309         /*
310         function killme()
311         function local_user()
312         function public_contact()
313         function remote_user()
314         function notice($s)
315         function info($s)
316         function is_site_admin()
317         function get_server()
318         function get_temppath()
319         function get_cachefile($file, $writemode = true)
320         function get_itemcachepath()
321         function get_spoolpath()
322         */
323 }