This repository has been archived on 2024-09-05. You can view files and clone it, but cannot push or open issues or pull requests.
shimmie2/ext/static_files/main.php

76 lines
2.2 KiB
PHP
Raw Normal View History

2021-12-14 18:32:47 +00:00
<?php
declare(strict_types=1);
2018-11-11 17:38:32 +00:00
namespace Shimmie2;
class RobotsBuildingEvent extends Event
{
/** @var string[] */
public array $parts = [
"User-agent: *",
// Site is rate limited to 1 request / sec,
// returns 503 for more than that
"Crawl-delay: 3",
];
public function add_disallow(string $path): void
{
$this->parts[] = "Disallow: /$path";
}
}
class StaticFiles extends Extension
{
public function onPageRequest(PageRequestEvent $event): void
{
global $config, $page;
if ($event->page_matches("robots.txt")) {
$rbe = send_event(new RobotsBuildingEvent());
$page->set_mode(PageMode::DATA);
2023-03-30 21:27:12 +00:00
$page->set_mime("text/plain");
$page->set_data(join("\n", $rbe->parts));
}
// hax.
2019-06-19 01:58:28 +00:00
if ($page->mode == PageMode::PAGE && (!isset($page->blocks) || $this->count_main($page->blocks) == 0)) {
$h_pagename = html_escape(implode('/', $event->args));
$f_pagename = preg_replace_ex("/[^a-z_\-\.]+/", "_", $h_pagename);
2019-08-02 19:40:03 +00:00
$theme_name = $config->get_string(SetupConfig::THEME, "default");
2018-11-11 17:38:32 +00:00
$theme_file = "themes/$theme_name/static/$f_pagename";
$static_file = "ext/static_files/static/$f_pagename";
2018-11-11 17:38:32 +00:00
if (file_exists($theme_file) || file_exists($static_file)) {
$filename = file_exists($theme_file) ? $theme_file : $static_file;
2018-11-11 17:38:32 +00:00
$page->add_http_header("Cache-control: public, max-age=600");
$page->add_http_header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 600) . ' GMT');
2019-06-19 01:58:28 +00:00
$page->set_mode(PageMode::DATA);
$page->set_data(\Safe\file_get_contents($filename));
2020-06-14 16:05:55 +00:00
$page->set_mime(MimeType::get_for_file($filename));
}
}
}
2018-11-11 17:38:32 +00:00
/**
* @param Block[] $blocks
*/
private function count_main(array $blocks): int
{
$n = 0;
foreach ($blocks as $block) {
if ($block->section == "main" && $block->is_content) {
$n++;
} // more hax.
}
return $n;
}
2018-11-11 17:38:32 +00:00
public function get_priority(): int
{
return 98;
} // before 404
2018-11-11 17:38:32 +00:00
}