From 7cd6eefe28c567297718f2a4f25e2b3c93f67587 Mon Sep 17 00:00:00 2001 From: Juan Leyva Date: Wed, 2 Mar 2016 11:14:31 +0100 Subject: [PATCH] MDL-53175 file: Allow file_rewrite_pluginfile_urls to reverse --- lib/filelib.php | 10 ++++++++-- lib/tests/filelib_test.php | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/lib/filelib.php b/lib/filelib.php index 059eb2ca3c3d1..39a7dacaee4d2 100644 --- a/lib/filelib.php +++ b/lib/filelib.php @@ -445,6 +445,8 @@ function file_prepare_draft_area(&$draftitemid, $contextid, $component, $fileare /** * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL. + * Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs + * in the @@PLUGINFILE@@ form. * * @category files * @global stdClass $CFG @@ -454,7 +456,7 @@ function file_prepare_draft_area(&$draftitemid, $contextid, $component, $fileare * @param string $component * @param string $filearea helps identify the file area. * @param int $itemid helps identify the file area. - * @param array $options text and file options ('forcehttps'=>false) + * @param array $options text and file options ('forcehttps'=>false), use reverse = true to reverse the behaviour of the function. * @return string the processed text. */ function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) { @@ -479,7 +481,11 @@ function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $fil $baseurl = str_replace('http://', 'https://', $baseurl); } - return str_replace('@@PLUGINFILE@@/', $baseurl, $text); + if (!empty($options['reverse'])) { + return str_replace($baseurl, '@@PLUGINFILE@@/', $text); + } else { + return str_replace('@@PLUGINFILE@@/', $baseurl, $text); + } } /** diff --git a/lib/tests/filelib_test.php b/lib/tests/filelib_test.php index 555a45cb235de..78854dd887d8c 100644 --- a/lib/tests/filelib_test.php +++ b/lib/tests/filelib_test.php @@ -951,6 +951,26 @@ public function test_curl_useragent() { $this->assertSame(0, $extcurl->get_errno()); $this->assertSame('', $contents); } + + /** + * Test file_rewrite_pluginfile_urls. + */ + public function test_file_rewrite_pluginfile_urls() { + + $syscontext = context_system::instance(); + $originaltext = 'Fake test with an image '; + + // Do the rewrite. + $finaltext = file_rewrite_pluginfile_urls($originaltext, 'pluginfile.php', $syscontext->id, 'user', 'private', 0); + $this->assertContains("pluginfile.php", $finaltext); + + // Now undo. + $options = array('reverse' => true); + $finaltext = file_rewrite_pluginfile_urls($finaltext, 'pluginfile.php', $syscontext->id, 'user', 'private', 0, $options); + + // Compare the final text is the same that the original. + $this->assertEquals($originaltext, $finaltext); + } } /**