From 9f7ba7599ea93847dd3cce972e3f6e357d6d4a02 Mon Sep 17 00:00:00 2001 From: Casey Peel Date: Wed, 14 Oct 2026 14:31:39 -0700 Subject: [PATCH] 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. --- pinc/RandomRule.inc | 23 ++++++++++++++++++++++- tools/site_admin/manage_random_rules.php | 11 ++++++++--- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/pinc/RandomRule.inc b/pinc/RandomRule.inc index c1b617256..eeb9aa6a7 100644 --- a/pinc/RandomRule.inc +++ b/pinc/RandomRule.inc @@ -202,10 +202,31 @@ class RandomRule // delete all existing random rules for this ($document, $langcode) RandomRule::delete_rules($document, $langcode); - if (($fhandle = fopen($url, "rt")) === false) { + // basic HTTP contexts for the fopen -- mostly a placeholder for + // customization in other branches who want to set specific headers + $context_opts = [ + 'http' => [ + 'method' => "GET", + ], + ]; + + $context = stream_context_create($context_opts); + if (($fhandle = fopen($url, "rt", context: $context)) === false) { throw new RuntimeException(sprintf(_("Failed to load rules from %s."), $url)); } + $meta_data = stream_get_meta_data($fhandle); + $status_line = $meta_data["wrapper_data"][0] ?? ""; + if (! preg_match("/HTTP\/\S+\s+200\b/", $status_line)) { + throw new RuntimeException( + sprintf( + "%s %s", + sprintf(_("Failed to load rules from %s."), $url), + $status_line + ) + ); + } + $anchor = $subject = $rule = ""; $in_rule = false; while ($line = fgets($fhandle)) { diff --git a/tools/site_admin/manage_random_rules.php b/tools/site_admin/manage_random_rules.php index 36ee8ac10..34176a64d 100644 --- a/tools/site_admin/manage_random_rules.php +++ b/tools/site_admin/manage_random_rules.php @@ -23,9 +23,14 @@ // do POST actions if ($action == 'update') { - RandomRule::reload_rules($url, $document, $langcode); - // TRANSLATORS: %3$s is a URL - echo "

" . sprintf(_('Loaded rules for document %1$s and language %2$s from %3$s.'), RandomRule::$document_values[$document], $langcode, $url) . "

"; + try { + RandomRule::reload_rules($url, $document, $langcode); + + // TRANSLATORS: %3$s is a URL + echo "

" . sprintf(_('Loaded rules for document %1$s and language %2$s from %3$s.'), RandomRule::$document_values[$document], $langcode, $url) . "

"; + } catch (RuntimeException $exception) { + echo "

" . $exception->getMessage() . "

"; + } } elseif ($action == 'delete') { RandomRule::delete_rules($document, $langcode); echo "

" . sprintf(_('Deleted rules for document %1$s and language %2$s.'), RandomRule::$document_values[$document], $langcode) . "

";