]> git.mxchange.org Git - friendica.git/blob - src/App/Page.php
Simplify Theme::getPathForfile to expand its uses
[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 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         /**
43          * @var string The basepath of the page
44          */
45         private $basePath;
46
47         /**
48          * @param string $basepath The Page basepath
49          */
50         public function __construct(string $basepath)
51         {
52                 $this->basePath = $basepath;
53
54                 $this->page = [
55                         'aside'       => '',
56                         'bottom'      => '',
57                         'content'     => '',
58                         'footer'      => '',
59                         'htmlhead'    => '',
60                         'nav'         => '',
61                         'page_title'  => '',
62                         'right_aside' => '',
63                         'template'    => '',
64                         'title'       => ''
65                 ];
66         }
67
68         /**
69          * Whether a offset exists
70          *
71          * @link  https://php.net/manual/en/arrayaccess.offsetexists.php
72          *
73          * @param mixed $offset <p>
74          *                      An offset to check for.
75          *                      </p>
76          *
77          * @return boolean true on success or false on failure.
78          * </p>
79          * <p>
80          * The return value will be casted to boolean if non-boolean was returned.
81          * @since 5.0.0
82          */
83         public function offsetExists($offset)
84         {
85                 return isset($this->page[$offset]);
86         }
87
88         /**
89          * Offset to retrieve
90          *
91          * @link  https://php.net/manual/en/arrayaccess.offsetget.php
92          *
93          * @param mixed $offset <p>
94          *                      The offset to retrieve.
95          *                      </p>
96          *
97          * @return mixed Can return all value types.
98          * @since 5.0.0
99          */
100         public function offsetGet($offset)
101         {
102                 return $this->page[$offset] ?? null;
103         }
104
105         /**
106          * Offset to set
107          *
108          * @link  https://php.net/manual/en/arrayaccess.offsetset.php
109          *
110          * @param mixed $offset <p>
111          *                      The offset to assign the value to.
112          *                      </p>
113          * @param mixed $value  <p>
114          *                      The value to set.
115          *                      </p>
116          *
117          * @return void
118          * @since 5.0.0
119          */
120         public function offsetSet($offset, $value)
121         {
122                 $this->page[$offset] = $value;
123         }
124
125         /**
126          * Offset to unset
127          *
128          * @link  https://php.net/manual/en/arrayaccess.offsetunset.php
129          *
130          * @param mixed $offset <p>
131          *                      The offset to unset.
132          *                      </p>
133          *
134          * @return void
135          * @since 5.0.0
136          */
137         public function offsetUnset($offset)
138         {
139                 if (isset($this->page[$offset])) {
140                         unset($this->page[$offset]);
141                 }
142         }
143
144         /**
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.
148          *
149          * @param string $path
150          *
151          * @see Page::initHead()
152          *
153          */
154         public function registerStylesheet($path)
155         {
156                 if (mb_strpos($path, $this->basePath . DIRECTORY_SEPARATOR) === 0) {
157                         $path = mb_substr($path, mb_strlen($this->basePath . DIRECTORY_SEPARATOR));
158                 }
159
160                 $this->stylesheets[] = trim($path, '/');
161         }
162
163         /**
164          * Initializes Page->page['htmlhead'].
165          *
166          * Includes:
167          * - Page title
168          * - Favicons
169          * - Registered stylesheets (through App->registerStylesheet())
170          * - Infinite scroll data
171          * - head.tpl template
172          *
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)
178          *
179          * @throws HTTPException\InternalServerErrorException
180          */
181         private function initHead(App $app, Module $module, L10n $l10n, Configuration $config, PConfiguration $pConfig)
182         {
183                 $interval = ((local_user()) ? $pConfig->get(local_user(), 'system', 'update_interval') : 40000);
184
185                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
186                 if ($interval < 0) {
187                         $interval = 2147483647;
188                 }
189
190                 if ($interval < 10000) {
191                         $interval = 40000;
192                 }
193
194                 // Default title: current module called
195                 if (empty($this->page['title']) && $module->getName()) {
196                         $this->page['title'] = ucfirst($module->getName());
197                 }
198
199                 // Prepend the sitename to the page title
200                 $this->page['title'] = $config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
201
202                 if (!empty(Renderer::$theme['stylesheet'])) {
203                         $stylesheet = Renderer::$theme['stylesheet'];
204                 } else {
205                         $stylesheet = $app->getCurrentThemeStylesheetPath();
206                 }
207
208                 $this->registerStylesheet($stylesheet);
209
210                 $shortcut_icon = $config->get('system', 'shortcut_icon');
211                 if ($shortcut_icon == '') {
212                         $shortcut_icon = 'images/friendica-32.png';
213                 }
214
215                 $touch_icon = $config->get('system', 'touch_icon');
216                 if ($touch_icon == '') {
217                         $touch_icon = 'images/friendica-128.png';
218                 }
219
220                 Hook::callAll('head', $this->page['htmlhead']);
221
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
225                  * being first
226                  */
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'];
237         }
238
239         /**
240          * Initializes Page->page['footer'].
241          *
242          * Includes:
243          * - Javascript homebase
244          * - Mobile toggle link
245          * - Registered footer scripts (through App->registerFooterScript())
246          * - footer.tpl template
247          *
248          * @param App  $app  The Friendica App instance
249          * @param Mode $mode The Friendica runtime mode
250          * @param L10n $l10n The l10n instance
251          *
252          * @throws HTTPException\InternalServerErrorException
253          */
254         private function initFooter(App $app, Mode $mode, L10n $l10n)
255         {
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'];
261                 }
262
263                 if (isset($homebase)) {
264                         $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
265                 }
266
267                 /*
268                  * Add a "toggle mobile" link if we're using a mobile device
269                  */
270                 if ($mode->isMobile() || $mode->isTablet()) {
271                         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
272                                 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
273                         } else {
274                                 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
275                         }
276                         $this->page['footer'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
277                                 '$toggle_link' => $link,
278                                 '$toggle_text' => $l10n->t('toggle mobile')
279                         ]);
280                 }
281
282                 Hook::callAll('footer', $this->page['footer']);
283
284                 $tpl                  = Renderer::getMarkupTemplate('footer.tpl');
285                 $this->page['footer'] = Renderer::replaceMacros($tpl, [
286                         '$footerScripts' => array_unique($this->footerScripts),
287                 ]) . $this->page['footer'];
288         }
289
290         /**
291          * Initializes Page->page['content'].
292          *
293          * Includes:
294          * - module content
295          * - hooks for content
296          *
297          * @param Module $module The module
298          * @param Mode   $mode   The Friendica execution mode
299          *
300          * @throws HTTPException\InternalServerErrorException
301          */
302         private function initContent(Module $module, Mode $mode)
303         {
304                 $content = '';
305
306                 try {
307                         $moduleClass = $module->getClassName();
308
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);
317                 }
318
319                 // initialise content region
320                 if ($mode->isNormal()) {
321                         Hook::callAll('page_content_top', $this->page['content']);
322                 }
323
324                 $this->page['content'] .= $content;
325         }
326
327         /**
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.
331          *
332          * @param string $path
333          *
334          * @see Page::initFooter()
335          *
336          */
337         public function registerFooterScript($path)
338         {
339                 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
340
341                 $this->footerScripts[] = trim($url, '/');
342         }
343
344         /**
345          * Executes the creation of the current page and prints it to the screen
346          *
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
354          *
355          * @throws HTTPException\InternalServerErrorException
356          */
357         public function run(App $app, BaseURL $baseURL, Mode $mode, Module $module, L10n $l10n, Configuration $config, PConfiguration $pconfig)
358         {
359                 $moduleName = $module->getName();
360
361                 /* Create the page content.
362                  * Calls all hooks which are including content operations
363                  *
364                  * Sets the $Page->page['content'] variable
365                  */
366                 $this->initContent($module, $mode);
367
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;
373                 }
374
375                 if (function_exists(str_replace('-', '_', $currentTheme) . '_init')) {
376                         $func = str_replace('-', '_', $currentTheme) . '_init';
377                         $func($app);
378                 }
379
380                 /* Create the page head after setting the language
381                  * and getting any auth credentials.
382                  *
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.
386                  */
387                 $this->initHead($app, $module, $l10n, $config, $pconfig);
388
389                 /* Build the page ending -- this is stuff that goes right before
390                  * the closing </body> tag
391                  */
392                 $this->initFooter($app, $mode, $l10n);
393
394                 if (!$mode->isAjax()) {
395                         Hook::callAll('page_end', $this->page['content']);
396                 }
397
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);
402                 }
403
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();
407
408                         $target = new DOMDocument();
409                         $target->loadXML("<root></root>");
410
411                         $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
412
413                         /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
414                         @$doc->loadHTML($content);
415
416                         $xpath = new DOMXPath($doc);
417
418                         $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]");  /* */
419
420                         foreach ($list as $item) {
421                                 $item = $target->importNode($item, true);
422
423                                 // And then append it to the target
424                                 $target->documentElement->appendChild($item);
425                         }
426
427                         if ($_GET["mode"] == "raw") {
428                                 header("Content-type: text/html; charset=utf-8");
429
430                                 echo substr($target->saveHTML(), 6, -8);
431
432                                 exit();
433                         }
434                 }
435
436                 $page    = $this->page;
437                 $profile = $app->profile;
438
439                 header("X-Friendica-Version: " . FRIENDICA_VERSION);
440                 header("Content-type: text/html; charset=utf-8");
441
442                 if ($config->get('system', 'hsts') && ($baseURL->getSSLPolicy() == BaseURL::SSL_POLICY_FULL)) {
443                         header("Strict-Transport-Security: max-age=31536000");
444                 }
445
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');
451
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'");
454
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.
458                  */
459                 if (isset($_GET['mode'])) {
460                         $template = Theme::getPathForFile('php/' . Strings::sanitizeFilePathItem($_GET['mode']) . '.php');
461                 }
462
463                 // If there is no page template use the default page template
464                 if (empty($template)) {
465                         $template = Theme::getPathForFile('php/default.php');
466                 }
467
468                 // Theme templates expect $a as an App instance
469                 $a = $app;
470
471                 // Used as is in view/php/default.php
472                 $lang = $l10n->getCurrentLang();
473
474                 require_once $template;
475         }
476 }