]> git.mxchange.org Git - friendica.git/blob - src/Core/System.php
Log function
[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\Network\HTTPException\InternalServerErrorException;
10 use Friendica\Util\XML;
11
12 /**
13  * @file include/Core/System.php
14  *
15  * @brief Contains the class with system relevant stuff
16  */
17
18
19 /**
20  * @brief System methods
21  */
22 class System extends BaseObject
23 {
24         /**
25          * @brief Retrieves the Friendica instance base URL
26          *
27          * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
28          * @return string Friendica server base URL
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          */
42         public static function removedBaseUrl($orig_url)
43         {
44                 return self::getApp()->removeBaseURL($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                 $counter = 0;
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         public static function xmlExit($st, $message = '')
96         {
97                 $result = ['status' => $st];
98
99                 if ($message != '') {
100                         $result['message'] = $message;
101                 }
102
103                 if ($st) {
104                         Logger::log('xml_status returning non_zero: ' . $st . " message=" . $message);
105                 }
106
107                 header("Content-type: text/xml");
108
109                 $xmldata = ["result" => $result];
110
111                 echo XML::fromArray($xmldata, $xml);
112
113                 killme();
114         }
115
116         /**
117          * @brief Send HTTP status header and exit.
118          *
119          * @param integer $val         HTTP status result value
120          * @param array   $description optional message
121          *                             'title' => header title
122          *                             'description' => optional message
123          */
124         public static function httpExit($val, $description = [])
125         {
126                 $err = '';
127                 if ($val >= 400) {
128                         $err = 'Error';
129                         if (!isset($description["title"])) {
130                                 $description["title"] = $err." ".$val;
131                         }
132                 }
133
134                 if ($val >= 200 && $val < 300) {
135                         $err = 'OK';
136                 }
137
138                 Logger::log('http_status_exit ' . $val);
139                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
140
141                 if (isset($description["title"])) {
142                         $tpl = get_markup_template('http_status.tpl');
143                         echo replace_macros($tpl, ['$title' => $description["title"],
144                                 '$description' => defaults($description, 'description', '')]);
145                 }
146
147                 exit();
148         }
149
150         /**
151          * @brief Encodes content to json.
152          *
153          * This function encodes an array to json format
154          * and adds an application/json HTTP header to the output.
155          * After finishing the process is getting killed.
156          *
157          * @param array  $x The input content.
158          * @param string $content_type Type of the input (Default: 'application/json').
159          */
160         public static function jsonExit($x, $content_type = 'application/json') {
161                 header("Content-type: $content_type");
162                 echo json_encode($x);
163                 killme();
164         }
165
166         /**
167          * Generates a random string in the UUID format
168          *
169          * @param bool|string  $prefix   A given prefix (default is empty)
170          * @return string a generated UUID
171          */
172         public static function createUUID($prefix = '')
173         {
174                 $guid = System::createGUID(32, $prefix);
175                 return substr($guid, 0, 8). '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
176         }
177
178         /**
179          * Generates a GUID with the given parameters
180          *
181          * @param int          $size     The size of the GUID (default is 16)
182          * @param bool|string  $prefix   A given prefix (default is empty)
183          * @return string a generated GUID
184          */
185         public static function createGUID($size = 16, $prefix = '')
186         {
187                 if (is_bool($prefix) && !$prefix) {
188                         $prefix = '';
189                 } elseif (empty($prefix)) {
190                         $prefix = hash('crc32', self::getApp()->getHostName());
191                 }
192
193                 while (strlen($prefix) < ($size - 13)) {
194                         $prefix .= mt_rand();
195                 }
196
197                 if ($size >= 24) {
198                         $prefix = substr($prefix, 0, $size - 22);
199                         return str_replace('.', '', uniqid($prefix, true));
200                 } else {
201                         $prefix = substr($prefix, 0, max($size - 13, 0));
202                         return uniqid($prefix);
203                 }
204         }
205
206         /**
207          * Generates a process identifier for the logging
208          *
209          * @param string $prefix A given prefix
210          *
211          * @return string a generated process identifier
212          */
213         public static function processID($prefix)
214         {
215                 // We aren't calling any other function here.
216                 // Doing so could easily create an endless loop
217                 $trailer = $prefix . ':' . getmypid() . ':';
218                 return substr($trailer . uniqid('') . mt_rand(), 0, 26);
219         }
220
221         /**
222          * Returns the current Load of the System
223          *
224          * @return integer
225          */
226         public static function currentLoad()
227         {
228                 if (!function_exists('sys_getloadavg')) {
229                         return false;
230                 }
231
232                 $load_arr = sys_getloadavg();
233
234                 if (!is_array($load_arr)) {
235                         return false;
236                 }
237
238                 return max($load_arr[0], $load_arr[1]);
239         }
240
241         /**
242          * Redirects to an external URL (fully qualified URL)
243          * If you want to route relative to the current Friendica base, use App->internalRedirect()
244          *
245          * @param string $url The new Location to redirect
246          * @throws InternalServerErrorException If the URL is not fully qualified
247          */
248         public static function externalRedirect($url)
249         {
250                 if (!filter_var($url, FILTER_VALIDATE_URL)) {
251                         throw new InternalServerErrorException("'$url' is not a fully qualified URL, please use App->internalRedirect() instead");
252                 }
253
254                 header("Location: $url");
255                 exit();
256         }
257
258         /// @todo Move the following functions from boot.php
259         /*
260         function killme()
261         function local_user()
262         function public_contact()
263         function remote_user()
264         function notice($s)
265         function info($s)
266         function is_site_admin()
267         function random_digits($digits)
268         function get_server()
269         function get_temppath()
270         function get_cachefile($file, $writemode = true)
271         function get_itemcachepath()
272         function get_spoolpath()
273         */
274 }