From 4ddb4e8c2c3a61b7d78c17f6dafc9585beb0938c Mon Sep 17 00:00:00 2001 From: Dave Longley Date: Sat, 14 Sep 2013 21:27:55 -0400 Subject: [PATCH] Validate URLs; check for file/json read errors. --- jsonld.php | 11 ++++++++++- test.php | 14 +++++++++++--- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/jsonld.php b/jsonld.php index 211b134..072524f 100644 --- a/jsonld.php +++ b/jsonld.php @@ -5063,6 +5063,9 @@ class JsonLdProcessor { // for tracking the URLs to retrieve $urls = new stdClass(); + // regex for validating URLs + $regex = '/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/'; + // find all URLs in the given input $this->_findContextUrls($input, $urls, false, $base); @@ -5070,6 +5073,12 @@ class JsonLdProcessor { $queue = array(); foreach($urls as $url => $ctx) { if($ctx === false) { + // validate URL + if(!preg_match($regex, $url)) { + throw new JsonLdException( + 'Malformed or unsupported URL.', 'jsonld.InvalidUrl', + 'loading remote context failed', array('url' => $url)); + } $queue[] = $url; } } @@ -5098,7 +5107,7 @@ class JsonLdProcessor { catch(Exception $e) { throw new JsonLdException( 'Could not parse JSON from URL.', - 'jsonld.ParseError', 'invalid remote context', + 'jsonld.ParseError', 'loading remote context failed', array('url' => $url), $e); } } diff --git a/test.php b/test.php index 3ffe166..215ff50 100644 --- a/test.php +++ b/test.php @@ -570,15 +570,23 @@ class EarlReport implements PHPUnit_Framework_TestListener { class Util { public static function readFile($filename) { - return file_get_contents($filename); + $rval = @file_get_contents($filename); + if($rval === false) { + throw new Exception('File read error: ' . $filename); + } + return $rval; } public static function readJson($filename) { - return json_decode(file_get_contents($filename)); + $rval = json_decode(self::readFile($filename)); + if($rval === null) { + throw new Exception('JSON parse error'); + } + return $rval; } public static function readNQuads($filename) { - return readFile($filename); + return self::readFile($filename); } public static function jsonldEncode($input) {