// For lstat
#include "soap/soapH.h" // gSOAP header
#include "soap/swad.nsmap" // Namespaces map used
#include "swad_account.h"
#include "swad_API.h"
#include "swad_API_database.h"
#include "swad_attendance_database.h"
#include "swad_autolink.h"
#include "swad_browser.h"
#include "swad_browser_database.h"
#include "swad_course_database.h"
#include "swad_database.h"
#include "swad_enrolment_database.h"
#include "swad_error.h"
#include "swad_forum.h"
#include "swad_game_database.h"
#include "swad_global.h"
#include "swad_group_database.h"
#include "swad_hierarchy.h"
#include "swad_hierarchy_level.h"
#include "swad_ID.h"
#include "swad_mail_database.h"
#include "swad_match.h"
#include "swad_match_database.h"
#include "swad_message_database.h"
#include "swad_nickname_database.h"
#include "swad_notice.h"
#include "swad_notice_database.h"
#include "swad_notification.h"
#include "swad_notification_database.h"
#include "swad_password.h"
#include "swad_plugin_database.h"
#include "swad_question_database.h"
#include "swad_role.h"
#include "swad_role_database.h"
#include "swad_room_database.h"
#include "swad_search.h"
#include "swad_session_database.h"
#include "swad_setting_database.h"
#include "swad_tag_database.h"
#include "swad_test_config.h"
#include "swad_test_visibility.h"
#include "swad_user.h"
#include "swad_user_database.h"
#include "swad_xml.h"
/*****************************************************************************/
/************** External global variables from others modules ****************/
/*****************************************************************************/
extern struct Globals Gbl;
extern const char Str_BIN_TO_BASE64URL[64 + 1];
/*****************************************************************************/
/***************************** Private constants *****************************/
/*****************************************************************************/
// Add new functions at the end
static const char *API_Functions[1 + API_NUM_FUNCTIONS] =
{
[API_unknown ] = "?", // 0 ==> unknown function
[API_loginBySessionKey ] = "loginBySession", // 1
[API_loginByUserPassword ] = "loginByUserPassword", // 2 (deprecated)
[API_loginByUserPasswordKey ] = "loginByUserPasswordKey", // 3
[API_getCourses ] = "getCourses", // 4
[API_getUsers ] = "getUsers", // 5
[API_getNotifications ] = "getNotifications", // 6
[API_getTestConfig ] = "getTestConfig", // 7
[API_getTests ] = "getTests", // 8
[API_sendMessage ] = "sendMessage", // 9
[API_sendNotice ] = "sendNotice", // 10
[API_getDirectoryTree ] = "getDirectoryTree", // 11
[API_getGroups ] = "getGroups", // 12
[API_getGroupTypes ] = "getGroupTypes", // 13
[API_sendMyGroups ] = "sendMyGroups", // 14
[API_getFile ] = "getFile", // 15
[API_markNotificationsAsRead ] = "markNotificationsAsRead", // 16
[API_getNewPassword ] = "getNewPassword", // 17
[API_getCourseInfo ] = "getCourseInfo", // 18
[API_getAttendanceEvents ] = "getAttendanceEvents", // 19
[API_sendAttendanceEvent ] = "sendAttendanceEvent", // 20
[API_getAttendanceUsers ] = "getAttendanceUsers", // 21
[API_sendAttendanceUsers ] = "sendAttendanceUsers", // 22
[API_createAccount ] = "createAccount", // 23
[API_getMarks ] = "getMarks", // 24
[API_getTrivialQuestion ] = "getTrivialQuestion", // 25
[API_findUsers ] = "findUsers", // 26
[API_removeAttendanceEvent ] = "removeAttendanceEvent", // 27
[API_getGames ] = "getGames", // 28
[API_getMatches ] = "getMatches", // 29
[API_getMatchStatus ] = "getMatchStatus", // 30
[API_answerMatchQuestion ] = "answerMatchQuestion", // 31
[API_getLocation ] = "getLocation", // 32
[API_sendMyLocation ] = "sendMyLocation", // 33
[API_getLastLocation ] = "getLastLocation", // 34
[API_getAvailableRoles ] = "getAvailableRoles", // 35
};
/* Web service roles (they do not match internal swad-core roles) */
#define API_NUM_ROLES 4
typedef enum
{
API_ROLE_UNKNOWN = 0, // User not logged in (do not change this constant to any value other than 0)
API_ROLE__GUEST_ = 1, // User not belonging to any course
API_ROLE_STUDENT = 2, // Student in current course
API_ROLE_TEACHER = 3, // Teacher in current course
} API_Role_t;
/* Translation from service-web-role to swad-core-role */
static const Rol_Role_t API_SvcRole_to_RolRole[API_NUM_ROLES] =
{
[API_ROLE_UNKNOWN] = Rol_UNK,
[API_ROLE__GUEST_] = Rol_GST,
[API_ROLE_STUDENT] = Rol_STD,
[API_ROLE_TEACHER] = Rol_TCH, // TODO: Create new web service role for non-editing teachers
};
/* Translation from swad-core-role to service-web-role */
static const API_Role_t API_RolRole_to_SvcRole[Rol_NUM_ROLES] =
{
[Rol_GST] = API_ROLE__GUEST_,
[Rol_STD] = API_ROLE_STUDENT,
[Rol_NET] = API_ROLE_TEACHER, // TODO: Create new web service role for non-editing teachers
[Rol_TCH] = API_ROLE_TEACHER,
};
/*****************************************************************************/
/***************************** Private prototypes ****************************/
/*****************************************************************************/
static void API_Set_gSOAP_RuntimeEnv (struct soap *soap);
static void API_FreeSoapContext (struct soap *soap);
static int API_GetPlgCodFromAppKey (struct soap *soap,
const char *appKey);
static int API_CheckIdSession (struct soap *soap,
const char *IdSes);
static int API_CheckAPIKey (char APIKey[API_BYTES_KEY + 1]);
static int API_CheckCourseAndGroupCodes (struct soap *soap,
long CrsCod,long GrpCod);
static int API_GenerateNewAPIKey (struct soap *soap,
long UsrCod,
char APIKey[API_BYTES_KEY + 1]);
static bool API_GetSomeUsrDataFromUsrCod (struct UsrData *UsrDat,long CrsCod);
static int API_CheckParamsNewAccount (char *NewNickWithArr, // Input
char NewNickWithoutArr[Nck_MAX_BYTES_NICK_WITHOUT_ARROBA + 1], // Output
char *NewEmail, // Input-output
char *NewPlainPassword, // Input
char NewEncryptedPassword[Pwd_BYTES_ENCRYPTED_PASSWORD + 1]); // Output
static int API_WriteSyllabusIntoHTMLBuffer (struct soap *soap,
struct Syl_Syllabus *Syllabus,
char **HTMLBuffer);
static int API_WritePlainTextIntoHTMLBuffer (struct soap *soap,
char **HTMLBuffer);
static int API_WritePageIntoHTMLBuffer (struct soap *soap,
char **HTMLBuffer);
static void API_CopyListUsers (struct soap *soap,
Rol_Role_t Role,
struct swad__getUsersOutput *getUsersOut);
static void API_CopyUsrData (struct soap *soap,
struct swad__user *Usr,struct UsrData *UsrDat,
bool UsrIDIsVisible);
static void API_GetListGrpsInAttendanceEventFromDB (struct soap *soap,
long AttCod,char **ListGroups);
static void API_GetLstGrpsSel (const char *Groups);
static int API_GetMyLanguage (struct soap *soap);
static int API_SendMessageToUsr (long OriginalMsgCod,
long ReplyUsrCod,long RecipientUsrCod,
bool NotifyByEmail,
const char *Subject,const char *Content);
static int API_GetTstTags (struct soap *soap,
long CrsCod,struct swad__getTestsOutput *getTestsOut);
static int API_GetTstQuestions (struct soap *soap,
long CrsCod,time_t BeginTime,
struct swad__getTestsOutput *getTestsOut);
static int API_GetTstAnswers (struct soap *soap,
long CrsCod,time_t BeginTime,
struct swad__getTestsOutput *getTestsOut);
static int API_GetTstQuestionTags (struct soap *soap,
long CrsCod,time_t BeginTime,
struct swad__getTestsOutput *getTestsOut);
static void API_GetListGrpsInMatchFromDB (struct soap *soap,
long MchCod,char **ListGroups);
static void API_ListDir (unsigned Level,const char *Path,const char *PathInTree);
static bool API_WriteRowFileBrowser (unsigned Level,Brw_FileType_t FileType,const char *FileName);
static void API_IndentXMLLine (unsigned Level);
static void API_GetDataOfLocation (struct soap *soap,
struct swad__location *location,
time_t *CheckInTime,
MYSQL_RES **mysql_res,
unsigned NumLocs);
static void API_ResetLocation (struct soap *soap,
struct swad__location *location);
/*****************************************************************************/
/******* Function called when a web service if required by a plugin **********/
/*****************************************************************************/
static struct soap *API_soap = NULL; // gSOAP runtime environment
static void API_Set_gSOAP_RuntimeEnv (struct soap *soap)
{
API_soap = soap;
}
struct soap *API_Get_gSOAP_RuntimeEnv (void)
{
return API_soap;
}
/*****************************************************************************/
/******* Function called when a web service if required by a plugin **********/
/*****************************************************************************/
void API_WebService (void)
{
struct soap *soap;
if ((soap = soap_new ())) // Allocate and initialize runtime context
{
soap_serve (soap);
API_FreeSoapContext (soap);
}
}
/*****************************************************************************/
/******* Function called to exit on error when executing web service *********/
/*****************************************************************************/
void API_Exit (const char *DetailErrorMessage)
{
struct soap *soap = API_Get_gSOAP_RuntimeEnv ();
int ReturnCode = 0;
if (soap)
{
ReturnCode = (DetailErrorMessage ? soap_receiver_fault (soap,
"Error in swad web service",
DetailErrorMessage) :
0);
API_FreeSoapContext (soap);
}
exit (ReturnCode);
}
/*****************************************************************************/
/****************************** Free SOAP context ****************************/
/*****************************************************************************/
static void API_FreeSoapContext (struct soap *soap)
{
soap_destroy (soap); // delete managed C++ objects
soap_end (soap); // delete managed memory
soap_free (soap); // free the context
API_Set_gSOAP_RuntimeEnv (NULL); // set pointer to NULL in order to not try to free the context again
}
/*****************************************************************************/
/****** Check if the application key of the requester of a web service *******/
/****** is one of the application keys allowed in the plugins *******/
/*****************************************************************************/
static int API_GetPlgCodFromAppKey (struct soap *soap,
const char *appKey)
{
/***** Get plugin code from application key *****/
if ((Gbl.WebService.PlgCod = Plg_DB_GetPlgCodFromAppKey (appKey)) <= 0)
return soap_sender_fault (soap,
"Unknown application key",
"Unknown application");
return SOAP_OK;
}
/*****************************************************************************/
/****** Get the name of a web service function given the function code *******/
/*****************************************************************************/
const char *API_GetFunctionNameFromFunCod (long FunCod)
{
if (FunCod < 0 || FunCod > API_NUM_FUNCTIONS)
return API_Functions[0];
return API_Functions[FunCod];
}
/*****************************************************************************/
/****** Check if a session identifier is valid and exists in database ********/
/*****************************************************************************/
static int API_CheckIdSession (struct soap *soap,
const char *IdSes)
{
const char *Ptr;
unsigned i;
/***** Check if pointer is NULL *****/
if (IdSes == NULL)
return soap_sender_fault (soap,
"Bad session identifier",
"Session identifier is a null pointer");
/***** Check length of session identifier *****/
if (strlen (IdSes) != Cns_BYTES_SESSION_ID)
return soap_sender_fault (soap,
"Bad session identifier",
"The length of the session identifier is wrong");
/***** Check if session identifier is in base64url *****/
for (Ptr = IdSes;
*Ptr;
Ptr++)
{
for (i = 0;
i < 64;
i++) // Check if this character is one of the allowed characters
if (*Ptr == Str_BIN_TO_BASE64URL[i])
break;
if (i == 64) // Character not found
return soap_sender_fault (soap,
"Bad session identifier",
"The session identifier must contain only base64url characters");
}
/***** Query if session identifier already exists in database *****/
if (!Ses_DB_CheckIfSessionExists (IdSes))
return soap_receiver_fault (soap,
"Bad session identifier",
"Session identifier does not exist in database");
return SOAP_OK;
}
/*****************************************************************************/
/************** Check if a web service key exists in database ****************/
/*****************************************************************************/
static int API_CheckAPIKey (char APIKey[API_BYTES_KEY + 1])
{
MYSQL_RES *mysql_res;
MYSQL_ROW row;
/***** Set default user's code *****/
Gbl.Usrs.Me.UsrDat.UsrCod = -1L;
Gbl.Usrs.Me.Logged = false;
Gbl.WebService.PlgCod = -1L;
/***** Check that key does not exist in database *****/
if (API_DB_GetDataFromAPIKey (&mysql_res,APIKey))
{
row = mysql_fetch_row (mysql_res);
Gbl.Usrs.Me.UsrDat.UsrCod = Str_ConvertStrCodToLongCod (row[0]);
Gbl.Usrs.Me.Logged = true;
Gbl.WebService.PlgCod = Str_ConvertStrCodToLongCod (row[1]);
}
/***** Free structure that stores the query result *****/
DB_FreeMySQLResult (&mysql_res);
return SOAP_OK;
}
/*****************************************************************************/
/** Check if a course code and a group code are valid and exist in database **/
/*****************************************************************************/
static int API_CheckCourseAndGroupCodes (struct soap *soap,
long CrsCod,long GrpCod)
{
/***** Check if course code is correct *****/
if (CrsCod <= 0)
return soap_sender_fault (soap,
"Bad course code",
"Course code must be a integer greater than 0");
/***** Query if course code already exists in database *****/
if (!Crs_DB_CheckIfCrsCodExists (CrsCod))
return soap_sender_fault (soap,
"Bad course code",
"Course code does not exist in database");
/***** Course code exists in database, so check if group code exists in database and belongs to course *****/
if (GrpCod > 0) // <= 0 means "the whole course"
if (!Grp_DB_CheckIfGrpBelongsToCrs (GrpCod,CrsCod))
return soap_sender_fault (soap,
"Bad group code",
"Group code does not exist in database or it's not a group of the specified course");
return SOAP_OK;
}
/*****************************************************************************/
/***** Generate a key used in subsequents calls to other web services ********/
/*****************************************************************************/
static int API_GenerateNewAPIKey (struct soap *soap,
long UsrCod,
char APIKey[API_BYTES_KEY + 1])
{
/***** Remove expired web service keys *****/
API_DB_RemoveOldAPIKeys ();
/***** Create a unique name for the key *****/
Str_Copy (APIKey,Gbl.UniqueNameEncrypted,API_BYTES_KEY);
/***** Check that key does not exist in database *****/
if (API_DB_CheckIfAPIKeyExists (APIKey))
return soap_receiver_fault (soap,
"Error when generating key",
"Generated key already existed in database");
/***** Insert key into database *****/
API_DB_CreateAPIKey (APIKey,UsrCod,Gbl.WebService.PlgCod);
return SOAP_OK;
}
/*****************************************************************************/
/************ Get user's data from database giving a user's code *************/
/*****************************************************************************/
// Return false if UsrDat->UsrCod does not exist ini database
static bool API_GetSomeUsrDataFromUsrCod (struct UsrData *UsrDat,long CrsCod)
{
MYSQL_RES *mysql_res;
MYSQL_ROW row;
bool UsrFound;
/***** Check if user's code is valid *****/
if (UsrDat->UsrCod <= 0)
return false;
/***** Get some user's data *****/
if ((UsrFound = Usr_DB_GetSomeUsrDataFromUsrCod (&mysql_res,UsrDat->UsrCod)))
{
/***** Read some user's data *****/
row = mysql_fetch_row (mysql_res);
/* Get user's name (row[0], row[1], row[2]) and photo (row[3]) */
Str_Copy (UsrDat->Surname1,row[0],sizeof (UsrDat->Surname1) - 1);
Str_Copy (UsrDat->Surname2,row[1],sizeof (UsrDat->Surname2) - 1);
Str_Copy (UsrDat->FrstName,row[2],sizeof (UsrDat->FrstName) - 1);
Str_Copy (UsrDat->Photo ,row[3],sizeof (UsrDat->Photo ) - 1);
/* Get user's brithday (row[4]) */
Dat_GetDateFromYYYYMMDD (&(UsrDat->Birthday),row[4]);
/***** Get list of user's IDs *****/
ID_GetListIDsFromUsrCod (UsrDat);
/***** Get user's nickname *****/
Nck_DB_GetNicknameFromUsrCod (UsrDat->UsrCod,UsrDat->Nickname);
/***** Get user's role *****/
if (CrsCod > 0)
/* Get the role in the given course */
UsrDat->Roles.InCurrentCrs = Rol_DB_GetRoleUsrInCrs (UsrDat->UsrCod,CrsCod);
else
/* Get the maximum role in any course */
UsrDat->Roles.InCurrentCrs = Rol_DB_GetMaxRoleUsrInCrss (UsrDat->UsrCod);
}
/***** Free structure that stores the query result *****/
DB_FreeMySQLResult (&mysql_res);
return UsrFound;
}
/*****************************************************************************/
/**************************** Get info of my marks ***************************/
/*****************************************************************************/
#define API_CHECK_NEW_ACCOUNT_OK 0
#define API_CHECK_NEW_ACCOUNT_NICKNAME_NOT_VALID -1
#define API_CHECK_NEW_ACCOUNT_NICKNAME_REGISTERED_BY_ANOTHER_USER -2
#define API_CHECK_NEW_ACCOUNT_EMAIL_NOT_VALID -3
#define API_CHECK_NEW_ACCOUNT_EMAIL_REGISTERED_BY_ANOTHER_USER -4
#define API_CHECK_NEW_ACCOUNT_PASSWORD_NOT_VALID -5
int swad__createAccount (struct soap *soap,
char *userNickname,char *userEmail,char *userPassword,char *appKey, // input
struct swad__createAccountOutput *createAccountOut) // output
{
char NewNickWithoutArr[Nck_MAX_BYTES_NICK_WITHOUT_ARROBA + 1];
char NewEncryptedPassword[Pwd_BYTES_ENCRYPTED_PASSWORD + 1];
int Result;
int ReturnCode;
/***** Initializations *****/
API_Set_gSOAP_RuntimeEnv (soap);
Gbl.WebService.Function = API_createAccount;
/***** Allocate space for strings *****/
createAccountOut->wsKey = soap_malloc (soap,API_BYTES_KEY + 1);
/***** Default values returned on error *****/
createAccountOut->userCode = 0; // Undefined error
createAccountOut->wsKey[0] = '\0';
/***** Get plugin code *****/
if ((ReturnCode = API_GetPlgCodFromAppKey (soap,appKey)) != SOAP_OK)
return ReturnCode;
/***** Check parameters used to create the new account *****/
Result = API_CheckParamsNewAccount (userNickname, // Input
NewNickWithoutArr, // Output
userEmail, // Input-output
userPassword, // Input
NewEncryptedPassword); // Output
if (Result < 0)
{
createAccountOut->userCode = Result;
return SOAP_OK;
}
/***** User's has no ID *****/
Gbl.Usrs.Me.UsrDat.IDs.Num = 0;
Gbl.Usrs.Me.UsrDat.IDs.List = NULL;
/***** Set password to the password typed by the user *****/
Str_Copy (Gbl.Usrs.Me.UsrDat.Password,NewEncryptedPassword,
sizeof (Gbl.Usrs.Me.UsrDat.Password) - 1);
/***** User does not exist in the platform, so create him/her! *****/
Acc_CreateNewUsr (&Gbl.Usrs.Me.UsrDat,
true); // I am creating my own account
/***** Save nickname *****/
Nck_DB_UpdateNick (Gbl.Usrs.Me.UsrDat.UsrCod,NewNickWithoutArr);
Str_Copy (Gbl.Usrs.Me.UsrDat.Nickname,NewNickWithoutArr,
sizeof (Gbl.Usrs.Me.UsrDat.Nickname) - 1);
/***** Save email *****/
if (Mai_UpdateEmailInDB (&Gbl.Usrs.Me.UsrDat,userEmail))
{
/* Email updated sucessfully */
Str_Copy (Gbl.Usrs.Me.UsrDat.Email,userEmail,
sizeof (Gbl.Usrs.Me.UsrDat.Email) - 1);
Gbl.Usrs.Me.UsrDat.EmailConfirmed = false;
}
/***** Copy new user's code *****/
createAccountOut->userCode = Gbl.Usrs.Me.UsrDat.UsrCod;
/***** Generate a key used in subsequents calls to other web services *****/
return API_GenerateNewAPIKey (soap,
(long) createAccountOut->userCode,
createAccountOut->wsKey);
}
/*****************************************************************************/
/************* Get parameters for the creation of a new account **************/
/*****************************************************************************/
// Return false on error
//char *userNickname,char *userEmail,char *userID,char *userPassword
static int API_CheckParamsNewAccount (char *NewNickWithArr, // Input
char NewNickWithoutArr[Nck_MAX_BYTES_NICK_WITHOUT_ARROBA + 1], // Output
char *NewEmail, // Input-output
char *NewPlainPassword, // Input
char NewEncryptedPassword[Pwd_BYTES_ENCRYPTED_PASSWORD + 1]) // Output
{
char CopyOfNewNick[Nck_MAX_BYTES_NICK_WITH_ARROBA + 1];
/***** Step 1/3: Check new nickname *****/
/* Make a copy without possible starting arrobas */
if (Nck_CheckIfNickWithArrIsValid (NewNickWithArr)) // If new nickname is valid
{
/***** Remove leading arrobas *****/
Str_Copy (CopyOfNewNick,NewNickWithArr,sizeof (CopyOfNewNick) - 1);
Str_RemoveLeadingArrobas (CopyOfNewNick);
/***** Check if the new nickname matches any of the nicknames of other users *****/
if (Nck_DB_CheckIfNickMatchesAnyNick (CopyOfNewNick)) // Already without leading arrobas
return API_CHECK_NEW_ACCOUNT_NICKNAME_REGISTERED_BY_ANOTHER_USER;
/***** Output value of nickname without leading arrobas *****/
Str_Copy (NewNickWithoutArr,CopyOfNewNick,Nck_MAX_BYTES_NICK_WITHOUT_ARROBA);
}
else // New nickname is not valid
return API_CHECK_NEW_ACCOUNT_NICKNAME_NOT_VALID;
/***** Step 2/3: Check new email *****/
if (Mai_CheckIfEmailIsValid (NewEmail)) // New email is valid
{
/***** Check if the new email matches any of the confirmed emails of other users *****/
if (Mai_DB_CheckIfEmailExistsConfirmed (NewEmail)) // An email of another user is the same that my email
return API_CHECK_NEW_ACCOUNT_EMAIL_REGISTERED_BY_ANOTHER_USER;
}
else // New email is not valid
return API_CHECK_NEW_ACCOUNT_EMAIL_NOT_VALID;
/***** Step 3/3: Check new password *****/
Cry_EncryptSHA512Base64 (NewPlainPassword,NewEncryptedPassword);
if (!Pwd_SlowCheckIfPasswordIsGood (NewPlainPassword,NewEncryptedPassword,-1L)) // New password is good?
return API_CHECK_NEW_ACCOUNT_PASSWORD_NOT_VALID;
return API_CHECK_NEW_ACCOUNT_OK;
}
/*****************************************************************************/
/****************** Login user by user, password and key *********************/
/*****************************************************************************/
int swad__loginByUserPasswordKey (struct soap *soap,
char *userID,char *userPassword,char *appKey, // input
struct swad__loginByUserPasswordKeyOutput *loginByUserPasswordKeyOut) // output
{
char UsrIDNickOrEmail[Cns_MAX_BYTES_USR_LOGIN + 1];
int ReturnCode;
char PhotoURL[Cns_MAX_BYTES_WWW + 1];
bool UsrFound;
/***** Initializations *****/
API_Set_gSOAP_RuntimeEnv (soap);
Gbl.WebService.Function = API_loginByUserPasswordKey;
/***** Allocate space for strings *****/
loginByUserPasswordKeyOut->wsKey = soap_malloc (soap,API_BYTES_KEY + 1);
loginByUserPasswordKeyOut->userNickname = soap_malloc (soap,Nck_MAX_BYTES_NICK_WITHOUT_ARROBA + 1);
loginByUserPasswordKeyOut->userID = soap_malloc (soap,ID_MAX_BYTES_USR_ID + 1);
loginByUserPasswordKeyOut->userFirstname = soap_malloc (soap,Usr_MAX_BYTES_FIRSTNAME_OR_SURNAME + 1);
loginByUserPasswordKeyOut->userSurname1 = soap_malloc (soap,Usr_MAX_BYTES_FIRSTNAME_OR_SURNAME + 1);
loginByUserPasswordKeyOut->userSurname2 = soap_malloc (soap,Usr_MAX_BYTES_FIRSTNAME_OR_SURNAME + 1);
loginByUserPasswordKeyOut->userPhoto = soap_malloc (soap,Cns_MAX_BYTES_WWW + 1);
loginByUserPasswordKeyOut->userBirthday = soap_malloc (soap,Dat_LENGTH_YYYYMMDD + 1);
/***** Default values returned on error *****/
loginByUserPasswordKeyOut->userCode = -1;
loginByUserPasswordKeyOut->wsKey[0] = '\0';
loginByUserPasswordKeyOut->userNickname[0] = '\0';
loginByUserPasswordKeyOut->userID[0] = '\0';
loginByUserPasswordKeyOut->userFirstname[0] = '\0';
loginByUserPasswordKeyOut->userSurname1[0] = '\0';
loginByUserPasswordKeyOut->userSurname2[0] = '\0';
loginByUserPasswordKeyOut->userPhoto[0] = '\0';
loginByUserPasswordKeyOut->userBirthday[0] = '\0';
loginByUserPasswordKeyOut->userRole = 0; // unknown
/***** Get plugin code *****/
if ((ReturnCode = API_GetPlgCodFromAppKey (soap,appKey)) != SOAP_OK)
return ReturnCode;
/***** Check if user's email, @nickname or ID are valid *****/
Str_Copy (UsrIDNickOrEmail,userID,sizeof (UsrIDNickOrEmail) - 1);
if (Nck_CheckIfNickWithArrIsValid (UsrIDNickOrEmail)) // 1: It's a nickname
{
Str_RemoveLeadingArrobas (UsrIDNickOrEmail);
/* User has typed a nickname */
Gbl.Usrs.Me.UsrDat.UsrCod = Usr_DB_GetUsrCodFromNickPwd (UsrIDNickOrEmail,
userPassword);
}
else if (Mai_CheckIfEmailIsValid (UsrIDNickOrEmail)) // 2: It's an email
/* User has typed an email */
// TODO: Get only if email confirmed?
Gbl.Usrs.Me.UsrDat.UsrCod = Usr_DB_GetUsrCodFromEmailPwd (UsrIDNickOrEmail,
userPassword);
else // 3: It's not a nickname nor email
{
// Users' IDs are always stored internally in capitals and without leading zeros
Str_RemoveLeadingZeros (UsrIDNickOrEmail);
Str_ConvertToUpperText (UsrIDNickOrEmail);
if (ID_CheckIfUsrIDIsValid (UsrIDNickOrEmail))
/* User has typed a valid user's ID (existing or not) */
Gbl.Usrs.Me.UsrDat.UsrCod = Usr_DB_GetUsrCodFromIDPwd (UsrIDNickOrEmail,
userPassword);
else // String is not a valid user's nickname, email or ID
return soap_receiver_fault (soap,
"Bad log in",
"User's ID or nickname don't exist or password is wrong");
}
/***** Get user's data from database *****/
if (Gbl.Usrs.Me.UsrDat.UsrCod > 0) // User found in table of users' data
/***** Get user's data *****/
UsrFound = API_GetSomeUsrDataFromUsrCod (&Gbl.Usrs.Me.UsrDat,-1L); // Get some user's data from database
else
UsrFound = false;
if (UsrFound)
{
Gbl.Usrs.Me.Logged = true;
Gbl.Usrs.Me.Role.Logged = Gbl.Usrs.Me.UsrDat.Roles.InCurrentCrs;
loginByUserPasswordKeyOut->userCode = (int) Gbl.Usrs.Me.UsrDat.UsrCod;
Str_Copy (loginByUserPasswordKeyOut->userNickname,
Gbl.Usrs.Me.UsrDat.Nickname,Nck_MAX_BYTES_NICK_WITHOUT_ARROBA);
if (Gbl.Usrs.Me.UsrDat.IDs.Num)
Str_Copy (loginByUserPasswordKeyOut->userID,
Gbl.Usrs.Me.UsrDat.IDs.List[0].ID, // TODO: What user's ID?
ID_MAX_BYTES_USR_ID);
Str_Copy (loginByUserPasswordKeyOut->userSurname1,
Gbl.Usrs.Me.UsrDat.Surname1,Usr_MAX_BYTES_FIRSTNAME_OR_SURNAME);
Str_Copy (loginByUserPasswordKeyOut->userSurname2,
Gbl.Usrs.Me.UsrDat.Surname2,Usr_MAX_BYTES_FIRSTNAME_OR_SURNAME);
Str_Copy (loginByUserPasswordKeyOut->userFirstname,
Gbl.Usrs.Me.UsrDat.FrstName,Usr_MAX_BYTES_FIRSTNAME_OR_SURNAME);
Pho_BuildLinkToPhoto (&Gbl.Usrs.Me.UsrDat,PhotoURL);
Str_Copy (loginByUserPasswordKeyOut->userPhoto,PhotoURL,Cns_MAX_BYTES_WWW);
Str_Copy (loginByUserPasswordKeyOut->userBirthday,
Gbl.Usrs.Me.UsrDat.Birthday.YYYYMMDD,Dat_LENGTH_YYYYMMDD);
loginByUserPasswordKeyOut->userRole =
API_RolRole_to_SvcRole[Gbl.Usrs.Me.UsrDat.Roles.InCurrentCrs];
/***** Generate a key used in subsequents calls to other web services *****/
return API_GenerateNewAPIKey (soap,
(long) loginByUserPasswordKeyOut->userCode,
loginByUserPasswordKeyOut->wsKey);
}
else
{
loginByUserPasswordKeyOut->userCode = -1;
loginByUserPasswordKeyOut->userID = NULL;
loginByUserPasswordKeyOut->userSurname1 = NULL;
loginByUserPasswordKeyOut->userSurname2 = NULL;
loginByUserPasswordKeyOut->userFirstname = NULL;
loginByUserPasswordKeyOut->userPhoto = NULL;
loginByUserPasswordKeyOut->userRole = 0;
return soap_receiver_fault (soap,
"Bad log in",
"User's ID or nickname don't exist or password is wrong");
}
}
/*****************************************************************************/
/************************** Login user by session ****************************/
/*****************************************************************************/
int swad__loginBySessionKey (struct soap *soap,
char *sessionID,char *appKey, // input
struct swad__loginBySessionKeyOutput *loginBySessionKeyOut) // output
{
int ReturnCode;
MYSQL_RES *mysql_res;
MYSQL_ROW row;
char PhotoURL[Cns_MAX_BYTES_WWW + 1];
bool UsrFound;
/***** Initializations *****/
API_Set_gSOAP_RuntimeEnv (soap);
Gbl.WebService.Function = API_loginBySessionKey;
/***** Allocate space for strings *****/
loginBySessionKeyOut->wsKey = soap_malloc (soap,API_BYTES_KEY + 1);
loginBySessionKeyOut->userNickname = soap_malloc (soap,Nck_MAX_BYTES_NICK_WITHOUT_ARROBA + 1);
loginBySessionKeyOut->userID = soap_malloc (soap,ID_MAX_BYTES_USR_ID + 1);
loginBySessionKeyOut->userFirstname = soap_malloc (soap,Usr_MAX_BYTES_FIRSTNAME_OR_SURNAME + 1);
loginBySessionKeyOut->userSurname1 = soap_malloc (soap,Usr_MAX_BYTES_FIRSTNAME_OR_SURNAME + 1);
loginBySessionKeyOut->userSurname2 = soap_malloc (soap,Usr_MAX_BYTES_FIRSTNAME_OR_SURNAME + 1);
loginBySessionKeyOut->userPhoto = soap_malloc (soap,Cns_MAX_BYTES_WWW + 1);
loginBySessionKeyOut->userBirthday = soap_malloc (soap,Dat_LENGTH_YYYYMMDD + 1);
loginBySessionKeyOut->degreeName = soap_malloc (soap,Cns_HIERARCHY_MAX_BYTES_FULL_NAME + 1);
loginBySessionKeyOut->courseName = soap_malloc (soap,Cns_HIERARCHY_MAX_BYTES_FULL_NAME + 1);
/***** Default values returned on error *****/
loginBySessionKeyOut->userCode = -1;
loginBySessionKeyOut->degreeCode = -1;
loginBySessionKeyOut->courseCode = -1;
loginBySessionKeyOut->wsKey[0] = '\0';
loginBySessionKeyOut->userNickname[0] = '\0';
loginBySessionKeyOut->userID[0] = '\0';
loginBySessionKeyOut->userFirstname[0] = '\0';
loginBySessionKeyOut->userSurname1[0] = '\0';
loginBySessionKeyOut->userSurname2[0] = '\0';
loginBySessionKeyOut->userPhoto[0] = '\0';
loginBySessionKeyOut->userBirthday[0] = '\0';
loginBySessionKeyOut->userRole = Rol_UNK;
loginBySessionKeyOut->degreeName[0] = '\0';
loginBySessionKeyOut->courseName[0] = '\0';
/***** Get plugin code *****/
if ((ReturnCode = API_GetPlgCodFromAppKey (soap,appKey)) != SOAP_OK)
return ReturnCode;
/***** Check length of session identifier *****/
if (sessionID == NULL)
return soap_sender_fault (soap,
"SessionID is null",
"Login by session");
/***** Check session identifier coming from an external plugin *****/
if ((ReturnCode = API_CheckIdSession (soap,sessionID)) != SOAP_OK)
return ReturnCode;
// Now, we know that sessionID is a valid session identifier
/***** Query data of the session from database *****/
if (Ses_DB_GetSomeSessionData (&mysql_res,sessionID)) // Session found in table of sessions
{
row = mysql_fetch_row (mysql_res);
/***** Get course (row[2]) *****/
Gbl.Hierarchy.Crs.CrsCod = Str_ConvertStrCodToLongCod (row[2]);
Crs_GetDataOfCourseByCod (&Gbl.Hierarchy.Crs);
loginBySessionKeyOut->courseCode = (int) Gbl.Hierarchy.Crs.CrsCod;
Str_Copy (loginBySessionKeyOut->courseName,Gbl.Hierarchy.Crs.FullName,
Cns_HIERARCHY_MAX_BYTES_FULL_NAME);
/***** Get user code (row[0]) *****/
Gbl.Usrs.Me.UsrDat.UsrCod = Str_ConvertStrCodToLongCod (row[0]);
UsrFound = API_GetSomeUsrDataFromUsrCod (&Gbl.Usrs.Me.UsrDat,Gbl.Hierarchy.Crs.CrsCod); // Get some user's data from database
/***** Get degree (row[1]) *****/
Gbl.Hierarchy.Deg.DegCod = Str_ConvertStrCodToLongCod (row[1]);
Deg_GetDataOfDegreeByCod (&Gbl.Hierarchy.Deg);
loginBySessionKeyOut->degreeCode = (int) Gbl.Hierarchy.Deg.DegCod;
Str_Copy (loginBySessionKeyOut->degreeName,Gbl.Hierarchy.Deg.FullName,
Cns_HIERARCHY_MAX_BYTES_FULL_NAME);
}
else
UsrFound = false;
/***** Free structure that stores the query result *****/
DB_FreeMySQLResult (&mysql_res);
/***** Get degree of current course *****/
Gbl.Hierarchy.Deg.DegCod = Crs_DB_GetCurrentDegCodFromCurrentCrsCod ();
if (UsrFound)
{
Gbl.Usrs.Me.Logged = true;
Gbl.Usrs.Me.Role.Logged = Gbl.Usrs.Me.UsrDat.Roles.InCurrentCrs;
loginBySessionKeyOut->userCode = (int) Gbl.Usrs.Me.UsrDat.UsrCod;
Str_Copy (loginBySessionKeyOut->userNickname,Gbl.Usrs.Me.UsrDat.Nickname,
Nck_MAX_BYTES_NICK_WITHOUT_ARROBA);
if (Gbl.Usrs.Me.UsrDat.IDs.Num)
Str_Copy (loginBySessionKeyOut->userID,
Gbl.Usrs.Me.UsrDat.IDs.List[0].ID, // TODO: What user's ID?
ID_MAX_BYTES_USR_ID);
Str_Copy (loginBySessionKeyOut->userSurname1,
Gbl.Usrs.Me.UsrDat.Surname1,Usr_MAX_BYTES_FIRSTNAME_OR_SURNAME);
Str_Copy (loginBySessionKeyOut->userSurname2,
Gbl.Usrs.Me.UsrDat.Surname2,Usr_MAX_BYTES_FIRSTNAME_OR_SURNAME);
Str_Copy (loginBySessionKeyOut->userFirstname,
Gbl.Usrs.Me.UsrDat.FrstName,Usr_MAX_BYTES_FIRSTNAME_OR_SURNAME);
Pho_BuildLinkToPhoto (&Gbl.Usrs.Me.UsrDat,PhotoURL);
Str_Copy (loginBySessionKeyOut->userPhoto,PhotoURL,Cns_MAX_BYTES_WWW);
Str_Copy (loginBySessionKeyOut->userBirthday,
Gbl.Usrs.Me.UsrDat.Birthday.YYYYMMDD,Dat_LENGTH_YYYYMMDD);
loginBySessionKeyOut->userRole = API_RolRole_to_SvcRole[Gbl.Usrs.Me.UsrDat.Roles.InCurrentCrs];
/***** Generate a key used in subsequents calls to other web services *****/
return API_GenerateNewAPIKey (soap,
(long) loginBySessionKeyOut->userCode,
loginBySessionKeyOut->wsKey);
}
else
return soap_receiver_fault (soap,
"Bad session identifier",
"Session identifier does not exist in database");
}
/*****************************************************************************/
/***************** Get available roles in the current course *****************/
/*****************************************************************************/
/*
With this function, SWADroid is able to check if user can see the button to show the MAC address of the nearest WiFi access point
*/
int swad__getAvailableRoles (struct soap *soap,
char *wsKey,int courseCode, // input
struct swad__getAvailableRolesOutput *getAvailableRolesOut) // output
{
int ReturnCode;
/***** Initializations *****/
API_Set_gSOAP_RuntimeEnv (soap);
Gbl.WebService.Function = API_getAvailableRoles;
/***** Initialize hierarchy *****/
Gbl.Hierarchy.Crs.CrsCod = (long) courseCode;
Hie_InitHierarchy ();
/***** Default value returned on error *****/
getAvailableRolesOut->roles = 0; // error
/***** Check API (web service) key *****/
if ((ReturnCode = API_CheckAPIKey (wsKey)) != SOAP_OK)
return ReturnCode;
if (Gbl.Usrs.Me.UsrDat.UsrCod < 0) // Web service key does not exist in database
return soap_receiver_fault (soap,
"Bad web service key",
"Web service key does not exist in database");
/***** Get some of my data *****/
if (!API_GetSomeUsrDataFromUsrCod (&Gbl.Usrs.Me.UsrDat,-1L))
return soap_receiver_fault (soap,
"Can not get user's data from database",
"User does not exist in database");
Gbl.Usrs.Me.Logged = true;
Gbl.Usrs.Me.Role.Logged = Gbl.Usrs.Me.UsrDat.Roles.InCurrentCrs;
/***** Return available roles *****/
Rol_SetMyRoles ();
getAvailableRolesOut->roles = Gbl.Usrs.Me.Role.Available;
return SOAP_OK;
}
/*****************************************************************************/
/*********************** Send a new password by email ************************/
/*****************************************************************************/
int swad__getNewPassword (struct soap *soap,
char *userID,char *appKey, // input
struct swad__getNewPasswordOutput *getNewPasswordOut) // output
{
int ReturnCode;
char UsrIDNickOrEmail[Cns_MAX_BYTES_USR_LOGIN + 1];
char NewRandomPlainPassword[Pwd_MAX_BYTES_PLAIN_PASSWORD + 1];
/***** Initializations *****/
API_Set_gSOAP_RuntimeEnv (soap);
Gbl.WebService.Function = API_getNewPassword;
/***** Default value returned on error *****/
getNewPasswordOut->success = 0; // error
/***** Get plugin code *****/
if ((ReturnCode = API_GetPlgCodFromAppKey (soap,appKey)) != SOAP_OK)
return ReturnCode;
/***** Check if user's email, @nickname or ID are valid *****/
Str_Copy (UsrIDNickOrEmail,userID,sizeof (UsrIDNickOrEmail) - 1);
if (Nck_CheckIfNickWithArrIsValid (UsrIDNickOrEmail)) // 1: It's a nickname
{
Str_RemoveLeadingArrobas (UsrIDNickOrEmail);
/* User has typed a nickname */
Gbl.Usrs.Me.UsrDat.UsrCod = Usr_DB_GetUsrCodFromNick (UsrIDNickOrEmail);
}
else if (Mai_CheckIfEmailIsValid (Gbl.Usrs.Me.UsrIdLogin)) // 2: It's an email
/* User has typed an email */
Gbl.Usrs.Me.UsrDat.UsrCod = Usr_DB_GetUsrCodFromEmail (UsrIDNickOrEmail);
else // 3: It's not a nickname nor email
{
// Users' IDs are always stored internally in capitals and without leading zeros
Str_RemoveLeadingZeros (UsrIDNickOrEmail);
Str_ConvertToUpperText (UsrIDNickOrEmail);
if (ID_CheckIfUsrIDIsValid (UsrIDNickOrEmail))
/* User has typed a valid user's ID (existing or not) */
Gbl.Usrs.Me.UsrDat.UsrCod = Usr_DB_GetUsrCodFromID (UsrIDNickOrEmail);
else // String is not a valid user's nickname, email or ID
return soap_receiver_fault (soap,
"Bad log in",
"User's email, nickname or ID don't exist");
}
/***** Get user's data from database *****/
if (Gbl.Usrs.Me.UsrDat.UsrCod > 0) // One unique user found in table of users' data
{
Usr_GetUsrDataFromUsrCod (&Gbl.Usrs.Me.UsrDat, // Get my data
Usr_DONT_GET_PREFS,
Usr_DONT_GET_ROLE_IN_CURRENT_CRS);
if (Gbl.Usrs.Me.UsrDat.Email[0])
if (Pwd_SendNewPasswordByEmail (NewRandomPlainPassword) == 0) // Message sent successfully
{
Pwd_SetMyPendingPassword (NewRandomPlainPassword);
getNewPasswordOut->success = 1;
}
}
return SOAP_OK;
}
/*****************************************************************************/
/************************ Return courses of a user ***************************/
/*****************************************************************************/
int swad__getCourses (struct soap *soap,
char *wsKey, // input
struct swad__getCoursesOutput *getCoursesOut) // output
{
int ReturnCode;
MYSQL_RES *mysql_res;
MYSQL_ROW row;
unsigned NumCrs;
unsigned NumCrss;
Rol_Role_t Role;
/***** Initializations *****/
API_Set_gSOAP_RuntimeEnv (soap);
Gbl.WebService.Function = API_getCourses;
/***** Check web service key *****/
if ((ReturnCode = API_CheckAPIKey (wsKey)) != SOAP_OK)
return ReturnCode;
if (Gbl.Usrs.Me.UsrDat.UsrCod < 0) // Web service key does not exist in database
return soap_receiver_fault (soap,
"Bad web service key",
"Web service key does not exist in database");
/***** Get some of my data *****/
if (!API_GetSomeUsrDataFromUsrCod (&Gbl.Usrs.Me.UsrDat,-1L))
return soap_receiver_fault (soap,
"Can not get user's data from database",
"User does not exist in database");
Gbl.Usrs.Me.Logged = true;
Gbl.Usrs.Me.Role.Logged = Gbl.Usrs.Me.UsrDat.Roles.InCurrentCrs;
/***** Query my courses from database *****/
NumCrss = Enr_DB_GetMyCoursesNames (&mysql_res);
getCoursesOut->numCourses =
getCoursesOut->coursesArray.__size = (int) NumCrss;
if (NumCrss == 0)
getCoursesOut->coursesArray.__ptr = NULL;
else // Courses found
{
getCoursesOut->coursesArray.__ptr = soap_malloc (soap,
(getCoursesOut->coursesArray.__size) *
sizeof (*(getCoursesOut->coursesArray.__ptr)));
for (NumCrs = 0;
NumCrs < NumCrss;
NumCrs++)
{
/* Get next course */
row = mysql_fetch_row (mysql_res);
/* Get course code (row[0]) */
getCoursesOut->coursesArray.__ptr[NumCrs].courseCode = (int) Str_ConvertStrCodToLongCod (row[0]);
/* Get course short name (row[1])
and course full name (row[2]) */
getCoursesOut->coursesArray.__ptr[NumCrs].courseShortName =
soap_malloc (soap,Cns_HIERARCHY_MAX_BYTES_SHRT_NAME + 1);
getCoursesOut->coursesArray.__ptr[NumCrs].courseFullName =
soap_malloc (soap,Cns_HIERARCHY_MAX_BYTES_FULL_NAME + 1);
Str_Copy (getCoursesOut->coursesArray.__ptr[NumCrs].courseShortName,
row[1],Cns_HIERARCHY_MAX_BYTES_SHRT_NAME);
Str_Copy (getCoursesOut->coursesArray.__ptr[NumCrs].courseFullName,
row[2],Cns_HIERARCHY_MAX_BYTES_FULL_NAME);
/* Get role (row[3]) */
if (sscanf (row[3],"%u",&Role) != 1) // Role in this course
Role = Rol_UNK;
getCoursesOut->coursesArray.__ptr[NumCrs].userRole = API_RolRole_to_SvcRole[Role];
}
}
/***** Free structure that stores the query result *****/
DB_FreeMySQLResult (&mysql_res);
return SOAP_OK;
}
/*****************************************************************************/
/************************ Return course information **************************/
/*****************************************************************************/
// TODO: Not completely implemented
int swad__getCourseInfo (struct soap *soap,
char *wsKey,int courseCode,char *infoType, // input
struct swad__getCourseInfoOutput *getCourseInfo) // output
{
int ReturnCode;
struct Syl_Syllabus Syllabus;
Inf_Type_t InfoType;
size_t Length;
struct Inf_FromDB FromDB;
int Result = SOAP_OK;
const char *NamesInWSForInfoType[Inf_NUM_TYPES] =
{
[Inf_INTRODUCTION ] = "introduction",
[Inf_TEACHING_GUIDE] = "guide",
[Inf_LECTURES ] = "lectures",
[Inf_PRACTICALS ] = "practicals",
[Inf_BIBLIOGRAPHY ] = "bibliography",
[Inf_FAQ ] = "FAQ",
[Inf_LINKS ] = "links",
[Inf_ASSESSMENT ] = "assessment",
};
const char *NamesInWSForInfoSrc[Inf_NUM_SOURCES] =
{
[Inf_NONE ] = "none",
[Inf_EDITOR ] = "editor",
[Inf_PLAIN_TEXT] = "plainText",
[Inf_RICH_TEXT ] = "richText",
[Inf_PAGE ] = "page",
[Inf_URL ] = "URL",
};
/***** Initializations *****/
API_Set_gSOAP_RuntimeEnv (soap);
Gbl.WebService.Function = API_getCourseInfo;
/***** Initialize hierarchy *****/
Gbl.Hierarchy.Crs.CrsCod = (long) courseCode;
Hie_InitHierarchy ();
/***** Check web service key *****/
if ((ReturnCode = API_CheckAPIKey (wsKey)) != SOAP_OK)
return ReturnCode;
if (Gbl.Usrs.Me.UsrDat.UsrCod < 0) // Web service key does not exist in database
return soap_receiver_fault (soap,
"Bad web service key",
"Web service key does not exist in database");
/***** Check course and group codes *****/
if ((ReturnCode = API_CheckCourseAndGroupCodes (soap,
Gbl.Hierarchy.Crs.CrsCod,
-1L)) != SOAP_OK)
return ReturnCode;
/***** Get some of my data *****/
if (!API_GetSomeUsrDataFromUsrCod (&Gbl.Usrs.Me.UsrDat,Gbl.Hierarchy.Crs.CrsCod))
return soap_receiver_fault (soap,
"Can not get user's data from database",
"User does not exist in database");
Gbl.Usrs.Me.Logged = true;
Gbl.Usrs.Me.Role.Logged = Gbl.Usrs.Me.UsrDat.Roles.InCurrentCrs;
/***** Check if I am a student, non-editing teacher or teacher in the course *****/
if (Gbl.Usrs.Me.UsrDat.Roles.InCurrentCrs != Rol_STD &&
Gbl.Usrs.Me.UsrDat.Roles.InCurrentCrs != Rol_NET &&
Gbl.Usrs.Me.UsrDat.Roles.InCurrentCrs != Rol_TCH)
return soap_receiver_fault (soap,
"Request forbidden",
"Requester must belong to course");
/***** Reset syllabus context *****/
Syl_ResetSyllabus (&Syllabus);
/***** Get info source *****/
for (InfoType = (Inf_Type_t) 0;
InfoType <= (Inf_Type_t) (Inf_NUM_TYPES - 1);
InfoType++)
if (!strcmp (infoType,NamesInWSForInfoType[InfoType]))
break;
if (InfoType == Inf_NUM_TYPES) // Not found!
return soap_receiver_fault (soap,
"Bad info type",
"Unknown requested info type");
Gbl.Crs.Info.Type = InfoType;
Inf_GetAndCheckInfoSrcFromDB (&Syllabus,
Gbl.Hierarchy.Crs.CrsCod,
Gbl.Crs.Info.Type,
&FromDB);
Length = strlen (NamesInWSForInfoSrc[FromDB.Src]);
getCourseInfo->infoSrc = soap_malloc (soap,Length + 1);
Str_Copy (getCourseInfo->infoSrc,NamesInWSForInfoSrc[FromDB.Src],Length);
/***** Get info text *****/
getCourseInfo->infoTxt = NULL;
switch (FromDB.Src)
{
case Inf_NONE: // No info available
break;
case Inf_EDITOR: // Internal editor (only for syllabus)
switch (Gbl.Crs.Info.Type)
{
case Inf_LECTURES: // Syllabus (lectures)
case Inf_PRACTICALS: // Syllabys (practicals)
Result = API_WriteSyllabusIntoHTMLBuffer (soap,&Syllabus,&(getCourseInfo->infoTxt));
break;
default:
break;
}
break;
case Inf_PLAIN_TEXT: // Plain text
case Inf_RICH_TEXT: // Rich text (not yet available)
Result = API_WritePlainTextIntoHTMLBuffer (soap,&(getCourseInfo->infoTxt));
break;
case Inf_PAGE: // Web page hosted in SWAD server
Result = API_WritePageIntoHTMLBuffer (soap,&(getCourseInfo->infoTxt));
break;
case Inf_URL: // Link to a web page
getCourseInfo->infoTxt = soap_malloc (soap,Cns_MAX_BYTES_WWW + 1);
Inf_WriteURLIntoTxtBuffer (getCourseInfo->infoTxt);
break;
}
/***** Return empty text if pointer is null *****/
if (getCourseInfo->infoTxt == NULL)
{
getCourseInfo->infoTxt = soap_malloc (soap,1);
getCourseInfo->infoTxt[0] = '\0';
}
return Result;
}
/*****************************************************************************/
/************** Write the syllabus into a temporary HTML file ****************/
/*****************************************************************************/
static int API_WriteSyllabusIntoHTMLBuffer (struct soap *soap,
struct Syl_Syllabus *Syllabus,
char **HTMLBuffer)
{
extern struct LstItemsSyllabus Syl_LstItemsSyllabus;
char FileNameHTMLTmp[PATH_MAX + 1];
FILE *FileHTMLTmp;
size_t Length;
/***** Initialize buffer *****/
*HTMLBuffer = NULL;
/***** Load syllabus from XML file to list of items in memory *****/
Syl_LoadListItemsSyllabusIntoMemory (Syllabus,Gbl.Hierarchy.Crs.CrsCod);
if (Syl_LstItemsSyllabus.NumItems)
{
/***** Create a unique name for the file *****/
snprintf (FileNameHTMLTmp,sizeof (FileNameHTMLTmp),"%s/%s_syllabus.html",
Cfg_PATH_OUT_PRIVATE,Gbl.UniqueNameEncrypted);
/***** Create a new temporary file for writing and reading *****/
if ((FileHTMLTmp = fopen (FileNameHTMLTmp,"w+b")) == NULL)
{
Syl_FreeListItemsSyllabus ();
return soap_receiver_fault (soap,
"Syllabus can not be copied into buffer",
"Can not create temporary file");
}
/***** Write syllabus in HTML into a temporary file *****/
Syl_WriteSyllabusIntoHTMLTmpFile (FileHTMLTmp);
/***** Write syllabus from list of items in memory to text buffer *****/
/* Compute length of file */
Length = (size_t) ftell (FileHTMLTmp);
/* Allocate memory for buffer */
if ((*HTMLBuffer = malloc (Length + 1)) == NULL)
{
fclose (FileHTMLTmp);
unlink (FileNameHTMLTmp);
Syl_FreeListItemsSyllabus ();
return soap_receiver_fault (soap,
"Syllabus can not be copied into buffer",
"Not enough memory for buffer");
}
/* Copy file content into buffer */
fseek (FileHTMLTmp,0L,SEEK_SET);
if (fread (*HTMLBuffer,sizeof (char),Length,FileHTMLTmp) != Length)
{
fclose (FileHTMLTmp);
unlink (FileNameHTMLTmp);
Syl_FreeListItemsSyllabus ();
return soap_receiver_fault (soap,
"Syllabus can not be copied into buffer",
"Error reading file into buffer");
}
(*HTMLBuffer)[Length] = '\0';
/***** Close and remove temporary file *****/
fclose (FileHTMLTmp);
unlink (FileNameHTMLTmp);
}
/***** Free list of items *****/
Syl_FreeListItemsSyllabus ();
return SOAP_OK;
}
/*****************************************************************************/
/************* Check if exists and write page into HTML buffer ***************/
/*****************************************************************************/
static int API_WritePlainTextIntoHTMLBuffer (struct soap *soap,
char **HTMLBuffer)
{
extern const char *Txt_INFO_TITLE[Inf_NUM_TYPES];
char TxtHTML[Cns_MAX_BYTES_LONG_TEXT + 1];
char FileNameHTMLTmp[PATH_MAX + 1];
FILE *FileHTMLTmp;
size_t Length;
/***** Initialize buffer *****/
*HTMLBuffer = NULL;
/***** Get info text from database *****/
Inf_GetInfoTxtFromDB (Gbl.Hierarchy.Crs.CrsCod,Gbl.Crs.Info.Type,
TxtHTML,NULL);
if (TxtHTML[0])
{
/***** Create a unique name for the file *****/
snprintf (FileNameHTMLTmp,sizeof (FileNameHTMLTmp),"%s/%s_info.html",
Cfg_PATH_OUT_PRIVATE,Gbl.UniqueNameEncrypted);
/***** Create a new temporary file for writing and reading *****/
if ((FileHTMLTmp = fopen (FileNameHTMLTmp,"w+b")) == NULL)
return soap_receiver_fault (soap,
"Plain text can not be copied into buffer",
"Can not create temporary file");
/***** Write start of HTML code *****/
Lay_BeginHTMLFile (FileHTMLTmp,Txt_INFO_TITLE[Gbl.Crs.Info.Type]);
fprintf (FileHTMLTmp,"\n"
"\n",
The_GetSuffix ());
/***** Write plain text into text buffer *****/
/* Convert to respectful HTML and insert links */
Str_ChangeFormat (Str_FROM_HTML,Str_TO_RIGOROUS_HTML,
TxtHTML,Cns_MAX_BYTES_LONG_TEXT,false); // Convert from HTML to recpectful HTML
ALn_InsertLinks (TxtHTML,Cns_MAX_BYTES_LONG_TEXT,60); // Insert links
/* Write text */
fprintf (FileHTMLTmp,"%s",TxtHTML);
/***** Write end of page into file *****/
fprintf (FileHTMLTmp,"
\n"
"\n"
"