Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

iss1315 - Emulate Moodle download_file_content function in API #1319

Merged
merged 1 commit into from
Nov 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions api/emulation/MoodleEmulation.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
define('MOODLE_INTERNAL', true);
define('PARAM_RAW', 'raw');
define('PARAM_PLUGIN', true);
define('PARAM_URL', true);

require_once('../config.php');
// Required to pass Moodle code check.
Expand Down Expand Up @@ -98,6 +99,57 @@ public function get_area_files($x, $y, $z, $a) {
return $storage;
}

/**
* Fetches content of file from Internet.
* Due to security concerns only downloads from http(s) sources are supported.
* (This is extremely stripped down from the Moodle function in lib/filelib.php which
* utilises the Moodle curl class.
* https://github.com/totara/moodle/blob/dda862abb57f656633f0736b858f7f048efd44bb/lib/filelib.php#L1172)
*
* @param string $url file url starting with http(s)://
* @return string|bool false if request failed or the file content as a string.
*/
function download_file_content($url) {
global $CFG;

// Only http and https links supported.
if (!preg_match('|^https?://|i', $url)) {
return false;
}

$options = [];
$options[CURLOPT_SSL_VERIFYPEER] = 1;
$options[CURLOPT_CONNECTTIMEOUT] = 20;
$options[CURLOPT_FOLLOWLOCATION] = 1;
$options[CURLOPT_MAXREDIRS] = 5;
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_NOBODY] = false;
$options[CURLOPT_TIMEOUT] = 300;
$options[CURLOPT_HTTPGET] = 1;
$options[CURLOPT_URL] = $url;
$curl = curl_init();
foreach ($options as $name => $value) {
curl_setopt($curl, $name, $value);
}

$result = curl_exec($curl);
$info = curl_getinfo($curl);
$error_no = curl_errno($curl);

if ($error_no) {
return false;
}
if (empty($info['http_code'])) {
// For security reasons we support only true http connections (Location: file:// exploit prevention).
return false;
}
if ($info['http_code'] != 200) {
return false;
}

return $result;
}

// Specialized emulations.
require_once('Constants.php');
require_once('Localization.php');
Expand Down
Loading