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