summaryrefslogtreecommitdiffstats
path: root/app/classes/OpmlManager.php
blob: 679d1c43053f046db5fddf9c223a1f954cfb49e8 (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
84
85
86
87
88
<?php


class OpmlManager
{
    public static function load(string $file) : Opml
    {
        if (!file_exists($file)) {
            throw new Exception('OPML file not found!');
        }

        $opml = new Opml();

        //Remove BOM if needed
        $BOM = '/^/';
        $fileContent = file_get_contents($file);
        $fileContent = preg_replace($BOM, '', $fileContent, 1);

        //Parse
        $opml->parse($fileContent);

        return $opml;
    }

    public static function format(Opml $opml, $freezeDateModified = false) : string
    {
        $owner = '';
        if ($opml->ownerName != '') {
            $owner .= '<ownerName>'.htmlspecialchars($opml->ownerName).'</ownerName>'."\n";
        }
        if ($opml->ownerEmail != '') {
            $owner .= '<ownerEmail>'.htmlspecialchars($opml->ownerEmail).'</ownerEmail>'."\n";
        }
        if ($opml->ownerId != '') {
            $owner .= '<ownerId>'.htmlspecialchars($opml->ownerId).'</ownerId>'."\n";
        }

        $entries = '';
        foreach ($opml->entries as $person) {
            $entries .= sprintf(
                "\t" . '<outline text="%s" htmlUrl="%s" xmlUrl="%s" isDown="%s" />',
                htmlspecialchars($person['name'], ENT_QUOTES),
                htmlspecialchars($person['website'], ENT_QUOTES),
                htmlspecialchars($person['feed'], ENT_QUOTES),
                htmlspecialchars($person['isDown'] ?? '', ENT_QUOTES)
            ) . "\n";
        }

        $template = <<<XML
<?xml version="1.0"?>
<opml version="2.0">
<head>
    <title>%s</title>
    <dateCreated>%s</dateCreated>
    <dateModified>%s</dateModified>
    %s
    <docs>http://opml.org/spec2.opml</docs>
</head>
<body>
%s
</body>
</opml>
XML;

        return sprintf(
            $template,
            htmlspecialchars($opml->getTitle()),
            $opml->dateCreated,
            $freezeDateModified ? $opml->dateModified : date_format(date_create('now', new DateTimeZone('UTC')), DateTimeInterface::ATOM),
            $owner,
            $entries
        );
    }

    /**
     * @param Opml   $opml
     * @param string $file
     */
    public static function save(Opml $opml, string $file) : int|bool
    {
        return file_put_contents($file, self::format($opml));
    }

    public static function backup($file)
    {
        copy($file, $file.'.bak');
    }
}