Skip to content

Commit 2bae0b6

Browse files
committed
Improve error handling for loading Random Rules
Provide better error handling when loading Random Rules and create a basic placeholder for other branches to enhance with any custom headers they want to include.
1 parent 2f71032 commit 2bae0b6

2 files changed

Lines changed: 30 additions & 4 deletions

File tree

‎pinc/RandomRule.inc‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,10 +202,31 @@ class RandomRule
202202
// delete all existing random rules for this ($document, $langcode)
203203
RandomRule::delete_rules($document, $langcode);
204204

205-
if (($fhandle = fopen($url, "rt")) === false) {
205+
// basic HTTP contexts for the fopen -- mostly a placeholder for
206+
// customization in other branches who want to set specific headers
207+
$context_opts = [
208+
'http' => [
209+
'method' => "GET",
210+
],
211+
];
212+
213+
$context = stream_context_create($context_opts);
214+
if (($fhandle = fopen($url, "rt", context: $context)) === false) {
206215
throw new RuntimeException(sprintf(_("Failed to load rules from %s."), $url));
207216
}
208217

218+
$meta_data = stream_get_meta_data($fhandle);
219+
$status_line = $meta_data["wrapper_data"][0] ?? "";
220+
if (! preg_match("/HTTP\/\S+\s+200\b/", $status_line)) {
221+
throw new RuntimeException(
222+
sprintf(
223+
"%s %s",
224+
sprintf(_("Failed to load rules from %s."), $url),
225+
$status_line
226+
)
227+
);
228+
}
229+
209230
$anchor = $subject = $rule = "";
210231
$in_rule = false;
211232
while ($line = fgets($fhandle)) {

‎tools/site_admin/manage_random_rules.php‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,14 @@
2323

2424
// do POST actions
2525
if ($action == 'update') {
26-
RandomRule::reload_rules($url, $document, $langcode);
27-
// TRANSLATORS: %3$s is a URL
28-
echo "<p class='warning'>" . sprintf(_('Loaded rules for document %1$s and language %2$s from %3$s.'), RandomRule::$document_values[$document], $langcode, $url) . "</p>";
26+
try {
27+
RandomRule::reload_rules($url, $document, $langcode);
28+
29+
// TRANSLATORS: %3$s is a URL
30+
echo "<p class='warning'>" . sprintf(_('Loaded rules for document %1$s and language %2$s from %3$s.'), RandomRule::$document_values[$document], $langcode, $url) . "</p>";
31+
} catch (RuntimeException $exception) {
32+
echo "<p class='error'>" . $exception->getMessage() . "</p>";
33+
}
2934
} elseif ($action == 'delete') {
3035
RandomRule::delete_rules($document, $langcode);
3136
echo "<p class='warning'>" . sprintf(_('Deleted rules for document %1$s and language %2$s.'), RandomRule::$document_values[$document], $langcode) . "</p>";

0 commit comments

Comments
 (0)