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