]> git.mxchange.org Git - friendica.git/blob - src/App/Page.php
Added parameters
[friendica.git] / src / App / Page.php
1 <?php
2
3 namespace Friendica\App;
4
5 use ArrayAccess;
6 use DOMDocument;
7 use DOMXPath;
8 use Friendica\App;
9 use Friendica\Content\Nav;
10 use Friendica\Core\Config\Configuration;
11 use Friendica\Core\Config\PConfiguration;
12 use Friendica\Core\Hook;
13 use Friendica\Core\L10n\L10n;
14 use Friendica\Core\Renderer;
15 use Friendica\Core\Theme;
16 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
17 use Friendica\Network\HTTPException;
18
19 /**
20  * Contains the page specific environment variables for the current Page
21  * - Contains all stylesheets
22  * - Contains all footer-scripts
23  * - Contains all page specific content (header, footer, content, ...)
24  *
25  * The run() method is the single point where the page will get printed to the screen
26  */
27 class Page implements ArrayAccess
28 {
29         /**
30          * @var array Contains all stylesheets, which should get loaded during page
31          */
32         private $stylesheets;
33         /**
34          * @var array Contains all scripts, which are added to the footer at last
35          */
36         private $footerScripts;
37         /**
38          * @var array The page content, which are showed directly
39          */
40         private $page;
41         /**
42          * @var string The basepath of the page
43          */
44         private $basePath;
45
46         /**
47          * @param string $basepath The Page basepath
48          */
49         public function __construct(string $basepath)
50         {
51                 $this->basePath = $basepath;
52
53                 $this->page = [
54                         'aside'       => '',
55                         'bottom'      => '',
56                         'content'     => '',
57                         'footer'      => '',
58                         'htmlhead'    => '',
59                         'nav'         => '',
60                         'page_title'  => '',
61                         'right_aside' => '',
62                         'template'    => '',
63                         'title'       => ''
64                 ];
65         }
66
67         /**
68          * Whether a offset exists
69          *
70          * @link  https://php.net/manual/en/arrayaccess.offsetexists.php
71          *
72          * @param mixed $offset <p>
73          *                      An offset to check for.
74          *                      </p>
75          *
76          * @return boolean true on success or false on failure.
77          * </p>
78          * <p>
79          * The return value will be casted to boolean if non-boolean was returned.
80          * @since 5.0.0
81          */
82         public function offsetExists($offset)
83         {
84                 return isset($this->page[$offset]);
85         }
86
87         /**
88          * Offset to retrieve
89          *
90          * @link  https://php.net/manual/en/arrayaccess.offsetget.php
91          *
92          * @param mixed $offset <p>
93          *                      The offset to retrieve.
94          *                      </p>
95          *
96          * @return mixed Can return all value types.
97          * @since 5.0.0
98          */
99         public function offsetGet($offset)
100         {
101                 return $this->page[$offset] ?? null;
102         }
103
104         /**
105          * Offset to set
106          *
107          * @link  https://php.net/manual/en/arrayaccess.offsetset.php
108          *
109          * @param mixed $offset <p>
110          *                      The offset to assign the value to.
111          *                      </p>
112          * @param mixed $value  <p>
113          *                      The value to set.
114          *                      </p>
115          *
116          * @return void
117          * @since 5.0.0
118          */
119         public function offsetSet($offset, $value)
120         {
121                 $this->page[$offset] = $value;
122         }
123
124         /**
125          * Offset to unset
126          *
127          * @link  https://php.net/manual/en/arrayaccess.offsetunset.php
128          *
129          * @param mixed $offset <p>
130          *                      The offset to unset.
131          *                      </p>
132          *
133          * @return void
134          * @since 5.0.0
135          */
136         public function offsetUnset($offset)
137         {
138                 if (isset($this->page[$offset])) {
139                         unset($this->page[$offset]);
140                 }
141         }
142
143         /**
144          * Register a stylesheet file path to be included in the <head> tag of every page.
145          * Inclusion is done in App->initHead().
146          * The path can be absolute or relative to the Friendica installation base folder.
147          *
148          * @param string $path
149          *
150          * @see Page::initHead()
151          *
152          */
153         public function registerStylesheet($path)
154         {
155                 if (mb_strpos($path, $this->basePath . DIRECTORY_SEPARATOR) === 0) {
156                         $path = mb_substr($path, mb_strlen($this->basePath . DIRECTORY_SEPARATOR));
157                 }
158
159                 $this->stylesheets[] = trim($path, '/');
160         }
161
162         /**
163          * Initializes Page->page['htmlhead'].
164          *
165          * Includes:
166          * - Page title
167          * - Favicons
168          * - Registered stylesheets (through App->registerStylesheet())
169          * - Infinite scroll data
170          * - head.tpl template
171          *
172          * @param App            $app     The Friendica App instance
173          * @param Module         $module  The loaded Friendica module
174          * @param L10n           $l10n    The l10n language instance
175          * @param Configuration  $config  The Friendica configuration
176          * @param PConfiguration $pConfig The Friendica personal configuration (for user)
177          *
178          * @throws HTTPException\InternalServerErrorException
179          */
180         private function initHead(App $app, Module $module, L10n $l10n, Configuration $config, PConfiguration $pConfig)
181         {
182                 $interval = ((local_user()) ? $pConfig->get(local_user(), 'system', 'update_interval') : 40000);
183
184                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
185                 if ($interval < 0) {
186                         $interval = 2147483647;
187                 }
188
189                 if ($interval < 10000) {
190                         $interval = 40000;
191                 }
192
193                 // Default title: current module called
194                 if (empty($this->page['title']) && $module->getName()) {
195                         $this->page['title'] = ucfirst($module->getName());
196                 }
197
198                 // Prepend the sitename to the page title
199                 $this->page['title'] = $config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
200
201                 if (!empty(Renderer::$theme['stylesheet'])) {
202                         $stylesheet = Renderer::$theme['stylesheet'];
203                 } else {
204                         $stylesheet = $app->getCurrentThemeStylesheetPath();
205                 }
206
207                 $this->registerStylesheet($stylesheet);
208
209                 $shortcut_icon = $config->get('system', 'shortcut_icon');
210                 if ($shortcut_icon == '') {
211                         $shortcut_icon = 'images/friendica-32.png';
212                 }
213
214                 $touch_icon = $config->get('system', 'touch_icon');
215                 if ($touch_icon == '') {
216                         $touch_icon = 'images/friendica-128.png';
217                 }
218
219                 Hook::callAll('head', $this->page['htmlhead']);
220
221                 $tpl = Renderer::getMarkupTemplate('head.tpl');
222                 /* put the head template at the beginning of page['htmlhead']
223                  * since the code added by the modules frequently depends on it
224                  * being first
225                  */
226                 $this->page['htmlhead'] = Renderer::replaceMacros($tpl, [
227                                 '$local_user'      => local_user(),
228                                 '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
229                                 '$delitem'         => $l10n->t('Delete this item?'),
230                                 '$update_interval' => $interval,
231                                 '$shortcut_icon'   => $shortcut_icon,
232                                 '$touch_icon'      => $touch_icon,
233                                 '$block_public'    => intval($config->get('system', 'block_public')),
234                                 '$stylesheets'     => $this->stylesheets,
235                         ]) . $this->page['htmlhead'];
236         }
237
238         /**
239          * Initializes Page->page['footer'].
240          *
241          * Includes:
242          * - Javascript homebase
243          * - Mobile toggle link
244          * - Registered footer scripts (through App->registerFooterScript())
245          * - footer.tpl template
246          *
247          * @param App  $app  The Friendica App instance
248          * @param Mode $mode The Friendica runtime mode
249          * @param L10n $l10n The l10n instance
250          *
251          * @throws HTTPException\InternalServerErrorException
252          */
253         private function initFooter(App $app, Mode $mode, L10n $l10n)
254         {
255                 // If you're just visiting, let javascript take you home
256                 if (!empty($_SESSION['visitor_home'])) {
257                         $homebase = $_SESSION['visitor_home'];
258                 } elseif (local_user()) {
259                         $homebase = 'profile/' . $app->user['nickname'];
260                 }
261
262                 if (isset($homebase)) {
263                         $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
264                 }
265
266                 /*
267                  * Add a "toggle mobile" link if we're using a mobile device
268                  */
269                 if ($mode->isMobile() || $mode->isTablet()) {
270                         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
271                                 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
272                         } else {
273                                 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
274                         }
275                         $this->page['footer'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
276                                 '$toggle_link' => $link,
277                                 '$toggle_text' => $l10n->t('toggle mobile')
278                         ]);
279                 }
280
281                 Hook::callAll('footer', $this->page['footer']);
282
283                 $tpl                  = Renderer::getMarkupTemplate('footer.tpl');
284                 $this->page['footer'] = Renderer::replaceMacros($tpl, [
285                                 '$footerScripts' => $this->footerScripts,
286                         ]) . $this->page['footer'];
287         }
288
289         /**
290          * Initializes Page->page['content'].
291          *
292          * Includes:
293          * - module content
294          * - hooks for content
295          *
296          * @param Module $module The module
297          * @param Mode   $mode   The Friendica execution mode
298          *
299          * @throws HTTPException\InternalServerErrorException
300          */
301         private function initContent(Module $module, Mode $mode)
302         {
303                 $content = '';
304
305                 try {
306                         $moduleClass = $module->getClassName();
307
308                         $arr = ['content' => $content];
309                         Hook::callAll($moduleClass . '_mod_content', $arr);
310                         $content = $arr['content'];
311                         $arr     = ['content' => call_user_func([$moduleClass, 'content'], [])];
312                         Hook::callAll($moduleClass . '_mod_aftercontent', $arr);
313                         $content .= $arr['content'];
314                 } catch (HTTPException $e) {
315                         $content = ModuleHTTPException::content($e);
316                 }
317
318                 // initialise content region
319                 if ($mode->isNormal()) {
320                         Hook::callAll('page_content_top', $this->page['content']);
321                 }
322
323                 $this->page['content'] .= $content;
324         }
325
326         /**
327          * Register a javascript file path to be included in the <footer> tag of every page.
328          * Inclusion is done in App->initFooter().
329          * The path can be absolute or relative to the Friendica installation base folder.
330          *
331          * @param string $path
332          *
333          * @see Page::initFooter()
334          *
335          */
336         public function registerFooterScript($path)
337         {
338                 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
339
340                 $this->footerScripts[] = trim($url, '/');
341         }
342
343         /**
344          * Executes the creation of the current page and prints it to the screen
345          *
346          * @param App            $app     The Friendica App
347          * @param BaseURL        $baseURL The Friendica Base URL
348          * @param Mode           $mode    The current node mode
349          * @param Module         $module  The loaded Friendica module
350          * @param L10n           $l10n    The l10n language class
351          * @param Configuration  $config  The Configuration of this node
352          * @param PConfiguration $pconfig The personal/user configuration
353          *
354          * @throws HTTPException\InternalServerErrorException
355          */
356         public function run(App $app, BaseURL $baseURL, Mode $mode, Module $module, L10n $l10n, Configuration $config, PConfiguration $pconfig)
357         {
358                 $moduleName = $module->getName();
359
360                 /* Create the page content.
361                  * Calls all hooks which are including content operations
362                  *
363                  * Sets the $Page->page['content'] variable
364                  */
365                 $this->initContent($module, $mode);
366
367                 // Load current theme info after module has been initialized as theme could have been set in module
368                 $currentTheme = $app->getCurrentTheme();
369                 $theme_info_file = 'view/theme/' . $currentTheme . '/theme.php';
370                 if (file_exists($theme_info_file)) {
371                         require_once $theme_info_file;
372                 }
373
374                 if (function_exists(str_replace('-', '_', $currentTheme) . '_init')) {
375                         $func = str_replace('-', '_', $currentTheme) . '_init';
376                         $func($app);
377                 }
378
379                 /* Create the page head after setting the language
380                  * and getting any auth credentials.
381                  *
382                  * Moved initHead() and initFooter() to after
383                  * all the module functions have executed so that all
384                  * theme choices made by the modules can take effect.
385                  */
386                 $this->initHead($app, $module, $l10n, $config, $pconfig);
387
388                 /* Build the page ending -- this is stuff that goes right before
389                  * the closing </body> tag
390                  */
391                 $this->initFooter($app, $mode, $l10n);
392
393                 if (!$mode->isAjax()) {
394                         Hook::callAll('page_end', $this->page['content']);
395                 }
396
397                 // Add the navigation (menu) template
398                 if ($moduleName != 'install' && $moduleName != 'maintenance') {
399                         $this->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('nav_head.tpl'), []);
400                         $this->page['nav']      = Nav::build($app);
401                 }
402
403                 // Build the page - now that we have all the components
404                 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
405                         $doc = new DOMDocument();
406
407                         $target = new DOMDocument();
408                         $target->loadXML("<root></root>");
409
410                         $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
411
412                         /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
413                         @$doc->loadHTML($content);
414
415                         $xpath = new DOMXPath($doc);
416
417                         $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]");  /* */
418
419                         foreach ($list as $item) {
420                                 $item = $target->importNode($item, true);
421
422                                 // And then append it to the target
423                                 $target->documentElement->appendChild($item);
424                         }
425
426                         if ($_GET["mode"] == "raw") {
427                                 header("Content-type: text/html; charset=utf-8");
428
429                                 echo substr($target->saveHTML(), 6, -8);
430
431                                 exit();
432                         }
433                 }
434
435                 $page    = $this->page;
436                 $profile = $app->profile;
437
438                 header("X-Friendica-Version: " . FRIENDICA_VERSION);
439                 header("Content-type: text/html; charset=utf-8");
440
441                 if ($config->get('system', 'hsts') && ($baseURL->getSSLPolicy() == BaseURL::SSL_POLICY_FULL)) {
442                         header("Strict-Transport-Security: max-age=31536000");
443                 }
444
445                 // Some security stuff
446                 header('X-Content-Type-Options: nosniff');
447                 header('X-XSS-Protection: 1; mode=block');
448                 header('X-Permitted-Cross-Domain-Policies: none');
449                 header('X-Frame-Options: sameorigin');
450
451                 // Things like embedded OSM maps don't work, when this is enabled
452                 // header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' https: data:; media-src 'self' https:; child-src 'self' https:; object-src 'none'");
453
454                 /* We use $_GET["mode"] for special page templates. So we will check if we have
455                  * to load another page template than the default one.
456                  * The page templates are located in /view/php/ or in the theme directory.
457                  */
458                 if (isset($_GET["mode"])) {
459                         $template = Theme::getPathForFile($_GET["mode"] . '.php');
460                 }
461
462                 // If there is no page template use the default page template
463                 if (empty($template)) {
464                         $template = Theme::getPathForFile("default.php");
465                 }
466
467                 // Theme templates expect $a as an App instance
468                 $a = $app;
469
470                 // Used as is in view/php/default.php
471                 $lang = $l10n->getCurrentLang();
472
473                 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
474                 require_once $template;
475         }
476 }