Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading file to Moodle using the REST Service core_files_upload

I am developing an Android app, which will upload content to a user's private files in my Moodle installation using the REST webservice core_files_upload provided by Moodle. core_files_upload takes the following parameters:

contextid
component
filearea
itemid
filepath
filename
filecontent

The documentation for the Moodle Web Services isn't very detailed so I have pieced together what I can from the Moodle forums and Google searches, but I feel I have come to a dead end. From examples I have seen that the parameters take the following values:

contextid: int - not sure whether this is the userid
component: "user"
filearea: "private"
itemid: 0
filepath: "/"
filename: "filename.jpg"
filecontent: base64 encoding of file

I am using my userid as the contextid - I'm usnsure whether this is correct due to lack of documentation. When I post this I receieve the error:

{"exception":"moodle_exception","errorcode":"nofile","message":"File not specified"}

I have looked at where core_files_upload is defined in "moodle/files/externallib.php" and this error message is generated when filecontent is not present.

I have tried posting to a test script and I can successfully create the image on the Moodle server based on the base64 encoding eg:

<?php
file_put_contents('MyFile.jpg', base64_decode($_POST['filecontent']));

Can anyone shed light on why I am being unsuccessful uploading to Moodle?
Is the contextid the userid of the user doing the upload?

like image 978
amburnside Avatar asked Feb 15 '23 12:02

amburnside


1 Answers

Ok, so after a bit of further reading and hacking around with code I can confirm that the context id is not the user id, but is derived from the user id. I have not found any way in Moodle to get the the context id, so I have created my own. Once I had the context id for the user, the upload worked.

define('AJAX_SCRIPT', true);
define('NO_MOODLE_COOKIES', true);

require_once(dirname(dirname(__FILE__)) . '/config.php');
require_once($CFG->dirroot . '/webservice/lib.php');

echo $OUTPUT->header();

// authenticate the user
$token = required_param('token', PARAM_ALPHANUM);
$webservicelib = new webservice();
$authenticationinfo = $webservicelib->authenticate_user($token);

// check the user can manage his own files (can upload)
$context = context_user::instance($USER->id);
$result = array("contextid"=>$context->id);
echo json_encode($result);

Hope this helps anyone else who faces the same problem.

like image 188
amburnside Avatar answered Feb 17 '23 03:02

amburnside