3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\App;
28 use Friendica\Content\Nav;
29 use Friendica\Core\Config\IConfig;
30 use Friendica\Core\PConfig\IPConfig;
31 use Friendica\Core\Hook;
32 use Friendica\Core\L10n;
33 use Friendica\Core\Renderer;
34 use Friendica\Core\Theme;
35 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
36 use Friendica\Network\HTTPException;
37 use Friendica\Util\Network;
38 use Friendica\Util\Strings;
41 * Contains the page specific environment variables for the current Page
42 * - Contains all stylesheets
43 * - Contains all footer-scripts
44 * - Contains all page specific content (header, footer, content, ...)
46 * The run() method is the single point where the page will get printed to the screen
48 class Page implements ArrayAccess
51 * @var array Contains all stylesheets, which should get loaded during page
53 private $stylesheets = [];
55 * @var array Contains all scripts, which are added to the footer at last
57 private $footerScripts = [];
59 * @var array The page content, which are showed directly
74 * @var string The basepath of the page
79 * @param string $basepath The Page basepath
81 public function __construct(string $basepath)
83 $this->basePath = $basepath;
87 * Whether a offset exists
89 * @link https://php.net/manual/en/arrayaccess.offsetexists.php
91 * @param mixed $offset <p>
92 * An offset to check for.
95 * @return boolean true on success or false on failure.
98 * The return value will be casted to boolean if non-boolean was returned.
101 public function offsetExists($offset)
103 return isset($this->page[$offset]);
109 * @link https://php.net/manual/en/arrayaccess.offsetget.php
111 * @param mixed $offset <p>
112 * The offset to retrieve.
115 * @return mixed Can return all value types.
118 public function offsetGet($offset)
120 return $this->page[$offset] ?? null;
126 * @link https://php.net/manual/en/arrayaccess.offsetset.php
128 * @param mixed $offset <p>
129 * The offset to assign the value to.
131 * @param mixed $value <p>
138 public function offsetSet($offset, $value)
140 $this->page[$offset] = $value;
146 * @link https://php.net/manual/en/arrayaccess.offsetunset.php
148 * @param mixed $offset <p>
149 * The offset to unset.
155 public function offsetUnset($offset)
157 if (isset($this->page[$offset])) {
158 unset($this->page[$offset]);
163 * Register a stylesheet file path to be included in the <head> tag of every page.
164 * Inclusion is done in App->initHead().
165 * The path can be absolute or relative to the Friendica installation base folder.
167 * @param string $path
169 * @see Page::initHead()
172 public function registerStylesheet($path)
174 $path = Network::appendQueryParam($path, ['v' => FRIENDICA_VERSION]);
176 if (mb_strpos($path, $this->basePath . DIRECTORY_SEPARATOR) === 0) {
177 $path = mb_substr($path, mb_strlen($this->basePath . DIRECTORY_SEPARATOR));
180 $this->stylesheets[] = trim($path, '/');
184 * Initializes Page->page['htmlhead'].
189 * - Registered stylesheets (through App->registerStylesheet())
190 * - Infinite scroll data
191 * - head.tpl template
193 * @param App $app The Friendica App instance
194 * @param Module $module The loaded Friendica module
195 * @param L10n $l10n The l10n language instance
196 * @param IConfig $config The Friendica configuration
197 * @param IPConfig $pConfig The Friendica personal configuration (for user)
199 * @throws HTTPException\InternalServerErrorException
201 private function initHead(App $app, Module $module, L10n $l10n, IConfig $config, IPConfig $pConfig)
203 $interval = ((local_user()) ? $pConfig->get(local_user(), 'system', 'update_interval') : 40000);
205 // If the update is 'deactivated' set it to the highest integer number (~24 days)
207 $interval = 2147483647;
210 if ($interval < 10000) {
214 // Default title: current module called
215 if (empty($this->page['title']) && $module->getName()) {
216 $this->page['title'] = ucfirst($module->getName());
219 // Prepend the sitename to the page title
220 $this->page['title'] = $config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
222 if (!empty(Renderer::$theme['stylesheet'])) {
223 $stylesheet = Renderer::$theme['stylesheet'];
225 $stylesheet = $app->getCurrentThemeStylesheetPath();
228 $this->registerStylesheet($stylesheet);
230 $shortcut_icon = $config->get('system', 'shortcut_icon');
231 if ($shortcut_icon == '') {
232 $shortcut_icon = 'images/friendica-32.png';
235 $touch_icon = $config->get('system', 'touch_icon');
236 if ($touch_icon == '') {
237 $touch_icon = 'images/friendica-128.png';
240 Hook::callAll('head', $this->page['htmlhead']);
242 $tpl = Renderer::getMarkupTemplate('head.tpl');
243 /* put the head template at the beginning of page['htmlhead']
244 * since the code added by the modules frequently depends on it
247 $this->page['htmlhead'] = Renderer::replaceMacros($tpl, [
248 '$local_user' => local_user(),
249 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
250 '$delitem' => $l10n->t('Delete this item?'),
251 '$update_interval' => $interval,
252 '$shortcut_icon' => $shortcut_icon,
253 '$touch_icon' => $touch_icon,
254 '$block_public' => intval($config->get('system', 'block_public')),
255 '$stylesheets' => array_unique($this->stylesheets),
256 ]) . $this->page['htmlhead'];
260 * Initializes Page->page['footer'].
263 * - Javascript homebase
264 * - Mobile toggle link
265 * - Registered footer scripts (through App->registerFooterScript())
266 * - footer.tpl template
268 * @param App $app The Friendica App instance
269 * @param Mode $mode The Friendica runtime mode
270 * @param L10n $l10n The l10n instance
272 * @throws HTTPException\InternalServerErrorException
274 private function initFooter(App $app, Mode $mode, L10n $l10n)
276 // If you're just visiting, let javascript take you home
277 if (!empty($_SESSION['visitor_home'])) {
278 $homebase = $_SESSION['visitor_home'];
279 } elseif (local_user()) {
280 $homebase = 'profile/' . $app->user['nickname'];
283 if (isset($homebase)) {
284 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
288 * Add a "toggle mobile" link if we're using a mobile device
290 if ($mode->isMobile() || $mode->isTablet()) {
291 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
292 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
294 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
296 $this->page['footer'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
297 '$toggle_link' => $link,
298 '$toggle_text' => $l10n->t('toggle mobile')
302 Hook::callAll('footer', $this->page['footer']);
304 $tpl = Renderer::getMarkupTemplate('footer.tpl');
305 $this->page['footer'] = Renderer::replaceMacros($tpl, [
306 '$footerScripts' => array_unique($this->footerScripts),
307 ]) . $this->page['footer'];
311 * Initializes Page->page['content'].
315 * - hooks for content
317 * @param Module $module The module
318 * @param Mode $mode The Friendica execution mode
320 * @throws HTTPException\InternalServerErrorException
322 private function initContent(Module $module, Mode $mode)
327 $moduleClass = $module->getClassName();
329 $arr = ['content' => $content];
330 Hook::callAll($moduleClass . '_mod_content', $arr);
331 $content = $arr['content'];
332 $arr = ['content' => call_user_func([$moduleClass, 'content'], $module->getParameters())];
333 Hook::callAll($moduleClass . '_mod_aftercontent', $arr);
334 $content .= $arr['content'];
335 } catch (HTTPException $e) {
336 $content = ModuleHTTPException::content($e);
339 // initialise content region
340 if ($mode->isNormal()) {
341 Hook::callAll('page_content_top', $this->page['content']);
344 $this->page['content'] .= $content;
348 * Register a javascript file path to be included in the <footer> tag of every page.
349 * Inclusion is done in App->initFooter().
350 * The path can be absolute or relative to the Friendica installation base folder.
352 * @param string $path
354 * @see Page::initFooter()
357 public function registerFooterScript($path)
359 $path = Network::appendQueryParam($path, ['v' => FRIENDICA_VERSION]);
361 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
363 $this->footerScripts[] = trim($url, '/');
367 * Executes the creation of the current page and prints it to the screen
369 * @param App $app The Friendica App
370 * @param BaseURL $baseURL The Friendica Base URL
371 * @param Mode $mode The current node mode
372 * @param Module $module The loaded Friendica module
373 * @param L10n $l10n The l10n language class
374 * @param IConfig $config The Configuration of this node
375 * @param IPConfig $pconfig The personal/user configuration
377 * @throws HTTPException\InternalServerErrorException
379 public function run(App $app, BaseURL $baseURL, Mode $mode, Module $module, L10n $l10n, IConfig $config, IPConfig $pconfig)
381 $moduleName = $module->getName();
383 /* Create the page content.
384 * Calls all hooks which are including content operations
386 * Sets the $Page->page['content'] variable
388 $this->initContent($module, $mode);
390 // Load current theme info after module has been initialized as theme could have been set in module
391 $currentTheme = $app->getCurrentTheme();
392 $theme_info_file = 'view/theme/' . $currentTheme . '/theme.php';
393 if (file_exists($theme_info_file)) {
394 require_once $theme_info_file;
397 if (function_exists(str_replace('-', '_', $currentTheme) . '_init')) {
398 $func = str_replace('-', '_', $currentTheme) . '_init';
402 /* Create the page head after setting the language
403 * and getting any auth credentials.
405 * Moved initHead() and initFooter() to after
406 * all the module functions have executed so that all
407 * theme choices made by the modules can take effect.
409 $this->initHead($app, $module, $l10n, $config, $pconfig);
411 /* Build the page ending -- this is stuff that goes right before
412 * the closing </body> tag
414 $this->initFooter($app, $mode, $l10n);
416 if (!$mode->isAjax()) {
417 Hook::callAll('page_end', $this->page['content']);
420 // Add the navigation (menu) template
421 if ($moduleName != 'install' && $moduleName != 'maintenance') {
422 $this->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('nav_head.tpl'), []);
423 $this->page['nav'] = Nav::build($app);
426 // Build the page - now that we have all the components
427 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
428 $doc = new DOMDocument();
430 $target = new DOMDocument();
431 $target->loadXML("<root></root>");
433 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
435 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
436 @$doc->loadHTML($content);
438 $xpath = new DOMXPath($doc);
440 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
442 foreach ($list as $item) {
443 $item = $target->importNode($item, true);
445 // And then append it to the target
446 $target->documentElement->appendChild($item);
449 if ($_GET["mode"] == "raw") {
450 header("Content-type: text/html; charset=utf-8");
452 echo substr($target->saveHTML(), 6, -8);
459 $profile = $app->profile;
461 header("X-Friendica-Version: " . FRIENDICA_VERSION);
462 header("Content-type: text/html; charset=utf-8");
464 if ($config->get('system', 'hsts') && ($baseURL->getSSLPolicy() == BaseURL::SSL_POLICY_FULL)) {
465 header("Strict-Transport-Security: max-age=31536000");
468 // Some security stuff
469 header('X-Content-Type-Options: nosniff');
470 header('X-XSS-Protection: 1; mode=block');
471 header('X-Permitted-Cross-Domain-Policies: none');
472 header('X-Frame-Options: sameorigin');
474 // Things like embedded OSM maps don't work, when this is enabled
475 // 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'");
477 /* We use $_GET["mode"] for special page templates. So we will check if we have
478 * to load another page template than the default one.
479 * The page templates are located in /view/php/ or in the theme directory.
481 if (isset($_GET['mode'])) {
482 $template = Theme::getPathForFile('php/' . Strings::sanitizeFilePathItem($_GET['mode']) . '.php');
485 // If there is no page template use the default page template
486 if (empty($template)) {
487 $template = Theme::getPathForFile('php/default.php');
490 // Theme templates expect $a as an App instance
493 // Used as is in view/php/default.php
494 $lang = $l10n->getCurrentLang();
496 require_once $template;