How do you retrieve a contextid for a webservice

Re: How do you retrieve a contextid for a webservice

by Andrew Maughan -
Number of replies: 0

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.