]> git.mxchange.org Git - friendica.git/blob - src/Core/System.php
Merge pull request #6224 from annando/dba-delete-contact
[friendica.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\Core\Logger;
9 use Friendica\Core\Renderer;
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 SSL_POLICY_SELFSIGN
29          * @return string Friendica server base URL
30          */
31         public static function baseUrl($ssl = false)
32         {
33                 return self::getApp()->getBaseURL($ssl);
34         }
35
36         /**
37          * @brief Removes the baseurl from an url. This avoids some mixed content problems.
38          *
39          * @param string $orig_url The url to be cleaned
40          *
41          * @return string The cleaned url
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                 $counter = 0;
63                 $previous = ['class' => '', 'function' => ''];
64
65                 // The ignore list contains all functions that are only wrapper functions
66                 $ignore = ['fetchUrl', 'call_user_func_array'];
67
68                 while ($func = array_pop($trace)) {
69                         if (!empty($func['class'])) {
70                                 // Don't show multiple calls from the "dba" class to show the essential parts of the callstack
71                                 if ((($previous['class'] != $func['class']) || ($func['class'] != 'Friendica\Database\DBA')) && ($previous['function'] != 'q')) {
72                                         $classparts = explode("\\", $func['class']);
73                                         $callstack[] = array_pop($classparts).'::'.$func['function'];
74                                         $previous = $func;
75                                 }
76                         } elseif (!in_array($func['function'], $ignore)) {
77                                 $callstack[] = $func['function'];
78                                 $func['class'] = '';
79                                 $previous = $func;
80                         }
81                 }
82
83                 $callstack2 = [];
84                 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
85                         $callstack2[] = array_pop($callstack);
86                 }
87
88                 return implode(', ', $callstack2);
89         }
90
91         /**
92          * Generic XML return
93          * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
94          * of $st and an optional text <message> of $message and terminates the current process.
95          */
96         public static function xmlExit($st, $message = '')
97         {
98                 $result = ['status' => $st];
99
100                 if ($message != '') {
101                         $result['message'] = $message;
102                 }
103
104                 if ($st) {
105                         Logger::log('xml_status returning non_zero: ' . $st . " message=" . $message);
106                 }
107
108                 header("Content-type: text/xml");
109
110                 $xmldata = ["result" => $result];
111
112                 echo XML::fromArray($xmldata, $xml);
113
114                 killme();
115         }
116
117         /**
118          * @brief Send HTTP status header and exit.
119          *
120          * @param integer $val         HTTP status result value
121          * @param array   $description optional message
122          *                             'title' => header title
123          *                             'description' => optional message
124          */
125         public static function httpExit($val, $description = [])
126         {
127                 $err = '';
128                 if ($val >= 400) {
129                         if (!empty($description['title'])) {
130                                 $err = $description['title'];
131                         } else {
132                                 $title = [
133                                         '400' => L10n::t('Error 400 - Bad Request'),
134                                         '401' => L10n::t('Error 401 - Unauthorized'),
135                                         '403' => L10n::t('Error 403 - Forbidden'),
136                                         '404' => L10n::t('Error 404 - Not Found'),
137                                         '500' => L10n::t('Error 500 - Internal Server Error'),
138                                         '503' => L10n::t('Error 503 - Service Unavailable'),
139                                         ];
140                                 $err = defaults($title, $val, 'Error ' . $val);
141                                 $description['title'] = $err;
142                         }
143                         if (empty($description['description'])) {
144                                 // Explanations are taken from https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
145                                 $explanation = [
146                                         '400' => L10n::t('The server cannot or will not process the request due to an apparent client error.'),
147                                         '401' => L10n::t('Authentication is required and has failed or has not yet been provided.'),
148                                         '403' => L10n::t('The request was valid, but the server is refusing action. The user might not have the necessary permissions for a resource, or may need an account.'),
149                                         '404' => L10n::t('The requested resource could not be found but may be available in the future.'),
150                                         '500' => L10n::t('An unexpected condition was encountered and no more specific message is suitable.'),
151                                         '503' => L10n::t('The server is currently unavailable (because it is overloaded or down for maintenance). Please try again later.'),
152                                         ];
153                                 if (!empty($explanation[$val])) {
154                                         $description['description'] = $explanation[$val];
155                                 }
156                         }
157                 }
158
159                 if ($val >= 200 && $val < 300) {
160                         $err = 'OK';
161                 }
162
163                 Logger::log('http_status_exit ' . $val);
164                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
165
166                 if (isset($description["title"])) {
167                         $tpl = Renderer::getMarkupTemplate('http_status.tpl');
168                         echo Renderer::replaceMacros($tpl, ['$title' => $description["title"],
169                                 '$description' => defaults($description, 'description', '')]);
170                 }
171
172                 exit();
173         }
174
175         /**
176          * @brief Encodes content to json.
177          *
178          * This function encodes an array to json format
179          * and adds an application/json HTTP header to the output.
180          * After finishing the process is getting killed.
181          *
182          * @param array  $x The input content.
183          * @param string $content_type Type of the input (Default: 'application/json').
184          */
185         public static function jsonExit($x, $content_type = 'application/json') {
186                 header("Content-type: $content_type");
187                 echo json_encode($x);
188                 killme();
189         }
190
191         /**
192          * Generates a random string in the UUID format
193          *
194          * @param bool|string  $prefix   A given prefix (default is empty)
195          * @return string a generated UUID
196          */
197         public static function createUUID($prefix = '')
198         {
199                 $guid = System::createGUID(32, $prefix);
200                 return substr($guid, 0, 8). '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
201         }
202
203         /**
204          * Generates a GUID with the given parameters
205          *
206          * @param int          $size     The size of the GUID (default is 16)
207          * @param bool|string  $prefix   A given prefix (default is empty)
208          * @return string a generated GUID
209          */
210         public static function createGUID($size = 16, $prefix = '')
211         {
212                 if (is_bool($prefix) && !$prefix) {
213                         $prefix = '';
214                 } elseif (empty($prefix)) {
215                         $prefix = hash('crc32', self::getApp()->getHostName());
216                 }
217
218                 while (strlen($prefix) < ($size - 13)) {
219                         $prefix .= mt_rand();
220                 }
221
222                 if ($size >= 24) {
223                         $prefix = substr($prefix, 0, $size - 22);
224                         return str_replace('.', '', uniqid($prefix, true));
225                 } else {
226                         $prefix = substr($prefix, 0, max($size - 13, 0));
227                         return uniqid($prefix);
228                 }
229         }
230
231         /**
232          * Generates a process identifier for the logging
233          *
234          * @param string $prefix A given prefix
235          *
236          * @return string a generated process identifier
237          */
238         public static function processID($prefix)
239         {
240                 // We aren't calling any other function here.
241                 // Doing so could easily create an endless loop
242                 $trailer = $prefix . ':' . getmypid() . ':';
243                 return substr($trailer . uniqid('') . mt_rand(), 0, 26);
244         }
245
246         /**
247          * Returns the current Load of the System
248          *
249          * @return integer
250          */
251         public static function currentLoad()
252         {
253                 if (!function_exists('sys_getloadavg')) {
254                         return false;
255                 }
256
257                 $load_arr = sys_getloadavg();
258
259                 if (!is_array($load_arr)) {
260                         return false;
261                 }
262
263                 return max($load_arr[0], $load_arr[1]);
264         }
265
266         /**
267          * Redirects to an external URL (fully qualified URL)
268          * If you want to route relative to the current Friendica base, use App->internalRedirect()
269          *
270          * @param string $url The new Location to redirect
271          * @throws InternalServerErrorException If the URL is not fully qualified
272          */
273         public static function externalRedirect($url)
274         {
275                 if (!filter_var($url, FILTER_VALIDATE_URL)) {
276                         throw new InternalServerErrorException("'$url' is not a fully qualified URL, please use App->internalRedirect() instead");
277                 }
278
279                 header("Location: $url");
280                 exit();
281         }
282
283         /// @todo Move the following functions from boot.php
284         /*
285         function killme()
286         function local_user()
287         function public_contact()
288         function remote_user()
289         function notice($s)
290         function info($s)
291         function is_site_admin()
292         function get_server()
293         function get_temppath()
294         function get_cachefile($file, $writemode = true)
295         function get_itemcachepath()
296         function get_spoolpath()
297         */
298 }