Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
78.05% covered (warning)
78.05%
32 / 41
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
releases
78.05% covered (warning)
78.05%
32 / 41
50.00% covered (danger)
50.00%
1 / 2
20.06
0.00% covered (danger)
0.00%
0 / 1
 latest
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 fetch
73.53% covered (warning)
73.53%
25 / 34
0.00% covered (danger)
0.00%
0 / 1
16.13
1<?php
2// This file is part of Moodle - https://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle.  If not, see <https://www.gnu.org/licenses/>.
16
17namespace message_notifyhub\local;
18
19/**
20 * The newest signed release of a channel, read from GitHub: the release zip, the SHA-256 GitHub publishes for
21 * it, and its signature file.
22 *
23 * Prereleases count while a channel has no stable release yet. Answers are kept for an hour, so the Gateways
24 * page does not use up GitHub's limit for anonymous calls.
25 *
26 * @package    message_notifyhub
27 * @copyright  2026 DevLMS <contact@devlms.com>
28 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 */
30final class releases {
31    /** @var int Seconds an answer from GitHub is kept. */
32    private const TTL = HOURSECS;
33
34    /** @var callable|null For tests: url => JSON text. */
35    public static $http = null;
36
37    /**
38     * The newest release of a channel that has an install zip, or null when GitHub has none or cannot be reached.
39     *
40     * @param string $name Component, such as message_ntfy.
41     * @param string $repo owner/name on GitHub.
42     * @param bool $fresh Ask GitHub even if a recent answer is kept.
43     * @return array|null tag, release (version text), url, sha256, sigurl
44     */
45    public static function latest(string $name, string $repo, bool $fresh = false): ?array {
46        $key = 'release_' . $name;
47        $kept = json_decode((string) get_config('message_notifyhub', $key), true);
48        if (!$fresh && is_array($kept) && ($kept['time'] ?? 0) > time() - self::TTL) {
49            return $kept['release'];
50        }
51        $release = self::fetch($name, $repo);
52        set_config($key, json_encode(['time' => time(), 'release' => $release]), 'message_notifyhub');
53        return $release;
54    }
55
56    /**
57     * Ask GitHub.
58     *
59     * @param string $name
60     * @param string $repo
61     * @return array|null
62     */
63    private static function fetch(string $name, string $repo): ?array {
64        global $CFG;
65        if (!preg_match('~^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$~', $repo)) {
66            return null;
67        }
68        $url = "https://api.github.com/repos/$repo/releases?per_page=10";
69        if (self::$http) {
70            $body = (self::$http)($url);
71        } else {
72            require_once($CFG->libdir . '/filelib.php');
73            $curl = new \curl();
74            $curl->setHeader(['Accept: application/vnd.github+json', 'User-Agent: Moodle-message_notifyhub']);
75            $body = $curl->get($url, [], ['CURLOPT_TIMEOUT' => 15, 'CURLOPT_CONNECTTIMEOUT' => 6]);
76            if ($curl->get_errno() || (int) ($curl->get_info()['http_code'] ?? 0) !== 200) {
77                return null;
78            }
79        }
80        $list = json_decode((string) $body, true);
81        if (!is_array($list)) {
82            return null;
83        }
84        foreach ($list as $release) {
85            if (!empty($release['draft'])) {
86                continue;
87            }
88            $assets = $release['assets'] ?? [];
89            $urls = array_column($assets, 'browser_download_url', 'name');
90            foreach ($assets as $asset) {
91                $digest = (string) ($asset['digest'] ?? '');
92                $sigurl = (string) ($urls[($asset['name'] ?? '') . '.sig'] ?? '');
93                if (
94                    preg_match('/^' . preg_quote($name, '/') . '-[0-9A-Za-z.+-]+\.zip$/', (string) ($asset['name'] ?? ''))
95                    && preg_match('/^sha256:([0-9a-f]{64})$/', $digest, $m)
96                    && str_starts_with((string) ($asset['browser_download_url'] ?? ''), 'https://github.com/' . $repo . '/')
97                    && str_starts_with($sigurl, 'https://github.com/' . $repo . '/')
98                ) {
99                    return [
100                        'tag' => (string) $release['tag_name'],
101                        'release' => ltrim((string) $release['tag_name'], 'v'),
102                        'url' => (string) $asset['browser_download_url'],
103                        'sha256' => $m[1],
104                        'sigurl' => $sigurl,
105                    ];
106                }
107            }
108        }
109        return null;
110    }
111}