From 34c0d46e9469ade205f38f6ba85f8cfd4a088d97 Mon Sep 17 00:00:00 2001 From: Dan Poltawski Date: Wed, 24 Aug 2011 15:20:46 +0100 Subject: [PATCH] MDL-29091 weblib - Introduce out_as_local_url() method to moodle_url This can be used for passing around PARAM_LOCALURL's where necessary stripping the wwwroot --- lib/simpletest/testweblib.php | 9 +++++++++ lib/weblib.php | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/lib/simpletest/testweblib.php b/lib/simpletest/testweblib.php index 35caacab4cd..bdcdd5509de 100644 --- a/lib/simpletest/testweblib.php +++ b/lib/simpletest/testweblib.php @@ -127,6 +127,15 @@ class web_test extends UnitTestCase { $this->assertTrue($url1->compare($url2, URL_MATCH_EXACT)); } + function test_out_as_local_url() { + $url1 = new moodle_url('/lib/simpletest/testweblib.php'); + $this->assertEqual('/lib/simpletest/testweblib.php', $url1->out_as_local_url()); + + $url2 = new moodle_url('http://www.google.com/lib/simpletest/testweblib.php'); + $this->expectException('coding_exception'); + $url2->out_as_local_url(); + } + public function test_html_to_text_simple() { $this->assertEqual("\n\n_Hello_ WORLD!", html_to_text('

Hello world!

')); } diff --git a/lib/weblib.php b/lib/weblib.php index 89bdce5d639..c97e06b9d9c 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -717,6 +717,28 @@ class moodle_url { $urlbase = "$CFG->wwwroot/file.php"; return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload); } + + /** + * Returns URL a relative path from $CFG->wwwroot + * + * Can be used for passing around urls with the wwwroot stripped + * + * @param boolean $escaped Use & as params separator instead of plain & + * @param array $overrideparams params to add to the output url, these override existing ones with the same name. + * @return string Resulting URL + * @throws coding_exception if called on a non-local url + */ + public function out_as_local_url($escaped = true, array $overrideparams = null) { + global $CFG; + + $url = $this->out($escaped, $overrideparams); + + if (strpos($url, $CFG->wwwroot) !== 0) { + throw new coding_exception('out_as_local_url called on a non-local URL'); + } + + return str_replace($CFG->wwwroot, '', $url); + } } /**