summaryrefslogtreecommitdiff
path: root/includes/pages/user_atom.php
blob: 9a4d65a58e2df2b3488963b2e4c22578ed46accb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php

use Engelsystem\Http\Exceptions\HttpForbidden;
use Engelsystem\Models\News;
use Illuminate\Database\Eloquent\Collection;

/**
 * Publically available page to feed the news to feed readers
 */
function user_atom()
{
    $request = request();
    $user = auth()->apiUser('key');

    if (
        !$request->has('key')
        || !preg_match('/^[\da-f]{32}$/', $request->input('key'))
        || empty($user)
    ) {
        throw new HttpForbidden('Missing or invalid key', ['content-type' => 'text/text']);
    }

    if (!auth()->can('atom')) {
        throw new HttpForbidden('Not allowed', ['content-type' => 'text/text']);
    }

    $news = $request->has('meetings') ? News::whereIsMeeting((bool)$request->get('meetings', false)) : News::query();
    $news
        ->limit((int)config('display_news'))
        ->orderByDesc('updated_at');
    $output = make_atom_entries_from_news($news->get());

    header('Content-Type: application/atom+xml; charset=utf-8');
    header('Content-Length: ' . strlen($output));
    raw_output($output);
}

/**
 * @param News[]|Collection $news_entries
 * @return string
 */
function make_atom_entries_from_news($news_entries)
{
    $request = app('request');
    $updatedAt = isset($news_entries[0]) ? $news_entries[0]->updated_at->format('Y-m-d\TH:i:sP') : '0000:00:00T00:00:00+00:00';

    $html = '<?xml version="1.0" encoding="utf-8"?>
  <feed xmlns="http://www.w3.org/2005/Atom">
  <title>' . config('app_name') . '</title>
  <id>' . $request->getHttpHost()
        . htmlspecialchars(preg_replace(
            '#[&?]key=[a-f\d]{32}#',
            '',
            $request->getRequestUri()
        ))
        . '</id>
  <updated>' . $updatedAt . '</updated>' . "\n";
    foreach ($news_entries as $news_entry) {
        $html .= make_atom_entry_from_news($news_entry);
    }
    $html .= '</feed>';
    return $html;
}

/**
 * @param News $news
 * @return string
 */
function make_atom_entry_from_news(News $news)
{
    return '
  <entry>
    <title>' . htmlspecialchars($news->title) . '</title>
    <link href="' . page_link_to('news_comments', ['nid' => $news->id]) . '"/>
    <id>' . preg_replace(
            '#^https?://#',
            '',
            page_link_to('news_comments', ['nid' => $news->id])
        ) . '</id>
    <updated>' . $news->updated_at->format('Y-m-d\TH:i:sP') . '</updated>
    <summary type="html">' . htmlspecialchars($news->text) . '</summary>
  </entry>' . "\n";
}