This commit is contained in:
Xes
2025-08-14 22:37:50 +02:00
parent fb6d5d5926
commit 3641e93527
9156 changed files with 1813532 additions and 0 deletions

View File

@@ -0,0 +1,109 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of addCoursesToSession() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
*
* @throws Exception
*
* @return int
*/
function addCoursesToSession($apiKey)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
'action' => 'add_courses_session',
// data of the user who makes the request
'username' => $webserviceUsername,
'api_key' => $apiKey,
// data of courses and session
'id_session' => 1,
'list_courses' => [
'5',
'6',
'7',
],
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Courses not assigned to session because : '.$jsonResponse->message);
}
return $jsonResponse->data[0];
}
$apiKey = authenticate();
//adding courses with id 5, 6, 7 to session with id 1
if (addCoursesToSession($apiKey)) {
echo 'Courses successfully added';
}

View File

@@ -0,0 +1,110 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
*
* @throws Exception
*
* @return int
*/
function addUsersToSession($apiKey)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'add_users_session',
'username' => $webserviceUsername,
'api_key' => $apiKey,
// data for users and session
'id_session' => 1,
'list_users' => [
'5',
'6',
'7',
],
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('Users not assigned to session because : '.$jsonResponse['message']);
}
return $jsonResponse['data']['status'];
}
$apiKey = authenticate();
//adding users with id 5, 6, 7 to session with id 1
if (addUsersToSession($apiKey)) {
echo 'Users successfully added';
}

View File

@@ -0,0 +1,58 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
$apiKey = authenticate();
echo 'user API Key: '.$apiKey;

View File

