From 6347de2635e70daf85d273dfee27e91079fa8d82 Mon Sep 17 00:00:00 2001 From: Joshua Ramon Enslin Date: Sat, 5 Mar 2022 13:58:18 +0100 Subject: [PATCH] Validate Wikidata IDs before attempting to fetch from Wikidata Close #8 --- src/NodaWikidataFetcher.php | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/NodaWikidataFetcher.php b/src/NodaWikidataFetcher.php index f742054..7bdec52 100644 --- a/src/NodaWikidataFetcher.php +++ b/src/NodaWikidataFetcher.php @@ -86,6 +86,26 @@ final class NodaWikidataFetcher { /** @var MDMysqli */ private MDMysqli $_mysqli_noda; + /** + * Validates a Wikidata ID. A Wikidata ID must start with a capital Q and be + * numeric otherwise. + * + * @param string $wikidata_id Input ID to validate. + * + * @return void + */ + public static function validateWikidataId(string $wikidata_id):void { + + if (substr($wikidata_id, 0, 1) !== 'Q') { + throw new MDgenericInvalidInputsException("Wikidata IDs start with Q"); + } + + if (!is_numeric(substr($wikidata_id, 1))) { + throw new MDgenericInvalidInputsException("Wikidata IDs are numeric following the Q"); + } + + } + /** * Attempts to fetch a Wikidata ID from a provided URL. * @@ -714,6 +734,8 @@ final class NodaWikidataFetcher { */ public function retrievePersinstInfoFromWikidataID(string $lang, string $wikidata_id, int $persinst_id, string $erfasst_von) { + self::validateWikidataId($wikidata_id); + $data = json_decode(MD_STD::runCurl("https://www.wikidata.org/wiki/Special:EntityData/" . $wikidata_id . ".json", 10000), true); if ($data === null) { throw new MDhttpFailedException("Failed fetching from Wikidata. Try again later."); @@ -1054,6 +1076,8 @@ final class NodaWikidataFetcher { */ public function retrievePlaceInfoFromWikidataID(string $lang, string $wikidata_id, int $onum, string $erfasst_von) { + self::validateWikidataId($wikidata_id); + $data = MD_STD::runCurl("https://www.wikidata.org/wiki/Special:EntityData/" . urlencode($wikidata_id) . ".json", 10000); if (!$data = json_decode($data, true)) { throw new MDhttpFailedException("Failed fetching from Wikidata. Try again later."); @@ -1455,6 +1479,8 @@ final class NodaWikidataFetcher { */ public function retrieveTagInfoFromWikidataID(string $lang, string $wikidata_id, int $tag_id, string $erfasst_von) { + self::validateWikidataId($wikidata_id); + $data = MD_STD::runCurl("https://www.wikidata.org/wiki/Special:EntityData/" . $wikidata_id . ".json", 10000); $data = json_decode($data, true); if ($data === null) {