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