]> git.mxchange.org Git - friendica.git/blob - src/Core/System.php
get markup template
[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                         $err = 'Error';
130                         if (!isset($description["title"])) {
131                                 $description["title"] = $err." ".$val;
132                         }
133                 }
134
135                 if ($val >= 200 && $val < 300) {
136                         $err = 'OK';
137                 }
138
139                 Logger::log('http_status_exit ' . $val);
140                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
141
142                 if (isset($description["title"])) {
143                         $tpl = Renderer::getMarkupTemplate('http_status.tpl');
144                         echo Renderer::replaceMacros($tpl, ['$title' => $description["title"],
145                                 '$description' => defaults($description, 'description', '')]);
146                 }
147
148                 exit();
149         }
150
151         /**
152          * @brief Encodes content to json.
153          *
154          * This function encodes an array to json format
155          * and adds an application/json HTTP header to the output.
156          * After finishing the process is getting killed.
157          *
158          * @param array  $x The input content.
159          * @param string $content_type Type of the input (Default: 'application/json').
160          */
161         public static function jsonExit($x, $content_type = 'application/json') {
162                 header("Content-type: $content_type");
163                 echo json_encode($x);
164                 killme();
165         }
166
167         /**
168          * Generates a random string in the UUID format
169          *
170          * @param bool|string  $prefix   A given prefix (default is empty)
171          * @return string a generated UUID
172          */
173         public static function createUUID($prefix = '')
174         {
175                 $guid = System::createGUID(32, $prefix);
176                 return substr($guid, 0, 8). '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
177         }
178
179         /**
180          * Generates a GUID with the given parameters
181          *
182          * @param int          $size     The size of the GUID (default is 16)
183          * @param bool|string  $prefix   A given prefix (default is empty)
184          * @return string a generated GUID
185          */
186         public static function createGUID($size = 16, $prefix = '')
187         {
188                 if (is_bool($prefix) && !$prefix) {
189                         $prefix = '';
190                 } elseif (empty($prefix)) {
191                         $prefix = hash('crc32', self::getApp()->getHostName());
192                 }
193
194                 while (strlen($prefix) < ($size - 13)) {
195                         $prefix .= mt_rand();
196                 }
197
198                 if ($size >= 24) {
199                         $prefix = substr($prefix, 0, $size - 22);
200                         return str_replace('.', '', uniqid($prefix, true));
201                 } else {
202                         $prefix = substr($prefix, 0, max($size - 13, 0));
203                         return uniqid($prefix);
204                 }
205         }
206
207         /**
208          * Generates a process identifier for the logging
209          *
210          * @param string $prefix A given prefix
211          *
212          * @return string a generated process identifier
213          */
214         public static function processID($prefix)
215         {
216                 // We aren't calling any other function here.
217                 // Doing so could easily create an endless loop
218                 $trailer = $prefix . ':' . getmypid() . ':';
219                 return substr($trailer . uniqid('') . mt_rand(), 0, 26);
220         }
221
222         /**
223          * Returns the current Load of the System
224          *
225          * @return integer
226          */
227         public static function currentLoad()
228         {
229                 if (!function_exists('sys_getloadavg')) {
230                         return false;
231                 }
232
233                 $load_arr = sys_getloadavg();
234
235                 if (!is_array($load_arr)) {
236                         return false;
237                 }
238
239                 return max($load_arr[0], $load_arr[1]);
240         }
241
242         /**
243          * Redirects to an external URL (fully qualified URL)
244          * If you want to route relative to the current Friendica base, use App->internalRedirect()
245          *
246          * @param string $url The new Location to redirect
247          * @throws InternalServerErrorException If the URL is not fully qualified
248          */
249         public static function externalRedirect($url)
250         {
251                 if (!filter_var($url, FILTER_VALIDATE_URL)) {
252                         throw new InternalServerErrorException("'$url' is not a fully qualified URL, please use App->internalRedirect() instead");
253                 }
254
255                 header("Location: $url");
256                 exit();
257         }
258
259         /// @todo Move the following functions from boot.php
260         /*
261         function killme()
262         function local_user()
263         function public_contact()
264         function remote_user()
265         function notice($s)
266         function info($s)
267         function is_site_admin()
268         function random_digits($digits)
269         function get_server()
270         function get_temppath()
271         function get_cachefile($file, $writemode = true)
272         function get_itemcachepath()
273         function get_spoolpath()
274         */
275 }