3 namespace 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 use Friendica\Util\Strings;
21 * Contains the page specific environment variables for the current Page
22 * - Contains all stylesheets
23 * - Contains all footer-scripts
24 * - Contains all page specific content (header, footer, content, ...)
26 * The run() method is the single point where the page will get printed to the screen
28 class Page implements ArrayAccess
31 * @var array Contains all stylesheets, which should get loaded during page
35 * @var array Contains all scripts, which are added to the footer at last
37 private $footerScripts;
39 * @var array The page content, which are showed directly
43 * @var string The basepath of the page
48 * @param string $basepath The Page basepath
50 public function __construct(string $basepath)
52 $this->basePath = $basepath;
69 * Whether a offset exists
71 * @link https://php.net/manual/en/arrayaccess.offsetexists.php
73 * @param mixed $offset <p>
74 * An offset to check for.
77 * @return boolean true on success or false on failure.
80 * The return value will be casted to boolean if non-boolean was returned.
83 public function offsetExists($offset)
85 return isset($this->page[$offset]);
91 * @link https://php.net/manual/en/arrayaccess.offsetget.php
93 * @param mixed $offset <p>
94 * The offset to retrieve.
97 * @return mixed Can return all value types.
100 public function offsetGet($offset)
102 return $this->page[$offset] ?? null;
108 * @link https://php.net/manual/en/arrayaccess.offsetset.php
110 * @param mixed $offset <p>
111 * The offset to assign the value to.
113 * @param mixed $value <p>
120 public function offsetSet($offset, $value)
122 $this->page[$offset] = $value;
128 * @link https://php.net/manual/en/arrayaccess.offsetunset.php
130 * @param mixed $offset <p>
131 * The offset to unset.
137 public function offsetUnset($offset)
139 if (isset($this->page[$offset])) {
140 unset($this->page[$offset]);
145 * Register a stylesheet file path to be included in the <head> tag of every page.
146 * Inclusion is done in App->initHead().
147 * The path can be absolute or relative to the Friendica installation base folder.
149 * @param string $path
151 * @see Page::initHead()
154 public function registerStylesheet($path)
156 if (mb_strpos($path, $this->basePath . DIRECTORY_SEPARATOR) === 0) {
157 $path = mb_substr($path, mb_strlen($this->basePath . DIRECTORY_SEPARATOR));
160 $this->stylesheets[] = trim($path, '/');
164 * Initializes Page->page['htmlhead'].
169 * - Registered stylesheets (through App->registerStylesheet())
170 * - Infinite scroll data
171 * - head.tpl template
173 * @param App $app The Friendica App instance
174 * @param Module $module The loaded Friendica module
175 * @param L10n $l10n The l10n language instance
176 * @param Configuration $config The Friendica configuration
177 * @param PConfiguration $pConfig The Friendica personal configuration (for user)
179 * @throws HTTPException\InternalServerErrorException
181 private function initHead(App $app, Module $module, L10n $l10n, Configuration $config, PConfiguration $pConfig)
183 $interval = ((local_user()) ? $pConfig->get(local_user(), 'system', 'update_interval') : 40000);
185 // If the update is 'deactivated' set it to the highest integer number (~24 days)
187 $interval = 2147483647;
190 if ($interval < 10000) {
194 // Default title: current module called
195 if (empty($this->page['title']) && $module->getName()) {
196 $this->page['title'] = ucfirst($module->getName());
199 // Prepend the sitename to the page title
200 $this->page['title'] = $config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
202 if (!empty(Renderer::$theme['stylesheet'])) {
203 $stylesheet = Renderer::$theme['stylesheet'];
205 $stylesheet = $app->getCurrentThemeStylesheetPath();
208 $this->registerStylesheet($stylesheet);
210 $shortcut_icon = $config->get('system', 'shortcut_icon');
211 if ($shortcut_icon == '') {
212 $shortcut_icon = 'images/friendica-32.png';
215 $touch_icon = $config->get('system', 'touch_icon');
216 if ($touch_icon == '') {
217 $touch_icon = 'images/friendica-128.png';
220 Hook::callAll('head', $this->page['htmlhead']);
222 $tpl = Renderer::getMarkupTemplate('head.tpl');
223 /* put the head template at the beginning of page['htmlhead']
224 * since the code added by the modules frequently depends on it
227 $this->page['htmlhead'] = Renderer::replaceMacros($tpl, [
228 '$local_user' => local_user(),
229 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
230 '$delitem' => $l10n->t('Delete this item?'),
231 '$update_interval' => $interval,
232 '$shortcut_icon' => $shortcut_icon,
233 '$touch_icon' => $touch_icon,
234 '$block_public' => intval($config->get('system', 'block_public')),
235 '$stylesheets' => array_unique($this->stylesheets),
236 ]) . $this->page['htmlhead'];
240 * Initializes Page->page['footer'].
243 * - Javascript homebase
244 * - Mobile toggle link
245 * - Registered footer scripts (through App->registerFooterScript())
246 * - footer.tpl template
248 * @param App $app The Friendica App instance
249 * @param Mode $mode The Friendica runtime mode
250 * @param L10n $l10n The l10n instance
252 * @throws HTTPException\InternalServerErrorException
254 private function initFooter(App $app, Mode $mode, L10n $l10n)
256 // If you're just visiting, let javascript take you home
257 if (!empty($_SESSION['visitor_home'])) {
258 $homebase = $_SESSION['visitor_home'];
259 } elseif (local_user()) {
260 $homebase = 'profile/' . $app->user['nickname'];
263 if (isset($homebase)) {
264 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
268 * Add a "toggle mobile" link if we're using a mobile device
270 if ($mode->isMobile() || $mode->isTablet()) {
271 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
272 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
274 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
276 $this->page['footer'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
277 '$toggle_link' => $link,
278 '$toggle_text' => $l10n->t('toggle mobile')
282 Hook::callAll('footer', $this->page['footer']);
284 $tpl = Renderer::getMarkupTemplate('footer.tpl');
285 $this->page['footer'] = Renderer::replaceMacros($tpl, [
286 '$footerScripts' => array_unique($this->footerScripts),
287 ]) . $this->page['footer'];
291 * Initializes Page->page['content'].
295 * - hooks for content
297 * @param Module $module The module
298 * @param Mode $mode The Friendica execution mode
300 * @throws HTTPException\InternalServerErrorException
302 private function initContent(Module $module, Mode $mode)
307 $moduleClass = $module->getClassName();
309 $arr = ['content' => $content];
310 Hook::callAll($moduleClass . '_mod_content', $arr);
311 $content = $arr['content'];
312 $arr = ['content' => call_user_func([$moduleClass, 'content'], $module->getParameters())];
313 Hook::callAll($moduleClass . '_mod_aftercontent', $arr);
314 $content .= $arr['content'];
315 } catch (HTTPException $e) {
316 $content = ModuleHTTPException::content($e);
319 // initialise content region
320 if ($mode->isNormal()) {
321 Hook::callAll('page_content_top', $this->page['content']);
324 $this->page['content'] .= $content;
328 * Register a javascript file path to be included in the <footer> tag of every page.
329 * Inclusion is done in App->initFooter().
330 * The path can be absolute or relative to the Friendica installation base folder.
332 * @param string $path
334 * @see Page::initFooter()
337 public function registerFooterScript($path)
339 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
341 $this->footerScripts[] = trim($url, '/');
345 * Executes the creation of the current page and prints it to the screen
347 * @param App $app The Friendica App
348 * @param BaseURL $baseURL The Friendica Base URL
349 * @param Mode $mode The current node mode
350 * @param Module $module The loaded Friendica module
351 * @param L10n $l10n The l10n language class
352 * @param Configuration $config The Configuration of this node
353 * @param PConfiguration $pconfig The personal/user configuration
355 * @throws HTTPException\InternalServerErrorException
357 public function run(App $app, BaseURL $baseURL, Mode $mode, Module $module, L10n $l10n, Configuration $config, PConfiguration $pconfig)
359 $moduleName = $module->getName();
361 /* Create the page content.
362 * Calls all hooks which are including content operations
364 * Sets the $Page->page['content'] variable
366 $this->initContent($module, $mode);
368 // Load current theme info after module has been initialized as theme could have been set in module
369 $currentTheme = $app->getCurrentTheme();
370 $theme_info_file = 'view/theme/' . $currentTheme . '/theme.php';
371 if (file_exists($theme_info_file)) {
372 require_once $theme_info_file;
375 if (function_exists(str_replace('-', '_', $currentTheme) . '_init')) {
376 $func = str_replace('-', '_', $currentTheme) . '_init';
380 /* Create the page head after setting the language
381 * and getting any auth credentials.
383 * Moved initHead() and initFooter() to after
384 * all the module functions have executed so that all
385 * theme choices made by the modules can take effect.
387 $this->initHead($app, $module, $l10n, $config, $pconfig);
389 /* Build the page ending -- this is stuff that goes right before
390 * the closing </body> tag
392 $this->initFooter($app, $mode, $l10n);
394 if (!$mode->isAjax()) {
395 Hook::callAll('page_end', $this->page['content']);
398 // Add the navigation (menu) template
399 if ($moduleName != 'install' && $moduleName != 'maintenance') {
400 $this->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('nav_head.tpl'), []);
401 $this->page['nav'] = Nav::build($app);
404 // Build the page - now that we have all the components
405 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
406 $doc = new DOMDocument();
408 $target = new DOMDocument();
409 $target->loadXML("<root></root>");
411 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
413 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
414 @$doc->loadHTML($content);
416 $xpath = new DOMXPath($doc);
418 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
420 foreach ($list as $item) {
421 $item = $target->importNode($item, true);
423 // And then append it to the target
424 $target->documentElement->appendChild($item);
427 if ($_GET["mode"] == "raw") {
428 header("Content-type: text/html; charset=utf-8");
430 echo substr($target->saveHTML(), 6, -8);
437 $profile = $app->profile;
439 header("X-Friendica-Version: " . FRIENDICA_VERSION);
440 header("Content-type: text/html; charset=utf-8");
442 if ($config->get('system', 'hsts') && ($baseURL->getSSLPolicy() == BaseURL::SSL_POLICY_FULL)) {
443 header("Strict-Transport-Security: max-age=31536000");
446 // Some security stuff
447 header('X-Content-Type-Options: nosniff');
448 header('X-XSS-Protection: 1; mode=block');
449 header('X-Permitted-Cross-Domain-Policies: none');
450 header('X-Frame-Options: sameorigin');
452 // Things like embedded OSM maps don't work, when this is enabled
453 // 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'");
455 /* We use $_GET["mode"] for special page templates. So we will check if we have
456 * to load another page template than the default one.
457 * The page templates are located in /view/php/ or in the theme directory.
459 if (isset($_GET['mode'])) {
460 $template = Theme::getPathForFile('php/' . Strings::sanitizeFilePathItem($_GET['mode']) . '.php');
463 // If there is no page template use the default page template
464 if (empty($template)) {
465 $template = Theme::getPathForFile('php/default.php');
468 // Theme templates expect $a as an App instance
471 // Used as is in view/php/default.php
472 $lang = $l10n->getCurrentLang();
474 require_once $template;