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