@@ -0,0 +1,103 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
* @param $courseId
*
* @throws Exception
*
* @return array
*/
function getCourseAgenda($apiKey, $courseId)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'course_agenda',
'username' => $webserviceUsername,
'api_key' => $apiKey,
'course' => $courseId,
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('cant get course agenda because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//Get the list of calendar events from inside the given course.
$courseAgenda = getCourseAgenda($apiKey, 1);
echo json_encode($courseAgenda);

View File

@@ -0,0 +1,105 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
* @param $courseId
* @param $announcementId
*
* @throws Exception
*
* @return int
*/
function getCourseAnnouncement($apiKey, $courseId, $announcementId)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'course_announcement',
'username' => $webserviceUsername,
'api_key' => $apiKey,
'course' => $courseId,
'announcement ' => $announcementId,
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('cant get announcement because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//Get the announcement published in the given course.
$courseAnnouncement = getCourseAnnouncement($apiKey, 1, 1);
echo json_encode($courseAnnouncement);

View File

@@ -0,0 +1,103 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
* @param $courseId
*
* @throws Exception
*
* @return array
*/
function getCourseAnnouncements($apiKey, $courseId)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'course_announcements',
'username' => $webserviceUsername,
'api_key' => $apiKey,
'course' => $courseId,
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('cant get announcements because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//Get the announcements published in the given course.
$courseAnnouncements = getCourseAnnouncements($apiKey, 1);
echo json_encode($courseAnnouncements);

View File

@@ -0,0 +1,103 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
* @param $courseId
*
* @throws Exception
*
* @return array
*/
function getCourseDescription($apiKey, $courseId)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'course_descriptions',
'username' => $webserviceUsername,
'api_key' => $apiKey,
'course' => $courseId,
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('cant get course description because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//Get the list of documents in the given course.
$courseDescription = getCourseDocuments($apiKey, 1);
echo json_encode($courseDescription);

View File

@@ -0,0 +1,104 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
* @param $courseId
*
* @throws Exception
*
* @return array
*/
function getCourseDocuments($apiKey, $courseId)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'course_documents',
'username' => $webserviceUsername,
'api_key' => $apiKey,
'course' => $courseId,
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('cant get course documents because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//Get the list of documents in the given course.
$courseDescription = getCourseDocuments($apiKey, 1);
echo json_encode($courseDescription);

View File

@@ -0,0 +1,106 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
* @param $courseId
* @param $forumId
*
* @throws Exception
*
* @return array
*/
function getCourseForum($apiKey, $courseId, $forumId)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'course_forum',
'username' => $webserviceUsername,
'api_key' => $apiKey,
'course' => $courseId,
'forum' => $forumId,
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('cant get course documents because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//Get details about a specific forum.
$courseForum = getCourseForum($apiKey, 1, 1);
echo json_encode($courseForum);

View File

@@ -0,0 +1,104 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
* @param $courseId
*
* @throws Exception
*
* @return array
*/
function getCourseForumCategories($apiKey, $courseId)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'course_forumcategories',
'username' => $webserviceUsername,
'api_key' => $apiKey,
'course' => $courseId,
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('cant get course documents because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//A list of forum categories
$courseForumCategories = getCourseForumCategories($apiKey, 1);
echo json_encode($courseForumCategories);

View File

@@ -0,0 +1,107 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
* @param $courseId
* @param $threadId
*
* @throws Exception
*
* @return array
*/
function getCourseForumThread($apiKey, $courseId, $forumId, $threadId)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'course_forumthread',
'username' => $webserviceUsername,
'api_key' => $apiKey,
'course' => $courseId,
'forum' => $forumId,
'thread' => $threadId,
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('cant get course documents because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//Get details about a specific forum thread.
$courseForumThread = getCourseForumThread($apiKey, 1, 1, 1);
echo json_encode($courseForumThread);

View File

@@ -0,0 +1,103 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
*
* @throws Exception
*
* @return int
*/
function getCourseInfo($apiKey, $courseId)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'course_info',
'username' => $webserviceUsername,
'api_key' => $apiKey,
'course' => $courseId,
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('Cant get course info because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//Get information about one course in particular
$userMessages = getCourseInfo($apiKey, 1);
echo json_encode($userMessages);

View File

@@ -0,0 +1,106 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
* @param $courseId
* @param $lpId
*
* @throws Exception
*
* @return array
*/
function getCourseForumThread($apiKey, $courseId, $lpId)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'course_learnpath',
'username' => $webserviceUsername,
'api_key' => $apiKey,
'course' => $courseId,
'lp_id' => $lpId,
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('cant get course documents because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//Get details about a specific forum thread.
$courseForumThread = getCourseForumThread($apiKey, 1, 1, 1);
echo json_encode($courseForumThread);

View File

@@ -0,0 +1,113 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
*
* @throws Exception
*
* @return int
*/
function createSession($apiKey)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'save_session',
'username' => $webserviceUsername,
'api_key' => $apiKey,
// data for new session
'name' => 'Test Session',
'coach_username' => 1, // user_id of CoachUsername that needs to already exist in Chamilo
'access_start_date' => '2020-01-15 15:00:00',
'access_end_date' => '2021-01-15 15:00:00',
'description' => 'My complete text description of the session',
'extra' => [
[
'extra_Price' => '200', // the "Price" session extra field needs to be already created in Chamilo
],
],
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('Cant save session because : '.$jsonResponse['message']);
}
return $jsonResponse['data']['id_session'];
}
$apiKey = authenticate();
//Creating a new session Test Session
$sessionId = createSession($apiKey);
echo 'ID of new session: '.$sessionId;

View File

@@ -0,0 +1,119 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
*
* @throws Exception
*
* @return int
*/
function createUser($apiKey)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'save_user',
'username' => $webserviceUsername,
'api_key' => $apiKey,
// data for new user
'firstname' => 'Test User',
'lastname' => 'Chamilo',
'status' => 5, // student
'email' => 'testuser@example.com',
'loginname' => 'restuser',
'password' => 'restuser',
'original_user_id_name' => 'myplatform_user_id', // field to identify the user in the external system
'original_user_id_value' => '1234', // ID for the user in the external system
'extra' => [
[
'field_name' => 'age',
'field_value' => 29,
],
],
'language' => 'english',
//'phone' => '',
//'expiration_date' => '',
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('User not created because : '.$jsonResponse->message);
}
return $jsonResponse->data[0];
}
$apiKey = authenticate();
//Creating a new user restuser
$userId = createUser($apiKey);
echo 'ID of new user: '.$userId;

View File

@@ -0,0 +1,114 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
*
* @throws Exception
*
* @return int
*/
function updateUserFromUsername($apiKey)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
// data for the user who makes the request
'action' => 'update_user_from_username',
'username' => $webserviceUsername,
'api_key' => $apiKey,
// data for the user to be updated
'loginName' => 'TestUser',
'firstname' => 'Test User',
'lastname' => 'Chamilo',
'status' => 5, // student
'email' => 'testuser@example.com',
'enabled' => 1,
'extra' => [
[
'field_name' => 'age', // The "age" user extra field needs to already be created on Chamilo
'field_value' => 35,
],
],
'language' => 'english',
'expiration_date' => '2025-12-31 23:59:59',
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('User not updated because : '.$jsonResponse->message);
}
return $jsonResponse->data[0];
}
$apiKey = authenticate();
//update user TestUser
if (updateUserFromUsername($apiKey)) {
echo 'User updated successfully';
}

View File

@@ -0,0 +1,101 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
*
* @throws Exception
*
* @return int
*/
function getUserCourses($apiKey)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'user_courses',
'username' => $webserviceUsername,
'api_key' => $apiKey,
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('Cant get user courses because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//Get a list of courses of the user calling this service.
$userMessages = getUserCourses($apiKey);
echo json_encode($userMessages);

View File

@@ -0,0 +1,106 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
*
* @throws Exception
*
* @return int
*/
function getUserMessageRead($apiKey)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'user_message_read',
'username' => $webserviceUsername,
'api_key' => $apiKey,
'messages' => [
1,
2,
3,
],
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('Cant get read messages because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//Mark a specific message (in the social network interface) as read.
$userMessages = getUserMessageRead($apiKey);
echo json_encode($userMessages);

View File

@@ -0,0 +1,107 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
*
* @throws Exception
*
* @return int
*/
function getUserMessageUnread($apiKey)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'user_message_unread',
'username' => $webserviceUsername,
'api_key' => $apiKey,
'messages' => [
1,
2,
3,
],
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('Cant get unread messages because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//Mark a specific message (in the social network interface) as "unread".
$userMessages = getUserMessageUnread($apiKey);
echo json_encode($userMessages);

View File

@@ -0,0 +1,102 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
*
* @throws Exception
*
* @return int
*/
function getUserMessages($apiKey)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'user_messages',
'username' => $webserviceUsername,
'api_key' => $apiKey,
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('Cant get user messages because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//Read user mesages
$userMessages = getUserMessages($apiKey);
echo json_encode($userMessages);

View File

@@ -0,0 +1,102 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
*
* @throws Exception
*
* @return int
*/
function getUserProfile($apiKey)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'user_profile',
'username' => $webserviceUsername,
'api_key' => $apiKey,
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('cant get user profile because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//Get the list of calendar events from inside the given course.
$userProfile = getUserProfile($apiKey);
echo json_encode($userProfile);

View File

@@ -0,0 +1,102 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
*
* @throws Exception
*
* @return int
*/
function getUserSessions($apiKey)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'user_sessions',
'username' => $webserviceUsername,
'api_key' => $apiKey,
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('cant get user profile because : '.$jsonResponse['message']);
}
return $jsonResponse['data'];
}
$apiKey = authenticate();
//Get the list of sessions of the current user
$userSessions = getUserSessions($apiKey);
echo json_encode($userSessions);

View File

@@ -0,0 +1,107 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Test example to user API v2.php.
*
* Using Guzzle' HTTP client to call the API endpoint and make requests.
* Change URL on the first lines of createUser() below to suit your needs.
*/
use GuzzleHttp\Client as Client;
// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
* Make a request to get the API key for admin user.
*
* @throws Exception
*
* @return string
*/
function authenticate()
{
global $webserviceURL;
global $webserviceUsername;
global $webservicePassword;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post('v2.php', [
'form_params' => [
'action' => 'authenticate',
'username' => $webserviceUsername,
'password' => $webservicePassword,
],
]);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$jsonResponse = json_decode($response->getBody()->getContents());
if ($jsonResponse->error) {
throw new Exception('Authentication failed because : '.$jsonResponse->message);
}
return $jsonResponse->data->apiKey;
}
/**
* @param $apiKey
*
* @throws Exception
*
* @return int
*/
function getUserNameExist($apiKey, $loginname)
{
global $webserviceURL;
global $webserviceUsername;
$client = new Client([
'base_uri' => $webserviceURL,
]);
$response = $client->post(
'v2.php',
[
'form_params' => [
// data for the user who makes the request
'action' => 'username_exist',
'username' => $webserviceUsername,
'api_key' => $apiKey,
'loginname' => $loginname,
],
]
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Entry denied with code : '.$response->getStatusCode());
}
$content = $response->getBody()->getContents();
$jsonResponse = json_decode($content, true);
if ($jsonResponse['error']) {
throw new Exception('cant get user profile because : '.$jsonResponse['message']);
}
return $jsonResponse['data'][0];
}
$apiKey = authenticate();
//Return if a username already exist
$userNameExist = getUserNameExist($apiKey, 'admin');
if ($userNameExist == true) {
echo "User name exist";
} else {
echo "User doesnt name exist";
}

View File

@@ -0,0 +1,347 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/V2TestCase.php';
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Class CreateSessionFromModelTest
*
* CREATE_SESSION_FROM_MODEL webservice unit tests
*/
class CreateSessionFromModelTest extends V2TestCase
{
public function action()
{
return 'create_session_from_model';
}
/**
* creates a session from a simple model session
* asserts that it was created with the supplied data
*/
public function testFromASimpleModel()
{
// create a model session
$modelSessionId = SessionManager::create_session(
'Model session'.time(),
'2019-01-01 00:00',
'2019-08-31 00:00',
'2019-01-01 00:00',
'2019-08-31 00:00',
'2019-01-01 00:00',
'2019-08-31 00:00',
null,
null
);
// call the webservice to create the new session from the model session,
// and assert it returns an integer
$name = 'New session'.time();
$startDate = '2019-09-01 00:00:00';
$endDate = '2019-12-31 00:00:00';
$newSessionId = $this->integer(
[
'modelSessionId' => $modelSessionId,
'sessionName' => $name,
'startDate' => $startDate,
'endDate' => $endDate,
]
);
// assert the session was created and given the returned session id
$entityManager = Database::getManager();
$repository = $entityManager->getRepository('ChamiloCoreBundle:Session');
$newSession = $repository->find($newSessionId);
$this->assertIsObject($newSession);
// assert the new session got the right data
$this->assertSame($name, $newSession->getName());
// FIXME account for UTC / local timezone shift
// $this->assertSame($endDate, $newSession->getDisplayEndDate());
// $this->assertSame($startDate, $newSession->getAccessStartDate());
// $this->assertSame($endDate, $newSession->getAccessEndDate());
// $this->assertSame($startDate, $newSession->getCoachAccessStartDate());
// $this->assertSame($endDate, $newSession->getCoachAccessEndDate());
// clean up
SessionManager::delete($modelSessionId);
SessionManager::delete($newSessionId);
}
/**
* creates a session from a model session subscribed to a promotion
* asserts that the promotion is inherited by the new session
*/
public function testFromAModelWithAPromotion()
{
// create a promotion
$career = new Career();
$careerId = $career->save(['name' => 'test career'.time()]);
$promotion = new Promotion();
$promotionId = $promotion->save(['career_id' => $careerId, 'name' => 'test promo'.time()]);
// create a model session
$modelSessionId = SessionManager::create_session(
'Model session'.time(),
'2019-01-01 00:00',
'2019-08-31 00:00',
'2019-01-01 00:00',
'2019-08-31 00:00',
'2019-01-01 00:00',
'2019-08-31 00:00',
null,
null
);
// subscribe the model session to the promotion - the new session will inherit this too
SessionManager::subscribe_sessions_to_promotion($promotionId, [$modelSessionId]);
// call the webservice to create the new session from the model session,
// and assert it returns an integer
$newSessionId = $this->integer(
[
'modelSessionId' => $modelSessionId,
'sessionName' => 'New session'.time(),
'startDate' => '2019-09-01 00:00',
'endDate' => '2019-12-31 00:00',
]
);
// assert both sessions are in the promotion
$promotionSessions = SessionManager::get_all_sessions_by_promotion($promotionId);
$this->assertSame(2, count($promotionSessions));
$this->assertArrayHasKey($newSessionId, $promotionSessions);
$this->assertArrayHasKey($modelSessionId, $promotionSessions);
// clean up
SessionManager::delete($modelSessionId);
SessionManager::delete($newSessionId);
$promotion->delete($promotionId);
$career->delete($careerId);
}
/**
* Creates a session from a model session with a different URL
* asserts that the new session has the called web server URL
*/
public function testFromAModelWithADifferentURL()
{
if (!api_is_multiple_url_enabled()) {
$this->markTestSkipped('needs multiple URL enabled');
}
// create a model session
$modelSessionId = SessionManager::create_session(
'Model session'.time(),
'2019-01-01 00:00',
'2019-08-31 00:00',
'2019-01-01 00:00',
'2019-08-31 00:00',
'2019-01-01 00:00',
'2019-08-31 00:00',
null,
null
);
// move the session to a non-standard URL
$urlId = UrlManager::add('https://www.url.org/chamilo-lms/'.time(), 'Non-default URL', 1);
UrlManager::update_urls_rel_session([$modelSessionId], $urlId);
// call the webservice to create the new session from the model session,
// and assert it returns an integer
$newSessionId = $this->integer(
[
'modelSessionId' => $modelSessionId,
'sessionName' => 'Name of the new session'.time(),
'startDate' => '2019-09-01 00:00',
'endDate' => '2019-12-31 00:00',
]
);
// assert the current url was set on the new session
$urls = UrlManager::get_access_url_from_session($newSessionId);
$this->assertSame(1, count($urls));
$this->assertSame(api_get_current_access_url_id(), intval($urls[0]['access_url_id']));
// clean up
SessionManager::delete($modelSessionId);
SessionManager::delete($newSessionId);
UrlManager::delete($urlId);
}
/**
* creates a session from a model session with courses
* asserts that the new session inherits the same courses
* @throws Exception
*/
public function testFromAModelWithCourses()
{
// create a model session
$modelSessionId = SessionManager::create_session(
'Model session'.time(),
'2019-01-01 00:00',
'2019-08-31 00:00',
'2019-01-01 00:00',
'2019-08-31 00:00',
'2019-01-01 00:00',
'2019-08-31 00:00',
null,
null
);
// create courses and add them the the model session
$courseCodes = ['course A'.time(), 'course B'.time(), 'course C'.time()];
$courseList = [];
$authorId = UserManager::get_user_id_from_username(self::WEBSERVICE_USERNAME);
foreach ($courseCodes as $code) {
$course = CourseManager::create_course(['code' => $code, 'title' => $code], $authorId);
$courseList[] = $course['real_id'];
}
SessionManager::add_courses_to_session($modelSessionId, $courseList);
// call the webservice to create the new session from the model session,
// and assert it returns an integer
$newSessionId = $this->integer(
[
'modelSessionId' => $modelSessionId,
'sessionName' => 'Name of the new session'.time(),
'startDate' => '2019-09-01 00:00',
'endDate' => '2019-12-31 00:00',
]
);
// assert the new session inherited the model session courses
$modelCourseList = array_keys(SessionManager::get_course_list_by_session_id($modelSessionId));
$newCourseList = array_keys(SessionManager::get_course_list_by_session_id($newSessionId));
$this->assertSame($modelCourseList, $newCourseList);
// clean up
foreach ($courseCodes as $code) {
CourseManager::delete_course($code);
}
SessionManager::delete($modelSessionId);
SessionManager::delete($newSessionId);
}
/**
* creates a session from a model session with extra fields
* asserts that the new session inherits the extra fields
* and that specifying other extra field values works
*/
public function testFromAModelWithExtraFields()
{
// create a model session
$modelSessionId = SessionManager::create_session(
'Model session'.time(),
'2019-01-01 00:00',
'2019-08-31 00:00',
'2019-01-01 00:00',
'2019-08-31 00:00',
'2019-01-01 00:00',
'2019-08-31 00:00',
null,
null
);
// create an extra field and set its value in the model session
// the new session will be given a different value in this field
$extraFieldModel = new ExtraField('session');
$firstExtraFieldName = 'extraField'.time();
$firstExtraFieldNameForModelSession = 'extra field value for model';
$firstExtraFieldNameForNewSession = 'extra field value for new session';
$firstExtraFieldId = $extraFieldModel->save(
[
'field_type' => ExtraField::FIELD_TYPE_TEXT,
'variable' => $firstExtraFieldName,
'display_text' => $firstExtraFieldName,
'visible_to_self' => 1,
'visible_to_others' => 1,
'changeable' => 1,
'filter' => 1,
]
);
SessionManager::update_session_extra_field_value(
$modelSessionId,
$firstExtraFieldName,
$firstExtraFieldNameForModelSession
);
// create a second extra field and set its value in the model session
// the new session will inherit the same value in this field
$secondExtraFieldName = 'secondExtraField'.time();
$secondExtraFieldValue = 'second extra field value';
$secondExtraFieldId = $extraFieldModel->save(
[
'field_type' => ExtraField::FIELD_TYPE_TEXT,
'variable' => $secondExtraFieldName,
'display_text' => $secondExtraFieldName,
'visible_to_self' => 1,
'visible_to_others' => 1,
'changeable' => 1,
'filter' => 1,
]
);
SessionManager::update_session_extra_field_value(
$modelSessionId,
$secondExtraFieldName,
$secondExtraFieldValue
);
// call the webservice to create the new session from the model session,
// specifying a different value in the first extra field
// and assert it returns an integer
$newSessionId = $this->integer(
[
'modelSessionId' => $modelSessionId,
'sessionName' => 'Name of the new session'.time(),
'startDate' => '2019-09-01 00:00',
'endDate' => '2019-12-31 00:00',
'extraFields' => [
$firstExtraFieldName => $firstExtraFieldNameForNewSession,
],
]
);
// assert the new session has its own new value in the first extra field
$extraFieldValueModel = new ExtraFieldValue('session');
$extraFieldValue = $extraFieldValueModel->get_values_by_handler_and_field_variable(
$newSessionId,
$firstExtraFieldName
);
$this->assertNotFalse($extraFieldValue);
$this->assertSame($firstExtraFieldNameForNewSession, $extraFieldValue['value']);
// assert the model session still has its own original value in the first extra field
$extraFieldValue = $extraFieldValueModel->get_values_by_handler_and_field_variable(
$modelSessionId,
$firstExtraFieldName
);
$this->assertNotFalse($extraFieldValue);
$this->assertSame($firstExtraFieldNameForModelSession, $extraFieldValue['value']);
// assert the new session has inherited the model session value in the second extra field
$extraFieldValue = $extraFieldValueModel->get_values_by_handler_and_field_variable(
$newSessionId,
$secondExtraFieldName
);
$this->assertNotFalse($extraFieldValue);
$this->assertSame($secondExtraFieldValue, $extraFieldValue['value']);
// assert the model session still has the same value in the second extra field
$extraFieldValue = $extraFieldValueModel->get_values_by_handler_and_field_variable(
$modelSessionId,
$secondExtraFieldName
);
$this->assertNotFalse($extraFieldValue);
$this->assertSame($secondExtraFieldValue, $extraFieldValue['value']);
// clean up
SessionManager::delete($modelSessionId);
SessionManager::delete($newSessionId);
$extraFieldModel->delete($firstExtraFieldId);
$extraFieldModel->delete($secondExtraFieldId);
}
}

View File

@@ -0,0 +1,30 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/V2TestCase.php';
require_once __DIR__.'/../../../../vendor/autoload.php';
class GetCourseLpProgressTest extends V2TestCase
{
public function action()
{
return 'course_lp_progress';
}
public function testCourseList()
{
$result = $this->dataArray();
$this->assertIsArray($result);
//$result = $this->dataArray();
//$this->assertIsObject($result);
//$this->assertObjectHasAttribute('courses', $result);
//$this->assertSame(1, count($urls));
// expect the web service to return false
//$this->assertFalse($this->boolean(['loginname' => $loginName]));
}
}

View File

@@ -0,0 +1,135 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/V2TestCase.php';
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Class GetSessionFromExtraFieldTest
*
* GET_SESSION_FROM_EXTRA_FIELD webservice unit tests
*/
class GetSessionFromExtraFieldTest extends V2TestCase
{
public function action()
{
return 'get_session_from_extra_field';
}
/**
* creates two extra fields and 2 sessions
* asserts that the sessions can be found one by one but not together
*
*/
public function test()
{
// create 2 extra fields
$extraFieldModel = new ExtraField('session');
$firstExtraFieldName = 'firstExtraField'.time();
$firstExtraFieldId = $extraFieldModel->save(
[
'field_type' => ExtraField::FIELD_TYPE_TEXT,
'variable' => $firstExtraFieldName,
'display_text' => $firstExtraFieldName,
'visible_to_self' => 1,
'visible_to_others' => 1,
'changeable' => 1,
'filter' => 1,
]
);
$secondExtraFieldName = 'secondExtraField'.time();
$secondExtraFieldId = $extraFieldModel->save(
[
'field_type' => ExtraField::FIELD_TYPE_TEXT,
'variable' => $secondExtraFieldName,
'display_text' => $secondExtraFieldName,
'visible_to_self' => 1,
'visible_to_others' => 1,
'changeable' => 1,
'filter' => 1,
]
);
// create 2 sessions
$firstSessionId = SessionManager::create_session(
'First session'.time(),
'2019-01-01 00:00',
'2019-08-31 00:00',
'2019-01-01 00:00',
'2019-08-31 00:00',
'2019-01-01 00:00',
'2019-08-31 00:00',
null,
null
);
$secondSessionId = SessionManager::create_session(
'Second session'.time(),
'2019-09-01 00:00',
'2019-12-31 00:00',
'2019-09-01 00:00',
'2019-12-31 00:00',
'2019-09-01 00:00',
'2019-12-31 00:00',
null,
null
);
// assign unique distinct value in first field to each session
SessionManager::update_session_extra_field_value($firstSessionId, $firstExtraFieldName, $firstSessionId);
SessionManager::update_session_extra_field_value($secondSessionId, $firstExtraFieldName, $secondSessionId);
// assign the same value in second field to all sessions
$commonValue = 'common value';
SessionManager::update_session_extra_field_value($firstSessionId, $secondExtraFieldName, $commonValue);
SessionManager::update_session_extra_field_value($secondSessionId, $secondExtraFieldName, $commonValue);
// assert that the correct session id is returned using each unique value
$this->assertSame(
$firstSessionId,
$this->integer(
[
'field_name' => $firstExtraFieldName,
'field_value' => $firstSessionId,
]
)
);
$this->assertSame(
$secondSessionId,
$this->integer(
[
'field_name' => $firstExtraFieldName,
'field_value' => $secondSessionId,
]
)
);
// assert search for common value in second field generates the right error message
$this->assertSame(
get_lang('MoreThanOneSessionMatched'),
$this->errorMessageString(
[
'field_name' => $secondExtraFieldName,
'field_value' => $commonValue,
]
)
);
// assert search for unknown value generates the right error message
$this->assertSame(
get_lang('NoSessionMatched'),
$this->errorMessageString(
[
'field_name' => $secondExtraFieldName,
'field_value' => 'non-existent value',
]
)
);
// clean up
SessionManager::delete($firstSessionId);
SessionManager::delete($secondSessionId);
$extraFieldModel->delete($firstExtraFieldId);
$extraFieldModel->delete($secondExtraFieldId);
}
}

View File

@@ -0,0 +1,2 @@
Command to run the tests :
vendor/phpunit/phpunit/phpunit main/webservices/api/tests

View File

@@ -0,0 +1,94 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/V2TestCase.php';
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Class SaveUserJsonTest
*
* SAVE_USER_JSON webservice unit tests
*/
class SaveUserJsonTest extends V2TestCase
{
public function action()
{
return 'save_user_json';
}
/**
* creates a minimal test user
* asserts that it was created with the supplied data
*
* @throws Exception if it cannot delete the created test user
*/
public function testCreateAMinimalUser()
{
// call the web service with minimal information
$loginName = 'testUser'.time();
$email = 'testUser@local';
$status = 5;
$json = json_encode(
[
'loginname' => $loginName,
'firstname' => 'Małgorzata',
'lastname' => 'Summer',
'original_user_id_name' => 'external_user_id',
'original_user_id_value' => $loginName,
'email' => $email,
'status' => $status,
'password' => 'test',
]
);
$userId = $this->integer([ 'json' => $json ]);
// assert the user was saved and given the returned user id
$user = UserManager::getManager()->find($userId);
$this->assertNotNull($user, 'the returned userId does not point to an user');
// assert each field was filled with provided information
$this->assertSame($loginName, $user->getUserName());
$this->assertSame($email, $user->getEmail());
$this->assertSame($status, $user->getStatus());
// clean up
UserManager::delete_user($userId);
}
/**
* Creates a test user with an extra field asserts that the extra field values were saved.
*
* @throws Exception if it cannot delete the created test user
*/
public function testCreateAUserWithExtraFields()
{
// call the web service
$extraFieldName = 'age';
$extraFieldOriginalValue = '29';
$loginName = 'testUser'.time();
$json = json_encode(
[
'loginname' => $loginName,
'email' => 'testUser@local',
'original_user_id_name' => 'external_user_id',
'original_user_id_value' => $loginName,
'status' => 5,
'password' => 'test',
'firstname' => 'Małgorzata',
'lastname' => 'Summer',
'extra' => [
['field_name' => $extraFieldName, 'field_value' => $extraFieldOriginalValue],
],
]
);
$userId = $this->integer(['json' => $json]);
// assert user extra field value was saved
$savedValue = (new ExtraFieldValue('user'))->get_values_by_handler_and_field_variable($userId, $extraFieldName);
$this->assertNotFalse($savedValue);
$this->assertSame($extraFieldOriginalValue, $savedValue['value']);
// clean up
UserManager::delete_user($userId);
}
}

View File

@@ -0,0 +1,92 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/V2TestCase.php';
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Class SaveUserTest
*
* SAVE_USER webservice unit tests
*/
class SaveUserTest extends V2TestCase
{
public function action()
{
return 'save_user';
}
/**
* creates a minimal test user
* asserts that it was created with the supplied data
*
* @throws Exception if it cannot delete the created test user
*/
public function testCreateAMinimalUser()
{
// call the web service with minimal information
$loginName = 'testUser'.time();
$email = 'testUser@local';
$status = 5;
$userId = $this->integer(
[
'loginname' => $loginName,
'firstname' => 'Małgorzata',
'lastname' => 'Summer',
'original_user_id_name' => 'external_user_id',
'original_user_id_value' => $loginName,
'email' => $email,
'status' => $status,
'password' => 'test',
]
);
// assert the user was saved and given the returned user id
$user = UserManager::getManager()->find($userId);
$this->assertNotNull($user, 'the returned userId does not point to an user');
// assert each field was filled with provided information
$this->assertSame($loginName, $user->getUserName());
$this->assertSame($email, $user->getEmail());
$this->assertSame($status, $user->getStatus());
// clean up
UserManager::delete_user($userId);
}
/**
* Creates a test user with an extra field asserts that the extra field values were saved.
*
* @throws Exception if it cannot delete the created test user
*/
public function testCreateAUserWithExtraFields()
{
// call the web service
$extraFieldName = 'age';
$extraFieldOriginalValue = '29';
$loginName = 'testUser'.time();
$userId = $this->integer(
[
'loginname' => $loginName,
'email' => 'testUser@local',
'original_user_id_name' => 'external_user_id',
'original_user_id_value' => $loginName,
'status' => 5,
'password' => 'test',
'firstname' => 'Małgorzata',
'lastname' => 'Summer',
'extra' => [
['field_name' => $extraFieldName, 'field_value' => $extraFieldOriginalValue],
],
]
);
// assert user extra field value was saved
$savedValue = (new ExtraFieldValue('user'))->get_values_by_handler_and_field_variable($userId, $extraFieldName);
$this->assertNotFalse($savedValue);
$this->assertSame($extraFieldOriginalValue, $savedValue['value']);
// clean up
UserManager::delete_user($userId);
}
}

View File

@@ -0,0 +1,63 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/V2TestCase.php';
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Class SubscribeUserToSessionFromUsernameTest
*
* SUBSCRIBE_USER_TO_SESSION_FROM_USERNAME webservice unit tests
*/
class SubscribeUserToSessionFromUsernameTest extends V2TestCase
{
public function action()
{
return 'subscribe_user_to_session_from_username';
}
/**
* subscribes a test user to a test session that already has another user subscribed
* asserts that the user was subscribed to the session
* asserts that the other user was not unsubscribed from the session
*/
public function testSubscribeWithoutUnsubscribe()
{
// create a test session
$sessionId = SessionManager::create_session(
'Session to subscribe'.time(),
'2019-01-01 00:00',
'2019-08-31 00:00',
'2019-01-01 00:00',
'2019-08-31 00:00',
'2019-01-01 00:00',
'2019-08-31 00:00',
null,
null
);
// create a test user
$loginName = 'tester'.time();
$userId = UserManager::create_user('Tester', 'Tester', 5, 'tester@local', $loginName, 'xXxxXxxXX');
// create another user and subscribe it to the session
$anotherUserId = UserManager::create_user('Tester 2', 'Tester 2', 5, 'tester2@local', $loginName.'t2', 'xXxxX');
SessionManager::subscribeUsersToSession($sessionId, [$anotherUserId]);
// call the webservice to subscribe the first user to the session
$subscribed = $this->boolean(['sessionId' => $sessionId, 'loginname' => $loginName]);
$this->assertTrue($subscribed);
// assert we now have two users subscribed to the session
$sessionRelUsers = Database::getManager()
->getRepository('ChamiloCoreBundle:SessionRelUser')
->findBy(['session' => $sessionId]);
$this->assertSame(2, count($sessionRelUsers));
// clean up
UserManager::delete_users([$userId, $anotherUserId]);
SessionManager::delete($sessionId);
}
}

View File

@@ -0,0 +1,98 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/V2TestCase.php';
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Class UpdateUserFromUsernameTest
*
* UPDATE_USER_FROM_USERNAME webservice unit tests
*/
class UpdateUserFromUsernameTest extends V2TestCase
{
public function action()
{
return 'update_user_from_username';
}
/**
* updates a user
* asserts that its data was updated, including extra fields
*
* @throws Exception if it cannot delete the created test user
*/
public function test()
{
// create a user with initial data and extra field values
$loginName = 'testUser'.time();
$userId = UserManager::create_user(
'Initial first name',
'Initial last name',
5,
'initial.email@local',
$loginName,
'xXxxXxxXX'
);
// create an extra field and initialise its value for the user
$extraFieldModel = new ExtraField('user');
$extraFieldName = 'extraUserField'.time();
$extraFieldId = $extraFieldModel->save(
[
'field_type' => ExtraField::FIELD_TYPE_TEXT,
'variable' => $extraFieldName,
'display_text' => $extraFieldName,
'visible_to_self' => 1,
'visible_to_others' => 1,
'changeable' => 1,
'filter' => 1,
]
);
SessionManager::update_session_extra_field_value($userId, $extraFieldName, 'extra field initial value');
// update user with new data and extra field data
$newFirstName = 'New first name';
$newLastName = 'New last name';
$newStatus = 1;
$newEmail = 'new.address@local';
$parameters = [
'firstname' => $newFirstName,
'lastname' => $newLastName,
'status' => $newStatus,
'email' => $newEmail,
];
$extraFieldNewValue = 'extra field new value';
$parameters['extra'] = [
['field_name' => $extraFieldName, 'field_value' => $extraFieldNewValue],
];
$parameters['loginname'] = $loginName;
$updated = $this->boolean($parameters);
$this->assertTrue($updated);
// assert the webservice reports an error with a non-existent login name
$parameters['loginname'] = 'santaClaus';
$this->assertSame(get_lang('UserNotFound'), $this->errorMessageString($parameters));
// compare each saved value to the original
/** @var User $user */
$userManager = UserManager::getManager();
$user = $userManager->find($userId);
$userManager->reloadUser($user);
$this->assertSame($newFirstName, $user->getFirstname());
$this->assertSame($newLastName, $user->getLastname());
$this->assertSame($newStatus, $user->getStatus());
$this->assertSame($newEmail, $user->getEmail());
// assert extra field values have been updated
$extraFieldValueModel = new ExtraFieldValue('user');
$extraFieldValue = $extraFieldValueModel->get_values_by_handler_and_field_variable($userId, $extraFieldName);
$this->assertNotFalse($extraFieldValue);
$this->assertSame($extraFieldNewValue, $extraFieldValue['value']);
// clean up
UserManager::delete_user($userId);
$extraFieldModel->delete($extraFieldId);
}
}

View File

@@ -0,0 +1,37 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/V2TestCase.php';
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* UPDATE_USER_PAUSE_TRAINING webservice unit tests
*/
class UpdateUserPauseTrainingTest extends V2TestCase
{
public function action()
{
return Rest::UPDATE_USER_PAUSE_TRAINING;
}
/**
* creates a minimal test user
* asserts that it was created with the supplied data
*
* @throws Exception if it cannot delete the created test user
*/
public function testUpdate()
{
$params = [
'user_id' => 1,
'pause_formation' => 0,
'start_pause_date' => '2020-06-30 10:00',
'end_pause_date' => '2020-06-30 11:00',
'disable_emails' => 1,
];
$userId = $this->integer($params);
// assert each field was filled with provided information
$this->assertSame($userId, 1);
}
}

View File

@@ -0,0 +1,62 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/V2TestCase.php';
require_once __DIR__.'/../../../../vendor/autoload.php';
/**
* Class UsernameExistTest
*
* USERNAME_EXIST webservice unit tests
*/
class UsernameExistTest extends V2TestCase
{
public function action()
{
return 'username_exist';
}
/**
* test nonexistence of a username which does not exist
* assert that the webservice returns false
*/
public function testUsernameWhichDoesNotExist()
{
// generate a random name which does not exist in the database
do {
$loginName = rand();
} while (UserManager::get_user_id_from_username($loginName));
// expect the web service to return false
$this->assertFalse($this->boolean(['loginname' => $loginName]));
}
/**
* test existence of a username which does exist
* assert that the webservice returns true
*/
public function testUsernameWhichDoesExist()
{
// generate a random name which does not exist in the database
do {
$loginName = rand();
} while (UserManager::get_user_id_from_username($loginName));
// create a test user with this login name
$userId = UserManager::create_user(
$loginName,
$loginName,
STUDENT,
$loginName.'@local',
$loginName,
$loginName
);
// expect the web service to return true
$this->assertTrue($this->boolean(['loginname' => $loginName]));
// clean up
UserManager::delete_users([$userId]);
}
}

View File

@@ -0,0 +1,194 @@
<?php
/* For licensing terms, see /license.txt */
use GuzzleHttp\Client;
use PHPUnit\Framework\TestCase;
require_once __DIR__.'/../../../../vendor/autoload.php';
require_once __DIR__.'/../../../inc/global.inc.php';
/**
* Class V2Test
*
* Base class for all WebService API v2 tests
*/
abstract class V2TestCase extends TestCase
{
const WEBSERVICE_USERNAME = 'admin';
const WEBSERVICE_PASSWORD = 'admin';
const RELATIVE_URI = 'webservices/api/v2.php';
/**
* @var Client $client
*/
private $client;
private $apiKey;
/**
* Initialises the HTTP client and retrieves the API key from the server
*
* @throws Exception when it cannot get the API key
*/
protected function setUp(): void
{
parent::setUp();
$this->client = new Client(
[
'base_uri' => api_get_path(WEB_CODE_PATH),
]
);
$response = $this->client->post(
self::RELATIVE_URI,
[
'form_params' => [
'action' => 'authenticate',
'username' => self::WEBSERVICE_USERNAME,
'password' => self::WEBSERVICE_PASSWORD,
],
]
);
if (200 === $response->getStatusCode()) {
$decodedResponse = json_decode($response->getBody()->getContents(), false, 3, JSON_THROW_ON_ERROR);
if (is_object($decodedResponse)) {
$this->apiKey = $decodedResponse->data->apiKey;
} else {
throw new Exception('The returned JSON document is not an object');
}
} else {
throw new Exception($response->getReasonPhrase());
}
}
/**
* Posts an action request and assert the server returns an error message
*
* @param array $parameters parameters to send with the request
*
* @return string the "message" error string returned by the webservice
*/
protected function errorMessageString($parameters = [])
{
$decodedResponse = $this->decodedResponse($parameters);
$this->assertIsObject($decodedResponse);
$this->assertTrue(property_exists($decodedResponse, 'error'));
$error = $decodedResponse->error;
$this->assertIsBool(true, $error);
$this->assertTrue($error, 'error is not true: '.print_r($decodedResponse, true));
$this->assertTrue(property_exists($decodedResponse, 'message'));
$message = $decodedResponse->message;
$this->assertIsString($message);
return $message;
}
/**
* Posts an action request to the web server, asserts it returns a valid JSON-encoded response and decodes it
* supplied parameters complete or override the generated base parameters username, api_key and action
*
* @param array $parameters parameters to send with the request as an associative array
*
* @return mixed the decoded response (usually an object with properties data, error, message)
*/
protected function decodedResponse($parameters = [])
{
$baseParams = [
'username' => self::WEBSERVICE_USERNAME,
'api_key' => $this->apiKey,
'action' => $this->action(),
];
$response = $this->client->post(self::RELATIVE_URI, ['form_params' => array_merge($baseParams, $parameters)]);
$this->assertNotNull($response);
$this->assertSame(200, $response->getStatusCode());
$decodedResponse = json_decode($response->getBody()->getContents());
// Help debug
if (null === $decodedResponse) {
var_dump($this->action(), $response->getBody()->getContents());
}
$this->assertNotNull($decodedResponse);
return $decodedResponse;
}
/**
* returns the name of the webservice, to be passed as the "action" with the HTTP request
*
* @return string name of the webservice action to call
*/
abstract protected function action();
/**
* Posts an action request and assert it returns an integer value in the "data" property
*
* @param array $parameters parameters to send with the request
*
* @return integer the integer value
*/
protected function integer($parameters = [])
{
$value = $this->singleElementValue($parameters);
$this->assertIsInt($value);
return $value;
}
/**
* Posts an action request and assert the server returns a single value in the "data" array of the returned object
*
* @param array $parameters parameters to send with the request
*
* @return mixed the unique element of the "data" array
*/
protected function singleElementValue($parameters = [])
{
$data = $this->dataArray($parameters);
$this->assertSame(1, count($data));
return $data[0];
}
/**
* Posts an action request and assert the server returns a "data" array
*
* @param array $parameters parameters to send with the request
*
* @return array the "data" array returned by the webservice
*/
protected function dataArray($parameters = [])
{
$decodedResponse = $this->decodedResponse($parameters);
$this->assertIsObject($decodedResponse);
$this->assertTrue(
property_exists($decodedResponse, 'data'),
'response data property is missing: '.print_r($decodedResponse, true)
);
$data = $decodedResponse->data;
$this->assertIsArray($data);
return $data;
}
/**
* Posts an action request and assert it returns an array with a single boolean value
*
* @param array $parameters parameters to send with the request
*
* @return boolean the boolean value
*/
protected function boolean($parameters = [])
{
$value = $this->singleElementValue($parameters);
$this->assertIsBool($value);
return $value;
}
}

1100
main/webservices/api/v2.php Normal file

File diff suppressed because it is too large Load Diff