I am developing an android app to upload / download course content from my Moodle install. However, I am struggling to understand the API documentation. In the function core_files_upload the first required parameter is "contextid". How do you get the contextid?
How do you retrieve a contextid for a webservice
Number of replies: 4Re: How do you retrieve a contextid for a webservice
I'm assuming the context id is the id of the user if uploading to private files, so parameters would be:
contextid: 2 (my user id)
component: user
filearea: private
itemid: 0
filepath: /path/to/image.jpg
filename: image.jpg
filecontent: base64_encode(/path/to/image.jpg);
This appears to get me further than before. Now it returns an exception:
{"exception":"moodle_exception","errorcode":"nofile","message":"File not specified"}
Re: How do you retrieve a contextid for a webservice
Update.
I have created a small upload script in PHP, running locally on my desktop on WAMP. It posts to my remote Moodle installation. I have kept the parameters the same, but I get the same JSON response back. Can someone confirm I am doing this correctly:
a) contextid is the userid when uploading to a user's private storage
b) filepath is the path in Moodle
c) I have seen examples where itemid is set to 0 (zero) so I am using this. Is this correct?
Re: How do you retrieve a contextid for a webservice
Update 2
Remove point c) found this in file/externallib.php:
// TODO MDL-31116 in user private area, itemid is always 0.
Re: How do you retrieve a contextid for a webservice
Answer
The context id IS NOT the user id. I don't know how the heck you are supposed to get the contextid for the user, but I have had to create a script to get it, in order to get my app working.
If this is of any help to anyone, I created the file webservice/usercontext.php in my Moodle installation. The script returns a JSON string of the user's context id:
<?php
define('AJAX_SCRIPT', true);
/**
* NO_MOODLE_COOKIES - we don't want any cookie
*/
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);
If anyone has a better solution please let me know.