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